@keystrokehq/snowflake 0.0.16 → 0.0.18

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.
Files changed (82) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +9 -233
  3. package/package.json +39 -171
  4. package/dist/accounts/index.d.mts +0 -40
  5. package/dist/accounts/index.mjs +0 -51
  6. package/dist/bulk/index.d.mts +0 -71
  7. package/dist/bulk/index.mjs +0 -65
  8. package/dist/catalog/index.d.mts +0 -144
  9. package/dist/catalog/index.mjs +0 -158
  10. package/dist/client/index.d.mts +0 -44
  11. package/dist/client/index.mjs +0 -273
  12. package/dist/common-DfpCwJx5.mjs +0 -92
  13. package/dist/credential-sets/index.d.mts +0 -3
  14. package/dist/credential-sets/index.mjs +0 -4
  15. package/dist/databases/index.d.mts +0 -2
  16. package/dist/databases/index.mjs +0 -3
  17. package/dist/errors-60AsF7Su.mjs +0 -95
  18. package/dist/events/index.d.mts +0 -382
  19. package/dist/events/index.mjs +0 -291
  20. package/dist/file-formats/index.d.mts +0 -39
  21. package/dist/file-formats/index.mjs +0 -48
  22. package/dist/functions/index.d.mts +0 -53
  23. package/dist/functions/index.mjs +0 -56
  24. package/dist/grants/index.d.mts +0 -93
  25. package/dist/grants/index.mjs +0 -102
  26. package/dist/index.d.mts +0 -4
  27. package/dist/index.mjs +0 -6
  28. package/dist/operations/index.d.mts +0 -1
  29. package/dist/operations/index.mjs +0 -1
  30. package/dist/org-admin/index.d.mts +0 -80
  31. package/dist/org-admin/index.mjs +0 -79
  32. package/dist/pipes/index.d.mts +0 -119
  33. package/dist/pipes/index.mjs +0 -106
  34. package/dist/procedures/index.d.mts +0 -61
  35. package/dist/procedures/index.mjs +0 -79
  36. package/dist/results/index.d.mts +0 -16
  37. package/dist/results/index.mjs +0 -64
  38. package/dist/retry-B4-9MZIp.mjs +0 -164
  39. package/dist/retry-w7cTp1QL.d.mts +0 -10
  40. package/dist/roles/index.d.mts +0 -60
  41. package/dist/roles/index.mjs +0 -74
  42. package/dist/rows/index.d.mts +0 -106
  43. package/dist/rows/index.mjs +0 -223
  44. package/dist/schemas/index.d.mts +0 -2
  45. package/dist/schemas/index.mjs +0 -4
  46. package/dist/schemas-catalog/index.d.mts +0 -2
  47. package/dist/schemas-catalog/index.mjs +0 -3
  48. package/dist/shares/index.d.mts +0 -56
  49. package/dist/shares/index.mjs +0 -77
  50. package/dist/snowflake-s3-sns-webhook.credential-set-D6bLAWy5.d.mts +0 -50
  51. package/dist/snowflake-s3-sns-webhook.credential-set-DzR7oWNK.mjs +0 -44
  52. package/dist/snowflake.credential-set-BxT7Gf3A.d.mts +0 -114
  53. package/dist/snowflake.credential-set-DE3gXf-a.mjs +0 -106
  54. package/dist/sql/index.d.mts +0 -84
  55. package/dist/sql/index.mjs +0 -209
  56. package/dist/sql-options-2k5xQ-oS.d.mts +0 -32
  57. package/dist/sql-options-D6GEa21F.mjs +0 -79
  58. package/dist/sql-safety-BZpAPsq6.mjs +0 -56
  59. package/dist/stages/index.d.mts +0 -64
  60. package/dist/stages/index.mjs +0 -81
  61. package/dist/statements-BumhMhN4.mjs +0 -81
  62. package/dist/statements-DJL0qVNA.d.mts +0 -238
  63. package/dist/status-page/index.d.mts +0 -510
  64. package/dist/status-page/index.mjs +0 -261
  65. package/dist/streaming/index.d.mts +0 -70
  66. package/dist/streaming/index.mjs +0 -56
  67. package/dist/streams/index.d.mts +0 -71
  68. package/dist/streams/index.mjs +0 -78
  69. package/dist/tables/index.d.mts +0 -2
  70. package/dist/tables/index.mjs +0 -3
  71. package/dist/tasks/index.d.mts +0 -79
  72. package/dist/tasks/index.mjs +0 -104
  73. package/dist/triggers/index.d.mts +0 -381
  74. package/dist/triggers/index.mjs +0 -1100
  75. package/dist/users/index.d.mts +0 -61
  76. package/dist/users/index.mjs +0 -67
  77. package/dist/verification/index.d.mts +0 -201
  78. package/dist/verification/index.mjs +0 -512
  79. package/dist/views/index.d.mts +0 -2
  80. package/dist/views/index.mjs +0 -3
  81. package/dist/warehouses/index.d.mts +0 -68
  82. package/dist/warehouses/index.mjs +0 -101
