@stackone/olap 1.25.0 → 1.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/index.cjs CHANGED
@@ -1 +1 @@
1
- var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require(`@stackone/utils`),s=require(`@stackone/redaction`),c=require(`@aws-sdk/client-s3`),l=require(`@stackone/transport`),u=require(`zod`),d=require(`node:http`);d=__toESM(d);const f=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],p=[`refresh_authentication`],m=10*1024*1024;var AdvancedSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:n,result:r}of e){if(this.#t?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:n.mode,actionId:n.actionId,actionRunId:r.actionRunId,success:r.success,statusCode:r.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`});continue}if(t.errorsOnly&&r.success){this.#t?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${n.mode||`action`}`,category:`AdvancedSink`});continue}if(this.isBackgroundLog(n)&&!t.includeBackground){this.#t?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${n.mode}`,category:`AdvancedSink`});continue}let e=this.createActionS3(n,r,t?.ttl);await this.send(e)}}async sendStep(e,t,n){if(this.#t?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`});return}let r=this.createStepS3(e,t,n?.ttl);await this.send(r)}async sendSteps(e,t){for(let{input:n,result:r}of e)await this.sendStep(n,r,t)}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=process.env.ADVANCED_LOGS_BUCKET;if(!r)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let i=new c.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=process.env.ADVANCED_LOGS_BUCKET;if(!i)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let a=new c.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#t?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to advanced sink`,category:`AdvancedSink`});return}let n=process.env.ADVANCED_LOGS_BUCKET;if(!n)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);let r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60;this.#t?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:new Date(i*1e3).toISOString()}});try{await this.#e.send(new c.PutObjectCommand({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:new Date(i*1e3),Tagging:r}))}catch(t){throw this.#t?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}createActionS3(e,t,n){let r=`${t.organizationId}/${t.projectSecureId}/${t.actionRunId}/${t.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,m),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,m),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=(0,s.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},s.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,c=(0,s.redactObject)(e.body,s.CensorType.PARTIAL),l=(0,s.redactObject)(t.body,s.CensorType.PARTIAL),u=this.isBackgroundLog(e),d={data:{request:{id:t.actionRunId,actionId:t.actionId,method:t.httpMethod,headers:this.filterHeaders(a),url:{url:e.url,path:e.pathParams,queryParams:e.queryParams},body:c},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:l},...u?{isBackgroundLog:!0}:{}},metadata:{...u?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(d,r)}serializeStepResult(e,t,n,r){let i={data:{id:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(i,r)}serializeAndLimit(e,t){if((0,o.exceedsSize)(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=f.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}isDataSyncRequest(e){return e.mode===`data_sync`}isBackgroundLog(e){return(0,o.notMissing)(e.mode)&&p.includes(e.mode)}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const buildS3Client=(e,t)=>{try{return new c.S3Client(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var DefenderSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:n,result:r}of e){if(this.#t?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:n.mode,actionId:n.actionId,actionRunId:r.actionRunId,success:r.success,statusCode:r.statusCode,options:{enabled:t?.enabled}}}),(0,o.isMissing)(r.defenderContext)){this.#t?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}});continue}if(!t?.enabled){this.#t?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`});continue}let e=this.createActionS3(r);await this.send(e)}}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=process.env.DEFENDER_LOGS_BUCKET;if(!r)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);try{let i=new c.GetObjectCommand({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#t?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to defender sink`,category:`DefenderSink`});return}let t=process.env.DEFENDER_LOGS_BUCKET;if(!t)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);this.#t?.debug({message:`Storing defender log in S3 bucket ${t}`,category:`DefenderSink`,context:{bucket:t,key:e.Key}});try{await this.#e.send(new c.PutObjectCommand({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType}))}catch(t){throw this.#t?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createActionS3(e){let t=e.organizationId,n=e.projectSecureId;return{Key:this.generateS3Key(t,n,e.actionRunId),Body:JSON.stringify(e.defenderContext),ContentType:`application/json`}}};const buildHttpClient=e=>{try{return new l.HttpClient({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},buildKafkaClient=async(e,t)=>{if(e)try{let{Producer:t,stringSerializers:n}=await import(`@platformatic/kafka`);return new t({...e,serializers:n})??void 0}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},h=u.z.object({logType:u.z.enum([`action`,`step`,`unified`,`provider`]),eventTime:u.z.coerce.date(),startTime:u.z.coerce.date(),endTime:u.z.coerce.date().optional().nullable().transform(e=>e??void 0),durationMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:u.z.coerce.string(),projectSecureId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),g=h.extend({logType:u.z.literal(`action`),actionRunId:u.z.coerce.string(),actionId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string(),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),_=h.extend({logType:u.z.literal(`step`),actionRunId:u.z.coerce.string(),stepIndex:u.z.coerce.number(),stepId:u.z.coerce.string(),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),skipped:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),message:u.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),v=h.extend({logType:u.z.literal(`unified`),requestId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),status:u.z.coerce.number(),success:u.z.coerce.boolean(),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0)}),y=h.extend({logType:u.z.literal(`provider`),requestId:u.z.coerce.string(),id:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string(),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string(),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string(),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string(),success:u.z.coerce.boolean(),status:u.z.coerce.number(),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string()}),b=u.z.discriminatedUnion(`logType`,[g,_,v,y]);var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new d.default.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying Tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};const x=`project_logs.json`,S=`project_action_logs.json`,C=`project_step_logs.json`,w=`project_unified_logs.json`,T=`project_provider_logs.json`;var LogsSink=class{#e;#t;#n;constructor(e,t,n,r){this.#e=e,this.#n=r,this.#t=new TinybirdClient(t,n,r)}async initialize(){if(!this.#e){this.#n?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#t?.isReady()||this.#n?.warning({message:`Tinybird client is not ready (missing HTTP client or Tinybird config/token), logs sink will not be able to query`,category:`LogsSink`}),this.#n?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`})}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildActionLog(e,t));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async getLogs(e){try{this.#n?.info({message:`Querying logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(t.data),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getActions(e){try{this.#n?.info({message:`Querying action logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} action logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(t.data,g),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){try{this.#n?.info({message:`Querying step logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} step logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(t.data,_),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){try{this.#n?.info({message:`Querying unified logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} unified logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(t.data,v),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){try{this.#n?.info({message:`Querying provider logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} provider logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(t.data,y),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async send(e,t){if(!this.#e)throw this.#n?.error({message:`Kafka not initialized, dropping message for topic ${e}`,category:`KafkaSink`,code:`KafkaNotReady`}),Error(`Kafka producer is not initialized`);let n=Date.now(),r=t.map(t=>({topic:e,value:safeSerialize(t)}));this.#n?.debug({message:`Sending ${r.length} message(s) to topic ${e}`,category:`KafkaSink`});try{let t=await this.#e.send({messages:r,compression:`gzip`});this.#n?.debug({message:`Successfully sent ${r.length} message(s) to topic ${e}`,category:`KafkaSink`,context:{durationMs:Date.now()-n,topic:e,result:t}})}catch(t){throw this.#n?.error({message:`Error sending ${r.length} message(s) to topic ${e}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-n,topic:e,messageCount:r.length}}),t}}buildActionLog(e,t){let n=new Date,r=this.calculateDurationMs(t.startTime,t.endTime);return{logType:`action`,eventTime:n,startTime:t.startTime??n,organizationId:String(t.organizationId),projectSecureId:t.projectSecureId,accountSecureId:t.accountSecureId,actionRunId:t.actionRunId,actionId:t.actionId,connectorKey:t.connectorKey,connectorVersion:t.connectorVersion,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...e.mode&&{mode:e.mode},...t.actionType&&{actionType:t.actionType},...t.category&&{category:t.category},...t.originOwnerId&&{originOwnerId:t.originOwnerId},...t.originOwnerName&&{originOwnerName:t.originOwnerName},...t.httpMethod&&{httpMethod:t.httpMethod},...t.url&&{url:t.url},...e.sourceId&&{sourceId:e.sourceId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceValue&&{sourceValue:e.sourceValue},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.riskLevel&&{riskLevel:t.defenderContext.riskLevel},...t.defenderContext?.tier2Score!==void 0&&{tier2Score:t.defenderContext.tier2Score}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(t.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:t.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.message&&{message:t.message}}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof u.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#n?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,b)}};const E={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1},defender:{enabled:!0}};function resolveOlapOptions(e){return{logs:{...E.logs,...e?.logs},advanced:{...E.advanced,...e?.advanced},defender:{...E.defender,...e?.defender}}}var D=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){this.name=`OlapClient`,this.#s=e,this.#c=r,this.#l=a,this.#t=t(o),this.#n=n(i,o),this.#r=o}static async create({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){let s=new OlapClient({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});return await s.initialize(),s}async initialize(){this.#e=await this.#s(this.#c,this.#r),this.#i=new LogsSink(this.#e,this.#t,this.#l,this.#r),this.#a=new AdvancedSink(this.#n,this.#r),this.#o=new DefenderSink(this.#n,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){let{logs:r,advanced:i,defender:a}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record action`,category:`OlapClient`,context:{mode:e.mode,actionId:e.actionId,actionRunId:t.actionRunId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i,defender:a}}});let o=[];r?.enabled&&this.#i&&o.push(this.#i.sendAction(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&o.push(this.#a.sendAction(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),a?.enabled&&this.#o&&o.push(this.#o.sendAction(e,t,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(o)}async recordActions(e,t){let{logs:n,advanced:r,defender:i}=resolveOlapOptions(t),a=[];n?.enabled&&this.#i&&a.push(this.#i.sendActions(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&a.push(this.#a.sendActions(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#o&&a.push(this.#o.sendActions(e,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordStep(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendStep(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendStep(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async getLogs(e,t,n){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLogs(e,t,n){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n){let r=await this.#i?.getAction(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepLogs(e,t,n){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r){let i=await this.#i?.getStep(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n){let r=await this.#i?.getUnifiedLog(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getProviderLog(e,t,n,r){let i=await this.#i?.getProviderLog(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={})=>D.create({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o,getOlapClient:s=buildOlapClientInstance}={}){return this.olapClientPromise||=s({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};exports.OlapClient=D,exports.OlapClientManager=OlapClientManager;
1
+ var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require(`@stackone/utils`),s=require(`@stackone/redaction`),c=require(`@aws-sdk/client-s3`),l=require(`@stackone/transport`),u=require(`zod`),d=require(`node:http`);d=__toESM(d);const f=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],p=[`refresh_authentication`],m=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],h=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],g=10*1024*1024;var AdvancedSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:n,result:r}of e){if(this.#t?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:n.mode,actionId:n.actionId,actionRunId:r.actionRunId,success:r.success,statusCode:r.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`});continue}if(t.errorsOnly&&r.success){this.#t?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${n.mode||`action`}`,category:`AdvancedSink`});continue}if(this.isBackgroundLog(n)&&!t.includeBackground){this.#t?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${n.mode}`,category:`AdvancedSink`});continue}let e=this.createActionS3(n,r,t?.ttl);await this.send(e,t?.ttl)}}async sendStep(e,t,n){if(this.#t?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`});return}let r=this.createStepS3(e,t,n?.ttl);await this.send(r,n?.ttl)}async sendSteps(e,t){for(let{input:n,result:r}of e)await this.sendStep(n,r,t)}async sendUnified(e,t,n){if(!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`});return}this.#t?.info({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);await this.send(r,n?.ttl)}async sendProvider(e,t,n){if(!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`});return}this.#t?.info({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);await this.send(r,n?.ttl)}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=process.env.ADVANCED_LOGS_BUCKET;if(!r)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let i=new c.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=process.env.ADVANCED_LOGS_BUCKET;if(!i)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let a=new c.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#t?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=process.env.ADVANCED_LOGS_BUCKET;if(!r)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let i=new c.GetObjectCommand({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=process.env.ADVANCED_LOGS_BUCKET;if(!i)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let a=new c.GetObjectCommand({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#t?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to advanced sink`,category:`AdvancedSink`});return}let n=process.env.ADVANCED_LOGS_BUCKET;if(!n)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);let r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60;this.#t?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:new Date(i*1e3).toISOString()}});try{await this.#e.send(new c.PutObjectCommand({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:new Date(i*1e3),Tagging:r}))}catch(t){throw this.#t?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}createActionS3(e,t,n){let r=`${t.organizationId}/${t.projectSecureId}/${t.actionRunId}/${t.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,g),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,g),ContentType:`application/json`,Expires:new Date(i*1e3)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,g),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,g),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=(0,s.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},s.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,c=(0,s.redactObject)(e.body,s.CensorType.PARTIAL),l=(0,s.redactObject)(t.body,s.CensorType.PARTIAL),u=this.processContent(a,c,`upload`),d=this.processContent(o,l,`download`),f=this.isBackgroundLog(e),p={data:{request:{actionRunId:t.actionRunId,actionId:t.actionId,method:t.httpMethod,headers:this.filterHeaders(a),url:{url:e.url,path:e.pathParams,queryParams:e.queryParams},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:d},...f?{isBackgroundLog:!0}:{}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(p,r)}serializeStepResult(e,t,n,r){let i={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(i,r)}serializeUnifiedResult(e,t,n,r){let i=(0,s.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},s.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,c=(0,s.redactObject)(e.body,s.CensorType.PARTIAL),l=(0,s.redactObject)(t.body,s.CensorType.PARTIAL),u=this.processContent(a,c,`upload`),d=this.processContent(o,l,`download`),f=this.isBackgroundLog(e),p=`/`,m=e.url;if(e.url)try{m=(0,s.redactUrl)(e.url,s.CensorType.PARTIAL),p=new URL(m).pathname}catch{this.#t?.warning({message:`Invalid URL in unified request, using fallback path`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let h={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:m,path:p,queryParams:e.queryParams},body:u},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:d}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(h,r)}serializeProviderResult(e,t,n,r){let i=(0,s.redactObject)({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},s.CensorType.PARTIAL),a=i.req?.headers,o=i.res?.headers,c=(0,s.redactObject)(e.body,s.CensorType.PARTIAL),l=(0,s.redactObject)(t.body,s.CensorType.PARTIAL),u=this.processContent(a,c,`upload`),d=this.processContent(o,l,`download`),f,p=``,m=`/`,h={};if(e.url)try{f=(0,s.redactUrl)(e.url,s.CensorType.PARTIAL);let t=new URL(f);p=t.hostname,m=t.pathname,h=Object.fromEntries(t.searchParams)}catch{this.#t?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let g={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:f,hostname:p,path:m,queryParams:h},body:u},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:d}},metadata:{expirationTime:n}};return this.serializeAndLimit(g,r)}serializeAndLimit(e,t){if((0,o.exceedsSize)(e,t)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=f.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return m.includes(i)||h.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!(0,o.isMissing)(e)){if(!(0,o.isString)(e))return e;try{return JSON.parse(e)}catch{return e}}}isDataSyncRequest(e){return e.mode===`data_sync`}isBackgroundLog(e){return(0,o.notMissing)(e.mode)&&p.includes(e.mode)}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const buildS3Client=(e,t)=>{try{return new c.S3Client(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var DefenderSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:n,result:r}of e){if(this.#t?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:n.mode,actionId:n.actionId,actionRunId:r.actionRunId,success:r.success,statusCode:r.statusCode,options:{enabled:t?.enabled}}}),(0,o.isMissing)(r.defenderContext)){this.#t?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:r.actionRunId}});continue}if(!t?.enabled){this.#t?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`});continue}let e=this.createActionS3(r);await this.send(e)}}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=process.env.DEFENDER_LOGS_BUCKET;if(!r)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);try{let i=new c.GetObjectCommand({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#t?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to defender sink`,category:`DefenderSink`});return}let t=process.env.DEFENDER_LOGS_BUCKET;if(!t)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);this.#t?.debug({message:`Storing defender log in S3 bucket ${t}`,category:`DefenderSink`,context:{bucket:t,key:e.Key}});try{await this.#e.send(new c.PutObjectCommand({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType}))}catch(t){throw this.#t?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createActionS3(e){let t=e.organizationId,n=e.projectSecureId;return{Key:this.generateS3Key(t,n,e.actionRunId),Body:JSON.stringify(e.defenderContext),ContentType:`application/json`}}};const buildHttpClient=e=>{try{return new l.HttpClient({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},buildKafkaClient=async(e,t)=>{if(e)try{let{Producer:t,stringSerializers:n}=await import(`@platformatic/kafka`);return new t({...e,serializers:n})??void 0}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},_=u.z.object({logType:u.z.enum([`action`,`step`,`unified`,`provider`]),eventTime:u.z.coerce.date(),startTime:u.z.coerce.date(),endTime:u.z.coerce.date().optional().nullable().transform(e=>e??void 0),durationMs:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:u.z.coerce.string(),projectSecureId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),v=_.extend({logType:u.z.literal(`action`),actionRunId:u.z.coerce.string(),actionId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string(),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),actionType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),category:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0)}),y=_.extend({logType:u.z.literal(`step`),actionRunId:u.z.coerce.string(),stepIndex:u.z.coerce.number(),stepId:u.z.coerce.string(),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),skipped:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),message:u.z.coerce.string().optional().nullable().transform(e=>e??void 0)}),b=_.extend({logType:u.z.literal(`unified`),requestId:u.z.coerce.string(),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),status:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),provider:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:u.z.coerce.date().optional().nullable().transform(e=>e??void 0),duration:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),x=_.extend({logType:u.z.literal(`provider`),requestId:u.z.coerce.string(),id:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),action:u.z.coerce.string(),mode:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:u.z.coerce.string(),originOwnerId:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),url:u.z.coerce.string(),path:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:u.z.coerce.string(),connectorVersion:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),resource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),service:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),success:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:u.z.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:u.z.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:u.z.coerce.string(),accountSecureId:u.z.coerce.string(),provider:u.z.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:u.z.coerce.date().optional().nullable().transform(e=>e??void 0),duration:u.z.coerce.number().optional().nullable().transform(e=>e??void 0)}),S=u.z.discriminatedUnion(`logType`,[v,y,b,x]);var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new d.default.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying Tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}};const C=`project_logs.json`,w=`project_action_logs.json`,T=`project_step_logs.json`,E=`project_unified_logs.json`,D=`project_provider_logs.json`;var LogsSink=class{#e;#t;#n;constructor(e,t,n,r){this.#e=e,this.#n=r,this.#t=new TinybirdClient(t,n,r)}async initialize(){if(!this.#e){this.#n?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#t?.isReady()||this.#n?.warning({message:`Tinybird client is not ready (missing HTTP client or Tinybird config/token), logs sink will not be able to query`,category:`LogsSink`}),this.#n?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`})}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildActionLog(e,t));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n){if(!n?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#n?.info({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let r=this.buildUnifiedLog(e,t);await this.send(`unified_requests`,[r])}async sendProvider(e,t,n){if(!n?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#n?.info({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async getLogs(e){try{this.#n?.info({message:`Querying logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(t.data),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getActions(e){try{this.#n?.info({message:`Querying action logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} action logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(t.data,v),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){try{this.#n?.info({message:`Querying step logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} step logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(t.data,y),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){try{this.#n?.info({message:`Querying unified logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} unified logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(t.data,b),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){try{this.#n?.info({message:`Querying provider logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} provider logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(t.data,x),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async send(e,t){if(!this.#e)throw this.#n?.error({message:`Kafka not initialized, dropping message for topic ${e}`,category:`KafkaSink`,code:`KafkaNotReady`}),Error(`Kafka producer is not initialized`);let n=this.validateLogsBeforeSend(t);if(n.length===0){this.#n?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}n.length<t.length&&this.#n?.warning({message:`${t.length-n.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let r=Date.now(),i=n.map(t=>({topic:e,value:safeSerialize(t)}));this.#n?.debug({message:`Sending ${i.length} message(s) to topic ${e}`,category:`KafkaSink`});try{let t=await this.#e.send({messages:i,compression:`gzip`});this.#n?.debug({message:`Successfully sent ${i.length} message(s) to topic ${e}`,category:`KafkaSink`,context:{durationMs:Date.now()-r,topic:e,result:t}})}catch(t){throw this.#n?.error({message:`Error sending ${i.length} message(s) to topic ${e}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-r,topic:e,messageCount:i.length}}),t}}buildActionLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(t.organizationId),projectSecureId:t.projectSecureId,accountSecureId:t.accountSecureId,actionRunId:t.actionRunId,actionId:t.actionId,connectorKey:t.connectorKey,connectorVersion:t.connectorVersion,...r!==void 0&&{durationMs:r},...e.mode&&{mode:e.mode},...t.actionType&&{actionType:t.actionType},...t.category&&{category:t.category},...t.originOwnerId&&{originOwnerId:t.originOwnerId},...t.originOwnerName&&{originOwnerName:t.originOwnerName},...t.httpMethod&&{httpMethod:t.httpMethod},...t.url&&{url:t.url},...e.sourceId&&{sourceId:e.sourceId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceValue&&{sourceValue:e.sourceValue},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.riskLevel&&{riskLevel:t.defenderContext.riskLevel},...t.defenderContext?.tier2Score!==void 0&&{tier2Score:t.defenderContext.tier2Score},startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,isBackground:e.isBackground}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(t.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:t.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.message&&{message:t.message}}}buildUnifiedLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:`2`,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...e.sourceId&&{sourceId:e.sourceId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceValue&&{sourceValue:e.sourceValue},...t.statusCode!==void 0&&{status:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,provider:e.connectorKey,eventDatetime:n,duration:r}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,connectorVersion:`2`,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{status:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,provider:e.connectorKey,eventDatetime:n,duration:r}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof u.ZodError){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#n?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,S)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof u.ZodError?this.#n?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#n?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return v;case`step`:return y;case`unified`:return b;case`provider`:return x}}};const O={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1},defender:{enabled:!0}};function resolveOlapOptions(e){return{logs:{...O.logs,...e?.logs},advanced:{...O.advanced,...e?.advanced},defender:{...O.defender,...e?.defender}}}var k=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){this.name=`OlapClient`,this.#s=e,this.#c=r,this.#l=a,this.#t=t(o),this.#n=n(i,o),this.#r=o}static async create({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){let s=new OlapClient({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});return await s.initialize(),s}async initialize(){this.#e=await this.#s(this.#c,this.#r),this.#i=new LogsSink(this.#e,this.#t,this.#l,this.#r),this.#a=new AdvancedSink(this.#n,this.#r),this.#o=new DefenderSink(this.#n,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){let{logs:r,advanced:i,defender:a}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record action`,category:`OlapClient`,context:{mode:e.mode,actionId:e.actionId,actionRunId:t.actionRunId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i,defender:a}}});let o=[];r?.enabled&&this.#i&&o.push(this.#i.sendAction(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&o.push(this.#a.sendAction(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),a?.enabled&&this.#o&&o.push(this.#o.sendAction(e,t,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(o)}async recordActions(e,t){let{logs:n,advanced:r,defender:i}=resolveOlapOptions(t),a=[];n?.enabled&&this.#i&&a.push(this.#i.sendActions(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&a.push(this.#a.sendActions(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#o&&a.push(this.#o.sendActions(e,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordStep(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendStep(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendStep(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}});let a=[];r?.enabled&&this.#i&&a.push(this.#i.sendUnified(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendUnified(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async getLogs(e,t,n){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLogs(e,t,n){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,n){let r=await this.#i?.getAction(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepLogs(e,t,n){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,n,r){let i=await this.#i?.getStep(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,n){let r=await this.#i?.getUnifiedLog(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getProviderLog(e,t,n,r){let i=await this.#i?.getProviderLog(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getActionAdvancedLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getStepAdvancedLog(e,t,n,r){let i=await this.#a?.getStep(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedAdvancedLog(e,t,n){let r=await this.#a?.getUnified(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderAdvancedLog(e,t,n,r){let i=await this.#a?.getProvider(e,t,n,r);if((0,o.isMissing)(i)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#o?.getAction(e,t,n);if((0,o.isMissing)(r)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={})=>k.create({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o,getOlapClient:s=buildOlapClientInstance}={}){return this.olapClientPromise||=s({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};exports.OlapClient=k,exports.OlapClientManager=OlapClientManager;
package/dist/index.d.cts CHANGED
@@ -636,20 +636,6 @@ interface TinybirdQueryOptions<TParams = Record<string, unknown>, TResult = unkn
636
636
  parse: (data: unknown) => TResult;
637
637
  };
638
638
  }
