@transai/connector-runner-microsoft-office365-email 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,9 @@
1
+ ## 0.8.0 (2026-02-24)
2
+
3
+ ### 🧱 Updated Dependencies
4
+
5
+ - Updated @transai/connector-runtime-sdk to 0.9.0
6
+
1
7
  ## 0.7.1 (2026-02-12)
2
8
 
3
9
  ### 🧱 Updated Dependencies
package/index.cjs CHANGED
@@ -184,7 +184,7 @@ ${"".padEnd(t)}${"^".repeat(i)}`}function BK(e){return Fdt(Dy,e)}function Za(e){
184
184
  `):a).split(`
185
185
  `).map(n=>"> "+n).join(`
186
186
  `)})}function Oy(e,t){if(!t)return e;let i=typeof t[0]=="string"?t[0]:"[",r=typeof t[1]=="string"?t[1]:"]";return i+e+r}function $K(e,t,i,r,a){let n=typeof t=="function"?t(e,r,a):e;return n[0]==="/"&&i?m2t(i,"/")+n:n}function $2t(e,t,i,r){let a=e.attribs||{},n=a.alt?a.alt:"",s=a.src?$K(a.src,r.pathRewrite,r.baseUrl,i.metadata,e):"",A=s?n?n+" "+Oy(s,r.linkBrackets):Oy(s,r.linkBrackets):n;i.addInline(A,{noWordTransform:!0})}function tBt(e,t,i,r){function a(){if(r.ignoreHref||!e.attribs||!e.attribs.href)return"";let s=e.attribs.href.replace(/^mailto:/,"");return r.noAnchorUrl&&s[0]==="#"?"":(s=$K(s,r.pathRewrite,r.baseUrl,i.metadata,e),s)}let n=a();if(!n)t(e.children,i);else{let s="";i.pushWordTransform(c=>(c&&(s+=c),c)),t(e.children,i),i.popWordTransform(),r.hideLinkHrefIfSameAsText&&n===s||i.addInline(s?" "+Oy(n,r.linkBrackets):n,{noWordTransform:!0})}}function tj(e,t,i,r,a){let n=iu(e,["parent","name"])==="li",s=0,A=(e.children||[]).filter(c=>c.type!=="text"||!/^\s*$/.test(c.data)).map(function(c){if(c.name!=="li")return{node:c,prefix:""};let u=n?a().trimStart():a();return u.length>s&&(s=u.length),{node:c,prefix:u}});if(A.length){i.openList({interRowLineBreaks:1,leadingLineBreaks:n?1:r.leadingLineBreaks||2,maxPrefixLength:s,prefixAlign:"left"});for(let{node:c,prefix:u}of A)i.openListItem({prefix:u}),t([c],i),i.closeListItem();i.closeList({trailingLineBreaks:n?1:r.trailingLineBreaks||2})}}function eBt(e,t,i,r){let a=r.itemPrefix||" * ";return tj(e,t,i,r,()=>a)}function iBt(e,t,i,r){let a=Number(e.attribs.start||"1"),n=rBt(e.attribs.type);return tj(e,t,i,r,()=>" "+n(a++)+". ")}function rBt(e="1"){switch(e){case"a":return t=>YK(t,"a");case"A":return t=>YK(t,"A");case"i":return t=>KK(t).toLowerCase();case"I":return t=>KK(t);case"1":default:return t=>t.toString()}}function aBt(e){let t=[],i=[];for(let r of e)r.startsWith(".")?t.push(r.substring(1)):r.startsWith("#")&&i.push(r.substring(1));return{classes:t,ids:i}}function nBt(e,t){if(t===!0)return!0;if(!e)return!1;let{classes:i,ids:r}=aBt(t),a=(e.class||"").split(" "),n=(e.id||"").split(" ");return a.some(s=>i.includes(s))||n.some(s=>r.includes(s))}function sBt(e,t,i,r){return nBt(e.attribs,i.options.tables)?ej(e,t,i,r):ABt(e,t,i,r)}function ABt(e,t,i,r){i.openBlock({leadingLineBreaks:r.leadingLineBreaks}),t(e.children,i),i.closeBlock({trailingLineBreaks:r.trailingLineBreaks})}function ej(e,t,i,r){i.openTable(),e.children.forEach(n),i.closeTable({tableToString:s=>O2t(s,r.rowSpacing??0,r.colSpacing??3),leadingLineBreaks:r.leadingLineBreaks,trailingLineBreaks:r.trailingLineBreaks});function a(s){let A=+iu(s,["attribs","colspan"])||1,c=+iu(s,["attribs","rowspan"])||1;i.openTableCell({maxColumnWidth:r.maxColumnWidth}),t(s.children,i),i.closeTableCell({colspan:A,rowspan:c})}function n(s){if(s.type!=="tag")return;let A=r.uppercaseHeaderCells!==!1?c=>{i.pushWordTransform(u=>u.toUpperCase()),a(c),i.popWordTransform()}:a;switch(s.name){case"thead":case"tbody":case"tfoot":case"center":s.children.forEach(n);return;case"tr":{i.openTableRow();for(let c of s.children)if(c.type==="tag")switch(c.name){case"th":{A(c);break}case"td":{a(c);break}}i.closeTableRow();break}}}}var oBt=Object.freeze({__proto__:null,anchor:tBt,blockquote:X2t,dataTable:ej,heading:z2t,horizontalLine:W2t,image:$2t,lineBreak:K2t,orderedList:iBt,paragraph:V2t,pre:Z2t,table:sBt,unorderedList:eBt,wbr:j2t}),cBt={baseElements:{selectors:["body"],orderBy:"selectors",returnDomByDefault:!0},decodeEntities:!0,encodeCharacters:{},formatters:{},limits:{ellipsis:"...",maxBaseElements:void 0,maxChildNodes:void 0,maxDepth:void 0,maxInputLength:1<<24},longWordSplit:{forceWrapOnLimit:!1,wrapCharacters:[]},preserveNewlines:!1,selectors:[{selector:"*",format:"inline"},{selector:"a",format:"anchor",options:{baseUrl:null,hideLinkHrefIfSameAsText:!1,ignoreHref:!1,linkBrackets:["[","]"],noAnchorUrl:!0}},{selector:"article",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"aside",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"blockquote",format:"blockquote",options:{leadingLineBreaks:2,trailingLineBreaks:2,trimEmptyLines:!0}},{selector:"br",format:"lineBreak"},{selector:"div",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"footer",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"form",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"h1",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h2",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h3",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h4",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"h5",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"h6",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"header",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"hr",format:"horizontalLine",options:{leadingLineBreaks:2,length:void 0,trailingLineBreaks:2}},{selector:"img",format:"image",options:{baseUrl:null,linkBrackets:["[","]"]}},{selector:"main",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"nav",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"ol",format:"orderedList",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"p",format:"paragraph",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"pre",format:"pre",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"section",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"table",format:"table",options:{colSpacing:3,leadingLineBreaks:2,maxColumnWidth:60,rowSpacing:0,trailingLineBreaks:2,uppercaseHeaderCells:!0}},{selector:"ul",format:"unorderedList",options:{itemPrefix:" * ",leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"wbr",format:"wbr"}],tables:[],whitespaceCharacters:` \r
187
- \f\u200B`,wordwrap:80},uBt=(e,t,i)=>[...e,...t],ij=(e,t,i)=>[...t],lBt=(e,t,i)=>e.some(r=>typeof r=="object")?uBt(e,t):ij(e,t);function hBt(e={}){return e=(0,Ky.default)(cBt,e,{arrayMerge:ij,customMerge:t=>t==="selectors"?lBt:void 0}),e.formatters=Object.assign({},H2t,oBt,e.formatters),e.selectors=VK(e.selectors,(t=>t.selector)),gBt(e),D2t(e)}function rj(e,t={},i=void 0){return hBt(t)(e,i)}function gBt(e){if(e.tags){let i=Object.entries(e.tags).map(([r,a])=>({...a,selector:r||"*"}));e.selectors.push(...i),e.selectors=VK(e.selectors,(r=>r.selector))}function t(i,r,a){let n=r.pop();for(let s of r){let A=i[s];A||(A={},i[s]=A),i=A}i[n]=a}if(e.baseElement){let i=e.baseElement;t(e,["baseElements","selectors"],Array.isArray(i)?i:[i])}e.returnDomByDefault!==void 0&&t(e,["baseElements","returnDomByDefault"],e.returnDomByDefault);for(let i of e.selectors)i.format==="anchor"&&iu(i,["options","noLinkBrackets"])&&t(i,["options","linkBrackets"],!1)}var gB=class{async parsedToMailMessage(t,i,r,a){let n=[],s=[];i.headers.forEach((B,I)=>{n.push({key:String(I),header:Array.isArray(B)?B.join(", "):String(B)})}),i.headerLines.forEach(({key:B,line:I})=>{s.push({key:B,line:I})});let A=this.#t(i.to),c=this.#t(i.cc),u=this.#t(i.bcc),h=this.#t(i.from),g=this.#t(i.replyTo),d=typeof i.html=="string"?i.html:void 0,E=i.text||(d?rj(d):"");return{deltaLink:r,extraData:a,id:i.messageId??t.id,originalMessageId:t.internetMessageId,attachmentsCount:(i.attachments??[]).length,attachments:await this.#i(i.attachments??[]),headers:n,headerLines:s,subject:i.subject,conversationId:i.references?.[0],references:i.references,date:new Date(i.date??t.sentDateTime??new Date),to:A,from:h,fromDomain:h?.[0]?.split("@")[1],cc:c,bcc:u,replyTo:g,text:(E||"").trim(),html:d,messageId:i.messageId,inReplyTo:i.inReplyTo,categories:t.categories}}formatMailReplyBody(t,i){let r=t.from?.emailAddress?.address||"",a=t.toRecipients?.map(u=>u.emailAddress?.address).filter(Boolean).join("; ")||"",n=t.subject||"",s=t.sentDateTime?new Date(t.sentDateTime).toLocaleString():"",A=`<br><hr style="border:none;border-top:solid #b1b1b1 1px;height:1px;margin:16px 0 8px 0;" /><br>From: ${r}<br>Sent: ${s}<br>To: ${a}<br>Subject: ${n}<br><br>`,c=t.body?.content||"";return`${i}${A}${c}`}#t(t){if(!t)return;let i=a=>!a||typeof a!="object"?[]:"address"in a&&typeof a.address=="string"&&a.address?[a.address]:"group"in a&&Array.isArray(a.group)?a.group.flatMap(i):[];if("value"in t&&Array.isArray(t.value)){let a=t.value.flatMap(i).filter(Boolean);return a.length?a:void 0}if(Array.isArray(t)){let a=t.flatMap(i).filter(Boolean);return a.length?a:void 0}let r=i(t).filter(Boolean);return r.length?r:void 0}async#i(t){return(await Promise.all(t.map(async i=>{let r=i.contentType?.toLowerCase().includes("application/json")||i.filename?.toLowerCase().endsWith(".json"),a=await this.#e(i);if(!a&&!r)return;i=a??i;let n=Buffer.isBuffer(i.content)?i.content:await new Promise((s,A)=>{let c=[];i.content?.on?.("data",u=>c.push(u)),i.content?.once?.("end",()=>s(Buffer.concat(c))),i.content?.once?.("error",A)});return{id:i.cid,filename:i.filename||"attachment.json",contentType:"application/json",content:n.toString("utf-8")}}))).filter(i=>!!i)}async#e(t){if(!(t.contentType?.toLowerCase().includes("application/pdf")||t.filename?.toLowerCase().endsWith(".pdf")))return null;let r=await this.#r(t.content),a=await(0,aj.default)(r),n=`${t.filename?.replace(/\.pdf$/i,"")||"attachment"}.json`;return{...t,filename:n,contentType:"application/json",content:Buffer.from(a)}}async#r(t){return Buffer.isBuffer(t)?t:new Promise((i,r)=>{let a=[];t.on("data",n=>a.push(n)),t.once("end",()=>i(Buffer.concat(a))),t.once("error",r)})}};var xB=class{#t;#i;#e;#r;constructor(t,i,r){if(this.#e=t,this.#r=on.getInstance(),this.#t=i??new nE(this.#e.username,this.#e.emlTestMode??!1),this.#i=r??new gB,!this.#e.tenantId||!this.#e.clientId||!this.#e.clientSecret)throw new Error("Graph requires tenantId, clientId, and clientSecret")}async readMailbox(t,i,r,a=10){let n,s,A;try{if(await this.#n(),n=await this.#t.getFolder(t),!n)throw new Error(`Mailbox folder not found: ${t}`);let{mails:c,deltaLink:u}=await this.#t.getMails(n,i,r,a);s=c,A=u}catch(c){let u=`Failed to read email from mailbox ${t}: ${c?.message}`;throw this.#r.warn(u,{err:c}),new Error(u)}try{let c=[];for(let u of s.filter(Boolean)){let h=await this.#a(u,n,A);h&&c.push(h)}return{mails:c.sort((u,h)=>u.date.getTime()-h.date.getTime()),deltaLink:A}}catch(c){let u=`Failed to parse emails from mailbox ${t}: ${c?.message}`;throw this.#r.warn(u,{err:c}),new Error(u)}}async getAttachments(t){let i=await this.#t.getMail(t);if(!i)throw new Error(`Message with ID ${t} not found`);return(await this.#t.listAttachments(i)).filter(a=>a.isInline!==!0).map(a=>({id:a.cid??a.id,contentType:a.contentType,filename:a.fileName??a.name,content:a.contentBytes?Buffer.from(a.contentBytes,"base64").toString("utf-8"):void 0,contentBytes:a.contentBytes?Buffer.from(a.contentBytes,"base64"):void 0}))}async reply(t,i,r,a=!0){await this.#n();let n=await this.#t.getMail(t);if(!n)throw new Error(`Message with ID ${t} not found`);let s=await this.#t.createReply(n,this.#i.formatMailReplyBody(n,r),i);if(!a)return this.#t.sendMail(s);let A=await this.#t.getFolder("Drafts");if(!A)throw new Error("Folder not found: Drafts");return this.#t.moveMailToFolder(s,A)}async addCategory(t,...i){await this.#n();let r=await this.#t.getMail(t);if(!r)throw new Error(`Message with ID ${t} not found`);let n=(await this.#t.getMailCategories(r))?.categories||[];await this.#t.updateMailCategories(r,{categories:Array.from(new Set([...n,...i]).values())})}async removeCategory(t,...i){await this.#n();let r=await this.#t.getMail(t);if(!r)throw new Error(`Message with ID ${t} not found`);let n=(await this.#t.getMailCategories(r))?.categories||[];await this.#t.updateMailCategories(r,{categories:n.filter(s=>!i.includes(s))})}async#n(){this.#r.verbose(`Initializing Microsoft Office 365 mail client for ${this.#e.username}`),await this.#t.init(this.#e.tenantId,this.#e.clientId,this.#e.clientSecret),this.#r.debug(`Microsoft Office 365 mail client initialized for ${this.#e.username}`)}async#a(t,i,r){try{let a=await this.#t.getFullMail(i,t),n=null;return this.#e.emlTestMode&&(n=(await this.#t.getExtraData(i,t).catch(()=>null))?.toString()),this.#i.parsedToMailMessage(t,a,r,n)}catch(a){this.#r.warn(`Failed to read full mail and parse: [${i.id}] ${i.displayName} // [${t.id}] ${t.subject}: ${a?.message}`,{err:a});return}}};var EB=class{#t;#i;constructor(t,i){this.#t=t,this.#i=i}get callbackFunctionChain(){return this.#e(this.#r(this.#t.receiver.emitEventType(this.#t.receiver.responses.created())))}#e(t){return async i=>{if(i.type!=="JOB")return t(i);let r=i,a=await this.#t.receiver.getActionConfig(r);if(!a)return this.#t.receiver.responses.badRequest("Action configuration not found")(r);try{this.#t.logger.debug(`Apply templates on payload: ${JSON.stringify(r.payload)}, action: ${JSON.stringify(a)}`);let n=a.config.parsedTemplates,s=n.action({inputs:r.payload}).trim(),A=n.params({inputs:r.payload}).trim();if(r.testRun)return this.#t.logger.info(`Test run for ${r.eventId} with payload ${A} to action ${s}`),t(r);this.#t.logger.debug(`Parsed action: ${s}, parameters: ${A}`);let c=JSON.parse(A);switch(this.#t.logger.debug(`Parsed params json: ${JSON.stringify(c)}`),s){case"REPLY":await this.#i.reply(c.messageId,c.from,c.mailBody,!0);break;case"FORWARD":break;case"SEND":break;case"CATEGORY_ADD":await this.#i.addCategory(c.messageId,c.category);break;case"CATEGORY_REMOVE":await this.#i.removeCategory(c.messageId,c.category);break;default:this.#t.logger.error(`Unknown action type: ${s} in message ${r.eventId}`)}return t(r)}catch(n){return this.#t.receiver.responses.internalServerError(n instanceof Error?n.message:"Unknown error occurred")(r)}}}#r(t){return async i=>{if(i.type!=="ACTION")return t(i);let r=i;try{if(!r.payload.destination||!r.payload.content)return this.#t.receiver.responses.badRequest("Destination or content not found")(r);let a={success:!0,data:"Not implemented yet"};return a.success?t(r):this.#t.receiver.responses.internalServerError(a.data)(r)}catch(a){return this.#t.receiver.responses.internalServerError(a instanceof Error?a.message:"Unknown error occurred")(r)}}}};var dB=class{constructor(t,i,r){this.DEFAULT_EVENT_TTL=36e5;this.DEFAULT_INTERVAL_SECONDS=60;this.MAX_PROCESSING_TRIES=10;this.#a=!1;this.#o=0;this.#t=t,this.#i=r,this.#e=i,this.#r=this.#t.logger;let a=this.#e.attachmentDestination??this.#t.config.attachmentDestination;this.#n=a?this.#t.files(a):void 0}#t;#i;#e;#r;#n;#a;#o;get name(){return`mail-processor-${this.#e.mailboxIdentifier}-${this.#e.mailbox}`}async onRun(){if(this.#a){this.#o>this.MAX_PROCESSING_TRIES&&(this.#t.telemetry.increment("microsoft_office365_email.mailbox.exceeded_tries"),this.#r.error(`Exceeded processingTries for mailbox processor: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`),process.exit(1)),this.#t.telemetry.increment("microsoft_office365_email.mailbox.already_processing"),this.#r.debug(`Mailsource processor service is already processing: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`),this.#o+=1;return}this.#a=!0;try{let t=await this.#A(this.#e);this.#t.telemetry.increment("microsoft_office365_email.mailbox.processed",t)}catch(t){throw this.#t.telemetry.increment("microsoft_office365_email.mailbox.error"),this.#r.warn(`Error processing mailbox: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`,JSON.stringify(t)),this.#a=!1,this.#o+=1,t}this.#a=!1,this.#o=0}async#A(t){this.#r.debug(`Processing mailbox: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`);let i=new Date,r=await this.#t.offsetStore.getOffset(`${this.#e.offsetFilePrefix??"offset"}_${this.#e.mailboxIdentifier}`),a=r?.deltaLink,n=r?.dateTime;this.#r.verbose(`Last message ID of mailbox ${this.#e.mailboxIdentifier}/${this.#e.mailbox}: ${a}`);let s=await this.#i.readMailbox(t.mailbox,a?String(a):void 0,n?String(n):void 0,t.limit??10),A=await this.#l(t.mailboxIdentifier,t.mailbox,...s.mails);return this.#t.offsetStore.setOffset({timestamp:i.getTime(),dateTime:i.toISOString(),id:s.mails?.reverse()[0]?.originalMessageId??r?.originalMessageId,...s.deltaLink?{deltaLink:s.deltaLink}:{}},`${this.#e.offsetFilePrefix??"offset"}_${this.#e.mailboxIdentifier}`),A}async#l(t,i,...r){if(r.length===0)return this.#r.debug(`No new messages found for mailbox: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`),0;await this.#c(t,i,...r);let a=r.map(n=>({...n,attachments:(n.attachments??[]).map(s=>({...s,content:s.contentType==="application/json"?s.content:void 0,contentBytes:void 0}))}));return this.#r.debug(`Fetched ${a.length} new messages for mailbox ${this.#e.mailboxIdentifier}/${this.#e.mailbox}, sending as ${this.#e.type}`),this.#e.type==="metric"?await this.#t.sender.metricsLegacy(a,{keyField:"messageId",collection:this.#t.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}):await this.#t.sender.documents(a,{keyField:"messageId",collection:this.#t.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}),this.#r.info(`Fetched ${a.length} new messages for mailbox ${this.#e.mailboxIdentifier}/${this.#e.mailbox}, sent as ${this.#e.type}`),a.length}async#c(t,i,...r){if(!this.#n)return;let a=r.filter(n=>n.attachmentsCount>0);a.length!==0&&(this.#r.verbose(`Storing attachments for ${a.length} messages in mailbox ${this.#e.mailboxIdentifier}/${i}...`),await Promise.all(a.map(async n=>{let s;try{s=await this.#i.getAttachments(n.id)}catch(c){this.#r.error(`Failed to fetch attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id} due to: ${c.message}`,c);return}if(s.length===0){this.#r.info(`Somehow found ${s.length} of ${n.attachmentsCount} expected attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id}`);return}this.#r.verbose(`Found ${s.length} attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id}, storing to ${typeof this.#n}`);let A=await Promise.all(s.map(async c=>{if(!c.contentBytes&&!c.content)return;let u=`${t}/${i}/${encodeURIComponent(n.id)}/${c.filename}`;return this.#r.verbose(`Storing mail ${this.#e.mailboxIdentifier}/${i}/${n.id} attachment "${u}"...`),await this.#n.write(u,c.contentBytes??c.content).catch(g=>{this.#r.error(`Failed to store attachment to ${u} due to: ${g.message}`,g)})?(this.#r.debug(`Stored mail ${this.#e.mailboxIdentifier}/${i}/${n.id} attachment "${u}"`),{id:c.id,dsn:this.#n.pathAsDsn(u),filename:c.filename,contentType:c.contentType}):null}).filter(Boolean));this.#r.debug(`Stored ${A.length} attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id}`),n.storedAttachments=[...n.storedAttachments??[],...A]})))}};var Wy=class extends Fg{constructor(i,r){super(i,r);this.init=async()=>{let{config:i}=this.connectorSDK;await Promise.all(i.mailboxes.map(async r=>{let a=new dB(this.connectorSDK,r,this.#t);await this.connectorSDK.processing.registerInterval(r.interval??a.DEFAULT_INTERVAL_SECONDS,a,{immediate:!0})}))};let{config:a}=this.connectorSDK;this.#t=new xB(a.mailConfig),this.#i=new EB(this.connectorSDK,this.#t),this.callbackFunction=this.#i.callbackFunctionChain}#t;#i};0&&(module.exports={ConnectorRunnerMicrosoftOffice365Email});
187
+ \f\u200B`,wordwrap:80},uBt=(e,t,i)=>[...e,...t],ij=(e,t,i)=>[...t],lBt=(e,t,i)=>e.some(r=>typeof r=="object")?uBt(e,t):ij(e,t);function hBt(e={}){return e=(0,Ky.default)(cBt,e,{arrayMerge:ij,customMerge:t=>t==="selectors"?lBt:void 0}),e.formatters=Object.assign({},H2t,oBt,e.formatters),e.selectors=VK(e.selectors,(t=>t.selector)),gBt(e),D2t(e)}function rj(e,t={},i=void 0){return hBt(t)(e,i)}function gBt(e){if(e.tags){let i=Object.entries(e.tags).map(([r,a])=>({...a,selector:r||"*"}));e.selectors.push(...i),e.selectors=VK(e.selectors,(r=>r.selector))}function t(i,r,a){let n=r.pop();for(let s of r){let A=i[s];A||(A={},i[s]=A),i=A}i[n]=a}if(e.baseElement){let i=e.baseElement;t(e,["baseElements","selectors"],Array.isArray(i)?i:[i])}e.returnDomByDefault!==void 0&&t(e,["baseElements","returnDomByDefault"],e.returnDomByDefault);for(let i of e.selectors)i.format==="anchor"&&iu(i,["options","noLinkBrackets"])&&t(i,["options","linkBrackets"],!1)}var gB=class{async parsedToMailMessage(t,i,r,a){let n=[],s=[];i.headers.forEach((B,I)=>{n.push({key:String(I),header:Array.isArray(B)?B.join(", "):String(B)})}),i.headerLines.forEach(({key:B,line:I})=>{s.push({key:B,line:I})});let A=this.#t(i.to),c=this.#t(i.cc),u=this.#t(i.bcc),h=this.#t(i.from),g=this.#t(i.replyTo),d=typeof i.html=="string"?i.html:void 0,E=i.text||(d?rj(d):"");return{deltaLink:r,extraData:a,id:i.messageId??t.id,originalMessageId:t.internetMessageId,attachmentsCount:(i.attachments??[]).length,attachments:await this.#i(i.attachments??[]),headers:n,headerLines:s,subject:i.subject,conversationId:i.references?.[0],references:i.references,date:new Date(i.date??t.sentDateTime??new Date),to:A,from:h,fromDomain:h?.[0]?.split("@")[1],cc:c,bcc:u,replyTo:g,text:(E||"").trim(),html:d,messageId:i.messageId,inReplyTo:i.inReplyTo,categories:t.categories}}formatMailReplyBody(t,i){let r=t.from?.emailAddress?.address||"",a=t.toRecipients?.map(u=>u.emailAddress?.address).filter(Boolean).join("; ")||"",n=t.subject||"",s=t.sentDateTime?new Date(t.sentDateTime).toLocaleString():"",A=`<br><hr style="border:none;border-top:solid #b1b1b1 1px;height:1px;margin:16px 0 8px 0;" /><br>From: ${r}<br>Sent: ${s}<br>To: ${a}<br>Subject: ${n}<br><br>`,c=t.body?.content||"";return`${i}${A}${c}`}#t(t){if(!t)return;let i=a=>!a||typeof a!="object"?[]:"address"in a&&typeof a.address=="string"&&a.address?[a.address]:"group"in a&&Array.isArray(a.group)?a.group.flatMap(i):[];if("value"in t&&Array.isArray(t.value)){let a=t.value.flatMap(i).filter(Boolean);return a.length?a:void 0}if(Array.isArray(t)){let a=t.flatMap(i).filter(Boolean);return a.length?a:void 0}let r=i(t).filter(Boolean);return r.length?r:void 0}async#i(t){return(await Promise.all(t.map(async i=>{let r=i.contentType?.toLowerCase().includes("application/json")||i.filename?.toLowerCase().endsWith(".json"),a=await this.#e(i);if(!a&&!r)return;i=a??i;let n=Buffer.isBuffer(i.content)?i.content:await new Promise((s,A)=>{let c=[];i.content?.on?.("data",u=>c.push(u)),i.content?.once?.("end",()=>s(Buffer.concat(c))),i.content?.once?.("error",A)});return{id:i.cid,filename:i.filename||"attachment.json",contentType:"application/json",content:n.toString("utf-8")}}))).filter(i=>!!i)}async#e(t){if(!(t.contentType?.toLowerCase().includes("application/pdf")||t.filename?.toLowerCase().endsWith(".pdf")))return null;let r=await this.#r(t.content),a=await(0,aj.default)(r),n=`${t.filename?.replace(/\.pdf$/i,"")||"attachment"}.json`;return{...t,filename:n,contentType:"application/json",content:Buffer.from(a)}}async#r(t){return Buffer.isBuffer(t)?t:new Promise((i,r)=>{let a=[];t.on("data",n=>a.push(n)),t.once("end",()=>i(Buffer.concat(a))),t.once("error",r)})}};var xB=class{#t;#i;#e;#r;constructor(t,i,r){if(this.#e=t,this.#r=on.getInstance(),this.#t=i??new nE(this.#e.username,this.#e.emlTestMode??!1),this.#i=r??new gB,!this.#e.tenantId||!this.#e.clientId||!this.#e.clientSecret)throw new Error("Graph requires tenantId, clientId, and clientSecret")}async readMailbox(t,i,r,a=10){let n,s,A;try{if(await this.#n(),n=await this.#t.getFolder(t),!n)throw new Error(`Mailbox folder not found: ${t}`);let{mails:c,deltaLink:u}=await this.#t.getMails(n,i,r,a);s=c,A=u}catch(c){let u=`Failed to read email from mailbox ${t}: ${c?.message}`;throw this.#r.warn(u,{err:c}),new Error(u)}try{let c=[];for(let u of s.filter(Boolean)){let h=await this.#a(u,n,A);h&&c.push(h)}return{mails:c.sort((u,h)=>u.date.getTime()-h.date.getTime()),deltaLink:A}}catch(c){let u=`Failed to parse emails from mailbox ${t}: ${c?.message}`;throw this.#r.warn(u,{err:c}),new Error(u)}}async getAttachments(t){let i=await this.#t.getMail(t);if(!i)throw new Error(`Message with ID ${t} not found`);return(await this.#t.listAttachments(i)).filter(a=>a.isInline!==!0).map(a=>({id:a.cid??a.id,contentType:a.contentType,filename:a.fileName??a.name,content:a.contentBytes?Buffer.from(a.contentBytes,"base64").toString("utf-8"):void 0,contentBytes:a.contentBytes?Buffer.from(a.contentBytes,"base64"):void 0}))}async reply(t,i,r,a=!0){await this.#n();let n=await this.#t.getMail(t);if(!n)throw new Error(`Message with ID ${t} not found`);let s=await this.#t.createReply(n,this.#i.formatMailReplyBody(n,r),i);if(!a)return this.#t.sendMail(s);let A=await this.#t.getFolder("Drafts");if(!A)throw new Error("Folder not found: Drafts");return this.#t.moveMailToFolder(s,A)}async addCategory(t,...i){await this.#n();let r=await this.#t.getMail(t);if(!r)throw new Error(`Message with ID ${t} not found`);let n=(await this.#t.getMailCategories(r))?.categories||[];await this.#t.updateMailCategories(r,{categories:Array.from(new Set([...n,...i]).values())})}async removeCategory(t,...i){await this.#n();let r=await this.#t.getMail(t);if(!r)throw new Error(`Message with ID ${t} not found`);let n=(await this.#t.getMailCategories(r))?.categories||[];await this.#t.updateMailCategories(r,{categories:n.filter(s=>!i.includes(s))})}async#n(){this.#r.verbose(`Initializing Microsoft Office 365 mail client for ${this.#e.username}`),await this.#t.init(this.#e.tenantId,this.#e.clientId,this.#e.clientSecret),this.#r.debug(`Microsoft Office 365 mail client initialized for ${this.#e.username}`)}async#a(t,i,r){try{let a=await this.#t.getFullMail(i,t),n=null;return this.#e.emlTestMode&&(n=(await this.#t.getExtraData(i,t).catch(()=>null))?.toString()),this.#i.parsedToMailMessage(t,a,r,n)}catch(a){this.#r.warn(`Failed to read full mail and parse: [${i.id}] ${i.displayName} // [${t.id}] ${t.subject}: ${a?.message}`,{err:a});return}}};var EB=class{#t;#i;constructor(t,i){this.#t=t,this.#i=i}get callbackFunctionChain(){return this.#e(this.#r(this.#t.receiver.emitEventType(this.#t.receiver.responses.created())))}#e(t){return async i=>{if(i.type!=="JOB")return t(i);let r=i,a=await this.#t.receiver.getActionConfig(r);if(!a)return this.#t.receiver.responses.badRequest("Action configuration not found")(r);try{this.#t.logger.debug(`Apply templates on payload: ${JSON.stringify(r.payload)}, action: ${JSON.stringify(a)}`);let n=a.config.parsedTemplates,s=n.action({inputs:r.payload}).trim(),A=n.params({inputs:r.payload}).trim();if(r.testRun)return this.#t.logger.info(`Test run for ${r.eventId} with payload ${A} to action ${s}`),t(r);this.#t.logger.debug(`Parsed action: ${s}, parameters: ${A}`);let c=JSON.parse(A);this.#t.logger.debug(`Parsed params json: ${JSON.stringify(c)}`);let u=this.#n(c.mailboxIdentifier);switch(s){case"REPLY":await u.reply(c.messageId,c.from,c.mailBody,!0);break;case"FORWARD":break;case"SEND":break;case"CATEGORY_ADD":await u.addCategory(c.messageId,c.category);break;case"CATEGORY_REMOVE":await u.removeCategory(c.messageId,c.category);break;default:this.#t.logger.error(`Unknown action type: ${s} in message ${r.eventId}`)}return t(r)}catch(n){return this.#t.receiver.responses.internalServerError(n instanceof Error?n.message:"Unknown error occurred")(r)}}}#r(t){return async i=>{if(i.type!=="ACTION")return t(i);let r=i;try{if(!r.payload.destination||!r.payload.content)return this.#t.receiver.responses.badRequest("Destination or content not found")(r);let a={success:!0,data:"Not implemented yet"};return a.success?t(r):this.#t.receiver.responses.internalServerError(a.data)(r)}catch(a){return this.#t.receiver.responses.internalServerError(a instanceof Error?a.message:"Unknown error occurred")(r)}}}#n(t){let i=this.#i.get(t);if(!i)throw new Error(`Mail client not found for mailbox identifier: ${t}`);return i}};var dB=class{constructor(t,i,r){this.DEFAULT_EVENT_TTL=36e5;this.DEFAULT_INTERVAL_SECONDS=60;this.MAX_PROCESSING_TRIES=10;this.#a=!1;this.#o=0;this.#t=t,this.#i=r,this.#e=i,this.#r=this.#t.logger;let a=this.#e.attachmentDestination??this.#t.config.attachmentDestination;this.#n=a?this.#t.files(a):void 0}#t;#i;#e;#r;#n;#a;#o;get name(){return`mail-processor-${this.#e.mailboxIdentifier}-${this.#e.mailbox}`}async onRun(){if(this.#a){this.#o>this.MAX_PROCESSING_TRIES&&(this.#t.telemetry.increment("microsoft_office365_email.mailbox.exceeded_tries"),this.#r.error(`Exceeded processingTries for mailbox processor: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`),process.exit(1)),this.#t.telemetry.increment("microsoft_office365_email.mailbox.already_processing"),this.#r.debug(`Mailsource processor service is already processing: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`),this.#o+=1;return}this.#a=!0;try{let t=await this.#A(this.#e);this.#t.telemetry.increment("microsoft_office365_email.mailbox.processed",t)}catch(t){throw this.#t.telemetry.increment("microsoft_office365_email.mailbox.error"),this.#r.warn(`Error processing mailbox: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`,JSON.stringify(t)),this.#a=!1,this.#o+=1,t}this.#a=!1,this.#o=0}async#A(t){this.#r.debug(`Processing mailbox: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`);let i=new Date,r=await this.#t.offsetStore.getOffset(`${this.#e.offsetFilePrefix??"offset"}_${this.#e.mailboxIdentifier}`),a=r?.deltaLink,n=r?.dateTime;this.#r.verbose(`Last message ID of mailbox ${this.#e.mailboxIdentifier}/${this.#e.mailbox}: ${a}`);let s=await this.#i.readMailbox(t.mailbox,a?String(a):void 0,n?String(n):void 0,t.limit??10),A=await this.#l(t.mailboxIdentifier,t.mailbox,...s.mails);return this.#t.offsetStore.setOffset({timestamp:i.getTime(),dateTime:i.toISOString(),id:s.mails?.reverse()[0]?.originalMessageId??r?.originalMessageId,...s.deltaLink?{deltaLink:s.deltaLink}:{}},`${this.#e.offsetFilePrefix??"offset"}_${this.#e.mailboxIdentifier}`),A}async#l(t,i,...r){if(r.length===0)return this.#r.debug(`No new messages found for mailbox: ${this.#e.mailboxIdentifier}/${this.#e.mailbox}`),0;await this.#c(t,i,...r);let a=r.map(n=>({...n,attachments:(n.attachments??[]).map(s=>({...s,content:s.contentType==="application/json"?s.content:void 0,contentBytes:void 0}))}));return this.#r.debug(`Fetched ${a.length} new messages for mailbox ${this.#e.mailboxIdentifier}/${this.#e.mailbox}, sending as ${this.#e.type}`),this.#e.type==="metric"?await this.#t.sender.metricsLegacy(a,{keyField:"messageId",collection:this.#t.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}):await this.#t.sender.documents(a,{keyField:"messageId",collection:this.#t.config.datasourceIdentifier},{ttl:this.DEFAULT_EVENT_TTL}),this.#r.info(`Fetched ${a.length} new messages for mailbox ${this.#e.mailboxIdentifier}/${this.#e.mailbox}, sent as ${this.#e.type}`),a.length}async#c(t,i,...r){if(!this.#n)return;let a=r.filter(n=>n.attachmentsCount>0);a.length!==0&&(this.#r.verbose(`Storing attachments for ${a.length} messages in mailbox ${this.#e.mailboxIdentifier}/${i}...`),await Promise.all(a.map(async n=>{let s;try{s=await this.#i.getAttachments(n.id)}catch(c){this.#r.error(`Failed to fetch attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id} due to: ${c.message}`,c);return}if(s.length===0){this.#r.info(`Somehow found ${s.length} of ${n.attachmentsCount} expected attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id}`);return}this.#r.verbose(`Found ${s.length} attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id}, storing to ${typeof this.#n}`);let A=await Promise.all(s.map(async c=>{if(!c.contentBytes&&!c.content)return;let u=`${t}/${i}/${encodeURIComponent(n.id)}/${c.filename}`;return this.#r.verbose(`Storing mail ${this.#e.mailboxIdentifier}/${i}/${n.id} attachment "${u}"...`),await this.#n.write(u,c.contentBytes??c.content).catch(g=>{this.#r.error(`Failed to store attachment to ${u} due to: ${g.message}`,g)})?(this.#r.debug(`Stored mail ${this.#e.mailboxIdentifier}/${i}/${n.id} attachment "${u}"`),{id:c.id,dsn:this.#n.pathAsDsn(u),filename:c.filename,contentType:c.contentType}):null}).filter(Boolean));this.#r.debug(`Stored ${A.length} attachments for mail ${this.#e.mailboxIdentifier}/${i}/${n.id}`),n.storedAttachments=[...n.storedAttachments??[],...A]})))}};var Wy=class extends Fg{constructor(i,r){super(i,r);this.#t=new Map;this.init=async()=>{let{config:i}=this.connectorSDK;await Promise.all(i.mailboxes.map(async r=>{let a=this.#t.get(r.mailboxIdentifier??i.mailConfig.username);if(!a){this.connectorSDK.logger.error(`Mail client not found for mailboxIdentifier: ${r.mailboxIdentifier}, could not setup processor for mailbox: ${r.mailbox}`);return}let n=new dB(this.connectorSDK,r,a);await this.connectorSDK.processing.registerInterval(r.interval??n.DEFAULT_INTERVAL_SECONDS,n,{immediate:!0})}))};let{config:a}=this.connectorSDK;a.mailboxes.forEach(n=>{let s=n.mailboxIdentifier??a.mailConfig.username;this.#t.set(s,new xB({...a.mailConfig,username:s}))}),this.#i=new EB(this.connectorSDK,this.#t),this.callbackFunction=this.#i.callbackFunctionChain}#t;#i};0&&(module.exports={ConnectorRunnerMicrosoftOffice365Email});
188
188
  /*! Bundled license information:
189
189
 
190
190
  safe-buffer/index.js: