@stackone/olap 3.4.0 → 3.5.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.mjs CHANGED
@@ -1,17 +1,17 @@
1
- import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysToCamelCase as n,exceedsSize as r,extractSchema as i,isDate as a,isMissing as o,isObject as s,isString as c,snakeToCamel as l}from"@stackone/utils";import{randomUUID as u}from"crypto";import{ZodError as d,z as f}from"zod";import{CensorType as p,redactFields as m,redactFormBody as ee,redactHeaders as h,redactUrl as g}from"@stackone/redaction";import{createClient as te}from"@clickhouse/client";import{createStorage as ne,storageConfigFromEnv as re}from"@stackone/storage";import{OTLPTraceExporter as ie}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as ae}from"@opentelemetry/resources";import{BasicTracerProvider as oe,BatchSpanProcessor as se}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as ce}from"@opentelemetry/semantic-conventions";function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const narrowArrayFilter=(e,t)=>{let n=e.length===0?[...t]:t.filter(t=>e.includes(t));return n.length>0?n:void 0},_=`({authPairsApplied:UInt8} = 0 OR concat(authType, ':', authId) IN {authKeys:Array(String)})`;var InvalidAuthPairError=class extends Error{constructor(e){super(e),this.name=`InvalidAuthPairError`}};const toAuthKey=({authType:e,authId:t})=>{if(e.length===0||t.length===0)throw new InvalidAuthPairError(`Cannot filter on an auth pair with an empty type or id`);if(e.includes(`:`))throw new InvalidAuthPairError(`Cannot filter on auth type "${e}": it contains ":"`);return`${e}:${t}`},toAuthPairParams=e=>({authPairsApplied:e===void 0?0:1,authKeys:(e??[]).map(toAuthKey)}),v={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},le={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},ue={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},de={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},fe=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],pe=[v.Scheduler,v.DataSync,v.DataSyncV2,v.Internal],me=[`data_sync`],he=[v.DataSync,v.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&fe.includes(e)||t&&pe.includes(t))}function isDataSync(e,t){return!!(e&&me.includes(e)||t&&he.includes(t))}const ge=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>ge.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,t)=>{if(!c(e))return m(e,p.PARTIAL,!0);let n=parseJson(e);return n?redactBody(n.parsed,t):contentTypeOf(t).includes(`application/x-www-form-urlencoded`)?ee(e,p.PARTIAL):e},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>o(e)?!1:Array.isArray(e)||c(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,_e={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},y=`action_logs_filtered`,b=`organizationId.projectSecureId.actionRunId.accountSecureId.actionId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.actionType.mode.category.originOwnerId.originOwnerName.httpMethod.sourceType.sourceId.sourceValue.authType.authId.userAgent.ipAddress.sessionId.agentId.transportType.streamType.policyResult.riskLevel`.split(`.`),x=[...b.map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),S=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
1
+ import{t as e}from"./chunk-BhWHdk3m.mjs";import{CensorType as t,REDACT_CENSOR as n,redactFields as r,redactFormBody as i,redactHeaders as a,redactUrl as o}from"@stackone/redaction";import{calculateSize as s,convertKeysToCamelCase as c,exceedsSize as l,extractSchema as u,isDate as d,isMissing as f,isObject as p,isString as m,snakeToCamel as h}from"@stackone/utils";import{randomUUID as g}from"crypto";import{ZodError as _,z as v}from"zod";import{createClient as ee}from"@clickhouse/client";import{createStorage as te,storageConfigFromEnv as ne}from"@stackone/storage";import{OTLPTraceExporter as re}from"@opentelemetry/exporter-trace-otlp-proto";import{resourceFromAttributes as ie}from"@opentelemetry/resources";import{BasicTracerProvider as ae,BatchSpanProcessor as oe}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as se}from"@opentelemetry/semantic-conventions";const ce=new Set([`idempotency-key`,`x-hub-version`,`x-request-id`]),le=new Set([`authorization`,`cookie`,`x-api-key`]),codePointsOf=(e,t)=>Array.from(e.slice(0,t*2)).slice(0,t),joinedWithin=e=>e.reduce((e,t)=>{let n=e.shown===``?``:`, `,r=e.room-n.length;if(r<=0)return{...e,room:0};let i=codePointsOf(t,r);return{shown:e.shown+n+i.join(``),room:r-i.length}},{shown:``,room:256}).shown.trim(),textsOf=e=>(Array.isArray(e)?e:[e]).filter(m).map(e=>e.trim()).filter(e=>e!==``),callerHeadersOf=e=>{let t=[...Object.entries(e??{}).map(([e,t])=>[e.toLowerCase(),t]).filter(([e])=>ce.has(e)||le.has(e)).reduce((e,[t,n])=>e.set(t,[...e.get(t)??[],...textsOf(n)]),new Map)].filter(([,e])=>e.length>0).map(([e,t])=>[e,le.has(e)?n:joinedWithin(t)]);return t.length>0?Object.fromEntries(t):void 0};function toArray(e){return e==null?[]:Array.isArray(e)?e:[e]}function toCsvArray(e){return toArray(e).flatMap(e=>e.split(`,`)).map(e=>e.trim()).filter(e=>e.length>0)}function toStatusCodes(e){let t=toArray(e);if(t.length===0)return[];let n=t.map(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length===0?NaN:Number(t)}).filter(e=>Number.isInteger(e)&&e>=-32768&&e<=32767);return n.length>0?n:[-1]}function toClickHouseDate(e){return e?(typeof e==`string`?new Date(e):e).toISOString().replace(`T`,` `).replace(`Z`,``):null}function buildPaginationParams(e,t){let n=Math.min(t??100,1e3);return{limit:n,offset:(Math.max(e??1,1)-1)*n}}function sanitizeOrderDirection(e){return e?.toLowerCase()===`asc`?`ASC`:`DESC`}function sanitizeOrderBy(e,t,n){return e?t[e]??n:n}function buildArrayFilter(e,t,n=`String`){return`({${t}:Array(${n})} = [] OR ${e} IN {${t}:Array(${n})})`}const narrowArrayFilter=(e,t)=>{let n=e.length===0?[...t]:t.filter(t=>e.includes(t));return n.length>0?n:void 0},y=`({authPairsApplied:UInt8} = 0 OR concat(authType, ':', authId) IN {authKeys:Array(String)})`;var InvalidAuthPairError=class extends Error{constructor(e){super(e),this.name=`InvalidAuthPairError`}};const toAuthKey=({authType:e,authId:t})=>{if(e.length===0||t.length===0)throw new InvalidAuthPairError(`Cannot filter on an auth pair with an empty type or id`);if(e.includes(`:`))throw new InvalidAuthPairError(`Cannot filter on auth type "${e}": it contains ":"`);return`${e}:${t}`},toAuthPairParams=e=>({authPairsApplied:e===void 0?0:1,authKeys:(e??[]).map(toAuthKey)}),b={RequestTester:`REQUEST_TESTER`,ActionTester:`ACTION_TESTER`,Discode:`DISCODE`,Dashboard:`DASHBOARD`,Playground:`PLAYGROUND`,SDK:`SDK`,API:`API`,Scheduler:`SCHEDULER`,Webhook:`WEBHOOK`,Agent:`AGENT`,MCP:`MCP`,Application:`APPLICATION`,DataSync:`DATA_SYNC`,DataSyncV2:`DATA_SYNC_V2`,Internal:`INTERNAL`,ConnectionTest:`CONNECTION_TEST`},ue={HTTP:`HTTP`,MCP:`MCP`,ActionRPC:`ACTION_RPC`,WebSocket:`WEBSOCKET`},de={HTTP:`HTTP`,WebSocket:`WEBSOCKET`,SSE:`SSE`},fe={APIKey:`API_KEY`,SessionToken:`SESSION_TOKEN`,UserSession:`USER_SESSION`,Cookie:`COOKIE`,Webhook:`WEBHOOK`,Signature:`SIGNATURE`},pe=[`refresh_authentication`,`data_sync`,`test_action`,`webhook_setup`],me=[b.Scheduler,b.DataSync,b.DataSyncV2,b.Internal],he=[`data_sync`],ge=[b.DataSync,b.DataSyncV2];function isBackgroundLog(e,t){return!!(e&&pe.includes(e)||t&&me.includes(t))}function isDataSync(e,t){return!!(e&&he.includes(e)||t&&ge.includes(t))}const _e=[`content-type`,`contenttype`],contentTypeOf=e=>String(Object.entries(e??{}).find(([e])=>_e.includes(e.toLowerCase()))?.[1]??``).toLowerCase(),parseJson=e=>{try{return{parsed:JSON.parse(e)}}catch{return}},redactBody=(e,n)=>{if(!m(e))return r(e,t.PARTIAL,!0);let a=parseJson(e);return a?redactBody(a.parsed,n):contentTypeOf(n).includes(`application/x-www-form-urlencoded`)?i(e,t.PARTIAL):e},safeSerialize=e=>{try{return JSON.stringify(e)}catch{return`[Unserializable payload]`}},safeObject=e=>{try{return JSON.stringify(e),e}catch{return{error:`Unserializable payload`}}},hasErrorEntries=e=>f(e)?!1:Array.isArray(e)||m(e)?e.length>0:e instanceof Error?!0:typeof e==`object`?Object.keys(e).length>0:!0,ve={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},ye=`action_logs_filtered`,x=`organizationId.projectSecureId.actionRunId.accountSecureId.actionId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.actionType.mode.category.originOwnerId.originOwnerName.httpMethod.sourceType.sourceId.sourceValue.authType.authId.userAgent.ipAddress.sessionId.agentId.transportType.streamType.policyResult.riskLevel`.split(`.`),S=[...x.map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),C=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
2
2
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
3
- AND ${_}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(b.map(t=>[t,toArray(e[t])])),...toAuthPairParams(e.authPairs),statusCode:toStatusCodes(e.statusCode),isBackground:toNullableFlag(e.isBackground),success:toNullableFlag(e.success),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}),buildActionLogsQuery=e=>{let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
3
+ AND ${y}`,toNullableFlag=e=>e===void 0?null:Number(e),buildViewParams=e=>({...Object.fromEntries(x.map(t=>[t,toArray(e[t])])),...toAuthPairParams(e.authPairs),statusCode:toStatusCodes(e.statusCode),isBackground:toNullableFlag(e.isBackground),success:toNullableFlag(e.success),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}),buildActionLogsQuery=e=>{let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
4
4
  SELECT *
5
- FROM ${y}(${x})
6
- ${S}
7
- ORDER BY ${sanitizeOrderBy(e.orderBy,_e,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
5
+ FROM ${ye}(${S})
6
+ ${C}
7
+ ORDER BY ${sanitizeOrderBy(e.orderBy,ve,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
8
8
  LIMIT {limit:UInt32}
9
9
  OFFSET {offset:UInt32}
10
10
  `,params:{...buildViewParams(e),limit:t,offset:n}}},buildActionLogsCountQuery=e=>({sql:`
11
11
  SELECT count() as total
12
- FROM ${y}(${x})
13
- ${S}
14
- `,params:buildViewParams(e)}),ve={id:`project_action_logs`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery},ye=[`synced_field_listing`,`test_actions`];function buildActionsCountQuery(e){return{sql:`
12
+ FROM ${ye}(${S})
13
+ ${C}
14
+ `,params:buildViewParams(e)}),be={id:`project_action_logs`,buildQuery:buildActionLogsQuery,buildCountQuery:buildActionLogsCountQuery},xe=[`synced_field_listing`,`test_actions`];function buildActionsCountQuery(e){return{sql:`
15
15
  SELECT count() AS actions_count
16
16
  FROM actions FINAL
17
17
  WHERE ({organizationId:Nullable(String)} IS NULL OR organizationId = {organizationId:Nullable(String)})
@@ -21,25 +21,25 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
21
21
  AND isBackground = 0
22
22
  AND ifNull(sourceType, '') != {dataSyncV2:String}
23
23
  AND ifNull(mode, '') NOT IN {nonBillableModes:Array(String)}
24
- `,params:{organizationId:e.organizationId??null,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),dataSyncV2:v.DataSyncV2,nonBillableModes:ye}}}const be={id:`actions_count`,buildQuery:buildActionsCountQuery},C={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),xe={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},Se={Asc:`asc`,Desc:`desc`},w={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},Ce={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},we={EventType:`eventType`,Action:`action`,Resource:`resource`,Service:`service`,SourceType:`sourceType`,SourceId:`sourceId`,AuthType:`authType`,UserEmail:`userEmail`,StatusCode:`statusCode`,Success:`success`,IsRead:`isRead`,AgentId:`agentId`,TransportType:`transportType`,StreamType:`streamType`},T={actions:[`internal`],steps:[`internal`],unified_requests:[`internal`],provider_requests:[`internal`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===C.Platform,E={account_secure_id:`accountSecureId`,connector_key:`connectorKey`,connector_version:`connectorVersion`,connector_owner:`connectorOwner`,connector_profile_id:`connectorProfileId`,action_id:`actionId`,action_run_id:`actionRunId`,action_type:`actionType`,source_type:`sourceType`,source_id:`sourceId`,mode:`mode`,origin_owner_id:`originOwnerId`,origin_owner_name:`originOwnerName`,auth_type:`authType`,auth_id:`authId`,user_agent:`userAgent`,ip_address:`ipAddress`,session_id:`sessionId`,agent_id:`agentId`,transport_type:`transportType`,stream_type:`streamType`,http_method:`httpMethod`,service:`service`,resource:`resource`,risk_level:`riskLevel`,policy_result:`policyResult`,success:`success`,is_background:`isBackground`,status_code:`statusCode`,duration_ms:`durationMs`,log_id:`logId`,request_id:`requestId`,session_auth_id:`if(authType = 'SESSION_TOKEN', authId, NULL)`},D=Object.keys(E),O=new Set([`status_code`,`duration_ms`]),k=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`],A=new Set([`gt`,`gte`,`lt`,`lte`]),isFiniteNumber=e=>!!e.trim()&&Number.isFinite(Number(e)),isInt16=e=>{let t=Number(e);return isFiniteNumber(e)&&Number.isInteger(t)&&t>=-32768&&t<=32767},j=new Set([`status_code`]),M=new Set([`success`,`is_background`]),Te=f.object({field:f.enum(D),operator:f.enum(k),values:f.array(f.string().min(1).max(2048)).min(1).max(500)}).refine(({field:e,operator:t,values:n})=>{let r=O.has(e);return A.has(t)&&(!r||n.length!==1)?!1:j.has(e)?n.every(isInt16):r?n.every(isFiniteNumber):M.has(e)?n.every(e=>e===`true`||e===`false`):!0},{message:`Invalid log comparison values`}),Ee=f.array(Te).max(50);var InvalidLogQueryConditionsError=class extends Error{constructor(e){super(`Invalid log query conditions`),this.name=`InvalidLogQueryConditionsError`,this.cause=e,this.issues=e.issues.map(({path:e,message:t})=>({path:e.filter(e=>typeof e!=`symbol`),message:t}))}};const parseLogQueryConditions=(e=[])=>{let t=Ee.safeParse(e);if(!t.success)throw new InvalidLogQueryConditionsError(t.error);return t.data},De={type:`Int16`,cast:Number},Oe={type:`Float64`,cast:Number},ke={type:`UInt8`,cast:e=>+(e===`true`)},Ae={type:`String`,cast:e=>e},valueKind=e=>j.has(e)?De:O.has(e)?Oe:M.has(e)?ke:Ae,je={eq:{operator:`IN`,whenMissing:0},ne:{operator:`NOT IN`,whenMissing:1}},Me={gt:`>`,gte:`>=`,lt:`<`,lte:`<=`},isComparison=e=>A.has(e),buildCondition=({field:e,operator:t,values:n},r)=>{let i=`logCondition${r}`,a=E[e],{type:o,cast:s}=valueKind(e);if(isComparison(t))return{sql:`${a} ${Me[t]} {${i}:${o}}`,params:{[i]:s(n[0])}};let{operator:c,whenMissing:l}=je[t];return{sql:`ifNull(${a} ${c} {${i}:Array(${o})}, ${l})`,params:{[i]:n.map(e=>s(e))}}},and=e=>({sql:e.map(({sql:e})=>`(${e})`).join(` AND `),params:Object.assign({},...e.map(({params:e})=>e))}),buildLogConditions=e=>and(parseLogQueryConditions(e).map(buildCondition)),Ne={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},untypedFilter=(e,t)=>e[t];function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),transportType:toArray(e.transportType),streamType:toArray(e.streamType),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toStatusCodes(untypedFilter(e,`status`))}}const Pe=[...`organizationId.projectSecureId.accountSecureId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.sourceType.sourceId.sourceValue.authType.authId.sessionId.agentId.userAgent.ipAddress.transportType.streamType.mode.httpMethod.originOwnerId.originOwnerName.logId.requestId.resource.service.subResource.childResource.action.actionRunId.actionId.actionType.category.path.accountId.riskLevel.policyResult.logType`.split(`.`).map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`status = {status:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),Fe=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
24
+ `,params:{organizationId:e.organizationId??null,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),dataSyncV2:b.DataSyncV2,nonBillableModes:xe}}}const Se={id:`actions_count`,buildQuery:buildActionsCountQuery},w={Action:`action`,Step:`step`,Unified:`unified`,Provider:`provider`,Platform:`platform`},emptyQueryResult=()=>({logs:[],total:0,pageNumber:1,pageSize:0}),Ce={StartTime:`startTime`,EndTime:`endTime`,EventTime:`eventTime`,DurationMs:`durationMs`},we={Asc:`asc`,Desc:`desc`},T={Minute:`minute`,Hour:`hour`,Day:`day`,Week:`week`,Month:`month`,None:`none`},Te={ConnectorKey:`connectorKey`,Success:`success`,ActionType:`actionType`,Mode:`mode`,Service:`service`,Resource:`resource`,ActionId:`actionId`,HttpMethod:`httpMethod`,AccountSecureId:`accountSecureId`,SourceType:`sourceType`,StatusCode:`statusCode`,OriginOwnerId:`originOwnerId`,SourceId:`sourceId`,AuthType:`authType`,AuthId:`authId`,IsBackground:`isBackground`,PolicyResult:`policyResult`,RiskLevel:`riskLevel`},Ee={EventType:`eventType`,Action:`action`,Resource:`resource`,Service:`service`,SourceType:`sourceType`,SourceId:`sourceId`,AuthType:`authType`,UserEmail:`userEmail`,StatusCode:`statusCode`,Success:`success`,IsRead:`isRead`,AgentId:`agentId`,TransportType:`transportType`,StreamType:`streamType`},De={actions:[`internal`],steps:[`internal`],unified_requests:[`internal`],provider_requests:[`internal`],platform:[`internal`]},isPlatformLog=e=>typeof e==`object`&&!!e&&`logType`in e&&e.logType===w.Platform,Oe={account_secure_id:`accountSecureId`,connector_key:`connectorKey`,connector_version:`connectorVersion`,connector_owner:`connectorOwner`,connector_profile_id:`connectorProfileId`,action_id:`actionId`,action_run_id:`actionRunId`,action_type:`actionType`,source_type:`sourceType`,source_id:`sourceId`,mode:`mode`,origin_owner_id:`originOwnerId`,origin_owner_name:`originOwnerName`,auth_type:`authType`,auth_id:`authId`,user_agent:`userAgent`,ip_address:`ipAddress`,session_id:`sessionId`,agent_id:`agentId`,transport_type:`transportType`,stream_type:`streamType`,http_method:`httpMethod`,service:`service`,resource:`resource`,risk_level:`riskLevel`,policy_result:`policyResult`,success:`success`,is_background:`isBackground`,status_code:`statusCode`,duration_ms:`durationMs`,log_id:`logId`,request_id:`requestId`,session_auth_id:`if(authType = 'SESSION_TOKEN', authId, NULL)`},ke=Object.keys(Oe),Ae=new Set([`status_code`,`duration_ms`]),je=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`],Me=new Set([`gt`,`gte`,`lt`,`lte`]),isFiniteNumber=e=>!!e.trim()&&Number.isFinite(Number(e)),isInt16=e=>{let t=Number(e);return isFiniteNumber(e)&&Number.isInteger(t)&&t>=-32768&&t<=32767},Ne=new Set([`status_code`]),E=new Set([`success`,`is_background`]),Pe=v.object({field:v.enum(ke),operator:v.enum(je),values:v.array(v.string().min(1).max(2048)).min(1).max(500)}).refine(({field:e,operator:t,values:n})=>{let r=Ae.has(e);return Me.has(t)&&(!r||n.length!==1)?!1:Ne.has(e)?n.every(isInt16):r?n.every(isFiniteNumber):E.has(e)?n.every(e=>e===`true`||e===`false`):!0},{message:`Invalid log comparison values`}),Fe=v.array(Pe).max(50);var InvalidLogQueryConditionsError=class extends Error{constructor(e){super(`Invalid log query conditions`),this.name=`InvalidLogQueryConditionsError`,this.cause=e,this.issues=e.issues.map(({path:e,message:t})=>({path:e.filter(e=>typeof e!=`symbol`),message:t}))}};const parseLogQueryConditions=(e=[])=>{let t=Fe.safeParse(e);if(!t.success)throw new InvalidLogQueryConditionsError(t.error);return t.data},Ie={type:`Int16`,cast:Number},Le={type:`Float64`,cast:Number},Re={type:`UInt8`,cast:e=>+(e===`true`)},ze={type:`String`,cast:e=>e},valueKind=e=>Ne.has(e)?Ie:Ae.has(e)?Le:E.has(e)?Re:ze,Be={eq:{operator:`IN`,whenMissing:0},ne:{operator:`NOT IN`,whenMissing:1}},Ve={gt:`>`,gte:`>=`,lt:`<`,lte:`<=`},isComparison=e=>Me.has(e),buildCondition=({field:e,operator:t,values:n},r)=>{let i=`logCondition${r}`,a=Oe[e],{type:o,cast:s}=valueKind(e);if(isComparison(t))return{sql:`${a} ${Ve[t]} {${i}:${o}}`,params:{[i]:s(n[0])}};let{operator:c,whenMissing:l}=Be[t];return{sql:`ifNull(${a} ${c} {${i}:Array(${o})}, ${l})`,params:{[i]:n.map(e=>s(e))}}},and=e=>({sql:e.map(({sql:e})=>`(${e})`).join(` AND `),params:Object.assign({},...e.map(({params:e})=>e))}),buildLogConditions=e=>and(parseLogQueryConditions(e).map(buildCondition)),He={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},untypedFilter=(e,t)=>e[t];function buildCommonLogParams(e){return{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),transportType:toArray(e.transportType),streamType:toArray(e.streamType),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),logId:toArray(e.logId),requestId:toArray(e.requestId),resource:toArray(e.resource),service:toArray(e.service),subResource:toArray(e.subResource),childResource:toArray(e.childResource),action:toArray(e.action),actionRunId:toArray(e.actionRunId),actionId:toArray(e.actionId),actionType:toArray(e.actionType),category:toArray(e.category),path:toArray(untypedFilter(e,`path`)),accountId:toArray(untypedFilter(e,`accountId`)),riskLevel:toArray(untypedFilter(e,`riskLevel`)),policyResult:toArray(untypedFilter(e,`policyResult`)),status:toStatusCodes(untypedFilter(e,`status`))}}const Ue=[...`organizationId.projectSecureId.accountSecureId.connectorKey.connectorVersion.connectorOwner.connectorProfileId.sourceType.sourceId.sourceValue.authType.authId.sessionId.agentId.userAgent.ipAddress.transportType.streamType.mode.httpMethod.originOwnerId.originOwnerName.logId.requestId.resource.service.subResource.childResource.action.actionRunId.actionId.actionType.category.path.accountId.riskLevel.policyResult.logType`.split(`.`).map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`status = {status:Array(Int16)}`,`isBackground = {isBackground:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),We=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
25
25
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
26
- AND ${_}`,buildLogsViewParams=e=>({...buildCommonLogParams(e),logType:toArray(e.logType)}),Ie={action_id:`actionId`,action_run_id:`actionRunId`,action_type:`actionType`,policy_result:`policyResult`,request_id:`requestId`,resource:`resource`,risk_level:`riskLevel`,service:`service`},bindSingleTableMatches=(e,t)=>t.reduce((e,{field:t,operator:n,values:r})=>{let i=Ie[t];if(!i||n!==`eq`)return e;let a=narrowArrayFilter(e[i],r);return a?{...e,[i]:a}:e},e),buildLogsView=e=>{let t=buildLogConditions(e.conditions);return{sql:`SELECT * FROM logs_filtered(${Pe}) ${Fe}${t.sql?` AND ${t.sql}`:``}`,params:{...bindSingleTableMatches(buildLogsViewParams(e),parseLogQueryConditions(e.conditions)),...t.params}}};function buildLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,Ne,`eventTime`),i=sanitizeOrderDirection(e.orderDirection),a=buildLogsView(e);return{sql:`
26
+ AND ${y}`,buildLogsViewParams=e=>({...buildCommonLogParams(e),logType:toArray(e.logType)}),Ge={action_id:`actionId`,action_run_id:`actionRunId`,action_type:`actionType`,policy_result:`policyResult`,request_id:`requestId`,resource:`resource`,risk_level:`riskLevel`,service:`service`},bindSingleTableMatches=(e,t)=>t.reduce((e,{field:t,operator:n,values:r})=>{let i=Ge[t];if(!i||n!==`eq`)return e;let a=narrowArrayFilter(e[i],r);return a?{...e,[i]:a}:e},e),buildLogsView=e=>{let t=buildLogConditions(e.conditions);return{sql:`SELECT * FROM logs_filtered(${Ue}) ${We}${t.sql?` AND ${t.sql}`:``}`,params:{...bindSingleTableMatches(buildLogsViewParams(e),parseLogQueryConditions(e.conditions)),...t.params}}};function buildLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize),r=sanitizeOrderBy(e.orderBy,He,`eventTime`),i=sanitizeOrderDirection(e.orderDirection),a=buildLogsView(e);return{sql:`
27
27
  ${a.sql}
28
28
  ORDER BY ${r} ${i}
29
29
  LIMIT {limit:UInt32}
30
30
  OFFSET {offset:UInt32}
31
31
  `,params:{...a.params,limit:t,offset:n}}}function buildLogsCountQuery(e){let t=buildLogsView(e);return{sql:`
32
32
  SELECT count() as total FROM (${t.sql})
33
- `,params:t.params}}const Le={id:`project_logs`,buildQuery:buildLogsQuery,buildCountQuery:buildLogsCountQuery},N={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},P={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},Re={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(P,e)?P[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(Re,e)?Re[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=buildLogsView(e),n=toCsvArray(e.dimensions).map(l),r=e.intervalType??`hour`,i=Math.floor(Number(e.intervalPeriod??1)),a=Number.isFinite(i)&&i>0?i:1,o=n.filter(e=>Object.prototype.hasOwnProperty.call(N,e)).map(e=>N[e]),s=r===w.None?void 0:buildTimeBucket(r,a),c=[...s?[`${s} as startTime`]:[],`count() as count`,...o].join(`, `),u=[...s?[`startTime`]:[],...o],d=u.length>0?`GROUP BY ${u.join(`, `)}`:``,f=s?`ORDER BY startTime ASC`:``;return{sql:`
33
+ `,params:t.params}}const Ke={id:`project_logs`,buildQuery:buildLogsQuery,buildCountQuery:buildLogsCountQuery},D={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},O={minute:`toStartOfMinute`,hour:`toStartOfHour`,day:`toStartOfDay`,week:`toStartOfWeek`,month:`toStartOfMonth`},k={minute:60,hour:3600,day:86400,week:604800,month:2592e3};function buildTimeBucket(e,t){let n=Object.prototype.hasOwnProperty.call(O,e)?O[e]:`toStartOfHour`;if(t<=1)return`${n}(eventTime)`;let r=t*(Object.prototype.hasOwnProperty.call(k,e)?k[e]:3600);return`toDateTime(intDiv(toUnixTimestamp(${n}(eventTime)), ${r}) * ${r})`}function buildAggregationQuery(e){let t=buildLogsView(e),n=toCsvArray(e.dimensions).map(h),r=e.intervalType??`hour`,i=Math.floor(Number(e.intervalPeriod??1)),a=Number.isFinite(i)&&i>0?i:1,o=n.filter(e=>Object.prototype.hasOwnProperty.call(D,e)).map(e=>D[e]),s=r===T.None?void 0:buildTimeBucket(r,a),c=[...s?[`${s} as startTime`]:[],`count() as count`,...o].join(`, `),l=[...s?[`startTime`]:[],...o],u=l.length>0?`GROUP BY ${l.join(`, `)}`:``,d=s?`ORDER BY startTime ASC`:``;return{sql:`
34
34
  WITH logs AS (
35
35
  ${t.sql}
36
36
  )
37
37
  SELECT
38
38
  ${c}
39
39
  FROM logs
40
+ ${u}
40
41
  ${d}
41
- ${f}
42
- `,params:t.params}}const ze={id:`project_logs_aggregation`,buildQuery:buildAggregationQuery},F={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},I=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(l),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(F,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildLogsView(e),a=i.sql;return{sql:r.map(e=>{let t=F[e];return`
42
+ `,params:t.params}}const qe={id:`project_logs_aggregation`,buildQuery:buildAggregationQuery},A={connectorKey:`connectorKey`,success:`success`,actionType:`actionType`,mode:`mode`,service:`service`,resource:`resource`,actionId:`actionId`,httpMethod:`httpMethod`,accountSecureId:`accountSecureId`,sourceType:`sourceType`,statusCode:`statusCode`,originOwnerId:`originOwnerId`,sourceId:`sourceId`,authType:`authType`,authId:`authId`,isBackground:`isBackground`,policyResult:`policyResult`,riskLevel:`riskLevel`},j=new Set([`connectorKey`,`actionType`,`mode`,`service`,`resource`,`actionId`,`httpMethod`,`accountSecureId`,`sourceType`,`originOwnerId`,`sourceId`,`authType`,`authId`,`policyResult`,`riskLevel`]);function buildDimensionsQuery(e){let t=toCsvArray(e.dimensions).map(h),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(A,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildLogsView(e),a=i.sql;return{sql:r.map(e=>{let t=A[e];return`
43
43
  SELECT
44
44
  '${e}' as dimension,
45
45
  arrayReverseSort(
@@ -54,14 +54,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
54
54
  ${a}
55
55
  ) AS logs
56
56
  WHERE ${t} IS NOT NULL
57
- ${I.has(e)?`AND ${t} != ''`:``}
57
+ ${j.has(e)?`AND ${t} != ''`:``}
58
58
  GROUP BY ${t}
59
59
  ORDER BY count DESC
60
60
  LIMIT {maxValues:UInt32}
61
61
  ) AS facets
62
62
  `}).join(`
63
63
  UNION ALL
64
- `),params:{...i.params,maxValues:n}}}const Be={id:`project_logs_dimensions`,buildQuery:buildDimensionsQuery},narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=narrowArrayFilter(e[t],n);return r?{[t]:r}:{}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!I.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=buildLogsView(e),r=`
64
+ `),params:{...i.params,maxValues:n}}}const Je={id:`project_logs_dimensions`,buildQuery:buildDimensionsQuery},narrowScanFilter=(e,t,n)=>{if(!(t in e))return{};let r=narrowArrayFilter(e[t],n);return r?{[t]:r}:{}},buildLastLogsQuery=e=>{let t=e.entities?.field;if(!t||!j.has(t))return{sql:`SELECT 1 WHERE 0`,params:{}};let n=buildLogsView(e),r=`
65
65
  WITH logs AS (
66
66
  ${n.sql}
67
67
  )
@@ -69,10 +69,10 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
69
69
  WHERE ${t} IN {entityIds:Array(String)}
70
70
  ORDER BY eventTime DESC
71
71
  LIMIT 1 BY ${t}
72
- `,i=toArray(e.entities?.ids),a=n.params;return{sql:r,params:{...a,...narrowScanFilter(a,t,i),entityIds:i}}},Ve={id:`project_last_logs`,buildQuery:buildLastLogsQuery},He=[...[`organizationId`,`projectSecureId`,`eventId`,`eventType`,`service`,`userId`,`userEmail`,`action`,`resource`,`resourceId`,`sourceType`,`sourceId`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`].map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isRead = {isRead:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),L={eventType:`eventType`,action:`action`,resource:`resource`,service:`service`,sourceType:`sourceType`,sourceId:`sourceId`,authType:`authType`,userEmail:`userEmail`,statusCode:`statusCode`,success:`success`,isRead:`isRead`,agentId:`agentId`,transportType:`transportType`,streamType:`streamType`},Ue=new Set([`statusCode`,`success`,`isRead`]),We=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
72
+ `,i=toArray(e.entities?.ids),a=n.params;return{sql:r,params:{...a,...narrowScanFilter(a,t,i),entityIds:i}}},Ye={id:`project_last_logs`,buildQuery:buildLastLogsQuery},Xe=[...[`organizationId`,`projectSecureId`,`eventId`,`eventType`,`service`,`userId`,`userEmail`,`action`,`resource`,`resourceId`,`sourceType`,`sourceId`,`authType`,`authId`,`userAgent`,`ipAddress`,`sessionId`,`agentId`,`transportType`,`streamType`].map(e=>`${e} = {${e}:Array(String)}`),`statusCode = {statusCode:Array(Int16)}`,`isRead = {isRead:Nullable(UInt8)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),M={eventType:`eventType`,action:`action`,resource:`resource`,service:`service`,sourceType:`sourceType`,sourceId:`sourceId`,authType:`authType`,userEmail:`userEmail`,statusCode:`statusCode`,success:`success`,isRead:`isRead`,agentId:`agentId`,transportType:`transportType`,streamType:`streamType`},Ze=new Set([`statusCode`,`success`,`isRead`]),Qe=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
73
73
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`,buildPlatformViewSource=()=>`SELECT *
74
- FROM platform_filtered(${He})
75
- ${We}`,buildPlatformViewParams=e=>({organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)});function buildPlatformDimensionsQuery(e){let t=toArray(e.dimensions).map(l),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(L,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildPlatformViewSource();return{sql:r.map(e=>{let t=L[e];return`
74
+ FROM platform_filtered(${Xe})
75
+ ${Qe}`,buildPlatformViewParams=e=>({organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)});function buildPlatformDimensionsQuery(e){let t=toArray(e.dimensions).map(h),n=e.maxValues??100,r=t.filter(e=>Object.prototype.hasOwnProperty.call(M,e));if(r.length===0)return{sql:`SELECT 1 WHERE 0`,params:{}};let i=buildPlatformViewSource();return{sql:r.map(e=>{let t=M[e];return`
76
76
  SELECT
77
77
  '${e}' as dimension,
78
78
  arrayReverseSort(
@@ -87,14 +87,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
87
87
  ${i}
88
88
  ) AS platformLogs
89
89
  WHERE ${t} IS NOT NULL
90
- ${Ue.has(e)?``:`AND ${t} != ''`}
90
+ ${Ze.has(e)?``:`AND ${t} != ''`}
91
91
  GROUP BY ${t}
92
92
  ORDER BY count DESC
93
93
  LIMIT {maxValues:UInt32}
94
94
  ) AS facets
95
95
  `}).join(`
96
96
  UNION ALL
97
- `),params:{...buildPlatformViewParams(e),maxValues:n}}}const Ge={id:`organization_platform_dimensions`,buildQuery:buildPlatformDimensionsQuery},Ke={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
97
+ `),params:{...buildPlatformViewParams(e),maxValues:n}}}const $e={id:`organization_platform_dimensions`,buildQuery:buildPlatformDimensionsQuery},et={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`};function buildPlatformLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
98
98
  SELECT
99
99
  eventTime,
100
100
  startTime,
@@ -152,7 +152,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
152
152
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
153
153
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
154
154
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
155
- ORDER BY ${sanitizeOrderBy(e.orderBy,Ke,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
155
+ ORDER BY ${sanitizeOrderBy(e.orderBy,et,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
156
156
  LIMIT {limit:UInt32}
157
157
  OFFSET {offset:UInt32}
158
158
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildPlatformLogsCountQuery(e){return{sql:`
@@ -184,19 +184,19 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
184
184
  AND ({success:Nullable(UInt8)} IS NULL OR success = {success:Nullable(UInt8)})
185
185
  AND ({startTime:Nullable(DateTime64(3))} IS NULL OR eventTime >= {startTime:Nullable(DateTime64(3))})
186
186
  AND ({endTime:Nullable(DateTime64(3))} IS NULL OR eventTime <= {endTime:Nullable(DateTime64(3))})
187
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const qe={id:`organization_platform_logs`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery},Je={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},R=`provider_logs_filtered`,z=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),B=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
187
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),eventId:toArray(e.eventId),eventType:toArray(e.eventType),service:toArray(e.service),userId:toArray(e.userId),userEmail:toArray(e.userEmail),action:toArray(e.action),resource:toArray(e.resource),resourceId:toArray(e.resourceId),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),authType:toArray(e.authType),authId:toArray(e.authId),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),statusCode:toStatusCodes(e.statusCode),isRead:e.isRead===void 0?null:+!!e.isRead,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const tt={id:`organization_platform_logs`,buildQuery:buildPlatformLogsQuery,buildCountQuery:buildPlatformLogsCountQuery},nt={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},N=`provider_logs_filtered`,P=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`requestId = {requestId:Array(String)}`,`id = {id:Array(String)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),F=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
188
188
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildProviderLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
189
189
  SELECT *
190
- FROM ${R}(${z})
191
- ${B}
192
- ORDER BY ${sanitizeOrderBy(e.orderBy,Je,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
190
+ FROM ${N}(${P})
191
+ ${F}
192
+ ORDER BY ${sanitizeOrderBy(e.orderBy,nt,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
193
193
  LIMIT {limit:UInt32}
194
194
  OFFSET {offset:UInt32}
195
195
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildProviderLogsCountQuery(e){return{sql:`
196
196
  SELECT count() as total
197
- FROM ${R}(${z})
198
- ${B}
199
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Ye={id:`project_provider_logs`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery};function buildSourceUsageQuery(e){return{sql:`
197
+ FROM ${N}(${P})
198
+ ${F}
199
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),id:toArray(e.id),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const rt={id:`project_provider_logs`,buildQuery:buildProviderLogsQuery,buildCountQuery:buildProviderLogsCountQuery};function buildSourceUsageQuery(e){return{sql:`
200
200
  SELECT
201
201
  sourceId,
202
202
  sourceType,
@@ -213,29 +213,29 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{calculateSize as t,convertKeysTo
213
213
  AND sourceId != ''
214
214
  GROUP BY sourceId, sourceType
215
215
  ORDER BY request_count DESC
216
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const Xe={id:`project_source_usage`,buildQuery:buildSourceUsageQuery},Ze={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},Qe=`step_logs_filtered`,$e=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`actionRunId = {actionRunId:Array(String)}`,`stepId = {stepId:Array(String)}`,`stepIndex = {stepIndex:Array(Int32)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),et=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
216
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),sourceType:toArray(e.sourceType),startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const it={id:`project_source_usage`,buildQuery:buildSourceUsageQuery},at={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},I=`step_logs_filtered`,L=[`organizationId = {organizationId:Array(String)}`,`projectSecureId = {projectSecureId:Array(String)}`,`accountSecureId = {accountSecureId:Array(String)}`,`actionRunId = {actionRunId:Array(String)}`,`stepId = {stepId:Array(String)}`,`stepIndex = {stepIndex:Array(Int32)}`,`success = {success:Nullable(UInt8)}`,`startTime = {startTime:Nullable(DateTime64(3))}`,`endTime = {endTime:Nullable(DateTime64(3))}`].join(`, `),R=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
217
217
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}`;function buildStepLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
218
218
  SELECT *
219
- FROM ${Qe}(${$e})
220
- ${et}
221
- ORDER BY ${sanitizeOrderBy(e.orderBy,Ze,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
219
+ FROM ${I}(${L})
220
+ ${R}
221
+ ORDER BY ${sanitizeOrderBy(e.orderBy,at,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
222
222
  LIMIT {limit:UInt32}
223
223
  OFFSET {offset:UInt32}
224
224
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildStepLogsCountQuery(e){return{sql:`
225
225
  SELECT count() as total
226
- FROM ${Qe}(${$e})
227
- ${et}
228
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const tt={id:`project_step_logs`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery},nt={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},rt=`unified_logs_filtered`,it=`organizationId = {organizationId:Array(String)}.projectSecureId = {projectSecureId:Array(String)}.accountSecureId = {accountSecureId:Array(String)}.requestId = {requestId:Array(String)}.connectorKey = {connectorKey:Array(String)}.connectorVersion = {connectorVersion:Array(String)}.connectorOwner = {connectorOwner:Array(String)}.connectorProfileId = {connectorProfileId:Array(String)}.mode = {mode:Array(String)}.httpMethod = {httpMethod:Array(String)}.resource = {resource:Array(String)}.subResource = {subResource:Array(String)}.childResource = {childResource:Array(String)}.service = {service:Array(String)}.action = {action:Array(String)}.sourceType = {sourceType:Array(String)}.sourceId = {sourceId:Array(String)}.sourceValue = {sourceValue:Array(String)}.authType = {authType:Array(String)}.authId = {authId:Array(String)}.userAgent = {userAgent:Array(String)}.ipAddress = {ipAddress:Array(String)}.sessionId = {sessionId:Array(String)}.agentId = {agentId:Array(String)}.transportType = {transportType:Array(String)}.streamType = {streamType:Array(String)}.originOwnerId = {originOwnerId:Array(String)}.originOwnerName = {originOwnerName:Array(String)}.statusCode = {statusCode:Array(Int16)}.isBackground = {isBackground:Nullable(UInt8)}.success = {success:Nullable(UInt8)}.startTime = {startTime:Nullable(DateTime64(3))}.endTime = {endTime:Nullable(DateTime64(3))}`.split(`.`).join(`, `),at=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
226
+ FROM ${I}(${L})
227
+ ${R}
228
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),actionRunId:toArray(e.actionRunId),stepId:toArray(e.stepId),stepIndex:toArray(e.stepIndex),success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const ot={id:`project_step_logs`,buildQuery:buildStepLogsQuery,buildCountQuery:buildStepLogsCountQuery},st={startTime:`startTime`,endTime:`endTime`,eventTime:`eventTime`,durationMs:`durationMs`},z=`unified_logs_filtered`,B=`organizationId = {organizationId:Array(String)}.projectSecureId = {projectSecureId:Array(String)}.accountSecureId = {accountSecureId:Array(String)}.requestId = {requestId:Array(String)}.connectorKey = {connectorKey:Array(String)}.connectorVersion = {connectorVersion:Array(String)}.connectorOwner = {connectorOwner:Array(String)}.connectorProfileId = {connectorProfileId:Array(String)}.mode = {mode:Array(String)}.httpMethod = {httpMethod:Array(String)}.resource = {resource:Array(String)}.subResource = {subResource:Array(String)}.childResource = {childResource:Array(String)}.service = {service:Array(String)}.action = {action:Array(String)}.sourceType = {sourceType:Array(String)}.sourceId = {sourceId:Array(String)}.sourceValue = {sourceValue:Array(String)}.authType = {authType:Array(String)}.authId = {authId:Array(String)}.userAgent = {userAgent:Array(String)}.ipAddress = {ipAddress:Array(String)}.sessionId = {sessionId:Array(String)}.agentId = {agentId:Array(String)}.transportType = {transportType:Array(String)}.streamType = {streamType:Array(String)}.originOwnerId = {originOwnerId:Array(String)}.originOwnerName = {originOwnerName:Array(String)}.statusCode = {statusCode:Array(Int16)}.isBackground = {isBackground:Nullable(UInt8)}.success = {success:Nullable(UInt8)}.startTime = {startTime:Nullable(DateTime64(3))}.endTime = {endTime:Nullable(DateTime64(3))}`.split(`.`).join(`, `),V=`WHERE ${buildArrayFilter(`organizationId`,`organizationId`)}
229
229
  AND ${buildArrayFilter(`projectSecureId`,`projectSecureId`)}
230
- AND ${_}`;function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
230
+ AND ${y}`;function buildUnifiedLogsQuery(e){let{limit:t,offset:n}=buildPaginationParams(e.pageNumber,e.pageSize);return{sql:`
231
231
  SELECT *
232
- FROM ${rt}(${it})
233
- ${at}
234
- ORDER BY ${sanitizeOrderBy(e.orderBy,nt,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
232
+ FROM ${z}(${B})
233
+ ${V}
234
+ ORDER BY ${sanitizeOrderBy(e.orderBy,st,`eventTime`)} ${sanitizeOrderDirection(e.orderDirection)}
235
235
  LIMIT {limit:UInt32}
236
236
  OFFSET {offset:UInt32}
237
237
  `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime),limit:t,offset:n}}}function buildUnifiedLogsCountQuery(e){return{sql:`
238
238
  SELECT count() as total
239
- FROM ${rt}(${it})
240
- ${at}
241
- `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const ot={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=te({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(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:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},V=f.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new f.ZodError([{code:f.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},f.coerce.date()),H=f.object({logType:f.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:V,startTime:V,endTime:V.optional().nullable().transform(e=>e??void 0),durationMs:f.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:f.coerce.string(),projectSecureId:f.coerce.string().optional().nullable().transform(e=>e??void 0)}),U=H.extend({logType:f.literal(`action`),actionRunId:f.coerce.string(),actionId:f.coerce.string(),connectorKey:f.coerce.string(),connectorVersion:f.coerce.string(),connectorOwner:f.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:f.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:f.coerce.string(),accountSecureId:f.coerce.string(),actionType:f.coerce.string().optional().nullable().transform(e=>e??void 0),mode:f.coerce.string().optional().nullable().transform(e=>e??void 0),category:f.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:f.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:f.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:f.coerce.string().optional().nullable().transform(e=>e??void 0),url:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:f.coerce.string().optional().nullable().transform(e=>e??void 0),authType:f.coerce.string().optional().nullable().transform(e=>e??void 0),authId:f.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:f.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:f.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:f.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:f.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:f.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:f.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:f.coerce.string().optional().nullable().transform(e=>e??void 0),success:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:f.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:f.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:f.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:f.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:f.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:f.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:f.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:f.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:f.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:f.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:V.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:V.optional().nullable().transform(e=>e??void 0)}),W=H.extend({logType:f.literal(`step`),actionRunId:f.coerce.string(),stepIndex:f.coerce.number(),stepId:f.coerce.string(),projectSecureId:f.coerce.string(),accountSecureId:f.coerce.string(),skipped:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:f.coerce.number().optional().nullable().transform(e=>e??void 0),message:f.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:f.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:f.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:f.coerce.number().optional().nullable().transform(e=>e??void 0)}),G=H.extend({logType:f.literal(`unified`),requestId:f.coerce.string(),connectorKey:f.coerce.string(),connectorVersion:f.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:f.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:f.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:f.coerce.string(),accountSecureId:f.coerce.string(),mode:f.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:f.coerce.string().optional().nullable().transform(e=>e??void 0),url:f.coerce.string().optional().nullable().transform(e=>e??void 0),path:f.coerce.string().optional().nullable().transform(e=>e??void 0),resource:f.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:f.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:f.coerce.string().optional().nullable().transform(e=>e??void 0),service:f.coerce.string().optional().nullable().transform(e=>e??void 0),action:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:f.coerce.string().optional().nullable().transform(e=>e??void 0),authType:f.coerce.string().optional().nullable().transform(e=>e??void 0),authId:f.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:f.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:f.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:f.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:f.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:f.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:f.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:f.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:f.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:f.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:f.coerce.number().optional().nullable().transform(e=>e??void 0),success:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:f.coerce.number().optional().nullable().transform(e=>e??void 0),provider:f.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:V.optional().nullable().transform(e=>e??void 0),duration:f.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:V.optional().nullable().transform(e=>e??void 0)}),K=H.extend({logType:f.literal(`provider`),requestId:f.coerce.string(),id:f.coerce.string().optional().nullable().transform(e=>e??void 0),action:f.coerce.string(),mode:f.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:f.coerce.string(),originOwnerId:f.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:f.coerce.string().optional().nullable().transform(e=>e??void 0),url:f.coerce.string(),path:f.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:f.coerce.string(),connectorVersion:f.coerce.string().optional().nullable().transform(e=>e??void 0),resource:f.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:f.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:f.coerce.string().optional().nullable().transform(e=>e??void 0),service:f.coerce.string().optional().nullable().transform(e=>e??void 0),success:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:f.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:f.coerce.string(),accountSecureId:f.coerce.string(),status:f.coerce.number().optional().nullable().transform(e=>e??void 0),provider:f.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:V.optional().nullable().transform(e=>e??void 0),duration:f.coerce.number().optional().nullable().transform(e=>e??void 0)}),st=H.extend({logType:f.literal(`platform`),eventId:f.coerce.string(),eventType:f.coerce.string(),service:f.coerce.string(),organizationId:f.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:f.undefined().optional(),userId:f.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:f.coerce.string().optional().nullable().transform(e=>e??void 0),action:f.coerce.string().optional().nullable().transform(e=>e??void 0),resource:f.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:f.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:f.coerce.string().optional().nullable().transform(e=>e??void 0),authType:f.coerce.string().optional().nullable().transform(e=>e??void 0),authId:f.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:f.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:f.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:f.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:f.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:f.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:f.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:f.coerce.number().optional().nullable().transform(e=>e??void 0),success:f.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:f.record(f.string(),f.unknown()).optional().nullable().transform(e=>e??void 0)}),ct=f.discriminatedUnion(`logType`,[U,W,G,K]),lt=new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},ut=[`success`,`isWorker`,`isBackground`,`skipped`];var QueryClientNotConfiguredError=class extends Error{constructor(){super(`No ClickHouse query client is configured`),this.name=`QueryClientNotConfiguredError`}};const q=15e3;var LogsSink=class{#e;#t;#n;#r;#i;#a(){if(!this.#r?.isReady())throw new QueryClientNotConfiguredError;return this.#r}#o(e){parseLogQueryConditions(e.conditions)}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#u()}async close(e=3e4){return this.#s??=this.#c(e),this.#s}#s;async#c(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#l(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#l(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#u(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`connectivity probe timed out after ${q}ms`)),q),n.unref?.()})]),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}finally{n&&clearTimeout(n)}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.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,metadata:n})=>this.buildActionLog(e,t,n));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.#i?.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,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){this.#o(e);let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Le,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for logs`,category:`LogsSink`,code:`LogsQueryFailed`,error:e}),e}}async getLastLogs(e,t){this.#o(t);let n=this.#a(),r=e?.ids??[];if(r.length===0)return emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${r.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await n.queryWithPagination({query:Ve,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for last logs`,category:`LogsSink`,code:`LastLogsQueryFailed`,error:e}),e}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:ve,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,U),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for action logs, 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){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:tt,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for step logs, 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){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:ot,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for unified logs, 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){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ye,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t.query({query:Ge,params:e});this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=lt.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:qe,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,st),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],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 getAggregate(e,t,r){this.#o(r);let i=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:r}});let{dimensions:a,startTime:o,endTime:s,...c}=r,l=r.intervalType===w.None,u={organizationId:e,projectSecureId:t,...c,...a&&a.length>0&&{dimensions:a.join(`,`)},...o&&{startTime:o.toISOString()},...s&&{endTime:s.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await i.query({query:ze,params:u});this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>n(e,!0)).map(e=>{let t={...e};for(let e of ut)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){throw this.#i?.error({message:`Failed to query for logs stats aggregate`,category:`LogsSink`,code:`LogsAggregateQueryFailed`,error:e}),e}}async getDimensions(e,t,n){this.#o(n);let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r.query({query:Be,params:c});this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)ut.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}catch(e){throw this.#i?.error({message:`Failed to query for logs stats dimensions`,category:`LogsSink`,code:`LogsDimensionsQueryFailed`,error:e}),e}}async getActionsCount(e){let[t]=await this.#a().query({query:be,params:e});return Number(t?.actions_count??0)}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r.query({query:Xe,params:s});return this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))}catch(e){return this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}),[]}}#d(e){return(this.#n??T)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#d(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#f(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#f(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.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.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...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},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}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,...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&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??u(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}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 d){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.issues,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,ct)}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 d?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.issues,log:safeSerialize(n)}}):this.#i?.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 U;case`step`:return W;case`unified`:return G;case`provider`:return K;case`platform`:return st}}};const readStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let r=await e.readText(t);if(r===void 0){a?.debug({message:`No ${n} in storage`,category:i});return}return a?.debug({message:`Retrieved ${n} from storage`,category:i}),JSON.parse(r)}catch(e){throw a?.error({message:`Error when getting ${n} from storage`,error:e,code:r,category:i}),e}},writeStoredLog=async({bucket:e,key:t,body:n,ttlTag:r,expiresAt:i,description:a,errorCode:o,category:s,logger:c})=>{try{await e.write(t,n,{contentType:`application/json`,tags:{ttl:r},expiresAt:i})}catch(e){throw c?.error({message:`Failed to write ${a} to storage at ${t}`,error:e,code:o,category:s}),e}},statStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let n=await e.stat(t);return n===void 0?{exists:!1}:{exists:!0,expiresAt:n.expiresAt}}catch(e){throw a?.error({message:`Error when checking ${n} in storage`,error:e,code:r,category:i}),e}},dt=64*1024,ft=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],pt=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>s(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return s(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,n)=>{let{kept:r,total:i}=e.reduce((e,r)=>{if(e.total>n)return e;let i=e.total+t(r);return i>n?{kept:e.kept,total:i}:{kept:e.kept+1,total:i}},{kept:0,total:0});return i>n?e.slice(0,r):e},fitObject=(e,n)=>{let r=Object.entries(e).map(([e,n])=>({key:e,value:n,size:e.length*2+t(n)})).sort((e,t)=>e.size-t.size),{kept:i,remaining:a}=r.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:n}),o=r.filter(e=>!i.includes(e.key)),s=o.length===0?0:Math.floor(a/o.length);return Object.fromEntries(r.map(e=>[e.key,i.includes(e.key)?e.value:fitValue(e.value,s)]))},fitValue=(e,n)=>{let r=t(e);return r<=n?e:(c(e)||Array.isArray(e)||s(e)&&!a(e))&&n<=0?marker(r):c(e)?fitString(e,n):Array.isArray(e)?fitArray(e,n):s(e)&&!a(e)?fitObject(e,n):e},payloadFields=e=>ft.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!o(e)).map(e=>({...e,size:t(e.value)})),byRetentionPriority=e=>[...e.filter(e=>pt.includes(e.path)),...e.filter(e=>!pt.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*dt;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(dt,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>ft.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),mt=[`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`],ht=[`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`],gt=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],parseActionUrl=e=>e.startsWith(`/`)?new URL(e,`http://path.invalid`):new URL(e),platformKey=(e,t)=>`${e}/platform/${t}.json`,J=`AdvancedSink`,errorName=e=>e instanceof Error?e.name:`non-Error thrown`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(this.#t){this.#i?.warning({message:`No storage provided, advanced sink will not function`,category:J});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed (${errorName(e)}), content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`})}}async scrubPii(e,n){if(!n?.piiRedactionEnabled||!this.#a||this.truncationMode(n)===`drop`&&t(e)>this.#n)return e;try{return await this.#a.scrubObject(e)}catch(t){return this.#i?.warning({message:`PII content scrub failed (${errorName(t)}), storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`}),e}}requireBucket(){if(!this.#e)throw Error(`Advanced sink bucket is not configured`);return this.#e}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled,errorsOnly:t?.errorsOnly,includeBackground:t?.includeBackground,ttl:t?.ttl}}}),!t?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(isDataSync(r.mode,r.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),n.push(null);continue}if(t.errorsOnly&&i.success&&!i.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${r.mode||`action`}`,category:`AdvancedSink`}),n.push(null);continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`AdvancedSink`}),n.push(null);continue}let[e,a,o]=await Promise.all([this.scrubPii(redactBody(r.body,r.headers),t),this.scrubPii(m(r.queryParams,p.PARTIAL,!0),t),this.scrubPii(m(r.pathParams,p.PARTIAL,!0),t)]),s={...r,body:e,queryParams:a,pathParams:o},c={...i,body:await this.scrubPii(redactBody(i.body??i.refusal,i.headers),t)},l=this.createActionItem(s,c,t),u=await this.send(l,t?.ttl);n.push(u)}return n}async sendStep(e,t,n){if(this.#i?.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)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode,e.actionSourceType))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(n.errorsOnly&&e.actionSuccess===!0&&t.success!==!1&&!hasErrorEntries(t.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let r={...e,inputs:await this.scrubPii(m(e.inputs,p.PARTIAL,!0),n)},i={...t,outputs:await this.scrubPii(m(t.outputs,p.PARTIAL,!0),n),errors:await this.scrubPii(m(t.errors,p.PARTIAL,!0),n)},a=this.createStepItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createUnifiedItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createProviderItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for actionRunId ${n}`)}async getStep(e,t,n,r){return this.read(`${e}/${t}/${n}/steps/${r}.json`,`step log for actionRunId ${n} stepIndex ${r}`)}async getUnified(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for requestId ${n}`)}async getProvider(e,t,n,r){return this.read(`${e}/${t}/${n}/provider/${r}.json`,`provider log for requestId ${n} id ${r}`)}async read(e,t){if(this.#t){this.#i?.warning({message:`No storage available, cannot get ${t} from advanced sink`,category:J});return}return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:J,logger:this.#i})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to advanced sink`);let n=this.requireBucket(),r=t===1?`1d`:t===7?`7d`:`30d`,i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);return this.#i?.debug({message:`Storing advanced log in bucket ${n.name} with ttl of ${r}`,category:J,context:{bucket:n.name,key:e.key,ttlTag:r,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:e.key,body:e.body,ttlTag:r,expiresAt:a,description:`advanced logs`,errorCode:`AdvancedLogWriteError`,category:J,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:J}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:J,logger:this.#i})}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformItem(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){return this.read(platformKey(e,t),`platform advanced log for eventId ${t}`)}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n))}}createStepItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n))}}createPlatformItem(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{key:i,body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,n){let r=m(e.data,p.PARTIAL,!0),i={...e.metadata,expirationTime:n,sizeBytes:t(r)};return this.stringifyPlatform({data:r,metadata:i},i)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n))}}createProviderItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n))}}serializeActionResult(e,t,n,r,i){let a=h(e.headers,p.PARTIAL),o=h(t.headers,p.PARTIAL),c=this.processContent(a,e.body,`upload`),l=this.processContent(o,t.body,`download`),u=e.isBackground??isBackgroundLog(e.mode,e.sourceType),d=e.url,f={};if(e.url)try{d=g(e.url,p.PARTIAL);let t=parseActionUrl(d);f=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let m={...f,...s(e.queryParams)?e.queryParams:{}},ee={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:d,path:e.pathParams,queryParams:m},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(ee,r,isErrorResult(t),i)}serializeStepResult(e,t,n,r,i){let a={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(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,t,n,r,i){let a=h(e.headers,p.PARTIAL),o=h(t.headers,p.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),l=e.isBackground??isBackgroundLog(e.mode,e.sourceType),u=`/`,d=e.url,f={};if(e.url)try{d=g(e.url,p.PARTIAL);let t=new URL(d);u=t.pathname,f=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let m={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:d,path:u,queryParams:f},body:s},response:{statusCode:t.statusCode??500,headers:this.filterHeaders(o),body:c}},metadata:{...l?{isBackgroundLog:!0}:{},expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),i)}serializeProviderResult(e,t,n,r,i){let a=h(e.headers,p.PARTIAL),o=h(t.headers,p.PARTIAL),s=this.processContent(a,e.body,`upload`),c=this.processContent(o,t.body,`download`),l,u=``,d=`/`,f={};if(e.url)try{l=g(e.url,p.PARTIAL);let t=new URL(l);u=t.hostname,d=t.pathname,f=Object.fromEntries(t.searchParams)}catch{this.#i?.warning({message:`Invalid URL in provider request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId,id:e.id}})}let m={data:{request:{id:e.id,method:e.httpMethod,headers:this.filterHeaders(a),url:{url:l,hostname:u,path:d,queryParams:f},body:s},response:{statusCode:t.statusCode,headers:this.filterHeaders(o),body:c}},metadata:{expirationTime:n}};return this.serializeAndLimit(m,r,isErrorResult(t),i)}serializeAndLimit(e,n,r,i){let a=t(e);if(i===`complete`)return this.stringifyLog(e,{sizeBytes:a});let o=r&&i===`truncate`?n*this.#r:n;if(a<=o)return this.stringifyLog(e,{sizeBytes:a});if(i===`drop`)return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:a,maxSizeBytes:o,truncated:!0});let{data:s,truncatedPaths:c}=truncateToLimit(e,o);return this.#i?.warning({message:`Advanced log of ${a} bytes exceeds ${o}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:a,maxSizeBytes:o,isErrorResult:r,truncatedPaths:c}}),this.stringifyLog(s,{sizeBytes:a,maxSizeBytes:o,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=mt.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 ht.includes(i)||gt.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!o(e)){if(!c(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const Y=2e3,settleWithin=(e,t,n)=>new Promise(r=>{let i=setTimeout(()=>r(n),t);i.unref?.(),e.then(e=>{clearTimeout(i),r(e)})});function defaultProviderFactory(e){let t=new ie({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`},timeoutMillis:Y}),n={[ce]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new oe({resource:ae(n),spanProcessors:[new se(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;#i=new Set;#a;#o=!1;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(!this.#r)return;if(this.#i.size>=4){this.#t?.debug({message:`Logfire exports at the limit, leaving spans queued for the next flush`,category:`DatasetsSink`,context:{maxExportsInFlight:4}});return}let e=this.#s()?Y:50;await settleWithin(this.#c(this.#r).then(()=>!0),e,!1)||this.#t?.debug({message:`Logfire export still running, not waiting for it`,category:`DatasetsSink`,context:{flushTimeoutMs:e}})}async drain(e=4e3){if(!this.#r)return;let t=[...this.#i,this.#c(this.#r)];await settleWithin(Promise.all(t).then(()=>!0),e,!1)||this.#t?.warning({message:`Logfire exports still running at shutdown, their spans may be lost`,code:`LogfireDrainTimeout`,category:`DatasetsSink`,context:{timeoutMs:e}})}#s(){return this.#o?!1:this.#a===void 0||Date.now()-this.#a>3e5}#c(e){let t=Date.now(),n=!1,r=setTimeout(()=>{n=Date.now()-t>=2250},Y);r.unref?.();let i=new Promise(t=>t(e.forceFlush())).then(()=>{this.#a=Date.now(),this.#o=!1},e=>this.#l(e,Date.now()-t,n));return this.#i.add(i),i.finally(()=>{clearTimeout(r),this.#i.delete(i)}),i}#l(e,t,n){if(n){this.#a=void 0,this.#o=!1,this.#t?.debug({message:`Logfire export failed after the process was frozen`,category:`DatasetsSink`,context:{elapsedMs:t,exportTimeoutMs:Y,error:String(e)}});return}this.#o=!0,this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`,context:{elapsedMs:t}})}},DatasetsSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async close(e){this.#a??=this.#r.drain?.(e),await this.#a}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:i,result:a}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:i.mode,actionId:i.actionId,actionRunId:i.actionRunId,success:a.success,statusCode:a.statusCode,includeBackground:t.includeBackground}}),o(i.body)&&o(a.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(isBackgroundLog(i.mode,i.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${i.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(i,a);if(o(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}if(r(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:i.actionRunId}});continue}this.send(i,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=o(e.body)?void 0:i(e.body),r=o(t.body)?void 0:i(t.body);if(!(o(n)&&o(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}};const X=`DefenderSink`;var DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#e)throw Error(`Defender sink bucket is not configured`);return this.#e}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, defender sink will not function`,category:X});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:X,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:X}),n.push(null);continue}if(o(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:X,context:{actionRunId:r.actionRunId}}),n.push(null);continue}n.push(await this.send(r,i))}return n}async getAction(e,t,n){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from defender sink`,category:X});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:X,logger:this.#r})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to defender sink`);let n=this.requireBucket(),r=defenderKey(e.organizationId,e.projectSecureId,e.actionRunId),i=Math.floor(Date.now()/1e3)+this.#n*24*60*60,a=new Date(i*1e3),o=`${this.#n}d`;return this.#r?.debug({message:`Storing defender log in bucket ${n.name} with ${this.#n}-day TTL`,category:X,context:{bucket:n.name,key:r,ttlTag:o,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:r,body:JSON.stringify(t.defenderContext),ttlTag:o,expiresAt:a,description:`defender log`,errorCode:`DefenderLogWriteError`,category:X,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,Z={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Z.logs,...e?.logs},advanced:{...Z.advanced,...e?.advanced},defender:{...Z.defender,...e?.defender},policy:{...Z.policy,...e?.policy},datasets:{...Z.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const Q=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, policy sink will not function`,category:Q});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(!t?.enabled){n.push(null);continue}if(!this.#e&&!this.#t){n.push(null);continue}if(o(i.policyContext)){n.push(null);continue}if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);n.push(await this.send(this.#e,r,i))}return n}async getAction(e,t,n,r){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:Q});return}if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:Q,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:Q,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,_t=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${_t}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${_t}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),vt=e(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=vt(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=vt(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?ne(re()):void 0;var $=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async close(e){await Promise.all([this.#r?.close?.(e),this.#s?.close(e)])}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,policy:a,datasets:s}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,policy:a,datasets:s}}});for(let t of e)o(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let c=a?.enabled&&this.#o?this.#o.sendActions(e,a).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs storage: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),l=s?.enabled&&this.#s?this.#s.sendActions(e,s).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[u,d]=await Promise.all([r?.enabled&&this.#i?this.#i.sendActions(e,r).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#a?this.#a.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),f=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:u[t]?.expiresAt,defenderExpiresAt:d[t]?.expiresAt}})),p=n?.enabled&&this.#r?this.#r.sendActions(f,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([l,c,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#n?.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}}}),o(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#i?await this.#i.sendUnified(e,t,i).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#r&&await this.#r.sendUnified(e,t,a,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.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.#r?.getAction(e,t,n);if(o(r)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.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.#r?.getStep(e,t,n,r);if(o(i)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.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.#r?.getUnifiedLog(e,t,n);if(o(r)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,n,r){let i=await this.#r?.getProviderLog(e,t,n,r);if(o(i)){this.#n?.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.#i?.getAction(e,t,n);if(o(r)){this.#n?.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.#i?.getStep(e,t,n,r);if(o(i)){this.#n?.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.#i?.getUnified(e,t,n);if(o(r)){this.#n?.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.#i?.getProvider(e,t,n,r);if(o(i)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#i?.getPlatform(e,t);if(o(n)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getPolicyLog(e,t,n,r){let i=await this.#o?.getAction(e,t,n,r);if(o(i)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(o(r)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>$.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};export{de as AuthType,T as DEFAULT_TOPIC_CLUSTER_MAP,Ce as Dimension,w as IntervalType,InvalidAuthPairError,InvalidLogQueryConditionsError,D as LOG_QUERY_FIELDS,k as LOG_QUERY_OPERATORS,C as LogType,$ as OlapClient,OlapClientManager,xe as OrderBy,Se as OrderDirection,we as PlatformDimension,PolicySink,QueryClientNotConfiguredError,v as SourceType,ue as StreamType,le as TransportType,getPolicySink,hasErrorEntries,parseLogQueryConditions};
239
+ FROM ${z}(${B})
240
+ ${V}
241
+ `,params:{organizationId:toArray(e.organizationId),projectSecureId:toArray(e.projectSecureId),accountSecureId:toArray(e.accountSecureId),requestId:toArray(e.requestId),connectorKey:toArray(e.connectorKey),connectorVersion:toArray(e.connectorVersion),connectorOwner:toArray(e.connectorOwner),connectorProfileId:toArray(e.connectorProfileId),mode:toArray(e.mode),httpMethod:toArray(e.httpMethod),resource:toArray(e.resource),subResource:toArray(e.subResource),childResource:toArray(e.childResource),service:toArray(e.service),action:toArray(e.action),sourceType:toArray(e.sourceType),sourceId:toArray(e.sourceId),sourceValue:toArray(e.sourceValue),authType:toArray(e.authType),authId:toArray(e.authId),...toAuthPairParams(e.authPairs),userAgent:toArray(e.userAgent),ipAddress:toArray(e.ipAddress),sessionId:toArray(e.sessionId),agentId:toArray(e.agentId),transportType:toArray(e.transportType),streamType:toArray(e.streamType),originOwnerId:toArray(e.originOwnerId),originOwnerName:toArray(e.originOwnerName),statusCode:toStatusCodes(e.statusCode),isBackground:e.isBackground===void 0?null:+!!e.isBackground,success:e.success===void 0?null:+!!e.success,startTime:toClickHouseDate(e.startTime),endTime:toClickHouseDate(e.endTime)}}}const ct={id:`project_unified_logs`,buildQuery:buildUnifiedLogsQuery,buildCountQuery:buildUnifiedLogsCountQuery};var SchemaValidationError=class extends Error{constructor(e,t){super(e),this.name=`SchemaValidationError`,this.cause=t}},ClickHouseClient=class{#e;#t;#n;constructor(e,t){this.#t=e,this.#n=t,e?.url&&(this.#e=ee({url:e.url,username:e.username,password:e.password,database:e.database,request_timeout:e.requestTimeout??3e4,compression:{request:!0,response:!0},clickhouse_settings:{output_format_json_quote_64bit_integers:0,output_format_json_named_tuples_as_objects:1}}))}async query(e){let{data:t}=await this.#a(e);return t}async queryWithPagination(e){let{data:t,total:n}=await this.#a(e);return{data:t,total:n??t.length,pageNumber:e.pageNumber??1,pageSize:e.pageSize??t.length}}isReady(){return!!(this.#e&&this.#t?.url)}async close(){await this.#e?.close()}#r(){if(!this.#e)throw this.#n?.error({message:`ClickHouse client not initialized`,category:`ClickHouseClient`,code:`ClientNotReady`}),Error(`ClickHouse client is not initialized`);if(!this.#t?.url)throw this.#n?.warning({message:`Missing ClickHouse URL`,category:`ClickHouseClient`}),Error(`ClickHouseClient - Missing URL`);return this.#e}#i(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:`ClickHouseClient`}),n}catch(e){let t=e instanceof Error?e.message:String(e);throw this.#n?.error({message:`Schema validation failed: ${t}`,category:`ClickHouseClient`,code:`SchemaValidationError`,error:e}),new SchemaValidationError(t,e)}}async#a(e){try{let{data:t,total:n}=await this.#o(e.query,e.params);return{data:this.#i(t,e.schema),total:n}}catch(t){if(t instanceof SchemaValidationError)throw t;let n=t instanceof Error?t.message:String(t);throw this.#n?.error({message:`Error running clickhouse query ${e.query.id}: ${n}`,category:`ClickHouseClient`,code:`ClickHouseQueryError`}),t}}async#o(e,t){let n=this.#r(),{sql:r,params:i}=e.buildQuery(t);this.#n?.debug({message:`Running clickhouse query: ${e.id}`,category:`ClickHouseClient`,context:{query:e.id,params:t}});let a=Date.now(),o=await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json(),s=(Date.now()-a)/1e3,c;if(e.buildCountQuery){let{sql:r,params:i}=e.buildCountQuery(t);c=(await(await n.query({query:r,query_params:i,format:`JSONEachRow`})).json())[0]?.total}return this.#n?.debug({message:`ClickHouse query returned ${o.length} rows`,category:`ClickHouseClient`,context:{query:e.id,rows:o.length,elapsed:s}}),{data:o,total:c}}};const hasTimezone=e=>/Z$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(e),utcDateTransform=e=>{if(hasTimezone(e))return e;let t=e.replace(` `,`T`);return new Date(t+`Z`).toISOString()},H=v.preprocess(e=>{if(e instanceof Date)return e;if(typeof e==`string`&&e.length>0)try{return new Date(utcDateTransform(e))}catch(e){throw new v.ZodError([{code:v.ZodIssueCode.custom,path:[],message:e instanceof Error?e.message:`Invalid date string`}])}return e},v.coerce.date()),U=v.object({logType:v.enum([`action`,`step`,`unified`,`provider`,`platform`]),eventTime:H,startTime:H,endTime:H.optional().nullable().transform(e=>e??void 0),durationMs:v.coerce.number().optional().nullable().transform(e=>e??void 0),organizationId:v.coerce.string(),projectSecureId:v.coerce.string().optional().nullable().transform(e=>e??void 0)}),W=U.extend({logType:v.literal(`action`),actionRunId:v.coerce.string(),actionId:v.coerce.string(),connectorKey:v.coerce.string(),connectorVersion:v.coerce.string(),connectorOwner:v.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:v.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:v.coerce.string(),accountSecureId:v.coerce.string(),actionType:v.coerce.string().optional().nullable().transform(e=>e??void 0),mode:v.coerce.string().optional().nullable().transform(e=>e??void 0),category:v.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:v.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:v.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:v.coerce.string().optional().nullable().transform(e=>e??void 0),url:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:v.coerce.string().optional().nullable().transform(e=>e??void 0),authType:v.coerce.string().optional().nullable().transform(e=>e??void 0),authId:v.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:v.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:v.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:v.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:v.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:v.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:v.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:v.coerce.string().optional().nullable().transform(e=>e??void 0),success:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:v.coerce.number().optional().nullable().transform(e=>e??void 0),riskLevel:v.coerce.string().optional().nullable().transform(e=>e??void 0),allowed:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),tier2Decision:v.coerce.string().optional().nullable().transform(e=>e??void 0),tier2Score:v.coerce.number().optional().nullable().transform(e=>e??void 0),tier2LatencyMs:v.coerce.number().optional().nullable().transform(e=>e??void 0),tier3Decision:v.coerce.string().optional().nullable().transform(e=>e??void 0),tier3PromptTokens:v.coerce.number().optional().nullable().transform(e=>e??void 0),tier3CompletionTokens:v.coerce.number().optional().nullable().transform(e=>e??void 0),tier3LatencyMs:v.coerce.number().optional().nullable().transform(e=>e??void 0),policyResult:v.coerce.string().optional().nullable().transform(e=>e??void 0),isBackground:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0),defenderExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),G=U.extend({logType:v.literal(`step`),actionRunId:v.coerce.string(),stepIndex:v.coerce.number(),stepId:v.coerce.string(),projectSecureId:v.coerce.string(),accountSecureId:v.coerce.string(),skipped:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),success:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:v.coerce.number().optional().nullable().transform(e=>e??void 0),message:v.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionName:v.coerce.string().optional().nullable().transform(e=>e??void 0),stepFunctionVersion:v.coerce.string().optional().nullable().transform(e=>e??void 0),stepIterations:v.coerce.number().optional().nullable().transform(e=>e??void 0)}),K=U.extend({logType:v.literal(`unified`),requestId:v.coerce.string(),connectorKey:v.coerce.string(),connectorVersion:v.coerce.string().optional().nullable().transform(e=>e??void 0),connectorOwner:v.coerce.string().optional().nullable().transform(e=>e??void 0),connectorProfileId:v.coerce.string().optional().nullable().transform(e=>e??void 0),projectSecureId:v.coerce.string(),accountSecureId:v.coerce.string(),mode:v.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:v.coerce.string().optional().nullable().transform(e=>e??void 0),url:v.coerce.string().optional().nullable().transform(e=>e??void 0),path:v.coerce.string().optional().nullable().transform(e=>e??void 0),resource:v.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:v.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:v.coerce.string().optional().nullable().transform(e=>e??void 0),service:v.coerce.string().optional().nullable().transform(e=>e??void 0),action:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceValue:v.coerce.string().optional().nullable().transform(e=>e??void 0),authType:v.coerce.string().optional().nullable().transform(e=>e??void 0),authId:v.coerce.string().optional().nullable().transform(e=>e??void 0),actingUserId:v.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:v.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:v.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:v.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:v.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:v.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:v.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerId:v.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:v.coerce.string().optional().nullable().transform(e=>e??void 0),statusCode:v.coerce.number().optional().nullable().transform(e=>e??void 0),success:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),isWorker:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),isBackground:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),status:v.coerce.number().optional().nullable().transform(e=>e??void 0),provider:v.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:v.coerce.number().optional().nullable().transform(e=>e??void 0),advancedExpiresAt:H.optional().nullable().transform(e=>e??void 0)}),q=U.extend({logType:v.literal(`provider`),requestId:v.coerce.string(),id:v.coerce.string().optional().nullable().transform(e=>e??void 0),action:v.coerce.string(),mode:v.coerce.string().optional().nullable().transform(e=>e??void 0),httpMethod:v.coerce.string(),originOwnerId:v.coerce.string().optional().nullable().transform(e=>e??void 0),originOwnerName:v.coerce.string().optional().nullable().transform(e=>e??void 0),url:v.coerce.string(),path:v.coerce.string().optional().nullable().transform(e=>e??void 0),connectorKey:v.coerce.string(),connectorVersion:v.coerce.string().optional().nullable().transform(e=>e??void 0),resource:v.coerce.string().optional().nullable().transform(e=>e??void 0),subResource:v.coerce.string().optional().nullable().transform(e=>e??void 0),childResource:v.coerce.string().optional().nullable().transform(e=>e??void 0),service:v.coerce.string().optional().nullable().transform(e=>e??void 0),success:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:v.coerce.number().optional().nullable().transform(e=>e??void 0),isWorker:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),projectSecureId:v.coerce.string(),accountSecureId:v.coerce.string(),status:v.coerce.number().optional().nullable().transform(e=>e??void 0),provider:v.coerce.string().optional().nullable().transform(e=>e??void 0),eventDatetime:H.optional().nullable().transform(e=>e??void 0),duration:v.coerce.number().optional().nullable().transform(e=>e??void 0)}),lt=U.extend({logType:v.literal(`platform`),eventId:v.coerce.string(),eventType:v.coerce.string(),service:v.coerce.string(),organizationId:v.coerce.string().optional().nullable().transform(e=>e??void 0),accountSecureId:v.undefined().optional(),userId:v.coerce.string().optional().nullable().transform(e=>e??void 0),userEmail:v.coerce.string().optional().nullable().transform(e=>e??void 0),action:v.coerce.string().optional().nullable().transform(e=>e??void 0),resource:v.coerce.string().optional().nullable().transform(e=>e??void 0),resourceId:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceType:v.coerce.string().optional().nullable().transform(e=>e??void 0),sourceId:v.coerce.string().optional().nullable().transform(e=>e??void 0),authType:v.coerce.string().optional().nullable().transform(e=>e??void 0),authId:v.coerce.string().optional().nullable().transform(e=>e??void 0),userAgent:v.coerce.string().optional().nullable().transform(e=>e??void 0),ipAddress:v.coerce.string().optional().nullable().transform(e=>e??void 0),sessionId:v.coerce.string().optional().nullable().transform(e=>e??void 0),agentId:v.coerce.string().optional().nullable().transform(e=>e??void 0),transportType:v.coerce.string().optional().nullable().transform(e=>e??void 0),streamType:v.coerce.string().optional().nullable().transform(e=>e??void 0),isRead:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),statusCode:v.coerce.number().optional().nullable().transform(e=>e??void 0),success:v.coerce.boolean().optional().nullable().transform(e=>e??void 0),details:v.record(v.string(),v.unknown()).optional().nullable().transform(e=>e??void 0)}),ut=v.discriminatedUnion(`logType`,[W,G,K,q]),dt=new Set([`success`,`isRead`]),foldTimeBuckets=e=>{let t=new Map;for(let n of e){let{startTime:e,count:r,...i}=n,a=JSON.stringify(Object.entries(i).sort(([e],[t])=>e.localeCompare(t))),o=t.get(a);o?o.count+=r:t.set(a,{...i,count:r})}return[...t.values()]},ft=[`success`,`isWorker`,`isBackground`,`skipped`];var QueryClientNotConfiguredError=class extends Error{constructor(){super(`No ClickHouse query client is configured`),this.name=`QueryClientNotConfiguredError`}};const pt=15e3;var LogsSink=class{#e;#t;#n;#r;#i;#a(){if(!this.#r?.isReady())throw new QueryClientNotConfiguredError;return this.#r}#o(e){parseLogQueryConditions(e.conditions)}constructor(e,t,n,r,i){this.#e=e,this.#t=r,this.#n=i,this.#i=t,n&&(this.#r=new ClickHouseClient(n,t),this.#i?.debug({message:`LogsSink initialized with the ClickHouse query client`,category:`LogsSink`}))}async initialize(){if(!this.#e?.producer&&!this.#t?.producer){this.#i?.warning({message:`No kafka producer provided, logs sink cannot be initialized`,category:`LogsSink`});return}this.#r?.isReady()?this.#i?.info({message:`Logs sink query client ready: clickhouse`,category:`LogsSink`}):this.#i?.warning({message:`No query client is ready (missing config), logs sink will not be able to query`,category:`LogsSink`}),this.#i?.info({message:`Logs sink kafka producer initialized`,category:`LogsSink`}),await this.#u()}async close(e=3e4){return this.#s??=this.#c(e),this.#s}#s;async#c(e){let t=[];if(this.#e?.producer){let e=this.#e.producer;t.push([`external kafka producer`,()=>e.close()])}if(this.#t?.producer){let e=this.#t.producer;t.push([`internal kafka producer`,()=>e.close()])}if(this.#r){let e=this.#r;t.push([`clickhouse client`,()=>e.close()])}(await Promise.allSettled(t.map(([,t])=>this.#l(t,e)))).forEach((n,r)=>{if(n.status===`rejected`){let i=n.reason instanceof Error?n.reason:Error(String(n.reason)),a=i.name===`LogsSinkCloseTimeout`,o=t[r]?.[0]??`resource`,s=o.includes(`producer`),c={message:a?s?`Timed out closing ${o} after ${e}ms; buffered records may have been lost`:`Timed out releasing ${o} after ${e}ms`:`Error closing ${o}: ${i.message}`,error:i,code:`LogsSinkCloseError`,category:`LogsSink`};a&&s?this.#i?.error(c):this.#i?.warning(c)}})}async#l(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>{let e=Error(`timed out after ${t}ms`);e.name=`LogsSinkCloseTimeout`,r(e)},t),n.unref?.()});try{return await Promise.race([Promise.resolve().then(e),r])}finally{n&&clearTimeout(n)}}async#u(){let e=[{cluster:`external`,producer:this.#e?.producer},...this.#t?[{cluster:`internal`,producer:this.#t.producer}]:[]];await Promise.all(e.filter(({producer:e})=>e).map(async({cluster:e,producer:t})=>{let n;try{await Promise.race([t?.connectToBrokers(),new Promise((e,t)=>{n=setTimeout(()=>t(Error(`connectivity probe timed out after ${pt}ms`)),pt),n.unref?.()})]),this.#i?.info({message:`Kafka ${e} cluster connection established`,category:`LogsSink`,context:{cluster:e}})}catch(t){let n=t instanceof Error?t:Error(String(t));this.#i?.warning({message:`Kafka ${e} cluster connectivity probe failed: ${n.message}`,category:`LogsSink`,error:n,code:`KafkaConnectivityProbeFailed`,context:{cluster:e}})}finally{n&&clearTimeout(n)}}))}async sendAction(e,t,n,r){await this.sendActions([{input:e,result:t,metadata:n}],r)}async sendActions(e,t){if(!t?.enabled){this.#i?.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,metadata:n})=>this.buildActionLog(e,t,n));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.#i?.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,r){if(!r?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending unified to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending unified to log sink (topic: unified_requests)`,category:`LogsSink`});let i=this.buildUnifiedLog(e,t,n);await this.send(`unified_requests`,[i])}async sendProvider(e,t,n){if(!n?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending provider to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending provider to log sink (topic: provider_requests)`,category:`LogsSink`});let r=this.buildProviderLog(e,t);await this.send(`provider_requests`,[r])}async sendPlatform(e,t,n){let r=isPlatformLog(e);if(!(r?t:n)?.enabled){this.#i?.debug({message:`Logs sink is disabled, skipping sending platform to log sink`,category:`LogsSink`});return}this.#i?.debug({message:`Sending platform to log sink (topic: platform)`,category:`LogsSink`});let i=r?e:this.buildPlatformLog(e,t??{});await this.send(`platform`,[i])}async getLogs(e){this.#o(e);let t=this.#a();try{this.#i?.info({message:`Querying logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:Ke,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} logs (${n.total} total)`,category:`LogsSink`}),{logs:this.validateLogs(n.data),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for logs`,category:`LogsSink`,code:`LogsQueryFailed`,error:e}),e}}async getLastLogs(e,t){this.#o(t);let n=this.#a(),r=e?.ids??[];if(r.length===0)return emptyQueryResult();try{this.#i?.info({message:`Querying last logs for ${r.length} ${e.field} entity(s)`,category:`LogsSink`,context:{entities:e,query:t}});let i=await n.queryWithPagination({query:Ye,params:{...t,entities:e}});return this.#i?.info({message:`Successfully retrieved ${i.data.length} last log(s)`,category:`LogsSink`}),{logs:this.validateLogs(i.data),total:i.total,pageNumber:i.pageNumber,pageSize:i.pageSize}}catch(e){throw this.#i?.error({message:`Failed to query for last logs`,category:`LogsSink`,code:`LastLogsQueryFailed`,error:e}),e}}async getActions(e){let t=this.#a();try{this.#i?.info({message:`Querying action logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:be,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} action logs (${n.total} total)`,category:`LogsSink`}),{actionLogs:this.validateLogsWithSchema(n.data,W),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for action logs, 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){let t=this.#a();try{this.#i?.info({message:`Querying step logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:ot,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} step logs (${n.total} total)`,category:`LogsSink`}),{stepLogs:this.validateLogsWithSchema(n.data,G),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for step logs, 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){let t=this.#a();try{this.#i?.info({message:`Querying unified logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:ct,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} unified logs (${n.total} total)`,category:`LogsSink`}),{unifiedLogs:this.validateLogsWithSchema(n.data,K),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for unified logs, 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){let t=this.#a();try{this.#i?.info({message:`Querying provider logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:rt,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} provider logs (${n.total} total)`,category:`LogsSink`}),{providerLogs:this.validateLogsWithSchema(n.data,q),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.error({message:`Failed to query for provider logs, returning empty results`,category:`LogsSink`,code:`ProviderLogsQueryFailed`,error:t}),{providerLogs:[],total:0,pageNumber:e.pageNumber??1,pageSize:e.pageSize??0}}}async getPlatformLogDimensions(e){let t=this.#a();try{this.#i?.info({message:`Querying platform log dimensions`,category:`LogsSink`,context:{query:e}});let n=await t.query({query:$e,params:e});this.#i?.info({message:`Successfully retrieved ${n.length} platform dimension facets`,category:`LogsSink`});let r={};for(let e of n)r[e.dimension]=dt.has(e.dimension)?e.values.map(e=>({value:e.value===`1`?`true`:`false`,count:e.count})):e.values;return r}catch(e){return this.#i?.error({message:`Failed to query platform log dimensions: ${e instanceof Error?e.message:String(e)}`,category:`LogsSink`,code:`PlatformDimensionsQueryFailed`}),{}}}async getPlatformLogs(e){let t=this.#a();try{this.#i?.info({message:`Querying platform logs`,category:`LogsSink`,context:{query:e}});let n=await t.queryWithPagination({query:tt,params:e,pageNumber:e.pageNumber,pageSize:e.pageSize});return this.#i?.info({message:`Successfully retrieved ${n.data.length} platform logs (${n.total} total)`,category:`LogsSink`}),{platformLogs:this.validateLogsWithSchema(n.data,lt),total:n.total,pageNumber:n.pageNumber,pageSize:n.pageSize}}catch(t){return this.#i?.warning({message:`Failed to query for platform logs, returning empty results`,category:`LogsSink`,error:t}),{platformLogs:[],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 getAggregate(e,t,n){this.#o(n);let r=this.#a();try{this.#i?.info({message:`Querying logs stats aggregate`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,l=n.intervalType===T.None,u={organizationId:e,projectSecureId:t,...s,...i&&i.length>0&&{dimensions:i.join(`,`)},...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()},...l&&{pageSize:void 0,pageNumber:void 0}},d=await r.query({query:qe,params:u});this.#i?.info({message:`Successfully retrieved ${d.length} aggregated data points`,category:`LogsSink`});let f=d.map(e=>c(e,!0)).map(e=>{let t={...e};for(let e of ft)e in t&&typeof t[e]==`number`&&(t[e]=t[e]===1);return t});return{data:l?foldTimeBuckets(f):f}}catch(e){throw this.#i?.error({message:`Failed to query for logs stats aggregate`,category:`LogsSink`,code:`LogsAggregateQueryFailed`,error:e}),e}}async getDimensions(e,t,n){this.#o(n);let r=this.#a();try{this.#i?.info({message:`Querying logs stats dimensions`,category:`LogsSink`,context:{query:n}});let{dimensions:i,startTime:a,endTime:o,...s}=n,c={organizationId:e,projectSecureId:t,...s,dimensions:i.join(`,`),...a&&{startTime:a.toISOString()},...o&&{endTime:o.toISOString()}},l=await r.query({query:Je,params:c});this.#i?.info({message:`Successfully retrieved ${l.length} dimension facets`,category:`LogsSink`});let u={};for(let e of l)ft.includes(e.dimension)?u[e.dimension]=e.values.map(e=>({value:e.value===`1`?`true`:e.value===`0`?`false`:e.value,count:e.count})):u[e.dimension]=e.values;return u}catch(e){throw this.#i?.error({message:`Failed to query for logs stats dimensions`,category:`LogsSink`,code:`LogsDimensionsQueryFailed`,error:e}),e}}async getActionsCount(e){let[t]=await this.#a().query({query:Se,params:e});return Number(t?.actions_count??0)}async getSourceUsage(e,t,n){let r=this.#a();try{this.#i?.info({message:`Querying logs stats source usage`,category:`LogsSink`,context:{query:n}});let{startTime:i,endTime:a,sourceType:o}=n,s={organizationId:e,projectSecureId:t,sourceType:o||void 0,...i&&{startTime:i.toISOString()},...a&&{endTime:a.toISOString()}},c=await r.query({query:it,params:s});return this.#i?.info({message:`Successfully retrieved ${c.length} source usage records`,category:`LogsSink`}),c.map(e=>({sourceId:e.sourceId,sourceType:e.sourceType,requestCount:e.request_count,lastRequest:e.last_request}))}catch(e){return this.#i?.warning({message:`Failed to query for logs stats source usage, returning empty results`,category:`LogsSink`,error:e}),[]}}#d(e){return(this.#n??De)[e]?.map(e=>({cluster:e,producer:e===`internal`?this.#t?.producer:this.#e?.producer}))}async send(e,t){let n=this.#d(e);if(!n)throw this.#i?.error({message:`No cluster routing configured for topic ${e}, dropping ${t.length} log(s)`,category:`KafkaSink`,code:`TopicNotRouted`}),Error(`No cluster routing configured for topic ${e}`);if(n.length===0){this.#i?.debug({message:`Topic ${e} is muted by the topic cluster map, dropping ${t.length} log(s)`,category:`KafkaSink`});return}let r=this.validateLogsBeforeSend(t);if(r.length===0){this.#i?.warning({message:`All ${t.length} log(s) failed validation, nothing to send to topic ${e}`,category:`LogsSink`,code:`AllLogsInvalid`});return}r.length<t.length&&this.#i?.warning({message:`${t.length-r.length} of ${t.length} log(s) failed validation and were dropped`,category:`LogsSink`,code:`SomeLogsInvalid`});let i=r.map(t=>({topic:e,value:safeSerialize(t)})),a=await Promise.allSettled(n.map(({cluster:t,producer:n})=>this.#f(t,n,e,i))),o=a.filter(e=>e.status===`rejected`);if(o.length===a.length)throw o[0].reason}async#f(e,t,n,r){if(!t)throw this.#i?.error({message:`Kafka not initialized, dropping message for topic ${n}`,category:`KafkaSink`,code:`KafkaNotReady`,context:{cluster:e}}),Error(`Kafka producer is not initialized`);let i=Date.now();this.#i?.debug({message:`Sending ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{cluster:e}});try{let a=await t.send({messages:r,compression:`gzip`});this.#i?.debug({message:`Successfully sent ${r.length} message(s) to topic ${n}`,category:`KafkaSink`,context:{durationMs:Date.now()-i,topic:n,cluster:e,result:a}})}catch(t){throw this.#i?.error({message:`Error sending ${r.length} message(s) to topic ${n}: ${t.message}`,category:`KafkaSink`,error:t,code:`KafkaSendError`,context:{durationMs:Date.now()-i,topic:n,cluster:e,messageCount:r.length}}),t}}buildActionLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`action`,organizationId:String(e.organizationId),projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,actionRunId:e.actionRunId,actionId:e.actionId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.sessionId&&{sessionId:e.sessionId},...e.agentId&&{agentId:e.agentId},...e.transportType&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...i!==void 0&&{durationMs:i},...e.mode&&{mode:e.mode},...e.actionType&&{actionType:e.actionType},...e.category&&{category:e.category},...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.httpMethod&&{httpMethod:e.httpMethod},...e.url&&{url:e.url},...t.success!==void 0&&{success:t.success},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.defenderContext?.result?.riskLevel&&{riskLevel:t.defenderContext.result.riskLevel},...t.defenderContext?.result?.allowed!==void 0&&{allowed:t.defenderContext.result.allowed},...t.defenderContext?.result?.tier2Decision!==void 0&&{tier2Decision:t.defenderContext.result.tier2Decision},...t.defenderContext?.result?.tier2Score!==void 0&&{tier2Score:t.defenderContext.result.tier2Score},...t.defenderContext?.result?.tier2LatencyMs!==void 0&&{tier2LatencyMs:t.defenderContext.result.tier2LatencyMs},...t.defenderContext?.result?.tier3Decision!==void 0&&{tier3Decision:t.defenderContext.result.tier3Decision},...t.defenderContext?.result?.tier3PromptTokens!==void 0&&{tier3PromptTokens:t.defenderContext.result.tier3PromptTokens},...t.defenderContext?.result?.tier3CompletionTokens!==void 0&&{tier3CompletionTokens:t.defenderContext.result.tier3CompletionTokens},...t.defenderContext?.result?.tier3LatencyMs!==void 0&&{tier3LatencyMs:t.defenderContext.result.tier3LatencyMs},...t.policyContext&&{policyResult:t.policyContext.result},startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,isBackground:e.isBackground,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt},...n?.defenderExpiresAt&&{defenderExpiresAt:n.defenderExpiresAt}}}buildStepLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`step`,eventTime:n,startTime:e.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.statusCode!==void 0&&{statusCode:t.statusCode},...t.message&&{message:t.message},...e.stepFunctionName&&{stepFunctionName:e.stepFunctionName},...e.stepFunctionVersion&&{stepFunctionVersion:e.stepFunctionVersion},...e.stepIterations!==void 0&&{stepIterations:e.stepIterations}}}buildUnifiedLog(e,t,n){let r=new Date,i=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`unified`,requestId:e.requestId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion??`2`,...e.connectorOwner&&{connectorOwner:e.connectorOwner},...e.connectorProfileId&&{connectorProfileId:e.connectorProfileId},organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,...e.originOwnerId&&{originOwnerId:e.originOwnerId},...e.originOwnerName&&{originOwnerName:e.originOwnerName},...e.sourceType&&{sourceType:e.sourceType},...e.sourceId&&{sourceId:e.sourceId},...e.authType&&{authType:e.authType},...e.authId&&{authId:e.authId},...e.actingUserId&&{actingUserId:e.actingUserId},...e.userAgent&&{userAgent:e.userAgent},...e.ipAddress&&{ipAddress:e.ipAddress},...e.transportType&&{transportType:e.transportType},...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},...t.statusCode!==void 0&&{statusCode:t.statusCode},...t.success!==void 0&&{success:t.success},isBackground:e.isBackground,durationMs:i,startTime:e.startTime??r,...t.endTime&&{endTime:t.endTime},eventTime:r,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:r,duration:i,...n?.advancedExpiresAt&&{advancedExpiresAt:n.advancedExpiresAt}}}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,...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&&{statusCode:t.statusCode},durationMs:r,startTime:e.startTime??n,...t.endTime&&{endTime:t.endTime},eventTime:n,...t.statusCode!==void 0&&{status:t.statusCode},provider:e.connectorKey,eventDatetime:n,duration:r}}buildPlatformLog(e,t){let n=new Date,r=this.calculateDurationMs(e.startTime,t.endTime);return{logType:`platform`,eventId:e.eventId??g(),eventType:e.eventType,service:e.service,...e.organizationId!==void 0&&{organizationId:e.organizationId},...e.projectSecureId!==void 0&&{projectSecureId:e.projectSecureId},...e.userId!==void 0&&{userId:e.userId},...e.userEmail!==void 0&&{userEmail:e.userEmail},...e.action!==void 0&&{action:e.action},...e.resource!==void 0&&{resource:e.resource},...e.resourceId!==void 0&&{resourceId:e.resourceId},...e.sourceType!==void 0&&{sourceType:e.sourceType},...e.sourceId!==void 0&&{sourceId:e.sourceId},...e.authType!==void 0&&{authType:e.authType},...e.authId!==void 0&&{authId:e.authId},...e.userAgent!==void 0&&{userAgent:e.userAgent},...e.ipAddress!==void 0&&{ipAddress:e.ipAddress},...e.sessionId!==void 0&&{sessionId:e.sessionId},...e.agentId!==void 0&&{agentId:e.agentId},...e.transportType!==void 0&&{transportType:e.transportType},...e.streamType!==void 0&&{streamType:e.streamType},...e.isRead!==void 0&&{isRead:e.isRead},...e.statusCode!==void 0&&{statusCode:e.statusCode},...t.success!==void 0&&{success:t.success},...e.details!==void 0&&{details:safeObject(e.details)},startTime:e.startTime??n,...t.endTime!==void 0&&{endTime:t.endTime},...r!==void 0&&{durationMs:r},eventTime:n}}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 _){let n=`unknown`;if(typeof e==`object`&&e&&`logType`in e){let t=e;n=typeof t.logType==`string`?t.logType:`unknown`}throw this.#i?.error({message:`Failed to validate ${n} log from the query engine`,category:`LogsSink`,code:`LogParsingTypeError`,context:{validationErrors:t.issues,log:safeSerialize(e)}}),Error(`Log data validation failed for ${n} log: ${t.message}`)}throw t}})}validateLogs(e){return this.validateLogsWithSchema(e,ut)}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 _?this.#i?.warning({message:`Log validation failed before sending to Kafka, dropping ${n.logType} log`,category:`LogsSink`,code:`PreWriteValidationFailed`,context:{logType:n.logType,validationErrors:e.issues,log:safeSerialize(n)}}):this.#i?.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 W;case`step`:return G;case`unified`:return K;case`provider`:return q;case`platform`:return lt}}};const readStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let r=await e.readText(t);if(r===void 0){a?.debug({message:`No ${n} in storage`,category:i});return}return a?.debug({message:`Retrieved ${n} from storage`,category:i}),JSON.parse(r)}catch(e){throw a?.error({message:`Error when getting ${n} from storage`,error:e,code:r,category:i}),e}},writeStoredLog=async({bucket:e,key:t,body:n,ttlTag:r,expiresAt:i,description:a,errorCode:o,category:s,logger:c})=>{try{await e.write(t,n,{contentType:`application/json`,tags:{ttl:r},expiresAt:i})}catch(e){throw c?.error({message:`Failed to write ${a} to storage at ${t}`,error:e,code:o,category:s}),e}},statStoredLog=async({bucket:e,key:t,description:n,errorCode:r,category:i,logger:a})=>{try{let n=await e.stat(t);return n===void 0?{exists:!1}:{exists:!0,expiresAt:n.expiresAt}}catch(e){throw a?.error({message:`Error when checking ${n} in storage`,error:e,code:r,category:i}),e}},mt=64*1024,J=[`data.errors`,`data.request.body`,`data.input`,`data.response.body`,`data.outputs`],ht=[`data.request.body`,`data.input`],readPath=(e,t)=>t.split(`.`).reduce((e,t)=>p(e)?e[t]:void 0,e),withPath=(e,t,n)=>{let[r,...i]=t.split(`.`);if(i.length===0)return{...e,[r]:n};let a=e[r];return p(a)?{...e,[r]:withPath(a,i.join(`.`),n)}:{...e}},marker=e=>({truncated:!0,sizeBytes:e}),fitString=(e,t)=>`${e.slice(0,Math.max(0,Math.floor(t/2)-12))} [truncated]`,fitArray=(e,t)=>{let{kept:n,total:r}=e.reduce((e,n)=>{if(e.total>t)return e;let r=e.total+s(n);return r>t?{kept:e.kept,total:r}:{kept:e.kept+1,total:r}},{kept:0,total:0});return r>t?e.slice(0,n):e},fitObject=(e,t)=>{let n=Object.entries(e).map(([e,t])=>({key:e,value:t,size:e.length*2+s(t)})).sort((e,t)=>e.size-t.size),{kept:r,remaining:i}=n.reduce((e,t)=>t.size<=e.remaining?{kept:[...e.kept,t.key],remaining:e.remaining-t.size}:e,{kept:[],remaining:t}),a=n.filter(e=>!r.includes(e.key)),o=a.length===0?0:Math.floor(i/a.length);return Object.fromEntries(n.map(e=>[e.key,r.includes(e.key)?e.value:fitValue(e.value,o)]))},fitValue=(e,t)=>{let n=s(e);return n<=t?e:(m(e)||Array.isArray(e)||p(e)&&!d(e))&&t<=0?marker(n):m(e)?fitString(e,t):Array.isArray(e)?fitArray(e,t):p(e)&&!d(e)?fitObject(e,t):e},payloadFields=e=>J.map(t=>({path:t,value:readPath(e,t)})).filter(({value:e})=>!f(e)).map(e=>({...e,size:s(e.value)})),byRetentionPriority=e=>[...e.filter(e=>ht.includes(e.path)),...e.filter(e=>!ht.includes(e.path)).sort((e,t)=>e.size-t.size)],keptWholePaths=(e,t)=>e.reduce((t,n,r)=>{let i=(e.length-r-1)*mt;return n.size<=t.remaining-i?{paths:[...t.paths,n.path],remaining:t.remaining-n.size}:t},{paths:[],remaining:t}).paths,truncateToLimit=(e,t)=>{let n=byRetentionPriority(payloadFields(e)),r=keptWholePaths(n,t),i=n.filter(e=>r.includes(e.path)).reduce((e,t)=>e+t.size,0),a=n.filter(e=>!r.includes(e.path)),o=a.length===0?0:Math.max(mt,Math.floor((t-i)/a.length)),s=a.map(e=>({...e,fitted:fitValue(e.value,o)})).filter(e=>e.fitted!==e.value);return{data:s.reduce((e,t)=>withPath(e,t.path,t.fitted),e),truncatedPaths:s.map(e=>e.path)}},withoutPayloads=e=>J.reduce((e,t)=>readPath(e,t)===void 0?e:withPath(e,t,void 0),e),isErrorResult=e=>e.success===!1||e.hasStepErrors===!0||(e.statusCode??0)>=400||hasErrorEntries(e.errors),gt=[`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`],_t=[`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`],vt=[`image/`,`audio/`,`video/`,`application/vnd.`,`binary`],parseActionUrl=e=>e.startsWith(`/`)?new URL(e,`http://path.invalid`):new URL(e),platformKey=(e,t)=>`${e}/platform/${t}.json`,Y=`AdvancedSink`,errorName=e=>e instanceof Error?e.name:`non-Error thrown`;var AdvancedSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.maxItemSizeBytes??10485760,this.#r=t?.errorSizeMultiplier??5,this.#i=n,this.#a=t?.piiRedaction}async initialize(){if(this.#t){this.#i?.warning({message:`No storage provided, advanced sink will not function`,category:Y});return}try{await this.#a?.warmupTier2()}catch(e){this.#i?.warning({message:`PII Tier 2 warmup failed (${errorName(e)}), content scrub will fall back to structural redaction only`,category:`AdvancedSink`,code:`AdvancedSinkPiiWarmupError`})}}async scrubPii(e,t){if(!t?.piiRedactionEnabled||!this.#a||this.truncationMode(t)===`drop`&&s(e)>this.#n)return e;try{return await this.#a.scrubObject(e)}catch(t){return this.#i?.warning({message:`PII content scrub failed (${errorName(t)}), storing structurally-redacted body only`,category:`AdvancedSink`,code:`AdvancedSinkPiiScrubError`}),e}}requireBucket(){if(!this.#e)throw Error(`Advanced sink bucket is not configured`);return this.#e}truncationMode(e){return e?.truncation??`drop`}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,i){let a=[];for(let{input:o,result:s}of e){if(this.#i?.debug({message:`Advanced sink called to send action`,category:`AdvancedSink`,context:{mode:o.mode,actionId:o.actionId,actionRunId:o.actionRunId,success:s.success,statusCode:s.statusCode,options:{enabled:i?.enabled,errorsOnly:i?.errorsOnly,includeBackground:i?.includeBackground,ttl:i?.ttl}}}),!i?.enabled){this.#i?.debug({message:`Advanced sink is disabled, skipping sending action to advanced sink`,category:`AdvancedSink`}),a.push(null);continue}if(isDataSync(o.mode,o.sourceType)){this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending action to advanced sink`,category:`AdvancedSink`}),a.push(null);continue}if(i.errorsOnly&&s.success&&!s.hasStepErrors){this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${o.mode||`action`}`,category:`AdvancedSink`}),a.push(null);continue}if(isBackgroundLog(o.mode,o.sourceType)&&!i.includeBackground){this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${o.mode}`,category:`AdvancedSink`}),a.push(null);continue}let e=callerHeadersOf(o.callerHeaders),[c,l,u,d]=await Promise.all([this.scrubPii(redactBody(o.body,o.headers),i),this.scrubPii(r(o.queryParams,t.PARTIAL,!0),i),this.scrubPii(r(o.pathParams,t.PARTIAL,!0),i),Object.values(e??{}).some(e=>e!==n)?this.scrubPii(e,i):e]),f={...o,body:c,queryParams:l,pathParams:u,callerHeaders:d},p={...s,body:await this.scrubPii(redactBody(s.body??s.refusal,s.headers),i)},m=this.createActionItem(f,p,i),h=await this.send(m,i?.ttl);a.push(h)}return a}async sendStep(e,n,i){if(this.#i?.debug({message:`Advanced sink called to send step`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,success:n.success,options:{enabled:i?.enabled,errorsOnly:i?.errorsOnly,includeBackground:i?.includeBackground,ttl:i?.ttl}}}),!i?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending step to advanced sink`,category:`AdvancedSink`}),null;if(isDataSync(e.actionMode,e.actionSourceType))return this.#i?.debug({message:`Advanced sink does not record data sync, skipping sending step to advanced sink`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null;if(i.errorsOnly&&e.actionSuccess===!0&&n.success!==!1&&!hasErrorEntries(n.errors))return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful action for ${e.actionMode||`action`}`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.actionMode)&&!i.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping action with mode ${e.actionMode}`,category:`AdvancedSink`}),null;let a={...e,inputs:await this.scrubPii(r(e.inputs,t.PARTIAL,!0),i)},o={...n,outputs:await this.scrubPii(r(n.outputs,t.PARTIAL,!0),i),errors:await this.scrubPii(r(n.errors,t.PARTIAL,!0),i)},s=this.createStepItem(a,o,i);try{return await this.send(s,i?.ttl)}catch(t){return this.#i?.error({message:`Failed to send step to advanced sink`,error:t,code:`AdvancedStepWriteError`,category:`AdvancedSink`,context:{actionRunId:e.actionRunId,stepIndex:e.stepIndex}}),null}}async sendSteps(e,t){let n=[];for(let{input:r,result:i}of e){let e=await this.sendStep(r,i,t);n.push(e)}return n}async sendUnified(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending unified to advanced sink`,category:`AdvancedSink`}),null;if(n.errorsOnly&&t.success)return this.#i?.debug({message:`Advanced sink errorsOnly is enabled, skipping successful unified request`,category:`AdvancedSink`}),null;if(isBackgroundLog(e.mode,e.sourceType)&&!n.includeBackground)return this.#i?.debug({message:`Advanced sink is configured to exclude background logs, skipping unified with mode ${e.mode}`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending unified to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createUnifiedItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send unified to advanced sink`,error:t,code:`AdvancedUnifiedWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async sendProvider(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending provider to advanced sink`,category:`AdvancedSink`}),null;this.#i?.debug({message:`Sending provider to advanced sink`,category:`AdvancedSink`});let r={...e,body:await this.scrubPii(redactBody(e.body,e.headers),n)},i={...t,body:await this.scrubPii(redactBody(t.body,t.headers),n)},a=this.createProviderItem(r,i,n);try{return await this.send(a,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send provider to advanced sink`,error:t,code:`AdvancedProviderWriteError`,category:`AdvancedSink`,context:{requestId:e.requestId}}),null}}async getAction(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for actionRunId ${n}`)}async getStep(e,t,n,r){return this.read(`${e}/${t}/${n}/steps/${r}.json`,`step log for actionRunId ${n} stepIndex ${r}`)}async getUnified(e,t,n){return this.read(`${e}/${t}/${n}/${n}.json`,`advanced log for requestId ${n}`)}async getProvider(e,t,n,r){return this.read(`${e}/${t}/${n}/provider/${r}.json`,`provider log for requestId ${n} id ${r}`)}async read(e,t){if(this.#t){this.#i?.warning({message:`No storage available, cannot get ${t} from advanced sink`,category:Y});return}return readStoredLog({bucket:this.requireBucket(),key:e,description:t,errorCode:`AdvancedLogReadError`,category:Y,logger:this.#i})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to advanced sink`);let n=this.requireBucket(),r=t===1?`1d`:t===7?`7d`:`30d`,i=Math.floor(Date.now()/1e3)+(t??30)*24*60*60,a=new Date(i*1e3);return this.#i?.debug({message:`Storing advanced log in bucket ${n.name} with ttl of ${r}`,category:Y,context:{bucket:n.name,key:e.key,ttlTag:r,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:e.key,body:e.body,ttlTag:r,expiresAt:a,description:`advanced logs`,errorCode:`AdvancedLogWriteError`,category:Y,logger:this.#i}),{expiresAt:a}}async getObjectExpiry(e){return this.#t?(this.#i?.warning({message:`No storage available, cannot check object expiry`,category:Y}),{exists:!1}):statStoredLog({bucket:this.requireBucket(),key:e,description:`advanced log at ${e}`,errorCode:`AdvancedLogHeadError`,category:Y,logger:this.#i})}async hasAction(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async hasUnified(e,t,n){let r=`${e}/${t}/${n}/${n}.json`;return this.getObjectExpiry(r)}async sendPlatform(e,t,n){if(!n?.enabled)return this.#i?.debug({message:`Advanced sink is disabled, skipping sending platform to advanced sink`,category:`AdvancedSink`}),null;if(e.organizationId===void 0)return this.#i?.warning({message:`Skipping platform advanced log: no organization to key it under`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType}}),null;this.#i?.debug({message:`Sending platform to advanced sink`,category:`AdvancedSink`,context:{eventId:e.eventId,eventType:e.eventType,organizationId:e.organizationId}});let r=this.createPlatformItem(e,t,e.organizationId,n?.ttl);try{return await this.send(r,n?.ttl)}catch(t){return this.#i?.error({message:`Failed to send platform to advanced sink`,error:t,code:`AdvancedPlatformWriteError`,category:`AdvancedSink`,context:{eventId:e.eventId}}),null}}async getPlatform(e,t){return this.read(platformKey(e,t),`platform advanced log for eventId ${t}`)}async hasPlatform(e,t){return this.getObjectExpiry(platformKey(e,t))}createActionItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/${e.actionRunId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeActionResult(e,t,i,this.#n,this.truncationMode(n))}}createStepItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.actionRunId}/steps/${e.stepIndex}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeStepResult(e,t,i,this.#n,this.truncationMode(n))}}createPlatformItem(e,t,n,r){let i=platformKey(n,e.eventId),a=Math.floor(Date.now()/1e3)+(r??30)*24*60*60;return{key:i,body:this.serializePlatformAdvanced(t,a)}}serializePlatformAdvanced(e,n){let i=r(e.data,t.PARTIAL,!0),a={...e.metadata,expirationTime:n,sizeBytes:s(i)};return this.stringifyPlatform({data:i,metadata:a},a)}stringifyPlatform(e,t){try{return JSON.stringify(e)}catch{return this.#i?.warning({message:`Platform advanced payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedPlatformPayloadUnserializable`}),JSON.stringify({data:{},metadata:{...t,truncated:!0}})}}createUnifiedItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/${e.requestId}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeUnifiedResult(e,t,i,this.#n,this.truncationMode(n))}}createProviderItem(e,t,n){let r=`${e.organizationId}/${e.projectSecureId}/${e.requestId}/provider/${e.id}.json`,i=Math.floor(Date.now()/1e3)+(n?.ttl??30)*24*60*60;return{key:r,body:this.serializeProviderResult(e,t,i,this.#n,this.truncationMode(n))}}serializeActionResult(e,n,r,i,s){let c=a(e.headers,t.PARTIAL),l=a(n.headers,t.PARTIAL),u=this.processContent(c,e.body,`upload`),d=this.processContent(l,n.body,`download`),f=e.isBackground??isBackgroundLog(e.mode,e.sourceType),m=e.url,h={};if(e.url)try{m=o(e.url,t.PARTIAL);let n=parseActionUrl(m);h=Object.fromEntries(n.searchParams)}catch{this.#i?.warning({message:`Invalid URL in action request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{actionRunId:e.actionRunId,actionId:e.actionId}})}let g={...h,...p(e.queryParams)?e.queryParams:{}},_={data:{request:{actionRunId:e.actionRunId,actionId:e.actionId,method:e.httpMethod,headers:this.filterHeaders(c),callerHeaders:e.callerHeaders,url:{url:m,path:e.pathParams,queryParams:g},body:u},response:{statusCode:n.statusCode??500,headers:this.filterHeaders(l),body:d},...f?{isBackgroundLog:!0}:{}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:r}};return this.serializeAndLimit(_,i,isErrorResult(n),s)}serializeStepResult(e,t,n,r,i){let a={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(a,r,isErrorResult(t),i)}serializeUnifiedResult(e,n,r,i,s){let c=a(e.headers,t.PARTIAL),l=a(n.headers,t.PARTIAL),u=this.processContent(c,e.body,`upload`),d=this.processContent(l,n.body,`download`),f=e.isBackground??isBackgroundLog(e.mode,e.sourceType),p=`/`,m=e.url,h={};if(e.url)try{m=o(e.url,t.PARTIAL);let n=new URL(m);p=n.pathname,h=Object.fromEntries(n.searchParams)}catch{this.#i?.warning({message:`Invalid URL in unified request, using fallback values`,category:`AdvancedSink`,code:`InvalidUrl`,context:{requestId:e.requestId}})}let g={data:{request:{id:e.requestId,method:e.httpMethod,headers:this.filterHeaders(c),url:{url:m,path:p,queryParams:h},body:u},response:{statusCode:n.statusCode??500,headers:this.filterHeaders(l),body:d}},metadata:{...f?{isBackgroundLog:!0}:{},expirationTime:r}};return this.serializeAndLimit(g,i,isErrorResult(n),s)}serializeProviderResult(e,n,r,i,s){let c=a(e.headers,t.PARTIAL),l=a(n.headers,t.PARTIAL),u=this.processContent(c,e.body,`upload`),d=this.processContent(l,n.body,`download`),f,p=``,m=`/`,h={};if(e.url)try{f=o(e.url,t.PARTIAL);let n=new URL(f);p=n.hostname,m=n.pathname,h=Object.fromEntries(n.searchParams)}catch{this.#i?.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(c),url:{url:f,hostname:p,path:m,queryParams:h},body:u},response:{statusCode:n.statusCode,headers:this.filterHeaders(l),body:d}},metadata:{expirationTime:r}};return this.serializeAndLimit(g,i,isErrorResult(n),s)}serializeAndLimit(e,t,n,r){let i=s(e);if(r===`complete`)return this.stringifyLog(e,{sizeBytes:i});let a=n&&r===`truncate`?t*this.#r:t;if(i<=a)return this.stringifyLog(e,{sizeBytes:i});if(r===`drop`)return this.#i?.warning({message:`Advanced log of ${i} bytes exceeds ${a}, dropping payload`,category:`AdvancedSink`,code:`AdvancedLogTooLarge`,context:{sizeBytes:i,maxSizeBytes:a,isErrorResult:n}}),this.stringifyLog({...e,data:{outputs:{error:`Error.TOO_LARGE`}}},{sizeBytes:i,maxSizeBytes:a,truncated:!0});let{data:o,truncatedPaths:c}=truncateToLimit(e,a);return this.#i?.warning({message:`Advanced log of ${i} bytes exceeds ${a}, storing truncated payload`,category:`AdvancedSink`,code:`AdvancedLogTruncated`,context:{sizeBytes:i,maxSizeBytes:a,isErrorResult:n,truncatedPaths:c}}),this.stringifyLog(o,{sizeBytes:i,maxSizeBytes:a,truncated:!0})}stringifyLog(e,t){let n={...e,metadata:{...e.metadata,...t}};try{return JSON.stringify(n)}catch{return this.#i?.warning({message:`Advanced log payload could not be serialized, storing envelope only`,category:`AdvancedSink`,code:`AdvancedLogUnserializable`}),JSON.stringify(withoutPayloads(n))}}filterHeaders(e){if(!e)return;let t={},n=gt.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 _t.includes(i)||vt.some(e=>i.startsWith(e))?{type:`binary`,action:n,contentType:r}:this.parseJsonSafely(t)}parseJsonSafely(e){if(!f(e)){if(!m(e))return e;try{return JSON.parse(e)}catch{return e}}}getContentType(e){if(!e)return;let t=[`content-type`,`contenttype`];return Object.entries(e).find(([e])=>t.includes(e.toLowerCase()))?.[1]?.toString()}};const X=2e3,settleWithin=(e,t,n)=>new Promise(r=>{let i=setTimeout(()=>r(n),t);i.unref?.(),e.then(e=>{clearTimeout(i),r(e)})});function defaultProviderFactory(e){let t=new re({url:`${e.baseUrl??`https://logfire-eu.pydantic.dev`}/v1/traces`,headers:{Authorization:`Bearer ${e.token}`},timeoutMillis:X}),n={[se]:e.serviceName??`stackone-olap`};return e.environment&&(n[`deployment.environment.name`]=e.environment),e.region&&(n[`cloud.region`]=e.region),new ae({resource:ie(n),spanProcessors:[new oe(t)]})}var LogfireEmitter=class{#e;#t;#n;#r;#i=new Set;#a;#o=!1;constructor(e,t,n=defaultProviderFactory){this.#e=e,this.#t=t,this.#n=n}configure(){if(this.#e.token)try{this.#r=this.#n(this.#e)}catch(e){this.#t?.warning({message:`Failed to configure Logfire`,error:e,code:`LogfireConfigureError`,category:`DatasetsSink`})}}emit(e,t){if(this.#r)try{let n=this.#r.getTracer(`stackone-olap`).startSpan(e);for(let[e,r]of Object.entries(t))r!=null&&(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`)?n.setAttribute(e,r):n.setAttribute(e,JSON.stringify(r)));n.end()}catch(e){this.#t?.warning({message:`Failed to emit dataset log to Logfire`,error:e,code:`LogfireEmitError`,category:`DatasetsSink`})}}async flush(){if(!this.#r)return;if(this.#i.size>=4){this.#t?.debug({message:`Logfire exports at the limit, leaving spans queued for the next flush`,category:`DatasetsSink`,context:{maxExportsInFlight:4}});return}let e=this.#s()?X:50;await settleWithin(this.#c(this.#r).then(()=>!0),e,!1)||this.#t?.debug({message:`Logfire export still running, not waiting for it`,category:`DatasetsSink`,context:{flushTimeoutMs:e}})}async drain(e=4e3){if(!this.#r)return;let t=[...this.#i,this.#c(this.#r)];await settleWithin(Promise.all(t).then(()=>!0),e,!1)||this.#t?.warning({message:`Logfire exports still running at shutdown, their spans may be lost`,code:`LogfireDrainTimeout`,category:`DatasetsSink`,context:{timeoutMs:e}})}#s(){return this.#o?!1:this.#a===void 0||Date.now()-this.#a>3e5}#c(e){let t=Date.now(),n=!1,r=setTimeout(()=>{n=Date.now()-t>=2250},X);r.unref?.();let i=new Promise(t=>t(e.forceFlush())).then(()=>{this.#a=Date.now(),this.#o=!1},e=>this.#l(e,Date.now()-t,n));return this.#i.add(i),i.finally(()=>{clearTimeout(r),this.#i.delete(i)}),i}#l(e,t,n){if(n){this.#a=void 0,this.#o=!1,this.#t?.debug({message:`Logfire export failed after the process was frozen`,category:`DatasetsSink`,context:{elapsedMs:t,exportTimeoutMs:X,error:String(e)}});return}this.#o=!0,this.#t?.warning({message:`Failed to flush dataset logs to Logfire`,error:e,code:`LogfireFlushError`,category:`DatasetsSink`,context:{elapsedMs:t}})}},DatasetsSink=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n){this.#e=e?.logfire??{},this.#t=e?.logfire!==void 0,this.#n=e?.maxItemSizeBytes??1048576,this.#r=n??new LogfireEmitter(this.#e,t),this.#i=t}async initialize(){if(!this.#e.token){this.#t&&this.#i?.warning({message:`Logfire configured without a token, datasets sink will not emit`,category:`DatasetsSink`});return}this.#r.configure()}async close(e){this.#a??=this.#r.drain?.(e),await this.#a}async sendAction(e,t,n){await this.sendActions([{input:e,result:t}],n)}async sendActions(e,t){if(!t?.enabled){this.#i?.debug({message:`Datasets sink is disabled, skipping sending actions to datasets sink`,category:`DatasetsSink`});return}let n=0;for(let{input:r,result:i}of e){if(this.#i?.debug({message:`Datasets sink called to send action`,category:`DatasetsSink`,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,includeBackground:t.includeBackground}}),f(r.body)&&f(i.body)){this.#i?.debug({message:`No body in action result, skipping sending action to datasets sink`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(isBackgroundLog(r.mode,r.sourceType)&&!t.includeBackground){this.#i?.debug({message:`Datasets sink is configured to exclude background logs, skipping action with mode ${r.mode}`,category:`DatasetsSink`});continue}let e=this.createSchemaLog(r,i);if(f(e)){this.#i?.debug({message:`No schema extracted from action, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}if(l(e,this.#n)){this.#i?.debug({message:`Dataset schema log exceeds ${this.#n} bytes, skipping`,category:`DatasetsSink`,context:{actionRunId:r.actionRunId}});continue}this.send(r,e),n++}n>0&&(await this.#r.flush(),this.#i?.info({message:`Sent ${n} schema log(s) to logfire`,category:`DatasetsSink`}))}send(e,t){this.#i?.debug({message:`Emitting schema log to Logfire`,category:`DatasetsSink`,context:{actionRunId:e.actionRunId,actionId:e.actionId}}),this.#r.emit(`dataset.schema`,t)}createSchemaLog(e,t){let n=f(e.body)?void 0:u(e.body),r=f(t.body)?void 0:u(t.body);if(!(f(n)&&f(r)))return{organizationId:e.organizationId,projectSecureId:e.projectSecureId,accountSecureId:e.accountSecureId,connectorKey:e.connectorKey,connectorVersion:e.connectorVersion,actionId:e.actionId,schemas:{input:n,result:r}}}};const Z=`DefenderSink`;var DefenderSink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}requireBucket(){if(!this.#e)throw Error(`Defender sink bucket is not configured`);return this.#e}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, defender sink will not function`,category:Z});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(this.#r?.debug({message:`Defender sink called to send action`,category:Z,context:{mode:r.mode,actionId:r.actionId,actionRunId:r.actionRunId,success:i.success,statusCode:i.statusCode,options:{enabled:t?.enabled}}}),!t?.enabled){this.#r?.debug({message:`Defender sink is disabled, skipping sending action to defender sink`,category:Z}),n.push(null);continue}if(f(i.defenderContext)){this.#r?.debug({message:`No defender context in action result, skipping sending action to defender sink`,category:Z,context:{actionRunId:r.actionRunId}}),n.push(null);continue}n.push(await this.send(r,i))}return n}async getAction(e,t,n){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from defender sink`,category:Z});return}return readStoredLog({bucket:this.requireBucket(),key:defenderKey(e,t,n),description:`defender log for actionRunId ${n}`,errorCode:`DefenderLogReadError`,category:Z,logger:this.#r})}async send(e,t){if(this.#t)throw Error(`No storage available, cannot send to defender sink`);let n=this.requireBucket(),r=defenderKey(e.organizationId,e.projectSecureId,e.actionRunId),i=Math.floor(Date.now()/1e3)+this.#n*24*60*60,a=new Date(i*1e3),o=`${this.#n}d`;return this.#r?.debug({message:`Storing defender log in bucket ${n.name} with ${this.#n}-day TTL`,category:Z,context:{bucket:n.name,key:r,ttlTag:o,expiresAt:a.toISOString()}}),await writeStoredLog({bucket:n,key:r,body:JSON.stringify(t.defenderContext),ttlTag:o,expiresAt:a,description:`defender log`,errorCode:`DefenderLogWriteError`,category:Z,logger:this.#r}),{expiresAt:a}}};const defenderKey=(e,t,n)=>`${e}/${t}/${n}/defender.json`,Q={logs:{enabled:!0},advanced:{enabled:!1,ttl:7,errorsOnly:!1,includeBackground:!1,truncation:`drop`,piiRedactionEnabled:!1},defender:{enabled:!0},policy:{enabled:!0},datasets:{enabled:!0,includeBackground:!1}};function resolveOlapOptions(e){return{logs:{...Q.logs,...e?.logs},advanced:{...Q.advanced,...e?.advanced},defender:{...Q.defender,...e?.defender},policy:{...Q.policy,...e?.policy},datasets:{...Q.datasets,...e?.datasets}}}function getPolicySink(e,t,n){return new PolicySink(e,t,n)}const $=`PolicySink`;var PolicySink=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t?.bucket?e?.bucket(t.bucket):void 0,this.#t=!!t?.bucket&&!e,this.#n=t?.ttlDays??365,this.#r=n}async initialize(){if(this.#t){this.#r?.warning({message:`No storage provided, policy sink will not function`,category:$});return}}async sendAction(e,t,n){return(await this.sendActions([{input:e,result:t}],n))[0]??null}async sendActions(e,t){let n=[];for(let{input:r,result:i}of e){if(!t?.enabled){n.push(null);continue}if(!this.#e&&!this.#t){n.push(null);continue}if(f(i.policyContext)){n.push(null);continue}if(!this.#e)throw Error(`No storage available, cannot send to policy sink`);n.push(await this.send(this.#e,r,i))}return n}async getAction(e,t,n,r){if(this.#t){this.#r?.warning({message:`No storage available, cannot get action log from policy sink`,category:$});return}if(this.#e)return readStoredLog({bucket:this.#e,key:policyKey(e,t,n,r),description:`policy log for actionRunId ${r}`,errorCode:`PolicyLogReadError`,category:$,logger:this.#r})}async send(e,t,n){let r=new Date(Date.now()+this.#n*24*60*60*1e3);return await writeStoredLog({bucket:e,key:policyKey(t.organizationId,t.projectSecureId,t.accountSecureId,t.actionRunId),body:JSON.stringify(n.policyContext),ttlTag:`${this.#n}d`,expiresAt:r,description:`policy log`,errorCode:`PolicyLogWriteError`,category:$,logger:this.#r}),{expiresAt:r}}};const policyKey=(e,t,n,r)=>`${e}/${t}/${n}/${r}/policy.json`,yt=`/computeMetadata/v1/instance/service-accounts/default`,requestMetadata=async(e,t)=>{let n=t?.metadataHost??`http://metadata.google.internal`,r=await(t?.fetchImpl??fetch)(`${n}${yt}${e}`,{headers:{"Metadata-Flavor":`Google`},signal:AbortSignal.timeout(t?.timeoutMs??3e3)});if(!r.ok)throw Error(`Google metadata request to ${n}${yt}${e} failed with ${r.status}`);return r},fetchGoogleAccessToken=async e=>{let t=await(await requestMetadata(`/token`,e)).json();if(!t.access_token||typeof t.expires_in!=`number`)throw Error(`Google metadata token response missing access_token or expires_in`);return{accessToken:t.access_token,expiresInSeconds:t.expires_in}},fetchGoogleServiceAccountEmail=async e=>{let t=(await(await requestMetadata(`/email`,e)).text()).trim();if(!t)throw Error(`Google metadata returned an empty service account email`);return t},encodeSegment=e=>Buffer.from(e,`utf8`).toString(`base64url`),bt=e(e=>e instanceof Error?e:Error(String(e)),`toError`),encodeClaims=e=>`{"exp": ${e.expiresAtSeconds}, "iss": "Google", "iat": ${e.issuedAtSeconds}, "sub": ${JSON.stringify(e.principal)}}`,encodeGoogleKafkaToken=(e,t)=>[encodeSegment(`{"typ": "JWT", "alg": "GOOG_OAUTH2_TOKEN"}`),encodeSegment(encodeClaims(t)),encodeSegment(e)].join(`.`),createGoogleKafkaTokenProvider=e=>{let t=e?.now??(()=>Math.floor(Date.now()/1e3)),n=e?.refreshSkewSeconds??60,r={},principal=async()=>(r.principal??=fetchGoogleServiceAccountEmail(e).catch(e=>{throw r.principal=void 0,e}),r.principal),refresh=async()=>{let{accessToken:n,expiresInSeconds:r}=await fetchGoogleAccessToken(e);return{accessToken:n,expiresAtSeconds:t()+r}},credential=async()=>{let i=r.credential;return i&&i.expiresAtSeconds-t()>n?i:(r.inflight??=refresh().then(e=>(r.credential=e,e)).catch(n=>{if(i&&i.expiresAtSeconds>t()){let t=bt(n);return e?.logger?.warning({message:`Google Kafka token refresh failed, using cached token: ${t.message}`,error:t,code:`GoogleKafkaTokenRefreshFailed`,category:`googleKafkaToken`}),i}throw n}).finally(()=>{r.inflight=void 0}),r.inflight)};return async()=>{try{let[{accessToken:e,expiresAtSeconds:n},r]=await Promise.all([credential(),principal()]);return encodeGoogleKafkaToken(e,{principal:r,issuedAtSeconds:t(),expiresAtSeconds:n})}catch(t){let n=bt(t);throw e?.logger?.error({message:`Failed to mint Google Kafka token: ${n.message}`,error:n,code:`GoogleKafkaTokenError`,category:`googleKafkaToken`}),n}}},resolveSasl=(e,t)=>e.mechanism!==`OAUTHBEARER`||e.token?e:{...e,token:createGoogleKafkaTokenProvider({logger:t})},failedOnClosedConnection=e=>{let{code:t,canRetry:n,errors:r}=e??{};return Array.isArray(r)&&r.length>0?r.every(failedOnClosedConnection):t===`PLT_KFK_NETWORK`&&n===!0},withLazyReconstruction=(e,t,n)=>{let r=e,i=0,a,o,s=new Set,closeQuietly=async e=>{try{await e.close()}catch(e){let t=e instanceof Error?e:Error(String(e));n?.warning({message:`Error closing kafka producer: ${t.message}`,error:t,code:`KafkaProducerCloseError`,category:`buildKafkaClient`})}},dispose=e=>{let t=closeQuietly(e).finally(()=>{s.delete(t)});return s.add(t),t},reconstruct=async e=>{if(a||o)return;let s=Date.now();if(!(s-i<3e4)){i=s;try{let i=r;o=t();let s=await o;if(a){await dispose(s);return}r=s,dispose(i),n?.warning({message:`Kafka producer reconstructed after send failure: ${e.message}`,error:e,code:`KafkaProducerReconstructed`,category:`buildKafkaClient`})}catch(e){let t=e;n?.error({message:`Error reconstructing kafka producer: ${t.message}`,error:t,code:`KafkaProducerReconstructionError`,category:`buildKafkaClient`})}finally{o=void 0}}},close=async()=>(a??=(async()=>{let e=o;for(await closeQuietly(r),e&&await e.catch(()=>void 0);s.size>0;)await Promise.allSettled([...s])})(),a),send=async e=>{let t=r;try{return await t.send(e)}catch(n){if(await reconstruct(n),r!==t&&!a&&failedOnClosedConnection(n))return r.send(e);throw n}};return new Proxy(e,{get:(e,t)=>{if(t===`send`)return send;if(t===`close`)return close;let n=Reflect.get(r,t,r);return typeof n==`function`?n.bind(r):n}})},buildKafkaClient=async(e,t)=>{if(!e)return;let construct=async()=>{let{Producer:n,stringSerializers:r}=await import(`@platformatic/kafka`);return new n({retries:3,retryDelay:1e3,...e,...e.sasl&&{sasl:resolveSasl(e.sasl,t)},serializers:r})};try{return withLazyReconstruction(await construct(),construct,t)}catch(e){let n=e;t?.error({message:`Error building kafka producer: ${n.message}`,error:n,code:`BuildKafkaProducerError`,category:`buildKafkaClient`});return}},toError=e=>e instanceof Error?e:Error(String(e)),createMskKafkaTokenProvider=({region:e,logger:t})=>async()=>{try{let{generateAuthToken:t}=await import(`aws-msk-iam-sasl-signer-js`),{token:n}=await t({region:e});return n}catch(e){let n=toError(e);throw t?.error({message:`Failed to mint MSK Kafka token: ${n.message}`,error:n,code:`MskKafkaTokenError`,category:`mskKafkaToken`}),n}},rotateBootstrapBrokers=(e,t=Math.random)=>{let n=Math.floor(t()*e.length);return[...e.slice(n),...e.slice(0,n)]},buildInternalKafkaClient=async(e,t,n=Math.random)=>{if(!e)return;let{bootstrapBrokers:r,region:i,clientId:a,...o}=e;return buildKafkaClient({bootstrapBrokers:rotateBootstrapBrokers(r,n),clientId:a??`olap-internal`,tls:{},sasl:{mechanism:`OAUTHBEARER`,token:createMskKafkaTokenProvider({region:i,logger:t})},...o},t)},defaultStorage=e=>e?.advanced?.bucket||e?.defender?.bucket||e?.policy?.bucket?te(ne()):void 0;var xt=class OlapClient{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;constructor({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){this.name=`OlapClient`,this.#c=e,this.#l=i??r,this.#u=t,this.#d=a,this.#m=o,this.#f=s,this.#p=c,this.#t=n??defaultStorage(c),this.#n=l}static async create({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}){let u=new OlapClient({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});return await u.initialize(),u}async initialize(){this.#e=await this.#c(this.#l,this.#n);let e=this.#d?{producer:await this.#u(this.#d,this.#n)}:void 0,t=this.#e||this.#l?{producer:this.#e}:void 0;this.#r=new LogsSink(t,this.#n,this.#f,e,this.#m),this.#i=new AdvancedSink(this.#t,this.#p?.advanced,this.#n),this.#a=new DefenderSink(this.#t,this.#p?.defender,this.#n),this.#o=new PolicySink(this.#t,this.#p?.policy,this.#n),this.#s=new DatasetsSink(this.#p?.datasets,this.#n),await this.#r?.initialize(),await this.#i?.initialize(),await this.#s?.initialize(),await this.#a?.initialize(),await this.#o?.initialize()}async close(e){await Promise.all([this.#r?.close?.(e),this.#s?.close(e)])}async recordAction(e,t,n){await this.recordActions([{input:e,result:t}],n)}async recordActions(e,t){let{logs:n,advanced:r,defender:i,policy:a,datasets:o}=resolveOlapOptions(t);this.#n?.info({message:`Olap client called to record ${e.length} action(s)`,category:`OlapClient`,context:{options:t,resolvedOptions:{logs:n,advanced:r,defender:i,policy:a,datasets:o}}});for(let t of e)f(t.input.isBackground)&&(t.input.isBackground=isBackgroundLog(t.input.mode,t.input.sourceType));let s=a?.enabled&&this.#o?this.#o.sendActions(e,a).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to policy logs storage: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=o?.enabled&&this.#s?this.#s.sendActions(e,o).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to datasets sink: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),[l,u]=await Promise.all([r?.enabled&&this.#i?this.#i.sendActions(e,r).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null)),i?.enabled&&this.#a?this.#a.sendActions(e,i).catch(t=>(this.#n?.warning({message:`[OlapClient] Error sending to defender logs storage: ${t.message}`,category:`OlapClient`,error:t}),e.map(()=>null))):Promise.resolve(e.map(()=>null))]),d=e.map((e,t)=>({...e,metadata:{advancedExpiresAt:l[t]?.expiresAt,defenderExpiresAt:u[t]?.expiresAt}})),p=n?.enabled&&this.#r?this.#r.sendActions(d,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve();await Promise.all([c,s,p])}async recordStep(e,t,n){await this.recordSteps([{input:e,result:t}],n)}async recordSteps(e,t){let{logs:n,advanced:r}=resolveOlapOptions(t),i=[];n?.enabled&&this.#r&&i.push(this.#r.sendSteps(e,n).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),r?.enabled&&this.#i&&i.push(this.#i.sendSteps(e,r).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(i)}async recordUnified(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n);this.#n?.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}}}),f(e.isBackground)&&(e.isBackground=isBackgroundLog(e.mode,e.sourceType));let a={advancedExpiresAt:(i?.enabled&&this.#i?await this.#i.sendUnified(e,t,i).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):null)?.expiresAt};r?.enabled&&this.#r&&await this.#r.sendUnified(e,t,a,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})}async recordProvider(e,t,n){let{logs:r,advanced:i}=resolveOlapOptions(n),a=[];r?.enabled&&this.#r&&a.push(this.#r.sendProvider(e,t,r).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})})),i?.enabled&&this.#i&&a.push(this.#i.sendProvider(e,t,i).then(()=>{}).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to storage: ${e.message}`,category:`OlapClient`,error:e})})),await Promise.all(a)}async recordPlatform(e,t,n){let r=isPlatformLog(e),i=r&&t&&`data`in t?t:void 0,{logs:a,advanced:o}=resolveOlapOptions(r&&!i?t:n),s=a?.enabled&&this.#r?(r?this.#r.sendPlatform(e,a):this.#r.sendPlatform(e,t??{},a)).catch(e=>{this.#n?.warning({message:`[OlapClient] Error sending to kafka: ${e.message}`,category:`OlapClient`,error:e})}):Promise.resolve(),c=r&&i&&o?.enabled&&this.#i?this.#i.sendPlatform(e,i,o).catch(e=>(this.#n?.warning({message:`[OlapClient] Error sending to advanced logs storage: ${e.message}`,category:`OlapClient`,error:e}),null)):Promise.resolve(null);await Promise.all([s,c])}async getLogs(e,t,n){return this.#n?.debug({message:`Querying logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query logs, returning empty result`,category:`OlapClient`}),{logs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getLastLogs(e,t,n,r={}){let i={...r,organizationId:e,projectSecureId:t};return this.#n?.debug({message:`Querying last logs`,category:`OlapClient`,context:{entities:n,query:i}}),await this.#r?.getLastLogs(n,i)||(this.#n?.warning({message:`Failed to query last logs, returning empty result`,category:`OlapClient`}),emptyQueryResult())}async getActionLogs(e,t,n){return this.#n?.debug({message:`Querying action logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getActions({...n,organizationId:e,projectSecureId:t})||(this.#n?.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.#r?.getAction(e,t,n);if(f(r)){this.#n?.debug({message:`Failed to retrieve action log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLog(e,t,n){this.#n?.debug({message:`Querying log by logId`,category:`OlapClient`,context:{logId:n}});let r=await this.getLogs(e,t,{logId:n,pageSize:1});if(!r||r.logs.length===0){this.#n?.debug({message:`Failed to retrieve log for logId ${n}`,category:`OlapClient`});return}let i=r.logs[0];if(i.logType===`action`||i.logType===`unified`)return i}async getStepLogs(e,t,n){return this.#n?.debug({message:`Querying step logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSteps({...n,organizationId:e,projectSecureId:t})||(this.#n?.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.#r?.getStep(e,t,n,r);if(f(i)){this.#n?.debug({message:`Failed to retrieve step log for actionRunId ${n} stepIndex ${r}`,category:`OlapClient`});return}return i}async getUnifiedLogs(e,t,n){return this.#n?.debug({message:`Querying unified logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getUnifiedLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.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.#r?.getUnifiedLog(e,t,n);if(f(r)){this.#n?.debug({message:`Failed to retrieve unified log for requestId ${n}`,category:`OlapClient`});return}return r}async getProviderLogs(e,t,n){return this.#n?.debug({message:`Querying provider logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getProviderLogs({...n,organizationId:e,projectSecureId:t})||(this.#n?.warning({message:`Failed to query provider logs, returning empty result`,category:`OlapClient`}),{providerLogs:[],total:0,pageNumber:n.pageNumber??1,pageSize:n.pageSize??0})}async getPlatformLogs(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform logs`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogs(n)||(this.#n?.warning({message:`Failed to query platform logs, returning empty result`,category:`OlapClient`}),{platformLogs:[],total:0,pageNumber:t.pageNumber??1,pageSize:t.pageSize??0})}async getPlatformLogDimensions(e,t){let n={...t,organizationId:e};return this.#n?.debug({message:`Querying platform log dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getPlatformLogDimensions(n)||(this.#n?.warning({message:`Failed to query platform log dimensions, returning empty result`,category:`OlapClient`}),{})}async getProviderLog(e,t,n,r){let i=await this.#r?.getProviderLog(e,t,n,r);if(f(i)){this.#n?.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.#i?.getAction(e,t,n);if(f(r)){this.#n?.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.#i?.getStep(e,t,n,r);if(f(i)){this.#n?.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.#i?.getUnified(e,t,n);if(f(r)){this.#n?.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.#i?.getProvider(e,t,n,r);if(f(i)){this.#n?.debug({message:`Failed to retrieve provider advanced log for requestId ${n} id ${r}`,category:`OlapClient`});return}return i}async getPlatformAdvancedLog(e,t){let n=await this.#i?.getPlatform(e,t);if(f(n)){this.#n?.debug({message:`Failed to retrieve platform advanced log for eventId ${t}`,category:`OlapClient`});return}return n}async getPolicyLog(e,t,n,r){let i=await this.#o?.getAction(e,t,n,r);if(f(i)){this.#n?.debug({message:`Failed to retrieve policy log for actionRunId ${r}`,category:`OlapClient`});return}return i}async getDefenderLog(e,t,n){let r=await this.#a?.getAction(e,t,n);if(f(r)){this.#n?.debug({message:`Failed to retrieve defender log for actionRunId ${n}`,category:`OlapClient`});return}return r}async getLogsStatsAggregate(e,t,n){return this.#n?.debug({message:`Querying logs stats aggregate`,category:`OlapClient`,context:{query:n}}),await this.#r?.getAggregate(e,t,n)??{data:[]}}async getLogsStatsDimensions(e,t,n){return this.#n?.debug({message:`Querying logs stats dimensions`,category:`OlapClient`,context:{query:n}}),await this.#r?.getDimensions(e,t,n)??{}}async getSourceUsage(e,t,n){return this.#n?.debug({message:`Querying source usage`,category:`OlapClient`,context:{query:n}}),await this.#r?.getSourceUsage(e,t,n)??[]}async getActionsCount(e){if(!this.#r)throw Error(`Cannot count actions: the logs sink is not configured`);return this.#r.getActionsCount(e)}};const buildOlapClientInstance=async({getKafkaClient:e=buildKafkaClient,getInternalKafkaClient:t=buildInternalKafkaClient,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l})=>xt.create({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l});var OlapClientManager=class{static{this.olapClientPromise=null}static{this.closingPromise=null}static getInstance({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l,getOlapClient:u=buildOlapClientInstance}){return this.olapClientPromise||=u({getKafkaClient:e,getInternalKafkaClient:t,storage:n,kafkaClientConfig:r,externalKafkaClientConfig:i,internalKafkaClientConfig:a,topicClusterMap:o,clickhouseConfig:s,sinkConfig:c,logger:l}),this.olapClientPromise}static resetInstance(){this.olapClientPromise=null,this.closingPromise=null}static async close(e){let t=this.olapClientPromise;if(this.olapClientPromise=null,!t)return this.closingPromise??void 0;let n=this.closingPromise,r=(async()=>{await n?.catch(()=>void 0),await this.drain(t,e)})().finally(()=>{this.closingPromise===r&&(this.closingPromise=null)});return this.closingPromise=r,r}static async drain(e,t){let n,r=!1;try{let i=await Promise.race([e,new Promise((e,t)=>{n=setTimeout(()=>{r=!0,t(Error(`timed out waiting for olap initialisation`))},6e4),n.unref?.()})]);n&&=(clearTimeout(n),void 0),await i.close?.(t)}catch{}finally{n&&clearTimeout(n),r&&e.then(e=>e.close?.(t)).catch(()=>void 0)}}};export{fe as AuthType,De as DEFAULT_TOPIC_CLUSTER_MAP,Te as Dimension,T as IntervalType,InvalidAuthPairError,InvalidLogQueryConditionsError,ke as LOG_QUERY_FIELDS,je as LOG_QUERY_OPERATORS,w as LogType,xt as OlapClient,OlapClientManager,Ce as OrderBy,we as OrderDirection,Ee as PlatformDimension,PolicySink,QueryClientNotConfiguredError,b as SourceType,de as StreamType,ue as TransportType,callerHeadersOf,getPolicySink,hasErrorEntries,parseLogQueryConditions};