@aiquants/daily-report 0.24.0 → 0.26.0

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