@onereach/step-run-snowflake-query 0.1.0-ci.7 → 0.1.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/package.json +1 -1
- package/dist/index.d.mts +0 -185
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -3
- package/dist/index.mjs.map +0 -1
package/package.json
CHANGED
package/dist/index.d.mts
DELETED
|
@@ -1,185 +0,0 @@
|
|
|
1
|
-
import { z } from "zod/v4-mini";
|
|
2
|
-
import { Connection } from "snowflake-sdk";
|
|
3
|
-
import Step from "@onereach/flow-sdk/step.js";
|
|
4
|
-
import { CONFIG, IFlow, ILogger, IStepInfo } from "@onereach/flow-sdk/types/index.js";
|
|
5
|
-
|
|
6
|
-
//#region src/schemas/data-in.d.ts
|
|
7
|
-
declare const logLevelSchema: z.ZodMiniEnum<{
|
|
8
|
-
TRACE: "TRACE";
|
|
9
|
-
DEBUG: "DEBUG";
|
|
10
|
-
INFO: "INFO";
|
|
11
|
-
WARNING: "WARNING";
|
|
12
|
-
ERROR: "ERROR";
|
|
13
|
-
OFF: "OFF";
|
|
14
|
-
}>;
|
|
15
|
-
type LogLevel = z.infer<typeof logLevelSchema>;
|
|
16
|
-
declare const authSchema: z.ZodMiniObject<{
|
|
17
|
-
auth: z.ZodMiniObject<{
|
|
18
|
-
account: z.ZodMiniString<string>;
|
|
19
|
-
authenticator: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
20
|
-
username: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
21
|
-
warehouse: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
22
|
-
role: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
23
|
-
host: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
24
|
-
schema: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
25
|
-
database: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
26
|
-
}, z.core.$loose>;
|
|
27
|
-
privateKey: z.ZodMiniObject<{
|
|
28
|
-
pemKey: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
29
|
-
keyPass: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
30
|
-
}, z.core.$strip>;
|
|
31
|
-
logLevel: z.ZodMiniDefault<z.ZodMiniEnum<{
|
|
32
|
-
TRACE: "TRACE";
|
|
33
|
-
DEBUG: "DEBUG";
|
|
34
|
-
INFO: "INFO";
|
|
35
|
-
WARNING: "WARNING";
|
|
36
|
-
ERROR: "ERROR";
|
|
37
|
-
OFF: "OFF";
|
|
38
|
-
}>>;
|
|
39
|
-
checkConnectionDelayMs: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
|
|
40
|
-
cacheConnection: z.ZodMiniDefault<z.ZodMiniEnum<{
|
|
41
|
-
process: "process";
|
|
42
|
-
thread: "thread";
|
|
43
|
-
}>>;
|
|
44
|
-
preCreateConnection: z.ZodMiniDefault<z.ZodMiniBoolean<boolean>>;
|
|
45
|
-
}, z.core.$strip>;
|
|
46
|
-
type SnowflakeAuth = z.infer<typeof authSchema>;
|
|
47
|
-
declare const dataInSchema: z.ZodMiniObject<{
|
|
48
|
-
auth: z.ZodMiniObject<{
|
|
49
|
-
account: z.ZodMiniString<string>;
|
|
50
|
-
authenticator: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
51
|
-
username: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
52
|
-
warehouse: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
53
|
-
role: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
54
|
-
host: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
55
|
-
schema: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
56
|
-
database: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
57
|
-
}, z.core.$loose>;
|
|
58
|
-
privateKey: z.ZodMiniObject<{
|
|
59
|
-
pemKey: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
60
|
-
keyPass: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniString<string>]>, z.ZodMiniTransform<string | undefined, string | undefined>>;
|
|
61
|
-
}, z.core.$strip>;
|
|
62
|
-
logLevel: z.ZodMiniDefault<z.ZodMiniEnum<{
|
|
63
|
-
TRACE: "TRACE";
|
|
64
|
-
DEBUG: "DEBUG";
|
|
65
|
-
INFO: "INFO";
|
|
66
|
-
WARNING: "WARNING";
|
|
67
|
-
ERROR: "ERROR";
|
|
68
|
-
OFF: "OFF";
|
|
69
|
-
}>>;
|
|
70
|
-
checkConnectionDelayMs: z.ZodMiniPipe<z.ZodMiniUnion<readonly [z.ZodMiniUndefined, z.ZodMiniLiteral<"">, z.ZodMiniNumber<unknown>]>, z.ZodMiniTransform<number | undefined, number | "" | undefined>>;
|
|
71
|
-
cacheConnection: z.ZodMiniDefault<z.ZodMiniEnum<{
|
|
72
|
-
process: "process";
|
|
73
|
-
thread: "thread";
|
|
74
|
-
}>>;
|
|
75
|
-
preCreateConnection: z.ZodMiniDefault<z.ZodMiniBoolean<boolean>>;
|
|
76
|
-
sqlText: z.ZodMiniString<string>;
|
|
77
|
-
binds: z.ZodMiniUnion<readonly [z.ZodMiniUnion<readonly [z.ZodMiniArray<z.ZodMiniUnion<readonly [z.ZodMiniNumber<unknown>, z.ZodMiniString<string>, z.ZodMiniBoolean<boolean>, z.ZodMiniNull]>>, z.ZodMiniArray<z.ZodMiniArray<z.ZodMiniUnion<readonly [z.ZodMiniNumber<unknown>, z.ZodMiniString<string>, z.ZodMiniBoolean<boolean>, z.ZodMiniNull]>>>]>, z.ZodMiniPipe<z.ZodMiniArray<z.ZodMiniObject<{
|
|
78
|
-
value: z.ZodMiniUnion<readonly [z.ZodMiniNumber<unknown>, z.ZodMiniString<string>, z.ZodMiniBoolean<boolean>, z.ZodMiniNull]>;
|
|
79
|
-
}, z.core.$strip>>, z.ZodMiniTransform<(string | number | boolean | null)[], {
|
|
80
|
-
value: string | number | boolean | null;
|
|
81
|
-
}[]>>, z.ZodMiniPipe<z.ZodMiniArray<z.ZodMiniObject<{
|
|
82
|
-
value: z.ZodMiniArray<z.ZodMiniUnion<readonly [z.ZodMiniNumber<unknown>, z.ZodMiniString<string>, z.ZodMiniBoolean<boolean>, z.ZodMiniNull]>>;
|
|
83
|
-
}, z.core.$strip>>, z.ZodMiniTransform<(string | number | boolean | null)[][], {
|
|
84
|
-
value: (string | number | boolean | null)[];
|
|
85
|
-
}[]>>]>;
|
|
86
|
-
fetchAsString: z.ZodMiniArray<z.ZodMiniEnum<{
|
|
87
|
-
Boolean: "Boolean";
|
|
88
|
-
Number: "Number";
|
|
89
|
-
Date: "Date";
|
|
90
|
-
Buffer: "Buffer";
|
|
91
|
-
JSON: "JSON";
|
|
92
|
-
}>>;
|
|
93
|
-
}, z.core.$strip>;
|
|
94
|
-
type DataIn = z.infer<typeof dataInSchema>;
|
|
95
|
-
//#endregion
|
|
96
|
-
//#region src/threads/base/types.d.ts
|
|
97
|
-
interface BaseConfig extends CONFIG {
|
|
98
|
-
dataIn: DataIn;
|
|
99
|
-
}
|
|
100
|
-
//#endregion
|
|
101
|
-
//#region src/threads/base/base.d.ts
|
|
102
|
-
declare class BaseStep<T extends BaseConfig> extends Step<T> {
|
|
103
|
-
resolveDataIn(): Promise<{
|
|
104
|
-
auth: {
|
|
105
|
-
[x: string]: unknown;
|
|
106
|
-
account: string;
|
|
107
|
-
authenticator: string | undefined;
|
|
108
|
-
username: string | undefined;
|
|
109
|
-
warehouse: string | undefined;
|
|
110
|
-
role: string | undefined;
|
|
111
|
-
host: string | undefined;
|
|
112
|
-
schema: string | undefined;
|
|
113
|
-
database: string | undefined;
|
|
114
|
-
};
|
|
115
|
-
privateKey: {
|
|
116
|
-
pemKey: string | undefined;
|
|
117
|
-
keyPass: string | undefined;
|
|
118
|
-
};
|
|
119
|
-
logLevel: "TRACE" | "DEBUG" | "INFO" | "WARNING" | "ERROR" | "OFF";
|
|
120
|
-
checkConnectionDelayMs: number | undefined;
|
|
121
|
-
cacheConnection: "process" | "thread";
|
|
122
|
-
preCreateConnection: boolean;
|
|
123
|
-
sqlText: string;
|
|
124
|
-
binds: (string | number | boolean | null)[] | (string | number | boolean | null)[][];
|
|
125
|
-
fetchAsString: ("Boolean" | "Number" | "Date" | "Buffer" | "JSON")[];
|
|
126
|
-
}>;
|
|
127
|
-
}
|
|
128
|
-
//#endregion
|
|
129
|
-
//#region src/threads/main/types.d.ts
|
|
130
|
-
interface SnowflakeExecuteSqlConfig extends CONFIG {
|
|
131
|
-
dataIn: DataIn;
|
|
132
|
-
}
|
|
133
|
-
//#endregion
|
|
134
|
-
//#region src/threads/main/step.d.ts
|
|
135
|
-
declare class SnowflakeExecuteSqlStep extends BaseStep<SnowflakeExecuteSqlConfig> {
|
|
136
|
-
static init(flow: IFlow<SnowflakeExecuteSqlConfig>, step: IStepInfo<SnowflakeExecuteSqlConfig>): void;
|
|
137
|
-
runStep(): Promise<void>;
|
|
138
|
-
private get snowflakeService();
|
|
139
|
-
}
|
|
140
|
-
//#endregion
|
|
141
|
-
//#region src/services/snowflake/connection-info.d.ts
|
|
142
|
-
declare class ConnectionInfo {
|
|
143
|
-
private readonly connection;
|
|
144
|
-
private readonly log;
|
|
145
|
-
private readonly _checkConnectionDelayMs;
|
|
146
|
-
private lastReconnectTime?;
|
|
147
|
-
private connectPromise?;
|
|
148
|
-
constructor(connectionData: SnowflakeAuth, logger: ILogger);
|
|
149
|
-
createConnection(logData?: Record<string, unknown>): Promise<Connection>;
|
|
150
|
-
/**
|
|
151
|
-
* Destroy specific Snowflake connection
|
|
152
|
-
*
|
|
153
|
-
* This method shout NOT use {@link ConnectionInfo.log} and instead use {@link logger} argument
|
|
154
|
-
* because this method runs in a flow level hook that has limited features.
|
|
155
|
-
*/
|
|
156
|
-
destroyConnection(logger: ILogger, logData?: Record<string, unknown>): Promise<void>;
|
|
157
|
-
private initConnection;
|
|
158
|
-
/**
|
|
159
|
-
* Runs connect for Snowflake connection
|
|
160
|
-
* After this method it's safe to await {@link connectPromise} to address concurrent connection requests
|
|
161
|
-
*
|
|
162
|
-
* @param logData Additional data for logs
|
|
163
|
-
*/
|
|
164
|
-
private connect;
|
|
165
|
-
/**
|
|
166
|
-
* Checks if connection is still valid and if it's not then connects
|
|
167
|
-
* After this method it's safe to await {@link connectPromise} to address concurrent connection requests
|
|
168
|
-
*
|
|
169
|
-
* @param logData Additional data for logs
|
|
170
|
-
*/
|
|
171
|
-
private reconnect;
|
|
172
|
-
private get checkConnectionDelayMs();
|
|
173
|
-
}
|
|
174
|
-
//#endregion
|
|
175
|
-
//#region src/services/snowflake/types.d.ts
|
|
176
|
-
type ConnHash = string;
|
|
177
|
-
type ConnectionsMap = Map<ConnHash, ConnectionInfo>;
|
|
178
|
-
type ThreadName = string | null;
|
|
179
|
-
type ThreadsConnectionsMap = Map<ThreadName, ConnectionsMap>;
|
|
180
|
-
//#endregion
|
|
181
|
-
//#region src/index.d.ts
|
|
182
|
-
declare const states: {};
|
|
183
|
-
//#endregion
|
|
184
|
-
export { BaseConfig, ConnHash, ConnectionsMap, DataIn, LogLevel, SnowflakeAuth, SnowflakeExecuteSqlConfig, ThreadName, ThreadsConnectionsMap, dataInSchema, states, SnowflakeExecuteSqlStep as step };
|
|
185
|
-
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/schemas/data-in.ts","../src/threads/base/types.ts","../src/threads/base/base.ts","../src/threads/main/types.ts","../src/threads/main/step.ts","../src/services/snowflake/connection-info.ts","../src/services/snowflake/types.ts","../src/index.ts"],"mappings":";;;;;;cAsCM,cAAA,EAAc,CAAA,CAAA,WAAA;;;;;;;;KACR,QAAA,GAAW,CAAA,CAAE,KAAA,QAAa,cAAA;AAAA,cAEhC,UAAA,EAAU,CAAA,CAAA,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA6BJ,aAAA,GAAgB,CAAA,CAAE,KAAA,QAAa,UAAA;AAAA,cAE9B,YAAA,EAAY,CAAA,CAAA,aAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAMb,MAAA,GAAS,CAAA,CAAE,KAAA,QAAa,YAAA;;;UC1EnB,UAAA,SAAmB,MAAA;EAClC,MAAA,EAAQ,MAAA;AAAA;;;cCGG,QAAA,WAAmB,UAAA,UAAoB,IAAA,CAAK,CAAA;EAE1C,aAAA,CAAA,GAAa,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;UCNX,yBAAA,SAAkC,MAAA;EACjD,MAAA,EAAQ,MAAA;AAAA;;;cCUG,uBAAA,SAAgC,QAAA,CAAS,yBAAA;EAAA,OAC7C,IAAA,CAAK,IAAA,EAAM,KAAA,CAAM,yBAAA,GAA4B,IAAA,EAAM,SAAA,CAAU,yBAAA;EAiBvD,OAAA,CAAA,GAAW,OAAA;EAAA,YASZ,gBAAA,CAAA;AAAA;;;cChCD,cAAA;EAAA,iBACM,UAAA;EAAA,iBACA,GAAA;EAAA,iBACA,uBAAA;EAAA,QAET,iBAAA;EAAA,QACA,cAAA;cAEI,cAAA,EAAgB,aAAA,EAAe,MAAA,EAAQ,OAAA;EAMtC,gBAAA,CAAiB,OAAA,GAAU,MAAA,oBAA0B,OAAA,CAAQ,UAAA;ELcxD;;;;;;EKIL,iBAAA,CAAkB,MAAA,EAAQ,OAAA,EAAS,OAAA,GAAU,MAAA,oBAA0B,OAAA;EAAA,QAmB5E,cAAA;;ALtBV;;;;;UK2CgB,OAAA;EL3CsB;;;AAAgB;;;EAAhB,QK6EtB,SAAA;EAAA,YA6BF,sBAAA,CAAA;AAAA;;;KC/IF,QAAA;AAAA,KACA,cAAA,GAAiB,GAAA,CAAI,QAAA,EAAU,cAAA;AAAA,KAC/B,UAAA;AAAA,KACA,qBAAA,GAAwB,GAAA,CAAI,UAAA,EAAY,cAAA;;;cCAvC,MAAA"}
|
package/dist/index.mjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";import{install as t}from"source-map-support";import{Memoize as n}from"typescript-memoize";import r from"@onereach/flow-sdk/errors/timeout.js";import{z as i}from"zod/v4-mini";import a from"@onereach/flow-sdk/errors/base.js";import o,{createPrivateKey as s}from"node:crypto";import c from"snowflake-sdk";import{setInstance as l}from"snowflake-sdk/dist/lib/logger.js";import{format as u}from"node:util";import{BasicThreadService as d}from"@onereach/flow-sdk/services/basic.js";import{readFile as f}from"node:fs/promises";import p from"@onereach/flow-sdk/step.js";import{en as m}from"zod/v4/locales";const h={UNKNOWN:`UNKNOWN`,STEP_LOGIC_ISSUE:`STEP_LOGIC_ISSUE`,AUTH:`AUTH`,TIMEOUT:`TIMEOUT`,VALIDATION:`VALIDATION`,INVALID_REQUEST:`INVALID_REQUEST`,RATE_LIMITED:`RATE_LIMITED`,SERVER_ERROR:`SERVER_ERROR`,UNSUPPORTED:`UNSUPPORTED`};var g=class extends a{};const _=[g,r];function v(e,t={}){let{preserveErrors:n=_,unknownMessage:a=`Unknown error`,unknownCode:o=h.UNKNOWN}=t;if(n?.some(t=>e instanceof t))return e;if(e instanceof i.core.$ZodError)return new g(i.prettifyError(e),e,{code:h.VALIDATION});if(typeof e==`string`)return new g(e,{code:h.UNKNOWN});if(e instanceof Error){if(e.message.includes(`Request timed out`))return new r(`Timeout`,e,{code:h.TIMEOUT});let t=e?.response?.data?.error?.message;return t==null?new g(a,e,{code:o}):new g(t,e,{code:h.SERVER_ERROR})}return new g(a,{code:o,data:e})}function y(e,t){function n(t,n,r,i){let a=e(t,n,r,i);if(typeof a==`function`){let e=i.value,t=a;if(e?.name!=null)try{Object.defineProperty(t,`name`,{value:e.name})}catch{}return i.value=t,i}return a??i}return function(e,r,i){if(typeof e==`object`&&e&&(typeof r==`string`||typeof r==`symbol`)&&typeof i==`object`&&i)return n(t,e,r,i);{let r=e??t;return(e,t,i)=>n(r,e,t,i)}}}const b=y((e,t,n,r)=>{let i=r.value;if(!(!i||typeof i!=`function`))return function(...e){try{let t=i.apply(this,e);return t instanceof Promise?t.catch(e=>{let t=n.toString();throw this.log.DEBUG?.(`Error in method '${t}'`,e),v(e)}):t}catch(e){let t=n.toString();throw this.log.DEBUG?.(`Error in method '${t}'`,e),v(e)}}},{});function x(e){let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(n&&typeof n==`object`){if(t.has(n))return`[Circular]`;if(t.add(n),Array.isArray(n))return n;let e={};for(let t of Object.keys(n).sort())e[t]=n[t];return e}return n})}function S(e){let t=x(e);return o.createHash(`sha256`).update(t).digest(`hex`)}function C(e,t){if(e!=null)return s({key:e.replaceAll(String.raw`\n`,`
|
|
2
|
-
`).trim(),format:`pem`,passphrase:t}).export({format:`pem`,type:`pkcs8`})}var w=class{log;logLevel;constructor(e,t){this.configure(t),this.log=e,this.logLevel=t.logLevel??`ERROR`}trace(e,...t){this.shouldLog(`TRACE`)&&this.log.DEBUG?.(u(e,...t))}debug(e,...t){this.shouldLog(`DEBUG`)&&this.log.DEBUG?.(u(e,...t))}info(e,...t){this.shouldLog(`INFO`)&&this.log.INFO?.(u(e,...t))}warn(e,...t){this.shouldLog(`WARNING`)&&this.log.WARN?.(u(e,...t))}error(e,...t){this.shouldLog(`ERROR`)&&this.log.ERROR?.(u(e,...t))}getLevelTag(){return this.logLevel??`ERROR`}getLevel(){return this.getLevelValue(this.getLevelTag())}getLogBuffer(){return[]}configure(e){e.logLevel&&(this.logLevel=e.logLevel)}shouldLog(e){return this.getLevelValue(e)>=this.getLevelValue(this.logLevel)}getLevelValue(e){let t={TRACE:0,DEBUG:1,INFO:2,WARNING:3,ERROR:4,OFF:5};return t[e]??t.ERROR}},T=class{connection;log;_checkConnectionDelayMs;lastReconnectTime;connectPromise;constructor(e,t){this.log=t,this.connection=this.initConnection(e),this._checkConnectionDelayMs=e.checkConnectionDelayMs}async createConnection(e){return this.lastReconnectTime?Date.now()-this.lastReconnectTime>this.checkConnectionDelayMs&&await this.reconnect(e):await this.connect(e),this.connectPromise&&await this.connectPromise,this.connection}async destroyConnection(e,t){return new Promise(n=>setImmediate(()=>{let r={connectionId:this.connection.getId(),...t};e.DEBUG?.(`Destroying Snowflake connection...`,r),this.connection.destroy(t=>{if(t)return e.WARN?.(`Failed to destroy Snowflake connection`,{error:t.message,...r}),n();e.DEBUG?.(`Successfully destroyed snowflake connection`,r),n()})}))}initConnection(e){return this.log.DEBUG?.(`Initializing Snowflake connection...`),l(new w(this.log,{logLevel:e.logLevel})),c.createConnection({clientSessionKeepAlive:!0,clientSessionKeepAliveHeartbeatFrequency:20,privateKey:C(e.privateKey.pemKey,e.privateKey.keyPass),...e.auth})}async connect(e){return this.lastReconnectTime=Date.now(),this.connectPromise=new Promise((t,n)=>setImmediate(()=>{this.log.DEBUG?.(`Connecting to Snowflake...`,e),this.connection.connect((r,i)=>{if(r)return this.log.DEBUG?.(`Failed to connect to Snowflake`,{error:r.message,...e}),delete this.lastReconnectTime,delete this.connectPromise,n(r);let a=Date.now()-this.lastReconnectTime;this.log.DEBUG?.(`Successfully connected to Snowflake`,{connectionId:i.getId(),durationMs:a,...e}),delete this.connectPromise,t()})})),this.connectPromise}async reconnect(e){return this.lastReconnectTime=Date.now(),this.connectPromise=new Promise((t,n)=>setImmediate(()=>{let r={connectionId:this.connection.getId(),...e};this.log.DEBUG?.(`Checking if Snowflake connection is still valid`,r),this.connection.isValidAsync().then(async n=>{n?(this.log.DEBUG?.(`Snowflake connection is still valid. Reusing it.`,r),delete this.connectPromise):await this.connect(e),t()}).catch(e=>{this.log.ERROR?.(`Failed to reconnect to Snowflake`,r),delete this.connectPromise,delete this.lastReconnectTime,n(e)})})),this.connectPromise}get checkConnectionDelayMs(){return this._checkConnectionDelayMs??3e4}},E=class e{process;static get processCacheKey(){return`snfl_cnc`}constructor(e){this.process=e}async createConnection(e,t){let n=this.getStore()??this.initStore(),r=t.cacheConnection===`thread`?e.id:null,i=n.get(r);i||(i=new Map,n.set(r,i));let{auth:a,privateKey:o}=t,s=S({auth:a,privateKey:o}),c=i.get(s);return c||(c=new T(t,e.log),i.set(s,c)),await c.createConnection({connectionHash:s,threadKey:r})}async destroyAllConnections(e){let t=this.getStore(e);if(!t){e.log.WARN?.(`Missing snowflake connections store`);return}let n=[];for(let[r,i]of t){let t=r?`thread '${r}'`:`process`;e.log.DEBUG?.(`Destroying Snowflake connections for ${t}...`);for(let[t,a]of i){let i=a.destroyConnection(e.log,{connectionHash:t,threadName:r});n.push(i)}}await Promise.allSettled(n),n.length>0&&e.log.DEBUG?.(`Finished destroying Snowflake connections`)}getStore(t=this.process){return t.cache[e.processCacheKey]}initStore(){let t=this.process.cache[e.processCacheKey];return t||(t=this.process.cache[e.processCacheKey]=new Map,this.process.flow.once(`process:response`,async({context:e})=>{let t=e;await this.destroyAllConnections(t)})),t}},D=class extends d{data;constructor(e,t){super(e),this.data=t}};function O(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function k(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var A,j=class extends D{async executeSql(){let e=await this.connectionsStore.createConnection(this.thread,this.data);return await this._executeSql(e)}async _executeSql(e){let{sqlText:t,binds:n,fetchAsString:r}=this.data,i=e.getId();this.log.DEBUG?.(`Executing Snowflake SQL query...`,{connectionId:i});let a=Date.now();return await new Promise((o,s)=>{e.execute({sqlText:t,binds:n,fetchAsString:[...new Set(r)],complete:(e,t,n)=>{let r=Date.now()-a;if(e)return this.log.DEBUG?.(`Failed to execute Snowflake SQL query`,{error:e.message,connectionId:i,durationMs:r}),s(e);this.log.DEBUG?.(`Successfully execute Snowflake SQL query`,{connectionId:i,durationMs:r}),o({rows:n})}})})}get connectionsStore(){return new E(this.process)}};k([n(),O(`design:type`,typeof(A=E!==void 0&&E)==`function`?A:Object),O(`design:paramtypes`,[])],j.prototype,`connectionsStore`,null);const M=e(import.meta.url);async function N(e){if(typeof e!=`string`||!/^\d+\.\d+\.\d+$/.test(e))throw new g(`Invalid minimum version format: ${e}`,{code:h.STEP_LOGIC_ISSUE});let t=M.resolve(`@onereach/flow-sdk/package.json`);if(!t)throw new g(`Could not find package.json for @onereach/flow-sdk`,{code:h.STEP_LOGIC_ISSUE});let n=await f(t,`utf8`),{version:r}=JSON.parse(n),{groups:i}=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)/.exec(r)||{};if(!i)throw new g(`Invalid Flow SDK version format: ${r}`,{code:h.STEP_LOGIC_ISSUE});let a=Number.parseInt(i.major??`0`,10),o=Number.parseInt(i.minor??`0`,10),s=Number.parseInt(i.patch??`0`,10);if(a==null||o==null||s==null||Number.isNaN(a)||Number.isNaN(o)||Number.isNaN(s))throw new g(`Invalid version format: ${r}`,{code:h.STEP_LOGIC_ISSUE});let[c,l,u]=e.split(`.`).map(e=>Number.parseInt(e,10));if(c==null||l==null||u==null||Number.isNaN(c)||Number.isNaN(l)||Number.isNaN(u))throw new g(`Invalid minimum version format: ${e}`,{code:h.STEP_LOGIC_ISSUE});if(a<c||a===c&&o<l||a===c&&o===l&&s<u)throw new g(`Flow SDK version '${r}' is lower than required minimum version '${e}' for the step`,{code:h.VALIDATION})}i.config(m());const P=i.string().check(i.trim(),i.refine(e=>![`undefined`,`null`].includes(e),{error:`Unexpected undefined or null merge-field value`})),F=i.union([i.coerce.number(),P,i.boolean(),i.null()]),I=i.array(i.array(F)),L=i.union([i.array(F),I]),R=i.union([L,i.pipe(i.array(i.object({value:F})),i.transform(e=>e.map(e=>e.value))),i.pipe(i.array(i.object({value:i.array(F)})),i.transform(e=>e.map(e=>e.value)))]),z=i.enum([`TRACE`,`DEBUG`,`INFO`,`WARNING`,`ERROR`,`OFF`]),B=i.object({auth:i.looseObject({account:P.check(i.minLength(1)),authenticator:H(P),username:H(P),warehouse:H(P),role:H(P),host:H(P.check(i.hostname())),schema:H(P),database:H(P)}),privateKey:i.object({pemKey:H(P.check(i.minLength(1))),keyPass:H(P)}),logLevel:i._default(z,`OFF`),checkConnectionDelayMs:H(i.coerce.number().check(i.int(),i.gte(1))),cacheConnection:i._default(i.enum([`process`,`thread`]),`process`),preCreateConnection:i._default(i.boolean(),!1)}).check(i.refine(e=>!e.preCreateConnection||e.cacheConnection===`process`,{error:`Pre-creating connection is only possible for process level caching`})),V=i.safeExtend(B,{sqlText:P.check(i.minLength(1)),binds:R,fetchAsString:i.array(i.enum([`Boolean`,`Number`,`Date`,`Buffer`,`JSON`]))});function H(e){return i.pipe(i.union([i.undefined(),i.literal(``),e]),i.transform(e=>e===``?void 0:e))}var U=class extends p{async resolveDataIn(){let e=await super.resolveDataIn();return V.parse(e)}};k([b,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],U.prototype,`resolveDataIn`,null);var W;let G=!0;var K=class extends U{static init(e,t){e.once(`process:request`,async({context:e})=>{let n=e,r=await t.data.dataIn.call(n.main);r.preCreateConnection&&(G&&=(n.log.DEBUG?.(`Pre-creating Snowflake connection...`),!1),new E(n).createConnection(n.main,r))})}async runStep(){await N(`8.0.72`);let e=await this.snowflakeService.executeSql();this.exitStep(`next`,e)}get snowflakeService(){return new j(this.thread,this.data)}};k([b,O(`design:type`,Function),O(`design:paramtypes`,[]),O(`design:returntype`,Promise)],K.prototype,`runStep`,null),k([n(),O(`design:type`,typeof(W=j!==void 0&&j)==`function`?W:Object),O(`design:paramtypes`,[])],K.prototype,`snowflakeService`,null),t();const q={};export{q as states,K as step};
|
|
3
|
-
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/errors/step-error.ts","../src/errors/error-filter.ts","../src/utils/create-method-decorator.ts","../src/decorators/error-filter.ts","../src/utils/get-object-hash.ts","../src/utils/get-private-key.ts","../src/services/snowflake/snowflake-logger.ts","../src/services/snowflake/connection-info.ts","../src/services/snowflake/connections-store.ts","../src/services/thread-service-with-data.ts","../src/services/snowflake/snowflake-service.ts","../src/utils/validate-flow-sdk-version.ts","../src/schemas/data-in.ts","../src/threads/base/base.ts","../src/threads/main/step.ts","../src/index.ts"],"sourcesContent":["import BaseError from '@onereach/flow-sdk/errors/base.js';\n\nexport const ErrorCode = {\n UNKNOWN: 'UNKNOWN',\n STEP_LOGIC_ISSUE: 'STEP_LOGIC_ISSUE',\n AUTH: 'AUTH',\n TIMEOUT: 'TIMEOUT',\n VALIDATION: 'VALIDATION',\n INVALID_REQUEST: 'INVALID_REQUEST',\n RATE_LIMITED: 'RATE_LIMITED',\n SERVER_ERROR: 'SERVER_ERROR',\n UNSUPPORTED: 'UNSUPPORTED',\n} as const;\n\nexport class SnowflakeExecuteSqlStepError extends BaseError<{\n code: keyof typeof ErrorCode;\n data?: unknown;\n}> {}\n\nexport class AbortRequestError extends BaseError {}\n","import TimeoutError from '@onereach/flow-sdk/errors/timeout.js';\nimport { z } from 'zod/v4-mini';\n\nimport { SnowflakeExecuteSqlStepError, ErrorCode } from './step-error.ts';\n\nconst defaultPreserveErrors = [SnowflakeExecuteSqlStepError, TimeoutError] as const;\nexport function errorFilter<P extends readonly AnyErrorClass[] = typeof defaultPreserveErrors>(\n error: unknown,\n options: ErrorFilterOptions<P> = {},\n): InstancesOf<P> | SnowflakeExecuteSqlStepError | TimeoutError {\n const {\n preserveErrors = defaultPreserveErrors,\n unknownMessage = 'Unknown error',\n unknownCode = ErrorCode.UNKNOWN,\n } = options;\n\n // if error is SnowflakeExecuteSqlStepError or TimeoutError, return it directly\n if (preserveErrors?.some((ErrorClass) => error instanceof ErrorClass)) {\n return error as InstancesOf<P>;\n }\n\n // validation errors\n if (error instanceof z.core.$ZodError) {\n return new SnowflakeExecuteSqlStepError(z.prettifyError(error), error, {\n code: ErrorCode.VALIDATION,\n });\n }\n\n // if error is a string assume it's an error message\n if (typeof error === 'string') {\n return new SnowflakeExecuteSqlStepError(error, {\n code: ErrorCode.UNKNOWN,\n });\n }\n\n if (error instanceof Error) {\n // timeout errors\n if (error.message.includes('Request timed out')) {\n return new TimeoutError('Timeout', error, { code: ErrorCode.TIMEOUT });\n }\n\n // TODO: fix interpreting of this kind of errors\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n const responseErrorMessage: string | undefined = (error as unknown as any)?.response?.data?.error?.message;\n if (responseErrorMessage != undefined) {\n return new SnowflakeExecuteSqlStepError(responseErrorMessage, error, {\n code: ErrorCode.SERVER_ERROR,\n });\n }\n\n return new SnowflakeExecuteSqlStepError(unknownMessage, error, {\n code: unknownCode,\n });\n }\n\n // catch all for unknown errors\n return new SnowflakeExecuteSqlStepError(unknownMessage, {\n code: unknownCode,\n data: error,\n });\n}\n\nexport type ErrorFilterOptions<P extends readonly AnyErrorClass[]> = {\n /** Array of error classes that should not be wrapped */\n preserveErrors?: P;\n /** Error message to use when message is unknown */\n unknownMessage?: string;\n /** Error code to use when message is unknown */\n unknownCode?: keyof typeof ErrorCode;\n};\n\n/** Any Error class */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyErrorClass<E extends Error = Error> = new (...arguments_: any[]) => E;\n\n/** Turn a tuple/array of constructors into a union of their instance types. */\nexport type InstancesOf<Ctors extends readonly AnyErrorClass[]> =\n Ctors[number] extends AnyErrorClass<infer I> ? I : never;\n","/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Creates a method decorator that can be used with or without options.\n * @param apply - Function that applies the decorator logic with given options.\n * @param defaultOptions - Default options to use if none are provided.\n */\nexport function createMethodDecoratorWithOptionalArguments<A, T extends AnyFunction = AnyFunction>(\n apply: (\n options: A,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => T | TypedPropertyDescriptor<T> | void,\n defaultOptions: A,\n): MethodDecoratorWithOptionalArguments<A, T> {\n function runApply(\n options: A,\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ): TypedPropertyDescriptor<T> | void {\n const maybe = apply(options, target, propertyKey, descriptor);\n\n // If the decorator factory returned a wrapped function, assign it to the descriptor here\n if (typeof maybe === 'function') {\n const originalMethod = descriptor.value;\n const wrappedMethod = maybe as typeof originalMethod;\n\n if (originalMethod?.name != undefined) {\n try {\n Object.defineProperty(wrappedMethod, 'name', { value: originalMethod.name });\n } catch {\n // ignore if name is non-configurable\n }\n }\n\n descriptor.value = wrappedMethod;\n return descriptor;\n }\n\n // If a descriptor was returned or decorator mutated descriptor in-place, use that\n return maybe ?? descriptor;\n }\n\n return function decoratorOrFactory(\n argument0?: object | A,\n argument1?: string | symbol,\n argument2?: TypedPropertyDescriptor<T>,\n ): any {\n if (\n argument0 !== null &&\n typeof argument0 === 'object' &&\n (typeof argument1 === 'string' || typeof argument1 === 'symbol') &&\n argument2 !== null &&\n typeof argument2 === 'object'\n ) {\n // Called as plain decorator: @Decorator\n return runApply(defaultOptions, argument0, argument1, argument2);\n } else {\n // Called as decorator factory: @Decorator(options)\n const options = (argument0 as A) ?? defaultOptions;\n return (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => {\n return runApply(options, target, propertyKey, descriptor);\n };\n }\n };\n}\n\nexport type AnyFunction = (...arguments_: any[]) => any;\n\nexport type MethodDecoratorWithOptionalArguments<A, T extends AnyFunction = AnyFunction> =\n // Plain method decorator (three arguments)\n ((\n target: object,\n propertyKey: string | symbol,\n descriptor: TypedPropertyDescriptor<T>,\n ) => TypedPropertyDescriptor<T> | void) &\n // Decorator factory (optional options argument)\n ((options?: A) => MethodDecorator);\n","import type Step from '@onereach/flow-sdk/step.js';\n\nimport { errorFilter } from '../errors/error-filter.ts';\nimport { createMethodDecoratorWithOptionalArguments } from '../utils/create-method-decorator.ts';\n\nconst defaultOptions = {};\n\n/**\n * Will wrap method with `errorFilter` for every error.\n */\nexport const ErrorFilter = createMethodDecoratorWithOptionalArguments((_options, _target, propertyKey, descriptor) => {\n const originalMethod = descriptor.value;\n\n if (!originalMethod || typeof originalMethod !== 'function') return;\n\n return function (this: Step, ...arguments_: Parameters<typeof originalMethod>): ReturnType<typeof originalMethod> {\n try {\n const result: unknown = originalMethod.apply(this, arguments_);\n\n if (result instanceof Promise) {\n return result.catch((error: unknown) => {\n const methodName = propertyKey.toString();\n this.log.DEBUG?.(`Error in method '${methodName}'`, error);\n throw errorFilter(error);\n }) as ReturnType<typeof originalMethod>;\n }\n\n return result;\n } catch (error) {\n const methodName = propertyKey.toString();\n this.log.DEBUG?.(`Error in method '${methodName}'`, error);\n throw errorFilter(error);\n }\n };\n}, defaultOptions);\n","import crypto from 'node:crypto';\n\nfunction stableStringify<T>(object: T): string {\n const seen = new WeakSet<object>();\n\n const replacer = (_key: string, value: unknown): unknown => {\n if (value && typeof value === 'object') {\n if (seen.has(value)) {\n // Avoid cycles; you can also throw here if you prefer\n return '[Circular]';\n }\n seen.add(value);\n\n if (Array.isArray(value)) return value;\n\n const sorted: Record<string, unknown> = {};\n // eslint-disable-next-line unicorn/no-array-sort\n for (const k of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[k] = (value as Record<string, unknown>)[k];\n }\n return sorted;\n }\n return value;\n };\n\n return JSON.stringify(object, replacer);\n}\n\n/**\n * Get 64 character hash key based on given object\n * @param object object to calculate hash for\n * @returns object hash\n */\nexport function getObjectHash<T = unknown>(object: T): string {\n const json = stableStringify<T>(object);\n return crypto.createHash('sha256').update(json).digest('hex');\n}\n","import { createPrivateKey } from 'node:crypto';\n\n/**\n * Converts PEM encoded private encryption key into pkcs8 format without passphrase\n *\n * If pemKey is `undefined` method will return `undefined`\n * @param pemKey PEM encoded private key\n * @param passphrase Passphrase for private key\n * @returns encoded private key without passkey\n */\nexport function getPrivateKey(pemKey?: string, passphrase?: string): string | undefined {\n if (pemKey == undefined) return undefined;\n\n // Get the private key from the file as an object.\n const privateKeyObject = createPrivateKey({\n key: pemKey.replaceAll(String.raw`\\n`, '\\n').trim(),\n format: 'pem',\n passphrase,\n });\n\n // Extract the private key from the object as a PEM-encoded string.\n return privateKeyObject.export({\n format: 'pem',\n type: 'pkcs8',\n }) as string;\n}\n","import type { ILogger } from '@onereach/flow-sdk/types/index.js';\nimport { format } from 'node:util';\nimport type Logger from 'snowflake-sdk/dist/lib/logger/browser.js';\n\nimport type { LogLevel } from '../../schemas/data-in.ts';\n\nexport type SnowflakeLoggerConfig = {\n logLevel?: LogLevel;\n};\n\nexport class SnowflakeLogger implements Logger {\n private readonly log: ILogger;\n private logLevel: LogLevel;\n\n constructor(logger: ILogger, config: SnowflakeLoggerConfig) {\n this.configure(config);\n this.log = logger;\n this.logLevel = config.logLevel ?? 'ERROR';\n }\n\n public trace(message: string, ...parameters: unknown[]): void {\n if (this.shouldLog('TRACE')) {\n this.log.DEBUG?.(format(message, ...parameters));\n }\n }\n\n public debug(message: string, ...parameters: unknown[]): void {\n if (this.shouldLog('DEBUG')) {\n this.log.DEBUG?.(format(message, ...parameters));\n }\n }\n\n public info(message: string, ...parameters: unknown[]): void {\n if (this.shouldLog('INFO')) {\n this.log.INFO?.(format(message, ...parameters));\n }\n }\n\n public warn(message: string, ...parameters: unknown[]): void {\n if (this.shouldLog('WARNING')) {\n this.log.WARN?.(format(message, ...parameters));\n }\n }\n\n public error(message: string, ...parameters: unknown[]): void {\n if (this.shouldLog('ERROR')) {\n this.log.ERROR?.(format(message, ...parameters));\n }\n }\n\n public getLevelTag(): LogLevel {\n return this.logLevel ?? 'ERROR';\n }\n\n /** Required to implement Logger interface */\n public getLevel(): number {\n return this.getLevelValue(this.getLevelTag());\n }\n\n /** Required to implement Logger interface */\n public getLogBuffer(): string[] {\n return [];\n }\n\n /** Required to implement Logger interface */\n public configure(config: SnowflakeLoggerConfig) {\n if (config.logLevel) {\n this.logLevel = config.logLevel;\n }\n }\n\n /** If returns `true`, log would be created */\n private shouldLog(level: LogLevel): boolean {\n return this.getLevelValue(level) >= this.getLevelValue(this.logLevel);\n }\n\n /** Map Snowflake log levels to numeric values */\n private getLevelValue(level: LogLevel): number {\n const levels = { TRACE: 0, DEBUG: 1, INFO: 2, WARNING: 3, ERROR: 4, OFF: 5 };\n return levels[level] ?? levels.ERROR;\n }\n}\n","import type { ILogger } from '@onereach/flow-sdk/types/index.js';\nimport snowflake from 'snowflake-sdk';\nimport type { Connection } from 'snowflake-sdk';\nimport { setInstance } from 'snowflake-sdk/dist/lib/logger.js';\n\nimport { SnowflakeAuth } from '../../schemas/data-in.ts';\nimport { getPrivateKey } from '../../utils/get-private-key.ts';\n\nimport { SnowflakeLogger } from './snowflake-logger.ts';\n\nexport class ConnectionInfo {\n private readonly connection: Connection;\n private readonly log: ILogger;\n private readonly _checkConnectionDelayMs: number | undefined;\n\n private lastReconnectTime?: number;\n private connectPromise?: Promise<void>;\n\n constructor(connectionData: SnowflakeAuth, logger: ILogger) {\n this.log = logger;\n this.connection = this.initConnection(connectionData);\n this._checkConnectionDelayMs = connectionData.checkConnectionDelayMs;\n }\n\n public async createConnection(logData?: Record<string, unknown>): Promise<Connection> {\n // first connect logic\n if (!this.lastReconnectTime) await this.connect(logData);\n // reconnect handling\n else if (Date.now() - this.lastReconnectTime > this.checkConnectionDelayMs) await this.reconnect(logData);\n\n // parallel connection requests handling\n if (this.connectPromise) await this.connectPromise;\n\n return this.connection;\n }\n\n /**\n * Destroy specific Snowflake connection\n *\n * This method shout NOT use {@link ConnectionInfo.log} and instead use {@link logger} argument\n * because this method runs in a flow level hook that has limited features.\n */\n public async destroyConnection(logger: ILogger, logData?: Record<string, unknown>): Promise<void> {\n return new Promise<void>((resolve) =>\n setImmediate(() => {\n const connectionId = this.connection.getId();\n const extendedLogData = { connectionId, ...logData };\n logger.DEBUG?.('Destroying Snowflake connection...', extendedLogData);\n this.connection.destroy((error) => {\n if (error) {\n logger.WARN?.('Failed to destroy Snowflake connection', { error: error.message, ...extendedLogData });\n return resolve();\n }\n\n logger.DEBUG?.('Successfully destroyed snowflake connection', extendedLogData);\n resolve();\n });\n }),\n );\n }\n\n private initConnection(connectionData: SnowflakeAuth): Connection {\n this.log.DEBUG?.('Initializing Snowflake connection...');\n\n // set Snowflake SDK logger\n setInstance(new SnowflakeLogger(this.log, { logLevel: connectionData.logLevel }));\n\n return snowflake.createConnection({\n clientSessionKeepAlive: true, // Keep connections alive\n clientSessionKeepAliveHeartbeatFrequency: 20, // 20 seconds\n // timeout: 20_000,\n privateKey: getPrivateKey(connectionData.privateKey.pemKey, connectionData.privateKey.keyPass),\n ...connectionData.auth,\n });\n }\n\n /**\n * Runs connect for Snowflake connection\n * After this method it's safe to await {@link connectPromise} to address concurrent connection requests\n *\n * @param logData Additional data for logs\n */\n private async connect(logData?: Record<string, unknown>): Promise<void> {\n this.lastReconnectTime = Date.now();\n this.connectPromise = new Promise<void>((resolve, reject) =>\n setImmediate(() => {\n this.log.DEBUG?.('Connecting to Snowflake...', logData);\n this.connection.connect((error, conn) => {\n if (error) {\n this.log.DEBUG?.('Failed to connect to Snowflake', { error: error.message, ...logData });\n delete this.lastReconnectTime;\n delete this.connectPromise;\n return reject(error);\n }\n\n const durationMs = Date.now() - this.lastReconnectTime!;\n this.log.DEBUG?.('Successfully connected to Snowflake', {\n connectionId: conn.getId(),\n durationMs,\n ...logData,\n });\n delete this.connectPromise;\n resolve();\n });\n }),\n );\n\n return this.connectPromise;\n }\n\n /**\n * Checks if connection is still valid and if it's not then connects\n * After this method it's safe to await {@link connectPromise} to address concurrent connection requests\n *\n * @param logData Additional data for logs\n */\n private async reconnect(logData?: Record<string, unknown>): Promise<void> {\n this.lastReconnectTime = Date.now();\n this.connectPromise = new Promise((resolve, reject) =>\n setImmediate(() => {\n const extendedLogData = { connectionId: this.connection.getId(), ...logData };\n this.log.DEBUG?.('Checking if Snowflake connection is still valid', extendedLogData);\n this.connection\n .isValidAsync()\n .then(async (isConnectionValid) => {\n if (isConnectionValid) {\n this.log.DEBUG?.('Snowflake connection is still valid. Reusing it.', extendedLogData);\n delete this.connectPromise;\n } else {\n await this.connect(logData);\n }\n resolve();\n })\n .catch((error: Error) => {\n this.log.ERROR?.('Failed to reconnect to Snowflake', extendedLogData);\n delete this.connectPromise;\n delete this.lastReconnectTime;\n reject(error);\n });\n }),\n );\n\n return this.connectPromise;\n }\n\n private get checkConnectionDelayMs(): number {\n return this._checkConnectionDelayMs ?? 30_000;\n }\n}\n","import type { CONFIG, IProcess, IThread } from '@onereach/flow-sdk/types/index.js';\nimport type { Connection } from 'snowflake-sdk';\n\nimport type { SnowflakeAuth } from '../../schemas/data-in.ts';\nimport { getObjectHash } from '../../utils/get-object-hash.ts';\n\nimport { ConnectionInfo } from './connection-info.ts';\nimport type { ConnectionsMap, ConnHash, ThreadName, ThreadsConnectionsMap } from './types.ts';\n\nexport class ConnectionsStore<TConfig extends CONFIG> {\n private readonly process: IProcess<TConfig>;\n\n static get processCacheKey() {\n return 'snfl_cnc' as const;\n }\n\n constructor(process: IProcess<TConfig>) {\n this.process = process;\n }\n\n /**\n * Create snowflake connection\n * @param thread thread that plans to use the connection\n * @param connectionData connection details for creating it\n * @returns created or cached connection\n */\n public async createConnection(thread: IThread<TConfig>, connectionData: SnowflakeAuth): Promise<Connection> {\n const store = this.getStore() ?? this.initStore();\n\n // eslint-disable-next-line unicorn/no-null\n const threadKey: ThreadName = connectionData.cacheConnection === 'thread' ? thread.id : null;\n let connectionsMap = store.get(threadKey);\n if (!connectionsMap) {\n connectionsMap = new Map();\n store.set(threadKey, connectionsMap);\n }\n\n const { auth, privateKey } = connectionData;\n const connectionHash: ConnHash = getObjectHash({ auth, privateKey });\n\n let connectionInfo = connectionsMap.get(connectionHash);\n if (!connectionInfo) {\n connectionInfo = new ConnectionInfo(connectionData, thread.log);\n connectionsMap.set(connectionHash, connectionInfo);\n }\n\n return await connectionInfo.createConnection({ connectionHash, threadKey });\n }\n\n /**\n * Destroy all open Snowflake connections\n *\n * This method should NOT use {@link ConnectionsStore.process} and use {@link process} argument instead\n */\n private async destroyAllConnections(process: IProcess<TConfig>): Promise<void> {\n const store = this.getStore(process);\n if (!store) {\n process.log.WARN?.('Missing snowflake connections store');\n return;\n }\n\n const tasks: Promise<void>[] = [];\n\n for (const [threadName, connectionsMap] of store) {\n const threadNamePart = threadName ? `thread '${threadName}'` : 'process';\n process.log.DEBUG?.(`Destroying Snowflake connections for ${threadNamePart}...`);\n\n for (const [connectionHash, connectionInfo] of connectionsMap) {\n const destroyTask = connectionInfo.destroyConnection(process.log, { connectionHash, threadName });\n tasks.push(destroyTask);\n }\n }\n\n await Promise.allSettled(tasks);\n\n if (tasks.length > 0) process.log.DEBUG?.('Finished destroying Snowflake connections');\n }\n\n private getStore(process: IProcess<TConfig> = this.process): ThreadsConnectionsMap | undefined {\n return process.cache[ConnectionsStore.processCacheKey] as ThreadsConnectionsMap | undefined;\n }\n\n private initStore(): ThreadsConnectionsMap {\n let threadsMap = this.process.cache[ConnectionsStore.processCacheKey] as ThreadsConnectionsMap | undefined;\n if (!threadsMap) {\n threadsMap = this.process.cache[ConnectionsStore.processCacheKey] = new Map<ThreadName, ConnectionsMap>();\n\n // add listener for destroying all connections\n this.process.flow.once('process:response', async ({ context }) => {\n const process = context as IProcess<TConfig>;\n await this.destroyAllConnections(process);\n });\n }\n\n return threadsMap;\n }\n}\n","import { BasicThreadService } from '@onereach/flow-sdk/services/basic.js';\nimport type { CONFIG, IN, IThread } from '@onereach/flow-sdk/types/index.js';\n\nexport class ThreadServiceWithData<\n TConfig extends CONFIG,\n TData extends IN<CONFIG> = IN<TConfig>,\n> extends BasicThreadService<TConfig> {\n protected readonly data: TData;\n\n constructor(thread: IThread<TConfig>, data: TData) {\n super(thread);\n this.data = data;\n }\n}\n","import type { CONFIG } from '@onereach/flow-sdk/types/index.js';\nimport type { Connection } from 'snowflake-sdk';\nimport { Memoize } from 'typescript-memoize';\n\nimport type { DataIn } from '../../schemas/data-in.ts';\nimport { ThreadServiceWithData } from '../thread-service-with-data.ts';\n\nimport { ConnectionsStore } from './connections-store.ts';\n\nexport class SnowflakeService<TConfig extends CONFIG> extends ThreadServiceWithData<TConfig, DataIn> {\n public async executeSql<T = unknown>(): Promise<{ rows: T[] | undefined }> {\n const connection = await this.connectionsStore.createConnection(this.thread, this.data);\n return await this._executeSql<T>(connection);\n }\n\n private async _executeSql<T = unknown>(connection: Connection): Promise<{ rows: T[] | undefined }> {\n const { sqlText, binds, fetchAsString } = this.data;\n\n const connectionId = connection.getId();\n this.log.DEBUG?.('Executing Snowflake SQL query...', { connectionId });\n const start = Date.now();\n return await new Promise((resolve, reject) => {\n connection.execute({\n sqlText,\n binds,\n fetchAsString: [...new Set(fetchAsString)],\n complete: (error, _stmt, rows) => {\n const durationMs = Date.now() - start;\n if (error) {\n this.log.DEBUG?.('Failed to execute Snowflake SQL query', {\n error: error.message,\n connectionId,\n durationMs,\n });\n return reject(error);\n }\n\n this.log.DEBUG?.('Successfully execute Snowflake SQL query', { connectionId, durationMs });\n resolve({ rows });\n },\n });\n });\n }\n\n @Memoize()\n private get connectionsStore(): ConnectionsStore<TConfig> {\n return new ConnectionsStore<TConfig>(this.process);\n }\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\n\nimport { ErrorCode, SnowflakeExecuteSqlStepError } from '../errors/step-error.ts';\n\nconst require = createRequire(import.meta.url);\n\nexport async function validateFlowSdkVersion(minVersion: string): Promise<void> {\n if (typeof minVersion !== 'string' || !/^\\d+\\.\\d+\\.\\d+$/.test(minVersion)) {\n throw new SnowflakeExecuteSqlStepError(`Invalid minimum version format: ${minVersion}`, {\n code: ErrorCode.STEP_LOGIC_ISSUE,\n });\n }\n\n const packageJsonPath = require.resolve('@onereach/flow-sdk/package.json');\n if (!packageJsonPath) {\n throw new SnowflakeExecuteSqlStepError(`Could not find package.json for @onereach/flow-sdk`, {\n code: ErrorCode.STEP_LOGIC_ISSUE,\n });\n }\n // Read the package.json file to get the version\n const packageJsonContent = await readFile(packageJsonPath, 'utf8');\n\n const { version } = JSON.parse(packageJsonContent) as { version: string };\n const { groups } = /^(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)/.exec(version) || {};\n\n if (!groups)\n throw new SnowflakeExecuteSqlStepError(`Invalid Flow SDK version format: ${version}`, {\n code: ErrorCode.STEP_LOGIC_ISSUE,\n });\n\n const major = Number.parseInt(groups.major ?? '0', 10);\n const minor = Number.parseInt(groups.minor ?? '0', 10);\n const patch = Number.parseInt(groups.patch ?? '0', 10);\n\n if (\n major == undefined ||\n minor == undefined ||\n patch == undefined ||\n Number.isNaN(major) ||\n Number.isNaN(minor) ||\n Number.isNaN(patch)\n ) {\n throw new SnowflakeExecuteSqlStepError(`Invalid version format: ${version}`, { code: ErrorCode.STEP_LOGIC_ISSUE });\n }\n\n const [minMajor, minMinor, minPatch] = minVersion.split('.').map((x) => Number.parseInt(x, 10));\n\n if (\n minMajor == undefined ||\n minMinor == undefined ||\n minPatch == undefined ||\n Number.isNaN(minMajor) ||\n Number.isNaN(minMinor) ||\n Number.isNaN(minPatch)\n ) {\n throw new SnowflakeExecuteSqlStepError(`Invalid minimum version format: ${minVersion}`, {\n code: ErrorCode.STEP_LOGIC_ISSUE,\n });\n }\n\n if (\n major < minMajor ||\n (major === minMajor && minor < minMinor) ||\n (major === minMajor && minor === minMinor && patch < minPatch)\n ) {\n throw new SnowflakeExecuteSqlStepError(\n `Flow SDK version '${version}' is lower than required minimum version '${minVersion}' for the step`,\n { code: ErrorCode.VALIDATION },\n );\n }\n}\n","import type { Bind, Binds, InsertBinds /* , LogLevel as SnowflakeLogLevel */ } from 'snowflake-sdk';\nimport { en } from 'zod/v4/locales';\nimport { z } from 'zod/v4-mini';\nz.config(en());\n\n// string that prevents 'undefined' and 'null' values\nconst stringNoUndefinedSchema = z.string().check(\n z.trim(),\n z.refine((value) => !['undefined', 'null'].includes(value), {\n error: 'Unexpected undefined or null merge-field value',\n }),\n);\n\nconst bindSchema = z.union([\n z.coerce.number(),\n stringNoUndefinedSchema,\n z.boolean(),\n z.null(),\n]) satisfies z.core.$ZodType<Bind>;\n\nconst insertBindsSchema = z.array(z.array(bindSchema)) satisfies z.core.$ZodType<InsertBinds>;\nconst bindsSchema = z.union([z.array(bindSchema), insertBindsSchema]) satisfies z.core.$ZodType<Binds>;\nconst extendedBindsSchema = z.union([\n bindsSchema,\n\n // binds wrapped in object with \"value\" key from UI\n z.pipe(\n z.array(z.object({ value: bindSchema })),\n z.transform((array) => array.map((o) => o.value)),\n ),\n\n // insert binds wrapped in object with \"value\" key from UI\n z.pipe(\n z.array(z.object({ value: z.array(bindSchema) })),\n z.transform((array) => array.map((o) => o.value)),\n ),\n]);\n\nconst logLevelSchema = z.enum(['TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'OFF']); //satisfies z.core.$ZodType<SnowflakeLogLevel>;\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nconst authSchema = z\n .object({\n auth: z.looseObject({\n account: stringNoUndefinedSchema.check(z.minLength(1)),\n authenticator: optionalStringValue(stringNoUndefinedSchema),\n username: optionalStringValue(stringNoUndefinedSchema),\n\n warehouse: optionalStringValue(stringNoUndefinedSchema),\n role: optionalStringValue(stringNoUndefinedSchema),\n host: optionalStringValue(stringNoUndefinedSchema.check(z.hostname())),\n schema: optionalStringValue(stringNoUndefinedSchema),\n database: optionalStringValue(stringNoUndefinedSchema),\n // TODO: add timeout\n }),\n privateKey: z.object({\n pemKey: optionalStringValue(stringNoUndefinedSchema.check(z.minLength(1))),\n keyPass: optionalStringValue(stringNoUndefinedSchema),\n }),\n logLevel: z._default(logLevelSchema, 'OFF'),\n checkConnectionDelayMs: optionalStringValue(z.coerce.number().check(z.int(), z.gte(1))),\n cacheConnection: z._default(z.enum(['process', 'thread']), 'process'),\n preCreateConnection: z._default(z.boolean(), false),\n })\n .check(\n z.refine((data) => !data.preCreateConnection || data.cacheConnection === 'process', {\n error: 'Pre-creating connection is only possible for process level caching',\n }),\n );\n\nexport type SnowflakeAuth = z.infer<typeof authSchema>;\n\nexport const dataInSchema = z.safeExtend(authSchema, {\n sqlText: stringNoUndefinedSchema.check(z.minLength(1)),\n binds: extendedBindsSchema,\n fetchAsString: z.array(z.enum(['Boolean', 'Number', 'Date', 'Buffer', 'JSON'])),\n});\n\nexport type DataIn = z.infer<typeof dataInSchema>;\n\n/**\n * Convert empty string to undefined before running schema validation\n * @param schema schema to validate against\n * @param defaultValue optional default value\n */\nfunction optionalStringValue<T extends z.core.SomeType>(schema: T) {\n return z.pipe(\n z.union([z.undefined(), z.literal(''), schema]),\n z.transform((value) => (value === '' ? undefined : value)),\n );\n}\n","import Step from '@onereach/flow-sdk/step.js';\n\nimport { ErrorFilter } from '../../decorators/error-filter.ts';\nimport { dataInSchema } from '../../schemas/data-in.ts';\n\nimport type { BaseConfig } from './types.ts';\n\n// TODO: convert it into class decorator\nexport class BaseStep<T extends BaseConfig> extends Step<T> {\n @ErrorFilter\n public async resolveDataIn() {\n const dataIn = await super.resolveDataIn();\n return dataInSchema.parse(dataIn);\n }\n}\n\nexport const baseClassIdPrefix = 'snfl_sql';\n","import type { IFlow, IProcess, IStepInfo } from '@onereach/flow-sdk/types/index.js';\nimport { Memoize } from 'typescript-memoize';\n\nimport { ErrorFilter } from '../../decorators/error-filter.ts';\nimport { ConnectionsStore } from '../../services/snowflake/connections-store.ts';\nimport { SnowflakeService } from '../../services/snowflake/snowflake-service.ts';\nimport { validateFlowSdkVersion } from '../../utils/validate-flow-sdk-version.ts';\nimport { BaseStep } from '../base/base.ts';\n\nimport { SnowflakeExecuteSqlConfig } from './types.ts';\n\nconst MINIMAL_FLOW_SDK_VERSION = '8.0.72';\n\nlet showInitLog = true;\n\nexport class SnowflakeExecuteSqlStep extends BaseStep<SnowflakeExecuteSqlConfig> {\n static init(flow: IFlow<SnowflakeExecuteSqlConfig>, step: IStepInfo<SnowflakeExecuteSqlConfig>) {\n flow.once('process:request', async ({ context }) => {\n const process = context as IProcess<SnowflakeExecuteSqlConfig>;\n const data = await step.data.dataIn.call(process.main);\n\n if (!data.preCreateConnection) return;\n\n if (showInitLog) {\n process.log.DEBUG?.('Pre-creating Snowflake connection...');\n showInitLog = false;\n }\n const store = new ConnectionsStore(process);\n void store.createConnection(process.main, data);\n });\n }\n\n @ErrorFilter\n public async runStep(): Promise<void> {\n await validateFlowSdkVersion(MINIMAL_FLOW_SDK_VERSION);\n\n const result = await this.snowflakeService.executeSql();\n\n this.exitStep('next', result);\n }\n\n @Memoize()\n private get snowflakeService(): SnowflakeService<SnowflakeExecuteSqlConfig> {\n return new SnowflakeService(this.thread, this.data);\n }\n}\n","import { install } from 'source-map-support';\n\n// enable source map support for better error stack traces\ninstall();\n\nexport const states = {}; // for potential future use\nexport { SnowflakeExecuteSqlStep as step } from './threads/main/step.ts';\n\nexport type * from './types.ts';\n"],"mappings":"goBAEA,MAAa,EAAY,CACvB,QAAS,UACT,iBAAkB,mBAClB,KAAM,OACN,QAAS,UACT,WAAY,aACZ,gBAAiB,kBACjB,aAAc,eACd,aAAc,eACd,YAAa,cACd,CAED,IAAa,EAAb,cAAkD,CAG/C,GCZH,MAAM,EAAwB,CAAC,EAA8B,EAAa,CAC1E,SAAgB,EACd,EACA,EAAiC,EAAE,CAC2B,CAC9D,GAAM,CACJ,iBAAiB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