@@ -1,65 +0,0 @@
1
- import { executeSql } from "../sql/index.mjs";
2
- import { a as quoteLiteral, t as buildFqn } from "../sql-safety-BZpAPsq6.mjs";
3
- import { n as renderOptionGroup, t as formatOptions } from "../sql-options-D6GEa21F.mjs";
4
- import { stagePath } from "../stages/index.mjs";
5
-
6
- //#region src/bulk/index.ts
7
- function tableFqn(ref) {
8
- return buildFqn(ref.database, ref.schema, ref.table);
9
- }
10
- function renderSource(source) {
11
- if (source.kind === "query") return `(${source.sql})`;
12
- if (source.kind === "stage") return `${stagePath(source.stage, source.pathSuffix)}${source.files && source.files.length > 0 ? ` FILES = (${source.files.map(quoteLiteral).join(", ")})` : ""}${source.pattern ? ` PATTERN = ${quoteLiteral(source.pattern)}` : ""}`;
13
- const files = source.files && source.files.length > 0 ? ` FILES = (${source.files.map(quoteLiteral).join(", ")})` : "";
14
- const pattern = source.pattern ? ` PATTERN = ${quoteLiteral(source.pattern)}` : "";
15
- const creds = renderOptionGroup("CREDENTIALS", source.credentials);
16
- const enc = renderOptionGroup("ENCRYPTION", source.encryption);
17
- return `${quoteLiteral(source.url)}${creds}${enc}${files}${pattern}`;
18
- }
19
- function collectCopyOptions(opts) {
20
- const merged = { ...opts.copyOptions ?? {} };
21
- if (opts.onError !== void 0) merged.onError = opts.onError;
22
- if (opts.force !== void 0) merged.force = opts.force;
23
- if (opts.truncateColumns !== void 0) merged.truncateColumns = opts.truncateColumns;
24
- return Object.keys(merged).length > 0 ? merged : void 0;
25
- }
26
- async function copyInto(client, options) {
27
- const columnList = options.columns && options.columns.length > 0 ? `(${options.columns.map((c) => `"${c.replaceAll("\"", "\"\"")}"`).join(", ")})` : "";
28
- const copyOpts = collectCopyOptions(options);
29
- return executeSql(client, {
30
- statement: `COPY INTO ${tableFqn(options)}${columnList ? ` ${columnList}` : ""} FROM ${renderSource(options.source)}` + renderOptionGroup("FILE_FORMAT", options.fileFormat) + (copyOpts ? ` ${formatOptions(copyOpts)}` : "") + (options.validationMode ? ` VALIDATION_MODE = ${options.validationMode}` : ""),
31
- warehouse: options.warehouse,
32
- role: options.role
33
- });
34
- }
35
- async function validateCopyInto(client, options) {
36
- return copyInto(client, {
37
- ...options,
38
- validationMode: options.validationMode ?? "RETURN_ERRORS"
39
- });
40
- }
41
- async function unload(client, options) {
42
- const scope = stagePath(options.stage, options.pathSuffix);
43
- const copyOpts = { ...options.copyOptions ?? {} };
44
- if (options.overwrite !== void 0) copyOpts.overwrite = options.overwrite;
45
- if (options.header !== void 0) copyOpts.header = options.header;
46
- if (options.singleFile !== void 0) copyOpts.singleFile = options.singleFile;
47
- if (options.maxFileSize !== void 0) copyOpts.maxFileSize = options.maxFileSize;
48
- const copyOptions = Object.keys(copyOpts).length > 0 ? copyOpts : void 0;
49
- const partition = options.partitionBy ? ` PARTITION BY (${options.partitionBy})` : "";
50
- return executeSql(client, {
51
- statement: `COPY INTO ${scope} FROM (${options.query})` + renderOptionGroup("FILE_FORMAT", options.fileFormat) + (copyOptions ? ` ${formatOptions(copyOptions)}` : "") + partition,
52
- warehouse: options.warehouse,
53
- role: options.role
54
- });
55
- }
56
- async function truncateTable(client, options) {
57
- await executeSql(client, {
58
- statement: `TRUNCATE TABLE${options.ifExists ? " IF EXISTS" : ""} ${tableFqn(options)}`,
59
- warehouse: options.warehouse,
60
- role: options.role
61
- });
62
- }
63
-
64
- //#endregion
65
- export { copyInto, truncateTable, unload, validateCopyInto };
@@ -1,144 +0,0 @@
1
- import { SnowflakeClient } from "../client/index.mjs";
2
- import { d as HydratedRow } from "../statements-DJL0qVNA.mjs";
3
- //#region src/catalog/index.d.ts
4
- interface ShowOptions {
5
- /** Optional `LIKE '<pattern>'` filter. Escaped via {@link quoteLiteral}. */
6
- readonly like?: string;
7
- /** Cap results. Snowflake supports `LIMIT <n>` on SHOW. */
8
- readonly limit?: number;
9
- /** Runtime overrides forwarded to {@link executeSql}. */
10
- readonly warehouse?: string;
11
- readonly role?: string;
12
- readonly database?: string;
13
- readonly schema?: string;
14
- }
15
- interface ShowScopedOptions extends ShowOptions {
16
- /** Restrict results to the named database. */
17
- readonly inDatabase?: string;
18
- /** Restrict to a `DB.SCHEMA` scope. */
19
- readonly inSchema?: {
20
- readonly database: string;
21
- readonly schema: string;
22
- };
23
- /** Restrict to `SHOW X IN ACCOUNT`. */
24
- readonly inAccount?: boolean;
25
- }
26
- interface CatalogResult {
27
- readonly rows: readonly HydratedRow[];
28
- readonly columns: readonly {
29
- readonly name: string;
30
- readonly type: string;
31
- }[];
32
- }
33
- interface ShowDatabasesOptions extends ShowOptions {}
34
- declare function showDatabases(client: SnowflakeClient, options?: ShowDatabasesOptions): Promise<CatalogResult>;
35
- interface ShowSchemasOptions extends ShowScopedOptions {
36
- /** `HISTORY` variant returns dropped schemas too. */
37
- readonly history?: boolean;
38
- }
39
- declare function showSchemas(client: SnowflakeClient, options?: ShowSchemasOptions): Promise<CatalogResult>;
40
- interface ShowTablesOptions extends ShowScopedOptions {
41
- readonly history?: boolean;
42
- /** Cascading to TEMPORARY + TRANSIENT + EXTERNAL tables. */
43
- readonly terse?: boolean;
44
- }
45
- declare function showTables(client: SnowflakeClient, options?: ShowTablesOptions): Promise<CatalogResult>;
46
- interface ShowViewsOptions extends ShowScopedOptions {
47
- readonly terse?: boolean;
48
- }
49
- declare function showViews(client: SnowflakeClient, options?: ShowViewsOptions): Promise<CatalogResult>;
50
- interface ShowMaterializedViewsOptions extends ShowScopedOptions {}
51
- declare function showMaterializedViews(client: SnowflakeClient, options?: ShowMaterializedViewsOptions): Promise<CatalogResult>;
52
- interface ShowColumnsOptions extends ShowOptions {
53
- readonly inTable?: {
54
- readonly database?: string;
55
- readonly schema?: string;
56
- readonly table: string;
57
- };
58
- readonly inView?: {
59
- readonly database?: string;
60
- readonly schema?: string;
61
- readonly view: string;
62
- };
63
- readonly inSchema?: {
64
- readonly database: string;
65
- readonly schema: string;
66
- };
67
- readonly inDatabase?: string;
68
- }
69
- declare function showColumns(client: SnowflakeClient, options?: ShowColumnsOptions): Promise<CatalogResult>;
70
- declare function showWarehouses(client: SnowflakeClient, options?: ShowOptions): Promise<CatalogResult>;
71
- declare function showRoles(client: SnowflakeClient, options?: ShowOptions): Promise<CatalogResult>;
72
- declare function showUsers(client: SnowflakeClient, options?: ShowOptions): Promise<CatalogResult>;
73
- declare function showStages(client: SnowflakeClient, options?: ShowScopedOptions): Promise<CatalogResult>;
74
- declare function showPipes(client: SnowflakeClient, options?: ShowScopedOptions): Promise<CatalogResult>;
75
- declare function showTasks(client: SnowflakeClient, options?: ShowScopedOptions & {
76
- readonly terse?: boolean;
77
- }): Promise<CatalogResult>;
78
- declare function showStreams(client: SnowflakeClient, options?: ShowScopedOptions): Promise<CatalogResult>;
79
- declare function showShares(client: SnowflakeClient, options?: ShowOptions): Promise<CatalogResult>;
80
- declare function showFunctions(client: SnowflakeClient, options?: ShowScopedOptions): Promise<CatalogResult>;
81
- declare function showProcedures(client: SnowflakeClient, options?: ShowScopedOptions): Promise<CatalogResult>;
82
- declare function showFileFormats(client: SnowflakeClient, options?: ShowScopedOptions): Promise<CatalogResult>;
83
- interface ShowGrantsOptions extends ShowOptions {
84
- /** `SHOW GRANTS ON <object>`. Object keyword is caller-provided (TABLE, DATABASE, etc.). */
85
- readonly on?: {
86
- readonly objectType: string;
87
- readonly name: string;
88
- readonly schema?: string;
89
- readonly database?: string;
90
- };
91
- /** `SHOW GRANTS TO {ROLE | USER | SHARE} <name>`. */
92
- readonly toRole?: string;
93
- readonly toUser?: string;
94
- readonly toShare?: string;
95
- /** `SHOW GRANTS OF ROLE <name>`. */
96
- readonly ofRole?: string;
97
- readonly ofShare?: string;
98
- }
99
- declare function showGrants(client: SnowflakeClient, options?: ShowGrantsOptions): Promise<CatalogResult>;
100
- interface DescribeTableOptions extends Pick<ShowOptions, 'warehouse' | 'role'> {
101
- readonly database?: string;
102
- readonly schema?: string;
103
- readonly table: string;
104
- /** `DESCRIBE TABLE X TYPE = STAGE | COLUMNS` (default COLUMNS). */
105
- readonly type?: 'COLUMNS' | 'STAGE';
106
- }
107
- declare function describeTable(client: SnowflakeClient, options: DescribeTableOptions): Promise<CatalogResult>;
108
- interface ExploreColumnsOptions extends Pick<ShowOptions, 'warehouse' | 'role'> {
109
- readonly database?: string;
110
- readonly schema?: string;
111
- readonly table: string;
112
- /** Restrict to these columns; when empty, all columns are sampled. */
113
- readonly columns?: readonly string[];
114
- /** Distinct-value sample cap per column (default 100). */
115
- readonly limit?: number;
116
- }
117
- interface ExploreColumnsResult {
118
- readonly table: string;
119
- readonly samples: readonly {
120
- readonly column: string;
121
- readonly distinctValues: readonly unknown[];
122
- }[];
123
- }
124
- /**
125
- * Composio `SNOWFLAKE_BASIC_EXPLORE_COLUMNS` parity — pull a small distinct
126
- * sample from each requested column to help LLMs disambiguate column
127
- * semantics.
128
- */
129
- declare function exploreColumns(client: SnowflakeClient, options: ExploreColumnsOptions): Promise<ExploreColumnsResult>;
130
- interface FindDatabasesOptions extends ShowOptions {
131
- /** Optional case-insensitive substring match applied client-side. */
132
- readonly nameContains?: string;
133
- }
134
- declare function findDatabases(client: SnowflakeClient, options?: FindDatabasesOptions): Promise<CatalogResult>;
135
- interface FindSchemasOptions extends ShowSchemasOptions {
136
- readonly nameContains?: string;
137
- }
138
- declare function findSchemas(client: SnowflakeClient, options?: FindSchemasOptions): Promise<CatalogResult>;
139
- interface FindTablesOptions extends ShowTablesOptions {
140
- readonly nameContains?: string;
141
- }
142
- declare function findTables(client: SnowflakeClient, options?: FindTablesOptions): Promise<CatalogResult>;
143
- //#endregion
144
- export { CatalogResult, DescribeTableOptions, ExploreColumnsOptions, ExploreColumnsResult, FindDatabasesOptions, FindSchemasOptions, FindTablesOptions, ShowColumnsOptions, ShowDatabasesOptions, ShowGrantsOptions, ShowMaterializedViewsOptions, ShowOptions, ShowSchemasOptions, ShowScopedOptions, ShowTablesOptions, ShowViewsOptions, describeTable, exploreColumns, findDatabases, findSchemas, findTables, showColumns, showDatabases, showFileFormats, showFunctions, showGrants, showMaterializedViews, showPipes, showProcedures, showRoles, showSchemas, showShares, showStages, showStreams, showTables, showTasks, showUsers, showViews, showWarehouses };
@@ -1,158 +0,0 @@
1
- import { executeSql } from "../sql/index.mjs";
2
- import { i as quoteIdentifier, n as inClause, r as likeClause, t as buildFqn } from "../sql-safety-BZpAPsq6.mjs";
3
-
4
- //#region src/catalog/index.ts
5
- function limitClause(limit) {
6
- return limit && limit > 0 ? ` LIMIT ${Math.floor(limit)}` : "";
7
- }
8
- function toScope(options) {
9
- if (options.inAccount) return " IN ACCOUNT";
10
- if (options.inSchema) return inClause("SCHEMA", buildFqn(options.inSchema.database, options.inSchema.schema));
11
- if (options.inDatabase) return inClause("DATABASE", quoteIdentifier(options.inDatabase));
12
- return "";
13
- }
14
- async function runShow(client, sql, ctx) {
15
- const result = await executeSql(client, {
16
- statement: sql,
17
- warehouse: ctx.warehouse,
18
- role: ctx.role,
19
- database: ctx.database,
20
- schema: ctx.schema
21
- });
22
- return {
23
- rows: result.rows,
24
- columns: result.columns.map((c) => ({
25
- name: c.name,
26
- type: c.type
27
- }))
28
- };
29
- }
30
- async function showDatabases(client, options = {}) {
31
- return runShow(client, `SHOW DATABASES${likeClause(options.like)}${limitClause(options.limit)}`, options);
32
- }
33
- async function showSchemas(client, options = {}) {
34
- return runShow(client, `SHOW${options.history ? " HISTORY" : ""} SCHEMAS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
35
- }
36
- async function showTables(client, options = {}) {
37
- return runShow(client, `SHOW${options.terse ? " TERSE" : ""}${options.history ? " HISTORY" : ""} TABLES${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
38
- }
39
- async function showViews(client, options = {}) {
40
- return runShow(client, `SHOW${options.terse ? " TERSE" : ""} VIEWS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
41
- }
42
- async function showMaterializedViews(client, options = {}) {
43
- return runShow(client, `SHOW MATERIALIZED VIEWS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
44
- }
45
- async function showColumns(client, options = {}) {
46
- let scope = "";
47
- if (options.inTable) scope = ` IN TABLE ${buildFqn(options.inTable.database, options.inTable.schema, options.inTable.table)}`;
48
- else if (options.inView) scope = ` IN VIEW ${buildFqn(options.inView.database, options.inView.schema, options.inView.view)}`;
49
- else if (options.inSchema) scope = ` IN SCHEMA ${buildFqn(options.inSchema.database, options.inSchema.schema)}`;
50
- else if (options.inDatabase) scope = ` IN DATABASE ${quoteIdentifier(options.inDatabase)}`;
51
- return runShow(client, `SHOW COLUMNS${scope}${likeClause(options.like)}${limitClause(options.limit)}`, options);
52
- }
53
- async function showWarehouses(client, options = {}) {
54
- return runShow(client, `SHOW WAREHOUSES${likeClause(options.like)}${limitClause(options.limit)}`, options);
55
- }
56
- async function showRoles(client, options = {}) {
57
- return runShow(client, `SHOW ROLES${likeClause(options.like)}${limitClause(options.limit)}`, options);
58
- }
59
- async function showUsers(client, options = {}) {
60
- return runShow(client, `SHOW USERS${likeClause(options.like)}${limitClause(options.limit)}`, options);
61
- }
62
- async function showStages(client, options = {}) {
63
- return runShow(client, `SHOW STAGES${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
64
- }
65
- async function showPipes(client, options = {}) {
66
- return runShow(client, `SHOW PIPES${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
67
- }
68
- async function showTasks(client, options = {}) {
69
- return runShow(client, `SHOW${options.terse ? " TERSE" : ""} TASKS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
70
- }
71
- async function showStreams(client, options = {}) {
72
- return runShow(client, `SHOW STREAMS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
73
- }
74
- async function showShares(client, options = {}) {
75
- return runShow(client, `SHOW SHARES${likeClause(options.like)}${limitClause(options.limit)}`, options);
76
- }
77
- async function showFunctions(client, options = {}) {
78
- return runShow(client, `SHOW FUNCTIONS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
79
- }
80
- async function showProcedures(client, options = {}) {
81
- return runShow(client, `SHOW PROCEDURES${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
82
- }
83
- async function showFileFormats(client, options = {}) {
84
- return runShow(client, `SHOW FILE FORMATS${toScope(options)}${likeClause(options.like)}${limitClause(options.limit)}`, options);
85
- }
86
- async function showGrants(client, options = {}) {
87
- let tail = "";
88
- if (options.on) {
89
- const fqn = buildFqn(options.on.database, options.on.schema, options.on.name);
90
- tail = ` ON ${options.on.objectType.toUpperCase()} ${fqn}`;
91
- } else if (options.toRole) tail = ` TO ROLE ${quoteIdentifier(options.toRole)}`;
92
- else if (options.toUser) tail = ` TO USER ${quoteIdentifier(options.toUser)}`;
93
- else if (options.toShare) tail = ` TO SHARE ${quoteIdentifier(options.toShare)}`;
94
- else if (options.ofRole) tail = ` OF ROLE ${quoteIdentifier(options.ofRole)}`;
95
- else if (options.ofShare) tail = ` OF SHARE ${quoteIdentifier(options.ofShare)}`;
96
- return runShow(client, `SHOW GRANTS${tail}${likeClause(options.like)}`, options);
97
- }
98
- async function describeTable(client, options) {
99
- return runShow(client, `DESCRIBE TABLE ${buildFqn(options.database, options.schema, options.table)}${options.type ? ` TYPE = ${options.type}` : ""}`, options);
100
- }
101
- /**
102
- * Composio `SNOWFLAKE_BASIC_EXPLORE_COLUMNS` parity — pull a small distinct
103
- * sample from each requested column to help LLMs disambiguate column
104
- * semantics.
105
- */
106
- async function exploreColumns(client, options) {
107
- const fqn = buildFqn(options.database, options.schema, options.table);
108
- const columns = options.columns && options.columns.length > 0 ? options.columns : (await describeTable(client, options)).rows.map((row) => row.name ?? row.NAME).filter((name) => Boolean(name));
109
- const limit = options.limit ?? 100;
110
- const samples = [];
111
- for (const column of columns) {
112
- const distinctValues = (await executeSql(client, {
113
- statement: `SELECT DISTINCT ${quoteIdentifier(column)} AS v FROM ${fqn} LIMIT ${Math.max(1, Math.floor(limit))}`,
114
- warehouse: options.warehouse,
115
- role: options.role
116
- })).rows.map((row) => row.V ?? row.v);
117
- samples.push({
118
- column,
119
- distinctValues
120
- });
121
- }
122
- return {
123
- table: fqn,
124
- samples
125
- };
126
- }
127
- function applyNameFilter(rows, substring) {
128
- if (!substring) return [...rows];
129
- const needle = substring.toLowerCase();
130
- return rows.filter((row) => {
131
- const name = row.name ?? row.NAME;
132
- return typeof name === "string" && name.toLowerCase().includes(needle);
133
- });
134
- }
135
- async function findDatabases(client, options = {}) {
136
- const result = await showDatabases(client, options);
137
- return {
138
- columns: result.columns,
139
- rows: applyNameFilter(result.rows, options.nameContains)
140
- };
141
- }
142
- async function findSchemas(client, options = {}) {
143
- const result = await showSchemas(client, options);
144
- return {
145
- columns: result.columns,
146
- rows: applyNameFilter(result.rows, options.nameContains)
147
- };
148
- }
149
- async function findTables(client, options = {}) {
150
- const result = await showTables(client, options);
151
- return {
152
- columns: result.columns,
153
- rows: applyNameFilter(result.rows, options.nameContains)
154
- };
155
- }
156
-
157
- //#endregion
158
- export { describeTable, exploreColumns, findDatabases, findSchemas, findTables, showColumns, showDatabases, showFileFormats, showFunctions, showGrants, showMaterializedViews, showPipes, showProcedures, showRoles, showSchemas, showShares, showStages, showStreams, showTables, showTasks, showUsers, showViews, showWarehouses };
@@ -1,44 +0,0 @@
1
- import { n as SnowflakeCredentials } from "../snowflake.credential-set-BxT7Gf3A.mjs";
2
- import { t as RetryPolicy } from "../retry-w7cTp1QL.mjs";
3
-
4
- //#region src/client/index.d.ts
5
- type SnowflakeAuthTokenType = 'KEYPAIR_JWT' | 'OAUTH' | 'PROGRAMMATIC_ACCESS_TOKEN' | 'BASIC';
6
- type SnowflakeHttpMethod = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
7
- type QueryPrimitive = string | number | boolean;
8
- type SnowflakeQueryValue = QueryPrimitive | readonly QueryPrimitive[] | null | undefined;
9
- interface SnowflakeQuery {
10
- readonly [key: string]: SnowflakeQueryValue;
11
- }
12
- interface SnowflakeRequestInit {
13
- readonly method?: SnowflakeHttpMethod;
14
- readonly body?: unknown;
15
- readonly query?: SnowflakeQuery;
16
- readonly headers?: Readonly<Record<string, string>>;
17
- readonly timeoutMs?: number;
18
- readonly requestId?: string;
19
- /** Raw body; when true the response object is returned verbatim. */
20
- readonly raw?: boolean;
21
- /** Disable retries for this call (statement cancel, etc.). */
22
- readonly retry?: boolean | RetryPolicy;
23
- }
24
- interface SnowflakeClientOptions {
25
- readonly fetchImpl?: typeof fetch;
26
- readonly timeoutMs?: number;
27
- readonly retry?: RetryPolicy;
28
- readonly sleep?: (ms: number) => Promise<void>;
29
- readonly now?: () => number;
30
- readonly userAgent?: string;
31
- readonly randomUUID?: () => string;
32
- }
33
- interface SnowflakeClient {
34
- readonly host: string;
35
- readonly account: string;
36
- readonly credentials: SnowflakeCredentials;
37
- request<T = unknown>(path: string, init?: SnowflakeRequestInit): Promise<T>;
38
- requestRaw(path: string, init?: SnowflakeRequestInit): Promise<Response>;
39
- buildUrl(path: string, query?: SnowflakeQuery): string;
40
- }
41
- declare function createSnowflakeClient(rawCredentials: SnowflakeCredentials | unknown, options?: SnowflakeClientOptions): SnowflakeClient;
42
- declare function resolveHost(credentials: SnowflakeCredentials): string;
43
- //#endregion
44
- export { SnowflakeAuthTokenType, SnowflakeClient, SnowflakeClientOptions, SnowflakeHttpMethod, SnowflakeQuery, SnowflakeQueryValue, SnowflakeRequestInit, createSnowflakeClient, resolveHost };
@@ -1,273 +0,0 @@
1
- import { t as parseSnowflakeCredentials } from "../snowflake.credential-set-DE3gXf-a.mjs";
2
- import { a as extractSnowflakeMessage, c as parseRetryAfterHeader, i as extractSnowflakeCode, n as SnowflakeSqlError, o as extractSnowflakeSqlState, r as classifySnowflakeHttpStatus, s as extractSnowflakeStatementHandle, t as SnowflakeApiError } from "../errors-60AsF7Su.mjs";
3
- import { a as createSnowflakeJwt, i as shouldRetry, n as computeBackoffMs, r as defaultSleep, t as DEFAULT_RETRY_POLICY } from "../retry-B4-9MZIp.mjs";
4
-
5
- //#region src/client/index.ts
6
- /**
7
- * Core HTTP client for the Snowflake integration.
8
- *
9
- * Shape — kept intentionally generic so the same client backs every domain
10
- * module (SQL API v2, Snowpipe REST, org-admin REST). Higher-level helpers
11
- * (`sql.ts`, `pipes.ts`, ...) consume `SnowflakeClient.request` and layer
12
- * their own schemas on top.
13
- *
14
- * Responsibilities:
15
- * - resolve credentials -> `Authorization` header + auth-token-type header
16
- * - sign JWTs for `mode=keypair` and cache them until expiry
17
- * - apply default retry policy with exponential backoff + `Retry-After`
18
- * - classify non-2xx responses into structured errors (see `errors.ts`)
19
- * - attach a deterministic `requestId` for idempotent statement submission
20
- */
21
- const DEFAULT_TIMEOUT_MS = 3e4;
22
- const JWT_REFRESH_SKEW_SECONDS = 60;
23
- const USER_AGENT = "keystroke-snowflake/0.0.0";
24
- function createSnowflakeClient(rawCredentials, options = {}) {
25
- const credentials = isSnowflakeCredentials(rawCredentials) ? rawCredentials : parseSnowflakeCredentials(rawCredentials);
26
- const fetchImpl = options.fetchImpl ?? fetch;
27
- const sleep = options.sleep ?? defaultSleep;
28
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
29
- const retryPolicy = options.retry ?? DEFAULT_RETRY_POLICY;
30
- const now = options.now ?? (() => Date.now());
31
- const userAgent = options.userAgent ?? USER_AGENT;
32
- const randomUUID = options.randomUUID ?? (() => typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : pseudoRandomUuid());
33
- const host = resolveHost(credentials);
34
- const account = credentials.SNOWFLAKE_ACCOUNT.trim();
35
- let cachedJwt;
36
- async function authorization() {
37
- if (credentials.mode === "keypair") {
38
- const nowMs = now();
39
- if (!cachedJwt || cachedJwt.expiresAtMs - JWT_REFRESH_SKEW_SECONDS * 1e3 <= nowMs) {
40
- if (!credentials.SNOWFLAKE_USER || !credentials.SNOWFLAKE_PRIVATE_KEY) throw new SnowflakeApiError({
41
- kind: "auth",
42
- status: 0,
43
- message: "SNOWFLAKE_USER and SNOWFLAKE_PRIVATE_KEY are required for keypair mode"
44
- });
45
- const jwt = await createSnowflakeJwt({
46
- account,
47
- user: credentials.SNOWFLAKE_USER,
48
- privateKeyPem: credentials.SNOWFLAKE_PRIVATE_KEY,
49
- publicKeyFingerprint: credentials.SNOWFLAKE_PUBLIC_KEY_FP,
50
- now: () => nowMs
51
- });
52
- cachedJwt = {
53
- token: jwt.token,
54
- expiresAtMs: jwt.expiresAt * 1e3
55
- };
56
- }
57
- return {
58
- header: `Bearer ${cachedJwt.token}`,
59
- tokenType: "KEYPAIR_JWT"
60
- };
61
- }
62
- if (credentials.mode === "oauth") {
63
- if (!credentials.SNOWFLAKE_OAUTH_ACCESS_TOKEN) throw new SnowflakeApiError({
64
- kind: "auth",
65
- status: 0,
66
- message: "SNOWFLAKE_OAUTH_ACCESS_TOKEN is required for oauth mode"
67
- });
68
- return {
69
- header: `Bearer ${credentials.SNOWFLAKE_OAUTH_ACCESS_TOKEN}`,
70
- tokenType: "OAUTH"
71
- };
72
- }
73
- if (credentials.mode === "pat") {
74
- if (!credentials.SNOWFLAKE_PAT) throw new SnowflakeApiError({
75
- kind: "auth",
76
- status: 0,
77
- message: "SNOWFLAKE_PAT is required for pat mode"
78
- });
79
- return {
80
- header: `Bearer ${credentials.SNOWFLAKE_PAT}`,
81
- tokenType: "PROGRAMMATIC_ACCESS_TOKEN"
82
- };
83
- }
84
- if (!credentials.SNOWFLAKE_USER || !credentials.SNOWFLAKE_PASSWORD) throw new SnowflakeApiError({
85
- kind: "auth",
86
- status: 0,
87
- message: "SNOWFLAKE_USER and SNOWFLAKE_PASSWORD are required for basic mode"
88
- });
89
- return {
90
- header: `Basic ${base64EncodeString(`${credentials.SNOWFLAKE_USER}:${credentials.SNOWFLAKE_PASSWORD}`)}`,
91
- tokenType: "BASIC"
92
- };
93
- }
94
- function buildUrl(path, query) {
95
- return `${path.startsWith("http://") || path.startsWith("https://") ? path : `https://${host}${path.startsWith("/") ? path : `/${path}`}`}${toQueryString(query)}`;
96
- }
97
- async function requestRaw(path, init = {}) {
98
- const method = init.method ?? "GET";
99
- const policy = resolveRetryPolicy(init.retry, retryPolicy);
100
- const attemptTimeoutMs = init.timeoutMs ?? timeoutMs;
101
- const requestId = init.requestId ?? randomUUID();
102
- const url = buildUrl(path, {
103
- ...init.query ?? {},
104
- ...method === "POST" && path.includes("/api/v2/statements") ? { requestId } : {}
105
- });
106
- let body;
107
- const headers = {
108
- Accept: "application/json",
109
- "User-Agent": userAgent,
110
- ...init.headers
111
- };
112
- if (init.body !== void 0) {
113
- headers["Content-Type"] = "application/json";
114
- body = JSON.stringify(init.body);
115
- }
116
- let attempt = 0;
117
- for (;;) {
118
- const auth = await authorization();
119
- headers.Authorization = auth.header;
120
- headers["X-Snowflake-Authorization-Token-Type"] = auth.tokenType;
121
- const controller = new AbortController();
122
- const timer = setTimeout(() => controller.abort(), attemptTimeoutMs);
123
- let response;
124
- try {
125
- response = await fetchImpl(url, {
126
- method,
127
- headers,
128
- ...body !== void 0 ? { body } : {},
129
- signal: controller.signal
130
- });
131
- } catch (error) {
132
- clearTimeout(timer);
133
- const isAbort = error instanceof Error && (error.name === "AbortError" || /aborted|abort/iu.test(error.message));
134
- const kind = isAbort ? "timeout" : "network";
135
- if (policy && shouldRetry(kind, attempt, policy)) {
136
- attempt += 1;
137
- await sleep(computeBackoffMs({
138
- attempt,
139
- policy
140
- }));
141
- continue;
142
- }
143
- throw new SnowflakeApiError({
144
- kind,
145
- status: 0,
146
- message: isAbort ? `Request to \`${path}\` timed out after ${attemptTimeoutMs}ms` : `Request to \`${path}\` failed: ${error?.message ?? String(error)}`,
147
- requestId,
148
- cause: error
149
- });
150
- }
151
- clearTimeout(timer);
152
- if (response.ok || response.status === 202) return response;
153
- const parsed = await readResponseBody(response);
154
- const retryAfterMs = parseRetryAfterHeader(response.headers.get("retry-after"));
155
- const kind = classifySnowflakeHttpStatus(response.status);
156
- if (policy && shouldRetry(kind, attempt, policy)) {
157
- attempt += 1;
158
- await sleep(computeBackoffMs({
159
- attempt,
160
- retryAfterMs,
161
- policy
162
- }));
163
- continue;
164
- }
165
- throw toStructuredError({
166
- response,
167
- body: parsed,
168
- requestId,
169
- retryAfterMs
170
- });
171
- }
172
- }
173
- async function request(path, init = {}) {
174
- const response = await requestRaw(path, init);
175
- if (init.raw) return response;
176
- if (response.status === 204) return void 0;
177
- return await readResponseBody(response);
178
- }
179
- return {
180
- host,
181
- account,
182
- credentials,
183
- request,
184
- requestRaw,
185
- buildUrl
186
- };
187
- }
188
- function resolveRetryPolicy(override, fallback) {
189
- if (override === false) return void 0;
190
- if (override === true || override === void 0) return fallback;
191
- return override;
192
- }
193
- async function readResponseBody(response) {
194
- if ((response.headers.get("content-type") ?? "").includes("application/json")) return response.json().catch(() => void 0);
195
- return response.text().catch(() => void 0);
196
- }
197
- function toStructuredError(args) {
198
- const { response, body, requestId, retryAfterMs } = args;
199
- const kind = classifySnowflakeHttpStatus(response.status);
200
- const message = extractSnowflakeMessage(body) ?? `Snowflake HTTP ${response.status} (${response.statusText})`;
201
- const providerCode = extractSnowflakeCode(body);
202
- const snowflakeRequestId = response.headers.get("x-snowflake-request-id") ?? void 0;
203
- if (response.status === 422) return new SnowflakeSqlError({
204
- kind: "sql",
205
- status: response.status,
206
- message,
207
- body,
208
- providerCode,
209
- requestId: snowflakeRequestId ?? requestId,
210
- retryAfterMs,
211
- sqlState: extractSnowflakeSqlState(body),
212
- code: providerCode,
213
- statementHandle: extractSnowflakeStatementHandle(body)
214
- });
215
- return new SnowflakeApiError({
216
- kind,
217
- status: response.status,
218
- message,
219
- body,
220
- providerCode,
221
- requestId: snowflakeRequestId ?? requestId,
222
- retryAfterMs
223
- });
224
- }
225
- function resolveHost(credentials) {
226
- if (credentials.SNOWFLAKE_HOST) return stripProtocol(credentials.SNOWFLAKE_HOST).replace(/\/+$/u, "");
227
- const account = credentials.SNOWFLAKE_ACCOUNT.trim();
228
- const region = credentials.SNOWFLAKE_REGION?.trim();
229
- if (region && !account.includes(".") && !account.includes("-")) return `${account}.${region}.snowflakecomputing.com`;
230
- if (/snowflakecomputing\.com$/u.test(account)) return account;
231
- return `${account}.snowflakecomputing.com`;
232
- }
233
- function stripProtocol(host) {
234
- return host.replace(/^https?:\/\//u, "");
235
- }
236
- function toQueryString(query) {
237
- if (!query) return "";
238
- const params = new URLSearchParams();
239
- for (const [key, value] of Object.entries(query)) {
240
- if (value === void 0 || value === null) continue;
241
- if (Array.isArray(value)) {
242
- for (const item of value) params.append(key, String(item));
243
- continue;
244
- }
245
- params.set(key, String(value));
246
- }
247
- const qs = params.toString();
248
- return qs.length > 0 ? `?${qs}` : "";
249
- }
250
- function isSnowflakeCredentials(value) {
251
- if (typeof value !== "object" || value === null) return false;
252
- const mode = value.mode;
253
- return mode === "keypair" || mode === "oauth" || mode === "pat" || mode === "basic";
254
- }
255
- function base64EncodeString(input) {
256
- if (typeof btoa === "function") return btoa(unescape(encodeURIComponent(input)));
257
- /* c8 ignore next */
258
- return Buffer.from(input, "utf8").toString("base64");
259
- }
260
- function pseudoRandomUuid() {
261
- /* c8 ignore start */
262
- const bytes = new Uint8Array(16);
263
- for (let i = 0; i < 16; i += 1) bytes[i] = Math.floor(Math.random() * 256);
264
- bytes[6] = (bytes[6] ?? 0) & 15 | 64;
265
- bytes[8] = (bytes[8] ?? 0) & 63 | 128;
266
- const hex = [];
267
- for (const b of bytes) hex.push(b.toString(16).padStart(2, "0"));
268
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
269
- /* c8 ignore end */
270
- }
271
-
272
- //#endregion
273
- export { createSnowflakeClient, resolveHost };