@aiquants/daily-report 0.46.0 → 0.46.1
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 +16 -0
- package/README.md +4 -1
- package/dist/client.js +5 -5
- package/dist/client.mjs +5 -5
- package/dist/server.js +8 -8
- package/dist/server.mjs +8 -8
- package/package.json +1 -1
package/dist/server.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
var Go=e=>{throw TypeError(e)};var Ko=(e,t,r)=>t.has(e)||Go("Cannot "+r);var tr=(e,t,r)=>(Ko(e,t,"read from private field"),r?r.call(e):t.get(e)),An=(e,t,r)=>t.has(e)?Go("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Tn=(e,t,r,n)=>(Ko(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,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Pt(r)}`),je=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),En=(e,t,r)=>Q(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 Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},ve=(e,t,r,n)=>t===void 0?n:ie(e,t,r),rr=(e,t)=>{if(t===void 0)throw je(e,"a function");if(typeof t!="function")throw Q(e,"a function",t);return t};var se=()=>Math.floor(performance.now());var wn=Object.freeze({defaultTtlMs:6e4,maxBuckets:4096,maxBytes:512*1024*1024}),Ke=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,dc=8,pc=32,mc=24,yc=16,hc=-(2**30),fc=2**30-1,Rc=e=>Number.isInteger(e)&&e>=hc&&e<=fc&&!Object.is(e,-0),Sc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=pc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=dc*a.length;for(let i of a)typeof i=="string"?r+=mc+2*i.length:typeof i=="number"&&!Rc(i)?r+=yc: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 Ke(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 Ke("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 Ke("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 Ke&&(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=ve("cacheDefaultTtlMs",t.defaultTtlMs,1,wn.defaultTtlMs),this.maxBuckets=ve("cacheMaxBuckets",t.maxBuckets,1,wn.maxBuckets),this.maxBytes=ve("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=Sc(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 jp}from"@aiquants/request-isolation";var gc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Jo=e=>e<10?`0${e}`:`${e}`,bc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Jo(e.getMonth()+1),n=Jo(e.getDate());return`${t}-${r}-${n}`},Vt=e=>{let t=gc.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 Ue=e=>e==null?null:e instanceof Date?bc(e):Vt(e);import{z as Dc}from"zod/v3";var at=e=>Number.isSafeInteger(e)&&e>0,Ne=Dc.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as te}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"),it=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),kt),ea=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Lt=(e,t)=>({code:"invalid_type",expected:e,received:ea(t)}),Ac=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tc=e=>{let t=0;for(let r in e)t+=1;return t},Qo=(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(!Ac(n))return it(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=Qo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?kt:a!==null?a:Tc(n)===l?n:Qo(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 it(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},pe=(e,t,r)=>e==null||typeof e=="string"?e:it(t,r,Lt("string",e)),Xo=(e,t,r)=>e===null||typeof e=="string"?e:it(t,r,Lt("string",e)),Zo=(e,t,r)=>typeof e=="string"?e:it(t,r,Lt("string",e)),Ec=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:it(t,r,Lt("number",e)),sr=(e,t,r)=>typeof e=="boolean"?e:it(t,r,Lt("boolean",e)),_n=(e,t,r)=>{if(typeof e=="number"&&at(e))return e;for(let{message:n,path:o,...a}of Ne.safeParse(e).error.issues)it(t,r,a);return kt},ta={present:!0,absent:!0,unknown:!0},ra=Object.keys(ta),wc=ra.map(e=>`'${e}'`).join(" | "),Ic=(e,t,r)=>typeof e!="string"?it(t,r,{code:"invalid_type",expected:wc,received:ea(e)}):Object.hasOwn(ta,e)?e:it(t,r,{code:"invalid_enum_value",received:e,options:[...ra]}),na=qt({name:pe,affiliation:pe}),oa=qt({name:pe,text:pe,color:pe}),aa=qt({id:_n,name:pe,color:pe}),ia=qt({id:_n,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:sr}),_c=qt({id:Zo,fileName:Zo,fileType:Xo,fileSize:Ec,createdAt:Xo,state:Ic,hasThumbnail:sr}),xc=qt({reportHubId:_n,date:pe,createdAt:pe,author:pe,userId:pe,sourceType:pe,employeeName:pe,updatedBy:pe,updatedAt:pe,category:pe,creationCategory:pe,visitTimeFrom:pe,visitTimeTo:pe,customerName:pe,interviewers:ir(ar(na)),subject:pe,content:pe,externalComments:ir(ar(oa)),isRead:sr,isStarred:sr,isDraft:sr,labels:ir(ar(aa)),postedComments:ir(ar(ia)),attachments:ir(ar(_c))}),lr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===kt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},sa=e=>lr(xc,e),la=e=>lr(na,e),ca=e=>lr(oa,e),ua=e=>lr(aa,e),da=e=>lr(ia,e);var pa=15e3,ma="lastEventId",Cc=/^\d{1,15}-\d{1,15}$/,ya=e=>Cc.test(e),Tt="0-0",cr=e=>te.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 te.NEVER}),Gy=cr(la),Ky=cr(ca),Jy=cr(ua),Mc=cr(da),ur=cr(sa),dr=te.string().regex(Pr),ha=te.object({type:te.literal("connected")}),fa=te.object({type:te.literal("status-update"),reportHubId:Ne,statusType:te.enum(["star","read"]),value:te.boolean(),clientTempId:dr}),xn=te.string(),Ra=te.object({type:te.literal("comment-add"),reportHubId:Ne,comment:Mc,clientTempId:dr,sourceType:xn}),Sa=te.object({type:te.literal("comment-delete"),reportHubId:Ne,commentId:Ne,clientTempId:dr,sourceType:xn}),kr={recipientRawUserId:Ne.optional()},Cn=fa.extend(kr),Mn=Ra.extend(kr),Pn=Sa.extend(kr),jt={reportHubId:Ne,report:ur,clientTempId:dr},kn={...kr,actorRawUserId:Ne},Ln={viewerIsActor:te.boolean()},Pc=te.object({type:te.literal("report-create"),...jt,...Ln}),kc=te.object({type:te.literal("report-update"),...jt,...Ln}),Lc=te.object({type:te.literal("report-publish"),...jt,...Ln}),vn=te.object({type:te.literal("report-create"),...jt,...kn}),Nn=te.object({type:te.literal("report-update"),...jt,...kn}),On=te.object({type:te.literal("report-publish"),...jt,...kn}),Lr=te.object({type:te.literal("report-delete"),reportHubId:Ne,clientTempId:dr,sourceType:xn}),Qy=te.discriminatedUnion("type",[ha,fa,Ra,Sa,Pc,kc,Lc,Lr]),Hn=te.discriminatedUnion("type",[ha,Cn,Mn,Pn,vn,Nn,On,Lr]);var ga="ids-columns";var vc=/^[0-9a-f]{1,16}$/,ba=e=>at(e.reportHubId)&&(e.businessDate===null||Mr(e.businessDate)),Da=e=>typeof e=="string"&&vc.test(e),th=Object.freeze({kind:"absent"}),rh=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:h}=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=h===void 0?null:h,y=s.get(p);y===void 0&&(y=i.length,i.push(p),s.set(p,y)),l.push(y)}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+(?=.)/,"")},Aa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Nc=(e,t,r,n)=>Aa(e,t,r,n)<0,Fn=(e,t)=>Aa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ta=e=>{for(let t=1;t<e.length;t++)if(!Nc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ea=(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:ga,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ge=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 wa=(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)}}},ih=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Ia=e=>`[DailyReport${e}]`,be=(e,t,r)=>e===void 0?wa(t,Ia(r)):wa(0,Ia(r),e);import{z as vt}from"zod/v3";var pr=e=>({reportHubId:e,outcome:"not_found"}),dh=vt.discriminatedUnion("outcome",[vt.object({reportHubId:Ne,outcome:vt.literal("ok"),report:ur}).strict(),vt.object({reportHubId:Ne,outcome:vt.literal("not_found")}).strict(),vt.object({reportHubId:Ne,outcome:vt.literal("failed")}).strict()]);var Oc="legacy-",$n=e=>`${Oc}${e}`;var Hc=/^[1-9][0-9]*$/,Fc=/^(?:0|[1-9][0-9]*)$/,Je=e=>{if(e===null||!Hc.test(e))return null;let t=Number(e);return at(t)?t:null},Un=e=>{if(e===null||!Fc.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 _a=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),pt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var $c=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,$c);return o>>>0},xa=e=>qn(Vn,e,0,e.length),Uc=String.fromCodePoint(3),Bc=String.fromCodePoint(2),Vc=String.fromCodePoint(1),Nr=e=>xa(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Uc)).join(Bc)).join(Vc));var Ca=e=>e==="intersection"||e==="union",xe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),jn=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 Rh=2*(1+jn);import{z as Dh}from"zod/v3";var Ma=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var We=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 Qe=(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),Qe(()=>{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 mt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var _h=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),qc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Yn=e=>{let t=e.trim();return t.length===0?null:t.replace(qc,"\uFFFD")},jc=e=>{let t=Yn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>mt.maxValueLength?"filter-value-too-long":null},Wc=e=>{if(e.length>mt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=jc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},Yc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Pa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Wc(t);if(r!==null)return r}return Yc(e)>mt.maxTotalValueLength?"filters-too-long":null};var ka=e=>e.trim().length===0;var zn=e=>e!==null&&Pr.test(e)?e:null,Gn=e=>Ca(e)?e:null,Kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>xe.maxDetailIds)return null;let r=[];for(let n of t){let o=Je(n);if(o===null||r.includes(o))return null;r.push(o)}return r},La=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},va=(e,t)=>{let r={authors:e.getAll(ge.searchAuthor),sourceTypes:e.getAll(ge.searchSourceType),customers:e.getAll(ge.searchCustomer)},n=Pa(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:La(r.authors),customers:La(r.customers)}}},Na=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Ha=Object.freeze({status:400,error:"Invalid form"}),Fa=e=>({status:413,error:"Form too large",measuredBy:e}),zc=(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)}}))},Gc=async e=>{let t=Un(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Fa("declared")};let r=!1,n=e.body===null?null:zc(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?Fa("counted"):Ha}}let l=Na(i);return l===null?{refusal:Ha}:{fields:l}},$a=(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}}},Ba=Object.freeze({update:(e,t,r)=>{let n=e.get(We.title),o=e.get(We.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:$a("toggleStar",We.isStarred),toggleRead:$a("toggleRead",We.isRead),addComment:(e,t)=>{let r=e.get(We.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Je(e.get(We.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Kc=e=>Object.hasOwn(Ba,e),Jc=(e,t)=>{let r=e.get(We.intent),n=e.get(We.businessDate),o=n===null?null:Vt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(We.operationTimestamp),i=Un(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(We.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=Je(e.get(We.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!Kc(r)?{error:"Invalid intent"}:Ba[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Va=async(e,t)=>{let r=await Gc(e);if("refusal"in r)return r;let n=Jc(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Qc=6e4,Xc="form_too_large",Ua=["declared","counted"],qa=e=>{let t=Ce({windowMs:Qc,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(Xc,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"]}}),ja=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})}),Wa=e=>Object.hasOwn(Qn,e);var Zc="download",eu="thumbnail",tu="1";var Xn=e=>{let t=e.getAll(eu),r=e.getAll(Zc);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Wa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===tu?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as au}from"@aiquants/request-isolation";import{createHash as ru}from"crypto";var Zn=e=>`"${ru("sha256").update(e).digest("hex")}"`,Ya=e=>Zn(JSON.stringify(e));var st=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},za=(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,...st});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",...st});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)},nu=5e3/1e3,ou=new Map([[503,nu]]),Te=e=>{let t=ou.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var oo="Cross-site request rejected",iu="Not Found",Ga=["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",...st}}),su=()=>Ka(403,oo),Fr=()=>Ka(404,iu),yr=Object.freeze({...au,frameworkDataRefusal:()=>null,crossSiteRejection:su}),Ja=e=>new URL(e.url).pathname.endsWith(".data"),lu=6e4,cu="refusals",uu=32,du=/^[a-z-]+$/,no=e=>{if(e===null)return"-";let t=e.slice(0,uu);return du.test(t)&&t===e?e:JSON.stringify(t)},Qa=e=>{let t=Ce({windowMs:lu,tallies:Ga,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Ga.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(cu,r,a)}};var Xa=(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 pu="same-origin",mu="SAMEORIGIN",Yt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":pu,"X-Frame-Options":mu}),$r=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Yt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Za=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),yu=/^[\x20-\x7E]+$/,hu=/^[\w.+-]+\/[\w.+-]+/,ao=e=>e&&yu.test(e)&&hu.test(e)?e:null,fu=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,ei=e=>encodeURIComponent(e.replace(fu,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ti=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"},ri={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Ur=e=>typeof e=="string"&&Object.hasOwn(ri,e),Br=e=>ri[e],yt="Attachment request failed";var lt=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=(m,R)=>m.get(R)??0,c=(m,R,T)=>{let E=s(m,R)+T;E<=0?m.delete(R):m.set(R,E)},d=m=>s(l,m)<r,u=m=>o<t&&d(m),h=m=>(o+=1,c(l,m,1),f(m)),p=()=>{let m=-1,R=r;for(let[T,E]of a.entries()){let S=s(l,E.owner);if(S<R&&(m=T,R=S,S===0))break}return m},y=()=>{for(;o<t;){let m=p();if(m<0)return;let[R]=a.splice(m,1);c(i,R.owner,-1),R.grant(h(R.owner))}},f=m=>{let R=!1;return()=>{R||(R=!0,o-=1,c(l,m,-1),y())}};return{canAcquire:u,acquire:(m,R)=>{if(R.aborted)return Promise.resolve(null);if(u(m))return Promise.resolve(h(m));if(n===null||a.length>=n.max||s(i,m)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:T}=n,E=S=>{let g=()=>{let H=a.indexOf(_);H<0||(a.splice(H,1),c(i,m,-1),A(),S(null))},C=Qe(g,T),A=()=>{clearTimeout(C),R.removeEventListener("abort",g)},_={owner:m,grant:H=>{A(),S(H)}};a.push(_),c(i,m,1),R.addEventListener("abort",g,{once:!0})};return new Promise(E)}}};var Ru=1024,io="Too many requests",Su=(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<=Ru)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))}}},ht=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=Su(e.limitPerWindow,r),i=Object.freeze({status:429,message:io,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,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var bu=256*1024,ni=6e4,Du=e=>Math.ceil(e/2),Au=new Uint8Array(new ArrayBuffer(0)),Tu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Au,t()},i=l=>{clearTimeout(o),o=Qe(()=>{l.error(new Error(`attachment body idle for ${ni} ms`)),a()},ni)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+bu,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})},oi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ht({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=lt({limit:e.concurrency,maxHeldPerOwner:Du(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:p,cookie:y,fail:f}=s,m=e.maxBytes,R=i.spend(h,`attachment=${u} viewer=${h}`);if(R)return f(R.status,R.message,R.headers);let T=await n(c,"initial");if(!T.ok)return f(503,hr[503],Te(503));let E=await t.getAttachmentForUser(T.scope,u,h);if(!E)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),f(404,"Attachment not found");if(E.fileSize!=null&&E.fileSize>m)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),f(413,"Attachment too large");let S=ao(E.fileType),g=`filename="${ti(E.fileName)}"; filename*=UTF-8''${ei(E.fileName)}`,C=await l.acquire(h,c.signal);if(!C)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),f(503,"Too many concurrent downloads",Te(503)));let A=!1;try{let _=await p(E.filePath,{maxBytes:m,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),f(503,"Attachment request aborted");if(!_.ok){if(!Ur(_.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),f(500,yt);let F=Br(_.reason);return _.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${h} reason=${_.reason} code=${_.code??"-"}`),f(F,hr[F],Te(F))}if(_.bytes.byteLength>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,yt);let H=c.method==="HEAD";if(H&&_.size!==void 0&&_.size>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,yt);if(!H&&_.size!==void 0&&_.size!==_.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),f(500,yt);let w=S??ao(_.contentType),k=w!==null&&Za.has(w),x=k?w:"application/octet-stream",q=k&&d.kind!=="download"?"inline":"attachment",K=H?_.size:_.bytes.byteLength,z=new Headers({"Content-Type":x,"Content-Disposition":`${q}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Yt});return K!==void 0&&z.set("Content-Length",String(K)),y&&z.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${x} disposition=${q} bytes=${K??"-"}`),H?new Response(null,{status:200,headers:z}):(A=!0,new Response(Tu(_.bytes,C),{status:200,headers:z}))}finally{A||C()}}};var Be=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Rf=Be.queueWaitMs+Be.readMs+Be.renderMs+Be.transferMarginMs;import{Buffer as Eu}from"buffer";var si=new Set([194,198,202,206]),wu=new Set([192,193,194,195]),li=216,Iu=217,ci=218,_u=4,xu=64,Cu=2,ai=8,ii=28,Et=12,so=8,Mu=20,ui=Et+so+10,Pu=2,ft=(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},ct=(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},di=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,pi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),mi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),yi=e=>e[0]===255&&e[1]===li,hi=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!mi(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===Iu)return"eoi";if(o===0||o===li)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ft(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")}},ku=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!mi(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}},fi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ft(e,r+1),a=ft(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}},Ri=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>_u||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Si=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:si.has(e.marker)||t<e.components.length}),lo=e=>{if(!yi(e))return null;let t=pi(e.byteLength),r=null;for(let n=2;;){if(hi(e,n,t)!=="segment")return null;if(di(t.marker)){if(r!==null||(r=fi(e,t),r===null))return null}else if(t.marker===ci){if(r===null)return null;let o=Ri(e,t);return o===null?null:Si(r,o.length)}n=t.end}},gi=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*ai)),i=Math.ceil(e.height*o/(r*ai));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},bi=e=>e.multiScan?gi(e).reduce((r,n)=>r+n,0)*xu*Cu:0,Lu=896,Di=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!yi(e))return null;let n=Eu.from(e.buffer,e.byteOffset,e.byteLength),o=pi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=hi(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,di(o.marker)){if(a!==null||!wu.has(o.marker)||(a=fi(e,o),a===null))return null;let p=gi(a);l=new Map;for(let[y,f]of a.components.entries()){let m=l.get(f.id);l.set(f.id,m===void 0?p[y]:Math.max(m,p[y]))}s=a.components.length*(si.has(a.marker)?Lu:1)}else if(o.marker===ci){if(a===null||d===s)return null;let p=Ri(e,o);if(p===null)return null;for(let f of p){let m=l.get(f);if(m===void 0)return null;c+=m}if(d+=1,i===null&&(i=Si(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=ku(n,o.end,o);if(y===null)return null;u=y}}},Ai=e=>{if(e.byteLength<24||ft(e,8)!==0||ft(e,10)!==13||!ct(e,12,"IHDR"))return null;let t=ft(e,16)*65536+ft(e,18),r=ft(e,20)*65536+ft(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},vu=e=>{if(ct(e,Et,"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(ct(e,Et,"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 ct(e,Et,"VP8X")?e.byteLength<ui?null:{width:zt(e,24,3)+1,height:zt(e,27,3)+1}:null},Ti=e=>{if(Ai(e)===null||e.byteLength<=ii)return null;switch(e[ii]){case 0:return!1;case 1:return!0;default:return null}},Ei=(e,t)=>{if(ct(e,Et,"VP8 "))return"lossy";if(ct(e,Et,"VP8L"))return"lossless";if(!ct(e,Et,"VP8X")||e.byteLength<ui)return null;if((e[Mu]&Pu)!==0)return"animated";let r=!1,n=t;for(let o=Et;o+so<=e.byteLength;){if(n-=1,n<0)return null;if(ct(e,o,"VP8L"))return"lossless";if(ct(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ct(e,o,"ALPH")&&(r=!0);let a=zt(e,o+4,4);o+=so+a+a%2}return null},wi={png:Ai,jpeg:lo,webp:vu};var co=Object.freeze(["image/webp","image/jpeg","image/png"]),uo=1024*1024;var Nu=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Ou={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Hu=new Set(co),Fu=e=>typeof e=="string"&&Hu.has(e),$u=256,Vr=(e,t)=>e.fileType===null||!Nu.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Uu=[137,80,78,71,13,10,26,10],Bu=[255,216,255],Vu=[[71,73,70,56,55,97],[71,73,70,56,57,97]],qu=[82,73,70,70],ju=[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,Uu,0))return"png";if(fr(e,Bu,0))return"jpeg";for(let t of Vu)if(fr(e,t,0))return"gif";return fr(e,qu,0)&&fr(e,ju,8)?"webp":null},Ii=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:Ya([t])}},_i=(e,t)=>{if(!Fu(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=Ou[e.contentType];if(po(e.bytes)!==r)return"signature";let n=wi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},xi=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)+$u;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)},h=S=>{c=Qe(()=>{s=!0,S({timedOut:!0}),d=Qe(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(h),y=AbortSignal.any([r,l.signal]),f=S=>{S(n(y))},m=new Promise(f),R=S=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,S.kind==="error"?{error:S.error}:null),S),T=m.then(S=>R({kind:"value",value:S}),S=>R({kind:"error",error:S}));return{outcome:Promise.race([m.then(S=>({timedOut:!1,value:S})),p]),settled:T}};var Rt={404:"Attachment not found",500:yt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Ci=(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=_i(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Wu=e=>{let t=new AbortController,r=()=>{t.abort()},n=Qe(r,Be.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Mi=()=>{},Yu=(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)}),Pi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,y)=>{let f=y.then(Mi,Mi);l.set(p,f);let m=()=>{l.get(p)===f&&l.delete(p)};f.then(m)},c=async(p,y)=>{let f=l.get(p.key);if(f===void 0)return t.acquire(p.owner,y);let m=Wu(y);try{if(await Yu(f,m.signal),m.signal.aborted)return null;let R=r.get(p.key);return R!==void 0?{...R,identity:"verified"}:await t.acquire(p.owner,m.signal)}finally{m.end()}},d=(p,y)=>{if(p.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===p.fileSize:p.fileSize>y.maxBytes)return"verified";let m=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${m} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,y)=>(f,m)=>{let R=m===null?"":` message=${m.error instanceof Error?m.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${f} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${R}`)},h=(p,y)=>f=>{i.warn(`${p}_stuck ms=${f} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(p,y)=>{let f=await c(p,y);if(f===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof f!="function")return f;let m=f,R=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let T=r.get(p.key);if(T!==void 0)return{...T,identity:"verified"};let E=mo({budgetMs:Be.readMs,flightSignal:y,call:F=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:F}),onOverrun:u("read",p),onStuck:h("read",p)}),S=await E.outcome;if(S.timedOut)return R=E.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Ur(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 C=d(p,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),A=F=>{C==="verified"&&r.set(p.key,F)},_=F=>(A(F),{...F,identity:C});if(!g.ok)return _({kind:"unrenderable",reason:"too_large"});let H=po(g.bytes);if(H===null)return _({kind:"unrenderable",reason:"signature"});let w=mo({budgetMs:Be.renderMs,flightSignal:y,call:F=>p.renderer.render(g.bytes,{format:H,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:F}),onOverrun:u("render",p),onStuck:h("render",p)}),k=F=>{if(F.kind==="error")return;let I=Ci(F.value,p.box);"entry"in I&&A(I.entry)},x=null,q=()=>(x===null&&(x=w.settled.then(k),s(p.key,x)),x);y.addEventListener("abort",q,{once:!0});let K=await w.outcome.finally(()=>y.removeEventListener("abort",q));if(K.timedOut||y.aborted)return R=q(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let z=Ci(K.value,p.box);return"entry"in z?_(z.entry):z.failure}finally{R===null?m():R.then(m,m)}}};var ki=()=>{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 Ni=10,zu=1/Ni,Li=1-zu,Gu=1024,Ku=64,Ju=8,vi="private, no-cache",Qu="no-store",Xu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),Zu=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Oi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>ht({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Ni),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ku,maxPerOwner:Ju,maxWaitMs:Be.queueWaitMs}}),p=xi({maxBytes:l.cacheBytes,maxEntries:Gu}),y=ki(),f=Pi({gate:h,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),m=(S,g,C,A)=>{let _=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${A}`;if(g.kind==="failure")return o[Zu(g)](`${g.status} ${_} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,Rt[g.status],Te(g.status));let H=Xu[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${_} reason=${g.reason}${H}`),S.fail(404,Rt[404]);let w=g.identity==="verified"?{"Cache-Control":vi,ETag:C}:{"Cache-Control":Qu},k=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...w,"Content-Security-Policy":"default-src 'none'; sandbox",...Yt});return S.cookie&&k.append("Set-Cookie",S.cookie),o.info(`200 ${_} type=${g.contentType} bytes=${g.bytes.byteLength}${H}`),new Response(g.bytes,{status:200,headers:k})},R=(S,g)=>{let C=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return C===null?null:g.fail(C.status,C.message,C.headers)},T=S=>R(d,S),E=(S,g)=>g?R(u,S):T(S);return async(S,g)=>{let{request:C,attachmentId:A,internalUserId:_,readAttachment:H,cookie:w,fail:k}=S,x=Qn[g],q=C.headers.get("If-None-Match"),K=q!==null,z=E(S,K);if(z)return z;let F=await n(C,"initial");if(!F.ok)return k(503,Rt[503],Te(503));let I=await t.getAttachmentForUser(F.scope,A,_),j=I!==null&&Vr(I,i)?Ii({rendererId:s.id,box:x,attachmentId:A,filePath:I.filePath,fileType:I.fileType,fileSize:I.fileSize}):null;if(j&&eo(q,j.etag)){let b=new Headers({"Cache-Control":vi,ETag:j.etag,...Yt});return w&&b.append("Set-Cookie",w),o.info(`304 attachment=${A} viewer=${_} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(K){let b=T(S);if(b)return b}if(!I)return o.warn(`404 attachment=${A} viewer=${_} variant=thumbnail reason=not_visible`),k(404,Rt[404]);if(!j)return d.refund(_,Li),o.info(`404 attachment=${A} viewer=${_} variant=thumbnail reason=not_eligible`),k(404,Rt[404]);let{key:ce,etag:ne}=j,de=p.get(ce);if(de)return d.refund(_,Li),m(S,{...de,identity:"verified"},ne,"hit");let Re=b=>f({key:ce,attachmentId:A,filePath:I.filePath,fileSize:I.fileSize,box:x,owner:_,readAttachment:H,renderer:s},b),J;try{J=await y.join(ce,C.signal,Re)}catch(b){return o.error(`500 attachment=${A} viewer=${_} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),k(500,Rt[500])}return m(S,J,ne,"miss")}};var ed='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',td=()=>$r(403,oo,{cookie:null}),Hi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Xn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>$r(404,hr[404],{cookie:null}),crossSiteRejection:td}),Fi=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:Xa(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:oi({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Oi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(p,y,f={})=>$r(p,y,{cookie:u,extraHeaders:f});try{let{user:p,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!p)return h(401,"Unauthorized");let f=Xn(new URL(c.url).searchParams);if(f.kind==="invalid")return h(400,"Invalid attachment request");if(f.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(ed);let m=s.idCodec.decode(d.token);if(m===null||!at(m))return h(400,"Invalid attachment token");let R=await r.getUserIdByExternalId(p.id);if(!R)return h(403,"Forbidden");let T={request:c,delivery:f,attachmentId:m,internalUserId:R,readAttachment:s.read,cookie:u,fail:h};return f.kind!=="thumbnail"?await s.serveOriginal(T):s.serveThumbnail===null?h(404,Rt[404]):await s.serveThumbnail(T,f.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),h(500,yt)}}};var rd=32*1024*1024,nd=60,od=4,ad=120,id=2,sd=8*1024*1024,qr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ld=e=>{if(e===void 0)throw je("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!qr(e))throw Q("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw je("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},cd=e=>{if(e===void 0)return null;if(!qr(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:ld(e.renderer),rateLimitPerMinute:ve("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,ad),concurrency:ve("attachments.thumbnails.concurrency",e.concurrency,1,id),cacheBytes:ve("attachments.thumbnails.cacheBytes",e.cacheBytes,0,sd)})},$i=e=>{let t=e;if(t===void 0)return null;if(!qr(t))throw Q("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw je("attachments.idCodec","injected when attachments is given");if(!qr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw je("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:ve("attachments.maxBytes",t.maxBytes,1,rd),rateLimitPerMinute:ve("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,nd),concurrency:ve("attachments.concurrency",t.concurrency,1,od),thumbnails:cd(t.thumbnails)})},ud=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"]]),jr=e=>{for(let[t,r]of ud)if(Object.hasOwn(e,t))throw je(r,`given in place of the flat key ${t}`)};var Bi=8,dd=8*Bi,pd=128,md=2,Vi=md*pd,yd=4*Vi,hd=6e4,fd=6e4,Rd="Too many reads",Ui=Object.freeze(Object.keys(Ot).filter(e=>Ot[e].admission.includes("miss-gate"))),qi=e=>{let t=lt({limit:dd,maxHeldPerOwner:Bi,queue:{max:yd,maxPerOwner:Vi,maxWaitMs:hd}}),r=Ce({windowMs:fd,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:Rd}},503);for(let[o,a]of Object.entries(Te(503)))n.headers.set(o,a);return n};var ji=e=>{let t=e.get(ge.cursorReportHubId),r=e.get(ge.cursorBusinessDate),n=e.get(ge.cursorSnapshot),o=Da(n)?n:null,a=null;if(t!==null){let l=Je(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!ba(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=mr(e.get(ge.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Yr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,Sd=2,gd=16,bd=Sd*gd,Dd=6e4,Wi=()=>{},Ad=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Yi=e=>{let t=lt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:bd,queue:null}),r=Ce({windowMs:Dd,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 Wi;if(a.aborted){if(t.canAcquire(n))return Wi}else{let i=await t.acquire(n,a);if(i!==null)return Ad(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var zr=30,Qi=4e3,Td="stream interrupted by server error",Ed="Too many streams",wd=15e3,Xi=Symbol("ids-stream-heartbeat"),zi=()=>{},Gi=e=>e.return(void 0).then(zi,zi),Id=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Xi),wd)}),stop:()=>clearTimeout(e)}};async function*Ki(e,t,r,n){let o=t?Ea(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Qi),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 Zi=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...st});return e&&t.append("Set-Cookie",e),t},Ji=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Gi(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=Id();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===Xi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
1
|
+
var Go=e=>{throw TypeError(e)};var Ko=(e,t,r)=>t.has(e)||Go("Cannot "+r);var tr=(e,t,r)=>(Ko(e,t,"read from private field"),r?r.call(e):t.get(e)),An=(e,t,r)=>t.has(e)?Go("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Tn=(e,t,r,n)=>(Ko(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,Q=(e,t,r)=>new RangeError(`[daily-report] ${e} must be ${t}; got ${Pt(r)}`),We=(e,t)=>new TypeError(`[daily-report] ${e} must be ${t}`),En=(e,t,r)=>Q(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 Q(e,n===void 0?`an integer >= ${r}`:`an integer from ${r} to ${n}`,t)},ve=(e,t,r,n)=>t===void 0?n:ie(e,t,r),rr=(e,t)=>{if(t===void 0)throw We(e,"a function");if(typeof t!="function")throw Q(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,pc=8,mc=32,yc=24,hc=16,fc=-(2**30),Rc=2**30-1,Sc=e=>Number.isInteger(e)&&e>=fc&&e<=Rc&&!Object.is(e,-0),gc=(e,t)=>{let r=0,n=[e];for(;n.length>0&&r<=t;){let o=n.pop();if(r+=mc,ArrayBuffer.isView(o)){r+=o.byteLength;continue}let a=Array.isArray(o)?o:Object.keys(o).map(i=>o[i]);r+=pc*a.length;for(let i of a)typeof i=="string"?r+=yc+2*i.length:typeof i=="number"&&!Sc(i)?r+=hc: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=ve("cacheDefaultTtlMs",t.defaultTtlMs,1,wn.defaultTtlMs),this.maxBuckets=ve("cacheMaxBuckets",t.maxBuckets,1,wn.maxBuckets),this.maxBytes=ve("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=gc(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 Wp}from"@aiquants/request-isolation";var bc=/^(\d{4})([-/])(\d{2})\2(\d{2})$/;var Jo=e=>e<10?`0${e}`:`${e}`,Dc=e=>{if(Number.isNaN(e.getTime()))return null;let t=e.getFullYear(),r=Jo(e.getMonth()+1),n=Jo(e.getDate());return`${t}-${r}-${n}`},Vt=e=>{let t=bc.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 Ue=e=>e==null?null:e instanceof Date?Dc(e):Vt(e);import{z as Ac}from"zod/v3";var at=e=>Number.isSafeInteger(e)&&e>0,Ne=Ac.number().int().positive().max(Number.MAX_SAFE_INTEGER);import{z as te}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"),it=(e,t,r)=>(e.issues.push({...r,path:t===null?[...e.path]:[...e.path,t]}),kt),ea=e=>e===null?"null":Array.isArray(e)?"array":Number.isNaN(e)?"nan":typeof e,Lt=(e,t)=>({code:"invalid_type",expected:e,received:ea(t)}),Tc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ec=e=>{let t=0;for(let r in e)t+=1;return t},Qo=(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(!Tc(n))return it(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=Qo(n,t,s)),a!==null&&(u!==void 0||c in n)&&(a[c]=u)}return i?kt:a!==null?a:Ec(n)===l?n:Qo(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 it(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},pe=(e,t,r)=>e==null||typeof e=="string"?e:it(t,r,Lt("string",e)),Xo=(e,t,r)=>e===null||typeof e=="string"?e:it(t,r,Lt("string",e)),Zo=(e,t,r)=>typeof e=="string"?e:it(t,r,Lt("string",e)),wc=(e,t,r)=>e===null||typeof e=="number"&&!Number.isNaN(e)?e:it(t,r,Lt("number",e)),sr=(e,t,r)=>typeof e=="boolean"?e:it(t,r,Lt("boolean",e)),_n=(e,t,r)=>{if(typeof e=="number"&&at(e))return e;for(let{message:n,path:o,...a}of Ne.safeParse(e).error.issues)it(t,r,a);return kt},ta={present:!0,absent:!0,unknown:!0},ra=Object.keys(ta),Ic=ra.map(e=>`'${e}'`).join(" | "),_c=(e,t,r)=>typeof e!="string"?it(t,r,{code:"invalid_type",expected:Ic,received:ea(e)}):Object.hasOwn(ta,e)?e:it(t,r,{code:"invalid_enum_value",received:e,options:[...ra]}),na=qt({name:pe,affiliation:pe}),oa=qt({name:pe,text:pe,color:pe}),aa=qt({id:_n,name:pe,color:pe}),ia=qt({id:_n,userId:pe,userName:pe,content:pe,createdAt:pe,isMine:sr}),xc=qt({id:Zo,fileName:Zo,fileType:Xo,fileSize:wc,createdAt:Xo,state:_c,hasThumbnail:sr}),Cc=qt({reportHubId:_n,date:pe,createdAt:pe,author:pe,userId:pe,sourceType:pe,employeeName:pe,updatedBy:pe,updatedAt:pe,category:pe,creationCategory:pe,visitTimeFrom:pe,visitTimeTo:pe,customerName:pe,interviewers:ir(ar(na)),subject:pe,content:pe,externalComments:ir(ar(oa)),isRead:sr,isStarred:sr,isDraft:sr,labels:ir(ar(aa)),postedComments:ir(ar(ia)),attachments:ir(ar(xc))}),lr=(e,t)=>{let r={path:[],issues:[]},n=e(t,r);return n===kt?{ok:!1,issues:r.issues}:{ok:!0,value:n}},sa=e=>lr(Cc,e),la=e=>lr(na,e),ca=e=>lr(oa,e),ua=e=>lr(aa,e),da=e=>lr(ia,e);var pa=15e3,ma="lastEventId",Mc=/^\d{1,15}-\d{1,15}$/,ya=e=>Mc.test(e),Tt="0-0",cr=e=>te.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 te.NEVER}),Ky=cr(la),Jy=cr(ca),Qy=cr(ua),Pc=cr(da),ur=cr(sa),dr=te.string().regex(Pr),ha=te.object({type:te.literal("connected")}),fa=te.object({type:te.literal("status-update"),reportHubId:Ne,statusType:te.enum(["star","read"]),value:te.boolean(),clientTempId:dr}),xn=te.string(),Ra=te.object({type:te.literal("comment-add"),reportHubId:Ne,comment:Pc,clientTempId:dr,sourceType:xn}),Sa=te.object({type:te.literal("comment-delete"),reportHubId:Ne,commentId:Ne,clientTempId:dr,sourceType:xn}),kr={recipientRawUserId:Ne.optional()},Cn=fa.extend(kr),Mn=Ra.extend(kr),Pn=Sa.extend(kr),jt={reportHubId:Ne,report:ur,clientTempId:dr},kn={...kr,actorRawUserId:Ne},Ln={viewerIsActor:te.boolean()},kc=te.object({type:te.literal("report-create"),...jt,...Ln}),Lc=te.object({type:te.literal("report-update"),...jt,...Ln}),vc=te.object({type:te.literal("report-publish"),...jt,...Ln}),vn=te.object({type:te.literal("report-create"),...jt,...kn}),Nn=te.object({type:te.literal("report-update"),...jt,...kn}),On=te.object({type:te.literal("report-publish"),...jt,...kn}),Lr=te.object({type:te.literal("report-delete"),reportHubId:Ne,clientTempId:dr,sourceType:xn}),Xy=te.discriminatedUnion("type",[ha,fa,Ra,Sa,kc,Lc,vc,Lr]),Hn=te.discriminatedUnion("type",[ha,Cn,Mn,Pn,vn,Nn,On,Lr]);var ga="ids-columns";var Nc=/^[0-9a-f]{1,16}$/,ba=e=>at(e.reportHubId)&&(e.businessDate===null||Mr(e.businessDate)),Da=e=>typeof e=="string"&&Nc.test(e),rh=Object.freeze({kind:"absent"}),nh=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:h}=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=h===void 0?null:h,y=s.get(p);y===void 0&&(y=i.length,i.push(p),s.set(p,y)),l.push(y)}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+(?=.)/,"")},Aa=(e,t,r,n)=>e!==r?e===null?1:r===null||e>r?-1:1:n-t,Oc=(e,t,r,n)=>Aa(e,t,r,n)<0,Fn=(e,t)=>Aa(e.businessDate,e.reportHubId,t.businessDate,t.reportHubId),Ta=e=>{for(let t=1;t<e.length;t++)if(!Oc(e[t-1].businessDate,e[t-1].reportHubId,e[t].businessDate,e[t].reportHubId))return!1;return!0},Ea=(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:ga,report:"report",search:"search",reports:"reports",searchMarks:"search-marks",searchFacets:"search-facets",action:"action"}),ge=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 wa=(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)}}},sh=Object.freeze(["API","Action","Attachment","ExternalSource","Isolation","Reads","Refresh","Search","SSE","SseReader","Server","Service","Streams","Visibility","ActionProvider","DetailLoader","IdsStream","SseConnection"]),Ia=e=>`[DailyReport${e}]`,be=(e,t,r)=>e===void 0?wa(t,Ia(r)):wa(0,Ia(r),e);import{z as vt}from"zod/v3";var pr=e=>({reportHubId:e,outcome:"not_found"}),ph=vt.discriminatedUnion("outcome",[vt.object({reportHubId:Ne,outcome:vt.literal("ok"),report:ur}).strict(),vt.object({reportHubId:Ne,outcome:vt.literal("not_found")}).strict(),vt.object({reportHubId:Ne,outcome:vt.literal("failed")}).strict()]);var Hc="legacy-",$n=e=>`${Hc}${e}`;var Fc=/^[1-9][0-9]*$/,$c=/^(?:0|[1-9][0-9]*)$/,Qe=e=>{if(e===null||!Fc.test(e))return null;let t=Number(e);return at(t)?t:null},Un=e=>{if(e===null||!$c.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 _a=Object.freeze(["subject","content","author","employeeName","updatedBy","category","creationCategory","customerName"]),pt=Object.freeze({field:e=>e,interviewer:(e,t)=>`interviewer:${e}:${t}`,attachment:e=>`attachment:${e}`,comment:(e,t)=>`comment:${e}:${t}`});var Uc=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,Uc);return o>>>0},xa=e=>qn(Vn,e,0,e.length),Bc=String.fromCodePoint(3),Vc=String.fromCodePoint(2),qc=String.fromCodePoint(1),Nr=e=>xa(e.map(t=>t.map(r=>r.map(n=>`${n.tier}${n.text}`).join(Bc)).join(Vc)).join(qc));var Ca=e=>e==="intersection"||e==="union",xe=Object.freeze({maxQueryLength:500,maxSets:16,maxWordsPerSet:16,maxWords:32,maxWordLength:100,maxDetailIds:100}),jn=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 Sh=2*(1+jn);import{z as Ah}from"zod/v3";var Ma=e=>e.issues.map(t=>`${t.path.length===0?"(root)":t.path.join(".")}: ${t.code}`).join("; ");var Ye=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 Xe=(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),Xe(()=>{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 mt=Object.freeze({maxValuesPerFacet:16,maxValueLength:200,maxTotalValueLength:300});var xh=Object.freeze({authors:Object.freeze([]),sourceTypes:Object.freeze([]),customers:Object.freeze([])}),jc=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,Yn=e=>{let t=e.trim();return t.length===0?null:t.replace(jc,"\uFFFD")},Wc=e=>{let t=Yn(e);return t===null?"filter-blank-value":t!==e?"filter-value-not-canonical":e.length>mt.maxValueLength?"filter-value-too-long":null},Yc=e=>{if(e.length>mt.maxValuesPerFacet)return"filter-too-many-values";let t=new Set;for(let r of e){let n=Wc(r);if(n!==null)return n;if(t.has(r))return"filter-duplicate-value";t.add(r)}return null},zc=e=>{let t=0;for(let r of e.authors)t+=r.length;for(let r of e.customers)t+=r.length;return t},Pa=e=>{for(let t of[e.authors,e.sourceTypes,e.customers]){let r=Yc(t);if(r!==null)return r}return zc(e)>mt.maxTotalValueLength?"filters-too-long":null};var ka=e=>e.trim().length===0;var zn=e=>e!==null&&Pr.test(e)?e:null,Gn=e=>Ca(e)?e:null,Kn=e=>{if(e===null)return null;let t=e.split(",");if(t.length>xe.maxDetailIds)return null;let r=[];for(let n of t){let o=Qe(n);if(o===null||r.includes(o))return null;r.push(o)}return r},La=e=>{let[t,...r]=e;return t===void 0?null:[t,...r]},va=(e,t)=>{let r={authors:e.getAll(ge.searchAuthor),sourceTypes:e.getAll(ge.searchSourceType),customers:e.getAll(ge.searchCustomer)},n=Pa(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:La(r.authors),customers:La(r.customers)}}},Na=e=>{let t=new URLSearchParams;for(let[r,n]of e){if(typeof n!="string")return null;t.append(r,n)}return t};var Ha=Object.freeze({status:400,error:"Invalid form"}),Fa=e=>({status:413,error:"Form too large",measuredBy:e}),Gc=(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)}}))},Kc=async e=>{let t=Un(e.headers.get("Content-Length"));if(t!==null&&t>1048576)return{refusal:Fa("declared")};let r=!1,n=e.body===null?null:Gc(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?Fa("counted"):Ha}}let l=Na(i);return l===null?{refusal:Ha}:{fields:l}},$a=(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}}},Ba=Object.freeze({update:(e,t,r)=>{let n=e.get(Ye.title),o=e.get(Ye.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:$a("toggleStar",Ye.isStarred),toggleRead:$a("toggleRead",Ye.isRead),addComment:(e,t)=>{let r=e.get(Ye.content);return r?{command:{...t,intent:"addComment",content:r}}:{error:"Content required"}},deleteComment:(e,t)=>{let r=Qe(e.get(Ye.commentId));return r===null?{error:"Invalid commentId"}:{command:{...t,intent:"deleteComment",commentId:r}}}}),Jc=e=>Object.hasOwn(Ba,e),Qc=(e,t)=>{let r=e.get(Ye.intent),n=e.get(Ye.businessDate),o=n===null?null:Vt(n);if(n!==null&&o===null)return{error:"Invalid businessDate"};let a=e.get(Ye.operationTimestamp),i=Un(a);if(a!==null&&i===null)return{error:"Invalid operationTimestamp"};if(r==="clearCache")return{command:{intent:r}};let l=e.get(Ye.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=Qe(e.get(Ye.reportHubId));return c===null?{error:"Invalid reportHubId"}:r===null||!Jc(r)?{error:"Invalid intent"}:Ba[r](e,{clientTempId:s,businessDate:o,operationTimestamp:i,reportHubId:c},t)},Va=async(e,t)=>{let r=await Kc(e);if("refusal"in r)return r;let n=Qc(r.fields,t);return"error"in n?{refusal:{status:400,error:n.error}}:n},Xc=6e4,Zc="form_too_large",Ua=["declared","counted"],qa=e=>{let t=Ce({windowMs:Xc,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(Zc,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"]}}),ja=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})}),Wa=e=>Object.hasOwn(Qn,e);var eu="download",tu="thumbnail",ru="1";var Xn=e=>{let t=e.getAll(tu),r=e.getAll(eu);if(t.length>0&&r.length>0)return{kind:"invalid",reason:"conflict"};if(t.length>0){let[n]=t;return t.length===1&&Wa(n)?{kind:"thumbnail",variant:n}:{kind:"invalid",reason:"thumbnail_variant"}}return r.length>0?r.length===1&&r[0]===ru?{kind:"download"}:{kind:"invalid",reason:"download_value"}:{kind:"inline"}};import{NO_CROSS_ORIGIN_NAVIGATION as iu}from"@aiquants/request-isolation";import{createHash as nu}from"crypto";var Zn=e=>`"${nu("sha256").update(e).digest("hex")}"`,Ya=e=>Zn(JSON.stringify(e));var st=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},za=(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,...st});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",...st});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)},ou=5e3/1e3,au=new Map([[503,ou]]),Te=e=>{let t=au.get(e);return t===void 0?{}:{"Retry-After":String(t)}};var oo="Cross-site request rejected",su="Not Found",Ga=["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",...st}}),lu=()=>Ka(403,oo),Fr=()=>Ka(404,su),yr=Object.freeze({...iu,frameworkDataRefusal:()=>null,crossSiteRejection:lu}),Ja=e=>new URL(e.url).pathname.endsWith(".data"),cu=6e4,uu="refusals",du=32,pu=/^[a-z-]+$/,no=e=>{if(e===null)return"-";let t=e.slice(0,du);return pu.test(t)&&t===e?e:JSON.stringify(t)},Qa=e=>{let t=Ce({windowMs:cu,tallies:Ga,writeSuppressed:(r,{count:n,since:o,tallies:a})=>{e.warn(`cross_site_rejected_suppressed count=${n} since=${o} routes=${Ga.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(uu,r,a)}};var Xa=(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 mu="same-origin",yu="SAMEORIGIN",Yt=Object.freeze({"X-Content-Type-Options":"nosniff","Cross-Origin-Resource-Policy":mu,"X-Frame-Options":yu}),$r=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json","Cache-Control":"no-store",...r.extraHeaders,...Yt});return r.cookie&&n.append("Set-Cookie",r.cookie),new Response(JSON.stringify({error:{message:t}}),{status:e,headers:n})},Za=new Set(["image/png","image/jpeg","image/gif","image/webp","application/pdf","text/plain"]),hu=/^[\x20-\x7E]+$/,fu=/^[\w.+-]+\/[\w.+-]+/,ao=e=>e&&hu.test(e)&&fu.test(e)?e:null,Ru=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,ei=e=>encodeURIComponent(e.replace(Ru,"\uFFFD")).replace(/['()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),ti=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"},ri={not_found:404,denied:404,invalid_path:404,too_large:413,unavailable:502,busy:503,deadline:504},Ur=e=>typeof e=="string"&&Object.hasOwn(ri,e),Br=e=>ri[e],yt="Attachment request failed";var lt=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=(m,R)=>m.get(R)??0,c=(m,R,A)=>{let E=s(m,R)+A;E<=0?m.delete(R):m.set(R,E)},d=m=>s(l,m)<r,u=m=>o<t&&d(m),h=m=>(o+=1,c(l,m,1),f(m)),p=()=>{let m=-1,R=r;for(let[A,E]of a.entries()){let S=s(l,E.owner);if(S<R&&(m=A,R=S,S===0))break}return m},y=()=>{for(;o<t;){let m=p();if(m<0)return;let[R]=a.splice(m,1);c(i,R.owner,-1),R.grant(h(R.owner))}},f=m=>{let R=!1;return()=>{R||(R=!0,o-=1,c(l,m,-1),y())}};return{canAcquire:u,acquire:(m,R)=>{if(R.aborted)return Promise.resolve(null);if(u(m))return Promise.resolve(h(m));if(n===null||a.length>=n.max||s(i,m)>=n.maxPerOwner)return Promise.resolve(null);let{maxWaitMs:A}=n,E=S=>{let g=()=>{let H=a.indexOf(_);H<0||(a.splice(H,1),c(i,m,-1),D(),S(null))},C=Xe(g,A),D=()=>{clearTimeout(C),R.removeEventListener("abort",g)},_={owner:m,grant:H=>{D(),S(H)}};a.push(_),c(i,m,1),R.addEventListener("abort",g,{once:!0})};return new Promise(E)}}};var Su=1024,io="Too many requests",gu=(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<=Su)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))}}},ht=e=>{let{reason:t,windowMs:r,logger:n,windowFields:o}=e;if(ie("windowMs",r,1e3)%1e3!==0)throw Q("windowMs","a whole number of seconds (a multiple of 1000)",r);let a=gu(e.limitPerWindow,r),i=Object.freeze({status:429,message:io,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,se())?null:(l.record(s,t,()=>n.warn(`429 ${c} reason=${t}`)),i),refund:(s,c)=>{a.refund(s,se(),c)}}};var Du=256*1024,ni=6e4,Au=e=>Math.ceil(e/2),Tu=new Uint8Array(new ArrayBuffer(0)),Eu=(e,t)=>{let r=e,n=0,o,a=()=>{clearTimeout(o),r=Tu,t()},i=l=>{clearTimeout(o),o=Xe(()=>{l.error(new Error(`attachment body idle for ${ni} ms`)),a()},ni)};return new ReadableStream({start(l){i(l)},pull(l){let s=Math.min(n+Du,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})},oi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a}=e,i=ht({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:6e4,logger:o,windowFields:s=>`viewer=${s}`}),l=lt({limit:e.concurrency,maxHeldPerOwner:Au(e.concurrency),queue:null});return async s=>{let{request:c,delivery:d,attachmentId:u,internalUserId:h,readAttachment:p,cookie:y,fail:f}=s,m=e.maxBytes,R=i.spend(h,`attachment=${u} viewer=${h}`);if(R)return f(R.status,R.message,R.headers);let A=await n(c,"initial");if(!A.ok)return f(503,hr[503],Te(503));let E=await t.getAttachmentForUser(A.scope,u,h);if(!E)return o.warn(`404 attachment=${u} viewer=${h} reason=not_visible`),f(404,"Attachment not found");if(E.fileSize!=null&&E.fileSize>m)return o.warn(`413 attachment=${u} viewer=${h} reason=db_size`),f(413,"Attachment too large");let S=ao(E.fileType),g=`filename="${ti(E.fileName)}"; filename*=UTF-8''${ei(E.fileName)}`,C=await l.acquire(h,c.signal);if(!C)return c.signal.aborted?(o.info(`503 attachment=${u} viewer=${h} reason=aborted`),f(503,"Attachment request aborted")):(o.warn(`503 attachment=${u} viewer=${h} reason=concurrency`),f(503,"Too many concurrent downloads",Te(503)));let D=!1;try{let _=await p(E.filePath,{maxBytes:m,head:c.method==="HEAD",principal:r(h),signal:c.signal});if(c.signal.aborted)return o.info(`503 attachment=${u} viewer=${h} reason=aborted`),f(503,"Attachment request aborted");if(!_.ok){if(!Ur(_.reason))return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=failure_reason`),f(500,yt);let F=Br(_.reason);return _.reason==="not_found"&&a(u,!1),o.warn(`${F} attachment=${u} viewer=${h} reason=${_.reason} code=${_.code??"-"}`),f(F,hr[F],Te(F))}if(_.bytes.byteLength>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,yt);let H=c.method==="HEAD";if(H&&_.size!==void 0&&_.size>m)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=over_max_bytes`),f(500,yt);if(!H&&_.size!==void 0&&_.size!==_.bytes.byteLength)return o.error(`500 attachment=${u} viewer=${h} reason=port_contract code=size_mismatch`),f(500,yt);let w=S??ao(_.contentType),L=w!==null&&Za.has(w),x=L?w:"application/octet-stream",q=L&&d.kind!=="download"?"inline":"attachment",K=H?_.size:_.bytes.byteLength,G=new Headers({"Content-Type":x,"Content-Disposition":`${q}; ${g}`,"Cache-Control":"private, no-store","Content-Security-Policy":"default-src 'none'; sandbox",...Yt});return K!==void 0&&G.set("Content-Length",String(K)),y&&G.append("Set-Cookie",y),a(u,!0),o.info(`200 attachment=${u} viewer=${h} type=${x} disposition=${q} bytes=${K??"-"}`),H?new Response(null,{status:200,headers:G}):(D=!0,new Response(Eu(_.bytes,C),{status:200,headers:G}))}finally{D||C()}}};var Be=Object.freeze({queueWaitMs:3e4,readMs:3e4,renderMs:1e4,transferMarginMs:5e3}),Sf=Be.queueWaitMs+Be.readMs+Be.renderMs+Be.transferMarginMs;import{Buffer as wu}from"buffer";var si=new Set([194,198,202,206]),Iu=new Set([192,193,194,195]),li=216,_u=217,ci=218,xu=4,Cu=64,Mu=2,ai=8,ii=28,Et=12,so=8,Pu=20,ui=Et+so+10,ku=2,ft=(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},ct=(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},di=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204,pi=e=>({marker:0,body:0,length:0,end:0,stepsLeft:e}),mi=e=>(e.stepsLeft-=1,e.stepsLeft>=0),yi=e=>e[0]===255&&e[1]===li,hi=(e,t,r)=>{let n=t;for(;;){if(n>=e.byteLength||e[n]!==255)return null;do{if(!mi(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===_u)return"eoi";if(o===0||o===li)return null;if(o===1||o>=208&&o<=215)continue;if(n+2>e.byteLength)return null;let a=ft(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")}},Lu=(e,t,r)=>{let n=e.byteLength,o=t;for(;;){let a=e.indexOf(255,o);if(a<0)return n;for(;;){if(!mi(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}},fi=(e,{marker:t,body:r,length:n})=>{if(n<8)return null;let o=ft(e,r+1),a=ft(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}},Ri=(e,{body:t,length:r})=>{if(r<3)return null;let n=e[t];return n<1||n>xu||r!==6+2*n?null:Array.from({length:n},(o,a)=>e[t+1+2*a])},Si=(e,t)=>({width:e.width,height:e.height,components:e.components.map(({horizontal:r,vertical:n})=>({horizontal:r,vertical:n})),multiScan:si.has(e.marker)||t<e.components.length}),lo=e=>{if(!yi(e))return null;let t=pi(e.byteLength),r=null;for(let n=2;;){if(hi(e,n,t)!=="segment")return null;if(di(t.marker)){if(r!==null||(r=fi(e,t),r===null))return null}else if(t.marker===ci){if(r===null)return null;let o=Ri(e,t);return o===null?null:Si(r,o.length)}n=t.end}},gi=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*ai)),i=Math.ceil(e.height*o/(r*ai));return Math.ceil(a/n)*n*Math.ceil(i/o)*o})},bi=e=>e.multiScan?gi(e).reduce((r,n)=>r+n,0)*Cu*Mu:0,vu=896,Di=(e,{maxBlockVisits:t,maxWalkSteps:r})=>{if(!yi(e))return null;let n=wu.from(e.buffer,e.byteOffset,e.byteLength),o=pi(r),a=null,i=null,l=new Map,s=0,c=0,d=0;for(let u=2;;){let h=hi(e,u,o);if(h===null)return null;if(h==="eoi")return i===null?null:{header:i,blockVisits:c};if(u=o.end,di(o.marker)){if(a!==null||!Iu.has(o.marker)||(a=fi(e,o),a===null))return null;let p=gi(a);l=new Map;for(let[y,f]of a.components.entries()){let m=l.get(f.id);l.set(f.id,m===void 0?p[y]:Math.max(m,p[y]))}s=a.components.length*(si.has(a.marker)?vu:1)}else if(o.marker===ci){if(a===null||d===s)return null;let p=Ri(e,o);if(p===null)return null;for(let f of p){let m=l.get(f);if(m===void 0)return null;c+=m}if(d+=1,i===null&&(i=Si(a,p.length)),c>t||!i.multiScan)return{header:i,blockVisits:c};let y=Lu(n,o.end,o);if(y===null)return null;u=y}}},Ai=e=>{if(e.byteLength<24||ft(e,8)!==0||ft(e,10)!==13||!ct(e,12,"IHDR"))return null;let t=ft(e,16)*65536+ft(e,18),r=ft(e,20)*65536+ft(e,22);return t===0||r===0||t>2147483647||r>2147483647?null:{width:t,height:r}},Nu=e=>{if(ct(e,Et,"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(ct(e,Et,"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 ct(e,Et,"VP8X")?e.byteLength<ui?null:{width:zt(e,24,3)+1,height:zt(e,27,3)+1}:null},Ti=e=>{if(Ai(e)===null||e.byteLength<=ii)return null;switch(e[ii]){case 0:return!1;case 1:return!0;default:return null}},Ei=(e,t)=>{if(ct(e,Et,"VP8 "))return"lossy";if(ct(e,Et,"VP8L"))return"lossless";if(!ct(e,Et,"VP8X")||e.byteLength<ui)return null;if((e[Pu]&ku)!==0)return"animated";let r=!1,n=t;for(let o=Et;o+so<=e.byteLength;){if(n-=1,n<0)return null;if(ct(e,o,"VP8L"))return"lossless";if(ct(e,o,"VP8 "))return r?"lossy-alpha":"lossy";ct(e,o,"ALPH")&&(r=!0);let a=zt(e,o+4,4);o+=so+a+a%2}return null},wi={png:Ai,jpeg:lo,webp:Nu};var co=Object.freeze(["image/webp","image/jpeg","image/png"]),uo=1024*1024;var Ou=new Set(["image/png","image/jpeg","image/gif","image/webp"]),Hu={"image/webp":"webp","image/jpeg":"jpeg","image/png":"png"},Fu=new Set(co),$u=e=>typeof e=="string"&&Fu.has(e),Uu=256,Vr=(e,t)=>e.fileType===null||!Ou.has(e.fileType)?!1:e.fileSize===null||e.fileSize<=t,Bu=[137,80,78,71,13,10,26,10],Vu=[255,216,255],qu=[[71,73,70,56,55,97],[71,73,70,56,57,97]],ju=[82,73,70,70],Wu=[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,Bu,0))return"png";if(fr(e,Vu,0))return"jpeg";for(let t of qu)if(fr(e,t,0))return"gif";return fr(e,ju,0)&&fr(e,Wu,8)?"webp":null},Ii=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:Ya([t])}},_i=(e,t)=>{if(!$u(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=Hu[e.contentType];if(po(e.bytes)!==r)return"signature";let n=wi[r](e.bytes);return n===null||n.width>t.maxWidth||n.height>t.maxHeight?"dimensions":null},xi=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)+Uu;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)},h=S=>{c=Xe(()=>{s=!0,S({timedOut:!0}),d=Xe(u,t),l.abort(new DOMException(`stage exceeded its ${t} ms budget`,"TimeoutError"))},t)},p=new Promise(h),y=AbortSignal.any([r,l.signal]),f=S=>{S(n(y))},m=new Promise(f),R=S=>(clearTimeout(c),clearTimeout(d),s&&o(se()-i,S.kind==="error"?{error:S.error}:null),S),A=m.then(S=>R({kind:"value",value:S}),S=>R({kind:"error",error:S}));return{outcome:Promise.race([m.then(S=>({timedOut:!1,value:S})),p]),settled:A}};var Rt={404:"Attachment not found",500:yt,502:"Thumbnail unavailable",503:"Thumbnail temporarily unavailable",504:"Thumbnail storage timed out"},Ci=(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=_i(r,t);return n!==null?{failure:{kind:"failure",status:500,reason:"port_contract",code:n}}:{entry:{kind:"thumbnail",bytes:r.bytes,contentType:r.contentType}}},Yu=e=>{let t=new AbortController,r=()=>{t.abort()},n=Xe(r,Be.queueWaitMs);return e.addEventListener("abort",r,{once:!0}),e.aborted&&r(),{signal:t.signal,end:()=>{clearTimeout(n),e.removeEventListener("abort",r)}}},Mi=()=>{},zu=(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)}),Pi=e=>{let{gate:t,cache:r,maxBytes:n,encodeUserId:o,recordObjectState:a,logger:i}=e,l=new Map,s=(p,y)=>{let f=y.then(Mi,Mi);l.set(p,f);let m=()=>{l.get(p)===f&&l.delete(p)};f.then(m)},c=async(p,y)=>{let f=l.get(p.key);if(f===void 0)return t.acquire(p.owner,y);let m=Yu(y);try{if(await zu(f,m.signal),m.signal.aborted)return null;let R=r.get(p.key);return R!==void 0?{...R,identity:"verified"}:await t.acquire(p.owner,m.signal)}finally{m.end()}},d=(p,y)=>{if(p.fileSize===null)return y.kind==="exact"?"verified":"unrecorded";if(y.kind==="exact"?y.bytes===p.fileSize:p.fileSize>y.maxBytes)return"verified";let m=y.kind==="exact"?String(y.bytes):`>${y.maxBytes}`;return i.warn(`size_mismatch expected=${p.fileSize} got=${m} attachment=${p.attachmentId} viewer=${p.owner} variant=thumbnail`),"unverified"},u=(p,y)=>(f,m)=>{let R=m===null?"":` message=${m.error instanceof Error?m.error.message:"unknown"}`;i.warn(`${p}_overrun ms=${f} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail${R}`)},h=(p,y)=>f=>{i.warn(`${p}_stuck ms=${f} attachment=${y.attachmentId} viewer=${y.owner} variant=thumbnail`)};return async(p,y)=>{let f=await c(p,y);if(f===null)return{kind:"failure",status:503,reason:y.aborted?"aborted":"queue"};if(typeof f!="function")return f;let m=f,R=null;try{if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let A=r.get(p.key);if(A!==void 0)return{...A,identity:"verified"};let E=mo({budgetMs:Be.readMs,flightSignal:y,call:F=>p.readAttachment(p.filePath,{maxBytes:n,head:!1,principal:o(p.owner),signal:F}),onOverrun:u("read",p),onStuck:h("read",p)}),S=await E.outcome;if(S.timedOut)return R=E.settled,y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:504,reason:"read_timeout"};if(y.aborted)return{kind:"failure",status:503,reason:"aborted"};let g=S.value;if(!g.ok&&g.reason!=="too_large")return Ur(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 C=d(p,g.ok?{kind:"exact",bytes:g.bytes.byteLength}:{kind:"over",maxBytes:n}),D=F=>{C==="verified"&&r.set(p.key,F)},_=F=>(D(F),{...F,identity:C});if(!g.ok)return _({kind:"unrenderable",reason:"too_large"});let H=po(g.bytes);if(H===null)return _({kind:"unrenderable",reason:"signature"});let w=mo({budgetMs:Be.renderMs,flightSignal:y,call:F=>p.renderer.render(g.bytes,{format:H,maxWidth:p.box.maxWidth,maxHeight:p.box.maxHeight,signal:F}),onOverrun:u("render",p),onStuck:h("render",p)}),L=F=>{if(F.kind==="error")return;let I=Ci(F.value,p.box);"entry"in I&&D(I.entry)},x=null,q=()=>(x===null&&(x=w.settled.then(L),s(p.key,x)),x);y.addEventListener("abort",q,{once:!0});let K=await w.outcome.finally(()=>y.removeEventListener("abort",q));if(K.timedOut||y.aborted)return R=q(),y.aborted?{kind:"failure",status:503,reason:"aborted"}:{kind:"failure",status:502,reason:"render_timeout"};let G=Ci(K.value,p.box);return"entry"in G?_(G.entry):G.failure}finally{R===null?m():R.then(m,m)}}};var ki=()=>{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 Ni=10,Gu=1/Ni,Li=1-Gu,Ku=1024,Ju=64,Qu=8,vi="private, no-cache",Xu="no-store",Zu=Object.freeze({verified:"",unverified:" identity=unverified",unrecorded:" size=unrecorded"}),ed=e=>{switch(e.status){case 404:case 502:case 504:return"warn";case 500:return"error";case 503:return e.reason==="aborted"?"info":"warn"}},Oi=e=>{let{service:t,encodeUserId:r,resolveViewerScope:n,logger:o,recordObjectState:a,maxBytes:i,thumbnails:l}=e,{renderer:s}=l,c=(S,g)=>ht({reason:S,limitPerWindow:g,windowMs:6e4,logger:o,windowFields:C=>`viewer=${C} variant=thumbnail`}),d=c("rate_limit",l.rateLimitPerMinute),u=c("revalidation_rate_limit",l.rateLimitPerMinute*Ni),h=lt({limit:l.concurrency,maxHeldPerOwner:l.concurrency,queue:{max:Ju,maxPerOwner:Qu,maxWaitMs:Be.queueWaitMs}}),p=xi({maxBytes:l.cacheBytes,maxEntries:Ku}),y=ki(),f=Pi({gate:h,cache:p,maxBytes:i,encodeUserId:r,recordObjectState:a,logger:o}),m=(S,g,C,D)=>{let _=`attachment=${S.attachmentId} viewer=${S.internalUserId} variant=thumbnail cache=${D}`;if(g.kind==="failure")return o[ed(g)](`${g.status} ${_} reason=${g.reason} code=${g.code??"-"}`),S.fail(g.status,Rt[g.status],Te(g.status));let H=Zu[g.identity];if(g.kind==="unrenderable")return o.info(`404 ${_} reason=${g.reason}${H}`),S.fail(404,Rt[404]);let w=g.identity==="verified"?{"Cache-Control":vi,ETag:C}:{"Cache-Control":Xu},L=new Headers({"Content-Type":g.contentType,"Content-Length":String(g.bytes.byteLength),...w,"Content-Security-Policy":"default-src 'none'; sandbox",...Yt});return S.cookie&&L.append("Set-Cookie",S.cookie),o.info(`200 ${_} type=${g.contentType} bytes=${g.bytes.byteLength}${H}`),new Response(g.bytes,{status:200,headers:L})},R=(S,g)=>{let C=S.spend(g.internalUserId,`attachment=${g.attachmentId} viewer=${g.internalUserId} variant=thumbnail`);return C===null?null:g.fail(C.status,C.message,C.headers)},A=S=>R(d,S),E=(S,g)=>g?R(u,S):A(S);return async(S,g)=>{let{request:C,attachmentId:D,internalUserId:_,readAttachment:H,cookie:w,fail:L}=S,x=Qn[g],q=C.headers.get("If-None-Match"),K=q!==null,G=E(S,K);if(G)return G;let F=await n(C,"initial");if(!F.ok)return L(503,Rt[503],Te(503));let I=await t.getAttachmentForUser(F.scope,D,_),W=I!==null&&Vr(I,i)?Ii({rendererId:s.id,box:x,attachmentId:D,filePath:I.filePath,fileType:I.fileType,fileSize:I.fileSize}):null;if(W&&eo(q,W.etag)){let b=new Headers({"Cache-Control":vi,ETag:W.etag,...Yt});return w&&b.append("Set-Cookie",w),o.info(`304 attachment=${D} viewer=${_} variant=thumbnail cache=revalidated`),new Response(null,{status:304,headers:b})}if(K){let b=A(S);if(b)return b}if(!I)return o.warn(`404 attachment=${D} viewer=${_} variant=thumbnail reason=not_visible`),L(404,Rt[404]);if(!W)return d.refund(_,Li),o.info(`404 attachment=${D} viewer=${_} variant=thumbnail reason=not_eligible`),L(404,Rt[404]);let{key:ce,etag:ne}=W,de=p.get(ce);if(de)return d.refund(_,Li),m(S,{...de,identity:"verified"},ne,"hit");let Re=b=>f({key:ce,attachmentId:D,filePath:I.filePath,fileSize:I.fileSize,box:x,owner:_,readAttachment:H,renderer:s},b),J;try{J=await y.join(ce,C.signal,Re)}catch(b){return o.error(`500 attachment=${D} viewer=${_} variant=thumbnail cache=miss reason=port_exception message=${b instanceof Error?b.message:"unknown"}`),L(500,Rt[500])}return m(S,J,ne,"miss")}};var td='[daily-report] params.token must be passed by the route that mounts attachment.loader; declare a "token" route parameter ({apiBasePath}/attachment/{token})',rd=()=>$r(403,oo,{cookie:null}),Hi=Object.freeze({route:"attachment",navigable:e=>{let{kind:t}=Xn(new URL(e.url).searchParams);return t==="inline"||t==="download"},frameworkDataRefusal:()=>$r(404,hr[404],{cookie:null}),crossSiteRejection:rd}),Fi=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:Xa(r,a)},s=i===null?null:{idCodec:i.idCodec,read:i.read,serveOriginal:oi({...l,maxBytes:i.maxBytes,rateLimitPerMinute:i.rateLimitPerMinute,concurrency:i.concurrency}),serveThumbnail:i.thumbnails===null?null:Oi({...l,maxBytes:i.maxBytes,thumbnails:i.thumbnails})};return async({request:c,params:d})=>{let u=null,h=(p,y,f={})=>$r(p,y,{cookie:u,extraHeaders:f});try{let{user:p,cookie:y}=await t(c,{failureRedirect:null});if(u=y??null,!p)return h(401,"Unauthorized");let f=Xn(new URL(c.url).searchParams);if(f.kind==="invalid")return h(400,"Invalid attachment request");if(f.kind==="thumbnail"&&c.method!=="GET")return h(405,"Method not allowed",{Allow:"GET"});if(c.method!=="GET"&&c.method!=="HEAD")return h(405,"Method not allowed",{Allow:"GET, HEAD"});if(s===null)return h(404,"Attachment not found");if(d.token===void 0)throw new Error(td);let m=s.idCodec.decode(d.token);if(m===null||!at(m))return h(400,"Invalid attachment token");let R=await r.getUserIdByExternalId(p.id);if(!R)return h(403,"Forbidden");let A={request:c,delivery:f,attachmentId:m,internalUserId:R,readAttachment:s.read,cookie:u,fail:h};return f.kind!=="thumbnail"?await s.serveOriginal(A):s.serveThumbnail===null?h(404,Rt[404]):await s.serveThumbnail(A,f.variant)}catch(p){if(p instanceof Response)throw p;return a.error(`500 attachment=? viewer=? reason=unexpected message=${p instanceof Error?p.message:"unknown"}`),h(500,yt)}}};var nd=32*1024*1024,od=60,ad=4,id=120,sd=2,ld=8*1024*1024,qr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cd=e=>{if(e===void 0)throw We("attachments.thumbnails.renderer","injected when attachments.thumbnails is given");if(!qr(e))throw Q("attachments.thumbnails.renderer","an object with id and render",e);if(e.render===void 0)throw We("attachments.thumbnails.renderer.render","a function");if(typeof e.render!="function")throw Q("attachments.thumbnails.renderer.render","a function",e.render);if(typeof e.id!="string"||e.id.trim()==="")throw Q("attachments.thumbnails.renderer.id","a non-blank string naming the rendering pipeline version",e.id);return e},ud=e=>{if(e===void 0)return null;if(!qr(e))throw Q("attachments.thumbnails","an object with renderer",e);return Object.freeze({renderer:cd(e.renderer),rateLimitPerMinute:ve("attachments.thumbnails.rateLimitPerMinute",e.rateLimitPerMinute,1,id),concurrency:ve("attachments.thumbnails.concurrency",e.concurrency,1,sd),cacheBytes:ve("attachments.thumbnails.cacheBytes",e.cacheBytes,0,ld)})},$i=e=>{let t=e;if(t===void 0)return null;if(!qr(t))throw Q("attachments","an object with idCodec and read",t);let{idCodec:r,read:n}=t;if(r===void 0)throw We("attachments.idCodec","injected when attachments is given");if(!qr(r)||typeof r.encode!="function"||typeof r.decode!="function")throw Q("attachments.idCodec","an object with encode and decode functions",r);if(n===void 0)throw We("attachments.read","injected when attachments is given");if(typeof n!="function")throw Q("attachments.read","a function",n);return Object.freeze({idCodec:r,read:n,maxBytes:ve("attachments.maxBytes",t.maxBytes,1,nd),rateLimitPerMinute:ve("attachments.rateLimitPerMinute",t.rateLimitPerMinute,1,od),concurrency:ve("attachments.concurrency",t.concurrency,1,ad),thumbnails:ud(t.thumbnails)})},dd=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"]]),jr=e=>{for(let[t,r]of dd)if(Object.hasOwn(e,t))throw We(r,`given in place of the flat key ${t}`)};var Bi=8,pd=8*Bi,md=128,yd=2,Vi=yd*md,hd=4*Vi,fd=6e4,Rd=6e4,Sd="Too many reads",Ui=Object.freeze(Object.keys(Ot).filter(e=>Ot[e].admission.includes("miss-gate"))),qi=e=>{let t=lt({limit:pd,maxHeldPerOwner:Bi,queue:{max:hd,maxPerOwner:Vi,maxWaitMs:fd}}),r=Ce({windowMs:Rd,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:Sd}},503);for(let[o,a]of Object.entries(Te(503)))n.headers.set(o,a);return n};var ji=e=>{let t=e.get(ge.cursorReportHubId),r=e.get(ge.cursorBusinessDate),n=e.get(ge.cursorSnapshot),o=Da(n)?n:null,a=null;if(t!==null){let l=Qe(t);if(l===null)return{refused:"cursor"};let s={businessDate:r,reportHubId:l};if(!ba(s))return{refused:"cursor"};a=s}else if(r!==null)return{refused:"cursor"};let i=mr(e.get(ge.forceRefresh));return i===null?{refused:"forceRefresh"}:{query:{cursor:a,snapshot:o,forceRefresh:i}}};var Yr=e=>e.method==="HEAD"?AbortSignal.abort():e.signal,gd=2,bd=16,Dd=gd*bd,Ad=6e4,Wi=()=>{},Td=(e,t)=>{if(e.aborted)return t(),t;let r=()=>{e.removeEventListener("abort",r),t()};return e.addEventListener("abort",r,{once:!0}),r},Yi=e=>{let t=lt({limit:Number.MAX_SAFE_INTEGER,maxHeldPerOwner:Dd,queue:null}),r=Ce({windowMs:Ad,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 Wi;if(a.aborted){if(t.canAcquire(n))return Wi}else{let i=await t.acquire(n,a);if(i!==null)return Td(a,i)}return r.record(n,o,()=>e.warn(`503 ${o} viewer=${n} reason=streams_per_viewer`)),null}}};var zr=30,Qi=4e3,Ed="stream interrupted by server error",wd="Too many streams",Id=15e3,Xi=Symbol("ids-stream-heartbeat"),zi=()=>{},Gi=e=>e.return(void 0).then(zi,zi),_d=()=>{let e;return{fired:new Promise(r=>{e=setTimeout(()=>r(Xi),Id)}),stop:()=>clearTimeout(e)}};async function*Ki(e,t,r,n){let o=t?Ea(e,t):0,a=!0;for(;;){let i=Math.min(o+(a?r:Qi),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 Zi=e=>{let t=new Headers({"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"private, no-cache, no-transform",...st});return e&&t.append("Set-Cookie",e),t},Ji=(e,t,r,n,o)=>{let a=async(d,u)=>{o(),u&&await Gi(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=_d();try{s===null&&(s=t.next());let h=await Promise.race([s,u.fired]);if(u.stop(),h===Xi){if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`
|
|
2
2
|
`));return}s=null;let{value:p,done:y}=h;if(y){await a(d,!1);return}if(l||r.aborted){await a(d,!0);return}d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
3
|
-
`))}catch(h){if(u.stop(),s=null,o(),l||r.aborted)return;h instanceof
|
|
4
|
-
`)),d.close()}catch{}}},cancel(){l=!0,o(),Gi(t)}});return new Response(c,{status:200,headers:Zi(e)})},es=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,h,p)=>{let y=!1,f=null,m=null,R=new Promise((S,g)=>{f=S,m=g});R.catch(()=>{});let
|
|
5
|
-
`,fo=4e3,
|
|
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`],up=["","\u30A2","\u4F50"," "],dp=()=>JSON.stringify(cp.map(e=>en(e,8))),pp=e=>`dr-search-v${Vd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var mp=async()=>{let e=Ld("sha256");e.update(JSON.stringify(Qr));for(let t of up)await is(),e.update("\0"),e.update(Ro(lp(t)));return await is(),e.update("\0"),e.update(dp()),pp(e.digest("hex"))},yp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Ao=yp(mp);var fp=/^-+/u,Rp=/\s+/u,bs=e=>{let t=fp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},Sp=(e,t)=>{let r=[...bs(e).map(n=>({text:n,tier:Nt.word})),...t.flatMap(n=>bs(n).map(o=>({text:o,tier:Nt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},gp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),tn=(e,t)=>{if(e.length>xe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of hp(Zr(e),t).sets){let i=[],l=new Set;for(let c of a.split(Rp)){let d=Jr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>xe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=Sp(d,ms(c)),h=gp(u);l.has(h)||(l.add(h),i.push({alternatives:u}))}if(i.length>xe.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>xe.maxSets?{ok:!1,reason:"too-many-sets"}:o>xe.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 jR=Object.freeze({sourceTypes:null,authors:null,customers:null}),bp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,Ds=(e,t,r)=>{if(ka(e)&&bp(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 As=6e4,Dp=1,Ap=3200,Ts=2e3,Tp=Object.freeze({search:Ap,reports:Ts,"search-marks":Ts,"search-facets":null}),Ep=(e,t)=>{let r=Tp[e];return r===null?null:{max:t,maxPerOwner:Or,maxWaitMs:r}},br=e=>{let{concurrency:t,route:r,logger:n}=e,o=ht({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:As,logger:n,windowFields:()=>`route=${r}`}),a=lt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:Ep(r,t)}),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(Dp)})}),l=Ce({windowMs:As,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 Lp}from"@aiquants/sse";import{createSseResponse as vp,readLastEventId as Np,startSseHeartbeat as Op,terminalStreamResponse as Hp}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}},Es=new WeakMap,ws=(e,t,r)=>{let n=Es.get(e);n===void 0&&(n=new Map,Es.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,wp=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)}}},Ip=(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})},Is=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return ws(e,"every-viewer",()=>JSON.stringify(wp(n)));let o=n.actorRawUserId===t;return ws(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(Ip(n,o,r)))};import{systemSseRuntime as _p}from"@aiquants/sse";import{createSharedSource as xp}from"@aiquants/sse/shared-source";var wt="daily-report:ids:",Eo=(e,t)=>`${e}st:${t}`,wo=e=>`${wt}user:${e}:`,_s=(e,t)=>Eo(wo(e),t),Jt=e=>`daily-report:date:${e}:user:`,Qt=(e,t)=>`${Jt(e)}${t}:`,xs=(e,t,r)=>Eo(Qt(e,t),r),Ye=e=>`daily-report:detail:${e}:user:`,Io=(e,t)=>`${Ye(e)}${t}:`,Cs=(e,t,r)=>Eo(Io(e,t),r);var St=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Cp=5e3,Mp=Hr,Ar=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=be(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:Tt}_createSource(){return xp({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:_p,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:Cp,COUNT:Mp});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(wt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(Ye(n))}};var Pp=6e4,Tr="Report visibility is unavailable",Ms=["initial","refresh"],Ps=Object.freeze({ok:!1}),kp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,ks=(e,t)=>{let r=Ce({windowMs:Pp,tallies:Ms,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Ms.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)),Ps}let i=os(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${kp(a)}`)),Ps):{ok:!0,scope:i}}},Ls=(e,t,r)=>{let n=e(t,r,{error:{message:Tr}},503);for(let[o,a]of Object.entries(Te(503)))n.headers.set(o,a);return n};var Ns=Object.freeze({...yr,route:"sse",frameworkDataRefusal:Fr}),vs=864e5,Fp={baseMs:2e3,jitterMs:8e3},Os=6e4,_o=Hr,Hs=JSON.stringify({type:"connected"}),$p=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},Up=(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 we(t,e.report.sourceType);case"comment-add":case"comment-delete":return we(r,e.sourceType);case"report-delete":return we(t,e.sourceType)}},Bp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!we(t,e.report.sourceType),Vp=(e,t)=>{e.writeEvent({event:null,id:t,data:Hs})},qp=(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||!Up(o,r.visibleSet,r.commentableSet)){Vp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Is(n,r.internalUserId,Bp(o,r.commentableSet))})},Fs=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:h,internalUserId:p,cursor:y}=u,f=u.initialScope.visible,m=u.initialScope.commentable,R=0,T=setInterval(()=>{let x=++R;n(h,"refresh").then(q=>{if(x===R){if(!q.ok){d.close();return}f=q.scope.visible,m=q.scope.commentable}})},Os);d.onClose(()=>clearInterval(T));let E=y===null?Tt:y,S=y!==null&&o!==void 0,g=[],C=null,A=x=>{St(x.id,E)||(E=x.id,qp(d,x,{internalUserId:p,visibleSet:f,commentableSet:m}))},_=async(x,q)=>{let[K]=await x.xRange(i,"-","+",{COUNT:1});return K!==void 0&&!St(K.id,q)},H=async(x,q)=>{let[K]=await x.xRange(i,"-","+",{COUNT:1});if(K===void 0)return!0;let z;if(q===Tt){if($p(await x.xInfoStream(i))>0)return!1;z=K.id}else{if(!St(K.id,q))return!1;z=q}for(;;){let F=await x.xRange(i,z,"+",{COUNT:_o}),I=F[0];if(I!==void 0&&I.id!==z&&await _(x,z))return!1;for(let j of F){if(C!==null&&St(C,j.id))return!0;St(j.id,E)||A(Dr(j,s).entry)}let $=F.at(-1);if(F.length<_o||$===void 0||d.isClosed())return!0;z=$.id}},w=a.subscribe(x=>{if(!S){A(x);return}St(x.id,E)||(C===null&&(C=x.id),g.push(x))},x=>{s.error(`[SSE:${p}] Fan-Out reader error:`,x),d.close()});if(d.onClose(w),y===null){await a.ready();try{let x=await o?.getClient();if(x){let q=await x.xRevRange(i,"+","-",{COUNT:1});q.length>0&&!St(q[0].id,E)&&(E=q[0].id)}}catch{}}if(d.writeEvent({event:null,id:E===Tt?null:E,data:Hs}),Op(d,{intervalMs:pa,retry:Fp,runtime:Lp}),y===null||o===void 0)return;await a.ready();let k=await o.getClient();if(k===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await H(k,y)){d.writeRetry(vs),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}S=!1;for(let x of g.splice(0))A(x)};return async({request:d,params:u})=>{let h,p=()=>{let f=new Headers;h!==void 0&&f.append("Set-Cookie",h);for(let[m,R]of Object.entries(st))f.set(m,R);return f},y=f=>Hp(f,{data:"",retryMs:vs,headers:p()});try{let f=await t(d,{failureRedirect:null});h=f.cookie;let{user:m}=f;if(!m)return y("auth-required");let R=await r.getUserIdByExternalId(m.id);if(!R)return y("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let T=Np(d,ma);if(T!==null&&!ya(T))return s.warn(`[SSE:${R}] malformed resume cursor; asking the client to resync`),y("resync-required");let E=Yr(d),S=await l.admit(R,"sse",E);if(S===null){let C=p();for(let[A,_]of Object.entries(Te(503)))C.set(A,_);return new Response("Too many streams",{status:503,headers:C})}let g=!1;try{let C=await n(d,"initial");if(!C.ok){let _=p();for(let[H,w]of Object.entries(Te(503)))_.set(H,w);return new Response(Tr,{status:503,headers:_})}let A=C.scope;return vp({requestSignal:E,headers:p(),onError:(_,H)=>s.error(`[SSE:${R}] ${H} failed:`,_),produce:_=>(g=!0,_.onClose(S),c(_,{request:d,internalUserId:R,cursor:T,initialScope:A}))})}finally{g||S()}}catch(f){if(f instanceof Response)throw f;let m=f instanceof Error?f:new Error(String(f));return s.error(`500 sse name=${m.name} message=${m.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var $s=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...st});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Wp=Object.freeze({...yr,route:"api",frameworkDataRefusal:({params:e})=>Jn(e.endpoint)&&Ot[e.endpoint].body==="stream"?Fr():null}),Yp=Object.freeze({...yr,route:"action"}),zp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),js=6e4,Ws=5,Gp=Ws*Math.ceil(js/500),Kp=2,Jp=6,Qp=6e4,Xp=Ws*Kp*Jp,Zp=2,em=10,tm=2,rm=10,Us=(e,t)=>Math.max(e,Or)*t,Ys=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},nm=Object.freeze({etag:(e,t,r)=>za(e,t,r,200),"no-store":(e,t,r)=>to(t,r,200)}),om=e=>ro(e.body==="json"?nm[e.cache]:null),Bs=ro(null),Vs=(e,t,r,n)=>Ys(e(t,r,{error:{message:n.message}},n.status),n.headers),qs=(e,t,r)=>Ys(e(t,r,null,503),Te(503));function xo(e){jr(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 Q("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=be(e.logger,3,"API"),d=be(e.logger,3,"Visibility"),u=ks(rr("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),h=be(e.logger,1,"SSE"),p=be(e.logger,1,"Attachment"),y=be(e.logger,2,"Isolation"),f=be(e.logger,2,"Action"),m=be(e.logger,2,"Search"),R=be(e.logger,2,"Refresh"),T=be(e.logger,2,"Streams"),E=be(e.logger,2,"Reads"),S=ht({reason:"refresh_rate_limit",limitPerWindow:Xp,windowMs:Qp,logger:R,windowFields:()=>"route=api"}),g=Yi(T),C=qi(E),A=async(b,v,L,P,O,W)=>{let X=await r.getUserIdByExternalId(v.id);try{return await W(X===null?void 0:C.admissionFor(X,b,L.signal))}catch(Y){if(Y instanceof Ke)return Wr(O,L,P);throw Y}},_=(b,v,L,P,O)=>{let W=S.spend(v.id,`endpoint=${b}`);return W===null?null:Vs(O,L,P,W)},H=async({request:b})=>{let{user:v,cookie:L}=await t(b,{failureRedirect:s}),P=new Headers;L&&P.append("Set-Cookie",L);let O=await r.getUserIdByExternalId(v.id),W=O?n(O):null;return{data:{user:v,userId:W},headers:P}},w=b=>{let{limiter:v}=b;return async(L,P,O,W,X,Y)=>{if(v===null)return Y(O,P,{error:{message:"Unknown endpoint"}},404);let M=b.parse(L);if(!M.ok)return Y(O,P,M.invalid,400);let D=await r.getUserIdByExternalId(W.id);if(!D)return Y(O,P,b.emptyAnswer(M.parsed),200);let{signal:N}=O,U=await v.admit(D,N);if("refusal"in U)return N.aborted?qs(Y,O,P):Vs(Y,O,P,U.refusal);try{N.throwIfAborted();let G=await b.read(M.parsed,{userId:D,user:W,scope:X},N);return N.throwIfAborted(),Y(O,P,G,200)}catch(G){if(N.aborted&&G===N.reason)return qs(Y,O,P);throw G}finally{U.release()}}},k=r.searchLimits===null?null:br({...r.searchLimits,route:le.search,logger:m}),x=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,Zp),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*em,route:le.reports,logger:m}),q=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,tm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*rm,route:le.searchMarks,logger:m}),K=r.searchLimits===null?null:br({...r.searchLimits,route:le.searchFacets,logger:m}),z={[le.businessDate]:async(b,v,L,P,O,W)=>{let X=b.searchParams.get(ge.businessDate),Y=X===null?null:Vt(X);if(Y===null)return W(L,v,{error:{message:"Invalid business date"}},400);let M=mr(b.searchParams.get(ge.forceRefresh));if(M===null)return W(L,v,{error:{message:"Invalid forceRefresh"}},400);let D=M?_(le.businessDate,P,L,v,W):null;return D!==null?D:A(le.businessDate,P,L,v,W,async N=>{let U=await r.getDailyReportsByBusinessDateByExternalId(O,Y,P.id,{forceRefresh:M,admission:N});return W(L,v,{businessDate:Y,reports:U},200)})},[le.idsStream]:es({service:r,logger:c,streamSlots:g,missGate:C,refuseForcedRead:(b,v,L,P)=>_(le.idsStream,b,v,L,P)}),[le.report]:async(b,v,L,P,O,W)=>{let X=Je(b.searchParams.get(ge.reportHubId));if(X===null)return W(L,v,{error:{message:"Invalid reportHubId"}},400);let Y=mr(b.searchParams.get(ge.forceRefresh));if(Y===null)return W(L,v,{error:{message:"Invalid forceRefresh"}},400);let M=Y?_(le.report,P,L,v,W):null;return M!==null?M:A(le.report,P,L,v,W,async D=>{let N=await r.getDailyReportDetailByIdByExternalId(O,X,P.id,{snapshot:!0,forceRefresh:Y,admission:D});return N?W(L,v,{report:N},200):W(L,v,{error:{message:"Report not found"}},404)})},[le.search]:w({limiter:k,parse:b=>{let v=b.searchParams.get(ge.searchQuery),L=Gn(b.searchParams.get(ge.searchCombine));if(v===null||L===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=va(b.searchParams,r.searchFilterSourceTypes);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:P.reason}}};let O=Ds(v,L,P.filters);if(!O.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:O.reason}}};let{criteria:W}=O;return{ok:!0,parsed:{criteria:W,words:W.plan===null?[]:gr(W.plan)}}},emptyAnswer:({words:b})=>Wn([],b),read:async({criteria:b,words:v},{userId:L,scope:P})=>Wn(await r.searchDailyReports(P,L,b),v)}),[le.reports]:w({limiter:x,parse:b=>{let v=Kn(b.searchParams.get(ge.reportIds));return v===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:v}},emptyAnswer:b=>({outcomes:b.map(pr)}),read:async(b,{user:v,scope:L},P)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(L,b,v.id,{signal:P})})}),[le.searchMarks]:w({limiter:q,parse:b=>{let v=b.searchParams.get(ge.searchQuery),L=Gn(b.searchParams.get(ge.searchCombine));if(v===null||L===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let P=tn(v,L);if(!P.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:P.reason}}};let O=Kn(b.searchParams.get(ge.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:P.plan,ids:O}}},emptyAnswer:({plan:b})=>({wordsDigest:Nr(gr(b)),reports:[],deferred:[]}),read:({plan:b,ids:v},{userId:L,scope:P},O)=>r.markDailyReportSearchHits(P,L,b,v,{signal:O})}),[le.searchFacets]:w({limiter:K,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:v,scope:L})=>r.listDailyReportSearchFacets(L,v)})},F=async({request:b,params:v})=>{let{user:L,cookie:P}=await t(b,{failureRedirect:null}),O=P??null;if(!L)return Bs(b,O,{error:{message:"Unauthorized"}},401);let W=v.endpoint;if(!Jn(W))return Bs(b,O,{error:{message:"Unknown endpoint"}},404);let X=Ot[W],Y=om(X),M=ja[X.body];if(!M.includes(b.method)){let N=Y(b,O,{error:{message:"Method not allowed"}},405);return N.headers.set("Allow",M.join(", ")),N}let D=se();try{let N=new URL(b.url),U=await u(b,"initial"),G=U.ok?await z[W](N,O,b,L,U.scope,Y):Ls(Y,b,O);return X.body==="json"&&c.debug(G.headers.has("ETag")?`${G.status} endpoint=${W} etag_match=${G.status===304}`:`${G.status} endpoint=${W}`),G}catch(N){let U=se()-D,G=N instanceof Error?N:new Error(String(N));return c.error(`500 endpoint=${W} elapsed=${U}ms name=${G.name} code=${"code"in G?G.code:"N/A"} message=${G.message}`,G),Y(b,O,{error:{message:"Internal Server Error"}},500)}},I=qa(f),$=ht({reason:"rate_limit",limitPerWindow:Gp,windowMs:js,logger:f,windowFields:()=>"route=action"}),j=async(b,v,L,P,O)=>{let{clientTempId:W}=b;if(b.intent==="create")try{let D=await r.createDailyReport(L,v,b.businessDate,W);return O(b,D.reportHubId,{report:D})}catch(D){if(D instanceof Error&&D.message==="Forbidden")return P({error:"Creating reports is restricted"},{status:403});throw D}let{reportHubId:X,businessDate:Y}=b,M=async(D,N)=>{try{let U=await N(D.value);return O(D,X,{updatedStatus:{isStarred:U.isStarred,isRead:U.isRead},operationTimestamp:D.operationTimestamp})}catch(U){if(U instanceof Error&&U.message==="Not Found")return P({error:"Report not found"},{status:404});throw U}};switch(b.intent){case"update":try{return await r.updateDailyReport(L,X,v,b.changes,W),O(b,X,{})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Report not found"},{status:404})}throw D}case"publish":try{let D=await r.publishDailyReport(L,X,v,W);return O(b,X,{report:D})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Report not found"},{status:404})}throw D}case"delete":try{return await r.deleteDailyReport(L,X,v,W),O(b,X,{})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Report not found"},{status:404})}throw D}case"toggleStar":return await M(b,D=>r.setStarStatus(L,v,X,Y,D,W));case"toggleRead":return await M(b,D=>r.setReadStatus(L,v,X,Y,D,W));case"addComment":try{let D=await r.addComment(L,v,X,b.content,Y,W);return O(b,X,{newComment:D})}catch(D){if(D instanceof Error){if(D.message==="Not Found")return P({error:"Report not found"},{status:404});if(D.message.startsWith("Comments are restricted"))return P({error:"Comments are restricted for this report"},{status:403})}throw D}case"deleteComment":try{return await r.deleteComment(L,v,X,b.commentId,Y,W),O(b,X,{deletedCommentId:b.commentId})}catch(D){if(D instanceof Error){if(D.message==="Unauthorized")return P({error:"Unauthorized"},{status:403});if(D.message==="Not Found")return P({error:"Comment not found"},{status:404})}throw D}}},ce=async({request:b,params:v})=>{let{user:L,cookie:P}=await t(b,{failureRedirect:null}),O=(Y,M)=>$s(Y,{...M,setCookie:P}),W=(Y,M,D)=>$s(zp(Y,M,D),{setCookie:P});if(!L)return O({error:"Unauthorized"},{status:401});let X=se();try{if(v.endpoint!==le.action)return O({error:"Unknown endpoint"},{status:404});let Y=$.spend(L.id,"action");if(Y!==null)return O({error:Y.message},{status:Y.status,headers:Y.headers});let M=await Va(b,l);if("refusal"in M){let{refusal:G}=M;return G.status===413&&I(G.measuredBy),O({error:G.error},{status:G.status})}let{command:D}=M;if(D.intent==="clearCache"&&!e.enableDevCacheClear)return O({error:"Invalid intent"},{status:400});let N=await u(b,"initial");if(!N.ok)return O({error:Tr},{status:503,headers:{...Te(503),"Cache-Control":"no-store"}});let U=await r.getUserIdByExternalId(L.id);return U?D.intent==="clearCache"?(await r.clearCache(),O({status:"OK",intent:"clearCache"})):await j(D,U,N.scope,O,W):O({error:"User not found"},{status:404})}catch(Y){if(Y instanceof Response)throw Y;let M=se()-X,D=Y instanceof Error?Y:new Error(String(Y));return c.error(`500 action elapsed=${M}ms name=${D.name} message=${D.message}`,D),O({error:"Internal Server Error"},{status:500})}},ne=Fs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),de=Fi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),Re=Qa(y),J=(b,v)=>async L=>{let P=Ja(L.request)?b.frameworkDataRefusal(L):null;if(P!==null)throw P;let O=jp(L.request,b);return O===void 0?v(L):(Re(b.route,O,L.request),b.crossSiteRejection())};return{index:{loader:H},api:{loader:J(Wp,F),action:J(Yp,ce)},sse:{loader:J(Ns,ne)},attachment:{loader:J(Hi,de)}}}import{chunk as oy,MAX_IN_LIST as ay,runWithTransactionRetry as iy}from"@aiquants/mssql";import{asc as bt,eq as fn,inArray as Rn}from"drizzle-orm";var am=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],im=["document","comment"],sm=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],lm=["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},zs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw En(e,n,r)},Gs=(e,t,r)=>{if(typeof t!="object"||t===null)throw Q(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Q(`${e}.${o}`,"a column",n[o])},Ks=(e,t)=>{if(!Co(e))throw Q("search","a plain object",e);zs("search key",e,am);let{tables:r}=e;if(!Co(r))throw Q("search.tables","a plain object with document and comment",r);zs("search.tables key",r,im),Gs("search.tables.document",r.document,sm),Gs("search.tables.comment",r.comment,lm);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Co(e.externalSourceTexts))throw Q("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 Q(`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 It=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"?Je(e):typeof e=="number"&&at(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 B}from"drizzle-orm";import{sql as _t}from"drizzle-orm";var Js=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 _t.join(e.map(t=>_t`${t}`),_t`, `)},nn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return _t`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Js(t)}))`},Qs=(e,t)=>{let{hubLabel:r,label:n}=e;return _t`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Js(t)}))`},on=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?_t`${o.userId} = ${t} OR ${o.userId} IS NULL`:_t`${o.userId} = ${t}`;return _t`(${a} OR NOT ${nn(e,r)})`};var cm=/[[%_]/gu,um=e=>e.replace(cm,t=>`[${t}]`),Xs=e=>`%${um(e)}%`;var et=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),$t=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),wr=Object.freeze({value:"value"}),Me=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),V=e=>B`${B.identifier(e.name)}`,Er=e=>B.join(e.map(t=>B`${t}`),B`, `),Zs=(e,t)=>B`SELECT ${V(e.id)} AS ${B.identifier(Me.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Er(t)}) ORDER BY ${e.id}`,dm=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Xs(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),s=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),c=Sr(n.sourceType,r.scope.commentable),d=c===void 0?B``:B` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},el=(e,t,r)=>B`(${B.join(t.words.map(n=>dm(e,n,r)),B` AND `)})`,Mo=(e,t,r,n)=>{let{hub:o}=e,a=[B`${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(B`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},pm=(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(B`LOWER(${r.sourceType}) IN (${Er([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${Er(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${Er(t.customers)})`),o},tl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Mo(e,r,n,o),...pm(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B` AND `:B` OR `;s.push(B`(${B.join(l.sets.map(d=>el(e,d,r)),c)})`)}return B`SELECT ${V(a.id)} AS ${B.identifier(et.reportHubId)}, CONVERT(char(10), ${V(a.businessDate)}, 23) AS ${B.identifier(et.businessDate)}, ${V(a.sourceType)} AS ${B.identifier(et.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(s,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},rl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((s,c)=>B`(CASE WHEN ${el(e,s,r)} THEN ${2**c} ELSE 0 END)`),B` + `);return B`SELECT ${V(a.id)} AS ${B.identifier($t.reportHubId)}, ${l} AS ${B.identifier($t.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(Mo(e,r,n,o),B` AND `)}`},nl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Mo(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(wr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},ol=(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 B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${V(n.hubId)} bigint, ${V(n.searchText)} nvarchar(max), ${V(n.sourceDigest)} char(64), ${V(n.normalizerVersion)} varchar(64), ${V(n.authorName)} nvarchar(max), ${V(n.customerName)} nvarchar(max))) AS s ON t.${V(n.hubId)} = s.${V(n.hubId)}
|
|
3
|
+
`))}catch(h){if(u.stop(),s=null,o(),l||r.aborted)return;h instanceof Je||n.error(`ids-stream emission failed: ${h instanceof Error?h.message:String(h)}`);try{let p={kind:"error",error:Ed};d.enqueue(i.encode(`${JSON.stringify(p)}
|
|
4
|
+
`)),d.close()}catch{}}},cancel(){l=!0,o(),Gi(t)}});return new Response(c,{status:200,headers:Zi(e)})},es=e=>{let{service:t,logger:r,streamSlots:n,missGate:o,refuseForcedRead:a}=e,i=async(l,s,c,d,u,h,p)=>{let y=!1,f=null,m=null,R=new Promise((S,g)=>{f=S,m=g});R.catch(()=>{});let A=t.getDailyReportIdsByExternalId(c,s.id,{forceRefresh:l.forceRefresh,admission:p,onFetchStart:l.cursor?void 0:()=>{y=!0,t.readSseStreamAnchor().then(S=>t.getDailyReportIdsFirstPageByExternalId(c,s.id,zr).then(g=>({items:g,streamAnchor:S}))).then(S=>f?.(S),S=>m?.(S))}});if(A.catch(()=>{}),l.cursor){let{items:S,streamAnchor:g,snapshot:C}=await A,D=l.snapshot!==null&&l.snapshot===C;return Ji(d,Ki(S,D?l.cursor:null,zr,{snapshot:C,restarted:!D,streamAnchor:g}),u,r,h)}let E=(async function*(){let S=await Promise.race([A.then(D=>({kind:"full",source:D}),D=>({kind:"full-error",error:D})),R.then(D=>({kind:"page",page:D}),()=>({kind:"page-error"}))]),g=null,C=!1;if(S.kind==="full")g=S.source;else if(S.kind==="page"){let{items:D,streamAnchor:_}=S.page;if(D.length<zr){yield{kind:"chunk",...Wt(D,0,D.length),nextCursor:null,isLast:!0,total:D.length,streamAnchor:_};return}yield{kind:"chunk",...Wt(D,0,D.length),nextCursor:null,isLast:!1,provisional:!0},C=!0}else if(S.kind==="full-error"&&y){let D=await R.catch(()=>null);D&&D.items.length>0&&(yield{kind:"chunk",...Wt(D.items,0,D.items.length),nextCursor:null,isLast:!1,provisional:!0})}g===null&&(g=await A),yield*Ki(g.items,null,C?Qi:zr,{snapshot:g.snapshot,streamAnchor:g.streamAnchor})})();return Ji(d,E,u,r,h)};return async(l,s,c,d,u,h)=>{let p=ji(l.searchParams);if("refused"in p)return h(c,s,{error:{message:p.refused==="cursor"?"Invalid cursor":"Invalid forceRefresh"}},400);let{query:y}=p;if(y.forceRefresh){let A=a(d,c,s,h);if(A!==null)return A}let f=Yr(c),m=await t.getUserIdByExternalId(d.id),R=await n.admit(m,"ids-stream",f);if(R===null){let A=h(c,s,{error:{message:wd}},503);for(let[E,S]of Object.entries(Te(503)))A.headers.set(E,S);return A}if(f.aborted)return new Response(null,{status:200,headers:Zi(s)});try{return await i(y,d,u,s,f,R,m===null?void 0:o.admissionFor(m,le.idsStream,f))}catch(A){if(R(),A instanceof Je)return Wr(h,c,s);throw A}}};import{inArray as xd,sql as Gr}from"drizzle-orm";var Ve="Internal",ts=e=>e.trim().toLowerCase();var Cd="",Md=64,Pd=e=>e.toLowerCase(),rs=e=>{let t=new Set;if(!Array.isArray(e))return t;for(let r of e){if(typeof r!="string")continue;let n=ts(r);n.length>0&&t.add(n)}return t};function we(e,t){return e===null?!0:t==null?!1:e.has(Pd(t))}function He(e){return e!==null&&e.size===0}var kd=4e3,ho=e=>{let t=e.getSQLType();if(!t.startsWith("nvarchar("))throw Q("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,kd)};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 xd(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=rs(r?t.read:t);if(!r||t.comment===void 0)return new Rr(n,n);let o=new Set;for(let a of rs(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 Ze=Rr,yo=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Ld=new Set(["read","comment"]),os=e=>{if(yo(e))return Ze.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?Ze.unrestricted(o):null}let{read:r,comment:n}=e;return t.every(o=>Ld.has(o))&&yo(r)?n===void 0?Ze.restrictTo({read:r}):yo(n)?Ze.restrictTo({read:r,comment:n}):null:null};function Kr(e){let t=ns(e.visible),r=ns(e.commentable);return t===r?t:`d:${t.length}:${t}${r}`}function ns(e){if(e===null)return"all";if(e.size===0)return"none";let t=[...e].sort().map(n=>`${n.length}:${n}`).join(Cd);if(t.length<=Md)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 as=(e,t,r,n)=>we(n.commentable,t)||e.authorUserId===r;import{parseQuerySets as fp}from"@aiquants/fuzzy-search";import{createHash as vd}from"crypto";import{setImmediate as is}from"timers/promises";import{clusterCountOf as Nd,DEFAULT_NORMALIZE_OPTIONS as Qr,InteriorPairs as Od,isAnswerTier as Hd,normalizeText as Fd,queryNeedles as $d,resolveNormalizeOptions as Ud,toMappedFormsInto as Bd,trimmedRange as Vd}from"@aiquants/fuzzy-search/normalize";var Xr=`
|
|
5
|
+
`,fo=4e3,qd=1,us=new Set([8203,8288,65279,173]),jd=new RegExp(`[${String.fromCodePoint(...us)}]`,"gu"),ds=new RegExp(`\\r\\n|[\\n\\r${String.fromCodePoint(133,8232,8233)}]`,"gu"),ps=/(\s+)/u,Wd=/^\s+$/u,Yd=new RegExp(ps.source,"gu"),zd=/^(?:(?=\p{Lo})[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]|[A-Za-z0-9])$/u,Gd=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(jd,"");var Ro=e=>Fd(e,Qr),Jr=e=>Ro(Zr(e)),Kd=Ud({...Qr,convertRomaji:!0},"[daily-report] search reading options"),Jd=3,Qd=/^[-ー]+/u,Xd=/[^\p{L}\p{M}]/gu,Zd=/ー{2,}/gu,ep=/\p{Script=Latin}/u,ss=/(?=\p{L})\p{Script=Latin}/u,tp=e=>Nd(e.replace(Qd,"").replace(Xd,"").replace(Zd,"\u30FC")),rp=(e,t)=>{for(let r of t)if(!Hd(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})`)},ms=e=>{if(!ss.test(e))return[];let t=Jr(e);if(!ss.test(t))return[];let r=$d(t,Kd,!1);rp(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>xe.maxWordLength)&&!(a===t||ep.test(a))&&!(tp(a)<Jd||n.includes(a))&&(n.push(a),n.length===jn))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},ys=(e,t)=>{let r=e.codePointAt(t),n=t>=2&&So(e,t-1)?t-2:t-1;return zd.test(String.fromCodePoint(r))&&!Gd.has(e.codePointAt(n))},np=(e,t,r)=>{let n=[],o=0,a=0;for(;e.length-a>r;){let i=a+r;for(;i>a&&!ys(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(ps)){let c=o;if(o+=s.length,i+s.length<=t){i===0&&(a=c),i+=s.length;continue}if(l(),Wd.test(s))continue;if(s.length<=t){a=c,i=s.length;continue}let d=np(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}},op=(e,t)=>{let r=0;for(let n of e.matchAll(ds))t(e.slice(r,n.index),r),r=n.index+n[0].length;t(e.slice(r),r)},ap=(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},hs=(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=ap(Bd(d,Qr,new Od(0)),d),[h,p]=Vd(u.text);i+=u.text.slice(h,p);for(let y=h;y<p;y++)l.push(c.start+u.start[y]),s.push(c.start+u.end[y])}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 op(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}},fs=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}}},ls=4096;function*ip(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);us.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+=ls)r.push(Reflect.apply(String.fromCharCode,null,c.subarray(d-s,Math.min(o,d+ls)-s)))}i=l}return a?{text:r.join(""),rawIndex:n.subarray(0,o)}:{text:e,rawIndex:null}}var Rs=e=>{let t={units:0};return Do(t,ip(e,t))};function*sp(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(ds)){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 Ss=(e,t)=>{let r={units:0};return Do(r,sp(e,t,r))};function*cs(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,ys(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*lp(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,y,f)=>{let m=y-p;return i+m<=t?(i===0&&(a=p),i+=m,!1):(i>0&&n.push([{start:a,end:a+i}]),i=0,f?!1:m<=t?(a=p,i=m,!1):!0)},u=p=>{c&&(d(l,s,!0),l=s),c=!1,s=p},h=p=>{let y=-1;return!c&&s>l&&(d(l,s,!1)&&(y=l),l=s),c=!0,s=p,y};for(let p=0;p<e.length;){for(;r.units===0;)yield;let y=Math.min(e.length,p+r.units);r.units-=y-p;let f=p;for(let m of e.slice(p,y).matchAll(Yd)){let R=p+m.index;R>f&&u(R),f=R+m[0].length;let A=h(f);if(A>=0){let E=yield*cs(e,A,R,t,r);o+=E.forcedCuts,n.push(E.pieces)}}y>f&&u(y),p=y}if(d(l,s,c)){let p=yield*cs(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 gs=(e,t)=>{let r={units:0};return Do(r,lp(e,t,r))},cp=e=>{let t=[];for(let r=0;r<=65535;r++)r>=55296&&r<=57343||t.push(e+String.fromCharCode(r));return t.join(`
|
|
6
|
+
`)},up=[`\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`],dp=["","\u30A2","\u4F50"," "],pp=()=>JSON.stringify(up.map(e=>en(e,8))),mp=e=>`dr-search-v${qd};fz=${e.slice(0,16)};u=${process.versions.unicode};icu=${process.versions.icu}`;var yp=async()=>{let e=vd("sha256");e.update(JSON.stringify(Qr));for(let t of dp)await is(),e.update("\0"),e.update(Ro(cp(t)));return await is(),e.update("\0"),e.update(pp()),mp(e.digest("hex"))},hp=e=>{let t=null;return()=>{if(t===null){let r=e();t=r,r.catch(()=>{t=null})}return t}},Ao=hp(yp);var Rp=/^-+/u,Sp=/\s+/u,bs=e=>{let t=Rp.exec(e);return t===null?[e]:[e,"\u30FC".repeat(t[0].length)+e.slice(t[0].length)]},gp=(e,t)=>{let r=[...bs(e).map(n=>({text:n,tier:Nt.word})),...t.flatMap(n=>bs(n).map(o=>({text:o,tier:Nt.reading})))];return r.filter((n,o)=>r.findIndex(a=>a.text===n.text)===o)},bp=e=>JSON.stringify(e.map(({text:t,tier:r})=>JSON.stringify([r,t])).sort()),tn=(e,t)=>{if(e.length>xe.maxQueryLength)return{ok:!1,reason:"too-long"};let r=[],n=new Set,o=0;for(let{query:a}of fp(Zr(e),t).sets){let i=[],l=new Set;for(let c of a.split(Sp)){let d=Jr(c);if(d.length===0)return{ok:!1,reason:"blank-word"};if(d.length>xe.maxWordLength)return{ok:!1,reason:"word-too-long"};let u=gp(d,ms(c)),h=bp(u);l.has(h)||(l.add(h),i.push({alternatives:u}))}if(i.length>xe.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>xe.maxSets?{ok:!1,reason:"too-many-sets"}:o>xe.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 WR=Object.freeze({sourceTypes:null,authors:null,customers:null}),Dp=e=>e.sourceTypes!==null||e.authors!==null||e.customers!==null,Ds=(e,t,r)=>{if(ka(e)&&Dp(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 As=6e4,Ap=1,Tp=3200,Ts=2e3,Ep=Object.freeze({search:Tp,reports:Ts,"search-marks":Ts,"search-facets":null}),wp=(e,t)=>{let r=Ep[e];return r===null?null:{max:t,maxPerOwner:Or,maxWaitMs:r}},br=e=>{let{concurrency:t,route:r,logger:n}=e,o=ht({reason:"rate_limit",limitPerWindow:e.rateLimitPerMinute,windowMs:As,logger:n,windowFields:()=>`route=${r}`}),a=lt({limit:t,maxHeldPerOwner:Math.max(1,Math.floor(t/2)),queue:wp(r,t)}),i=Object.freeze({status:429,message:io,headers:Object.freeze({"Retry-After":String(Ap)})}),l=Ce({windowMs:As,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 vp}from"@aiquants/sse";import{createSseResponse as Np,readLastEventId as Op,startSseHeartbeat as Hp,terminalStreamResponse as Fp}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}},Es=new WeakMap,ws=(e,t,r)=>{let n=Es.get(e);n===void 0&&(n=new Map,Es.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,Ip=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)}}},_p=(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})},Is=(e,t,r)=>{let{parsed:n}=e;if(n.type!=="report-create"&&n.type!=="report-update"&&n.type!=="report-publish")return ws(e,"every-viewer",()=>JSON.stringify(Ip(n)));let o=n.actorRawUserId===t;return ws(e,`${o?"actor":"observer"}${r?"-comments-redacted":""}`,()=>JSON.stringify(_p(n,o,r)))};import{systemSseRuntime as xp}from"@aiquants/sse";import{createSharedSource as Cp}from"@aiquants/sse/shared-source";var wt="daily-report:ids:",Eo=(e,t)=>`${e}st:${t}`,wo=e=>`${wt}user:${e}:`,_s=(e,t)=>Eo(wo(e),t),Jt=e=>`daily-report:date:${e}:user:`,Qt=(e,t)=>`${Jt(e)}${t}:`,xs=(e,t,r)=>Eo(Qt(e,t),r),ze=e=>`daily-report:detail:${e}:user:`,Io=(e,t)=>`${ze(e)}${t}:`,Cs=(e,t,r)=>Eo(Io(e,t),r);var St=(e,t)=>{let[r,n]=e.split("-").map(Number),[o,a]=t.split("-").map(Number);return r!==o?r<o:n<=a},Mp=5e3,Pp=Hr,Ar=class{constructor(t){this.config=t;this._lastId=null;this._positioning=null;this._generation=0;this._logger=be(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:Tt}_createSource(){return Cp({start:t=>this._start(t),lingerMs:0,replay:"none",runtime:xp,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:Mp,COUNT:Pp});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(wt),(r==="comment-add"||r==="comment-delete"||r==="status-update")&&typeof n=="number"&&this.config.cache.invalidatePrefix(ze(n))}};var kp=6e4,Tr="Report visibility is unavailable",Ms=["initial","refresh"],Ps=Object.freeze({ok:!1}),Lp=e=>e===null?"null":Array.isArray(e)?"array":typeof e,ks=(e,t)=>{let r=Ce({windowMs:kp,tallies:Ms,writeSuppressed:(n,{count:o,since:a,tallies:i})=>{t.error(`visibility_unavailable_suppressed count=${o} since=${a} cause=${n} reasons=${Ms.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)),Ps}let i=os(a);return i===null?(r.record("port_contract",o,()=>t.error(`visibility unavailable cause=port_contract reason=${o} answer=${Lp(a)}`)),Ps):{ok:!0,scope:i}}},Ls=(e,t,r)=>{let n=e(t,r,{error:{message:Tr}},503);for(let[o,a]of Object.entries(Te(503)))n.headers.set(o,a);return n};var Ns=Object.freeze({...yr,route:"sse",frameworkDataRefusal:Fr}),vs=864e5,$p={baseMs:2e3,jitterMs:8e3},Os=6e4,_o=Hr,Hs=JSON.stringify({type:"connected"}),Up=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},Bp=(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 we(t,e.report.sourceType);case"comment-add":case"comment-delete":return we(r,e.sourceType);case"report-delete":return we(t,e.sourceType)}},Vp=(e,t)=>t===null||e.type!=="report-create"&&e.type!=="report-update"&&e.type!=="report-publish"?!1:!we(t,e.report.sourceType),qp=(e,t)=>{e.writeEvent({event:null,id:t,data:Hs})},jp=(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||!Bp(o,r.visibleSet,r.commentableSet)){qp(e,t.id);return}e.writeEvent({event:null,id:t.id,data:Is(n,r.internalUserId,Vp(o,r.commentableSet))})},Fs=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:h,internalUserId:p,cursor:y}=u,f=u.initialScope.visible,m=u.initialScope.commentable,R=0,A=setInterval(()=>{let x=++R;n(h,"refresh").then(q=>{if(x===R){if(!q.ok){d.close();return}f=q.scope.visible,m=q.scope.commentable}})},Os);d.onClose(()=>clearInterval(A));let E=y===null?Tt:y,S=y!==null&&o!==void 0,g=[],C=null,D=x=>{St(x.id,E)||(E=x.id,jp(d,x,{internalUserId:p,visibleSet:f,commentableSet:m}))},_=async(x,q)=>{let[K]=await x.xRange(i,"-","+",{COUNT:1});return K!==void 0&&!St(K.id,q)},H=async(x,q)=>{let[K]=await x.xRange(i,"-","+",{COUNT:1});if(K===void 0)return!0;let G;if(q===Tt){if(Up(await x.xInfoStream(i))>0)return!1;G=K.id}else{if(!St(K.id,q))return!1;G=q}for(;;){let F=await x.xRange(i,G,"+",{COUNT:_o}),I=F[0];if(I!==void 0&&I.id!==G&&await _(x,G))return!1;for(let W of F){if(C!==null&&St(C,W.id))return!0;St(W.id,E)||D(Dr(W,s).entry)}let U=F.at(-1);if(F.length<_o||U===void 0||d.isClosed())return!0;G=U.id}},w=a.subscribe(x=>{if(!S){D(x);return}St(x.id,E)||(C===null&&(C=x.id),g.push(x))},x=>{s.error(`[SSE:${p}] Fan-Out reader error:`,x),d.close()});if(d.onClose(w),y===null){await a.ready();try{let x=await o?.getClient();if(x){let q=await x.xRevRange(i,"+","-",{COUNT:1});q.length>0&&!St(q[0].id,E)&&(E=q[0].id)}}catch{}}if(d.writeEvent({event:null,id:E===Tt?null:E,data:Hs}),Hp(d,{intervalMs:pa,retry:$p,runtime:vp}),y===null||o===void 0)return;await a.ready();let L=await o.getClient();if(L===void 0)throw new Error("redis client unavailable for the SSE catch-up");if(!await H(L,y)){d.writeRetry(vs),d.writeEvent({event:"resync-required",id:null,data:""}),d.close();return}S=!1;for(let x of g.splice(0))D(x)};return async({request:d,params:u})=>{let h,p=()=>{let f=new Headers;h!==void 0&&f.append("Set-Cookie",h);for(let[m,R]of Object.entries(st))f.set(m,R);return f},y=f=>Fp(f,{data:"",retryMs:vs,headers:p()});try{let f=await t(d,{failureRedirect:null});h=f.cookie;let{user:m}=f;if(!m)return y("auth-required");let R=await r.getUserIdByExternalId(m.id);if(!R)return y("forbidden");if(u.endpoint!=="updates")return new Response("Not Found",{status:404,headers:p()});let A=Op(d,ma);if(A!==null&&!ya(A))return s.warn(`[SSE:${R}] malformed resume cursor; asking the client to resync`),y("resync-required");let E=Yr(d),S=await l.admit(R,"sse",E);if(S===null){let C=p();for(let[D,_]of Object.entries(Te(503)))C.set(D,_);return new Response("Too many streams",{status:503,headers:C})}let g=!1;try{let C=await n(d,"initial");if(!C.ok){let _=p();for(let[H,w]of Object.entries(Te(503)))_.set(H,w);return new Response(Tr,{status:503,headers:_})}let D=C.scope;return Np({requestSignal:E,headers:p(),onError:(_,H)=>s.error(`[SSE:${R}] ${H} failed:`,_),produce:_=>(g=!0,_.onClose(S),c(_,{request:d,internalUserId:R,cursor:A,initialScope:D}))})}finally{g||S()}}catch(f){if(f instanceof Response)throw f;let m=f instanceof Error?f:new Error(String(f));return s.error(`500 sse name=${m.name} message=${m.message}`),new Response("Internal Server Error",{status:500,headers:p()})}}};var $s=(e,t)=>{let r=new Headers({...t?.headers,"Content-Type":"application/json",...st});return t?.setCookie&&r.append("Set-Cookie",t.setCookie),new Response(JSON.stringify(e),{status:t?.status??200,headers:r})},Yp=Object.freeze({...yr,route:"api",frameworkDataRefusal:({params:e})=>Jn(e.endpoint)&&Ot[e.endpoint].body==="stream"?Fr():null}),zp=Object.freeze({...yr,route:"action"}),Gp=(e,t,r)=>({...r,status:"OK",intent:e.intent,reportHubId:t,clientTempId:e.clientTempId}),js=6e4,Ws=5,Kp=Ws*Math.ceil(js/500),Jp=2,Qp=6,Xp=6e4,Zp=Ws*Jp*Qp,em=2,tm=10,rm=2,nm=10,Us=(e,t)=>Math.max(e,Or)*t,Ys=(e,t)=>{for(let[r,n]of Object.entries(t))e.headers.set(r,n);return e},om=Object.freeze({etag:(e,t,r)=>za(e,t,r,200),"no-store":(e,t,r)=>to(t,r,200)}),am=e=>ro(e.body==="json"?om[e.cache]:null),Bs=ro(null),Vs=(e,t,r,n)=>Ys(e(t,r,{error:{message:n.message}},n.status),n.headers),qs=(e,t,r)=>Ys(e(t,r,null,503),Te(503));function xo(e){jr(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 Q("loginRedirectPath","the non-blank path of the host's sign-in route",s);let c=be(e.logger,3,"API"),d=be(e.logger,3,"Visibility"),u=ks(rr("resolveVisibleSourceTypes",e.resolveVisibleSourceTypes),d),h=be(e.logger,1,"SSE"),p=be(e.logger,1,"Attachment"),y=be(e.logger,2,"Isolation"),f=be(e.logger,2,"Action"),m=be(e.logger,2,"Search"),R=be(e.logger,2,"Refresh"),A=be(e.logger,2,"Streams"),E=be(e.logger,2,"Reads"),S=ht({reason:"refresh_rate_limit",limitPerWindow:Zp,windowMs:Xp,logger:R,windowFields:()=>"route=api"}),g=Yi(A),C=qi(E),D=async(b,N,v,k,O,Y)=>{let X=await r.getUserIdByExternalId(N.id);try{return await Y(X===null?void 0:C.admissionFor(X,b,v.signal))}catch(z){if(z instanceof Je)return Wr(O,v,k);throw z}},_=(b,N,v,k,O)=>{let Y=S.spend(N.id,`endpoint=${b}`);return Y===null?null:Vs(O,v,k,Y)},H=async({request:b})=>{let{user:N,cookie:v}=await t(b,{failureRedirect:s}),k=new Headers;v&&k.append("Set-Cookie",v);let O=await r.getUserIdByExternalId(N.id),Y=O?n(O):null;return{data:{user:N,userId:Y},headers:k}},w=b=>{let{limiter:N}=b;return async(v,k,O,Y,X,z)=>{if(N===null)return z(O,k,{error:{message:"Unknown endpoint"}},404);let M=b.parse(v);if(!M.ok)return z(O,k,M.invalid,400);let P=await r.getUserIdByExternalId(Y.id);if(!P)return z(O,k,b.emptyAnswer(M.parsed),200);let{signal:T}=O,$=await N.admit(P,T);if("refusal"in $)return T.aborted?qs(z,O,k):Vs(z,O,k,$.refusal);try{T.throwIfAborted();let j=await b.read(M.parsed,{userId:P,user:Y,scope:X},T);return T.throwIfAborted(),z(O,k,j,200)}catch(j){if(T.aborted&&j===T.reason)return qs(z,O,k);throw j}finally{$.release()}}},L=r.searchLimits===null?null:br({...r.searchLimits,route:le.search,logger:m}),x=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,em),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*tm,route:le.reports,logger:m}),q=r.searchLimits===null?null:br({concurrency:Us(r.searchLimits.concurrency,rm),rateLimitPerMinute:r.searchLimits.rateLimitPerMinute*nm,route:le.searchMarks,logger:m}),K=r.searchLimits===null?null:br({...r.searchLimits,route:le.searchFacets,logger:m}),G={[le.businessDate]:async(b,N,v,k,O,Y)=>{let X=b.searchParams.get(ge.businessDate),z=X===null?null:Vt(X);if(z===null)return Y(v,N,{error:{message:"Invalid business date"}},400);let M=mr(b.searchParams.get(ge.forceRefresh));if(M===null)return Y(v,N,{error:{message:"Invalid forceRefresh"}},400);let P=M?_(le.businessDate,k,v,N,Y):null;return P!==null?P:D(le.businessDate,k,v,N,Y,async T=>{let $=await r.getDailyReportsByBusinessDateByExternalId(O,z,k.id,{forceRefresh:M,admission:T});return Y(v,N,{businessDate:z,reports:$},200)})},[le.idsStream]:es({service:r,logger:c,streamSlots:g,missGate:C,refuseForcedRead:(b,N,v,k)=>_(le.idsStream,b,N,v,k)}),[le.report]:async(b,N,v,k,O,Y)=>{let X=Qe(b.searchParams.get(ge.reportHubId));if(X===null)return Y(v,N,{error:{message:"Invalid reportHubId"}},400);let z=mr(b.searchParams.get(ge.forceRefresh));if(z===null)return Y(v,N,{error:{message:"Invalid forceRefresh"}},400);let M=z?_(le.report,k,v,N,Y):null;return M!==null?M:D(le.report,k,v,N,Y,async P=>{let T=await r.getDailyReportDetailByIdByExternalId(O,X,k.id,{snapshot:!0,forceRefresh:z,admission:P});return T?Y(v,N,{report:T},200):Y(v,N,{error:{message:"Report not found"}},404)})},[le.search]:w({limiter:L,parse:b=>{let N=b.searchParams.get(ge.searchQuery),v=Gn(b.searchParams.get(ge.searchCombine));if(N===null||v===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let k=va(b.searchParams,r.searchFilterSourceTypes);if(!k.ok)return{ok:!1,invalid:{error:{message:"Invalid search filters",reason:k.reason}}};let O=Ds(N,v,k.filters);if(!O.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:O.reason}}};let{criteria:Y}=O;return{ok:!0,parsed:{criteria:Y,words:Y.plan===null?[]:gr(Y.plan)}}},emptyAnswer:({words:b})=>Wn([],b),read:async({criteria:b,words:N},{userId:v,scope:k})=>Wn(await r.searchDailyReports(k,v,b),N)}),[le.reports]:w({limiter:x,parse:b=>{let N=Kn(b.searchParams.get(ge.reportIds));return N===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:N}},emptyAnswer:b=>({outcomes:b.map(pr)}),read:async(b,{user:N,scope:v},k)=>({outcomes:await r.getDailyReportDetailsByIdsByExternalId(v,b,N.id,{signal:k})})}),[le.searchMarks]:w({limiter:q,parse:b=>{let N=b.searchParams.get(ge.searchQuery),v=Gn(b.searchParams.get(ge.searchCombine));if(N===null||v===null)return{ok:!1,invalid:{error:{message:"Invalid search request"}}};let k=tn(N,v);if(!k.ok)return{ok:!1,invalid:{error:{message:"Invalid search query",reason:k.reason}}};let O=Kn(b.searchParams.get(ge.reportIds));return O===null?{ok:!1,invalid:{error:{message:"Invalid ids"}}}:{ok:!0,parsed:{plan:k.plan,ids:O}}},emptyAnswer:({plan:b})=>({wordsDigest:Nr(gr(b)),reports:[],deferred:[]}),read:({plan:b,ids:N},{userId:v,scope:k},O)=>r.markDailyReportSearchHits(k,v,b,N,{signal:O})}),[le.searchFacets]:w({limiter:K,parse:()=>({ok:!0,parsed:null}),emptyAnswer:()=>({sourceTypes:[],authors:[],customers:[]}),read:(b,{userId:N,scope:v})=>r.listDailyReportSearchFacets(v,N)})},F=async({request:b,params:N})=>{let{user:v,cookie:k}=await t(b,{failureRedirect:null}),O=k??null;if(!v)return Bs(b,O,{error:{message:"Unauthorized"}},401);let Y=N.endpoint;if(!Jn(Y))return Bs(b,O,{error:{message:"Unknown endpoint"}},404);let X=Ot[Y],z=am(X),M=ja[X.body];if(!M.includes(b.method)){let T=z(b,O,{error:{message:"Method not allowed"}},405);return T.headers.set("Allow",M.join(", ")),T}let P=se();try{let T=new URL(b.url),$=await u(b,"initial"),j=$.ok?await G[Y](T,O,b,v,$.scope,z):Ls(z,b,O);return X.body==="json"&&c.debug(j.headers.has("ETag")?`${j.status} endpoint=${Y} etag_match=${j.status===304}`:`${j.status} endpoint=${Y}`),j}catch(T){let $=se()-P,j=T instanceof Error?T:new Error(String(T));return c.error(`500 endpoint=${Y} elapsed=${$}ms name=${j.name} code=${"code"in j?j.code:"N/A"} message=${j.message}`,j),z(b,O,{error:{message:"Internal Server Error"}},500)}},I=qa(f),U=ht({reason:"rate_limit",limitPerWindow:Kp,windowMs:js,logger:f,windowFields:()=>"route=action"}),W=async(b,N,v,k,O)=>{let{clientTempId:Y}=b;if(b.intent==="create")try{let T=await r.createDailyReport(v,N,b.businessDate,Y);return O(b,T.reportHubId,{report:T})}catch(T){if(T instanceof Error&&T.message==="Forbidden")return k({error:"Creating reports is restricted"},{status:403});throw T}let{reportHubId:X,businessDate:z}=b,M=async(T,$)=>{try{let j=await $(T.value);return O(T,X,{updatedStatus:{isStarred:j.isStarred,isRead:j.isRead},operationTimestamp:T.operationTimestamp})}catch(j){if(j instanceof Error&&j.message==="Not Found")return k({error:"Report not found"},{status:404});throw j}},P=T=>T instanceof Error?T.message==="Forbidden"?k({error:"Reports from this source are read-only"},{status:403}):T.message==="Unauthorized"?k({error:"Unauthorized"},{status:403}):T.message==="Not Found"?k({error:"Report not found"},{status:404}):null:null;switch(b.intent){case"update":try{return await r.updateDailyReport(v,X,N,b.changes,Y),O(b,X,{})}catch(T){let $=P(T);if($===null)throw T;return $}case"publish":try{let T=await r.publishDailyReport(v,X,N,Y);return O(b,X,{report:T})}catch(T){let $=P(T);if($===null)throw T;return $}case"delete":try{return await r.deleteDailyReport(v,X,N,Y),O(b,X,{})}catch(T){let $=P(T);if($===null)throw T;return $}case"toggleStar":return await M(b,T=>r.setStarStatus(v,N,X,z,T,Y));case"toggleRead":return await M(b,T=>r.setReadStatus(v,N,X,z,T,Y));case"addComment":try{let T=await r.addComment(v,N,X,b.content,z,Y);return O(b,X,{newComment:T})}catch(T){if(T instanceof Error){if(T.message==="Not Found")return k({error:"Report not found"},{status:404});if(T.message.startsWith("Comments are restricted"))return k({error:"Comments are restricted for this report"},{status:403})}throw T}case"deleteComment":try{return await r.deleteComment(v,N,X,b.commentId,z,Y),O(b,X,{deletedCommentId:b.commentId})}catch(T){if(T instanceof Error){if(T.message==="Unauthorized")return k({error:"Unauthorized"},{status:403});if(T.message==="Not Found")return k({error:"Comment not found"},{status:404})}throw T}}},ce=async({request:b,params:N})=>{let{user:v,cookie:k}=await t(b,{failureRedirect:null}),O=(z,M)=>$s(z,{...M,setCookie:k}),Y=(z,M,P)=>$s(Gp(z,M,P),{setCookie:k});if(!v)return O({error:"Unauthorized"},{status:401});let X=se();try{if(N.endpoint!==le.action)return O({error:"Unknown endpoint"},{status:404});let z=U.spend(v.id,"action");if(z!==null)return O({error:z.message},{status:z.status,headers:z.headers});let M=await Va(b,l);if("refusal"in M){let{refusal:j}=M;return j.status===413&&I(j.measuredBy),O({error:j.error},{status:j.status})}let{command:P}=M;if(P.intent==="clearCache"&&!e.enableDevCacheClear)return O({error:"Invalid intent"},{status:400});let T=await u(b,"initial");if(!T.ok)return O({error:Tr},{status:503,headers:{...Te(503),"Cache-Control":"no-store"}});let $=await r.getUserIdByExternalId(v.id);return $?P.intent==="clearCache"?(await r.clearCache(),O({status:"OK",intent:"clearCache"})):await W(P,$,T.scope,O,Y):O({error:"User not found"},{status:404})}catch(z){if(z instanceof Response)throw z;let M=se()-X,P=z instanceof Error?z:new Error(String(z));return c.error(`500 action elapsed=${M}ms name=${P.name} message=${P.message}`,P),O({error:"Internal Server Error"},{status:500})}},ne=Fs({authenticate:t,service:r,resolveViewerScope:u,redis:o,sseReader:a,streamKey:i,streamSlots:g,logger:h}),de=Fi({authenticate:t,service:r,encodeUserId:n,resolveViewerScope:u,logger:p}),Re=Qa(y),J=(b,N)=>async v=>{let k=Ja(v.request)?b.frameworkDataRefusal(v):null;if(k!==null)throw k;let O=Wp(v.request,b);return O===void 0?N(v):(Re(b.route,O,v.request),b.crossSiteRejection())};return{index:{loader:H},api:{loader:J(Yp,F),action:J(zp,ce)},sse:{loader:J(Ns,ne)},attachment:{loader:J(Hi,de)}}}import{chunk as ay,MAX_IN_LIST as iy,runWithTransactionRetry as sy}from"@aiquants/mssql";import{asc as bt,eq as fn,inArray as Rn}from"drizzle-orm";var im=["tables","externalSourceTexts","concurrency","rateLimitPerMinute"],sm=["document","comment"],lm=["hubId","searchText","sourceDigest","normalizerVersion","indexedAt","rowVersion","authorName","customerName"],cm=["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},zs=(e,t,r)=>{for(let n of Object.keys(t))if(!r.includes(n))throw En(e,n,r)},Gs=(e,t,r)=>{if(typeof t!="object"||t===null)throw Q(e,"a table object",t);let n=t;for(let o of r)if(typeof n[o]!="object"||n[o]===null)throw Q(`${e}.${o}`,"a column",n[o])},Ks=(e,t)=>{if(!Co(e))throw Q("search","a plain object",e);zs("search key",e,im);let{tables:r}=e;if(!Co(r))throw Q("search.tables","a plain object with document and comment",r);zs("search.tables key",r,sm),Gs("search.tables.document",r.document,lm),Gs("search.tables.comment",r.comment,cm);let n=new Map;if(e.externalSourceTexts!==void 0){if(!Co(e.externalSourceTexts))throw Q("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 Q(`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 It=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"?Qe(e):typeof e=="number"&&at(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 B}from"drizzle-orm";import{sql as _t}from"drizzle-orm";var Js=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 _t.join(e.map(t=>_t`${t}`),_t`, `)},nn=(e,t)=>{let{hub:r,hubLabel:n,label:o}=e;return _t`EXISTS (SELECT 1 FROM ${n} INNER JOIN ${o} ON ${o.id} = ${n.labelId} WHERE ${n.hubId} = ${r.id} AND ${o.name} IN (${Js(t)}))`},Qs=(e,t)=>{let{hubLabel:r,label:n}=e;return _t`${r.labelId} IN (SELECT ${n.id} FROM ${n} WHERE ${n.name} IN (${Js(t)}))`},on=(e,t,r,n)=>{let{hub:o}=e,a=n==="author-or-authorless"?_t`${o.userId} = ${t} OR ${o.userId} IS NULL`:_t`${o.userId} = ${t}`;return _t`(${a} OR NOT ${nn(e,r)})`};var um=/[[%_]/gu,dm=e=>e.replace(um,t=>`[${t}]`),Xs=e=>`%${dm(e)}%`;var et=Object.freeze({reportHubId:"report_hub_id",businessDate:"business_date",sourceType:"source_type"}),$t=Object.freeze({reportHubId:"report_hub_id",matchedSets:"matched_sets"}),wr=Object.freeze({value:"value"}),Me=Object.freeze({hubId:"hub_id",sourceDigest:"source_digest",normalizerVersion:"normalizer_version"}),V=e=>B`${B.identifier(e.name)}`,Er=e=>B.join(e.map(t=>B`${t}`),B`, `),Zs=(e,t)=>B`SELECT ${V(e.id)} AS ${B.identifier(Me.hubId)} FROM ${e} WITH (UPDLOCK, ROWLOCK) WHERE ${e.id} IN (${Er(t)}) ORDER BY ${e.id}`,pm=(e,t,r)=>{let{hub:n}=e,{document:o,comment:a}=e.search,i=t.alternatives.map(u=>Xs(u.text)),l=B.join(i.map(u=>B`${o.searchText} LIKE ${u}`),B` OR `),s=B.join(i.map(u=>B`${a.commentText} LIKE ${u}`),B` OR `),c=Sr(n.sourceType,r.scope.commentable),d=c===void 0?B``:B` AND (${c} OR ${a.authorUserId} = ${r.userId})`;return B`((${l}) OR EXISTS (SELECT 1 FROM ${a} WHERE ${a.hubId} = ${n.id} AND (${s})${d}))`},el=(e,t,r)=>B`(${B.join(t.words.map(n=>pm(e,n,r)),B` AND `)})`,Mo=(e,t,r,n)=>{let{hub:o}=e,a=[B`${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(B`${o.id} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${JSON.stringify(n)}))`),a},mm=(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(B`LOWER(${r.sourceType}) IN (${Er([...t.sourceTypes])})`)}return t.authors!==null&&o.push(B`${n.authorName} IN (${Er(t.authors)})`),t.customers!==null&&o.push(B`${n.customerName} IN (${Er(t.customers)})`),o},tl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,{plan:l}=t,s=[...Mo(e,r,n,o),...mm(e,t.filters)];if(l!==null){let c=l.combine==="intersection"?B` AND `:B` OR `;s.push(B`(${B.join(l.sets.map(d=>el(e,d,r)),c)})`)}return B`SELECT ${V(a.id)} AS ${B.identifier(et.reportHubId)}, CONVERT(char(10), ${V(a.businessDate)}, 23) AS ${B.identifier(et.businessDate)}, ${V(a.sourceType)} AS ${B.identifier(et.sourceType)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(s,B` AND `)} ORDER BY ${a.businessDate} DESC, ${a.id} DESC`},rl=(e,t,r,n,o)=>{let{hub:a}=e,{document:i}=e.search,l=B.join(t.sets.map((s,c)=>B`(CASE WHEN ${el(e,s,r)} THEN ${2**c} ELSE 0 END)`),B` + `);return B`SELECT ${V(a.id)} AS ${B.identifier($t.reportHubId)}, ${l} AS ${B.identifier($t.matchedSets)} FROM ${a} INNER JOIN ${i} ON ${i.hubId} = ${a.id} WHERE ${B.join(Mo(e,r,n,o),B` AND `)}`},nl=(e,t,r,n)=>{let{hub:o}=e,{document:a}=e.search,i=a[t],l=[...Mo(e,r,n),B`${i} IS NOT NULL`];return B`SELECT ${i} AS ${B.identifier(wr.value)} FROM ${o} INNER JOIN ${a} ON ${a.hubId} = ${o.id} WHERE ${B.join(l,B` AND `)} GROUP BY ${i} ORDER BY ${i}`},ol=(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 B`MERGE ${n} WITH (HOLDLOCK) AS t USING (SELECT * FROM OPENJSON(${a}) WITH (${V(n.hubId)} bigint, ${V(n.searchText)} nvarchar(max), ${V(n.sourceDigest)} char(64), ${V(n.normalizerVersion)} varchar(64), ${V(n.authorName)} nvarchar(max), ${V(n.customerName)} nvarchar(max))) AS s ON t.${V(n.hubId)} = s.${V(n.hubId)}
|
|
8
8
|
WHEN MATCHED THEN UPDATE SET t.${V(n.searchText)} = s.${V(n.searchText)}, t.${V(n.sourceDigest)} = CONVERT(binary(32), s.${V(n.sourceDigest)}, 2), t.${V(n.normalizerVersion)} = s.${V(n.normalizerVersion)}, t.${V(n.authorName)} = s.${V(n.authorName)}, t.${V(n.customerName)} = s.${V(n.customerName)}, t.${V(n.indexedAt)} = SYSUTCDATETIME()
|
|
9
9
|
WHEN NOT MATCHED THEN INSERT (${V(n.hubId)}, ${V(n.searchText)}, ${V(n.sourceDigest)}, ${V(n.normalizerVersion)}, ${V(n.authorName)}, ${V(n.customerName)}) VALUES (s.${V(n.hubId)}, s.${V(n.searchText)}, CONVERT(binary(32), s.${V(n.sourceDigest)}, 2), s.${V(n.normalizerVersion)}, s.${V(n.authorName)}, s.${V(n.customerName)});
|
|
10
10
|
DELETE FROM ${o} WHERE ${o.hubId} IN (SELECT CAST([value] AS bigint) FROM OPENJSON(${l}));
|
|
11
|
-
INSERT INTO ${o} (${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)}) SELECT ${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)} FROM OPENJSON(${i}) WITH (${V(o.hubId)} bigint, ${V(o.ordinal)} int, ${V(o.authorUserId)} bigint, ${V(o.commentText)} nvarchar(max));`},al=(e,t)=>B`SELECT ${V(e.hubId)} AS ${B.identifier(Me.hubId)}, LOWER(CONVERT(char(64), ${V(e.sourceDigest)}, 2)) AS ${B.identifier(Me.sourceDigest)}, ${V(e.normalizerVersion)} AS ${B.identifier(Me.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Er(t)})`,il=(e,t,r)=>B`SELECT TOP (${r}) ${V(e.id)} AS ${B.identifier(Me.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var sl=e=>({search:async(t,r)=>He(r.scope.visible)?[]:It(await t.execute(tl(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ft(o[et.sourceType],et.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${et.sourceType} is null`);return{reportHubId:Ht(o[et.reportHubId],et.reportHubId),businessDate:Ft(o[et.businessDate],et.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(He(r.scope.visible))return new Map;let n=It(await t.execute(rl(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[$t.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${$t.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Ht(i[$t.reportHubId],$t.reportHubId),l)}return a},facetValues:async(t,r)=>He(r.scope.visible)?[]:It(await t.execute(nl(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 cl}from"drizzle-orm";import{createHash as mm}from"crypto";var ym=Object.freeze({authorName:"author",customerName:"customer"}),Po=e=>e===null?null:Yn(e),ll=(e,t,r)=>{let n=Po(r);if(n!==null&&n.length>mt.maxValueLength){let o=mt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${ym[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",hm=e=>{let t=mm("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:fs(r),comments:n,sourceDigest:hm(e),forcedCuts:t,authorName:ll(e.hubId,"authorName",e.filterValues.authorName),customerName:ll(e.hubId,"customerName",e.filterValues.customerName)}};var ul=e=>{let t=async(s,c)=>{let d=[];for(let u of an(c,sn))for(let h of It(await s.execute(Zs(e.hub,u))))d.push(Ht(h[Me.hubId],Me.hubId));return d},r=async(s,c)=>{for(let d of an(c,sn))await s.execute(ol(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of an(c,sn))for(let h of It(await s.execute(al(e.tables.document,u))))d.set(Ht(h[Me.hubId],Me.hubId),{sourceDigest:Ft(h[Me.sourceDigest],Me.sourceDigest),normalizerVersion:Ft(h[Me.normalizerVersion],Me.normalizerVersion)});return d},o=async(s,c,d)=>It(await s.execute(il(e.hub,c,d))).map(u=>Ht(u[Me.hubId],Me.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((h,p)=>h-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(cl`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),h=(await e.loadSources(c,d)).map(ko),p=h.filter(y=>{let f=u.get(y.hubId);return f===void 0||f.sourceDigest!==y.sourceDigest||f.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(cl`SET DEADLOCK_PRIORITY NORMAL`),{scanned:h.length,written:p.length,forcedCuts:h.reduce((y,f)=>y+f.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:h,onProgress:p}=c;ie("reconcileSearchIndex: batchSize",d,1,sn);let y=se(),f=u===void 0?null:an([...new Set(u)].sort((R,T)=>R-T),d),m={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let R=0;;R++){h?.throwIfAborted();let T=f===null?await o(s,m.lastHubId===null?0:m.lastHubId,d):f[R];if(T===void 0||T.length===0)break;let E=await i(T);m={scanned:m.scanned+E.scanned,written:m.written+E.written,skipped:m.skipped+E.scanned-E.written,forcedCuts:m.forcedCuts+E.forcedCuts,lastHubId:T[T.length-1]},p?.(m)}return{...m,elapsedMs:se()-y}}}};import{holdsMultiUnitCluster as fm}from"@aiquants/fuzzy-search/normalize";var Lo=255,ln=Object.values(Nt).sort((e,t)=>e-t),Rm=new Intl.Segmenter("und",{granularity:"grapheme"}),fe=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ut=5e5,cn=Math.floor(ut/fe.linear),Sm=Math.floor(ut/fe.segment),dl=Math.floor(ut/fe.sweep),ml=Math.floor(ut/fe.scan),xr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),yl=(e,t)=>{let r=0,n=t(),o=ut,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ut,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ut,a=!1}}},Lg=Object.freeze({fits:()=>!0,charge:()=>{}}),hl=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 gm=(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},bm=(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*Dm(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)*fe.linear;n.fits(u)||(yield),o=fm(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Rm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(Sm,s.value.segment.length);n.fits(c*fe.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:h}=s.value;a.fill(t+u,u,u+h.length),i.fill(t+u+h.length,u,u+h.length),d+=h.length,s=l.next()}n.charge(d*fe.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Am=256,Tm=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]},Em=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=Tm(r),a=Math.max(ml-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(Am/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)},pl=(e,t,r)=>{let n=un(e,t);return e.pieces[n>=0?n:un(e,r==="start"?t-1:t+1)]},fl=(e,t)=>{let r=un(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=un(e,t);if(r<0)return fl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},wm=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),Im=Object.freeze({kind:"done"}),vo=Object.freeze({kind:"slice"}),_m=Object.freeze({kind:"clusters"}),xm=(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(fe.run))return vo;let p=pl(e,n.closedStart,"start"),y=pl(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(y.mapped===null)return{kind:"map",piece:y};if(e.isCut&&e.clusters===void 0)return _m;let f=t(e.offset+fl(e,n.closedStart)),m=t(e.offset+Rl(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let R=e.clusters;R==null?a(f,m,s):a(R.clusterStarts[f-R.start],R.clusterEnds[m-1-R.start],s),o.charge(fe.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ut))return vo;let{period:p,continuation:y}=c,f=n.periodicEnd,m=Math.min(i.length,f+Math.max(ml,y.length)),R=f;for(;R+y.length<=m&&i.startsWith(y,R);)R+=y.length;let T=R+y.length>m&&m<i.length;if(!T)for(;R<i.length&&i.charCodeAt(R)===i.charCodeAt(R-p);)R++;if(o.charge((R-f)*fe.scan),T){n.periodicEnd=R;continue}n.periodicEnd=-1,n.last+=Math.floor((R-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return Im;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ut))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)*fe.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*fe.scan);let h=n.windowStart+u;(n.runStart<0||h>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=h),n.last=h,c===null?n.from=h+1:n.periodicEnd=h+l.length}};function*No(e,t,r){let n=Math.floor(ut/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Cm(e,t,r,n,o){if(t.length===0)return;let a=yield*No(Rs(e),fe.strip,n),i=[],l=[];yield*No(Ss(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),fe.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(fe.line)||(yield),n.charge(fe.line);let d=i[c],u=a.text.slice(d,l[c]),h=yield*No(gs(u,r),fe.plan,n),p=[],y="";for(let m of h.chunks){let R="",T=[];for(let E of m){let S=(E.end-E.start)*fe.normalize;n.fits(S)||(yield);let g=bo(E.start===0&&E.end===u.length?u:u.slice(E.start,E.end),r).text;n.charge(S),g.length>0&&T.push({start:E.start,end:E.end,text:g,chunkStart:R.length}),R+=g}if(R.length!==0){y.length>0&&(y+=" ");for(let E of T)p.push({start:E.start,end:E.end,text:E.text,plainStart:y.length+E.chunkStart,mapped:null});y+=R}}if(y.length===0)continue;let f={offset:d,plain:y,pieces:p,isCut:!bm(h,u),lastPiece:0,clusters:void 0};for(let m of t){let R=wm();for(;;){let T=xm(f,s,m,R,n,o);if(T.kind==="done")break;if(T.kind==="slice"){yield;continue}if(T.kind==="clusters"){f.clusters=yield*Dm(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:E}=T,S=(E.end-E.start)*fe.map;n.fits(S)||(yield);let g=u.slice(E.start,E.end);E.mapped=gm(hs(g,go(g,r)),E.text),n.charge(S)}}}}function*Mm(e,t,r,n){let o=new Int32Array(ln.length),a=0,i=Lo;for(let l=0;l<=e;l+=dl){let s=Math.min(e+1,l+dl),c=(s-l)*fe.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Lo;for(let h=ln.length-1;h>=0;h--){let p=ln[h];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*Pm(e,t,r,n,o){let a=null;return yield*Cm(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*Mm(e.length,a,n,o)}var km=(e,t,r,n)=>{let o=Em(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return hl(function*(){return(yield*Pm(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var Sl=(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)},gl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of _a)r(pt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(pt.interviewer(o,"name"),n.name),r(pt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(pt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(pt.comment($n(o),"author"),n.name),r(pt.comment($n(o),"content"),n.text)});for(let n of e.postedComments)r(pt.comment(n.id,"author"),n.userName),r(pt.comment(n.id,"content"),n.content);return t};function*Lm(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)*fe.linear;t.fits(a)||(yield),r=qn(r,e,n,o),t.charge(a)}return r}var bl=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:h,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let y=await i(hl(Lm(p,n))),f=await i(km(p,c.alternatives,{maxLength:fo,maxRanges:t.maxFieldRanges},n));if(o+=p.length,f.dense){u[h]={fingerprint:y,dense:!0};continue}if(u[h]={fingerprint:y,ranges:f.ranges},a+=f.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(h=>h.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};import{and as Hm,asc as Tl,eq as pn,inArray as Fm,isNull as $m}from"drizzle-orm";import{and as Dl,asc as vm,eq as dn,getColumns as Nm,sql as Om}from"drizzle-orm";var gt=e=>Nm(e),Ie=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Al=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=w=>Sr(i.sourceType,w),h=(w,k)=>on(a,w,c,k),p=Om`CASE WHEN ${nn(a,c)} THEN 1 ELSE 0 END`,y=async w=>{let[k]=await t.select({id:i.id}).top(1).from(i).where(Dl(dn(i.id,w),nn(a,c)));return k!==void 0},f=w=>w==null||w===""?null:/^\d+$/.test(w)?n(Number(w)):w,m=()=>{let w={};for(let k of s)w[`ext_${k.sourceType}`]=gt(k.table);return w},R=w=>{let k=w;for(let x of s)k=k.leftJoin(x.table,Dl(dn(i.sourceType,x.sourceType),dn(i.sourceIdNum,x.idColumn)));return k},T=w=>{let{hub:k,internal:x}=w,q=k.summary,K=[],z=null,F=null,I=null,$=null,j=null,ce=null,ne=[],de=s.find(J=>J.sourceType===k.sourceType),Re=de?w[`ext_${de.sourceType}`]:void 0;if(de&&Re){let J=de.mapRow(Re);J.content!==void 0&&(q=J.content),J.employeeName!==void 0&&(ce=J.employeeName),J.category!==void 0&&(z=J.category),J.creationCategory!==void 0&&(F=J.creationCategory),J.visitTimeFrom!==void 0&&(I=J.visitTimeFrom),J.visitTimeTo!==void 0&&($=J.visitTimeTo),J.customerName!==void 0&&(j=J.customerName),J.interviewers!==void 0&&(K=J.interviewers),J.externalComments!==void 0&&(ne=J.externalComments)}else k.sourceType===Xe&&x&&(q=x.body);return{content:q,author:w.creatorName??f(k.createdBy)??"",employeeName:ce??w.creatorName??f(k.createdBy),updatedBy:f(k.updatedBy),category:z,creationCategory:F,visitTimeFrom:I,visitTimeTo:$,customerName:j,interviewers:K,externalComments:ne}},E=w=>{if(w===1)return!0;if(w===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(w)}`)},S=w=>w.creationCategory!==null&&c.includes(w.creationCategory),g=(w,k)=>E(w.hasDraftLabel)?!0:S(k),C=async w=>{let[k]=await w.select({id:l.id}).top(1).from(l).where(dn(l.name,d)).orderBy(vm(l.id));return k===void 0?null:k.id},A=()=>C(t);return{visibleSourceTypeCondition:u,draftVisibleTo:h,draftLabelFlag:p,isDraftReport:y,externalSelections:m,applyExternalJoins:R,resolveHubDisplayFields:T,readCanonicalDraftLabelId:C,getDraftLabelId:A,resolveCreationCategoryDraftLabelId:w=>w.some(S)?A():Promise.resolve(null),mapHubRecord:(w,k,x,q,K)=>{let{hub:z}=k,F=k.labels.map(j=>({id:j.id,name:j.name,color:j.color})),I=k.postedCommentRows,$=we(w.commentable,z.sourceType);return q!==null&&S(x)&&!F.some(j=>j.id===q)&&F.push({id:q,name:d,color:null}),{reportHubId:z.id,date:Ie(z.businessDate,"YYYY-MM-DD"),author:x.author,userId:z.userId?n(z.userId):"",sourceType:z.sourceType,createdAt:Ie(z.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Ie(z.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:x.updatedBy,employeeName:x.employeeName,category:x.category,creationCategory:x.creationCategory,visitTimeFrom:x.visitTimeFrom,visitTimeTo:x.visitTimeTo,customerName:x.customerName,interviewers:x.interviewers,subject:z.title,content:x.content,externalComments:$?x.externalComments:[],isRead:k.isRead??!1,isStarred:k.isStarred??!1,isDraft:g(k,x),labels:F,postedComments:I.filter(j=>as({authorUserId:j.userId},z.sourceType,K,w)).map(j=>({...j,userId:n(j.userId),isMine:K?j.userId===K:!1})),attachments:k.attachments}}}};var El=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(y,f)=>f!=null?"absent":y!=null?"present":"unknown";return{getAttachmentsByHubIds:async y=>{let f=new Map,m=o.attachment;if(y.length===0||!m||s===null)return f;let R=s.idCodec,T=s.thumbnails!==null,E=await n.select({id:m.id,hubId:m.hubId,fileName:m.fileName,fileType:m.fileType,fileSize:m.fileSize,createdAt:m.createdAt,objectCheckedAt:m.objectCheckedAt,objectMissingAt:m.objectMissingAt}).from(m).where(Fm(m.hubId,y)).orderBy(Tl(m.createdAt),Tl(m.id));for(let S of E){let g=S.fileType?String(S.fileType):null,C=S.fileSize!=null?Number(S.fileSize):null,A=c(S.objectCheckedAt,S.objectMissingAt),_={id:R.encode(Number(S.id)),fileName:String(S.fileName),fileType:g,fileSize:C,createdAt:Ie(S.createdAt,"YYYY-MM-DD HH:mm:ss"),state:A,hasThumbnail:T&&A!=="absent"&&Vr({fileType:g,fileSize:C},s.maxBytes)},H=f.get(Number(S.hubId));H?H.push(_):f.set(Number(S.hubId),[_])}return f},getAttachmentForUser:async(y,f,m)=>{let R=o.attachment;return!R||He(y.visible)?null:(await n.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(l,pn(l.id,R.hubId)).where(Hm(pn(R.id,f),$m(l.deletedAt),t(m,"author"),r(y.visible))))[0]??null},markAttachmentMissing:async y=>{let f=o.attachment;if(!f)return;let m=new Date;try{await n.update(f).set({objectCheckedAt:m,objectMissingAt:m,updatedAt:m}).where(pn(f.id,y))}catch(R){a.error("markAttachmentMissing failed",R)}},markAttachmentPresent:async y=>{let f=o.attachment;if(!f)return;let m=new Date;try{await n.update(f).set({objectCheckedAt:m,objectMissingAt:null,updatedAt:m}).where(pn(f.id,y))}catch(R){a.error("markAttachmentPresent failed",R)}}}};import{eq as Oo}from"drizzle-orm";import{and as Um,eq as wl,isNull as Bm}from"drizzle-orm";var Xt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(Um(wl(t.id,r),Bm(t.deletedAt),n===null?void 0:wl(t.userId,n)))).length===0)throw new Error("Not Found")};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,{dateEpochPrefix:h,detailEpochPrefix:p}=e.settings.redisKeys,{hub:y,comment:f}=a,m=async(S,g)=>{if(g!==null)return await t(S)?g:void 0},R=async(S,g,C,A,_,H)=>{let w=await r(S,C,g);if(!we(S.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!==Xe.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let k=await m(C,w.userId),x=await d(),q=await c(async I=>{await Xt(I,y,C,null);let[$]=await I.insert(f).output().values({hubId:C,userId:g,body:A,createdAt:new Date,createdBy:String(g),updatedAt:new Date,updatedBy:String(g)});return x!==null&&await x.writeHubs(I,[C]),$}),[K]=await o.select({displayName:i.displayName}).top(1).from(i).where(Oo(i.id,g)),z=K?.displayName??"";if(_){let I=Ue(_);I&&(s.invalidatePrefix(Jt(I)),await n(`${h}${I}`))}s.invalidatePrefix(Ye(C)),await n(`${p}${C}`);let F={id:q.id,userId:l(q.userId),userName:z,content:q.body,createdAt:Ie(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Mn.parse({type:"comment-add",reportHubId:C,comment:F,clientTempId:H,recipientRawUserId:k,sourceType:w.sourceType}),"addComment"),F},T=async(S,g)=>await S.select().top(1).from(f).where(Oo(f.id,g));return{addComment:R,deleteComment:async(S,g,C,A,_,H)=>{let w=await T(o,A);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==C)throw new Error("Not Found");let k=await r(S,w[0].hubId,g);if(w[0].userId!==g)throw new Error("Unauthorized");let x=await m(C,k.userId),q=await d();if(await c(async K=>{await Xt(K,y,C,null),await K.delete(f).where(Oo(f.id,A)),q!==null&&await q.writeHubs(K,[C])}),_){let K=Ue(_);K&&(s.invalidatePrefix(Jt(K)),await n(`${h}${K}`))}s.invalidatePrefix(Ye(C)),await n(`${p}${C}`),await u(Pn.parse({type:"comment-delete",reportHubId:C,commentId:A,clientTempId:H,recipientRawUserId:x,sourceType:k.sourceType}),"deleteComment")}}};import{and as _l,eq as Ut,isNull as Vm}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:h,settings:p,draftVisibilityTables:y}=e,{idsEpoch:f,dateEpochPrefix:m,detailEpochPrefix:R}=e.settings.redisKeys,{hub:T,internal:E,hubLabel:S,userStatus:g}=l,{canonicalDraftLabelName:C,draftLabelNames:A}=p,_=async(F,I,$,j)=>{if(!Mr($))throw Q("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(!we(F.visible,Xe))throw new Error("Forbidden");c.info("createDailyReport called",{userId:I,businessDate:$});let ce=await u();try{let ne=await d(async b=>{c.info("Starting transaction");let v=await t(b);if(v===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(C)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let L=`internal-temp-${Date.now()}-${Math.random()}`,[P]=await b.insert(T).output().values({sourceType:Xe,sourceId:L,businessDate:new Date(`${$}T00:00:00Z`),userId:I,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)});return await b.update(T).set({sourceId:String(P.id)}).where(Ut(T.id,P.id)),c.info("Hub created",P),await b.insert(E).values({hubId:P.id,body:"",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),c.info("Internal created"),await b.insert(S).values({hubId:P.id,labelId:v,createdAt:new Date,createdBy:String(I)}),c.info("Label assigned"),await b.insert(g).values({hubId:P.id,userId:I,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),ce!==null&&await ce.writeHubs(b,[P.id]),P.id});s.invalidatePrefix(Qt($,I)),s.invalidatePrefix(wo(I)),await a(f),await a(`${m}${$}`);let de=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ne,I,{forceRefresh:!0});if(de===null)throw new Error(`[daily-report] createDailyReport: report ${ne} was committed but its detail read returned nothing`);let Re=await r(de.reportHubId);await h(vn.parse({type:"report-create",reportHubId:de.reportHubId,report:de,clientTempId:j,recipientRawUserId:Re?I:void 0,actorRawUserId:I}),"createDailyReport");let J=await n(F,ne,I,{forceRefresh:!0});if(J===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ne} it just created`);return J}catch(ne){throw c.error("Error in createDailyReport",ne),ne}},H=async(F,I)=>await F.select().top(1).from(T).where(Ut(T.id,I)),w=async(F,I,$)=>{await o(F,I,$);let[j]=await H(i,I);if(j===void 0||j.deletedAt)throw new Error("Not Found");if(j.userId!==$)throw new Error("Unauthorized");return j},k=async(F,I,$)=>{await F.update(T).set($).where(Ut(T.id,I))},x=async(F,I,$)=>{await F.update(E).set($).where(Ut(E.hubId,I))};return{createDailyReport:_,updateDailyReport:async(F,I,$,j,ce)=>{let ne=await w(F,I,$),de=await u();await d(async b=>{await Xt(b,T,I,$),j.title!==void 0&&await k(b,I,{title:xl(j.title),updatedAt:new Date,updatedBy:String($)}),j.content!==void 0&&await x(b,I,{body:xl(j.content),updatedAt:new Date,updatedBy:String($)}),de!==null&&await de.writeHubs(b,[I])}),s.invalidatePrefix(Ye(I)),await a(`${R}${I}`);let Re=Ue(Ie(ne.businessDate,"YYYY-MM-DD"));Re&&(s.invalidatePrefix(Jt(Re)),await a(`${m}${Re}`));let J=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,$,{forceRefresh:!0});if(J){let b=await r(I);await h(Nn.parse({type:"report-update",reportHubId:J.reportHubId,report:J,clientTempId:ce,recipientRawUserId:b?$:void 0,actorRawUserId:$}),"updateDailyReport")}},publishDailyReport:async(F,I,$,j)=>{let ce=await w(F,I,$),ne=await u();if(await d(async b=>{await Xt(b,T,I,$),await b.delete(S).where(_l(Ut(S.hubId,I),Qs(y,A))),ne!==null&&await ne.writeHubs(b,[I])}),s.invalidatePrefix(Ye(I)),s.invalidatePrefix(wt),await a(f),ce.businessDate){let b=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));b&&await a(`${m}${b}`)}let de=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));de&&s.invalidatePrefix(Qt(de,$));let Re=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,$,{forceRefresh:!0});if(Re===null)return null;let J=await r(I);return await h(On.parse({type:"report-publish",reportHubId:Re.reportHubId,report:Re,clientTempId:j,recipientRawUserId:J?$:void 0,actorRawUserId:$}),"publishDailyReport"),await n(F,I,$,{forceRefresh:!0})},deleteDailyReport:async(F,I,$,j)=>{let ce=await w(F,I,$);if(await d(async ne=>{if((await ne.update(T).set({deletedAt:new Date,deletedBy:String($),updatedAt:new Date,updatedBy:String($)}).output().where(_l(Ut(T.id,I),Ut(T.userId,$),Vm(T.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(Ye(I)),s.invalidatePrefix(wt),await a(f),ce.businessDate){let ne=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));ne&&await a(`${m}${ne}`)}await h(Lr.parse({type:"report-delete",reportHubId:I,clientTempId:j,sourceType:ce.sourceType}),"deleteDailyReport")}}};import{and as Zt,asc as Ml,desc as Cr,eq as Pe,inArray as Ho,isNull as mn,sql as qm}from"drizzle-orm";var Pl=vr([]),jm=6e4,$o=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw je(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw Q(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw je(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw Q(`${e}: options.signal`,r,n);return n},Uo=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}}},Wm=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 (${Ma(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:h,tables:p,users:y,resolveUserId:f,cache:m,epochs:R,logger:T,settings:E}=e,{idsEpoch:S,dateEpochPrefix:g,detailEpochPrefix:C}=e.settings.redisKeys,{hub:A,internal:_,comment:H,label:w,hubLabel:k,userStatus:x}=p,q=E.idsTtlMs,K=E.businessDateTtlMs,z=async(M,D)=>(await h.select({reportHubId:A.id,businessDate:A.businessDate,sourceType:A.sourceType}).from(A).where(Zt(mn(A.deletedAt),t(D,"author-or-authorless"),r(M.visible))).orderBy(Cr(A.businessDate),Cr(A.id))).map(U=>({...U,businessDate:Ie(U.businessDate,"YYYY-MM-DD")})),F=async(M,D,N)=>{let U=await $(D);return U?He(M.visible)?[]:(await h.select({reportHubId:A.id,businessDate:A.businessDate,sourceType:A.sourceType}).top(N).from(A).where(Zt(mn(A.deletedAt),t(U,"author-or-authorless"),r(M.visible))).orderBy(Cr(A.businessDate),Cr(A.id))).map(he=>({...he,businessDate:Ie(he.businessDate,"YYYY-MM-DD")})):[]},I=new Map,$=async M=>{if(!E.disableUserIdCache&&I.has(M))return I.get(M)??null;let D=await f(M);return D!==null&&!E.disableUserIdCache&&I.set(M,D),D},j=async(M,D,{forceRefresh:N=!1,snapshot:U=!1,ttlMsOverride:G,onFetchStart:he,admission:Oe}={})=>{let Ae=await $(D);if(!Ae)return{items:[],streamAnchor:null,snapshot:Pl};if(He(M.visible))return{items:[],streamAnchor:await d(),snapshot:Pl};let ye=_s(Ae,Kr(M)),[Se]=await m.getOrFetch({cacheKey:ye,fetcher:async()=>{let qe=await d(),rt=await z(M,Ae);if(!Ta(rt)){T.warn("ids array is not in stream order; re-sorting (check SQL ORDER BY vs compareIdsStreamOrder, or concurrent row movement during the scan)");let re=[...rt].sort(Fn);return[{items:re,streamAnchor:qe,snapshot:vr(re)}]}return[{items:rt,streamAnchor:qe,snapshot:vr(rt)}]},onFetchStart:he,forceRefresh:N,snapshot:U,admission:Oe,ttlMsOverride:G??q,epochKey:S,refreshAheadRatio:.5});if(Se===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Se},ce=async(M,D,N)=>{let U=await a(h.select({hub:gt(A),internal:gt(_),isRead:x.isRead,isStarred:x.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(A)).leftJoin(_,Pe(A.id,_.hubId)).leftJoin(x,Zt(Pe(A.id,x.hubId),Pe(x.userId,D))).leftJoin(y,Pe(A.userId,y.id)).where(Zt(N,mn(A.deletedAt),t(D,"author"),r(M.visible))).orderBy(Cr(A.id));if(U.length===0)return[];let G=U.map(re=>re.hub.id),he=await h.select({hubId:k.hubId,id:w.id,name:w.name,color:w.color}).from(k).innerJoin(w,Pe(k.labelId,w.id)).where(Ho(k.hubId,G)),Oe=await h.select({hubId:H.hubId,id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,Pe(H.userId,y.id)).where(Ho(H.hubId,G)).orderBy(Ml(H.createdAt)),Ae=await c(G),ye=new Map,Se=new Map;for(let re of he){let Le=ye.get(re.hubId);Le||(Le=[],ye.set(re.hubId,Le)),Le.push({id:re.id,name:re.name,color:re.color})}for(let re of Oe){let Le=Se.get(re.hubId);Le||(Le=[],Se.set(re.hubId,Le)),Le.push({id:re.id,content:re.body,createdAt:Ie(re.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:re.userId,userName:re.userName||""})}let qe=U.map(re=>Fo(()=>i(re))),rt=await l(qe.flatMap(re=>re.ok?[re.value]:[]));return U.map((re,Le)=>{let dt=re.hub.id,Ct=qe[Le],Dt=Ct.ok?Fo(()=>s(M,{...re,attachments:Ae.get(dt)??[],labels:ye.get(dt)||[],postedCommentRows:Se.get(dt)||[]},Ct.value,rt,D)):Ct;return Dt.ok?{reportHubId:dt,outcome:"ok",report:Dt.value}:{reportHubId:dt,outcome:"failed",cause:Dt.cause}})},ne=async(M,D,N)=>(await ce(M,D,N)).map(U=>{if(U.outcome==="failed")throw U.cause;return U.report}),de=M=>Ce({windowMs:jm,tallies:["failed"],writeSuppressed:(D,{count:N,since:U})=>{T.warn(`failed_report_suppressed count=${N} since=${U} read=${M} report=${D}`)}}),Re={markDailyReportSearchHits:de("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:de("getDailyReportDetailsByIdsByExternalId")},J=(M,D,N)=>{Re[M].record(D,"failed",()=>T.error(`${M}: report ${D} passed the visibility predicate but its own assembly failed`,N))},b=(M,D)=>{let N=D.outcome==="ok"?Wm(D.report):{ok:!1,cause:D.cause};return N.ok?{reportHubId:D.reportHubId,outcome:"ok",report:N.value}:(J(M,D.reportHubId,N.cause),{reportHubId:D.reportHubId,outcome:"failed"})},v=async(M,D,N,{read:U,signal:G,slicing:he})=>{let Oe=await ce(M,D,Ho(A.id,[...N]));G.throwIfAborted();let Ae=[],ye=he.now();for(let Se of Oe)Ae.length>0&&he.now()-ye>=he.sliceMs&&(await he.pause(),ye=he.now()),Ae.push(b(U,Se));return Ae},L=async(M,D,N,{forceRefresh:U=!1,snapshot:G=!1,ttlMsOverride:he,admission:Oe}={})=>{let Ae=await $(N);if(!Ae)return[];let ye=Ue(D);if(!ye)return[];if(He(M.visible))return[];let Se=xs(ye,Ae,Kr(M));return m.getOrFetch({cacheKey:Se,fetcher:()=>ne(M,Ae,Pe(A.businessDate,qm`${ye}`)),forceRefresh:U,snapshot:G,admission:Oe,ttlMsOverride:he??K,epochKey:`${g}${ye}`})},P=async(M,D,N,{forceRefresh:U=!1,snapshot:G=!1,ttlMsOverride:he,admission:Oe}={})=>{if(He(M.visible))return null;let Ae=Cs(D,N,Kr(M));return(await m.getOrFetch({cacheKey:Ae,fetcher:async()=>{let Se=await a(h.select({hub:gt(A),internal:gt(_),isRead:x.isRead,isStarred:x.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(A)).leftJoin(_,Pe(A.id,_.hubId)).leftJoin(x,Zt(Pe(A.id,x.hubId),Pe(x.userId,N))).leftJoin(y,Pe(A.userId,y.id)).where(Zt(Pe(A.id,D),mn(A.deletedAt),t(N,"author"),r(M.visible)));if(Se.length===0)return[];let qe=Se[0].hub.id,rt=await h.select({id:w.id,name:w.name,color:w.color}).from(k).innerJoin(w,Pe(k.labelId,w.id)).where(Pe(k.hubId,qe)),re=await h.select({id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,Pe(H.userId,y.id)).where(Pe(H.hubId,qe)).orderBy(Ml(H.createdAt)),Le=await c([qe]),dt=rt.map(ze=>({id:ze.id,name:ze.name,color:ze.color})),Ct=re.map(ze=>({id:ze.id,content:ze.body,createdAt:Ie(ze.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:ze.userId,userName:ze.userName||""})),Dt=i(Se[0]),Dn=await l([Dt]);return[s(M,{...Se[0],attachments:Le.get(qe)??[],labels:dt,postedCommentRows:Ct},Dt,Dn,N)]},forceRefresh:U,snapshot:G,admission:Oe,ttlMsOverride:he??K,epochKey:`${C}${D}`}))[0]??null};return{getUserIdByExternalId:$,getDailyReportIdsByExternalId:j,getDailyReportIdsFirstPageByExternalId:F,getDailyReportsByBusinessDateByExternalId:L,getDailyReportDetailById:P,getDailyReportDetailByIdByExternalId:async(M,D,N,U={})=>{let G=await $(N);return G?P(M,D,G,U):null},getDailyReportDetailsByIdsByExternalId:async(M,D,N,U)=>{let G=$o("getDailyReportDetailsByIdsByExternalId",U);if(D.length>xe.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${xe.maxDetailIds} ids`,D.length);let he=await $(N);if(!he||D.length===0||He(M.visible))return D.map(pr);G.throwIfAborted();let Oe=await v(M,he,D,{read:"getDailyReportDetailsByIdsByExternalId",signal:G,slicing:Uo(G)}),Ae=new Map(Oe.map(ye=>[ye.reportHubId,ye]));return D.map(ye=>{let Se=Ae.get(ye);return Se===void 0?pr(ye):Se})},fetchDeliveredHubOutcomes:v,invalidateHubReadCaches:async(M,D)=>{m.invalidatePrefix(wt),await u(S);for(let N of new Set(M))m.invalidatePrefix(Ye(N)),await u(`${C}${N}`);for(let N of new Set(D)){let U=Ue(N);U&&await u(`${g}${U}`)}},clearCache:async()=>{m.clearAll(),I.clear(),R&&await u(S),T.info("Server-side DB/SQL caches cleared successfully.")}}};var Ym="v4",zm=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,Bo=e=>{if(typeof e!="string"||!zm.test(e))throw Q("redisKeyPrefix",'a Redis key prefix of one or more characters without whitespace or control characters, neither starting nor ending with ":"',e);return Object.freeze({sseStream:`${e}:sse-stream:${Ym}`,idsEpoch:`${e}:ids:epoch`,dateEpochPrefix:`${e}:date-epoch:`,detailEpochPrefix:`${e}:detail-epoch:`})};var yn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,redisKeyPrefix:"daily-report",streamMaxLen:1e4}),Gm=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return ie("tables.hub.title.length",t,1)},Km=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 Q("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Jm=e=>{let t=new Map([[Xe.toLowerCase(),`the internal source type ${JSON.stringify(Xe)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Q(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Xe,...e.map(r=>r.sourceType)])},Ll=e=>{let t=e.externalSources??[],r=Km(e.draftLabelNames);if(jr(e),Object.hasOwn(e,"streamKey"))throw je("redisKeyPrefix","given in place of the removed key streamKey");let n=$i(e.attachments),o=Gm(e.tables.hub.title);ho(e.tables.hub.sourceType);let a=ve("idsTtlMs",e.idsTtlMs,1,yn.idsTtlMs),i=ve("businessDateTtlMs",e.businessDateTtlMs,1,yn.businessDateTtlMs),l=ve("streamMaxLen",e.streamMaxLen,1,yn.streamMaxLen),s=Bo(e.redisKeyPrefix===void 0?yn.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:Jm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamMaxLen:l,redisKeys:s,disableUserIdCache:!!e.disableUserIdCache})};var vl=({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),h=Buffer.byteLength(u);if(h>6356992){t.warn(`[SSE] Event too large (${c}): ${h} bytes > ${6356992}; not published`);return}let p=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let y=se()-p;y>1e3&&t.warn(`[SSE] Slow publish (${c}): ${y}ms`)}catch(y){t.error(`[SSE] Redis publish failed (${c}):`,y)}},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?Tt:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});import{and as Xm,eq as Zm,sql as De}from"drizzle-orm";var hn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],ey={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},Ve=e=>De`${De.identifier(e.name)}`,ty=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=Ve(e[t]),s=(p,y)=>De`t.${Ve(p)} = CASE WHEN t.${l} = ${o} THEN t.${Ve(p)} ELSE ${y} END`,c={hubId:De`s.${Ve(e.hubId)}`,userId:De`s.${Ve(e.userId)}`,isRead:De`${t==="isRead"?o:!1}`,isStarred:De`${t==="isStarred"?o:!1}`,createdAt:De`${a}`,createdBy:De`${i}`,updatedAt:De`${a}`,updatedBy:De`${i}`},d=De.join(hn.map(p=>Ve(e[p])),De`, `),u=De.join(hn.map(p=>c[p]),De`, `),h=De.join(hn.map(p=>De`inserted.${Ve(e[p])} AS ${De.identifier(p)}`),De`, `);return De`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${Ve(e.hubId)}, ${n} AS ${Ve(e.userId)}) AS s ON t.${Ve(e.hubId)} = s.${Ve(e.hubId)} AND t.${Ve(e.userId)} = s.${Ve(e.userId)}
|
|
11
|
+
INSERT INTO ${o} (${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)}) SELECT ${V(o.hubId)}, ${V(o.ordinal)}, ${V(o.authorUserId)}, ${V(o.commentText)} FROM OPENJSON(${i}) WITH (${V(o.hubId)} bigint, ${V(o.ordinal)} int, ${V(o.authorUserId)} bigint, ${V(o.commentText)} nvarchar(max));`},al=(e,t)=>B`SELECT ${V(e.hubId)} AS ${B.identifier(Me.hubId)}, LOWER(CONVERT(char(64), ${V(e.sourceDigest)}, 2)) AS ${B.identifier(Me.sourceDigest)}, ${V(e.normalizerVersion)} AS ${B.identifier(Me.normalizerVersion)} FROM ${e} WHERE ${e.hubId} IN (${Er(t)})`,il=(e,t,r)=>B`SELECT TOP (${r}) ${V(e.id)} AS ${B.identifier(Me.hubId)} FROM ${e} WHERE ${e.id} > ${t} ORDER BY ${e.id}`;var sl=e=>({search:async(t,r)=>He(r.scope.visible)?[]:It(await t.execute(tl(e.tables,r.criteria,{userId:r.viewerUserId,scope:r.scope},e.draftLabelNames))).map(o=>{let a=Ft(o[et.sourceType],et.sourceType);if(a===null)throw new Error(`[daily-report] search: column ${et.sourceType} is null`);return{reportHubId:Ht(o[et.reportHubId],et.reportHubId),businessDate:Ft(o[et.businessDate],et.businessDate),sourceType:a}}),matchedSets:async(t,r)=>{if(He(r.scope.visible))return new Map;let n=It(await t.execute(rl(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[$t.matchedSets];if(!(typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&l<=o))throw new Error(`[daily-report] search: column ${$t.matchedSets} holds no mask of ${r.plan.sets.length} keywords`);a.set(Ht(i[$t.reportHubId],$t.reportHubId),l)}return a},facetValues:async(t,r)=>He(r.scope.visible)?[]:It(await t.execute(nl(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 cl}from"drizzle-orm";import{createHash as ym}from"crypto";var hm=Object.freeze({authorName:"author",customerName:"customer"}),Po=e=>e===null?null:Yn(e),ll=(e,t,r)=>{let n=Po(r);if(n!==null&&n.length>mt.maxValueLength){let o=mt.maxValueLength;throw new Error(`[daily-report] search index: report ${e}: the ${hm[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",fm=e=>{let t=ym("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:fs(r),comments:n,sourceDigest:fm(e),forcedCuts:t,authorName:ll(e.hubId,"authorName",e.filterValues.authorName),customerName:ll(e.hubId,"customerName",e.filterValues.customerName)}};var ul=e=>{let t=async(s,c)=>{let d=[];for(let u of an(c,sn))for(let h of It(await s.execute(Zs(e.hub,u))))d.push(Ht(h[Me.hubId],Me.hubId));return d},r=async(s,c)=>{for(let d of an(c,sn))await s.execute(ol(e.tables,d,e.normalizerVersion))},n=async(s,c)=>{let d=new Map;for(let u of an(c,sn))for(let h of It(await s.execute(al(e.tables.document,u))))d.set(Ht(h[Me.hubId],Me.hubId),{sourceDigest:Ft(h[Me.sourceDigest],Me.sourceDigest),normalizerVersion:Ft(h[Me.normalizerVersion],Me.normalizerVersion)});return d},o=async(s,c,d)=>It(await s.execute(il(e.hub,c,d))).map(u=>Ht(u[Me.hubId],Me.hubId)),a=async(s,c)=>{let d=await t(s,[...new Set(c)].sort((h,p)=>h-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(cl`SET DEADLOCK_PRIORITY LOW`);let d=await t(c,s),u=await n(c,d),h=(await e.loadSources(c,d)).map(ko),p=h.filter(y=>{let f=u.get(y.hubId);return f===void 0||f.sourceDigest!==y.sourceDigest||f.normalizerVersion!==e.normalizerVersion});return p.length>0&&await r(c,p),await c.execute(cl`SET DEADLOCK_PRIORITY NORMAL`),{scanned:h.length,written:p.length,forcedCuts:h.reduce((y,f)=>y+f.forcedCuts,0)}});return{writeHubs:a,reconcile:async(s,c)=>{let{batchSize:d,hubIds:u,signal:h,onProgress:p}=c;ie("reconcileSearchIndex: batchSize",d,1,sn);let y=se(),f=u===void 0?null:an([...new Set(u)].sort((R,A)=>R-A),d),m={scanned:0,written:0,skipped:0,forcedCuts:0,lastHubId:null};for(let R=0;;R++){h?.throwIfAborted();let A=f===null?await o(s,m.lastHubId===null?0:m.lastHubId,d):f[R];if(A===void 0||A.length===0)break;let E=await i(A);m={scanned:m.scanned+E.scanned,written:m.written+E.written,skipped:m.skipped+E.scanned-E.written,forcedCuts:m.forcedCuts+E.forcedCuts,lastHubId:A[A.length-1]},p?.(m)}return{...m,elapsedMs:se()-y}}}};import{holdsMultiUnitCluster as Rm}from"@aiquants/fuzzy-search/normalize";var Lo=255,ln=Object.values(Nt).sort((e,t)=>e-t),Sm=new Intl.Segmenter("und",{granularity:"grapheme"}),fe=Object.freeze({strip:30,split:200,line:2e3,plan:90,normalize:900,map:2200,scan:2,run:700,segment:150,sweep:30,linear:6}),ut=5e5,cn=Math.floor(ut/fe.linear),gm=Math.floor(ut/fe.segment),dl=Math.floor(ut/fe.sweep),ml=Math.floor(ut/fe.scan),xr=Object.freeze({maxRanges:5e5,maxUnits:4e6,maxFieldRanges:1e4,sliceNs:8e6,sliceMs:5}),yl=(e,t)=>{let r=0,n=t(),o=ut,a=!1;return{fits:i=>r===0?!0:r+i>e.sliceNs?!1:(r>=o&&(o=r+ut,a=t()-n>=e.sliceMs),!a),charge:i=>{r+=i},startSlice:()=>{r=0,n=t(),o=ut,a=!1}}},vg=Object.freeze({fits:()=>!0,charge:()=>{}}),hl=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 bm=(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},Dm=(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*Am(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)*fe.linear;n.fits(u)||(yield),o=Rm(e.slice(c,d)),n.charge(u)}if(!o)return null;let a=new Int32Array(r-t),i=new Int32Array(r-t),l=Sm.segment(e.slice(t,r))[Symbol.iterator](),s=l.next();for(;!s.done;){let c=Math.max(gm,s.value.segment.length);n.fits(c*fe.segment)||(yield);let d=0;for(;!s.done&&d+s.value.segment.length<=c;){let{index:u,segment:h}=s.value;a.fill(t+u,u,u+h.length),i.fill(t+u+h.length,u,u+h.length),d+=h.length,s=l.next()}n.charge(d*fe.segment)}return{start:t,clusterStarts:a,clusterEnds:i}}var Tm=256,Em=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]},wm=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=Em(r),a=Math.max(ml-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(Tm/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)},pl=(e,t,r)=>{let n=un(e,t);return e.pieces[n>=0?n:un(e,r==="start"?t-1:t+1)]},fl=(e,t)=>{let r=un(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=un(e,t);if(r<0)return fl(e,t+1);let n=e.pieces[r];return n.start+n.mapped.end[t-n.plainStart]},Im=()=>({from:0,runStart:-1,last:0,periodicEnd:-1,window:"",windowStart:0,windowEnd:0,closedStart:0,closedEnd:-1}),_m=Object.freeze({kind:"done"}),vo=Object.freeze({kind:"slice"}),xm=Object.freeze({kind:"clusters"}),Cm=(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(fe.run))return vo;let p=pl(e,n.closedStart,"start"),y=pl(e,n.closedEnd-1,"end");if(p.mapped===null)return{kind:"map",piece:p};if(y.mapped===null)return{kind:"map",piece:y};if(e.isCut&&e.clusters===void 0)return xm;let f=t(e.offset+fl(e,n.closedStart)),m=t(e.offset+Rl(e,n.closedEnd-1)-1)+1;n.closedEnd=-1;let R=e.clusters;R==null?a(f,m,s):a(R.clusterStarts[f-R.start],R.clusterEnds[m-1-R.start],s),o.charge(fe.run);continue}if(c!==null&&n.periodicEnd>=0){if(!o.fits(ut))return vo;let{period:p,continuation:y}=c,f=n.periodicEnd,m=Math.min(i.length,f+Math.max(ml,y.length)),R=f;for(;R+y.length<=m&&i.startsWith(y,R);)R+=y.length;let A=R+y.length>m&&m<i.length;if(!A)for(;R<i.length&&i.charCodeAt(R)===i.charCodeAt(R-p);)R++;if(o.charge((R-f)*fe.scan),A){n.periodicEnd=R;continue}n.periodicEnd=-1,n.last+=Math.floor((R-n.last-l.length)/p)*p,n.from=n.last+l.length-p+1;continue}if(n.from<0){if(n.runStart<0)return _m;n.closedStart=n.runStart,n.closedEnd=n.last+l.length,n.runStart=-1;continue}if(!o.fits(ut))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)*fe.scan),n.from=n.windowStart+n.window.length===i.length?-1:n.windowEnd;continue}o.charge((u+l.length-d)*fe.scan);let h=n.windowStart+u;(n.runStart<0||h>=n.last+l.length)&&(n.runStart>=0&&(n.closedStart=n.runStart,n.closedEnd=n.last+l.length),n.runStart=h),n.last=h,c===null?n.from=h+1:n.periodicEnd=h+l.length}};function*No(e,t,r){let n=Math.floor(ut/t);for(;!e.done();)r.fits(n*t)||(yield),r.charge(e.advance(n)*t);return e.result()}function*Mm(e,t,r,n,o){if(t.length===0)return;let a=yield*No(Rs(e),fe.strip,n),i=[],l=[];yield*No(Ss(a.text,(c,d)=>{i.push(d),l.push(d+c.length)}),fe.split,n);let s=c=>a.rawIndex===null?c:a.rawIndex[c];for(let c=0;c<i.length;c++){n.fits(fe.line)||(yield),n.charge(fe.line);let d=i[c],u=a.text.slice(d,l[c]),h=yield*No(gs(u,r),fe.plan,n),p=[],y="";for(let m of h.chunks){let R="",A=[];for(let E of m){let S=(E.end-E.start)*fe.normalize;n.fits(S)||(yield);let g=bo(E.start===0&&E.end===u.length?u:u.slice(E.start,E.end),r).text;n.charge(S),g.length>0&&A.push({start:E.start,end:E.end,text:g,chunkStart:R.length}),R+=g}if(R.length!==0){y.length>0&&(y+=" ");for(let E of A)p.push({start:E.start,end:E.end,text:E.text,plainStart:y.length+E.chunkStart,mapped:null});y+=R}}if(y.length===0)continue;let f={offset:d,plain:y,pieces:p,isCut:!Dm(h,u),lastPiece:0,clusters:void 0};for(let m of t){let R=Im();for(;;){let A=Cm(f,s,m,R,n,o);if(A.kind==="done")break;if(A.kind==="slice"){yield;continue}if(A.kind==="clusters"){f.clusters=yield*Am(e,s(d),s(d+u.length-1)+1,n);continue}let{piece:E}=A,S=(E.end-E.start)*fe.map;n.fits(S)||(yield);let g=u.slice(E.start,E.end);E.mapped=bm(hs(g,go(g,r)),E.text),n.charge(S)}}}}function*Pm(e,t,r,n){let o=new Int32Array(ln.length),a=0,i=Lo;for(let l=0;l<=e;l+=dl){let s=Math.min(e+1,l+dl),c=(s-l)*fe.sweep;r.fits(c)||(yield);for(let d=l;d<s;d++){let u=Lo;for(let h=ln.length-1;h>=0;h--){let p=ln[h];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*km(e,t,r,n,o){let a=null;return yield*Mm(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*Pm(e.length,a,n,o)}var Lm=(e,t,r,n)=>{let o=wm(t),a=[],i=(s,c,d)=>(a.push(s,c,d),a.length<=3*r.maxRanges);return hl(function*(){return(yield*km(e,o,r.maxLength,n,i))?{dense:!1,ranges:a}:{dense:!0}}())};var Sl=(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)},gl=e=>{let t=[],r=(n,o)=>{typeof o=="string"&&o.length>0&&t.push({key:n,value:o})};for(let n of _a)r(pt.field(n),e[n]);e.interviewers.forEach((n,o)=>{r(pt.interviewer(o,"name"),n.name),r(pt.interviewer(o,"affiliation"),n.affiliation)}),e.attachments.forEach((n,o)=>{r(pt.attachment(o),n.fileName)}),e.externalComments.forEach((n,o)=>{r(pt.comment($n(o),"author"),n.name),r(pt.comment($n(o),"content"),n.text)});for(let n of e.postedComments)r(pt.comment(n.id,"author"),n.userName),r(pt.comment(n.id,"content"),n.content);return t};function*vm(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)*fe.linear;t.fits(a)||(yield),r=qn(r,e,n,o),t.charge(a)}return r}var bl=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:h,value:p}of c.fields){if(!d&&o+p.length>t.maxUnits)return null;let y=await i(hl(vm(p,n))),f=await i(Lm(p,c.alternatives,{maxLength:fo,maxRanges:t.maxFieldRanges},n));if(o+=p.length,f.dense){u[h]={fingerprint:y,dense:!0};continue}if(u[h]={fingerprint:y,ranges:f.ranges},a+=f.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(h=>h.reportHubId)};s.push({reportHubId:d.reportHubId,matchedSets:d.matchedSets,fields:u})}return{reports:s,deferred:[]}};import{and as Fm,asc as Tl,eq as pn,inArray as $m,isNull as Um}from"drizzle-orm";import{and as Dl,asc as Nm,eq as dn,getColumns as Om,sql as Hm}from"drizzle-orm";var gt=e=>Om(e),Ie=(e,t)=>{if(!e)return null;let r=e instanceof Date?e:new Date(e);if(Number.isNaN(r.getTime()))return typeof e=="string"?e:null;let n=r.getFullYear(),o=n<0?`-${String(-n).padStart(4,"0")}`:String(n).padStart(4,"0"),a=String(r.getMonth()+1).padStart(2,"0"),i=String(r.getDate()).padStart(2,"0");if(t==="YYYY-MM-DD")return`${o}-${a}-${i}`;let l=String(r.getHours()).padStart(2,"0"),s=String(r.getMinutes()).padStart(2,"0"),c=String(r.getSeconds()).padStart(2,"0");return`${o}-${a}-${i} ${l}:${s}:${c}`},Al=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=w=>Sr(i.sourceType,w),h=(w,L)=>on(a,w,c,L),p=Hm`CASE WHEN ${nn(a,c)} THEN 1 ELSE 0 END`,y=async w=>{let[L]=await t.select({id:i.id}).top(1).from(i).where(Dl(dn(i.id,w),nn(a,c)));return L!==void 0},f=w=>w==null||w===""?null:/^\d+$/.test(w)?n(Number(w)):w,m=()=>{let w={};for(let L of s)w[`ext_${L.sourceType}`]=gt(L.table);return w},R=w=>{let L=w;for(let x of s)L=L.leftJoin(x.table,Dl(dn(i.sourceType,x.sourceType),dn(i.sourceIdNum,x.idColumn)));return L},A=w=>{let{hub:L,internal:x}=w,q=L.summary,K=[],G=null,F=null,I=null,U=null,W=null,ce=null,ne=[],de=s.find(J=>J.sourceType===L.sourceType),Re=de?w[`ext_${de.sourceType}`]:void 0;if(de&&Re){let J=de.mapRow(Re);J.content!==void 0&&(q=J.content),J.employeeName!==void 0&&(ce=J.employeeName),J.category!==void 0&&(G=J.category),J.creationCategory!==void 0&&(F=J.creationCategory),J.visitTimeFrom!==void 0&&(I=J.visitTimeFrom),J.visitTimeTo!==void 0&&(U=J.visitTimeTo),J.customerName!==void 0&&(W=J.customerName),J.interviewers!==void 0&&(K=J.interviewers),J.externalComments!==void 0&&(ne=J.externalComments)}else L.sourceType===Ve&&x&&(q=x.body);return{content:q,author:w.creatorName??f(L.createdBy)??"",employeeName:ce??w.creatorName??f(L.createdBy),updatedBy:f(L.updatedBy),category:G,creationCategory:F,visitTimeFrom:I,visitTimeTo:U,customerName:W,interviewers:K,externalComments:ne}},E=w=>{if(w===1)return!0;if(w===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(w)}`)},S=w=>w.creationCategory!==null&&c.includes(w.creationCategory),g=(w,L)=>E(w.hasDraftLabel)?!0:S(L),C=async w=>{let[L]=await w.select({id:l.id}).top(1).from(l).where(dn(l.name,d)).orderBy(Nm(l.id));return L===void 0?null:L.id},D=()=>C(t);return{visibleSourceTypeCondition:u,draftVisibleTo:h,draftLabelFlag:p,isDraftReport:y,externalSelections:m,applyExternalJoins:R,resolveHubDisplayFields:A,readCanonicalDraftLabelId:C,getDraftLabelId:D,resolveCreationCategoryDraftLabelId:w=>w.some(S)?D():Promise.resolve(null),mapHubRecord:(w,L,x,q,K)=>{let{hub:G}=L,F=L.labels.map(W=>({id:W.id,name:W.name,color:W.color})),I=L.postedCommentRows,U=we(w.commentable,G.sourceType);return q!==null&&S(x)&&!F.some(W=>W.id===q)&&F.push({id:q,name:d,color:null}),{reportHubId:G.id,date:Ie(G.businessDate,"YYYY-MM-DD"),author:x.author,userId:G.userId?n(G.userId):"",sourceType:G.sourceType,createdAt:Ie(G.createdAt,"YYYY-MM-DD HH:mm:ss"),updatedAt:Ie(G.updatedAt,"YYYY-MM-DD HH:mm:ss"),updatedBy:x.updatedBy,employeeName:x.employeeName,category:x.category,creationCategory:x.creationCategory,visitTimeFrom:x.visitTimeFrom,visitTimeTo:x.visitTimeTo,customerName:x.customerName,interviewers:x.interviewers,subject:G.title,content:x.content,externalComments:U?x.externalComments:[],isRead:L.isRead??!1,isStarred:L.isStarred??!1,isDraft:g(L,x),labels:F,postedComments:I.filter(W=>as({authorUserId:W.userId},G.sourceType,K,w)).map(W=>({...W,userId:n(W.userId),isMine:K?W.userId===K:!1})),attachments:L.attachments}}}};var El=(e,{draftVisibleTo:t,visibleSourceTypeCondition:r})=>{let{db:n,tables:o,logger:a,settings:i}=e,{hub:l}=o,{attachmentDelivery:s}=i,c=(y,f)=>f!=null?"absent":y!=null?"present":"unknown";return{getAttachmentsByHubIds:async y=>{let f=new Map,m=o.attachment;if(y.length===0||!m||s===null)return f;let R=s.idCodec,A=s.thumbnails!==null,E=await n.select({id:m.id,hubId:m.hubId,fileName:m.fileName,fileType:m.fileType,fileSize:m.fileSize,createdAt:m.createdAt,objectCheckedAt:m.objectCheckedAt,objectMissingAt:m.objectMissingAt}).from(m).where($m(m.hubId,y)).orderBy(Tl(m.createdAt),Tl(m.id));for(let S of E){let g=S.fileType?String(S.fileType):null,C=S.fileSize!=null?Number(S.fileSize):null,D=c(S.objectCheckedAt,S.objectMissingAt),_={id:R.encode(Number(S.id)),fileName:String(S.fileName),fileType:g,fileSize:C,createdAt:Ie(S.createdAt,"YYYY-MM-DD HH:mm:ss"),state:D,hasThumbnail:A&&D!=="absent"&&Vr({fileType:g,fileSize:C},s.maxBytes)},H=f.get(Number(S.hubId));H?H.push(_):f.set(Number(S.hubId),[_])}return f},getAttachmentForUser:async(y,f,m)=>{let R=o.attachment;return!R||He(y.visible)?null:(await n.select({fileName:R.fileName,filePath:R.filePath,fileType:R.fileType,fileSize:R.fileSize}).top(1).from(R).innerJoin(l,pn(l.id,R.hubId)).where(Fm(pn(R.id,f),Um(l.deletedAt),t(m,"author"),r(y.visible))))[0]??null},markAttachmentMissing:async y=>{let f=o.attachment;if(!f)return;let m=new Date;try{await n.update(f).set({objectCheckedAt:m,objectMissingAt:m,updatedAt:m}).where(pn(f.id,y))}catch(R){a.error("markAttachmentMissing failed",R)}},markAttachmentPresent:async y=>{let f=o.attachment;if(!f)return;let m=new Date;try{await n.update(f).set({objectCheckedAt:m,objectMissingAt:null,updatedAt:m}).where(pn(f.id,y))}catch(R){a.error("markAttachmentPresent failed",R)}}}};import{eq as Oo}from"drizzle-orm";import{and as Bm,eq as wl,isNull as Vm}from"drizzle-orm";var Xt=async(e,t,r,n)=>{if((await e.update(t).set({deletedAt:null}).output().where(Bm(wl(t.id,r),Vm(t.deletedAt),n===null?void 0:wl(t.userId,n)))).length===0)throw new Error("Not Found")};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,{dateEpochPrefix:h,detailEpochPrefix:p}=e.settings.redisKeys,{hub:y,comment:f}=a,m=async(S,g)=>{if(g!==null)return await t(S)?g:void 0},R=async(S,g,C,D,_,H)=>{let w=await r(S,C,g);if(!we(S.commentable,w.sourceType))throw new Error("Comments are restricted by the viewer's comment permission");if(w.sourceType.toLowerCase()!==Ve.toLowerCase())throw new Error("Comments are restricted for external daily report sources");let L=await m(C,w.userId),x=await d(),q=await c(async I=>{await Xt(I,y,C,null);let[U]=await I.insert(f).output().values({hubId:C,userId:g,body:D,createdAt:new Date,createdBy:String(g),updatedAt:new Date,updatedBy:String(g)});return x!==null&&await x.writeHubs(I,[C]),U}),[K]=await o.select({displayName:i.displayName}).top(1).from(i).where(Oo(i.id,g)),G=K?.displayName??"";if(_){let I=Ue(_);I&&(s.invalidatePrefix(Jt(I)),await n(`${h}${I}`))}s.invalidatePrefix(ze(C)),await n(`${p}${C}`);let F={id:q.id,userId:l(q.userId),userName:G,content:q.body,createdAt:Ie(q.createdAt,"YYYY-MM-DD HH:mm:ss")??"",isMine:!0};return await u(Mn.parse({type:"comment-add",reportHubId:C,comment:F,clientTempId:H,recipientRawUserId:L,sourceType:w.sourceType}),"addComment"),F},A=async(S,g)=>await S.select().top(1).from(f).where(Oo(f.id,g));return{addComment:R,deleteComment:async(S,g,C,D,_,H)=>{let w=await A(o,D);if(w.length===0)throw new Error("Not Found");if(w[0].hubId!==C)throw new Error("Not Found");let L=await r(S,w[0].hubId,g);if(w[0].userId!==g)throw new Error("Unauthorized");let x=await m(C,L.userId),q=await d();if(await c(async K=>{await Xt(K,y,C,null),await K.delete(f).where(Oo(f.id,D)),q!==null&&await q.writeHubs(K,[C])}),_){let K=Ue(_);K&&(s.invalidatePrefix(Jt(K)),await n(`${h}${K}`))}s.invalidatePrefix(ze(C)),await n(`${p}${C}`),await u(Pn.parse({type:"comment-delete",reportHubId:C,commentId:D,clientTempId:H,recipientRawUserId:x,sourceType:L.sourceType}),"deleteComment")}}};import{and as xl,eq as Ut,isNull as qm}from"drizzle-orm";var _l=e=>e===Ve;var Cl=e=>e===""?null:e,Ml=(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:h,settings:p,draftVisibilityTables:y}=e,{idsEpoch:f,dateEpochPrefix:m,detailEpochPrefix:R}=e.settings.redisKeys,{hub:A,internal:E,hubLabel:S,userStatus:g}=l,{canonicalDraftLabelName:C,draftLabelNames:D}=p,_=async(F,I,U,W)=>{if(!Mr(U))throw Q("createDailyReport: businessDate","a business-date key in the canonical form YYYY-MM-DD naming a day from 0001-01-01 to 9999-12-31",U);if(!we(F.visible,Ve))throw new Error("Forbidden");c.info("createDailyReport called",{userId:I,businessDate:U});let ce=await u();try{let ne=await d(async b=>{c.info("Starting transaction");let N=await t(b);if(N===null)throw new Error(`[daily-report] createDailyReport: the canonical draft label ${JSON.stringify(C)} (draftLabelNames[0]) does not exist; create that label before creating reports (a report without it would be visible to every viewer)`);let v=`internal-temp-${Date.now()}-${Math.random()}`,[k]=await b.insert(A).output().values({sourceType:Ve,sourceId:v,businessDate:new Date(`${U}T00:00:00Z`),userId:I,title:"(\u7121\u984C)",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)});return await b.update(A).set({sourceId:String(k.id)}).where(Ut(A.id,k.id)),c.info("Hub created",k),await b.insert(E).values({hubId:k.id,body:"",createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),c.info("Internal created"),await b.insert(S).values({hubId:k.id,labelId:N,createdAt:new Date,createdBy:String(I)}),c.info("Label assigned"),await b.insert(g).values({hubId:k.id,userId:I,isRead:!0,isStarred:!1,createdAt:new Date,createdBy:String(I),updatedAt:new Date,updatedBy:String(I)}),ce!==null&&await ce.writeHubs(b,[k.id]),k.id});s.invalidatePrefix(Qt(U,I)),s.invalidatePrefix(wo(I)),await a(f),await a(`${m}${U}`);let de=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),ne,I,{forceRefresh:!0});if(de===null)throw new Error(`[daily-report] createDailyReport: report ${ne} was committed but its detail read returned nothing`);let Re=await r(de.reportHubId);await h(vn.parse({type:"report-create",reportHubId:de.reportHubId,report:de,clientTempId:W,recipientRawUserId:Re?I:void 0,actorRawUserId:I}),"createDailyReport");let J=await n(F,ne,I,{forceRefresh:!0});if(J===null)throw new Error(`[daily-report] createDailyReport: the actor's scope cannot read report ${ne} it just created`);return J}catch(ne){throw c.error("Error in createDailyReport",ne),ne}},H=async(F,I)=>await F.select().top(1).from(A).where(Ut(A.id,I)),w=async(F,I,U)=>{await o(F,I,U);let[W]=await H(i,I);if(W===void 0||W.deletedAt)throw new Error("Not Found");if(!_l(W.sourceType))throw new Error("Forbidden");if(W.userId!==U)throw new Error("Unauthorized");return W},L=async(F,I,U)=>{await F.update(A).set(U).where(Ut(A.id,I))},x=async(F,I,U)=>{await F.update(E).set(U).where(Ut(E.hubId,I))};return{createDailyReport:_,updateDailyReport:async(F,I,U,W,ce)=>{let ne=await w(F,I,U),de=await u();await d(async b=>{await Xt(b,A,I,U),W.title!==void 0&&await L(b,I,{title:Cl(W.title),updatedAt:new Date,updatedBy:String(U)}),W.content!==void 0&&await x(b,I,{body:Cl(W.content),updatedAt:new Date,updatedBy:String(U)}),de!==null&&await de.writeHubs(b,[I])}),s.invalidatePrefix(ze(I)),await a(`${R}${I}`);let Re=Ue(Ie(ne.businessDate,"YYYY-MM-DD"));Re&&(s.invalidatePrefix(Jt(Re)),await a(`${m}${Re}`));let J=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,U,{forceRefresh:!0});if(J){let b=await r(I);await h(Nn.parse({type:"report-update",reportHubId:J.reportHubId,report:J,clientTempId:ce,recipientRawUserId:b?U:void 0,actorRawUserId:U}),"updateDailyReport")}},publishDailyReport:async(F,I,U,W)=>{let ce=await w(F,I,U),ne=await u();if(await d(async b=>{await Xt(b,A,I,U),await b.delete(S).where(xl(Ut(S.hubId,I),Qs(y,D))),ne!==null&&await ne.writeHubs(b,[I])}),s.invalidatePrefix(ze(I)),s.invalidatePrefix(wt),await a(f),ce.businessDate){let b=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));b&&await a(`${m}${b}`)}let de=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));de&&s.invalidatePrefix(Qt(de,U));let Re=await n(Ze.unrestricted("post-write event payload: SSE delivery filters it for each recipient"),I,U,{forceRefresh:!0});if(Re===null)return null;let J=await r(I);return await h(On.parse({type:"report-publish",reportHubId:Re.reportHubId,report:Re,clientTempId:W,recipientRawUserId:J?U:void 0,actorRawUserId:U}),"publishDailyReport"),await n(F,I,U,{forceRefresh:!0})},deleteDailyReport:async(F,I,U,W)=>{let ce=await w(F,I,U);if(await d(async ne=>{if((await ne.update(A).set({deletedAt:new Date,deletedBy:String(U),updatedAt:new Date,updatedBy:String(U)}).output().where(xl(Ut(A.id,I),Ut(A.userId,U),qm(A.deletedAt)))).length===0)throw new Error("Not Found")}),s.invalidatePrefix(ze(I)),s.invalidatePrefix(wt),await a(f),ce.businessDate){let ne=Ue(Ie(ce.businessDate,"YYYY-MM-DD"));ne&&await a(`${m}${ne}`)}await h(Lr.parse({type:"report-delete",reportHubId:I,clientTempId:W,sourceType:ce.sourceType}),"deleteDailyReport")}}};import{and as Zt,asc as Pl,desc as Cr,eq as Pe,inArray as Ho,isNull as mn,sql as jm}from"drizzle-orm";var kl=vr([]),Wm=6e4,$o=(e,t)=>{let r="the request's AbortSignal (new AbortController().signal for a call that is never aborted)";if(t===void 0)throw We(`${e}: options.signal`,r);if(typeof t!="object"||t===null)throw Q(`${e}: options`,"an object carrying the request's AbortSignal",t);let{signal:n}=t;if(n===void 0)throw We(`${e}: options.signal`,r);if(!(n instanceof AbortSignal))throw Q(`${e}: options.signal`,r,n);return n},Uo=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}}},Ym=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 (${Ma(t.error)})`);return t.data}),Ll=(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:h,tables:p,users:y,resolveUserId:f,cache:m,epochs:R,logger:A,settings:E}=e,{idsEpoch:S,dateEpochPrefix:g,detailEpochPrefix:C}=e.settings.redisKeys,{hub:D,internal:_,comment:H,label:w,hubLabel:L,userStatus:x}=p,q=E.idsTtlMs,K=E.businessDateTtlMs,G=async(M,P)=>(await h.select({reportHubId:D.id,businessDate:D.businessDate,sourceType:D.sourceType}).from(D).where(Zt(mn(D.deletedAt),t(P,"author-or-authorless"),r(M.visible))).orderBy(Cr(D.businessDate),Cr(D.id))).map($=>({...$,businessDate:Ie($.businessDate,"YYYY-MM-DD")})),F=async(M,P,T)=>{let $=await U(P);return $?He(M.visible)?[]:(await h.select({reportHubId:D.id,businessDate:D.businessDate,sourceType:D.sourceType}).top(T).from(D).where(Zt(mn(D.deletedAt),t($,"author-or-authorless"),r(M.visible))).orderBy(Cr(D.businessDate),Cr(D.id))).map(he=>({...he,businessDate:Ie(he.businessDate,"YYYY-MM-DD")})):[]},I=new Map,U=async M=>{if(!E.disableUserIdCache&&I.has(M))return I.get(M)??null;let P=await f(M);return P!==null&&!E.disableUserIdCache&&I.set(M,P),P},W=async(M,P,{forceRefresh:T=!1,snapshot:$=!1,ttlMsOverride:j,onFetchStart:he,admission:Oe}={})=>{let Ae=await U(P);if(!Ae)return{items:[],streamAnchor:null,snapshot:kl};if(He(M.visible))return{items:[],streamAnchor:await d(),snapshot:kl};let ye=_s(Ae,Kr(M)),[Se]=await m.getOrFetch({cacheKey:ye,fetcher:async()=>{let je=await d(),rt=await G(M,Ae);if(!Ta(rt)){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 re=[...rt].sort(Fn);return[{items:re,streamAnchor:je,snapshot:vr(re)}]}return[{items:rt,streamAnchor:je,snapshot:vr(rt)}]},onFetchStart:he,forceRefresh:T,snapshot:$,admission:Oe,ttlMsOverride:j??q,epochKey:S,refreshAheadRatio:.5});if(Se===void 0)throw new Error("[daily-report] getDailyReportIdsByExternalId: the ids cache returned no record");return Se},ce=async(M,P,T)=>{let $=await a(h.select({hub:gt(D),internal:gt(_),isRead:x.isRead,isStarred:x.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(D)).leftJoin(_,Pe(D.id,_.hubId)).leftJoin(x,Zt(Pe(D.id,x.hubId),Pe(x.userId,P))).leftJoin(y,Pe(D.userId,y.id)).where(Zt(T,mn(D.deletedAt),t(P,"author"),r(M.visible))).orderBy(Cr(D.id));if($.length===0)return[];let j=$.map(re=>re.hub.id),he=await h.select({hubId:L.hubId,id:w.id,name:w.name,color:w.color}).from(L).innerJoin(w,Pe(L.labelId,w.id)).where(Ho(L.hubId,j)),Oe=await h.select({hubId:H.hubId,id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,Pe(H.userId,y.id)).where(Ho(H.hubId,j)).orderBy(Pl(H.createdAt)),Ae=await c(j),ye=new Map,Se=new Map;for(let re of he){let Le=ye.get(re.hubId);Le||(Le=[],ye.set(re.hubId,Le)),Le.push({id:re.id,name:re.name,color:re.color})}for(let re of Oe){let Le=Se.get(re.hubId);Le||(Le=[],Se.set(re.hubId,Le)),Le.push({id:re.id,content:re.body,createdAt:Ie(re.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:re.userId,userName:re.userName||""})}let je=$.map(re=>Fo(()=>i(re))),rt=await l(je.flatMap(re=>re.ok?[re.value]:[]));return $.map((re,Le)=>{let dt=re.hub.id,Ct=je[Le],Dt=Ct.ok?Fo(()=>s(M,{...re,attachments:Ae.get(dt)??[],labels:ye.get(dt)||[],postedCommentRows:Se.get(dt)||[]},Ct.value,rt,P)):Ct;return Dt.ok?{reportHubId:dt,outcome:"ok",report:Dt.value}:{reportHubId:dt,outcome:"failed",cause:Dt.cause}})},ne=async(M,P,T)=>(await ce(M,P,T)).map($=>{if($.outcome==="failed")throw $.cause;return $.report}),de=M=>Ce({windowMs:Wm,tallies:["failed"],writeSuppressed:(P,{count:T,since:$})=>{A.warn(`failed_report_suppressed count=${T} since=${$} read=${M} report=${P}`)}}),Re={markDailyReportSearchHits:de("markDailyReportSearchHits"),getDailyReportDetailsByIdsByExternalId:de("getDailyReportDetailsByIdsByExternalId")},J=(M,P,T)=>{Re[M].record(P,"failed",()=>A.error(`${M}: report ${P} passed the visibility predicate but its own assembly failed`,T))},b=(M,P)=>{let T=P.outcome==="ok"?Ym(P.report):{ok:!1,cause:P.cause};return T.ok?{reportHubId:P.reportHubId,outcome:"ok",report:T.value}:(J(M,P.reportHubId,T.cause),{reportHubId:P.reportHubId,outcome:"failed"})},N=async(M,P,T,{read:$,signal:j,slicing:he})=>{let Oe=await ce(M,P,Ho(D.id,[...T]));j.throwIfAborted();let Ae=[],ye=he.now();for(let Se of Oe)Ae.length>0&&he.now()-ye>=he.sliceMs&&(await he.pause(),ye=he.now()),Ae.push(b($,Se));return Ae},v=async(M,P,T,{forceRefresh:$=!1,snapshot:j=!1,ttlMsOverride:he,admission:Oe}={})=>{let Ae=await U(T);if(!Ae)return[];let ye=Ue(P);if(!ye)return[];if(He(M.visible))return[];let Se=xs(ye,Ae,Kr(M));return m.getOrFetch({cacheKey:Se,fetcher:()=>ne(M,Ae,Pe(D.businessDate,jm`${ye}`)),forceRefresh:$,snapshot:j,admission:Oe,ttlMsOverride:he??K,epochKey:`${g}${ye}`})},k=async(M,P,T,{forceRefresh:$=!1,snapshot:j=!1,ttlMsOverride:he,admission:Oe}={})=>{if(He(M.visible))return null;let Ae=Cs(P,T,Kr(M));return(await m.getOrFetch({cacheKey:Ae,fetcher:async()=>{let Se=await a(h.select({hub:gt(D),internal:gt(_),isRead:x.isRead,isStarred:x.isStarred,creatorName:y.displayName,hasDraftLabel:n,...o()}).from(D)).leftJoin(_,Pe(D.id,_.hubId)).leftJoin(x,Zt(Pe(D.id,x.hubId),Pe(x.userId,T))).leftJoin(y,Pe(D.userId,y.id)).where(Zt(Pe(D.id,P),mn(D.deletedAt),t(T,"author"),r(M.visible)));if(Se.length===0)return[];let je=Se[0].hub.id,rt=await h.select({id:w.id,name:w.name,color:w.color}).from(L).innerJoin(w,Pe(L.labelId,w.id)).where(Pe(L.hubId,je)),re=await h.select({id:H.id,body:H.body,createdAt:H.createdAt,userId:H.userId,userName:y.displayName}).from(H).leftJoin(y,Pe(H.userId,y.id)).where(Pe(H.hubId,je)).orderBy(Pl(H.createdAt)),Le=await c([je]),dt=rt.map(Ge=>({id:Ge.id,name:Ge.name,color:Ge.color})),Ct=re.map(Ge=>({id:Ge.id,content:Ge.body,createdAt:Ie(Ge.createdAt,"YYYY-MM-DD HH:mm:ss")||"",userId:Ge.userId,userName:Ge.userName||""})),Dt=i(Se[0]),Dn=await l([Dt]);return[s(M,{...Se[0],attachments:Le.get(je)??[],labels:dt,postedCommentRows:Ct},Dt,Dn,T)]},forceRefresh:$,snapshot:j,admission:Oe,ttlMsOverride:he??K,epochKey:`${C}${P}`}))[0]??null};return{getUserIdByExternalId:U,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:F,getDailyReportsByBusinessDateByExternalId:v,getDailyReportDetailById:k,getDailyReportDetailByIdByExternalId:async(M,P,T,$={})=>{let j=await U(T);return j?k(M,P,j,$):null},getDailyReportDetailsByIdsByExternalId:async(M,P,T,$)=>{let j=$o("getDailyReportDetailsByIdsByExternalId",$);if(P.length>xe.maxDetailIds)throw Q("getDailyReportDetailsByIdsByExternalId: reportHubIds",`at most ${xe.maxDetailIds} ids`,P.length);let he=await U(T);if(!he||P.length===0||He(M.visible))return P.map(pr);j.throwIfAborted();let Oe=await N(M,he,P,{read:"getDailyReportDetailsByIdsByExternalId",signal:j,slicing:Uo(j)}),Ae=new Map(Oe.map(ye=>[ye.reportHubId,ye]));return P.map(ye=>{let Se=Ae.get(ye);return Se===void 0?pr(ye):Se})},fetchDeliveredHubOutcomes:N,invalidateHubReadCaches:async(M,P)=>{m.invalidatePrefix(wt),await u(S);for(let T of new Set(M))m.invalidatePrefix(ze(T)),await u(`${C}${T}`);for(let T of new Set(P)){let $=Ue(T);$&&await u(`${g}${$}`)}},clearCache:async()=>{m.clearAll(),I.clear(),R&&await u(S),A.info("Server-side DB/SQL caches cleared successfully.")}}};var zm="v4",Gm=/^(?!:)[^\s\p{Cc}]+(?<!:)$/u,Bo=e=>{if(typeof e!="string"||!Gm.test(e))throw Q("redisKeyPrefix",'a Redis key prefix of one or more characters without whitespace or control characters, neither starting nor ending with ":"',e);return Object.freeze({sseStream:`${e}:sse-stream:${zm}`,idsEpoch:`${e}:ids:epoch`,dateEpochPrefix:`${e}:date-epoch:`,detailEpochPrefix:`${e}:detail-epoch:`})};var yn=Object.freeze({idsTtlMs:18e4,businessDateTtlMs:3e5,redisKeyPrefix:"daily-report",streamMaxLen:1e4}),Km=e=>{let{length:t}=e;if(t===void 0)throw Q("tables.hub.title","a character column with a declared length",t);return ie("tables.hub.title.length",t,1)},Jm=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 Q("draftLabelNames","one or more non-blank label names",e);return Object.freeze([...e])},Qm=e=>{let t=new Map([[Ve.toLowerCase(),`the internal source type ${JSON.stringify(Ve)}`]]);for(let[r,{sourceType:n}]of e.entries()){let o=`externalSources[${r}].sourceType`,a=t.get(n.toLowerCase());if(a!==void 0)throw Q(o,`a source type that differs, ignoring case, from ${a}`,n);t.set(n.toLowerCase(),`${o} ${JSON.stringify(n)}`)}return Object.freeze([Ve,...e.map(r=>r.sourceType)])},vl=e=>{let t=e.externalSources??[],r=Jm(e.draftLabelNames);if(jr(e),Object.hasOwn(e,"streamKey"))throw We("redisKeyPrefix","given in place of the removed key streamKey");let n=$i(e.attachments),o=Km(e.tables.hub.title);ho(e.tables.hub.sourceType);let a=ve("idsTtlMs",e.idsTtlMs,1,yn.idsTtlMs),i=ve("businessDateTtlMs",e.businessDateTtlMs,1,yn.businessDateTtlMs),l=ve("streamMaxLen",e.streamMaxLen,1,yn.streamMaxLen),s=Bo(e.redisKeyPrefix===void 0?yn.redisKeyPrefix:e.redisKeyPrefix);return Object.freeze({externalSources:t,sourceTypes:Qm(t),draftLabelNames:r,canonicalDraftLabelName:r[0],attachmentDelivery:n,titleMaxLength:o,idsTtlMs:a,businessDateTtlMs:i,streamMaxLen:l,redisKeys:s,disableUserIdCache:!!e.disableUserIdCache})};var Nl=({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),h=Buffer.byteLength(u);if(h>6356992){t.warn(`[SSE] Event too large (${c}): ${h} bytes > ${6356992}; not published`);return}let p=se();try{await d.xAdd(n,"*",{data:u},{TRIM:{strategy:"MAXLEN",strategyModifier:"~",threshold:o}});let y=se()-p;y>1e3&&t.warn(`[SSE] Slow publish (${c}): ${y}ms`)}catch(y){t.error(`[SSE] Redis publish failed (${c}):`,y)}},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?Tt:c.id}catch(s){return t.error("SSE stream anchor read failed",s),null}}});import{and as Zm,eq as ey,sql as De}from"drizzle-orm";var hn=["hubId","userId","isRead","isStarred","createdAt","createdBy","updatedAt","updatedBy"],ty={isRead:{statusType:"read",callerName:"setReadStatus"},isStarred:{statusType:"star",callerName:"setStarStatus"}},qe=e=>De`${De.identifier(e.name)}`,ry=(e,t,{reportHubId:r,userId:n,value:o,at:a})=>{let i=String(n),l=qe(e[t]),s=(p,y)=>De`t.${qe(p)} = CASE WHEN t.${l} = ${o} THEN t.${qe(p)} ELSE ${y} END`,c={hubId:De`s.${qe(e.hubId)}`,userId:De`s.${qe(e.userId)}`,isRead:De`${t==="isRead"?o:!1}`,isStarred:De`${t==="isStarred"?o:!1}`,createdAt:De`${a}`,createdBy:De`${i}`,updatedAt:De`${a}`,updatedBy:De`${i}`},d=De.join(hn.map(p=>qe(e[p])),De`, `),u=De.join(hn.map(p=>c[p]),De`, `),h=De.join(hn.map(p=>De`inserted.${qe(e[p])} AS ${De.identifier(p)}`),De`, `);return De`MERGE ${e} WITH (HOLDLOCK) AS t USING (SELECT ${r} AS ${qe(e.hubId)}, ${n} AS ${qe(e.userId)}) AS s ON t.${qe(e.hubId)} = s.${qe(e.hubId)} AND t.${qe(e.userId)} = s.${qe(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 ${h};`},Nl=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Ol=e=>e instanceof Date||typeof e=="string",ry=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(", ")},ny=(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||!Nl(a.hubId,t)||!Nl(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Ol(a.createdAt)||!Ol(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 ${ry(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Hl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{dateEpochPrefix:l,detailEpochPrefix:s}=e.settings.redisKeys,{hub:c,userStatus:d}=o,u=async(m,R)=>{let[T]=await n.select({sourceType:c.sourceType,userId:c.userId,deletedAt:c.deletedAt}).top(1).from(c).where(Xm(Zm(c.id,m),t(R,"author")));return T??null},h=async(m,R,T)=>{let E=await u(R,T);if(!E||E.deletedAt||!we(m.visible,E.sourceType))throw new Error("Not Found");return{sourceType:E.sourceType,userId:E.userId}},p=async(m,R,T,E,S,g,C)=>{await h(R,E,T);let A={reportHubId:E,userId:T,value:g,at:new Date},_=ny(await n.execute(ty(d,m,A)),A);if(S){let k=Ue(S);k&&(a.invalidatePrefix(Qt(k,T)),await r(`${l}${k}`))}a.invalidatePrefix(Io(E,T)),await r(`${s}${E}`);let{statusType:H,callerName:w}=ey[m];return await i(Cn.parse({type:"status-update",reportHubId:E,recipientRawUserId:T,statusType:H,value:g,clientTempId:C}),w),_};return{assertHubMutable:h,setStarStatus:(m,R,T,E,S,g)=>p("isStarred",m,R,T,E,S,g),setReadStatus:(m,R,T,E,S,g)=>p("isRead",m,R,T,E,S,g)}};var sy=Object.freeze([]),Vo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Sn=(e,t)=>e.get(t)??sy,Fl=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Xr);function qo(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:h,hubLabel:p}=r,y=Ll(e),{externalSources:f,draftLabelNames:m,attachmentDelivery:R,titleMaxLength:T}=y,E=be(e.logger,1,"Service"),S=ee=>iy(me=>t.transaction(Z=>me(()=>ee(Z))),e.transactionRetry),g=e.search===void 0?null:Ks(e.search,f.map(ee=>ee.sourceType)),C={hub:c,hubLabel:p,label:h},A=g===null?null:sl({tables:{...C,search:g.tables},draftLabelNames:m});g!==null&&Ao();let _=null,H=async()=>{if(g===null)return null;if(_===null){let ee=await Ao(),me=g.externalSourceTexts;_=ul({hub:c,tables:g.tables,loadSources:(Z,oe)=>ze(Z,oe,me),inTransaction:S,normalizerVersion:ee})}return _},{incrementRedisEpoch:w,publishToSseStream:k,readSseStreamAnchor:x}=vl({redis:i,logger:E,epochs:s,streamKey:y.redisKeys.sseStream,streamMaxLen:y.streamMaxLen}),q={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:E,settings:y,draftVisibilityTables:C,inTransaction:S,publishToSseStream:k,prepareSearchIndex:H},{visibleSourceTypeCondition:K,draftVisibleTo:z,draftLabelFlag:F,isDraftReport:I,externalSelections:$,applyExternalJoins:j,resolveHubDisplayFields:ce,readCanonicalDraftLabelId:ne,getDraftLabelId:de,resolveCreationCategoryDraftLabelId:Re,mapHubRecord:J}=Al(q),{getAttachmentsByHubIds:b,getAttachmentForUser:v,markAttachmentMissing:L,markAttachmentPresent:P}=El(q,{draftVisibleTo:z,visibleSourceTypeCondition:K}),{getUserIdByExternalId:O,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:X,getDailyReportsByBusinessDateByExternalId:Y,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:D,getDailyReportDetailsByIdsByExternalId:N,fetchDeliveredHubOutcomes:U,invalidateHubReadCaches:G,clearCache:he}=kl(q,{draftVisibleTo:z,visibleSourceTypeCondition:K,draftLabelFlag:F,externalSelections:$,applyExternalJoins:j,resolveHubDisplayFields:ce,resolveCreationCategoryDraftLabelId:Re,mapHubRecord:J,getAttachmentsByHubIds:b,readSseStreamAnchor:x,incrementRedisEpoch:w}),{assertHubMutable:Oe,setStarStatus:Ae,setReadStatus:ye}=Hl(q,{draftVisibleTo:z,incrementRedisEpoch:w}),{addComment:Se,deleteComment:qe}=Il(q,{isDraftReport:I,assertHubMutable:Oe,incrementRedisEpoch:w}),{createDailyReport:rt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:dt}=Cl(q,{readCanonicalDraftLabelId:ne,isDraftReport:I,getDailyReportDetailById:M,assertHubMutable:Oe,incrementRedisEpoch:w}),Ct=async(ee,me)=>{let Z=new Map,oe=r.attachment;if(!oe||R===null)return Z;let Ee=await ee.select({hubId:oe.hubId,fileName:oe.fileName}).from(oe).where(Rn(oe.hubId,[...me])).orderBy(bt(oe.hubId),bt(oe.createdAt),bt(oe.id));for(let ae of Ee)Vo(Z,Number(ae.hubId),String(ae.fileName));return Z},Dt=async(ee,me,Z)=>{let oe=new Map;for(let[Ee,ae]of Z){let nt=new Map;for(let{hub:Fe}of me)Fe.sourceType===Ee&&Fe.sourceIdNum!==null&&nt.set(Fe.sourceIdNum,Fe.id);if(nt.size===0)continue;let At=await ae(ee,[...nt.keys()]);for(let[Fe,ot]of At){let Mt=nt.get(Fe);if(Mt===void 0)throw Q(`search.externalSourceTexts.${Ee} answer key`,"a source id that was asked for",Fe);if(!(Array.isArray(ot)&&ot.every(er=>typeof er=="string")))throw Q(`search.externalSourceTexts.${Ee} answer for ${Fe}`,"an array of strings",ot);oe.set(Mt,ot)}}return oe},Dn=(ee,me)=>{let Z=ce(ee),oe=[["subject",ee.hub.title],["content",Z.content],["author",Z.author],["employeeName",Z.employeeName],["updatedBy",Z.updatedBy],["category",Z.category],["creationCategory",Z.creationCategory],["customerName",Z.customerName]];for(let ae of Z.interviewers)oe.push(["interviewerName",ae.name??null],["interviewerAffiliation",ae.affiliation??null]);for(let ae of me.labelNames)oe.push(["label",ae]);for(let ae of me.attachmentNames)oe.push(["attachment",ae]);for(let ae of me.extraTexts)oe.push(["extra",ae]);let Ee=[];for(let ae of Z.externalComments)Ee.push({authorUserId:null,text:Fl(ae.name,ae.text)});for(let ae of me.postedComments)Ee.push({authorUserId:ae.userId,text:Fl(ae.userName,ae.body)});return{hubId:ee.hub.id,fields:oe,comments:Ee,filterValues:{authorName:Z.employeeName,customerName:Z.customerName}}},ze=async(ee,me,Z)=>{let oe=[];for(let Ee of oy(me,ay)){let ae=await j(ee.select({hub:gt(c),internal:gt(d),creatorName:n.displayName,...$()}).from(c)).leftJoin(d,fn(c.id,d.hubId)).leftJoin(n,fn(c.userId,n.id)).where(Rn(c.id,[...Ee])).orderBy(bt(c.id)),nt=new Map,At=await ee.select({hubId:p.hubId,name:h.name}).from(p).innerJoin(h,fn(p.labelId,h.id)).where(Rn(p.hubId,[...Ee])).orderBy(bt(p.hubId),bt(h.id));for(let Ge of At)Vo(nt,Ge.hubId,Ge.name);let Fe=new Map,ot=await ee.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,[...Ee])).orderBy(bt(u.hubId),bt(u.createdAt),bt(u.id));for(let Ge of ot)Vo(Fe,Ge.hubId,Ge);let Mt=await Ct(ee,Ee),er=await Dt(ee,ae,Z);for(let Ge of ae){let $e=Ge.hub.id;oe.push(Dn(Ge,{labelNames:Sn(nt,$e),postedComments:Sn(Fe,$e),attachmentNames:Sn(Mt,$e),extraTexts:Sn(er,$e)}))}}return oe},ac=(ee,me,Z)=>A===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):A.search(t,{criteria:Z,viewerUserId:me,scope:ee}),Wo=y.sourceTypes,ic=async(ee,me)=>{if(A===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Z=Wo.filter(ae=>we(ee.visible,ae)),oe=await A.facetValues(t,{column:"authorName",viewerUserId:me,scope:ee}),Ee=await A.facetValues(t,{column:"customerName",viewerUserId:me,scope:ee});return{sourceTypes:Z,authors:oe,customers:Ee}},sc=async(ee,me,Z,oe,Ee)=>{let ae=$o("markDailyReportSearchHits",Ee);if(A===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(oe.length>xe.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${xe.maxDetailIds} ids`,oe.length);let nt=Nr(gr(Z));if(oe.length===0||He(ee.visible))return{wordsDigest:nt,reports:[],deferred:[]};ae.throwIfAborted();let At=Uo(ae),Fe=await U(ee,me,oe,{read:"markDailyReportSearchHits",signal:ae,slicing:At});await At.pause();let ot=Fe.flatMap($e=>$e.outcome==="ok"?[{reportHubId:$e.reportHubId,fields:gl($e.report)}]:[]),Mt=Z.combine==="union"&&Z.sets.length>=2&&ot.length>0?await A.matchedSets(t,{plan:Z,viewerUserId:me,scope:ee,ids:ot.map($e=>$e.reportHubId)}):null,er=ot.map(({reportHubId:$e,fields:cc})=>{let Yo=Mt===null?null:Mt.get($e),zo=Yo===void 0?0:Yo;return{reportHubId:$e,matchedSets:zo,alternatives:Sl(Z,zo).flatMap(uc=>uc.alternatives),fields:cc}}),Ge=await bl(er,xr,At.pause,yl(xr,At.now));return{wordsDigest:nt,reports:Ge.reports,deferred:Ge.deferred}},lc=async ee=>{let me=await H();if(me===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return me.reconcile(t,ee)};return{streamKey:y.redisKeys.sseStream,attachmentDelivery:R,titleMaxLength:T,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:Wo,clearCache:he,invalidateHubReadCaches:G,getUserIdByExternalId:O,getDailyReportIdsByExternalId:W,getDailyReportIdsFirstPageByExternalId:X,readSseStreamAnchor:x,getDailyReportsByBusinessDateByExternalId:Y,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:D,getDailyReportDetailsByIdsByExternalId:N,getDraftLabelId:de,searchDailyReports:ac,markDailyReportSearchHits:sc,listDailyReportSearchFacets:ic,reconcileSearchIndex:lc,getAttachmentsByHubIds:b,getAttachmentForUser:v,markAttachmentMissing:L,markAttachmentPresent:P,setStarStatus:Ae,setReadStatus:ye,addComment:Se,deleteComment:qe,createDailyReport:rt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:dt}}var ly=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(be(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return be(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as $l,sql as cy}from"drizzle-orm";import{bigint as _e,bit as Ul,date as uy,datetime2 as ke,foreignKey as tt,index as xt,int as dy,mssqlSchema as py,nvarchar as ue,primaryKey as Bt,uniqueIndex as my}from"drizzle-orm/mssql-core";function yy(e,t){let r=py(e),n=t.userTable,o=r.table("DailyReportHub",{id:_e("id",{mode:"number"}).identity().notNull(),sourceType:ue("source_type",{length:20}).notNull(),sourceId:ue("source_id",{length:100}).notNull(),sourceIdNum:_e("source_id_num",{mode:"number"}).generatedAlwaysAs(cy`TRY_CAST(source_id AS BIGINT)`),businessDate:uy("business_date"),userId:_e("user_id",{mode:"number"}),title:ue("title",{length:200}),summary:ue("summary",{length:"max"}),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull(),deletedAt:ke("deleted_at"),deletedBy:ue("deleted_by",{length:50})},u=>[Bt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),tt({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($l(u.businessDate),$l(u.id)),xt(`${e}_DailyReportHub_deleted_at_index`).on(u.deletedAt)]),a=r.table("DailyReportInternal",{hubId:_e("hub_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}),metadata:ue("metadata",{length:"max"}),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),tt({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:_e("id",{mode:"number"}).identity().notNull(),hubId:_e("hub_id",{mode:"number"}).notNull(),userId:_e("user_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({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:_e("id",{mode:"number"}).identity().notNull(),userId:_e("user_id",{mode:"number"}),name:ue("name",{length:50}).notNull(),color:ue("color",{length:20}),sortOrder:dy("sort_order"),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:_e("hub_id",{mode:"number"}).notNull(),labelId:_e("label_id",{mode:"number"}).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),tt({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:_e("hub_id",{mode:"number"}).notNull(),userId:_e("user_id",{mode:"number"}).notNull(),isRead:Ul("is_read").default(!1).notNull(),isStarred:Ul("is_starred").default(!1).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),tt({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:_e("id",{mode:"number"}).identity().notNull(),hubId:_e("hub_id",{mode:"number"}).notNull(),uploadedBy:_e("uploaded_by",{mode:"number"}),sourceKey:ue("source_key",{length:200}).notNull(),fileName:ue("file_name",{length:255}).notNull(),filePath:ue("file_path",{length:"max"}).notNull(),fileType:ue("file_type",{length:100}),fileSize:_e("file_size",{mode:"number"}),objectCheckedAt:ke("object_checked_at"),objectMissingAt:ke("object_missing_at"),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),my(`${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 jo,binary as Bl,datetime2 as hy,int as fy,mssqlSchema as Ry,nvarchar as gn,primaryKey as Vl,varchar as Sy}from"drizzle-orm/mssql-core";function gy(e){let t=Ry(e),r=t.table("DailyReportSearchDocument",{hubId:jo("hub_id",{mode:"number"}).notNull(),searchText:gn("search_text",{length:"max"}).notNull(),sourceDigest:Bl("source_digest",{length:32}).notNull(),normalizerVersion:Sy("normalizer_version",{length:64}).notNull(),indexedAt:hy("indexed_at").notNull(),rowVersion:Bl("row_version",{length:8}).notNull(),authorName:gn("author_name",{length:mt.maxValueLength}),customerName:gn("customer_name",{length:mt.maxValueLength})},o=>[Vl({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:jo("hub_id",{mode:"number"}).notNull(),ordinal:fy("ordinal").notNull(),authorUserId:jo("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 by=5e7,Zl=2e8,Dy=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,jl=4,Wl=16,Yl=50,zl=2,bn=Object.freeze({renderMs:Be.renderMs,nanosecondsPerBlockVisit:ql,margin:jl,maxBlockVisits:Math.floor(Be.renderMs*1e6/(ql*jl)),walkBudgetMs:Wl,nanosecondsPerWalkStep:Yl,walkMargin:zl,maxWalkSteps:Math.floor(Wl*1e6/(Yl*zl))}),Ay=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",Ty=1,Ey={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},wy=[/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:bi(e)}),rc=(e,t)=>{switch(t){case"jpeg":{let r=lo(e);return r===null?null:tc(r)}case"png":{let r=Ti(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ei(e,bn.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},nc=(e,t)=>{let r=Ay.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},Iy=(e,t,r)=>{let n=rc(e,t);return n===null?null:nc(n,r)},_y=e=>e!==null&&e<=Zl,xy=(e,t)=>{if(t!=="jpeg")return rc(e,t);let r=Di(e,bn);return r===null||r.blockVisits>bn.maxBlockVisits?null:tc(r.header)},Cy=e=>{let t=e instanceof Error?e.message:"";return wy.some(r=>r.test(t))?"failed":"unsupported"},My=e=>{e.cache(!1),e.concurrency(Dy),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(Ey)});let t=async(n,o,a,i,l)=>{let s=xy(n,o);if(s===null)return Xl;try{let c=e(n,{limitInputPixels:by,animated:!1});if(!_y(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:Cy(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${Ty}`,render:r}};var oc=6e4,Py=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[h,p]of o)p.expiresAt<=s&&o.delete(h);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function ND(e){e.redis||be(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=qo({...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,Os as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,oc as DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,Ar as DailyReportSseReader,Ze as DailyReportViewerScope,or as SqlResultCache,Bo as buildDailyReportRedisKeys,xo as createDailyReportHandlers,ND as createDailyReportServer,qo as createDailyReportService,Py as createDailyReportVisibilityCache,In as createEpochStore,My as createSharpThumbnailRenderer,Hn as dailyReportSseStreamMessageSchema,yy as defineDailyReportSchema,gy as defineDailyReportSearchSchema,Wt as encodeIdsStreamRows,St as isStreamIdLte,zn as parseClientTempId,Iy as predictSharpThumbnailWorkingSetBytes,Dr as readDailyReportSseStreamEntry,ly as transformJsonArray};
|
|
14
|
+
OUTPUT ${h};`},Ol=(e,t)=>(typeof e=="number"||typeof e=="string")&&String(e)===String(t),Hl=e=>e instanceof Date||typeof e=="string",ny=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(", ")},oy=(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||!Ol(a.hubId,t)||!Ol(a.userId,r)||typeof a.isRead!="boolean"||typeof a.isStarred!="boolean"||!Hl(a.createdAt)||!Hl(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 ${ny(n)}`);return{hubId:t,userId:r,isRead:a.isRead,isStarred:a.isStarred,createdAt:a.createdAt,createdBy:a.createdBy,updatedAt:a.updatedAt,updatedBy:a.updatedBy}},Fl=(e,{draftVisibleTo:t,incrementRedisEpoch:r})=>{let{db:n,tables:o,cache:a,publishToSseStream:i}=e,{dateEpochPrefix:l,detailEpochPrefix:s}=e.settings.redisKeys,{hub:c,userStatus:d}=o,u=async(m,R)=>{let[A]=await n.select({sourceType:c.sourceType,userId:c.userId,deletedAt:c.deletedAt}).top(1).from(c).where(Zm(ey(c.id,m),t(R,"author")));return A??null},h=async(m,R,A)=>{let E=await u(R,A);if(!E||E.deletedAt||!we(m.visible,E.sourceType))throw new Error("Not Found");return{sourceType:E.sourceType,userId:E.userId}},p=async(m,R,A,E,S,g,C)=>{await h(R,E,A);let D={reportHubId:E,userId:A,value:g,at:new Date},_=oy(await n.execute(ry(d,m,D)),D);if(S){let L=Ue(S);L&&(a.invalidatePrefix(Qt(L,A)),await r(`${l}${L}`))}a.invalidatePrefix(Io(E,A)),await r(`${s}${E}`);let{statusType:H,callerName:w}=ty[m];return await i(Cn.parse({type:"status-update",reportHubId:E,recipientRawUserId:A,statusType:H,value:g,clientTempId:C}),w),_};return{assertHubMutable:h,setStarStatus:(m,R,A,E,S,g)=>p("isStarred",m,R,A,E,S,g),setReadStatus:(m,R,A,E,S,g)=>p("isRead",m,R,A,E,S,g)}};var ly=Object.freeze([]),Vo=(e,t,r)=>{let n=e.get(t);n?n.push(r):e.set(t,[r])},Sn=(e,t)=>e.get(t)??ly,$l=(e,t)=>[e,t].filter(r=>typeof r=="string"&&r.length>0).join(Xr);function qo(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:h,hubLabel:p}=r,y=vl(e),{externalSources:f,draftLabelNames:m,attachmentDelivery:R,titleMaxLength:A}=y,E=be(e.logger,1,"Service"),S=ee=>sy(me=>t.transaction(Z=>me(()=>ee(Z))),e.transactionRetry),g=e.search===void 0?null:Ks(e.search,f.map(ee=>ee.sourceType)),C={hub:c,hubLabel:p,label:h},D=g===null?null:sl({tables:{...C,search:g.tables},draftLabelNames:m});g!==null&&Ao();let _=null,H=async()=>{if(g===null)return null;if(_===null){let ee=await Ao(),me=g.externalSourceTexts;_=ul({hub:c,tables:g.tables,loadSources:(Z,oe)=>Ge(Z,oe,me),inTransaction:S,normalizerVersion:ee})}return _},{incrementRedisEpoch:w,publishToSseStream:L,readSseStreamAnchor:x}=Nl({redis:i,logger:E,epochs:s,streamKey:y.redisKeys.sseStream,streamMaxLen:y.streamMaxLen}),q={db:t,tables:r,users:n,resolveUserId:o,encodeUserId:a,cache:l,epochs:s,logger:E,settings:y,draftVisibilityTables:C,inTransaction:S,publishToSseStream:L,prepareSearchIndex:H},{visibleSourceTypeCondition:K,draftVisibleTo:G,draftLabelFlag:F,isDraftReport:I,externalSelections:U,applyExternalJoins:W,resolveHubDisplayFields:ce,readCanonicalDraftLabelId:ne,getDraftLabelId:de,resolveCreationCategoryDraftLabelId:Re,mapHubRecord:J}=Al(q),{getAttachmentsByHubIds:b,getAttachmentForUser:N,markAttachmentMissing:v,markAttachmentPresent:k}=El(q,{draftVisibleTo:G,visibleSourceTypeCondition:K}),{getUserIdByExternalId:O,getDailyReportIdsByExternalId:Y,getDailyReportIdsFirstPageByExternalId:X,getDailyReportsByBusinessDateByExternalId:z,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:P,getDailyReportDetailsByIdsByExternalId:T,fetchDeliveredHubOutcomes:$,invalidateHubReadCaches:j,clearCache:he}=Ll(q,{draftVisibleTo:G,visibleSourceTypeCondition:K,draftLabelFlag:F,externalSelections:U,applyExternalJoins:W,resolveHubDisplayFields:ce,resolveCreationCategoryDraftLabelId:Re,mapHubRecord:J,getAttachmentsByHubIds:b,readSseStreamAnchor:x,incrementRedisEpoch:w}),{assertHubMutable:Oe,setStarStatus:Ae,setReadStatus:ye}=Fl(q,{draftVisibleTo:G,incrementRedisEpoch:w}),{addComment:Se,deleteComment:je}=Il(q,{isDraftReport:I,assertHubMutable:Oe,incrementRedisEpoch:w}),{createDailyReport:rt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:dt}=Ml(q,{readCanonicalDraftLabelId:ne,isDraftReport:I,getDailyReportDetailById:M,assertHubMutable:Oe,incrementRedisEpoch:w}),Ct=async(ee,me)=>{let Z=new Map,oe=r.attachment;if(!oe||R===null)return Z;let Ee=await ee.select({hubId:oe.hubId,fileName:oe.fileName}).from(oe).where(Rn(oe.hubId,[...me])).orderBy(bt(oe.hubId),bt(oe.createdAt),bt(oe.id));for(let ae of Ee)Vo(Z,Number(ae.hubId),String(ae.fileName));return Z},Dt=async(ee,me,Z)=>{let oe=new Map;for(let[Ee,ae]of Z){let nt=new Map;for(let{hub:Fe}of me)Fe.sourceType===Ee&&Fe.sourceIdNum!==null&&nt.set(Fe.sourceIdNum,Fe.id);if(nt.size===0)continue;let At=await ae(ee,[...nt.keys()]);for(let[Fe,ot]of At){let Mt=nt.get(Fe);if(Mt===void 0)throw Q(`search.externalSourceTexts.${Ee} answer key`,"a source id that was asked for",Fe);if(!(Array.isArray(ot)&&ot.every(er=>typeof er=="string")))throw Q(`search.externalSourceTexts.${Ee} answer for ${Fe}`,"an array of strings",ot);oe.set(Mt,ot)}}return oe},Dn=(ee,me)=>{let Z=ce(ee),oe=[["subject",ee.hub.title],["content",Z.content],["author",Z.author],["employeeName",Z.employeeName],["updatedBy",Z.updatedBy],["category",Z.category],["creationCategory",Z.creationCategory],["customerName",Z.customerName]];for(let ae of Z.interviewers)oe.push(["interviewerName",ae.name??null],["interviewerAffiliation",ae.affiliation??null]);for(let ae of me.labelNames)oe.push(["label",ae]);for(let ae of me.attachmentNames)oe.push(["attachment",ae]);for(let ae of me.extraTexts)oe.push(["extra",ae]);let Ee=[];for(let ae of Z.externalComments)Ee.push({authorUserId:null,text:$l(ae.name,ae.text)});for(let ae of me.postedComments)Ee.push({authorUserId:ae.userId,text:$l(ae.userName,ae.body)});return{hubId:ee.hub.id,fields:oe,comments:Ee,filterValues:{authorName:Z.employeeName,customerName:Z.customerName}}},Ge=async(ee,me,Z)=>{let oe=[];for(let Ee of ay(me,iy)){let ae=await W(ee.select({hub:gt(c),internal:gt(d),creatorName:n.displayName,...U()}).from(c)).leftJoin(d,fn(c.id,d.hubId)).leftJoin(n,fn(c.userId,n.id)).where(Rn(c.id,[...Ee])).orderBy(bt(c.id)),nt=new Map,At=await ee.select({hubId:p.hubId,name:h.name}).from(p).innerJoin(h,fn(p.labelId,h.id)).where(Rn(p.hubId,[...Ee])).orderBy(bt(p.hubId),bt(h.id));for(let Ke of At)Vo(nt,Ke.hubId,Ke.name);let Fe=new Map,ot=await ee.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,[...Ee])).orderBy(bt(u.hubId),bt(u.createdAt),bt(u.id));for(let Ke of ot)Vo(Fe,Ke.hubId,Ke);let Mt=await Ct(ee,Ee),er=await Dt(ee,ae,Z);for(let Ke of ae){let $e=Ke.hub.id;oe.push(Dn(Ke,{labelNames:Sn(nt,$e),postedComments:Sn(Fe,$e),attachmentNames:Sn(Mt,$e),extraTexts:Sn(er,$e)}))}}return oe},ic=(ee,me,Z)=>D===null?Promise.reject(new Error("[daily-report] searchDailyReports: the search setting is not configured")):D.search(t,{criteria:Z,viewerUserId:me,scope:ee}),Wo=y.sourceTypes,sc=async(ee,me)=>{if(D===null)throw new Error("[daily-report] listDailyReportSearchFacets: the search setting is not configured");let Z=Wo.filter(ae=>we(ee.visible,ae)),oe=await D.facetValues(t,{column:"authorName",viewerUserId:me,scope:ee}),Ee=await D.facetValues(t,{column:"customerName",viewerUserId:me,scope:ee});return{sourceTypes:Z,authors:oe,customers:Ee}},lc=async(ee,me,Z,oe,Ee)=>{let ae=$o("markDailyReportSearchHits",Ee);if(D===null)throw new Error("[daily-report] markDailyReportSearchHits: the search setting is not configured");if(oe.length>xe.maxDetailIds)throw Q("markDailyReportSearchHits: reportHubIds",`at most ${xe.maxDetailIds} ids`,oe.length);let nt=Nr(gr(Z));if(oe.length===0||He(ee.visible))return{wordsDigest:nt,reports:[],deferred:[]};ae.throwIfAborted();let At=Uo(ae),Fe=await $(ee,me,oe,{read:"markDailyReportSearchHits",signal:ae,slicing:At});await At.pause();let ot=Fe.flatMap($e=>$e.outcome==="ok"?[{reportHubId:$e.reportHubId,fields:gl($e.report)}]:[]),Mt=Z.combine==="union"&&Z.sets.length>=2&&ot.length>0?await D.matchedSets(t,{plan:Z,viewerUserId:me,scope:ee,ids:ot.map($e=>$e.reportHubId)}):null,er=ot.map(({reportHubId:$e,fields:uc})=>{let Yo=Mt===null?null:Mt.get($e),zo=Yo===void 0?0:Yo;return{reportHubId:$e,matchedSets:zo,alternatives:Sl(Z,zo).flatMap(dc=>dc.alternatives),fields:uc}}),Ke=await bl(er,xr,At.pause,yl(xr,At.now));return{wordsDigest:nt,reports:Ke.reports,deferred:Ke.deferred}},cc=async ee=>{let me=await H();if(me===null)throw new Error("[daily-report] reconcileSearchIndex: the search setting is not configured");return me.reconcile(t,ee)};return{streamKey:y.redisKeys.sseStream,attachmentDelivery:R,titleMaxLength:A,searchLimits:g===null?null:{concurrency:g.concurrency,rateLimitPerMinute:g.rateLimitPerMinute},searchFilterSourceTypes:Wo,clearCache:he,invalidateHubReadCaches:j,getUserIdByExternalId:O,getDailyReportIdsByExternalId:Y,getDailyReportIdsFirstPageByExternalId:X,readSseStreamAnchor:x,getDailyReportsByBusinessDateByExternalId:z,getDailyReportDetailById:M,getDailyReportDetailByIdByExternalId:P,getDailyReportDetailsByIdsByExternalId:T,getDraftLabelId:de,searchDailyReports:ic,markDailyReportSearchHits:lc,listDailyReportSearchFacets:sc,reconcileSearchIndex:cc,getAttachmentsByHubIds:b,getAttachmentForUser:N,markAttachmentMissing:v,markAttachmentPresent:k,setStarStatus:Ae,setReadStatus:ye,addComment:Se,deleteComment:je,createDailyReport:rt,updateDailyReport:re,publishDailyReport:Le,deleteDailyReport:dt}}var cy=(e,t,r,n)=>{if(!e)return[];try{let o=JSON.parse(e);return Array.isArray(o)?o.map(r).filter(a=>a!==null):(be(n,1,"ExternalSource").warn(`Unexpected ${t} format: not an array`),[])}catch(o){return be(n,1,"ExternalSource").warn(`Failed to parse ${t}:`,o),[]}};import{desc as Ul,sql as uy}from"drizzle-orm";import{bigint as _e,bit as Bl,date as dy,datetime2 as ke,foreignKey as tt,index as xt,int as py,mssqlSchema as my,nvarchar as ue,primaryKey as Bt,uniqueIndex as yy}from"drizzle-orm/mssql-core";function hy(e,t){let r=my(e),n=t.userTable,o=r.table("DailyReportHub",{id:_e("id",{mode:"number"}).identity().notNull(),sourceType:ue("source_type",{length:20}).notNull(),sourceId:ue("source_id",{length:100}).notNull(),sourceIdNum:_e("source_id_num",{mode:"number"}).generatedAlwaysAs(uy`TRY_CAST(source_id AS BIGINT)`),businessDate:dy("business_date"),userId:_e("user_id",{mode:"number"}),title:ue("title",{length:200}),summary:ue("summary",{length:"max"}),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull(),deletedAt:ke("deleted_at"),deletedBy:ue("deleted_by",{length:50})},u=>[Bt({name:`${e}_DailyReportHub_pk`,columns:[u.id]}),tt({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:_e("hub_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}),metadata:ue("metadata",{length:"max"}),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportInternal_pk`,columns:[u.hubId]}),tt({name:`${e}_DailyReportInternal_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]})]),i=r.table("DailyReportComment",{id:_e("id",{mode:"number"}).identity().notNull(),hubId:_e("hub_id",{mode:"number"}).notNull(),userId:_e("user_id",{mode:"number"}).notNull(),body:ue("body",{length:"max"}).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportComment_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportComment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({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:_e("id",{mode:"number"}).identity().notNull(),userId:_e("user_id",{mode:"number"}),name:ue("name",{length:50}).notNull(),color:ue("color",{length:20}),sortOrder:py("sort_order"),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportLabel_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportLabel_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),s=r.table("DailyReportHub_Label",{hubId:_e("hub_id",{mode:"number"}).notNull(),labelId:_e("label_id",{mode:"number"}).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportHub_Label_pk`,columns:[u.hubId,u.labelId]}),tt({name:`${e}_DailyReportHub_Label_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportHub_Label_label_id_fk`,columns:[u.labelId],foreignColumns:[l.id]})]),c=r.table("DailyReportUserStatus",{hubId:_e("hub_id",{mode:"number"}).notNull(),userId:_e("user_id",{mode:"number"}).notNull(),isRead:Bl("is_read").default(!1).notNull(),isStarred:Bl("is_starred").default(!1).notNull(),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportUserStatus_pk`,columns:[u.hubId,u.userId]}),tt({name:`${e}_DailyReportUserStatus_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportUserStatus_user_id_fk`,columns:[u.userId],foreignColumns:[n.id]})]),d=r.table("DailyReportAttachment",{id:_e("id",{mode:"number"}).identity().notNull(),hubId:_e("hub_id",{mode:"number"}).notNull(),uploadedBy:_e("uploaded_by",{mode:"number"}),sourceKey:ue("source_key",{length:200}).notNull(),fileName:ue("file_name",{length:255}).notNull(),filePath:ue("file_path",{length:"max"}).notNull(),fileType:ue("file_type",{length:100}),fileSize:_e("file_size",{mode:"number"}),objectCheckedAt:ke("object_checked_at"),objectMissingAt:ke("object_missing_at"),createdAt:ke("created_at").notNull(),createdBy:ue("created_by",{length:50}).notNull(),updatedAt:ke("updated_at").notNull(),updatedBy:ue("updated_by",{length:50}).notNull()},u=>[Bt({name:`${e}_DailyReportAttachment_pk`,columns:[u.id]}),tt({name:`${e}_DailyReportAttachment_hub_id_fk`,columns:[u.hubId],foreignColumns:[o.id]}),tt({name:`${e}_DailyReportAttachment_uploaded_by_fk`,columns:[u.uploadedBy],foreignColumns:[n.id]}),yy(`${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 jo,binary as Vl,datetime2 as fy,int as Ry,mssqlSchema as Sy,nvarchar as gn,primaryKey as ql,varchar as gy}from"drizzle-orm/mssql-core";function by(e){let t=Sy(e),r=t.table("DailyReportSearchDocument",{hubId:jo("hub_id",{mode:"number"}).notNull(),searchText:gn("search_text",{length:"max"}).notNull(),sourceDigest:Vl("source_digest",{length:32}).notNull(),normalizerVersion:gy("normalizer_version",{length:64}).notNull(),indexedAt:fy("indexed_at").notNull(),rowVersion:Vl("row_version",{length:8}).notNull(),authorName:gn("author_name",{length:mt.maxValueLength}),customerName:gn("customer_name",{length:mt.maxValueLength})},o=>[ql({name:`${e}_DailyReportSearchDocument_pk`,columns:[o.hubId]})]),n=t.table("DailyReportSearchComment",{hubId:jo("hub_id",{mode:"number"}).notNull(),ordinal:Ry("ordinal").notNull(),authorUserId:jo("author_user_id",{mode:"number"}),commentText:gn("comment_text",{length:"max"}).notNull()},o=>[ql({name:`${e}_DailyReportSearchComment_pk`,columns:[o.hubId,o.ordinal]})]);return{document:r,comment:n}}var Dy=5e7,ec=2e8,Ay=1,tc=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})})}),jl=125,Wl=4,Yl=16,zl=50,Gl=2,bn=Object.freeze({renderMs:Be.renderMs,nanosecondsPerBlockVisit:jl,margin:Wl,maxBlockVisits:Math.floor(Be.renderMs*1e6/(jl*Wl)),walkBudgetMs:Yl,nanosecondsPerWalkStep:zl,walkMargin:Gl,maxWalkSteps:Math.floor(Yl*1e6/(zl*Gl))}),Ty=new Map([["uchar",1],["char",1],["ushort",2],["short",2],["uint",4],["int",4],["float",4],["complex",8],["double",8]]),Kl=75,Jl=4,Ql="#ffffff",Ey=1,wy={png:"VipsForeignLoadPngBuffer",jpeg:"VipsForeignLoadJpegBuffer",gif:"VipsForeignLoadNsgifBuffer",webp:"VipsForeignLoadWebpBuffer"},Iy=[/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/],Xl=Object.freeze({ok:!1,reason:"failed"}),Zl=Object.freeze({ok:!1,reason:"unsupported"}),rc=e=>({layout:e.multiScan?"jpeg-multi-scan":"jpeg-single-scan",coefficientBytes:bi(e)}),nc=(e,t)=>{switch(t){case"jpeg":{let r=lo(e);return r===null?null:rc(r)}case"png":{let r=Ti(e);return r===null?null:{layout:r?"png-interlaced":"png",coefficientBytes:0}}case"gif":return{layout:"gif",coefficientBytes:0};case"webp":{let r=Ei(e,bn.maxWalkSteps);return r===null?null:{layout:`webp-${r}`,coefficientBytes:0}}}},oc=(e,t)=>{let r=Ty.get(t.depth);if(r===void 0)return null;let n=t.channels*r,o=tc,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},_y=(e,t,r)=>{let n=nc(e,t);return n===null?null:oc(n,r)},xy=e=>e!==null&&e<=ec,Cy=(e,t)=>{if(t!=="jpeg")return nc(e,t);let r=Di(e,bn);return r===null||r.blockVisits>bn.maxBlockVisits?null:rc(r.header)},My=e=>{let t=e instanceof Error?e.message:"";return Iy.some(r=>r.test(t))?"failed":"unsupported"},Py=e=>{e.cache(!1),e.concurrency(Ay),e.block({operation:["VipsForeignLoad"]}),e.unblock({operation:Object.values(wy)});let t=async(n,o,a,i,l)=>{let s=Cy(n,o);if(s===null)return Zl;try{let c=e(n,{limitInputPixels:Dy,animated:!1});if(!xy(oc(s,await c.metadata())))return Zl;if(l.aborted)return Xl;let d=await c.rotate().resize({width:a,height:i,fit:"inside",withoutEnlargement:!0}).flatten({background:Ql}).webp({quality:Kl,effort:Jl}).toBuffer();return{ok:!0,bytes:new Uint8Array(d),contentType:"image/webp"}}catch(c){return{ok:!1,reason:My(c)}}},r=async(n,{format:o,maxWidth:a,maxHeight:i,signal:l})=>l.aborted?Xl:t(n,o,a,i,l);return{id:`sharp-${e.versions.sharp}/vips-${e.versions.vips}/webp-q${Kl}-e${Jl}/flatten-${Ql}/v${Ey}`,render:r}};var ac=6e4,ky=e=>{let t=ie("ttlMs",e.ttlMs,1,ac),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[h,p]of o)p.expiresAt<=s&&o.delete(h);o.set(l,{expiresAt:s+t,answer:d});let u=()=>{o.get(l)?.answer===d&&o.delete(l)};return d.catch(u),d}};function $D(e){e.redis||be(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=qo({...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,ec as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_BUDGET_BYTES,bn as DAILY_REPORT_SHARP_THUMBNAIL_DECODE_WORK_MODEL,tc as DAILY_REPORT_SHARP_THUMBNAIL_WORKING_SET_MODEL,_o as DAILY_REPORT_SSE_CATCH_UP_BATCH,Os as DAILY_REPORT_SSE_VISIBILITY_REFRESH_MS,ac as DAILY_REPORT_VISIBILITY_MAX_CACHE_TTL_MS,Ar as DailyReportSseReader,Ze as DailyReportViewerScope,or as SqlResultCache,Bo as buildDailyReportRedisKeys,xo as createDailyReportHandlers,$D as createDailyReportServer,qo as createDailyReportService,ky as createDailyReportVisibilityCache,In as createEpochStore,Py as createSharpThumbnailRenderer,Hn as dailyReportSseStreamMessageSchema,hy as defineDailyReportSchema,by as defineDailyReportSearchSchema,Wt as encodeIdsStreamRows,St as isStreamIdLte,zn as parseClientTempId,_y as predictSharpThumbnailWorkingSetBytes,Dr as readDailyReportSseStreamEntry,cy as transformJsonArray};
|
|
15
15
|
/* v8 ignore next -- @preserve 到達不能: 時間切れと中断の購読はどちらも cleanup で同時に外れ、枠を渡すときも先に cleanup するので、列にいない待機者でここへは来ない。それでも splice(-1) が別の待機者を消さないよう残す */
|