639
- interface ITinybirdClient {
640
- query<TParams = Record<string, unknown>, TResult = unknown>(options: TinybirdQueryOptions<TParams, TResult>): Promise<TResult[]>;
641
- queryWithPagination<TParams = Record<string, unknown>, TResult = unknown>(options: TinybirdQueryOptions<TParams, TResult> & {
642
- pageNumber?: number;
643
- pageSize?: number;
644
- }): Promise<{
645
- data: TResult[];
646
- total: number;
647
- pageNumber: number;
648
- pageSize: number;
649
- }>;
650
- queryRaw<TParams = Record<string, unknown>, TResult = unknown>(options: TinybirdQueryOptions<TParams, TResult>): Promise<TinybirdResponse<TResult[]>>;
651
- isReady(): boolean;
652
- }
653
639
  interface ILog {
654
640
  logType: 'action' | 'step' | 'unified' | 'provider';
655
641
  eventTime: Date;
@@ -669,6 +655,7 @@ type ActionLog = ILog & {
669
655
  organizationId: string;
670
656
  projectSecureId: string;
671
657
  accountSecureId: string;
658
+ actionType?: string;
672
659
  mode?: string;
673
660
  category?: string;
674
661
  originOwnerId?: string;
@@ -678,6 +665,7 @@ type ActionLog = ILog & {
678
665
  sourceType?: string;
679
666
  sourceId?: string;
680
667
  sourceValue?: string;
668
+ isBackground?: boolean;
681
669
  success?: boolean;
682
670
  statusCode?: number;
683
671
  riskLevel?: string;
@@ -698,11 +686,11 @@ type StepLog = ILog & {
698
686
  type UnifiedLog = ILog & {
699
687
  logType: 'unified';
700
688
  requestId: string;
701
- connectorKey: string;
702
- connectorVersion?: string;
703
689
  organizationId: string;
704
690
  projectSecureId: string;
705
691
  accountSecureId: string;
692
+ connectorKey: string;
693
+ connectorVersion?: string;
706
694
  mode?: string;
707
695
  httpMethod?: string;
708
696
  url?: string;
@@ -715,16 +703,25 @@ type UnifiedLog = ILog & {
715
703
  sourceId?: string;
716
704
  sourceType?: string;
717
705
  sourceValue?: string;
706
+ isBackground?: boolean;
718
707
  originOwnerId?: string;
719
708
  originOwnerName?: string;
720
- status: number;
721
- success: boolean;
709
+ status?: number;
710
+ success?: boolean;
722
711
  isWorker?: boolean;
712
+ provider?: string;
713
+ eventDatetime?: Date;
714
+ duration?: number;
723
715
  };
724
716
  type ProviderLog = ILog & {
725
717
  logType: 'provider';
726
718
  requestId: string;
727
719
  id?: string;
720
+ organizationId: string;
721
+ projectSecureId: string;
722
+ accountSecureId: string;
723
+ connectorKey: string;
724
+ connectorVersion?: string;
728
725
  action: string;
729
726
  mode?: string;
730
727
  httpMethod: string;
@@ -732,18 +729,16 @@ type ProviderLog = ILog & {
732
729
  originOwnerName?: string;
733
730
  url: string;
734
731
  path?: string;
735
- connectorKey: string;
736
- connectorVersion?: string;
737
- resource: string;
732
+ resource?: string;
738
733
  subResource?: string;
739
734
  childResource?: string;
740
- service: string;
741
- success: boolean;
742
- status: number;
735
+ service?: string;
736
+ success?: boolean;
737
+ status?: number;
743
738
  isWorker?: boolean;
744
- organizationId: string;
745
- projectSecureId: string;
746
- accountSecureId: string;
739
+ provider?: string;
740
+ eventDatetime?: Date;
741
+ duration?: number;
747
742
  };
748
743
  //#endregion
749
744
  //#region src/types.d.ts
@@ -758,6 +753,8 @@ interface IOlapClient {
758
753
  input: StepInput;
759
754
  result: StepResult;
760
755
  }>, options?: OlapOptions): Promise<void>;
756
+ recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
757
+ recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
761
758
  getLogs(organizationId: string, projectSecureId: string, query: Query): Promise<QueryResult>;
762
759
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery): Promise<ActionsQueryResult>;
763
760
  getActionLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionLog | undefined>;
@@ -769,6 +766,8 @@ interface IOlapClient {
769
766
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
770
767
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
771
768
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
769
+ getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
770
+ getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
772
771
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
773
772
  }
774
773
  type DefenderContext = {
@@ -787,6 +786,8 @@ type ActionInput = {
787
786
  sourceId?: string;
788
787
  sourceType?: string;
789
788
  sourceValue?: string;
789
+ isBackground?: boolean;
790
+ startTime?: Date;
790
791
  };
791
792
  type ActionResult = {
792
793
  actionRunId: string;
@@ -812,7 +813,6 @@ type ActionResult = {
812
813
  headers?: Record<string, string>;
813
814
  body?: unknown;
814
815
  defenderContext?: DefenderContext;
815
- startTime?: Date;
816
816
  endTime?: Date;
817
817
  };
818
818
  type StepInput = {
@@ -835,6 +835,71 @@ type StepResult = {
835
835
  startTime?: Date;
836
836
  endTime?: Date;
837
837
  };
838
+ type UnifiedInput = {
839
+ requestId: string;
840
+ organizationId: string;
841
+ projectSecureId: string;
842
+ accountSecureId: string;
843
+ originOwnerId?: string;
844
+ originOwnerName?: string;
845
+ connectorKey: string;
846
+ action?: string;
847
+ service?: string;
848
+ mode?: string;
849
+ httpMethod?: string;
850
+ url?: string;
851
+ path?: string;
852
+ queryParams?: unknown;
853
+ body?: unknown;
854
+ headers?: Record<string, string>;
855
+ resource?: string;
856
+ subResource?: string;
857
+ childResource?: string;
858
+ sourceId?: string;
859
+ sourceType?: string;
860
+ sourceValue?: string;
861
+ isBackground?: boolean;
862
+ startTime?: Date;
863
+ };
864
+ type UnifiedResult = {
865
+ success?: boolean;
866
+ statusCode?: number;
867
+ message?: string;
868
+ headers?: Record<string, string>;
869
+ body?: unknown;
870
+ endTime?: Date;
871
+ };
872
+ type ProviderInput = {
873
+ requestId: string;
874
+ id: string;
875
+ organizationId: string;
876
+ projectSecureId: string;
877
+ accountSecureId: string;
878
+ originOwnerId?: string;
879
+ originOwnerName?: string;
880
+ connectorKey: string;
881
+ action: string;
882
+ service: string;
883
+ mode: string;
884
+ httpMethod: string;
885
+ url: string;
886
+ path?: string;
887
+ queryParams?: unknown;
888
+ headers?: Record<string, string>;
889
+ body?: unknown;
890
+ resource?: string;
891
+ subResource?: string;
892
+ childResource?: string;
893
+ startTime?: Date;
894
+ };
895
+ type ProviderResult = {
896
+ success?: boolean;
897
+ statusCode?: number;
898
+ headers?: Record<string, string>;
899
+ body?: unknown;
900
+ errors?: unknown;
901
+ endTime?: Date;
902
+ };
838
903
  //#endregion
839
904
  //#region src/advanced/types.d.ts
840
905
  type ActionAdvancedLog = {
@@ -854,6 +919,23 @@ type StepAdvancedLog = {
854
919
  expirationTime?: number;
855
920
  };
856
921
  };
922
+ type UnifiedAdvancedLog = {
923
+ data: {
924
+ [key: string]: unknown;
925
+ };
926
+ metadata?: {
927
+ isBackgroundLog?: boolean;
928
+ expirationTime?: number;
929
+ };
930
+ };
931
+ type ProviderAdvancedLog = {
932
+ data: {
933
+ [key: string]: unknown;
934
+ };
935
+ metadata?: {
936
+ expirationTime?: number;
937
+ };
938
+ };
857
939
  interface S3ClientConfig {
858
940
  region?: string;
859
941
  }
@@ -892,6 +974,8 @@ declare class OlapClient implements IOlapClient {
892
974
  input: StepInput;
893
975
  result: StepResult;
894
976
  }>, options?: OlapOptions): Promise<void>;
977
+ recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
978
+ recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
895
979
  getLogs(organizationId: string, projectSecureId: string, query: Query): Promise<QueryResult>;
896
980
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery): Promise<ActionsQueryResult>;
897
981
  getActionLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionLog | undefined>;
@@ -903,6 +987,8 @@ declare class OlapClient implements IOlapClient {
903
987
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
904
988
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
905
989
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
990
+ getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
991
+ getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
906
992
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
907
993
  }
908
994
  //#endregion
@@ -948,4 +1034,4 @@ declare class OlapClientManager {
948
1034
  static resetInstance(): void;
949
1035
  }
950
1036
  //#endregion
951
- export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type DefenderContext, type DefenderLog, type DefenderOptions, type ILog, type IOlapClient, type ITinybirdClient, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type Query, type QueryResult, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, type TinybirdConfig, type TinybirdQueryOptions, type TinybirdResponse, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult };
1037
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type DefenderContext, type DefenderLog, type DefenderOptions, type ILog, type IOlapClient, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryResult, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, type TinybirdConfig, type TinybirdQueryOptions, type TinybirdResponse, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult };
package/dist/index.d.mts CHANGED
@@ -636,20 +636,6 @@ interface TinybirdQueryOptions<TParams = Record<string, unknown>, TResult = unkn
636
636
  parse: (data: unknown) => TResult;
637
637
  };
638
638
  }
639
- interface ITinybirdClient {
640
- query<TParams = Record<string, unknown>, TResult = unknown>(options: TinybirdQueryOptions<TParams, TResult>): Promise<TResult[]>;
641
- queryWithPagination<TParams = Record<string, unknown>, TResult = unknown>(options: TinybirdQueryOptions<TParams, TResult> & {
642
- pageNumber?: number;
643
- pageSize?: number;
644
- }): Promise<{
645
- data: TResult[];
646
- total: number;
647
- pageNumber: number;
648
- pageSize: number;
649
- }>;
650
- queryRaw<TParams = Record<string, unknown>, TResult = unknown>(options: TinybirdQueryOptions<TParams, TResult>): Promise<TinybirdResponse<TResult[]>>;
651
- isReady(): boolean;
652
- }
653
639
  interface ILog {
654
640
  logType: 'action' | 'step' | 'unified' | 'provider';
655
641
  eventTime: Date;
@@ -669,6 +655,7 @@ type ActionLog = ILog & {
669
655
  organizationId: string;
670
656
  projectSecureId: string;
671
657
  accountSecureId: string;
658
+ actionType?: string;
672
659
  mode?: string;
673
660
  category?: string;
674
661
  originOwnerId?: string;
@@ -678,6 +665,7 @@ type ActionLog = ILog & {
678
665
  sourceType?: string;
679
666
  sourceId?: string;
680
667
  sourceValue?: string;
668
+ isBackground?: boolean;
681
669
  success?: boolean;
682
670
  statusCode?: number;
683
671
  riskLevel?: string;
@@ -698,11 +686,11 @@ type StepLog = ILog & {
698
686
  type UnifiedLog = ILog & {
699
687
  logType: 'unified';
700
688
  requestId: string;
701
- connectorKey: string;
702
- connectorVersion?: string;
703
689
  organizationId: string;
704
690
  projectSecureId: string;
705
691
  accountSecureId: string;
692
+ connectorKey: string;
693
+ connectorVersion?: string;
706
694
  mode?: string;
707
695
  httpMethod?: string;
708
696
  url?: string;
@@ -715,16 +703,25 @@ type UnifiedLog = ILog & {
715
703
  sourceId?: string;
716
704
  sourceType?: string;
717
705
  sourceValue?: string;
706
+ isBackground?: boolean;
718
707
  originOwnerId?: string;
719
708
  originOwnerName?: string;
720
- status: number;
721
- success: boolean;
709
+ status?: number;
710
+ success?: boolean;
722
711
  isWorker?: boolean;
712
+ provider?: string;
713
+ eventDatetime?: Date;
714
+ duration?: number;
723
715
  };
724
716
  type ProviderLog = ILog & {
725
717
  logType: 'provider';
726
718
  requestId: string;
727
719
  id?: string;
720
+ organizationId: string;
721
+ projectSecureId: string;
722
+ accountSecureId: string;
723
+ connectorKey: string;
724
+ connectorVersion?: string;
728
725
  action: string;
729
726
  mode?: string;
730
727
  httpMethod: string;
@@ -732,18 +729,16 @@ type ProviderLog = ILog & {
732
729
  originOwnerName?: string;
733
730
  url: string;
734
731
  path?: string;
735
- connectorKey: string;
736
- connectorVersion?: string;
737
- resource: string;
732
+ resource?: string;
738
733
  subResource?: string;
739
734
  childResource?: string;
740
- service: string;
741
- success: boolean;
742
- status: number;
735
+ service?: string;
736
+ success?: boolean;
737
+ status?: number;
743
738
  isWorker?: boolean;
744
- organizationId: string;
745
- projectSecureId: string;
746
- accountSecureId: string;
739
+ provider?: string;
740
+ eventDatetime?: Date;
741
+ duration?: number;
747
742
  };
748
743
  //#endregion
749
744
  //#region src/types.d.ts
@@ -758,6 +753,8 @@ interface IOlapClient {
758
753
  input: StepInput;
759
754
  result: StepResult;
760
755
  }>, options?: OlapOptions): Promise<void>;
756
+ recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
757
+ recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
761
758
  getLogs(organizationId: string, projectSecureId: string, query: Query): Promise<QueryResult>;
762
759
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery): Promise<ActionsQueryResult>;
763
760
  getActionLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionLog | undefined>;
@@ -769,6 +766,8 @@ interface IOlapClient {
769
766
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
770
767
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
771
768
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
769
+ getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
770
+ getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
772
771
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
773
772
  }
774
773
  type DefenderContext = {
@@ -787,6 +786,8 @@ type ActionInput = {
787
786
  sourceId?: string;
788
787
  sourceType?: string;
789
788
  sourceValue?: string;
789
+ isBackground?: boolean;
790
+ startTime?: Date;
790
791
  };
791
792
  type ActionResult = {
792
793
  actionRunId: string;
@@ -812,7 +813,6 @@ type ActionResult = {
812
813
  headers?: Record<string, string>;
813
814
  body?: unknown;
814
815
  defenderContext?: DefenderContext;
815
- startTime?: Date;
816
816
  endTime?: Date;
817
817
  };
818
818
  type StepInput = {
@@ -835,6 +835,71 @@ type StepResult = {
835
835
  startTime?: Date;
836
836
  endTime?: Date;
837
837
  };
838
+ type UnifiedInput = {
839
+ requestId: string;
840
+ organizationId: string;
841
+ projectSecureId: string;
842
+ accountSecureId: string;
843
+ originOwnerId?: string;
844
+ originOwnerName?: string;
845
+ connectorKey: string;
846
+ action?: string;
847
+ service?: string;
848
+ mode?: string;
849
+ httpMethod?: string;
850
+ url?: string;
851
+ path?: string;
852
+ queryParams?: unknown;
853
+ body?: unknown;
854
+ headers?: Record<string, string>;
855
+ resource?: string;
856
+ subResource?: string;
857
+ childResource?: string;
858
+ sourceId?: string;
859
+ sourceType?: string;
860
+ sourceValue?: string;
861
+ isBackground?: boolean;
862
+ startTime?: Date;
863
+ };
864
+ type UnifiedResult = {
865
+ success?: boolean;
866
+ statusCode?: number;
867
+ message?: string;
868
+ headers?: Record<string, string>;
869
+ body?: unknown;
870
+ endTime?: Date;
871
+ };
872
+ type ProviderInput = {
873
+ requestId: string;
874
+ id: string;
875
+ organizationId: string;
876
+ projectSecureId: string;
877
+ accountSecureId: string;
878
+ originOwnerId?: string;
879
+ originOwnerName?: string;
880
+ connectorKey: string;
881
+ action: string;
882
+ service: string;
883
+ mode: string;
884
+ httpMethod: string;
885
+ url: string;
886
+ path?: string;
887
+ queryParams?: unknown;
888
+ headers?: Record<string, string>;
889
+ body?: unknown;
890
+ resource?: string;
891
+ subResource?: string;
892
+ childResource?: string;
893
+ startTime?: Date;
894
+ };
895
+ type ProviderResult = {
896
+ success?: boolean;
897
+ statusCode?: number;
898
+ headers?: Record<string, string>;
899
+ body?: unknown;
900
+ errors?: unknown;
901
+ endTime?: Date;
902
+ };
838
903
  //#endregion
839
904
  //#region src/advanced/types.d.ts
840
905
  type ActionAdvancedLog = {
@@ -854,6 +919,23 @@ type StepAdvancedLog = {
854
919
  expirationTime?: number;
855
920
  };
856
921
  };
922
+ type UnifiedAdvancedLog = {
923
+ data: {
924
+ [key: string]: unknown;
925
+ };
926
+ metadata?: {
927
+ isBackgroundLog?: boolean;
928
+ expirationTime?: number;
929
+ };
930
+ };
931
+ type ProviderAdvancedLog = {
932
+ data: {
933
+ [key: string]: unknown;
934
+ };
935
+ metadata?: {
936
+ expirationTime?: number;
937
+ };
938
+ };
857
939
  interface S3ClientConfig {
858
940
  region?: string;
859
941
  }
@@ -892,6 +974,8 @@ declare class OlapClient implements IOlapClient {
892
974
  input: StepInput;
893
975
  result: StepResult;
894
976
  }>, options?: OlapOptions): Promise<void>;
977
+ recordUnified(unifiedInput: UnifiedInput, unifiedResult: UnifiedResult, options?: OlapOptions): Promise<void>;
978
+ recordProvider(providerInput: ProviderInput, providerResult: ProviderResult, options?: OlapOptions): Promise<void>;
895
979
  getLogs(organizationId: string, projectSecureId: string, query: Query): Promise<QueryResult>;
896
980
  getActionLogs(organizationId: string, projectSecureId: string, query: ActionsQuery): Promise<ActionsQueryResult>;
897
981
  getActionLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionLog | undefined>;
@@ -903,6 +987,8 @@ declare class OlapClient implements IOlapClient {
903
987
  getProviderLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderLog | undefined>;
904
988
  getActionAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<ActionAdvancedLog | undefined>;
905
989
  getStepAdvancedLog(organizationId: string, projectSecureId: string, actionRunId: string, stepIndex: number): Promise<StepAdvancedLog | undefined>;
990
+ getUnifiedAdvancedLog(organizationId: string, projectSecureId: string, requestId: string): Promise<UnifiedAdvancedLog | undefined>;
991
+ getProviderAdvancedLog(organizationId: string, projectSecureId: string, requestId: string, id: string): Promise<ProviderAdvancedLog | undefined>;
906
992
  getDefenderLog(organizationId: string, projectSecureId: string, actionRunId: string): Promise<DefenderLog | undefined>;
907
993
  }
908
994
  //#endregion
@@ -948,4 +1034,4 @@ declare class OlapClientManager {
948
1034
  static resetInstance(): void;
949
1035
  }
950
1036
  //#endregion
951
- export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type DefenderContext, type DefenderLog, type DefenderOptions, type ILog, type IOlapClient, type ITinybirdClient, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type Query, type QueryResult, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, type TinybirdConfig, type TinybirdQueryOptions, type TinybirdResponse, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult };
1037
+ export { type ActionAdvancedLog, type ActionInput, type ActionLog, type ActionResult, type ActionsQuery, type ActionsQueryResult, type AdvancedOptions, type DefenderContext, type DefenderLog, type DefenderOptions, type ILog, type IOlapClient, type LogsOptions, OlapClient, OlapClientManager, type OlapOptions, type ProviderAdvancedLog, type ProviderInput, type ProviderLog, type ProviderQuery, type ProviderQueryResult, type ProviderResult, type Query, type QueryResult, type StepAdvancedLog, type StepInput, type StepLog, type StepResult, type StepsQuery, type StepsQueryResult, type TinybirdConfig, type TinybirdQueryOptions, type TinybirdResponse, type UnifiedAdvancedLog, type UnifiedInput, type UnifiedLog, type UnifiedQuery, type UnifiedQueryResult, type UnifiedResult };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{t as e}from"./chunk-Cfxk5zVN.mjs";import{exceedsSize as t,isMissing as n,notMissing as r}from"@stackone/utils";import{CensorType as i,redactObject as a}from"@stackone/redaction";import{GetObjectCommand as o,PutObjectCommand as s,S3Client as c}from"@aws-sdk/client-s3";import{HttpClient as l}from"@stackone/transport";import{ZodError as u,z as d}from"zod";import f from"node:http";const p=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],m=[`refresh_authentication`],h=10*1024*1024;var AdvancedSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:n,result:r}of e){if(this.#t?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:n.mode,actionId:n.actionId,actionRunId:r.actionRunId,success:r.success,statusCode:r.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`});continue}if(t.errorsOnly&&r.success){this.#t?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${n.mode||`action`}`,category:`AdvancedSink`});continue}if(this.isBackgroundLog(n)&&!t.includeBackground){this.#t?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${n.mode}`,category:`AdvancedSink`});continue}let e=this.createActionS3(n,r,t?.ttl);await this.send(e)}}async sendStep(e,t,n){if(this.#t?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`});return}let r=this.createStepS3(e,t,n?.ttl);await this.send(r)}async sendSteps(e,t){for(let{input:n,result:r}of e)await this.sendStep(n,r,t)}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=process.env.ADVANCED_LOGS_BUCKET;if(!r)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let i=new o({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let s=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=process.env.ADVANCED_LOGS_BUCKET;if(!i)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let a=new o({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),s=await this.#e.send(a);if(!s.Body){this.#t?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let c=await s.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(c)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to advanced sink`,category:`AdvancedSink`});return}let n=process.env.ADVANCED_LOGS_BUCKET;if(!n)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);let r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60;this.#t?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:new Date(i*1e3).toISOString()}});try{await this.#e.send(new s({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:new Date(i*1e3),Tagging:r}))}catch(t){throw this.#t?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}createActionS3(e,t,n){let r=`${t.organizationId}/${t.projectSecureId}/${t.actionRunId}/${t.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,h),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,h),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let o=a({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},i.PARTIAL),s=o.req?.headers,c=o.res?.headers,l=a(e.body,i.PARTIAL),u=a(t.body,i.PARTIAL),d=this.isBackgroundLog(e),f={data:{request:{id:t.actionRunId,actionId:t.actionId,method:t.httpMethod,headers:this.filterHeaders(s),url:{url:e.url,path:e.pathParams,queryParams:e.queryParams},body:l},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:u},...d?{isBackgroundLog:!0}:{}},metadata:{...d?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(f,r)}serializeStepResult(e,t,n,r){let i={data:{id:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(i,r)}serializeAndLimit(e,n){if(t(e,n)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=p.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}isDataSyncRequest(e){return e.mode===`data_sync`}isBackgroundLog(e){return r(e.mode)&&m.includes(e.mode)}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const buildS3Client=(e,t)=>{try{return new c(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var DefenderSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:r,result:i}of e){if(this.#t?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:i.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),n(i.defenderContext)){this.#t?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:i.actionRunId}});continue}if(!t?.enabled){this.#t?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`});continue}let e=this.createActionS3(i);await this.send(e)}}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=process.env.DEFENDER_LOGS_BUCKET;if(!r)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);try{let i=new o({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let s=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#t?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to defender sink`,category:`DefenderSink`});return}let t=process.env.DEFENDER_LOGS_BUCKET;if(!t)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);this.#t?.debug({message:`Storing defender log in S3 bucket ${t}`,category:`DefenderSink`,context:{bucket:t,key:e.Key}});try{await this.#e.send(new s({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType}))}catch(t){throw this.#t?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createActionS3(e){let t=e.organizationId,n=e.projectSecureId;return{Key:this.generateS3Key(t,n,e.actionRunId),Body:JSON.stringify(e.defenderContext),ContentType:`application/json`}}};const buildHttpClient=e=>{try{return new l({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},buildKafkaClient=async(e,t)=>{if(e)try{let{Producer:t,stringSerializers:n}=await import(`@platformatic/kafka`);return new t({...e,serializers:n})??void 0}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},g=d.object({logType:d.enum([`action`,`step`,`unified`,`provider`]),eventTime:d.coerce.date(),startTime:d.coerce.date(),endTime:d.coerce.date().optional().nullable().transform(e=>e??void 0),durationMs:d.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:d.coerce.string(),projectSecureId:d.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:d.coerce.string().optional().nullable().transform(e=>e??void 0)}),_=g.extend({logType:d.literal(`action`),actionRunId:d.coerce.string(),actionId:d.coerce.string(),connectorKey:d.coerce.string(),connectorVersion:d.coerce.string(),projectSecureId:d.coerce.string(),accountSecureId:d.coerce.string(),mode:d.coerce.string().optional().nullable().transform(e=>e??void 0),category:d.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:d.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:d.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:d.coerce.string().optional().nullable().transform(e=>e??void 0),url:d.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:d.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:d.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:d.coerce.string().optional().nullable().transform(e=>e??void 0),success:d.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:d.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:d.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:d.coerce.number().optional().nullable().transform(e=>e??void 0)}),v=g.extend({logType:d.literal(`step`),actionRunId:d.coerce.string(),stepIndex:d.coerce.number(),stepId:d.coerce.string(),projectSecureId:d.coerce.string(),accountSecureId:d.coerce.string(),skipped:d.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:d.coerce.boolean().optional().nullable().transform(e=>e??void 0),message:d.coerce.string().optional().nullable().transform(e=>e??void 0)}),y=g.extend({logType:d.literal(`unified`),requestId:d.coerce.string(),connectorKey:d.coerce.string(),connectorVersion:d.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:d.coerce.string(),accountSecureId:d.coerce.string(),mode:d.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:d.coerce.string().optional().nullable().transform(e=>e??void 0),url:d.coerce.string().optional().nullable().transform(e=>e??void 0),path:d.coerce.string().optional().nullable().transform(e=>e??void 0),resource:d.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:d.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:d.coerce.string().optional().nullable().transform(e=>e??void 0),service:d.coerce.string().optional().nullable().transform(e=>e??void 0),action:d.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:d.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:d.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:d.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:d.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:d.coerce.string().optional().nullable().transform(e=>e??void 0),status:d.coerce.number(),success:d.coerce.boolean(),isWorker:d.coerce.boolean().optional().nullable().transform(e=>e??void 0)}),b=g.extend({logType:d.literal(`provider`),requestId:d.coerce.string(),id:d.coerce.string().optional().nullable().transform(e=>e??void 0),action:d.coerce.string(),mode:d.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:d.coerce.string(),originOwnerId:d.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:d.coerce.string().optional().nullable().transform(e=>e??void 0),url:d.coerce.string(),path:d.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:d.coerce.string(),connectorVersion:d.coerce.string().optional().nullable().transform(e=>e??void 0),resource:d.coerce.string(),subResource:d.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:d.coerce.string().optional().nullable().transform(e=>e??void 0),service:d.coerce.string(),success:d.coerce.boolean(),status:d.coerce.number(),isWorker:d.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:d.coerce.string(),accountSecureId:d.coerce.string()}),x=d.discriminatedUnion(`logType`,[_,v,y,b]);var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new f.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying Tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}},LogsSink=class{#e;#t;#n;constructor(e,t,n,r){this.#e=e,this.#n=r,this.#t=new TinybirdClient(t,n,r)}async initialize(){if(!this.#e){this.#n?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#t?.isReady()||this.#n?.warning({message:`Tinybird client is not ready (missing HTTP client or Tinybird config/token), logs sink will not be able to query`,category:`LogsSink`}),this.#n?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`})}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildActionLog(e,t));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async getLogs(e){try{this.#n?.info({message:`Querying logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(t.data),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getActions(e){try{this.#n?.info({message:`Querying action logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} action logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(t.data,_),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){try{this.#n?.info({message:`Querying step logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} step logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(t.data,v),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){try{this.#n?.info({message:`Querying unified logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} unified logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(t.data,y),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){try{this.#n?.info({message:`Querying provider logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} provider logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(t.data,b),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async send(e,t){if(!this.#e)throw this.#n?.error({message:`Kafka not initialized, dropping message for topic ${e}`,category:`KafkaSink`,code:`KafkaNotReady`}),Error(`Kafka producer is not initialized`);let n=Date.now(),r=t.map(t=>({topic:e,value:safeSerialize(t)}));this.#n?.debug({message:`Sending ${r.length} message(s) to topic ${e}`,category:`KafkaSink`});try{let t=await this.#e.send({messages:r,compression:`gzip`});this.#n?.debug({message:`Successfully sent ${r.length} message(s) to topic ${e}`,category:`KafkaSink`,context:{durationMs:Date.now()-n,topic:e,result:t}})}catch(t){throw this.#n?.error({message:`Error sending ${r.length} message(s) to topic ${e}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-n,topic:e,messageCount:r.length}}),t}}buildActionLog(e,t){let n=new Date,r=this.calculateDurationMs(t.startTime,t.endTime);return{logType:`action`,eventTime:n,startTime:t.startTime??n,organizationId:String(t.organizationId),projectSecureId:t.projectSecureId,accountSecureId:t.accountSecureId,actionRunId:t.actionRunId,actionId:t.actionId,connectorKey:t.connectorKey,connectorVersion:t.connectorVersion,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...e.mode&&{mode:e.mode},...t.actionType&&{actionType:t.actionType},...t.category&&{category:t.category},...t.originOwnerId&&{originOwnerId:t.originOwnerId},...t.originOwnerName&&{originOwnerName:t.originOwnerName},...t.httpMethod&&{httpMethod:t.httpMethod},...t.url&&{url:t.url},...e.sourceId&&{sourceId:e.sourceId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceValue&&{sourceValue:e.sourceValue},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.riskLevel&&{riskLevel:t.defenderContext.riskLevel},...t.defenderContext?.tier2Score!==void 0&&{tier2Score:t.defenderContext.tier2Score}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(t.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:t.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.message&&{message:t.message}}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof u){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#n?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,x)}};const S={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1},defender:{enabled:!0}};function resolveOlapOptions(e){return{logs:{...S.logs,...e?.logs},advanced:{...S.advanced,...e?.advanced},defender:{...S.defender,...e?.defender}}}var C=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){this.name=`OlapClient`,this.#s=e,this.#c=r,this.#l=a,this.#t=t(o),this.#n=n(i,o),this.#r=o}static async create({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){let s=new OlapClient({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});return await s.initialize(),s}async initialize(){this.#e=await this.#s(this.#c,this.#r),this.#i=new LogsSink(this.#e,this.#t,this.#l,this.#r),this.#a=new AdvancedSink(this.#n,this.#r),this.#o=new DefenderSink(this.#n,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){let{logs:r,advanced:i,defender:a}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record action`,category:`OlapClient`,context:{mode:e.mode,actionId:e.actionId,actionRunId:t.actionRunId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i,defender:a}}});let o=[];r?.enabled&&this.#i&&o.push(this.#i.sendAction(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&o.push(this.#a.sendAction(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),a?.enabled&&this.#o&&o.push(this.#o.sendAction(e,t,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(o)}async recordActions(e,t){let{logs:n,advanced:r,defender:i}=resolveOlapOptions(t),a=[];n?.enabled&&this.#i&&a.push(this.#i.sendActions(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&a.push(this.#a.sendActions(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#o&&a.push(this.#o.sendActions(e,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordStep(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendStep(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendStep(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async getLogs(e,t,n){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLogs(e,t,n){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepLogs(e,t,n){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#i?.getUnifiedLog(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getProviderLog(e,t,r,i){let a=await this.#i?.getProviderLog(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#a?.getStep(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,t,r){let i=await this.#o?.getAction(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});return}return i}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={})=>C.create({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o,getOlapClient:s=buildOlapClientInstance}={}){return this.olapClientPromise||=s({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{C as OlapClient,OlapClientManager};
1
+ import{t as e}from"./chunk-Cfxk5zVN.mjs";import{exceedsSize as t,isMissing as n,isString as r,notMissing as i}from"@stackone/utils";import{CensorType as a,redactObject as o,redactUrl as s}from"@stackone/redaction";import{GetObjectCommand as c,PutObjectCommand as l,S3Client as u}from"@aws-sdk/client-s3";import{HttpClient as d}from"@stackone/transport";import{ZodError as f,z as p}from"zod";import m from"node:http";const h=[`x-datadog-parent-id`,`x-datadog-sampling-priority`,`x-datadog-tags`,`x-datadog-trace-id`,`x-forwarded-proto`,`x-forwarded-port`,`x-forwarded-for`,`x-amzn-trace-id`,`traceparent`,`tracestate`,`x-request-nonce`,`x-signing-method`,`x-signature`,`host`,`via`],g=[`refresh_authentication`],_=[`application/octet-stream`,`application/pdf`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/zip`,`application/x-zip-compressed`],v=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],y=10*1024*1024;var AdvancedSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, advanced sink will not function`,category:`AdvancedSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:n,result:r}of e){if(this.#t?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:n.mode,actionId:n.actionId,actionRunId:r.actionRunId,success:r.success,statusCode:r.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`});continue}if(t.errorsOnly&&r.success){this.#t?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${n.mode||`action`}`,category:`AdvancedSink`});continue}if(this.isBackgroundLog(n)&&!t.includeBackground){this.#t?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${n.mode}`,category:`AdvancedSink`});continue}let e=this.createActionS3(n,r,t?.ttl);await this.send(e,t?.ttl)}}async sendStep(e,t,n){if(this.#t?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:t.success,options:{enabled:n?.enabled,errorsOnly:n?.errorsOnly,includeBackground:n?.includeBackground,ttl:n?.ttl}}}),!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`});return}let r=this.createStepS3(e,t,n?.ttl);await this.send(r,n?.ttl)}async sendSteps(e,t){for(let{input:n,result:r}of e)await this.sendStep(n,r,t)}async sendUnified(e,t,n){if(!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`});return}this.#t?.info({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r=this.createUnifiedS3(e,t,n?.ttl);await this.send(r,n?.ttl)}async sendProvider(e,t,n){if(!n?.enabled){this.#t?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`});return}this.#t?.info({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r=this.createProviderS3(e,t,n?.ttl);await this.send(r,n?.ttl)}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from advanced sink`,category:`AdvancedSink`});return}let r=process.env.ADVANCED_LOGS_BUCKET;if(!r)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let i=new c({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved advanced log from S3 for actionRunId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Advanced log not found in S3 for actionRunId ${n}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting advanced log from S3 for actionRunId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getStep(e,t,n,r){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get step log from advanced sink`,category:`AdvancedSink`});return}let i=process.env.ADVANCED_LOGS_BUCKET;if(!i)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let a=new c({Bucket:i,Key:`${e}/${t}/${n}/steps/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#t?.warning({message:`Received empty body when trying to get step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved step log from S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Step log not found in S3 for actionRunId ${n} stepIndex ${r}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting step log from S3 for actionRunId ${n} stepIndex ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getUnified(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get unified log from advanced sink`,category:`AdvancedSink`});return}let r=process.env.ADVANCED_LOGS_BUCKET;if(!r)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let i=new c({Bucket:r,Key:`${e}/${t}/${n}/${n}.json`}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get unified log from S3 for requestId ${n}`,category:`AdvancedSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved advanced log from S3 for requestId ${n}`,category:`AdvancedSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Advanced log not found in S3 for requestId ${n}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting advanced log from S3 for requestId ${n}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async getProvider(e,t,n,r){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get provider log from advanced sink`,category:`AdvancedSink`});return}let i=process.env.ADVANCED_LOGS_BUCKET;if(!i)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);try{let a=new c({Bucket:i,Key:`${e}/${t}/${n}/provider/${r}.json`}),o=await this.#e.send(a);if(!o.Body){this.#t?.warning({message:`Received empty body when trying to get provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}let s=await o.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved provider log from S3 for requestId ${n} id ${r}`,category:`AdvancedSink`}),JSON.parse(s)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Provider log not found in S3 for requestId ${n} id ${r}`,category:`AdvancedSink`});return}throw this.#t?.error({message:`Error when getting provider log from S3 for requestId ${n} id ${r}`,error:e,code:`AdvancedLogReadError`,category:`AdvancedSink`}),e}}async send(e,t){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to advanced sink`,category:`AdvancedSink`});return}let n=process.env.ADVANCED_LOGS_BUCKET;if(!n)throw Error(`ADVANCED_LOGS_BUCKET environment variable is not set`);let r=`ttl=30d`;typeof t==`number`&&(t===1?r=`ttl=1d`:t===7&&(r=`ttl=7d`));let i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60;this.#t?.debug({message:`Storing advanced log in S3 bucket ${n} with ttl of ${r}`,category:`AdvancedSink`,context:{bucket:n,key:e.Key,ttlTag:r,expiresAt:new Date(i*1e3).toISOString()}});try{await this.#e.send(new l({Bucket:n,Key:e.Key,Body:e.Body,ContentType:e.ContentType,Expires:new Date(i*1e3),Tagging:r}))}catch(t){throw this.#t?.error({message:`Failed to write advanced logs to S3 at ${e.Key}`,error:t,code:`AdvancedLogWriteError`,category:`AdvancedSink`}),t}}createActionS3(e,t,n){let r=`${t.organizationId}/${t.projectSecureId}/${t.actionRunId}/${t.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeActionResult(e,t,i,y),ContentType:`application/json`,Expires:new Date(i*1e3)}}createStepS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeStepResult(e,t,i,y),ContentType:`application/json`,Expires:new Date(i*1e3)}}createUnifiedS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeUnifiedResult(e,t,i,y),ContentType:`application/json`,Expires:new Date(i*1e3)}}createProviderS3(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n??30)*24*60*60;return{Key:r,Body:this.serializeProviderResult(e,t,i,y),ContentType:`application/json`,Expires:new Date(i*1e3)}}serializeActionResult(e,t,n,r){let i=o({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},a.PARTIAL),s=i.req?.headers,c=i.res?.headers,l=o(e.body,a.PARTIAL),u=o(t.body,a.PARTIAL),d=this.processContent(s,l,`upload`),f=this.processContent(c,u,`download`),p=this.isBackgroundLog(e),m={data:{request:{actionRunId:t.actionRunId,actionId:t.actionId,method:t.httpMethod,headers:this.filterHeaders(s),url:{url:e.url,path:e.pathParams,queryParams:e.queryParams},body:d},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(c),body:f},...p?{isBackgroundLog:!0}:{}},metadata:{...p?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,r)}serializeStepResult(e,t,n,r){let i={data:{actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,input:e.inputs,outputs:t.outputs,errors:t.errors},metadata:{expirationTime:n}};return this.serializeAndLimit(i,r)}serializeUnifiedResult(e,t,n,r){let i=o({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},a.PARTIAL),c=i.req?.headers,l=i.res?.headers,u=o(e.body,a.PARTIAL),d=o(t.body,a.PARTIAL),f=this.processContent(c,u,`upload`),p=this.processContent(l,d,`download`),m=this.isBackgroundLog(e),h=`/`,g=e.url;if(e.url)try{g=s(e.url,a.PARTIAL),h=new URL(g).pathname}catch{this.#t?.warning({message:`Invalid URL in unified request, using fallback path`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let _={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(c),url:{url:g,path:h,queryParams:e.queryParams},body:f},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(l),body:p}},metadata:{...m?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(_,r)}serializeProviderResult(e,t,n,r){let i=o({req:{...e.headers&&{headers:{...e.headers}}},res:{...t.headers&&{headers:{...t.headers}}}},a.PARTIAL),c=i.req?.headers,l=i.res?.headers,u=o(e.body,a.PARTIAL),d=o(t.body,a.PARTIAL),f=this.processContent(c,u,`upload`),p=this.processContent(l,d,`download`),m,h=``,g=`/`,_={};if(e.url)try{m=s(e.url,a.PARTIAL);let t=new URL(m);h=t.hostname,g=t.pathname,_=Object.fromEntries(t.searchParams)}catch{this.#t?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let v={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(c),url:{url:m,hostname:h,path:g,queryParams:_},body:f},response:{statusCode:t.statusCode,headers:this.filterHeaders(l),body:p}},metadata:{expirationTime:n}};return this.serializeAndLimit(v,r)}serializeAndLimit(e,n){if(t(e,n)){let t={...e,data:{outputs:{error:`Error.TOO_LARGE`}}};return JSON.stringify(t)}return JSON.stringify(e)}filterHeaders(e){if(!e)return;let t={},n=h.map(e=>e.toLowerCase());for(let[r,i]of Object.entries(e))n.includes(r.toLowerCase())||(t[r]=i);return t}processContent(e,t,n){let r=this.getContentType(e);if(!r)return this.parseJsonSafely(t);let i=r.toLowerCase().split(`;`)[0].trim();return _.includes(i)||v.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!n(e)){if(!r(e))return e;try{return JSON.parse(e)}catch{return e}}}isDataSyncRequest(e){return e.mode===`data_sync`}isBackgroundLog(e){return i(e.mode)&&g.includes(e.mode)}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const buildS3Client=(e,t)=>{try{return new u(e)??void 0}catch(e){let n=e;t?.error({message:`Error building s3 client: ${n.message}`,error:n,code:`BuildS3ClientError`,category:`buildS3Client`});return}};var DefenderSink=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async initialize(){if(!this.#e){this.#t?.warning({message:`No s3 client provided, defender sink will not function`,category:`DefenderSink`});return}}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){for(let{input:r,result:i}of e){if(this.#t?.debug({message:`Defender sink called to send action`,category:`DefenderSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:i.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),n(i.defenderContext)){this.#t?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:`DefenderSink`,context:{actionRunId:i.actionRunId}});continue}if(!t?.enabled){this.#t?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:`DefenderSink`});continue}let e=this.createActionS3(i);await this.send(e)}}async getAction(e,t,n){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot get action log from defender sink`,category:`DefenderSink`});return}let r=process.env.DEFENDER_LOGS_BUCKET;if(!r)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);try{let i=new c({Bucket:r,Key:this.generateS3Key(e,t,n)}),a=await this.#e.send(i);if(!a.Body){this.#t?.warning({message:`Received empty body when trying to get action log from S3 for actionRunId ${n}`,category:`DefenderSink`});return}let o=await a.Body.transformToString();return this.#t?.debug({message:`Successfully retrieved defender log from S3 for actionRunId ${n}`,category:`DefenderSink`}),JSON.parse(o)}catch(e){let t=e;if(t.name===`NoSuchKey`||t.$metadata?.httpStatusCode===404){this.#t?.debug({message:`Defender log not found in S3 for actionRunId ${n}`,category:`DefenderSink`});return}throw this.#t?.error({message:`Error when getting defender log from S3 for actionRunId ${n}`,error:e,code:`DefenderLogReadError`,category:`DefenderSink`}),e}}async send(e){if(!this.#e){this.#t?.warning({message:`No s3 client available, cannot send to defender sink`,category:`DefenderSink`});return}let t=process.env.DEFENDER_LOGS_BUCKET;if(!t)throw Error(`DEFENDER_LOGS_BUCKET environment variable is not set`);this.#t?.debug({message:`Storing defender log in S3 bucket ${t}`,category:`DefenderSink`,context:{bucket:t,key:e.Key}});try{await this.#e.send(new l({Bucket:t,Key:e.Key,Body:e.Body,ContentType:e.ContentType}))}catch(t){throw this.#t?.error({message:`Failed to write defender logs to S3 at ${e.Key}`,error:t,code:`DefenderLogWriteError`,category:`DefenderSink`}),t}}generateS3Key(e,t,n){return`${e}/${t}/${n}/defender.json`}createActionS3(e){let t=e.organizationId,n=e.projectSecureId;return{Key:this.generateS3Key(t,n,e.actionRunId),Body:JSON.stringify(e.defenderContext),ContentType:`application/json`}}};const buildHttpClient=e=>{try{return new d({logger:e})}catch(t){let n=t;e?.error({message:`Error building http client: ${n.message}`,error:n,code:`BuildHttpClientError`,category:`buildHttpClient`});return}},buildKafkaClient=async(e,t)=>{if(e)try{let{Producer:t,stringSerializers:n}=await import(`@platformatic/kafka`);return new t({...e,serializers:n})??void 0}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},b=p.object({logType:p.enum([`action`,`step`,`unified`,`provider`]),eventTime:p.coerce.date(),startTime:p.coerce.date(),endTime:p.coerce.date().optional().nullable().transform(e=>e??void 0),durationMs:p.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:p.coerce.string(),projectSecureId:p.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:p.coerce.string().optional().nullable().transform(e=>e??void 0)}),x=b.extend({logType:p.literal(`action`),actionRunId:p.coerce.string(),actionId:p.coerce.string(),connectorKey:p.coerce.string(),connectorVersion:p.coerce.string(),projectSecureId:p.coerce.string(),accountSecureId:p.coerce.string(),actionType:p.coerce.string().optional().nullable().transform(e=>e??void 0),mode:p.coerce.string().optional().nullable().transform(e=>e??void 0),category:p.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:p.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:p.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:p.coerce.string().optional().nullable().transform(e=>e??void 0),url:p.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:p.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:p.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:p.coerce.string().optional().nullable().transform(e=>e??void 0),success:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:p.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:p.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:p.coerce.number().optional().nullable().transform(e=>e??void 0),isBackground:p.coerce.boolean().optional().nullable().transform(e=>e??void 0)}),S=b.extend({logType:p.literal(`step`),actionRunId:p.coerce.string(),stepIndex:p.coerce.number(),stepId:p.coerce.string(),projectSecureId:p.coerce.string(),accountSecureId:p.coerce.string(),skipped:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),message:p.coerce.string().optional().nullable().transform(e=>e??void 0)}),C=b.extend({logType:p.literal(`unified`),requestId:p.coerce.string(),connectorKey:p.coerce.string(),connectorVersion:p.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:p.coerce.string(),accountSecureId:p.coerce.string(),mode:p.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:p.coerce.string().optional().nullable().transform(e=>e??void 0),url:p.coerce.string().optional().nullable().transform(e=>e??void 0),path:p.coerce.string().optional().nullable().transform(e=>e??void 0),resource:p.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:p.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:p.coerce.string().optional().nullable().transform(e=>e??void 0),service:p.coerce.string().optional().nullable().transform(e=>e??void 0),action:p.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:p.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:p.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:p.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:p.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:p.coerce.string().optional().nullable().transform(e=>e??void 0),status:p.coerce.number().optional().nullable().transform(e=>e??void 0),success:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),provider:p.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:p.coerce.date().optional().nullable().transform(e=>e??void 0),duration:p.coerce.number().optional().nullable().transform(e=>e??void 0)}),w=b.extend({logType:p.literal(`provider`),requestId:p.coerce.string(),id:p.coerce.string().optional().nullable().transform(e=>e??void 0),action:p.coerce.string(),mode:p.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:p.coerce.string(),originOwnerId:p.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:p.coerce.string().optional().nullable().transform(e=>e??void 0),url:p.coerce.string(),path:p.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:p.coerce.string(),connectorVersion:p.coerce.string().optional().nullable().transform(e=>e??void 0),resource:p.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:p.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:p.coerce.string().optional().nullable().transform(e=>e??void 0),service:p.coerce.string().optional().nullable().transform(e=>e??void 0),success:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:p.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:p.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:p.coerce.string(),accountSecureId:p.coerce.string(),provider:p.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:p.coerce.date().optional().nullable().transform(e=>e??void 0),duration:p.coerce.number().optional().nullable().transform(e=>e??void 0)}),T=p.discriminatedUnion(`logType`,[x,S,C,w]);var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},TinybirdClient=class{#e;#t;#n;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}async query(e){try{let t=await this.#o(e.endpoint,e.params);return this.#a(t.data,e.schema)}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryWithPagination(e){try{let t=await this.#o(e.endpoint,e.params),n=this.#a(t.data,e.schema);return{data:n,total:t.rows_before_limit_at_least??t.rows??n.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??n.length}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}async queryRaw(e){try{let t=await this.#o(e.endpoint,e.params);return t.data=this.#a(t.data,e.schema),t}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error querying Tinybird endpoint ${e.endpoint}: ${n}`,category:`TinybirdClient`,code:`TinybirdQueryError`}),t}}isReady(){return!!(this.#e&&this.#t?.token)}#r(){return new m.Agent({})}#i(){if(!this.#e)throw this.#n?.error({message:`HTTP client not initialized, cannot perform Tinybird query`,category:`TinybirdClient`,code:`HttpClientNotReady`}),Error(`HTTP client is not initialized`);if(!this.#t?.token)throw this.#n?.warning({message:`Missing OLAP token, cannot perform Tinybird query`,category:`TinybirdClient`}),Error(`TinybirdClient - Missing token`)}#a(e,t){if(!t)return e;try{let n=e.map(e=>t.parse(e));return this.#n?.debug({message:`Schema validation passed for ${n.length} rows`,category:`TinybirdClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`TinybirdClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#o(e,t){this.#i();let n=this.#e,r=this.#t;if(!n||!r)throw Error(`Client validation failed`);let i=new URL(`/v0/pipes/${e}`,r.baseUrl);this.#n?.debug({message:`Querying Tinybird endpoint: ${e}`,category:`TinybirdClient`,context:{endpoint:e,params:t}});let a=await n.request({method:`post`,url:i.toString(),payload:t,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${r.token}`},...r.allowHttp&&{httpAgent:this.#r()}});return this.#n?.debug({message:`Tinybird query returned ${a.data.data.length} rows`,category:`TinybirdClient`,context:{endpoint:e,rows:a.data.rows,statistics:a.data.statistics}}),a.data}},LogsSink=class{#e;#t;#n;constructor(e,t,n,r){this.#e=e,this.#n=r,this.#t=new TinybirdClient(t,n,r)}async initialize(){if(!this.#e){this.#n?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#t?.isReady()||this.#n?.warning({message:`Tinybird client is not ready (missing HTTP client or Tinybird config/token), logs sink will not be able to query`,category:`LogsSink`}),this.#n?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`})}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} actions to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildActionLog(e,t));await this.send(`actions`,n)}async sendStep(e,t,n){await this.sendSteps([{input:e,result:t}],n)}async sendSteps(e,t){if(!t?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending ${e.length} steps to log sink`,category:`LogsSink`});return}if(e.length===0)return;let n=e.map(({input:e,result:t})=>this.buildStepLog(e,t));await this.send(`steps`,n)}async sendUnified(e,t,n){if(!n?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#n?.info({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let r=this.buildUnifiedLog(e,t);await this.send(`unified_requests`,[r])}async sendProvider(e,t,n){if(!n?.enabled){this.#n?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#n?.info({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async getLogs(e){try{this.#n?.info({message:`Querying logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(t.data),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{logs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getActions(e){try{this.#n?.info({message:`Querying action logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_action_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} action logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(t.data,x),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for action logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{actionLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getAction(e,t,n){return(await this.getActions({organizationId:e,projectSecureId:t,actionRunId:n})).actionLogs[0]}async getSteps(e){try{this.#n?.info({message:`Querying step logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_step_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} step logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(t.data,S),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{stepLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getStep(e,t,n,r){return(await this.getSteps({organizationId:e,projectSecureId:t,actionRunId:n,stepIndex:r})).stepLogs[0]}async getUnifiedLogs(e){try{this.#n?.info({message:`Querying unified logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_unified_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} unified logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(t.data,C),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for unified logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{unifiedLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getUnifiedLog(e,t,n){return(await this.getUnifiedLogs({organizationId:e,projectSecureId:t,requestId:n})).unifiedLogs[0]}async getProviderLogs(e){try{this.#n?.info({message:`Querying provider logs from Tinybird`,category:`LogsSink`,context:{query:e}});let t=await this.#t?.queryWithPagination({endpoint:`project_provider_logs.json`,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return t?(this.#n?.info({message:`Successfully retrieved ${t.data.length} provider logs from Tinybird (${t.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(t.data,w),total:t.total,pageNumber:t.pageNumber,pageSize:t.pageSize}):(this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0})}catch(t){return this.#t?.isReady()?this.#n?.warning({message:`Failed to query Tinybird for provider logs, returning empty results`,category:`LogsSink`,error:t}):this.#n?.warning({message:`Tinybird client not available, returning empty results`,category:`LogsSink`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getProviderLog(e,t,n,r){return(await this.getProviderLogs({organizationId:e,projectSecureId:t,requestId:n,id:r})).providerLogs[0]}async send(e,t){if(!this.#e)throw this.#n?.error({message:`Kafka not initialized, dropping message for topic ${e}`,category:`KafkaSink`,code:`KafkaNotReady`}),Error(`Kafka producer is not initialized`);let n=this.validateLogsBeforeSend(t);if(n.length===0){this.#n?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}n.length<t.length&&this.#n?.warning({message:`${t.length-n.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let r=Date.now(),i=n.map(t=>({topic:e,value:safeSerialize(t)}));this.#n?.debug({message:`Sending ${i.length} message(s) to topic ${e}`,category:`KafkaSink`});try{let t=await this.#e.send({messages:i,compression:`gzip`});this.#n?.debug({message:`Successfully sent ${i.length} message(s) to topic ${e}`,category:`KafkaSink`,context:{durationMs:Date.now()-r,topic:e,result:t}})}catch(t){throw this.#n?.error({message:`Error sending ${i.length} message(s) to topic ${e}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-r,topic:e,messageCount:i.length}}),t}}buildActionLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(t.organizationId),projectSecureId:t.projectSecureId,accountSecureId:t.accountSecureId,actionRunId:t.actionRunId,actionId:t.actionId,connectorKey:t.connectorKey,connectorVersion:t.connectorVersion,...r!==void 0&&{durationMs:r},...e.mode&&{mode:e.mode},...t.actionType&&{actionType:t.actionType},...t.category&&{category:t.category},...t.originOwnerId&&{originOwnerId:t.originOwnerId},...t.originOwnerName&&{originOwnerName:t.originOwnerName},...t.httpMethod&&{httpMethod:t.httpMethod},...t.url&&{url:t.url},...e.sourceId&&{sourceId:e.sourceId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceValue&&{sourceValue:e.sourceValue},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.riskLevel&&{riskLevel:t.defenderContext.riskLevel},...t.defenderContext?.tier2Score!==void 0&&{tier2Score:t.defenderContext.tier2Score},startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,isBackground:e.isBackground}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(t.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:t.startTime??n,organizationId:String(e.organizationId),projectSecureId:String(e.projectSecureId),accountSecureId:String(e.accountSecureId),actionRunId:e.actionRunId,stepIndex:e.stepIndex,stepId:e.stepId,...t.endTime&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},...t.skipped!==void 0&&{skipped:t.skipped},...t.success!==void 0&&{success:t.success},...t.message&&{message:t.message}}}buildUnifiedLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:`2`,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.mode&&{mode:e.mode},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...e.path&&{path:e.path},...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...e.action&&{action:e.action},...e.sourceId&&{sourceId:e.sourceId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceValue&&{sourceValue:e.sourceValue},...t.statusCode!==void 0&&{status:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,provider:e.connectorKey,eventDatetime:n,duration:r}}buildProviderLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`provider`,requestId:e.requestId,id:e.id,organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},action:e.action,...e.mode&&{mode:e.mode},httpMethod:e.httpMethod,url:e.url,...e.path&&{path:e.path},connectorKey:e.connectorKey,connectorVersion:`2`,...e.resource&&{resource:e.resource},...e.subResource&&{subResource:e.subResource},...e.childResource&&{childResource:e.childResource},...e.service&&{service:e.service},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{status:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,provider:e.connectorKey,eventDatetime:n,duration:r}}calculateDurationMs(e,t){if(!(e instanceof Date)||!(t instanceof Date))return;let n=e.getTime(),r=t.getTime();if(!(Number.isNaN(n)||Number.isNaN(r)||r<n))return r-n}validateLogsWithSchema(e,t){return e.map(e=>{try{return t.parse(e)}catch(t){if(t instanceof f){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#n?.error({message:`Failed to validate ${n} log from Tinybird`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.errors,log:safeSerialize(e)}}),Error(`Tinybird data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,T)}validateLogsBeforeSend(e){let t=[];for(let n of e)try{let e=this.getSchemaForLogType(n.logType).parse(n);t.push(e)}catch(e){e instanceof f?this.#n?.warning({message:`Log validation failed before sending to Tinybird, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.errors,log:safeSerialize(n)}}):this.#n?.warning({message:`Unexpected error validating ${n.logType} log before send, dropping log`,category:`LogsSink`,code:`PreWriteValidationError`,error:e})}return t}getSchemaForLogType(e){switch(e){case`action`:return x;case`step`:return S;case`unified`:return C;case`provider`:return w}}};const E={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1},defender:{enabled:!0}};function resolveOlapOptions(e){return{logs:{...E.logs,...e?.logs},advanced:{...E.advanced,...e?.advanced},defender:{...E.defender,...e?.defender}}}var D=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){this.name=`OlapClient`,this.#s=e,this.#c=r,this.#l=a,this.#t=t(o),this.#n=n(i,o),this.#r=o}static async create({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={}){let s=new OlapClient({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});return await s.initialize(),s}async initialize(){this.#e=await this.#s(this.#c,this.#r),this.#i=new LogsSink(this.#e,this.#t,this.#l,this.#r),this.#a=new AdvancedSink(this.#n,this.#r),this.#o=new DefenderSink(this.#n,this.#r),await this.#i?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async recordAction(e,t,n){let{logs:r,advanced:i,defender:a}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record action`,category:`OlapClient`,context:{mode:e.mode,actionId:e.actionId,actionRunId:t.actionRunId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i,defender:a}}});let o=[];r?.enabled&&this.#i&&o.push(this.#i.sendAction(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&o.push(this.#a.sendAction(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),a?.enabled&&this.#o&&o.push(this.#o.sendAction(e,t,a).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(o)}async recordActions(e,t){let{logs:n,advanced:r,defender:i}=resolveOlapOptions(t),a=[];n?.enabled&&this.#i&&a.push(this.#i.sendActions(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&a.push(this.#a.sendActions(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#o&&a.push(this.#o.sendActions(e,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to defender logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordStep(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendStep(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendStep(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,n).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#a&&i.push(this.#a.sendSteps(e,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#r?.debug({message:`Olap client called to record unified`,category:`OlapClient`,context:{mode:e.mode,requestId:e.requestId,success:t.success,options:n,resolvedOptions:{logs:r,advanced:i}}});let a=[];r?.enabled&&this.#i&&a.push(this.#i.sendUnified(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendUnified(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to advanced logs s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,r).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#a&&a.push(this.#a.sendProvider(e,t,i).catch(e=>{this.#r?.warning({message:`[OlapClient] Error sending to s3: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async getLogs(e,t,n){return this.#r?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLogs(e,t,n){return this.#r?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query action logs, returning empty result`,category:`OlapClient`}),{actionLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getActionLog(e,t,r){let i=await this.#i?.getAction(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve action log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepLogs(e,t,n){return this.#r?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query step logs, returning empty result`,category:`OlapClient`}),{stepLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getStepLog(e,t,r,i){let a=await this.#i?.getStep(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve step log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedLogs(e,t,n){return this.#r?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query unified logs, returning empty result`,category:`OlapClient`}),{unifiedLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getUnifiedLog(e,t,r){let i=await this.#i?.getUnifiedLog(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve unified log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderLogs(e,t,n){return this.#r?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#i?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#r?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getProviderLog(e,t,r,i){let a=await this.#i?.getProviderLog(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve provider log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getActionAdvancedLog(e,t,r){let i=await this.#a?.getAction(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve action advanced log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getStepAdvancedLog(e,t,r,i){let a=await this.#a?.getStep(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve step advanced log for actionRunId ${r} stepIndex ${i}`,category:`OlapClient`});return}return a}async getUnifiedAdvancedLog(e,t,r){let i=await this.#a?.getUnified(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve unified advanced log for requestId ${r}`,category:`OlapClient`});return}return i}async getProviderAdvancedLog(e,t,r,i){let a=await this.#a?.getProvider(e,t,r,i);if(n(a)){this.#r?.debug({message:`Failed to retrieve provider advanced log for requestId ${r} id ${i}`,category:`OlapClient`});return}return a}async getDefenderLog(e,t,r){let i=await this.#o?.getAction(e,t,r);if(n(i)){this.#r?.debug({message:`Failed to retrieve defender log for actionRunId ${r}`,category:`OlapClient`});return}return i}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getHttpClient:t=buildHttpClient,getS3Client:n=buildS3Client,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}={})=>D.create({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o});var OlapClientManager=class{static{this.olapClientPromise=null}static getInstance({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o,getOlapClient:s=buildOlapClientInstance}={}){return this.olapClientPromise||=s({getKafkaClient:e,getHttpClient:t,getS3Client:n,kafkaClientConfig:r,s3ClientConfig:i,tinybirdConfig:a,logger:o}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null}};export{D as OlapClient,OlapClientManager};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/olap",
3
- "version": "1.25.0",
3
+ "version": "1.26.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",