@514labs/moose-lib 0.6.348 → 0.6.349

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.
@@ -30,337 +30,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  ));
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
- // src/dmv2/utils/stackTrace.ts
34
- function shouldSkipStackLine(line) {
35
- return line.includes("node_modules") || // Skip npm installed packages (prod)
36
- line.includes("node:internal") || // Skip Node.js internals (modern format)
37
- line.includes("internal/modules") || // Skip Node.js internals (older format)
38
- line.includes("ts-node") || // Skip TypeScript execution
39
- line.includes("/ts-moose-lib/src/") || // Skip dev/linked moose-lib src (Unix)
40
- line.includes("\\ts-moose-lib\\src\\") || // Skip dev/linked moose-lib src (Windows)
41
- line.includes("/ts-moose-lib/dist/") || // Skip dev/linked moose-lib dist (Unix)
42
- line.includes("\\ts-moose-lib\\dist\\");
43
- }
44
- function parseStackLine(line) {
45
- const match = line.match(/\((.*):(\d+):(\d+)\)/) || line.match(/at (.*):(\d+):(\d+)/);
46
- if (match && match[1]) {
47
- return {
48
- file: match[1],
49
- line: match[2]
50
- };
51
- }
52
- return void 0;
53
- }
54
- function getSourceFileInfo(stack) {
55
- if (!stack) return {};
56
- const lines = stack.split("\n");
57
- for (const line of lines) {
58
- if (shouldSkipStackLine(line)) continue;
59
- const info = parseStackLine(line);
60
- if (info) return info;
61
- }
62
- return {};
63
- }
64
- function getSourceLocationFromStack(stack) {
65
- if (!stack) return void 0;
66
- const lines = stack.split("\n");
67
- for (const line of lines.slice(1)) {
68
- if (shouldSkipStackLine(line)) {
69
- continue;
70
- }
71
- const v8Match = line.match(/at\s+(?:.*?\s+\()?(.+):(\d+):(\d+)\)?/);
72
- if (v8Match) {
73
- return {
74
- file: v8Match[1],
75
- line: parseInt(v8Match[2], 10),
76
- column: parseInt(v8Match[3], 10)
77
- };
78
- }
79
- const smMatch = line.match(/(?:.*@)?(.+):(\d+):(\d+)/);
80
- if (smMatch) {
81
- return {
82
- file: smMatch[1],
83
- line: parseInt(smMatch[2], 10),
84
- column: parseInt(smMatch[3], 10)
85
- };
86
- }
87
- }
88
- return void 0;
89
- }
90
- function getSourceFileFromStack(stack) {
91
- const location = getSourceLocationFromStack(stack);
92
- return location?.file;
93
- }
94
- var init_stackTrace = __esm({
95
- "src/dmv2/utils/stackTrace.ts"() {
96
- "use strict";
97
- }
98
- });
99
-
100
- // src/dmv2/typedBase.ts
101
- var TypedBase;
102
- var init_typedBase = __esm({
103
- "src/dmv2/typedBase.ts"() {
104
- "use strict";
105
- init_stackTrace();
106
- TypedBase = class {
107
- /** The JSON schema representation of type T. Injected by the compiler plugin. */
108
- schema;
109
- /** The name assigned to this resource instance. */
110
- name;
111
- /** A dictionary mapping column names (keys of T) to their Column definitions. */
112
- columns;
113
- /** An array containing the Column definitions for this resource. Injected by the compiler plugin. */
114
- columnArray;
115
- /** The configuration object specific to this resource type. */
116
- config;
117
- /** Typia validation functions for type T. Injected by the compiler plugin for OlapTable. */
118
- validators;
119
- /** Optional metadata for the resource, always present as an object. */
120
- metadata;
121
- /**
122
- * Whether this resource allows extra fields beyond the defined columns.
123
- * When true, extra fields in payloads are passed through to streaming functions.
124
- * Injected by the compiler plugin when the type has an index signature.
125
- */
126
- allowExtraFields;
127
- /**
128
- * @internal Constructor intended for internal use by subclasses and the compiler plugin.
129
- * It expects the schema and columns to be provided, typically injected by the compiler.
130
- *
131
- * @param name The name for the resource instance.
132
- * @param config The configuration object for the resource.
133
- * @param schema The JSON schema for the resource's data type T (injected).
134
- * @param columns The array of Column definitions for T (injected).
135
- * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
136
- */
137
- constructor(name, config, schema, columns, validators, allowExtraFields) {
138
- if (schema === void 0 || columns === void 0) {
139
- throw new Error(
140
- "Supply the type param T so that the schema is inserted by the compiler plugin."
141
- );
142
- }
143
- this.schema = schema;
144
- this.columnArray = columns;
145
- const columnsObj = {};
146
- columns.forEach((column) => {
147
- columnsObj[column.name] = column;
148
- });
149
- this.columns = columnsObj;
150
- this.name = name;
151
- this.config = config;
152
- this.validators = validators;
153
- this.allowExtraFields = allowExtraFields ?? false;
154
- this.metadata = config?.metadata ? { ...config.metadata } : {};
155
- if (!this.metadata.source) {
156
- const stack = new Error().stack;
157
- if (stack) {
158
- const info = getSourceFileInfo(stack);
159
- this.metadata.source = { file: info.file, line: info.line };
160
- }
161
- }
162
- }
163
- };
164
- }
165
- });
166
-
167
- // src/dataModels/dataModelTypes.ts
168
- function isArrayNestedType(dt) {
169
- return typeof dt === "object" && dt !== null && dt.elementType !== null && typeof dt.elementType === "object" && dt.elementType.hasOwnProperty("columns") && Array.isArray(dt.elementType.columns);
170
- }
171
- function isNestedType(dt) {
172
- return typeof dt === "object" && dt !== null && Array.isArray(dt.columns);
173
- }
174
- var init_dataModelTypes = __esm({
175
- "src/dataModels/dataModelTypes.ts"() {
176
- "use strict";
177
- }
178
- });
179
-
180
- // src/dataModels/types.ts
181
- var ClickHouseEngines;
182
- var init_types = __esm({
183
- "src/dataModels/types.ts"() {
184
- "use strict";
185
- ClickHouseEngines = /* @__PURE__ */ ((ClickHouseEngines2) => {
186
- ClickHouseEngines2["MergeTree"] = "MergeTree";
187
- ClickHouseEngines2["ReplacingMergeTree"] = "ReplacingMergeTree";
188
- ClickHouseEngines2["SummingMergeTree"] = "SummingMergeTree";
189
- ClickHouseEngines2["AggregatingMergeTree"] = "AggregatingMergeTree";
190
- ClickHouseEngines2["CollapsingMergeTree"] = "CollapsingMergeTree";
191
- ClickHouseEngines2["VersionedCollapsingMergeTree"] = "VersionedCollapsingMergeTree";
192
- ClickHouseEngines2["GraphiteMergeTree"] = "GraphiteMergeTree";
193
- ClickHouseEngines2["S3Queue"] = "S3Queue";
194
- ClickHouseEngines2["S3"] = "S3";
195
- ClickHouseEngines2["Buffer"] = "Buffer";
196
- ClickHouseEngines2["Distributed"] = "Distributed";
197
- ClickHouseEngines2["IcebergS3"] = "IcebergS3";
198
- ClickHouseEngines2["Kafka"] = "Kafka";
199
- ClickHouseEngines2["ReplicatedMergeTree"] = "ReplicatedMergeTree";
200
- ClickHouseEngines2["ReplicatedReplacingMergeTree"] = "ReplicatedReplacingMergeTree";
201
- ClickHouseEngines2["ReplicatedAggregatingMergeTree"] = "ReplicatedAggregatingMergeTree";
202
- ClickHouseEngines2["ReplicatedSummingMergeTree"] = "ReplicatedSummingMergeTree";
203
- ClickHouseEngines2["ReplicatedCollapsingMergeTree"] = "ReplicatedCollapsingMergeTree";
204
- ClickHouseEngines2["ReplicatedVersionedCollapsingMergeTree"] = "ReplicatedVersionedCollapsingMergeTree";
205
- return ClickHouseEngines2;
206
- })(ClickHouseEngines || {});
207
- }
208
- });
209
-
210
- // src/sqlHelpers.ts
211
- function sqlImpl(strings, ...values) {
212
- return new Sql(strings, values);
213
- }
214
- function createClickhouseParameter(parameterIndex, value) {
215
- return `{p${parameterIndex}:${mapToClickHouseType(value)}}`;
216
- }
217
- function emptyIfUndefined(value) {
218
- return value === void 0 ? "" : value;
219
- }
220
- var quoteIdentifier, isTable, isView, isColumn, sql, instanceofSql, Sql, toStaticQuery, toQuery, getValueFromParameter, mapToClickHouseType;
221
- var init_sqlHelpers = __esm({
222
- "src/sqlHelpers.ts"() {
223
- "use strict";
224
- quoteIdentifier = (name) => {
225
- return name.startsWith("`") && name.endsWith("`") ? name : `\`${name}\``;
226
- };
227
- isTable = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "OlapTable";
228
- isView = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "View";
229
- isColumn = (value) => typeof value === "object" && value !== null && !("kind" in value) && "name" in value && "annotations" in value;
230
- sql = sqlImpl;
231
- instanceofSql = (value) => typeof value === "object" && "values" in value && "strings" in value;
232
- Sql = class _Sql {
233
- values;
234
- strings;
235
- constructor(rawStrings, rawValues) {
236
- if (rawStrings.length - 1 !== rawValues.length) {
237
- if (rawStrings.length === 0) {
238
- throw new TypeError("Expected at least 1 string");
239
- }
240
- throw new TypeError(
241
- `Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`
242
- );
243
- }
244
- const valuesLength = rawValues.reduce(
245
- (len, value) => len + (instanceofSql(value) ? value.values.length : isColumn(value) || isTable(value) || isView(value) ? 0 : 1),
246
- 0
247
- );
248
- this.values = new Array(valuesLength);
249
- this.strings = new Array(valuesLength + 1);
250
- this.strings[0] = rawStrings[0];
251
- let i = 0, pos = 0;
252
- while (i < rawValues.length) {
253
- const child = rawValues[i++];
254
- const rawString = rawStrings[i];
255
- if (instanceofSql(child)) {
256
- this.strings[pos] += child.strings[0];
257
- let childIndex = 0;
258
- while (childIndex < child.values.length) {
259
- this.values[pos++] = child.values[childIndex++];
260
- this.strings[pos] = child.strings[childIndex];
261
- }
262
- this.strings[pos] += rawString;
263
- } else if (isColumn(child)) {
264
- const aggregationFunction = child.annotations.find(
265
- ([k, _]) => k === "aggregationFunction"
266
- );
267
- if (aggregationFunction !== void 0) {
268
- this.strings[pos] += `${aggregationFunction[1].functionName}Merge(\`${child.name}\`)`;
269
- } else {
270
- this.strings[pos] += `\`${child.name}\``;
271
- }
272
- this.strings[pos] += rawString;
273
- } else if (isTable(child)) {
274
- if (child.config.database) {
275
- this.strings[pos] += `\`${child.config.database}\`.\`${child.name}\``;
276
- } else {
277
- this.strings[pos] += `\`${child.name}\``;
278
- }
279
- this.strings[pos] += rawString;
280
- } else if (isView(child)) {
281
- this.strings[pos] += `\`${child.name}\``;
282
- this.strings[pos] += rawString;
283
- } else {
284
- this.values[pos++] = child;
285
- this.strings[pos] = rawString;
286
- }
287
- }
288
- }
289
- /**
290
- * Append another Sql fragment, returning a new Sql instance.
291
- */
292
- append(other) {
293
- return new _Sql([...this.strings, ""], [...this.values, other]);
294
- }
295
- };
296
- sql.join = function(fragments, separator) {
297
- if (fragments.length === 0) return new Sql([""], []);
298
- if (fragments.length === 1) return fragments[0];
299
- const sep = separator ?? ", ";
300
- const normalized = sep.includes(" ") ? sep : ` ${sep} `;
301
- const strings = ["", ...Array(fragments.length - 1).fill(normalized), ""];
302
- return new Sql(strings, fragments);
303
- };
304
- sql.raw = function(text) {
305
- return new Sql([text], []);
306
- };
307
- toStaticQuery = (sql3) => {
308
- const [query, params] = toQuery(sql3);
309
- if (Object.keys(params).length !== 0) {
310
- throw new Error(
311
- "Dynamic SQL is not allowed in the select statement in view creation."
312
- );
313
- }
314
- return query;
315
- };
316
- toQuery = (sql3) => {
317
- const parameterizedStubs = sql3.values.map(
318
- (v, i) => createClickhouseParameter(i, v)
319
- );
320
- const query = sql3.strings.map(
321
- (s, i) => s != "" ? `${s}${emptyIfUndefined(parameterizedStubs[i])}` : ""
322
- ).join("");
323
- const query_params = sql3.values.reduce(
324
- (acc, v, i) => ({
325
- ...acc,
326
- [`p${i}`]: getValueFromParameter(v)
327
- }),
328
- {}
329
- );
330
- return [query, query_params];
331
- };
332
- getValueFromParameter = (value) => {
333
- if (Array.isArray(value)) {
334
- const [type, val] = value;
335
- if (type === "Identifier") return val;
336
- }
337
- return value;
338
- };
339
- mapToClickHouseType = (value) => {
340
- if (typeof value === "number") {
341
- return Number.isInteger(value) ? "Int" : "Float";
342
- }
343
- if (typeof value === "boolean") return "Bool";
344
- if (value instanceof Date) return "DateTime";
345
- if (Array.isArray(value)) {
346
- const [type, _] = value;
347
- return type;
348
- }
349
- return "String";
350
- };
351
- }
352
- });
353
-
354
- // src/browserCompatible.ts
355
- var init_browserCompatible = __esm({
356
- "src/browserCompatible.ts"() {
357
- "use strict";
358
- init_dmv2();
359
- init_types();
360
- init_sqlHelpers();
361
- }
362
- });
363
-
364
33
  // src/commons.ts
365
34
  var commons_exports = {};
366
35
  __export(commons_exports, {
@@ -619,309 +288,6 @@ var init_commons = __esm({
619
288
  }
620
289
  });
621
290
 
622
- // src/secrets.ts
623
- var init_secrets = __esm({
624
- "src/secrets.ts"() {
625
- "use strict";
626
- }
627
- });
628
-
629
- // src/consumption-apis/helpers.ts
630
- var import_client2, import_node_crypto;
631
- var init_helpers = __esm({
632
- "src/consumption-apis/helpers.ts"() {
633
- "use strict";
634
- import_client2 = require("@temporalio/client");
635
- import_node_crypto = require("crypto");
636
- init_internal();
637
- init_sqlHelpers();
638
- }
639
- });
640
-
641
- // src/consumption-apis/webAppHelpers.ts
642
- var init_webAppHelpers = __esm({
643
- "src/consumption-apis/webAppHelpers.ts"() {
644
- "use strict";
645
- }
646
- });
647
-
648
- // src/scripts/task.ts
649
- var init_task = __esm({
650
- "src/scripts/task.ts"() {
651
- "use strict";
652
- }
653
- });
654
-
655
- // src/cluster-utils.ts
656
- var import_node_cluster, import_node_os, import_node_process;
657
- var init_cluster_utils = __esm({
658
- "src/cluster-utils.ts"() {
659
- "use strict";
660
- import_node_cluster = __toESM(require("cluster"));
661
- import_node_os = require("os");
662
- import_node_process = require("process");
663
- }
664
- });
665
-
666
- // src/compiler-config.ts
667
- var init_compiler_config = __esm({
668
- "src/compiler-config.ts"() {
669
- "use strict";
670
- }
671
- });
672
-
673
- // src/consumption-apis/runner.ts
674
- var jose;
675
- var init_runner = __esm({
676
- "src/consumption-apis/runner.ts"() {
677
- "use strict";
678
- init_commons();
679
- init_helpers();
680
- jose = __toESM(require("jose"));
681
- init_cluster_utils();
682
- init_sqlHelpers();
683
- init_internal();
684
- init_compiler_config();
685
- }
686
- });
687
-
688
- // src/clients/redisClient.ts
689
- var import_redis;
690
- var init_redisClient = __esm({
691
- "src/clients/redisClient.ts"() {
692
- "use strict";
693
- import_redis = require("redis");
694
- }
695
- });
696
-
697
- // src/consumption-apis/standalone.ts
698
- var init_standalone = __esm({
699
- "src/consumption-apis/standalone.ts"() {
700
- "use strict";
701
- init_helpers();
702
- init_commons();
703
- init_sqlHelpers();
704
- }
705
- });
706
-
707
- // src/utilities/json.ts
708
- var init_json = __esm({
709
- "src/utilities/json.ts"() {
710
- "use strict";
711
- }
712
- });
713
-
714
- // src/utilities/dataParser.ts
715
- var import_csv_parse, CSV_DELIMITERS, DEFAULT_CSV_CONFIG;
716
- var init_dataParser = __esm({
717
- "src/utilities/dataParser.ts"() {
718
- "use strict";
719
- import_csv_parse = require("csv-parse");
720
- init_json();
721
- CSV_DELIMITERS = {
722
- COMMA: ",",
723
- TAB: " ",
724
- SEMICOLON: ";",
725
- PIPE: "|"
726
- };
727
- DEFAULT_CSV_CONFIG = {
728
- delimiter: CSV_DELIMITERS.COMMA,
729
- columns: true,
730
- skipEmptyLines: true,
731
- trim: true
732
- };
733
- }
734
- });
735
-
736
- // src/utilities/index.ts
737
- var init_utilities = __esm({
738
- "src/utilities/index.ts"() {
739
- "use strict";
740
- init_dataParser();
741
- }
742
- });
743
-
744
- // src/connectors/dataSource.ts
745
- var init_dataSource = __esm({
746
- "src/connectors/dataSource.ts"() {
747
- "use strict";
748
- }
749
- });
750
-
751
- // src/index.ts
752
- var init_index = __esm({
753
- "src/index.ts"() {
754
- "use strict";
755
- init_browserCompatible();
756
- init_commons();
757
- init_secrets();
758
- init_helpers();
759
- init_webAppHelpers();
760
- init_task();
761
- init_runner();
762
- init_redisClient();
763
- init_helpers();
764
- init_standalone();
765
- init_sqlHelpers();
766
- init_utilities();
767
- init_dataSource();
768
- init_types();
769
- }
770
- });
771
-
772
- // src/dmv2/internal.ts
773
- var import_process, isClientOnlyMode, moose_internal, defaultRetentionPeriod, getMooseInternal, dlqSchema, dlqColumns;
774
- var init_internal = __esm({
775
- "src/dmv2/internal.ts"() {
776
- "use strict";
777
- import_process = __toESM(require("process"));
778
- init_index();
779
- init_commons();
780
- init_compiler_config();
781
- isClientOnlyMode = () => import_process.default.env.MOOSE_CLIENT_ONLY === "true";
782
- moose_internal = {
783
- tables: /* @__PURE__ */ new Map(),
784
- streams: /* @__PURE__ */ new Map(),
785
- ingestApis: /* @__PURE__ */ new Map(),
786
- apis: /* @__PURE__ */ new Map(),
787
- sqlResources: /* @__PURE__ */ new Map(),
788
- workflows: /* @__PURE__ */ new Map(),
789
- webApps: /* @__PURE__ */ new Map(),
790
- materializedViews: /* @__PURE__ */ new Map(),
791
- views: /* @__PURE__ */ new Map()
792
- };
793
- defaultRetentionPeriod = 60 * 60 * 24 * 7;
794
- getMooseInternal = () => globalThis.moose_internal;
795
- if (getMooseInternal() === void 0) {
796
- globalThis.moose_internal = moose_internal;
797
- }
798
- dlqSchema = {
799
- version: "3.1",
800
- components: {
801
- schemas: {
802
- DeadLetterModel: {
803
- type: "object",
804
- properties: {
805
- originalRecord: {
806
- $ref: "#/components/schemas/Recordstringany"
807
- },
808
- errorMessage: {
809
- type: "string"
810
- },
811
- errorType: {
812
- type: "string"
813
- },
814
- failedAt: {
815
- type: "string",
816
- format: "date-time"
817
- },
818
- source: {
819
- oneOf: [
820
- {
821
- const: "api"
822
- },
823
- {
824
- const: "transform"
825
- },
826
- {
827
- const: "table"
828
- }
829
- ]
830
- }
831
- },
832
- required: [
833
- "originalRecord",
834
- "errorMessage",
835
- "errorType",
836
- "failedAt",
837
- "source"
838
- ]
839
- },
840
- Recordstringany: {
841
- type: "object",
842
- properties: {},
843
- required: [],
844
- description: "Construct a type with a set of properties K of type T",
845
- additionalProperties: {}
846
- }
847
- }
848
- },
849
- schemas: [
850
- {
851
- $ref: "#/components/schemas/DeadLetterModel"
852
- }
853
- ]
854
- };
855
- dlqColumns = [
856
- {
857
- name: "originalRecord",
858
- data_type: "Json",
859
- primary_key: false,
860
- required: true,
861
- unique: false,
862
- default: null,
863
- annotations: [],
864
- ttl: null,
865
- codec: null,
866
- materialized: null,
867
- comment: null
868
- },
869
- {
870
- name: "errorMessage",
871
- data_type: "String",
872
- primary_key: false,
873
- required: true,
874
- unique: false,
875
- default: null,
876
- annotations: [],
877
- ttl: null,
878
- codec: null,
879
- materialized: null,
880
- comment: null
881
- },
882
- {
883
- name: "errorType",
884
- data_type: "String",
885
- primary_key: false,
886
- required: true,
887
- unique: false,
888
- default: null,
889
- annotations: [],
890
- ttl: null,
891
- codec: null,
892
- materialized: null,
893
- comment: null
894
- },
895
- {
896
- name: "failedAt",
897
- data_type: "DateTime",
898
- primary_key: false,
899
- required: true,
900
- unique: false,
901
- default: null,
902
- annotations: [],
903
- ttl: null,
904
- codec: null,
905
- materialized: null,
906
- comment: null
907
- },
908
- {
909
- name: "source",
910
- data_type: "String",
911
- primary_key: false,
912
- required: true,
913
- unique: false,
914
- default: null,
915
- annotations: [],
916
- ttl: null,
917
- codec: null,
918
- materialized: null,
919
- comment: null
920
- }
921
- ];
922
- }
923
- });
924
-
925
291
  // src/config/configFile.ts
926
292
  async function findConfigFile(startDir = process.cwd()) {
927
293
  const fs = await import("fs");
@@ -1106,1568 +472,2014 @@ var init_runtime = __esm({
1106
472
  }
1107
473
  });
1108
474
 
1109
- // src/dmv2/sdk/olapTable.ts
1110
- var import_node_stream, import_node_crypto2, OlapTable;
1111
- var init_olapTable = __esm({
1112
- "src/dmv2/sdk/olapTable.ts"() {
1113
- "use strict";
1114
- init_typedBase();
1115
- init_dataModelTypes();
1116
- init_types();
1117
- init_internal();
1118
- import_node_stream = require("stream");
1119
- import_node_crypto2 = require("crypto");
1120
- init_sqlHelpers();
1121
- OlapTable = class extends TypedBase {
1122
- name;
1123
- /** @internal */
1124
- kind = "OlapTable";
1125
- /** @internal Memoized ClickHouse client for reusing connections across insert calls */
1126
- _memoizedClient;
1127
- /** @internal Hash of the configuration used to create the memoized client */
1128
- _configHash;
1129
- /** @internal Cached table name to avoid repeated generation */
1130
- _cachedTableName;
1131
- constructor(name, config, schema, columns, validators) {
1132
- const resolvedConfig = config ? "engine" in config ? config : { ...config, engine: "MergeTree" /* MergeTree */ } : { engine: "MergeTree" /* MergeTree */ };
1133
- const hasFields = Array.isArray(resolvedConfig.orderByFields) && resolvedConfig.orderByFields.length > 0;
1134
- const hasExpr = typeof resolvedConfig.orderByExpression === "string" && resolvedConfig.orderByExpression.length > 0;
1135
- if (hasFields && hasExpr) {
1136
- throw new Error(
1137
- `OlapTable ${name}: Provide either orderByFields or orderByExpression, not both.`
1138
- );
1139
- }
1140
- const hasCluster = typeof resolvedConfig.cluster === "string";
1141
- const hasKeeperPath = typeof resolvedConfig.keeperPath === "string";
1142
- const hasReplicaName = typeof resolvedConfig.replicaName === "string";
1143
- if (hasCluster && (hasKeeperPath || hasReplicaName)) {
1144
- throw new Error(
1145
- `OlapTable ${name}: Cannot specify both 'cluster' and explicit replication params ('keeperPath' or 'replicaName'). Use 'cluster' for auto-injected params, or use explicit 'keeperPath' and 'replicaName' without 'cluster'.`
1146
- );
1147
- }
1148
- super(name, resolvedConfig, schema, columns, validators);
1149
- this.name = name;
1150
- const tables = getMooseInternal().tables;
1151
- const registryKey = this.config.version ? `${name}_${this.config.version}` : name;
1152
- if (!isClientOnlyMode() && tables.has(registryKey)) {
1153
- throw new Error(
1154
- `OlapTable with name ${name} and version ${config?.version ?? "unversioned"} already exists`
1155
- );
1156
- }
1157
- tables.set(registryKey, this);
1158
- }
1159
- /**
1160
- * Generates the versioned table name following Moose's naming convention
1161
- * Format: {tableName}_{version_with_dots_replaced_by_underscores}
1162
- */
1163
- generateTableName() {
1164
- if (this._cachedTableName) {
1165
- return this._cachedTableName;
1166
- }
1167
- const tableVersion = this.config.version;
1168
- if (!tableVersion) {
1169
- this._cachedTableName = this.name;
1170
- } else {
1171
- const versionSuffix = tableVersion.replace(/\./g, "_");
1172
- this._cachedTableName = `${this.name}_${versionSuffix}`;
1173
- }
1174
- return this._cachedTableName;
1175
- }
1176
- /**
1177
- * Creates a fast hash of the ClickHouse configuration.
1178
- * Uses crypto.createHash for better performance than JSON.stringify.
1179
- *
1180
- * @private
1181
- */
1182
- createConfigHash(clickhouseConfig) {
1183
- const effectiveDatabase = this.config.database ?? clickhouseConfig.database;
1184
- const configString = `${clickhouseConfig.host}:${clickhouseConfig.port}:${clickhouseConfig.username}:${clickhouseConfig.password}:${effectiveDatabase}:${clickhouseConfig.useSSL}`;
1185
- return (0, import_node_crypto2.createHash)("sha256").update(configString).digest("hex").substring(0, 16);
1186
- }
1187
- /**
1188
- * Gets or creates a memoized ClickHouse client.
1189
- * The client is cached and reused across multiple insert calls for better performance.
1190
- * If the configuration changes, a new client will be created.
1191
- *
1192
- * @private
1193
- */
1194
- async getMemoizedClient() {
1195
- await Promise.resolve().then(() => (init_runtime(), runtime_exports));
1196
- const configRegistry = globalThis._mooseConfigRegistry;
1197
- const { getClickhouseClient: getClickhouseClient2 } = await Promise.resolve().then(() => (init_commons(), commons_exports));
1198
- const clickhouseConfig = await configRegistry.getClickHouseConfig();
1199
- const currentConfigHash = this.createConfigHash(clickhouseConfig);
1200
- if (this._memoizedClient && this._configHash === currentConfigHash) {
1201
- return { client: this._memoizedClient, config: clickhouseConfig };
1202
- }
1203
- if (this._memoizedClient && this._configHash !== currentConfigHash) {
1204
- try {
1205
- await this._memoizedClient.close();
1206
- } catch (error) {
1207
- }
1208
- }
1209
- const effectiveDatabase = this.config.database ?? clickhouseConfig.database;
1210
- const client = getClickhouseClient2({
1211
- username: clickhouseConfig.username,
1212
- password: clickhouseConfig.password,
1213
- database: effectiveDatabase,
1214
- useSSL: clickhouseConfig.useSSL ? "true" : "false",
1215
- host: clickhouseConfig.host,
1216
- port: clickhouseConfig.port
1217
- });
1218
- this._memoizedClient = client;
1219
- this._configHash = currentConfigHash;
1220
- return { client, config: clickhouseConfig };
475
+ // src/dmv2/index.ts
476
+ var dmv2_exports = {};
477
+ __export(dmv2_exports, {
478
+ Api: () => Api,
479
+ ClickHouseEngines: () => ClickHouseEngines,
480
+ ConsumptionApi: () => ConsumptionApi,
481
+ DeadLetterQueue: () => DeadLetterQueue,
482
+ ETLPipeline: () => ETLPipeline,
483
+ IngestApi: () => IngestApi,
484
+ IngestPipeline: () => IngestPipeline,
485
+ LifeCycle: () => LifeCycle,
486
+ MaterializedView: () => MaterializedView,
487
+ OlapTable: () => OlapTable,
488
+ SqlResource: () => SqlResource,
489
+ Stream: () => Stream,
490
+ Task: () => Task,
491
+ View: () => View,
492
+ WebApp: () => WebApp,
493
+ Workflow: () => Workflow,
494
+ getApi: () => getApi,
495
+ getApis: () => getApis,
496
+ getIngestApi: () => getIngestApi,
497
+ getIngestApis: () => getIngestApis,
498
+ getMaterializedView: () => getMaterializedView,
499
+ getMaterializedViews: () => getMaterializedViews,
500
+ getSqlResource: () => getSqlResource,
501
+ getSqlResources: () => getSqlResources,
502
+ getStream: () => getStream,
503
+ getStreams: () => getStreams,
504
+ getTable: () => getTable,
505
+ getTables: () => getTables,
506
+ getView: () => getView,
507
+ getViews: () => getViews,
508
+ getWebApp: () => getWebApp,
509
+ getWebApps: () => getWebApps,
510
+ getWorkflow: () => getWorkflow,
511
+ getWorkflows: () => getWorkflows
512
+ });
513
+ module.exports = __toCommonJS(dmv2_exports);
514
+
515
+ // src/dmv2/utils/stackTrace.ts
516
+ function shouldSkipStackLine(line) {
517
+ return line.includes("node_modules") || // Skip npm installed packages (prod)
518
+ line.includes("node:internal") || // Skip Node.js internals (modern format)
519
+ line.includes("internal/modules") || // Skip Node.js internals (older format)
520
+ line.includes("ts-node") || // Skip TypeScript execution
521
+ line.includes("/ts-moose-lib/src/") || // Skip dev/linked moose-lib src (Unix)
522
+ line.includes("\\ts-moose-lib\\src\\") || // Skip dev/linked moose-lib src (Windows)
523
+ line.includes("/ts-moose-lib/dist/") || // Skip dev/linked moose-lib dist (Unix)
524
+ line.includes("\\ts-moose-lib\\dist\\");
525
+ }
526
+ function parseStackLine(line) {
527
+ const match = line.match(/\((.*):(\d+):(\d+)\)/) || line.match(/at (.*):(\d+):(\d+)/);
528
+ if (match && match[1]) {
529
+ return {
530
+ file: match[1],
531
+ line: match[2]
532
+ };
533
+ }
534
+ return void 0;
535
+ }
536
+ function getSourceFileInfo(stack) {
537
+ if (!stack) return {};
538
+ const lines = stack.split("\n");
539
+ for (const line of lines) {
540
+ if (shouldSkipStackLine(line)) continue;
541
+ const info = parseStackLine(line);
542
+ if (info) return info;
543
+ }
544
+ return {};
545
+ }
546
+ function getSourceLocationFromStack(stack) {
547
+ if (!stack) return void 0;
548
+ const lines = stack.split("\n");
549
+ for (const line of lines.slice(1)) {
550
+ if (shouldSkipStackLine(line)) {
551
+ continue;
552
+ }
553
+ const v8Match = line.match(/at\s+(?:.*?\s+\()?(.+):(\d+):(\d+)\)?/);
554
+ if (v8Match) {
555
+ return {
556
+ file: v8Match[1],
557
+ line: parseInt(v8Match[2], 10),
558
+ column: parseInt(v8Match[3], 10)
559
+ };
560
+ }
561
+ const smMatch = line.match(/(?:.*@)?(.+):(\d+):(\d+)/);
562
+ if (smMatch) {
563
+ return {
564
+ file: smMatch[1],
565
+ line: parseInt(smMatch[2], 10),
566
+ column: parseInt(smMatch[3], 10)
567
+ };
568
+ }
569
+ }
570
+ return void 0;
571
+ }
572
+ function getSourceFileFromStack(stack) {
573
+ const location = getSourceLocationFromStack(stack);
574
+ return location?.file;
575
+ }
576
+
577
+ // src/dmv2/typedBase.ts
578
+ var TypedBase = class {
579
+ /** The JSON schema representation of type T. Injected by the compiler plugin. */
580
+ schema;
581
+ /** The name assigned to this resource instance. */
582
+ name;
583
+ /** A dictionary mapping column names (keys of T) to their Column definitions. */
584
+ columns;
585
+ /** An array containing the Column definitions for this resource. Injected by the compiler plugin. */
586
+ columnArray;
587
+ /** The configuration object specific to this resource type. */
588
+ config;
589
+ /** Typia validation functions for type T. Injected by the compiler plugin for OlapTable. */
590
+ validators;
591
+ /** Optional metadata for the resource, always present as an object. */
592
+ metadata;
593
+ /**
594
+ * Whether this resource allows extra fields beyond the defined columns.
595
+ * When true, extra fields in payloads are passed through to streaming functions.
596
+ * Injected by the compiler plugin when the type has an index signature.
597
+ */
598
+ allowExtraFields;
599
+ /**
600
+ * @internal Constructor intended for internal use by subclasses and the compiler plugin.
601
+ * It expects the schema and columns to be provided, typically injected by the compiler.
602
+ *
603
+ * @param name The name for the resource instance.
604
+ * @param config The configuration object for the resource.
605
+ * @param schema The JSON schema for the resource's data type T (injected).
606
+ * @param columns The array of Column definitions for T (injected).
607
+ * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
608
+ */
609
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
610
+ if (schema === void 0 || columns === void 0) {
611
+ throw new Error(
612
+ "Supply the type param T so that the schema is inserted by the compiler plugin."
613
+ );
614
+ }
615
+ this.schema = schema;
616
+ this.columnArray = columns;
617
+ const columnsObj = {};
618
+ columns.forEach((column) => {
619
+ columnsObj[column.name] = column;
620
+ });
621
+ this.columns = columnsObj;
622
+ this.name = name;
623
+ this.config = config;
624
+ this.validators = validators;
625
+ this.allowExtraFields = allowExtraFields ?? false;
626
+ this.metadata = config?.metadata ? { ...config.metadata } : {};
627
+ if (!this.metadata.source) {
628
+ const stack = new Error().stack;
629
+ if (stack) {
630
+ const info = getSourceFileInfo(stack);
631
+ this.metadata.source = { file: info.file, line: info.line };
1221
632
  }
1222
- /**
1223
- * Closes the memoized ClickHouse client if it exists.
1224
- * This is useful for cleaning up connections when the table instance is no longer needed.
1225
- * The client will be automatically recreated on the next insert call if needed.
1226
- */
1227
- async closeClient() {
1228
- if (this._memoizedClient) {
1229
- try {
1230
- await this._memoizedClient.close();
1231
- } catch (error) {
1232
- } finally {
1233
- this._memoizedClient = void 0;
1234
- this._configHash = void 0;
1235
- }
633
+ }
634
+ }
635
+ };
636
+
637
+ // src/dataModels/dataModelTypes.ts
638
+ function isArrayNestedType(dt) {
639
+ return typeof dt === "object" && dt !== null && dt.elementType !== null && typeof dt.elementType === "object" && dt.elementType.hasOwnProperty("columns") && Array.isArray(dt.elementType.columns);
640
+ }
641
+ function isNestedType(dt) {
642
+ return typeof dt === "object" && dt !== null && Array.isArray(dt.columns);
643
+ }
644
+
645
+ // src/dataModels/types.ts
646
+ var ClickHouseEngines = /* @__PURE__ */ ((ClickHouseEngines2) => {
647
+ ClickHouseEngines2["MergeTree"] = "MergeTree";
648
+ ClickHouseEngines2["ReplacingMergeTree"] = "ReplacingMergeTree";
649
+ ClickHouseEngines2["SummingMergeTree"] = "SummingMergeTree";
650
+ ClickHouseEngines2["AggregatingMergeTree"] = "AggregatingMergeTree";
651
+ ClickHouseEngines2["CollapsingMergeTree"] = "CollapsingMergeTree";
652
+ ClickHouseEngines2["VersionedCollapsingMergeTree"] = "VersionedCollapsingMergeTree";
653
+ ClickHouseEngines2["GraphiteMergeTree"] = "GraphiteMergeTree";
654
+ ClickHouseEngines2["S3Queue"] = "S3Queue";
655
+ ClickHouseEngines2["S3"] = "S3";
656
+ ClickHouseEngines2["Buffer"] = "Buffer";
657
+ ClickHouseEngines2["Distributed"] = "Distributed";
658
+ ClickHouseEngines2["IcebergS3"] = "IcebergS3";
659
+ ClickHouseEngines2["Kafka"] = "Kafka";
660
+ ClickHouseEngines2["ReplicatedMergeTree"] = "ReplicatedMergeTree";
661
+ ClickHouseEngines2["ReplicatedReplacingMergeTree"] = "ReplicatedReplacingMergeTree";
662
+ ClickHouseEngines2["ReplicatedAggregatingMergeTree"] = "ReplicatedAggregatingMergeTree";
663
+ ClickHouseEngines2["ReplicatedSummingMergeTree"] = "ReplicatedSummingMergeTree";
664
+ ClickHouseEngines2["ReplicatedCollapsingMergeTree"] = "ReplicatedCollapsingMergeTree";
665
+ ClickHouseEngines2["ReplicatedVersionedCollapsingMergeTree"] = "ReplicatedVersionedCollapsingMergeTree";
666
+ return ClickHouseEngines2;
667
+ })(ClickHouseEngines || {});
668
+
669
+ // src/dmv2/internal.ts
670
+ var import_process = __toESM(require("process"));
671
+
672
+ // src/sqlHelpers.ts
673
+ var quoteIdentifier = (name) => {
674
+ return name.startsWith("`") && name.endsWith("`") ? name : `\`${name}\``;
675
+ };
676
+ var isTable = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "OlapTable";
677
+ var isView = (value) => typeof value === "object" && value !== null && "kind" in value && value.kind === "View";
678
+ var isColumn = (value) => typeof value === "object" && value !== null && !("kind" in value) && "name" in value && "annotations" in value;
679
+ function sqlImpl(strings, ...values) {
680
+ return new Sql(strings, values);
681
+ }
682
+ var sql = sqlImpl;
683
+ var instanceofSql = (value) => typeof value === "object" && "values" in value && "strings" in value;
684
+ var Sql = class _Sql {
685
+ values;
686
+ strings;
687
+ constructor(rawStrings, rawValues) {
688
+ if (rawStrings.length - 1 !== rawValues.length) {
689
+ if (rawStrings.length === 0) {
690
+ throw new TypeError("Expected at least 1 string");
691
+ }
692
+ throw new TypeError(
693
+ `Expected ${rawStrings.length} strings to have ${rawStrings.length - 1} values`
694
+ );
695
+ }
696
+ const valuesLength = rawValues.reduce(
697
+ (len, value) => len + (instanceofSql(value) ? value.values.length : isColumn(value) || isTable(value) || isView(value) ? 0 : 1),
698
+ 0
699
+ );
700
+ this.values = new Array(valuesLength);
701
+ this.strings = new Array(valuesLength + 1);
702
+ this.strings[0] = rawStrings[0];
703
+ let i = 0, pos = 0;
704
+ while (i < rawValues.length) {
705
+ const child = rawValues[i++];
706
+ const rawString = rawStrings[i];
707
+ if (instanceofSql(child)) {
708
+ this.strings[pos] += child.strings[0];
709
+ let childIndex = 0;
710
+ while (childIndex < child.values.length) {
711
+ this.values[pos++] = child.values[childIndex++];
712
+ this.strings[pos] = child.strings[childIndex];
713
+ }
714
+ this.strings[pos] += rawString;
715
+ } else if (isColumn(child)) {
716
+ const aggregationFunction = child.annotations.find(
717
+ ([k, _]) => k === "aggregationFunction"
718
+ );
719
+ if (aggregationFunction !== void 0) {
720
+ this.strings[pos] += `${aggregationFunction[1].functionName}Merge(\`${child.name}\`)`;
721
+ } else {
722
+ this.strings[pos] += `\`${child.name}\``;
723
+ }
724
+ this.strings[pos] += rawString;
725
+ } else if (isTable(child)) {
726
+ if (child.config.database) {
727
+ this.strings[pos] += `\`${child.config.database}\`.\`${child.name}\``;
728
+ } else {
729
+ this.strings[pos] += `\`${child.name}\``;
1236
730
  }
731
+ this.strings[pos] += rawString;
732
+ } else if (isView(child)) {
733
+ this.strings[pos] += `\`${child.name}\``;
734
+ this.strings[pos] += rawString;
735
+ } else {
736
+ this.values[pos++] = child;
737
+ this.strings[pos] = rawString;
1237
738
  }
1238
- /**
1239
- * Validates a single record using typia's comprehensive type checking.
1240
- * This provides the most accurate validation as it uses the exact TypeScript type information.
1241
- *
1242
- * @param record The record to validate
1243
- * @returns Validation result with detailed error information
1244
- */
1245
- validateRecord(record) {
1246
- if (this.validators?.validate) {
1247
- try {
1248
- const result = this.validators.validate(record);
1249
- return {
1250
- success: result.success,
1251
- data: result.data,
1252
- errors: result.errors?.map(
1253
- (err) => typeof err === "string" ? err : JSON.stringify(err)
1254
- )
1255
- };
1256
- } catch (error) {
1257
- return {
1258
- success: false,
1259
- errors: [error instanceof Error ? error.message : String(error)]
1260
- };
739
+ }
740
+ }
741
+ /**
742
+ * Append another Sql fragment, returning a new Sql instance.
743
+ */
744
+ append(other) {
745
+ return new _Sql([...this.strings, ""], [...this.values, other]);
746
+ }
747
+ };
748
+ sql.join = function(fragments, separator) {
749
+ if (fragments.length === 0) return new Sql([""], []);
750
+ if (fragments.length === 1) return fragments[0];
751
+ const sep = separator ?? ", ";
752
+ const normalized = sep.includes(" ") ? sep : ` ${sep} `;
753
+ const strings = ["", ...Array(fragments.length - 1).fill(normalized), ""];
754
+ return new Sql(strings, fragments);
755
+ };
756
+ sql.raw = function(text) {
757
+ return new Sql([text], []);
758
+ };
759
+ var toStaticQuery = (sql3) => {
760
+ const [query, params] = toQuery(sql3);
761
+ if (Object.keys(params).length !== 0) {
762
+ throw new Error(
763
+ "Dynamic SQL is not allowed in the select statement in view creation."
764
+ );
765
+ }
766
+ return query;
767
+ };
768
+ var toQuery = (sql3) => {
769
+ const parameterizedStubs = sql3.values.map(
770
+ (v, i) => createClickhouseParameter(i, v)
771
+ );
772
+ const query = sql3.strings.map(
773
+ (s, i) => s != "" ? `${s}${emptyIfUndefined(parameterizedStubs[i])}` : ""
774
+ ).join("");
775
+ const query_params = sql3.values.reduce(
776
+ (acc, v, i) => ({
777
+ ...acc,
778
+ [`p${i}`]: getValueFromParameter(v)
779
+ }),
780
+ {}
781
+ );
782
+ return [query, query_params];
783
+ };
784
+ var getValueFromParameter = (value) => {
785
+ if (Array.isArray(value)) {
786
+ const [type, val] = value;
787
+ if (type === "Identifier") return val;
788
+ }
789
+ return value;
790
+ };
791
+ function createClickhouseParameter(parameterIndex, value) {
792
+ return `{p${parameterIndex}:${mapToClickHouseType(value)}}`;
793
+ }
794
+ var mapToClickHouseType = (value) => {
795
+ if (typeof value === "number") {
796
+ return Number.isInteger(value) ? "Int" : "Float";
797
+ }
798
+ if (typeof value === "boolean") return "Bool";
799
+ if (value instanceof Date) return "DateTime";
800
+ if (Array.isArray(value)) {
801
+ const [type, _] = value;
802
+ return type;
803
+ }
804
+ return "String";
805
+ };
806
+ function emptyIfUndefined(value) {
807
+ return value === void 0 ? "" : value;
808
+ }
809
+
810
+ // src/index.ts
811
+ init_commons();
812
+
813
+ // src/consumption-apis/helpers.ts
814
+ var import_client2 = require("@temporalio/client");
815
+ var import_node_crypto = require("crypto");
816
+
817
+ // src/clients/redisClient.ts
818
+ var import_redis = require("redis");
819
+
820
+ // src/consumption-apis/standalone.ts
821
+ init_commons();
822
+
823
+ // src/utilities/dataParser.ts
824
+ var import_csv_parse = require("csv-parse");
825
+ var CSV_DELIMITERS = {
826
+ COMMA: ",",
827
+ TAB: " ",
828
+ SEMICOLON: ";",
829
+ PIPE: "|"
830
+ };
831
+ var DEFAULT_CSV_CONFIG = {
832
+ delimiter: CSV_DELIMITERS.COMMA,
833
+ columns: true,
834
+ skipEmptyLines: true,
835
+ trim: true
836
+ };
837
+
838
+ // src/dmv2/internal.ts
839
+ init_commons();
840
+ var isClientOnlyMode = () => import_process.default.env.MOOSE_CLIENT_ONLY === "true";
841
+ var moose_internal = {
842
+ tables: /* @__PURE__ */ new Map(),
843
+ streams: /* @__PURE__ */ new Map(),
844
+ ingestApis: /* @__PURE__ */ new Map(),
845
+ apis: /* @__PURE__ */ new Map(),
846
+ sqlResources: /* @__PURE__ */ new Map(),
847
+ workflows: /* @__PURE__ */ new Map(),
848
+ webApps: /* @__PURE__ */ new Map(),
849
+ materializedViews: /* @__PURE__ */ new Map(),
850
+ views: /* @__PURE__ */ new Map()
851
+ };
852
+ var defaultRetentionPeriod = 60 * 60 * 24 * 7;
853
+ var getMooseInternal = () => globalThis.moose_internal;
854
+ if (getMooseInternal() === void 0) {
855
+ globalThis.moose_internal = moose_internal;
856
+ }
857
+ var dlqSchema = {
858
+ version: "3.1",
859
+ components: {
860
+ schemas: {
861
+ DeadLetterModel: {
862
+ type: "object",
863
+ properties: {
864
+ originalRecord: {
865
+ $ref: "#/components/schemas/Recordstringany"
866
+ },
867
+ errorMessage: {
868
+ type: "string"
869
+ },
870
+ errorType: {
871
+ type: "string"
872
+ },
873
+ failedAt: {
874
+ type: "string",
875
+ format: "date-time"
876
+ },
877
+ source: {
878
+ oneOf: [
879
+ {
880
+ const: "api"
881
+ },
882
+ {
883
+ const: "transform"
884
+ },
885
+ {
886
+ const: "table"
887
+ }
888
+ ]
1261
889
  }
1262
- }
1263
- throw new Error("No typia validator found");
890
+ },
891
+ required: [
892
+ "originalRecord",
893
+ "errorMessage",
894
+ "errorType",
895
+ "failedAt",
896
+ "source"
897
+ ]
898
+ },
899
+ Recordstringany: {
900
+ type: "object",
901
+ properties: {},
902
+ required: [],
903
+ description: "Construct a type with a set of properties K of type T",
904
+ additionalProperties: {}
1264
905
  }
1265
- /**
1266
- * Type guard function using typia's is() function.
1267
- * Provides compile-time type narrowing for TypeScript.
1268
- *
1269
- * @param record The record to check
1270
- * @returns True if record matches type T, with type narrowing
1271
- */
1272
- isValidRecord(record) {
1273
- if (this.validators?.is) {
1274
- return this.validators.is(record);
1275
- }
1276
- throw new Error("No typia validator found");
906
+ }
907
+ },
908
+ schemas: [
909
+ {
910
+ $ref: "#/components/schemas/DeadLetterModel"
911
+ }
912
+ ]
913
+ };
914
+ var dlqColumns = [
915
+ {
916
+ name: "originalRecord",
917
+ data_type: "Json",
918
+ primary_key: false,
919
+ required: true,
920
+ unique: false,
921
+ default: null,
922
+ annotations: [],
923
+ ttl: null,
924
+ codec: null,
925
+ materialized: null,
926
+ comment: null
927
+ },
928
+ {
929
+ name: "errorMessage",
930
+ data_type: "String",
931
+ primary_key: false,
932
+ required: true,
933
+ unique: false,
934
+ default: null,
935
+ annotations: [],
936
+ ttl: null,
937
+ codec: null,
938
+ materialized: null,
939
+ comment: null
940
+ },
941
+ {
942
+ name: "errorType",
943
+ data_type: "String",
944
+ primary_key: false,
945
+ required: true,
946
+ unique: false,
947
+ default: null,
948
+ annotations: [],
949
+ ttl: null,
950
+ codec: null,
951
+ materialized: null,
952
+ comment: null
953
+ },
954
+ {
955
+ name: "failedAt",
956
+ data_type: "DateTime",
957
+ primary_key: false,
958
+ required: true,
959
+ unique: false,
960
+ default: null,
961
+ annotations: [],
962
+ ttl: null,
963
+ codec: null,
964
+ materialized: null,
965
+ comment: null
966
+ },
967
+ {
968
+ name: "source",
969
+ data_type: "String",
970
+ primary_key: false,
971
+ required: true,
972
+ unique: false,
973
+ default: null,
974
+ annotations: [],
975
+ ttl: null,
976
+ codec: null,
977
+ materialized: null,
978
+ comment: null
979
+ }
980
+ ];
981
+
982
+ // src/dmv2/sdk/olapTable.ts
983
+ var import_node_stream = require("stream");
984
+ var import_node_crypto2 = require("crypto");
985
+ var OlapTable = class extends TypedBase {
986
+ name;
987
+ /** @internal */
988
+ kind = "OlapTable";
989
+ /** @internal Memoized ClickHouse client for reusing connections across insert calls */
990
+ _memoizedClient;
991
+ /** @internal Hash of the configuration used to create the memoized client */
992
+ _configHash;
993
+ /** @internal Cached table name to avoid repeated generation */
994
+ _cachedTableName;
995
+ constructor(name, config, schema, columns, validators) {
996
+ const resolvedConfig = config ? "engine" in config ? config : { ...config, engine: "MergeTree" /* MergeTree */ } : { engine: "MergeTree" /* MergeTree */ };
997
+ const hasFields = Array.isArray(resolvedConfig.orderByFields) && resolvedConfig.orderByFields.length > 0;
998
+ const hasExpr = typeof resolvedConfig.orderByExpression === "string" && resolvedConfig.orderByExpression.length > 0;
999
+ if (hasFields && hasExpr) {
1000
+ throw new Error(
1001
+ `OlapTable ${name}: Provide either orderByFields or orderByExpression, not both.`
1002
+ );
1003
+ }
1004
+ const hasCluster = typeof resolvedConfig.cluster === "string";
1005
+ const hasKeeperPath = typeof resolvedConfig.keeperPath === "string";
1006
+ const hasReplicaName = typeof resolvedConfig.replicaName === "string";
1007
+ if (hasCluster && (hasKeeperPath || hasReplicaName)) {
1008
+ throw new Error(
1009
+ `OlapTable ${name}: Cannot specify both 'cluster' and explicit replication params ('keeperPath' or 'replicaName'). Use 'cluster' for auto-injected params, or use explicit 'keeperPath' and 'replicaName' without 'cluster'.`
1010
+ );
1011
+ }
1012
+ super(name, resolvedConfig, schema, columns, validators);
1013
+ this.name = name;
1014
+ const tables = getMooseInternal().tables;
1015
+ const registryKey = this.config.version ? `${name}_${this.config.version}` : name;
1016
+ if (!isClientOnlyMode() && tables.has(registryKey)) {
1017
+ throw new Error(
1018
+ `OlapTable with name ${name} and version ${config?.version ?? "unversioned"} already exists`
1019
+ );
1020
+ }
1021
+ tables.set(registryKey, this);
1022
+ }
1023
+ /**
1024
+ * Generates the versioned table name following Moose's naming convention
1025
+ * Format: {tableName}_{version_with_dots_replaced_by_underscores}
1026
+ */
1027
+ generateTableName() {
1028
+ if (this._cachedTableName) {
1029
+ return this._cachedTableName;
1030
+ }
1031
+ const tableVersion = this.config.version;
1032
+ if (!tableVersion) {
1033
+ this._cachedTableName = this.name;
1034
+ } else {
1035
+ const versionSuffix = tableVersion.replace(/\./g, "_");
1036
+ this._cachedTableName = `${this.name}_${versionSuffix}`;
1037
+ }
1038
+ return this._cachedTableName;
1039
+ }
1040
+ /**
1041
+ * Creates a fast hash of the ClickHouse configuration.
1042
+ * Uses crypto.createHash for better performance than JSON.stringify.
1043
+ *
1044
+ * @private
1045
+ */
1046
+ createConfigHash(clickhouseConfig) {
1047
+ const effectiveDatabase = this.config.database ?? clickhouseConfig.database;
1048
+ const configString = `${clickhouseConfig.host}:${clickhouseConfig.port}:${clickhouseConfig.username}:${clickhouseConfig.password}:${effectiveDatabase}:${clickhouseConfig.useSSL}`;
1049
+ return (0, import_node_crypto2.createHash)("sha256").update(configString).digest("hex").substring(0, 16);
1050
+ }
1051
+ /**
1052
+ * Gets or creates a memoized ClickHouse client.
1053
+ * The client is cached and reused across multiple insert calls for better performance.
1054
+ * If the configuration changes, a new client will be created.
1055
+ *
1056
+ * @private
1057
+ */
1058
+ async getMemoizedClient() {
1059
+ await Promise.resolve().then(() => (init_runtime(), runtime_exports));
1060
+ const configRegistry = globalThis._mooseConfigRegistry;
1061
+ const { getClickhouseClient: getClickhouseClient2 } = await Promise.resolve().then(() => (init_commons(), commons_exports));
1062
+ const clickhouseConfig = await configRegistry.getClickHouseConfig();
1063
+ const currentConfigHash = this.createConfigHash(clickhouseConfig);
1064
+ if (this._memoizedClient && this._configHash === currentConfigHash) {
1065
+ return { client: this._memoizedClient, config: clickhouseConfig };
1066
+ }
1067
+ if (this._memoizedClient && this._configHash !== currentConfigHash) {
1068
+ try {
1069
+ await this._memoizedClient.close();
1070
+ } catch (error) {
1277
1071
  }
1278
- /**
1279
- * Assert that a record matches type T, throwing detailed errors if not.
1280
- * Uses typia's assert() function for the most detailed error reporting.
1281
- *
1282
- * @param record The record to assert
1283
- * @returns The validated and typed record
1284
- * @throws Detailed validation error if record doesn't match type T
1285
- */
1286
- assertValidRecord(record) {
1287
- if (this.validators?.assert) {
1288
- return this.validators.assert(record);
1289
- }
1290
- throw new Error("No typia validator found");
1072
+ }
1073
+ const effectiveDatabase = this.config.database ?? clickhouseConfig.database;
1074
+ const client = getClickhouseClient2({
1075
+ username: clickhouseConfig.username,
1076
+ password: clickhouseConfig.password,
1077
+ database: effectiveDatabase,
1078
+ useSSL: clickhouseConfig.useSSL ? "true" : "false",
1079
+ host: clickhouseConfig.host,
1080
+ port: clickhouseConfig.port
1081
+ });
1082
+ this._memoizedClient = client;
1083
+ this._configHash = currentConfigHash;
1084
+ return { client, config: clickhouseConfig };
1085
+ }
1086
+ /**
1087
+ * Closes the memoized ClickHouse client if it exists.
1088
+ * This is useful for cleaning up connections when the table instance is no longer needed.
1089
+ * The client will be automatically recreated on the next insert call if needed.
1090
+ */
1091
+ async closeClient() {
1092
+ if (this._memoizedClient) {
1093
+ try {
1094
+ await this._memoizedClient.close();
1095
+ } catch (error) {
1096
+ } finally {
1097
+ this._memoizedClient = void 0;
1098
+ this._configHash = void 0;
1291
1099
  }
1292
- /**
1293
- * Validates an array of records with comprehensive error reporting.
1294
- * Uses the most appropriate validation method available (typia or basic).
1295
- *
1296
- * @param data Array of records to validate
1297
- * @returns Detailed validation results
1298
- */
1299
- async validateRecords(data) {
1300
- const valid = [];
1301
- const invalid = [];
1302
- valid.length = 0;
1303
- invalid.length = 0;
1304
- const dataLength = data.length;
1305
- for (let i = 0; i < dataLength; i++) {
1306
- const record = data[i];
1307
- try {
1308
- if (this.isValidRecord(record)) {
1309
- valid.push(this.mapToClickhouseRecord(record));
1310
- } else {
1311
- const result = this.validateRecord(record);
1312
- if (result.success) {
1313
- valid.push(this.mapToClickhouseRecord(record));
1314
- } else {
1315
- invalid.push({
1316
- record,
1317
- error: result.errors?.join(", ") || "Validation failed",
1318
- index: i,
1319
- path: "root"
1320
- });
1321
- }
1322
- }
1323
- } catch (error) {
1100
+ }
1101
+ }
1102
+ /**
1103
+ * Validates a single record using typia's comprehensive type checking.
1104
+ * This provides the most accurate validation as it uses the exact TypeScript type information.
1105
+ *
1106
+ * @param record The record to validate
1107
+ * @returns Validation result with detailed error information
1108
+ */
1109
+ validateRecord(record) {
1110
+ if (this.validators?.validate) {
1111
+ try {
1112
+ const result = this.validators.validate(record);
1113
+ return {
1114
+ success: result.success,
1115
+ data: result.data,
1116
+ errors: result.errors?.map(
1117
+ (err) => typeof err === "string" ? err : JSON.stringify(err)
1118
+ )
1119
+ };
1120
+ } catch (error) {
1121
+ return {
1122
+ success: false,
1123
+ errors: [error instanceof Error ? error.message : String(error)]
1124
+ };
1125
+ }
1126
+ }
1127
+ throw new Error("No typia validator found");
1128
+ }
1129
+ /**
1130
+ * Type guard function using typia's is() function.
1131
+ * Provides compile-time type narrowing for TypeScript.
1132
+ *
1133
+ * @param record The record to check
1134
+ * @returns True if record matches type T, with type narrowing
1135
+ */
1136
+ isValidRecord(record) {
1137
+ if (this.validators?.is) {
1138
+ return this.validators.is(record);
1139
+ }
1140
+ throw new Error("No typia validator found");
1141
+ }
1142
+ /**
1143
+ * Assert that a record matches type T, throwing detailed errors if not.
1144
+ * Uses typia's assert() function for the most detailed error reporting.
1145
+ *
1146
+ * @param record The record to assert
1147
+ * @returns The validated and typed record
1148
+ * @throws Detailed validation error if record doesn't match type T
1149
+ */
1150
+ assertValidRecord(record) {
1151
+ if (this.validators?.assert) {
1152
+ return this.validators.assert(record);
1153
+ }
1154
+ throw new Error("No typia validator found");
1155
+ }
1156
+ /**
1157
+ * Validates an array of records with comprehensive error reporting.
1158
+ * Uses the most appropriate validation method available (typia or basic).
1159
+ *
1160
+ * @param data Array of records to validate
1161
+ * @returns Detailed validation results
1162
+ */
1163
+ async validateRecords(data) {
1164
+ const valid = [];
1165
+ const invalid = [];
1166
+ valid.length = 0;
1167
+ invalid.length = 0;
1168
+ const dataLength = data.length;
1169
+ for (let i = 0; i < dataLength; i++) {
1170
+ const record = data[i];
1171
+ try {
1172
+ if (this.isValidRecord(record)) {
1173
+ valid.push(this.mapToClickhouseRecord(record));
1174
+ } else {
1175
+ const result = this.validateRecord(record);
1176
+ if (result.success) {
1177
+ valid.push(this.mapToClickhouseRecord(record));
1178
+ } else {
1324
1179
  invalid.push({
1325
1180
  record,
1326
- error: error instanceof Error ? error.message : String(error),
1181
+ error: result.errors?.join(", ") || "Validation failed",
1327
1182
  index: i,
1328
1183
  path: "root"
1329
1184
  });
1330
1185
  }
1331
1186
  }
1332
- return {
1333
- valid,
1334
- invalid,
1335
- total: dataLength
1336
- };
1187
+ } catch (error) {
1188
+ invalid.push({
1189
+ record,
1190
+ error: error instanceof Error ? error.message : String(error),
1191
+ index: i,
1192
+ path: "root"
1193
+ });
1337
1194
  }
1338
- /**
1339
- * Optimized batch retry that minimizes individual insert operations.
1340
- * Groups records into smaller batches to reduce round trips while still isolating failures.
1341
- *
1342
- * @private
1343
- */
1344
- async retryIndividualRecords(client, tableName, records) {
1345
- const successful = [];
1346
- const failed = [];
1347
- const RETRY_BATCH_SIZE = 10;
1348
- const totalRecords = records.length;
1349
- for (let i = 0; i < totalRecords; i += RETRY_BATCH_SIZE) {
1350
- const batchEnd = Math.min(i + RETRY_BATCH_SIZE, totalRecords);
1351
- const batch = records.slice(i, batchEnd);
1195
+ }
1196
+ return {
1197
+ valid,
1198
+ invalid,
1199
+ total: dataLength
1200
+ };
1201
+ }
1202
+ /**
1203
+ * Optimized batch retry that minimizes individual insert operations.
1204
+ * Groups records into smaller batches to reduce round trips while still isolating failures.
1205
+ *
1206
+ * @private
1207
+ */
1208
+ async retryIndividualRecords(client, tableName, records) {
1209
+ const successful = [];
1210
+ const failed = [];
1211
+ const RETRY_BATCH_SIZE = 10;
1212
+ const totalRecords = records.length;
1213
+ for (let i = 0; i < totalRecords; i += RETRY_BATCH_SIZE) {
1214
+ const batchEnd = Math.min(i + RETRY_BATCH_SIZE, totalRecords);
1215
+ const batch = records.slice(i, batchEnd);
1216
+ try {
1217
+ await client.insert({
1218
+ table: quoteIdentifier(tableName),
1219
+ values: batch,
1220
+ format: "JSONEachRow",
1221
+ clickhouse_settings: {
1222
+ date_time_input_format: "best_effort",
1223
+ // Add performance settings for retries
1224
+ max_insert_block_size: RETRY_BATCH_SIZE,
1225
+ max_block_size: RETRY_BATCH_SIZE
1226
+ }
1227
+ });
1228
+ successful.push(...batch);
1229
+ } catch (batchError) {
1230
+ for (let j = 0; j < batch.length; j++) {
1231
+ const record = batch[j];
1352
1232
  try {
1353
1233
  await client.insert({
1354
1234
  table: quoteIdentifier(tableName),
1355
- values: batch,
1235
+ values: [record],
1356
1236
  format: "JSONEachRow",
1357
1237
  clickhouse_settings: {
1358
- date_time_input_format: "best_effort",
1359
- // Add performance settings for retries
1360
- max_insert_block_size: RETRY_BATCH_SIZE,
1361
- max_block_size: RETRY_BATCH_SIZE
1238
+ date_time_input_format: "best_effort"
1362
1239
  }
1363
1240
  });
1364
- successful.push(...batch);
1365
- } catch (batchError) {
1366
- for (let j = 0; j < batch.length; j++) {
1367
- const record = batch[j];
1368
- try {
1369
- await client.insert({
1370
- table: quoteIdentifier(tableName),
1371
- values: [record],
1372
- format: "JSONEachRow",
1373
- clickhouse_settings: {
1374
- date_time_input_format: "best_effort"
1375
- }
1376
- });
1377
- successful.push(record);
1378
- } catch (error) {
1379
- failed.push({
1380
- record,
1381
- error: error instanceof Error ? error.message : String(error),
1382
- index: i + j
1383
- });
1384
- }
1385
- }
1386
- }
1387
- }
1388
- return { successful, failed };
1389
- }
1390
- /**
1391
- * Validates input parameters and strategy compatibility
1392
- * @private
1393
- */
1394
- validateInsertParameters(data, options) {
1395
- const isStream = data instanceof import_node_stream.Readable;
1396
- const strategy = options?.strategy || "fail-fast";
1397
- const shouldValidate = options?.validate !== false;
1398
- if (isStream && strategy === "isolate") {
1399
- throw new Error(
1400
- "The 'isolate' error strategy is not supported with stream input. Use 'fail-fast' or 'discard' instead."
1401
- );
1402
- }
1403
- if (isStream && shouldValidate) {
1404
- console.warn(
1405
- "Validation is not supported with stream input. Validation will be skipped."
1406
- );
1407
- }
1408
- return { isStream, strategy, shouldValidate };
1409
- }
1410
- /**
1411
- * Handles early return cases for empty data
1412
- * @private
1413
- */
1414
- handleEmptyData(data, isStream) {
1415
- if (isStream && !data) {
1416
- return {
1417
- successful: 0,
1418
- failed: 0,
1419
- total: 0
1420
- };
1421
- }
1422
- if (!isStream && (!data || data.length === 0)) {
1423
- return {
1424
- successful: 0,
1425
- failed: 0,
1426
- total: 0
1427
- };
1428
- }
1429
- return null;
1430
- }
1431
- /**
1432
- * Performs pre-insertion validation for array data
1433
- * @private
1434
- */
1435
- async performPreInsertionValidation(data, shouldValidate, strategy, options) {
1436
- if (!shouldValidate) {
1437
- return { validatedData: data, validationErrors: [] };
1438
- }
1439
- try {
1440
- const validationResult = await this.validateRecords(data);
1441
- const validatedData = validationResult.valid;
1442
- const validationErrors = validationResult.invalid;
1443
- if (validationErrors.length > 0) {
1444
- this.handleValidationErrors(validationErrors, strategy, data, options);
1445
- switch (strategy) {
1446
- case "discard":
1447
- return { validatedData, validationErrors };
1448
- case "isolate":
1449
- return { validatedData: data, validationErrors };
1450
- default:
1451
- return { validatedData, validationErrors };
1452
- }
1453
- }
1454
- return { validatedData, validationErrors };
1455
- } catch (validationError) {
1456
- if (strategy === "fail-fast") {
1457
- throw validationError;
1458
- }
1459
- console.warn("Validation error:", validationError);
1460
- return { validatedData: data, validationErrors: [] };
1461
- }
1462
- }
1463
- /**
1464
- * Handles validation errors based on the specified strategy
1465
- * @private
1466
- */
1467
- handleValidationErrors(validationErrors, strategy, data, options) {
1468
- switch (strategy) {
1469
- case "fail-fast":
1470
- const firstError = validationErrors[0];
1471
- throw new Error(
1472
- `Validation failed for record at index ${firstError.index}: ${firstError.error}`
1473
- );
1474
- case "discard":
1475
- this.checkValidationThresholds(validationErrors, data.length, options);
1476
- break;
1477
- case "isolate":
1478
- break;
1479
- }
1480
- }
1481
- /**
1482
- * Checks if validation errors exceed configured thresholds
1483
- * @private
1484
- */
1485
- checkValidationThresholds(validationErrors, totalRecords, options) {
1486
- const validationFailedCount = validationErrors.length;
1487
- const validationFailedRatio = validationFailedCount / totalRecords;
1488
- if (options?.allowErrors !== void 0 && validationFailedCount > options.allowErrors) {
1489
- throw new Error(
1490
- `Too many validation failures: ${validationFailedCount} > ${options.allowErrors}. Errors: ${validationErrors.map((e) => e.error).join(", ")}`
1491
- );
1492
- }
1493
- if (options?.allowErrorsRatio !== void 0 && validationFailedRatio > options.allowErrorsRatio) {
1494
- throw new Error(
1495
- `Validation failure ratio too high: ${validationFailedRatio.toFixed(3)} > ${options.allowErrorsRatio}. Errors: ${validationErrors.map((e) => e.error).join(", ")}`
1496
- );
1497
- }
1498
- }
1499
- /**
1500
- * Optimized insert options preparation with better memory management
1501
- * @private
1502
- */
1503
- prepareInsertOptions(tableName, data, validatedData, isStream, strategy, options) {
1504
- const insertOptions = {
1505
- table: quoteIdentifier(tableName),
1506
- format: "JSONEachRow",
1507
- clickhouse_settings: {
1508
- date_time_input_format: "best_effort",
1509
- wait_end_of_query: 1,
1510
- // Ensure at least once delivery for INSERT operations
1511
- // Performance optimizations
1512
- max_insert_block_size: isStream ? 1e5 : Math.min(validatedData.length, 1e5),
1513
- max_block_size: 65536,
1514
- // Use async inserts for better performance with large datasets
1515
- async_insert: validatedData.length > 1e3 ? 1 : 0,
1516
- wait_for_async_insert: 1
1517
- // For at least once delivery
1518
- }
1519
- };
1520
- if (isStream) {
1521
- insertOptions.values = data;
1522
- } else {
1523
- insertOptions.values = validatedData;
1524
- }
1525
- if (strategy === "discard" && (options?.allowErrors !== void 0 || options?.allowErrorsRatio !== void 0)) {
1526
- if (options.allowErrors !== void 0) {
1527
- insertOptions.clickhouse_settings.input_format_allow_errors_num = options.allowErrors;
1528
- }
1529
- if (options.allowErrorsRatio !== void 0) {
1530
- insertOptions.clickhouse_settings.input_format_allow_errors_ratio = options.allowErrorsRatio;
1531
- }
1532
- }
1533
- return insertOptions;
1534
- }
1535
- /**
1536
- * Creates success result for completed insertions
1537
- * @private
1538
- */
1539
- createSuccessResult(data, validatedData, validationErrors, isStream, shouldValidate, strategy) {
1540
- if (isStream) {
1541
- return {
1542
- successful: -1,
1543
- // -1 indicates stream mode where count is unknown
1544
- failed: 0,
1545
- total: -1
1546
- };
1547
- }
1548
- const insertedCount = validatedData.length;
1549
- const totalProcessed = shouldValidate ? data.length : insertedCount;
1550
- const result = {
1551
- successful: insertedCount,
1552
- failed: shouldValidate ? validationErrors.length : 0,
1553
- total: totalProcessed
1554
- };
1555
- if (shouldValidate && validationErrors.length > 0 && strategy === "discard") {
1556
- result.failedRecords = validationErrors.map((ve) => ({
1557
- record: ve.record,
1558
- error: `Validation error: ${ve.error}`,
1559
- index: ve.index
1560
- }));
1561
- }
1562
- return result;
1563
- }
1564
- /**
1565
- * Handles insertion errors based on the specified strategy
1566
- * @private
1567
- */
1568
- async handleInsertionError(batchError, strategy, tableName, data, validatedData, validationErrors, isStream, shouldValidate, options) {
1569
- switch (strategy) {
1570
- case "fail-fast":
1571
- throw new Error(
1572
- `Failed to insert data into table ${tableName}: ${batchError}`
1573
- );
1574
- case "discard":
1575
- throw new Error(
1576
- `Too many errors during insert into table ${tableName}. Error threshold exceeded: ${batchError}`
1577
- );
1578
- case "isolate":
1579
- return await this.handleIsolateStrategy(
1580
- batchError,
1581
- tableName,
1582
- data,
1583
- validatedData,
1584
- validationErrors,
1585
- isStream,
1586
- shouldValidate,
1587
- options
1588
- );
1589
- default:
1590
- throw new Error(`Unknown error strategy: ${strategy}`);
1591
- }
1592
- }
1593
- /**
1594
- * Handles the isolate strategy for insertion errors
1595
- * @private
1596
- */
1597
- async handleIsolateStrategy(batchError, tableName, data, validatedData, validationErrors, isStream, shouldValidate, options) {
1598
- if (isStream) {
1599
- throw new Error(
1600
- `Isolate strategy is not supported with stream input: ${batchError}`
1601
- );
1602
- }
1603
- try {
1604
- const { client } = await this.getMemoizedClient();
1605
- const skipValidationOnRetry = options?.skipValidationOnRetry || false;
1606
- const retryData = skipValidationOnRetry ? data : validatedData;
1607
- const { successful, failed } = await this.retryIndividualRecords(
1608
- client,
1609
- tableName,
1610
- retryData
1611
- );
1612
- const allFailedRecords = [
1613
- // Validation errors (if any and not skipping validation on retry)
1614
- ...shouldValidate && !skipValidationOnRetry ? validationErrors.map((ve) => ({
1615
- record: ve.record,
1616
- error: `Validation error: ${ve.error}`,
1617
- index: ve.index
1618
- })) : [],
1619
- // Insertion errors
1620
- ...failed
1621
- ];
1622
- this.checkInsertionThresholds(
1623
- allFailedRecords,
1624
- data.length,
1625
- options
1626
- );
1627
- return {
1628
- successful: successful.length,
1629
- failed: allFailedRecords.length,
1630
- total: data.length,
1631
- failedRecords: allFailedRecords
1632
- };
1633
- } catch (isolationError) {
1634
- throw new Error(
1635
- `Failed to insert data into table ${tableName} during record isolation: ${isolationError}`
1636
- );
1637
- }
1638
- }
1639
- /**
1640
- * Checks if insertion errors exceed configured thresholds
1641
- * @private
1642
- */
1643
- checkInsertionThresholds(failedRecords, totalRecords, options) {
1644
- const totalFailed = failedRecords.length;
1645
- const failedRatio = totalFailed / totalRecords;
1646
- if (options?.allowErrors !== void 0 && totalFailed > options.allowErrors) {
1647
- throw new Error(
1648
- `Too many failed records: ${totalFailed} > ${options.allowErrors}. Failed records: ${failedRecords.map((f) => f.error).join(", ")}`
1649
- );
1650
- }
1651
- if (options?.allowErrorsRatio !== void 0 && failedRatio > options.allowErrorsRatio) {
1652
- throw new Error(
1653
- `Failed record ratio too high: ${failedRatio.toFixed(3)} > ${options.allowErrorsRatio}. Failed records: ${failedRecords.map((f) => f.error).join(", ")}`
1654
- );
1655
- }
1656
- }
1657
- /**
1658
- * Recursively transforms a record to match ClickHouse's JSONEachRow requirements
1659
- *
1660
- * - For every Array(Nested(...)) field at any depth, each item is wrapped in its own array and recursively processed.
1661
- * - For every Nested struct (not array), it recurses into the struct.
1662
- * - This ensures compatibility with kafka_clickhouse_sync
1663
- *
1664
- * @param record The input record to transform (may be deeply nested)
1665
- * @param columns The schema columns for this level (defaults to this.columnArray at the top level)
1666
- * @returns The transformed record, ready for ClickHouse JSONEachRow insertion
1667
- */
1668
- mapToClickhouseRecord(record, columns = this.columnArray) {
1669
- const result = { ...record };
1670
- for (const col of columns) {
1671
- const value = record[col.name];
1672
- const dt = col.data_type;
1673
- if (isArrayNestedType(dt)) {
1674
- if (Array.isArray(value) && (value.length === 0 || typeof value[0] === "object")) {
1675
- result[col.name] = value.map((item) => [
1676
- this.mapToClickhouseRecord(item, dt.elementType.columns)
1677
- ]);
1678
- }
1679
- } else if (isNestedType(dt)) {
1680
- if (value && typeof value === "object") {
1681
- result[col.name] = this.mapToClickhouseRecord(value, dt.columns);
1682
- }
1683
- }
1684
- }
1685
- return result;
1686
- }
1687
- /**
1688
- * Inserts data directly into the ClickHouse table with enhanced error handling and validation.
1689
- * This method establishes a direct connection to ClickHouse using the project configuration
1690
- * and inserts the provided data into the versioned table.
1691
- *
1692
- * PERFORMANCE OPTIMIZATIONS:
1693
- * - Memoized client connections with fast config hashing
1694
- * - Single-pass validation with pre-allocated arrays
1695
- * - Batch-optimized retry strategy (batches of 10, then individual)
1696
- * - Optimized ClickHouse settings for large datasets
1697
- * - Reduced memory allocations and object creation
1698
- *
1699
- * Uses advanced typia validation when available for comprehensive type checking,
1700
- * with fallback to basic validation for compatibility.
1701
- *
1702
- * The ClickHouse client is memoized and reused across multiple insert calls for better performance.
1703
- * If the configuration changes, a new client will be automatically created.
1704
- *
1705
- * @param data Array of objects conforming to the table schema, or a Node.js Readable stream
1706
- * @param options Optional configuration for error handling, validation, and insertion behavior
1707
- * @returns Promise resolving to detailed insertion results
1708
- * @throws {ConfigError} When configuration cannot be read or parsed
1709
- * @throws {ClickHouseError} When insertion fails based on the error strategy
1710
- * @throws {ValidationError} When validation fails and strategy is 'fail-fast'
1711
- *
1712
- * @example
1713
- * ```typescript
1714
- * // Create an OlapTable instance (typia validators auto-injected)
1715
- * const userTable = new OlapTable<User>('users');
1716
- *
1717
- * // Insert with comprehensive typia validation
1718
- * const result1 = await userTable.insert([
1719
- * { id: 1, name: 'John', email: 'john@example.com' },
1720
- * { id: 2, name: 'Jane', email: 'jane@example.com' }
1721
- * ]);
1722
- *
1723
- * // Insert data with stream input (validation not available for streams)
1724
- * const dataStream = new Readable({
1725
- * objectMode: true,
1726
- * read() { // Stream implementation }
1727
- * });
1728
- * const result2 = await userTable.insert(dataStream, { strategy: 'fail-fast' });
1729
- *
1730
- * // Insert with validation disabled for performance
1731
- * const result3 = await userTable.insert(data, { validate: false });
1732
- *
1733
- * // Insert with error handling strategies
1734
- * const result4 = await userTable.insert(mixedData, {
1735
- * strategy: 'isolate',
1736
- * allowErrorsRatio: 0.1,
1737
- * validate: true // Use typia validation (default)
1738
- * });
1739
- *
1740
- * // Optional: Clean up connection when completely done
1741
- * await userTable.closeClient();
1742
- * ```
1743
- */
1744
- async insert(data, options) {
1745
- const { isStream, strategy, shouldValidate } = this.validateInsertParameters(data, options);
1746
- const emptyResult = this.handleEmptyData(data, isStream);
1747
- if (emptyResult) {
1748
- return emptyResult;
1749
- }
1750
- let validatedData = [];
1751
- let validationErrors = [];
1752
- if (!isStream && shouldValidate) {
1753
- const validationResult = await this.performPreInsertionValidation(
1754
- data,
1755
- shouldValidate,
1756
- strategy,
1757
- options
1758
- );
1759
- validatedData = validationResult.validatedData;
1760
- validationErrors = validationResult.validationErrors;
1761
- } else {
1762
- validatedData = isStream ? [] : data;
1763
- }
1764
- const { client } = await this.getMemoizedClient();
1765
- const tableName = this.generateTableName();
1766
- try {
1767
- const insertOptions = this.prepareInsertOptions(
1768
- tableName,
1769
- data,
1770
- validatedData,
1771
- isStream,
1772
- strategy,
1773
- options
1774
- );
1775
- await client.insert(insertOptions);
1776
- return this.createSuccessResult(
1777
- data,
1778
- validatedData,
1779
- validationErrors,
1780
- isStream,
1781
- shouldValidate,
1782
- strategy
1783
- );
1784
- } catch (batchError) {
1785
- return await this.handleInsertionError(
1786
- batchError,
1787
- strategy,
1788
- tableName,
1789
- data,
1790
- validatedData,
1791
- validationErrors,
1792
- isStream,
1793
- shouldValidate,
1794
- options
1795
- );
1241
+ successful.push(record);
1242
+ } catch (error) {
1243
+ failed.push({
1244
+ record,
1245
+ error: error instanceof Error ? error.message : String(error),
1246
+ index: i + j
1247
+ });
1248
+ }
1796
1249
  }
1797
1250
  }
1798
- // Note: Static factory methods (withS3Queue, withReplacingMergeTree, withMergeTree)
1799
- // were removed in ENG-856. Use direct configuration instead, e.g.:
1800
- // new OlapTable(name, { engine: ClickHouseEngines.ReplacingMergeTree, orderByFields: ["id"], ver: "updated_at" })
1801
- };
1251
+ }
1252
+ return { successful, failed };
1802
1253
  }
1803
- });
1804
-
1805
- // src/dmv2/sdk/stream.ts
1806
- function attachTypeGuard(dl, typeGuard) {
1807
- dl.asTyped = () => typeGuard(dl.originalRecord);
1808
- }
1809
- var import_node_crypto3, RoutedMessage, Stream, DeadLetterQueue;
1810
- var init_stream = __esm({
1811
- "src/dmv2/sdk/stream.ts"() {
1812
- "use strict";
1813
- init_typedBase();
1814
- init_internal();
1815
- import_node_crypto3 = require("crypto");
1816
- init_stackTrace();
1817
- RoutedMessage = class {
1818
- /** The destination stream for the message */
1819
- destination;
1820
- /** The message value(s) to send */
1821
- values;
1822
- /**
1823
- * Creates a new routed message.
1824
- *
1825
- * @param destination The target stream
1826
- * @param values The message(s) to route
1827
- */
1828
- constructor(destination, values) {
1829
- this.destination = destination;
1830
- this.values = values;
1831
- }
1832
- };
1833
- Stream = class extends TypedBase {
1834
- defaultDeadLetterQueue;
1835
- /** @internal Memoized KafkaJS producer for reusing connections across sends */
1836
- _memoizedProducer;
1837
- /** @internal Hash of the configuration used to create the memoized Kafka producer */
1838
- _kafkaConfigHash;
1839
- constructor(name, config, schema, columns, validators, allowExtraFields) {
1840
- super(name, config ?? {}, schema, columns, void 0, allowExtraFields);
1841
- const streams = getMooseInternal().streams;
1842
- if (streams.has(name)) {
1843
- throw new Error(`Stream with name ${name} already exists`);
1254
+ /**
1255
+ * Validates input parameters and strategy compatibility
1256
+ * @private
1257
+ */
1258
+ validateInsertParameters(data, options) {
1259
+ const isStream = data instanceof import_node_stream.Readable;
1260
+ const strategy = options?.strategy || "fail-fast";
1261
+ const shouldValidate = options?.validate !== false;
1262
+ if (isStream && strategy === "isolate") {
1263
+ throw new Error(
1264
+ "The 'isolate' error strategy is not supported with stream input. Use 'fail-fast' or 'discard' instead."
1265
+ );
1266
+ }
1267
+ if (isStream && shouldValidate) {
1268
+ console.warn(
1269
+ "Validation is not supported with stream input. Validation will be skipped."
1270
+ );
1271
+ }
1272
+ return { isStream, strategy, shouldValidate };
1273
+ }
1274
+ /**
1275
+ * Handles early return cases for empty data
1276
+ * @private
1277
+ */
1278
+ handleEmptyData(data, isStream) {
1279
+ if (isStream && !data) {
1280
+ return {
1281
+ successful: 0,
1282
+ failed: 0,
1283
+ total: 0
1284
+ };
1285
+ }
1286
+ if (!isStream && (!data || data.length === 0)) {
1287
+ return {
1288
+ successful: 0,
1289
+ failed: 0,
1290
+ total: 0
1291
+ };
1292
+ }
1293
+ return null;
1294
+ }
1295
+ /**
1296
+ * Performs pre-insertion validation for array data
1297
+ * @private
1298
+ */
1299
+ async performPreInsertionValidation(data, shouldValidate, strategy, options) {
1300
+ if (!shouldValidate) {
1301
+ return { validatedData: data, validationErrors: [] };
1302
+ }
1303
+ try {
1304
+ const validationResult = await this.validateRecords(data);
1305
+ const validatedData = validationResult.valid;
1306
+ const validationErrors = validationResult.invalid;
1307
+ if (validationErrors.length > 0) {
1308
+ this.handleValidationErrors(validationErrors, strategy, data, options);
1309
+ switch (strategy) {
1310
+ case "discard":
1311
+ return { validatedData, validationErrors };
1312
+ case "isolate":
1313
+ return { validatedData: data, validationErrors };
1314
+ default:
1315
+ return { validatedData, validationErrors };
1844
1316
  }
1845
- streams.set(name, this);
1846
- this.defaultDeadLetterQueue = this.config.defaultDeadLetterQueue;
1847
- }
1848
- /**
1849
- * Internal map storing transformation configurations.
1850
- * Maps destination stream names to arrays of transformation functions and their configs.
1851
- *
1852
- * @internal
1853
- */
1854
- _transformations = /* @__PURE__ */ new Map();
1855
- /**
1856
- * Internal function for multi-stream transformations.
1857
- * Allows a single transformation to route messages to multiple destinations.
1858
- *
1859
- * @internal
1860
- */
1861
- _multipleTransformations;
1862
- /**
1863
- * Internal array storing consumer configurations.
1864
- *
1865
- * @internal
1866
- */
1867
- _consumers = new Array();
1868
- /**
1869
- * Builds the full Kafka topic name including optional namespace and version suffix.
1870
- * Version suffix is appended as _x_y_z where dots in version are replaced with underscores.
1871
- */
1872
- buildFullTopicName(namespace) {
1873
- const versionSuffix = this.config.version ? `_${this.config.version.replace(/\./g, "_")}` : "";
1874
- const base = `${this.name}${versionSuffix}`;
1875
- return namespace !== void 0 && namespace.length > 0 ? `${namespace}.${base}` : base;
1876
1317
  }
1877
- /**
1878
- * Creates a fast hash string from relevant Kafka configuration fields.
1879
- */
1880
- createConfigHash(kafkaConfig) {
1881
- const configString = [
1882
- kafkaConfig.broker,
1883
- kafkaConfig.messageTimeoutMs,
1884
- kafkaConfig.saslUsername,
1885
- kafkaConfig.saslPassword,
1886
- kafkaConfig.saslMechanism,
1887
- kafkaConfig.securityProtocol,
1888
- kafkaConfig.namespace
1889
- ].join(":");
1890
- return (0, import_node_crypto3.createHash)("sha256").update(configString).digest("hex").substring(0, 16);
1318
+ return { validatedData, validationErrors };
1319
+ } catch (validationError) {
1320
+ if (strategy === "fail-fast") {
1321
+ throw validationError;
1891
1322
  }
1892
- /**
1893
- * Gets or creates a memoized KafkaJS producer using runtime configuration.
1894
- */
1895
- async getMemoizedProducer() {
1896
- await Promise.resolve().then(() => (init_runtime(), runtime_exports));
1897
- const configRegistry = globalThis._mooseConfigRegistry;
1898
- const { getKafkaProducer: getKafkaProducer2 } = await Promise.resolve().then(() => (init_commons(), commons_exports));
1899
- const kafkaConfig = await configRegistry.getKafkaConfig();
1900
- const currentHash = this.createConfigHash(kafkaConfig);
1901
- if (this._memoizedProducer && this._kafkaConfigHash === currentHash) {
1902
- return { producer: this._memoizedProducer, kafkaConfig };
1903
- }
1904
- if (this._memoizedProducer && this._kafkaConfigHash !== currentHash) {
1905
- try {
1906
- await this._memoizedProducer.disconnect();
1907
- } catch {
1908
- }
1909
- this._memoizedProducer = void 0;
1910
- }
1911
- const clientId = `moose-sdk-stream-${this.name}`;
1912
- const logger = {
1913
- logPrefix: clientId,
1914
- log: (message) => {
1915
- console.log(`${clientId}: ${message}`);
1916
- },
1917
- error: (message) => {
1918
- console.error(`${clientId}: ${message}`);
1919
- },
1920
- warn: (message) => {
1921
- console.warn(`${clientId}: ${message}`);
1922
- }
1923
- };
1924
- const producer = await getKafkaProducer2(
1925
- {
1926
- clientId,
1927
- broker: kafkaConfig.broker,
1928
- securityProtocol: kafkaConfig.securityProtocol,
1929
- saslUsername: kafkaConfig.saslUsername,
1930
- saslPassword: kafkaConfig.saslPassword,
1931
- saslMechanism: kafkaConfig.saslMechanism
1932
- },
1933
- logger
1323
+ console.warn("Validation error:", validationError);
1324
+ return { validatedData: data, validationErrors: [] };
1325
+ }
1326
+ }
1327
+ /**
1328
+ * Handles validation errors based on the specified strategy
1329
+ * @private
1330
+ */
1331
+ handleValidationErrors(validationErrors, strategy, data, options) {
1332
+ switch (strategy) {
1333
+ case "fail-fast":
1334
+ const firstError = validationErrors[0];
1335
+ throw new Error(
1336
+ `Validation failed for record at index ${firstError.index}: ${firstError.error}`
1934
1337
  );
1935
- this._memoizedProducer = producer;
1936
- this._kafkaConfigHash = currentHash;
1937
- return { producer, kafkaConfig };
1338
+ case "discard":
1339
+ this.checkValidationThresholds(validationErrors, data.length, options);
1340
+ break;
1341
+ case "isolate":
1342
+ break;
1343
+ }
1344
+ }
1345
+ /**
1346
+ * Checks if validation errors exceed configured thresholds
1347
+ * @private
1348
+ */
1349
+ checkValidationThresholds(validationErrors, totalRecords, options) {
1350
+ const validationFailedCount = validationErrors.length;
1351
+ const validationFailedRatio = validationFailedCount / totalRecords;
1352
+ if (options?.allowErrors !== void 0 && validationFailedCount > options.allowErrors) {
1353
+ throw new Error(
1354
+ `Too many validation failures: ${validationFailedCount} > ${options.allowErrors}. Errors: ${validationErrors.map((e) => e.error).join(", ")}`
1355
+ );
1356
+ }
1357
+ if (options?.allowErrorsRatio !== void 0 && validationFailedRatio > options.allowErrorsRatio) {
1358
+ throw new Error(
1359
+ `Validation failure ratio too high: ${validationFailedRatio.toFixed(3)} > ${options.allowErrorsRatio}. Errors: ${validationErrors.map((e) => e.error).join(", ")}`
1360
+ );
1361
+ }
1362
+ }
1363
+ /**
1364
+ * Optimized insert options preparation with better memory management
1365
+ * @private
1366
+ */
1367
+ prepareInsertOptions(tableName, data, validatedData, isStream, strategy, options) {
1368
+ const insertOptions = {
1369
+ table: quoteIdentifier(tableName),
1370
+ format: "JSONEachRow",
1371
+ clickhouse_settings: {
1372
+ date_time_input_format: "best_effort",
1373
+ wait_end_of_query: 1,
1374
+ // Ensure at least once delivery for INSERT operations
1375
+ // Performance optimizations
1376
+ max_insert_block_size: isStream ? 1e5 : Math.min(validatedData.length, 1e5),
1377
+ max_block_size: 65536,
1378
+ // Use async inserts for better performance with large datasets
1379
+ async_insert: validatedData.length > 1e3 ? 1 : 0,
1380
+ wait_for_async_insert: 1
1381
+ // For at least once delivery
1938
1382
  }
1939
- /**
1940
- * Closes the memoized Kafka producer if it exists.
1941
- */
1942
- async closeProducer() {
1943
- if (this._memoizedProducer) {
1944
- try {
1945
- await this._memoizedProducer.disconnect();
1946
- } catch {
1947
- } finally {
1948
- this._memoizedProducer = void 0;
1949
- this._kafkaConfigHash = void 0;
1950
- }
1951
- }
1383
+ };
1384
+ if (isStream) {
1385
+ insertOptions.values = data;
1386
+ } else {
1387
+ insertOptions.values = validatedData;
1388
+ }
1389
+ if (strategy === "discard" && (options?.allowErrors !== void 0 || options?.allowErrorsRatio !== void 0)) {
1390
+ if (options.allowErrors !== void 0) {
1391
+ insertOptions.clickhouse_settings.input_format_allow_errors_num = options.allowErrors;
1952
1392
  }
1953
- /**
1954
- * Sends one or more records to this stream's Kafka topic.
1955
- * Values are JSON-serialized as message values.
1956
- */
1957
- async send(values) {
1958
- const flat = Array.isArray(values) ? values : values !== void 0 && values !== null ? [values] : [];
1959
- if (flat.length === 0) return;
1960
- const { producer, kafkaConfig } = await this.getMemoizedProducer();
1961
- const topic = this.buildFullTopicName(kafkaConfig.namespace);
1962
- const sr = this.config.schemaConfig;
1963
- if (sr && sr.kind === "JSON") {
1964
- const schemaRegistryUrl = kafkaConfig.schemaRegistryUrl;
1965
- if (!schemaRegistryUrl) {
1966
- throw new Error("Schema Registry URL not configured");
1967
- }
1968
- const {
1969
- default: { SchemaRegistry }
1970
- } = await import("@kafkajs/confluent-schema-registry");
1971
- const registry = new SchemaRegistry({ host: schemaRegistryUrl });
1972
- let schemaId = void 0;
1973
- if ("id" in sr.reference) {
1974
- schemaId = sr.reference.id;
1975
- } else if ("subjectLatest" in sr.reference) {
1976
- schemaId = await registry.getLatestSchemaId(sr.reference.subjectLatest);
1977
- } else if ("subject" in sr.reference) {
1978
- schemaId = await registry.getRegistryId(
1979
- sr.reference.subject,
1980
- sr.reference.version
1981
- );
1982
- }
1983
- if (schemaId === void 0) {
1984
- throw new Error("Malformed schema reference.");
1985
- }
1986
- const encoded = await Promise.all(
1987
- flat.map(
1988
- (v) => registry.encode(schemaId, v)
1989
- )
1990
- );
1991
- await producer.send({
1992
- topic,
1993
- messages: encoded.map((value) => ({ value }))
1994
- });
1995
- return;
1996
- } else if (sr !== void 0) {
1997
- throw new Error("Currently only JSON Schema is supported.");
1998
- }
1999
- await producer.send({
2000
- topic,
2001
- messages: flat.map((v) => ({ value: JSON.stringify(v) }))
2002
- });
1393
+ if (options.allowErrorsRatio !== void 0) {
1394
+ insertOptions.clickhouse_settings.input_format_allow_errors_ratio = options.allowErrorsRatio;
2003
1395
  }
2004
- /**
2005
- * Adds a transformation step that processes messages from this stream and sends the results to a destination stream.
2006
- * Multiple transformations to the same destination stream can be added if they have distinct `version` identifiers in their config.
2007
- *
2008
- * @template U The data type of the messages in the destination stream.
2009
- * @param destination The destination stream for the transformed messages.
2010
- * @param transformation A function that takes a message of type T and returns zero or more messages of type U (or a Promise thereof).
2011
- * Return `null` or `undefined` or an empty array `[]` to filter out a message. Return an array to emit multiple messages.
2012
- * @param config Optional configuration for this specific transformation step, like a version.
2013
- */
2014
- addTransform(destination, transformation, config) {
2015
- const sourceFile = getSourceFileFromStack(new Error().stack);
2016
- const transformConfig = {
2017
- ...config ?? {},
2018
- sourceFile
2019
- };
2020
- if (transformConfig.deadLetterQueue === void 0) {
2021
- transformConfig.deadLetterQueue = this.defaultDeadLetterQueue;
2022
- }
2023
- if (this._transformations.has(destination.name)) {
2024
- const existingTransforms = this._transformations.get(destination.name);
2025
- const hasVersion = existingTransforms.some(
2026
- ([_, __, cfg]) => cfg.version === transformConfig.version
2027
- );
2028
- if (!hasVersion) {
2029
- existingTransforms.push([destination, transformation, transformConfig]);
2030
- }
2031
- } else {
2032
- this._transformations.set(destination.name, [
2033
- [destination, transformation, transformConfig]
1396
+ }
1397
+ return insertOptions;
1398
+ }
1399
+ /**
1400
+ * Creates success result for completed insertions
1401
+ * @private
1402
+ */
1403
+ createSuccessResult(data, validatedData, validationErrors, isStream, shouldValidate, strategy) {
1404
+ if (isStream) {
1405
+ return {
1406
+ successful: -1,
1407
+ // -1 indicates stream mode where count is unknown
1408
+ failed: 0,
1409
+ total: -1
1410
+ };
1411
+ }
1412
+ const insertedCount = validatedData.length;
1413
+ const totalProcessed = shouldValidate ? data.length : insertedCount;
1414
+ const result = {
1415
+ successful: insertedCount,
1416
+ failed: shouldValidate ? validationErrors.length : 0,
1417
+ total: totalProcessed
1418
+ };
1419
+ if (shouldValidate && validationErrors.length > 0 && strategy === "discard") {
1420
+ result.failedRecords = validationErrors.map((ve) => ({
1421
+ record: ve.record,
1422
+ error: `Validation error: ${ve.error}`,
1423
+ index: ve.index
1424
+ }));
1425
+ }
1426
+ return result;
1427
+ }
1428
+ /**
1429
+ * Handles insertion errors based on the specified strategy
1430
+ * @private
1431
+ */
1432
+ async handleInsertionError(batchError, strategy, tableName, data, validatedData, validationErrors, isStream, shouldValidate, options) {
1433
+ switch (strategy) {
1434
+ case "fail-fast":
1435
+ throw new Error(
1436
+ `Failed to insert data into table ${tableName}: ${batchError}`
1437
+ );
1438
+ case "discard":
1439
+ throw new Error(
1440
+ `Too many errors during insert into table ${tableName}. Error threshold exceeded: ${batchError}`
1441
+ );
1442
+ case "isolate":
1443
+ return await this.handleIsolateStrategy(
1444
+ batchError,
1445
+ tableName,
1446
+ data,
1447
+ validatedData,
1448
+ validationErrors,
1449
+ isStream,
1450
+ shouldValidate,
1451
+ options
1452
+ );
1453
+ default:
1454
+ throw new Error(`Unknown error strategy: ${strategy}`);
1455
+ }
1456
+ }
1457
+ /**
1458
+ * Handles the isolate strategy for insertion errors
1459
+ * @private
1460
+ */
1461
+ async handleIsolateStrategy(batchError, tableName, data, validatedData, validationErrors, isStream, shouldValidate, options) {
1462
+ if (isStream) {
1463
+ throw new Error(
1464
+ `Isolate strategy is not supported with stream input: ${batchError}`
1465
+ );
1466
+ }
1467
+ try {
1468
+ const { client } = await this.getMemoizedClient();
1469
+ const skipValidationOnRetry = options?.skipValidationOnRetry || false;
1470
+ const retryData = skipValidationOnRetry ? data : validatedData;
1471
+ const { successful, failed } = await this.retryIndividualRecords(
1472
+ client,
1473
+ tableName,
1474
+ retryData
1475
+ );
1476
+ const allFailedRecords = [
1477
+ // Validation errors (if any and not skipping validation on retry)
1478
+ ...shouldValidate && !skipValidationOnRetry ? validationErrors.map((ve) => ({
1479
+ record: ve.record,
1480
+ error: `Validation error: ${ve.error}`,
1481
+ index: ve.index
1482
+ })) : [],
1483
+ // Insertion errors
1484
+ ...failed
1485
+ ];
1486
+ this.checkInsertionThresholds(
1487
+ allFailedRecords,
1488
+ data.length,
1489
+ options
1490
+ );
1491
+ return {
1492
+ successful: successful.length,
1493
+ failed: allFailedRecords.length,
1494
+ total: data.length,
1495
+ failedRecords: allFailedRecords
1496
+ };
1497
+ } catch (isolationError) {
1498
+ throw new Error(
1499
+ `Failed to insert data into table ${tableName} during record isolation: ${isolationError}`
1500
+ );
1501
+ }
1502
+ }
1503
+ /**
1504
+ * Checks if insertion errors exceed configured thresholds
1505
+ * @private
1506
+ */
1507
+ checkInsertionThresholds(failedRecords, totalRecords, options) {
1508
+ const totalFailed = failedRecords.length;
1509
+ const failedRatio = totalFailed / totalRecords;
1510
+ if (options?.allowErrors !== void 0 && totalFailed > options.allowErrors) {
1511
+ throw new Error(
1512
+ `Too many failed records: ${totalFailed} > ${options.allowErrors}. Failed records: ${failedRecords.map((f) => f.error).join(", ")}`
1513
+ );
1514
+ }
1515
+ if (options?.allowErrorsRatio !== void 0 && failedRatio > options.allowErrorsRatio) {
1516
+ throw new Error(
1517
+ `Failed record ratio too high: ${failedRatio.toFixed(3)} > ${options.allowErrorsRatio}. Failed records: ${failedRecords.map((f) => f.error).join(", ")}`
1518
+ );
1519
+ }
1520
+ }
1521
+ /**
1522
+ * Recursively transforms a record to match ClickHouse's JSONEachRow requirements
1523
+ *
1524
+ * - For every Array(Nested(...)) field at any depth, each item is wrapped in its own array and recursively processed.
1525
+ * - For every Nested struct (not array), it recurses into the struct.
1526
+ * - This ensures compatibility with kafka_clickhouse_sync
1527
+ *
1528
+ * @param record The input record to transform (may be deeply nested)
1529
+ * @param columns The schema columns for this level (defaults to this.columnArray at the top level)
1530
+ * @returns The transformed record, ready for ClickHouse JSONEachRow insertion
1531
+ */
1532
+ mapToClickhouseRecord(record, columns = this.columnArray) {
1533
+ const result = { ...record };
1534
+ for (const col of columns) {
1535
+ const value = record[col.name];
1536
+ const dt = col.data_type;
1537
+ if (isArrayNestedType(dt)) {
1538
+ if (Array.isArray(value) && (value.length === 0 || typeof value[0] === "object")) {
1539
+ result[col.name] = value.map((item) => [
1540
+ this.mapToClickhouseRecord(item, dt.elementType.columns)
2034
1541
  ]);
2035
1542
  }
2036
- }
2037
- /**
2038
- * Adds a consumer function that processes messages from this stream.
2039
- * Multiple consumers can be added if they have distinct `version` identifiers in their config.
2040
- *
2041
- * @param consumer A function that takes a message of type T and performs an action (e.g., side effect, logging). Should return void or Promise<void>.
2042
- * @param config Optional configuration for this specific consumer, like a version.
2043
- */
2044
- addConsumer(consumer, config) {
2045
- const sourceFile = getSourceFileFromStack(new Error().stack);
2046
- const consumerConfig = {
2047
- ...config ?? {},
2048
- sourceFile
2049
- };
2050
- if (consumerConfig.deadLetterQueue === void 0) {
2051
- consumerConfig.deadLetterQueue = this.defaultDeadLetterQueue;
2052
- }
2053
- const hasVersion = this._consumers.some(
2054
- (existing) => existing.config.version === consumerConfig.version
2055
- );
2056
- if (!hasVersion) {
2057
- this._consumers.push({ consumer, config: consumerConfig });
1543
+ } else if (isNestedType(dt)) {
1544
+ if (value && typeof value === "object") {
1545
+ result[col.name] = this.mapToClickhouseRecord(value, dt.columns);
2058
1546
  }
2059
1547
  }
2060
- /**
2061
- * Helper method for `addMultiTransform` to specify the destination and values for a routed message.
2062
- * @param values The value or values to send to this stream.
2063
- * @returns A `RoutedMessage` object associating the values with this stream.
2064
- *
2065
- * @example
2066
- * ```typescript
2067
- * sourceStream.addMultiTransform((record) => [
2068
- * destinationStream1.routed(transformedRecord1),
2069
- * destinationStream2.routed([record2a, record2b])
2070
- * ]);
2071
- * ```
2072
- */
2073
- routed = (values) => new RoutedMessage(this, values);
2074
- /**
2075
- * Adds a single transformation function that can route messages to multiple destination streams.
2076
- * This is an alternative to adding multiple individual `addTransform` calls.
2077
- * Only one multi-transform function can be added per stream.
2078
- *
2079
- * @param transformation A function that takes a message of type T and returns an array of `RoutedMessage` objects,
2080
- * each specifying a destination stream and the message(s) to send to it.
2081
- */
2082
- addMultiTransform(transformation) {
2083
- this._multipleTransformations = transformation;
1548
+ }
1549
+ return result;
1550
+ }
1551
+ /**
1552
+ * Inserts data directly into the ClickHouse table with enhanced error handling and validation.
1553
+ * This method establishes a direct connection to ClickHouse using the project configuration
1554
+ * and inserts the provided data into the versioned table.
1555
+ *
1556
+ * PERFORMANCE OPTIMIZATIONS:
1557
+ * - Memoized client connections with fast config hashing
1558
+ * - Single-pass validation with pre-allocated arrays
1559
+ * - Batch-optimized retry strategy (batches of 10, then individual)
1560
+ * - Optimized ClickHouse settings for large datasets
1561
+ * - Reduced memory allocations and object creation
1562
+ *
1563
+ * Uses advanced typia validation when available for comprehensive type checking,
1564
+ * with fallback to basic validation for compatibility.
1565
+ *
1566
+ * The ClickHouse client is memoized and reused across multiple insert calls for better performance.
1567
+ * If the configuration changes, a new client will be automatically created.
1568
+ *
1569
+ * @param data Array of objects conforming to the table schema, or a Node.js Readable stream
1570
+ * @param options Optional configuration for error handling, validation, and insertion behavior
1571
+ * @returns Promise resolving to detailed insertion results
1572
+ * @throws {ConfigError} When configuration cannot be read or parsed
1573
+ * @throws {ClickHouseError} When insertion fails based on the error strategy
1574
+ * @throws {ValidationError} When validation fails and strategy is 'fail-fast'
1575
+ *
1576
+ * @example
1577
+ * ```typescript
1578
+ * // Create an OlapTable instance (typia validators auto-injected)
1579
+ * const userTable = new OlapTable<User>('users');
1580
+ *
1581
+ * // Insert with comprehensive typia validation
1582
+ * const result1 = await userTable.insert([
1583
+ * { id: 1, name: 'John', email: 'john@example.com' },
1584
+ * { id: 2, name: 'Jane', email: 'jane@example.com' }
1585
+ * ]);
1586
+ *
1587
+ * // Insert data with stream input (validation not available for streams)
1588
+ * const dataStream = new Readable({
1589
+ * objectMode: true,
1590
+ * read() { // Stream implementation }
1591
+ * });
1592
+ * const result2 = await userTable.insert(dataStream, { strategy: 'fail-fast' });
1593
+ *
1594
+ * // Insert with validation disabled for performance
1595
+ * const result3 = await userTable.insert(data, { validate: false });
1596
+ *
1597
+ * // Insert with error handling strategies
1598
+ * const result4 = await userTable.insert(mixedData, {
1599
+ * strategy: 'isolate',
1600
+ * allowErrorsRatio: 0.1,
1601
+ * validate: true // Use typia validation (default)
1602
+ * });
1603
+ *
1604
+ * // Optional: Clean up connection when completely done
1605
+ * await userTable.closeClient();
1606
+ * ```
1607
+ */
1608
+ async insert(data, options) {
1609
+ const { isStream, strategy, shouldValidate } = this.validateInsertParameters(data, options);
1610
+ const emptyResult = this.handleEmptyData(data, isStream);
1611
+ if (emptyResult) {
1612
+ return emptyResult;
1613
+ }
1614
+ let validatedData = [];
1615
+ let validationErrors = [];
1616
+ if (!isStream && shouldValidate) {
1617
+ const validationResult = await this.performPreInsertionValidation(
1618
+ data,
1619
+ shouldValidate,
1620
+ strategy,
1621
+ options
1622
+ );
1623
+ validatedData = validationResult.validatedData;
1624
+ validationErrors = validationResult.validationErrors;
1625
+ } else {
1626
+ validatedData = isStream ? [] : data;
1627
+ }
1628
+ const { client } = await this.getMemoizedClient();
1629
+ const tableName = this.generateTableName();
1630
+ try {
1631
+ const insertOptions = this.prepareInsertOptions(
1632
+ tableName,
1633
+ data,
1634
+ validatedData,
1635
+ isStream,
1636
+ strategy,
1637
+ options
1638
+ );
1639
+ await client.insert(insertOptions);
1640
+ return this.createSuccessResult(
1641
+ data,
1642
+ validatedData,
1643
+ validationErrors,
1644
+ isStream,
1645
+ shouldValidate,
1646
+ strategy
1647
+ );
1648
+ } catch (batchError) {
1649
+ return await this.handleInsertionError(
1650
+ batchError,
1651
+ strategy,
1652
+ tableName,
1653
+ data,
1654
+ validatedData,
1655
+ validationErrors,
1656
+ isStream,
1657
+ shouldValidate,
1658
+ options
1659
+ );
1660
+ }
1661
+ }
1662
+ // Note: Static factory methods (withS3Queue, withReplacingMergeTree, withMergeTree)
1663
+ // were removed in ENG-856. Use direct configuration instead, e.g.:
1664
+ // new OlapTable(name, { engine: ClickHouseEngines.ReplacingMergeTree, orderByFields: ["id"], ver: "updated_at" })
1665
+ };
1666
+
1667
+ // src/dmv2/sdk/stream.ts
1668
+ var import_node_crypto3 = require("crypto");
1669
+ var RoutedMessage = class {
1670
+ /** The destination stream for the message */
1671
+ destination;
1672
+ /** The message value(s) to send */
1673
+ values;
1674
+ /**
1675
+ * Creates a new routed message.
1676
+ *
1677
+ * @param destination The target stream
1678
+ * @param values The message(s) to route
1679
+ */
1680
+ constructor(destination, values) {
1681
+ this.destination = destination;
1682
+ this.values = values;
1683
+ }
1684
+ };
1685
+ var Stream = class extends TypedBase {
1686
+ defaultDeadLetterQueue;
1687
+ /** @internal Memoized KafkaJS producer for reusing connections across sends */
1688
+ _memoizedProducer;
1689
+ /** @internal Hash of the configuration used to create the memoized Kafka producer */
1690
+ _kafkaConfigHash;
1691
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
1692
+ super(name, config ?? {}, schema, columns, void 0, allowExtraFields);
1693
+ const streams = getMooseInternal().streams;
1694
+ if (streams.has(name)) {
1695
+ throw new Error(`Stream with name ${name} already exists`);
1696
+ }
1697
+ streams.set(name, this);
1698
+ this.defaultDeadLetterQueue = this.config.defaultDeadLetterQueue;
1699
+ }
1700
+ /**
1701
+ * Internal map storing transformation configurations.
1702
+ * Maps destination stream names to arrays of transformation functions and their configs.
1703
+ *
1704
+ * @internal
1705
+ */
1706
+ _transformations = /* @__PURE__ */ new Map();
1707
+ /**
1708
+ * Internal function for multi-stream transformations.
1709
+ * Allows a single transformation to route messages to multiple destinations.
1710
+ *
1711
+ * @internal
1712
+ */
1713
+ _multipleTransformations;
1714
+ /**
1715
+ * Internal array storing consumer configurations.
1716
+ *
1717
+ * @internal
1718
+ */
1719
+ _consumers = new Array();
1720
+ /**
1721
+ * Builds the full Kafka topic name including optional namespace and version suffix.
1722
+ * Version suffix is appended as _x_y_z where dots in version are replaced with underscores.
1723
+ */
1724
+ buildFullTopicName(namespace) {
1725
+ const versionSuffix = this.config.version ? `_${this.config.version.replace(/\./g, "_")}` : "";
1726
+ const base = `${this.name}${versionSuffix}`;
1727
+ return namespace !== void 0 && namespace.length > 0 ? `${namespace}.${base}` : base;
1728
+ }
1729
+ /**
1730
+ * Creates a fast hash string from relevant Kafka configuration fields.
1731
+ */
1732
+ createConfigHash(kafkaConfig) {
1733
+ const configString = [
1734
+ kafkaConfig.broker,
1735
+ kafkaConfig.messageTimeoutMs,
1736
+ kafkaConfig.saslUsername,
1737
+ kafkaConfig.saslPassword,
1738
+ kafkaConfig.saslMechanism,
1739
+ kafkaConfig.securityProtocol,
1740
+ kafkaConfig.namespace
1741
+ ].join(":");
1742
+ return (0, import_node_crypto3.createHash)("sha256").update(configString).digest("hex").substring(0, 16);
1743
+ }
1744
+ /**
1745
+ * Gets or creates a memoized KafkaJS producer using runtime configuration.
1746
+ */
1747
+ async getMemoizedProducer() {
1748
+ await Promise.resolve().then(() => (init_runtime(), runtime_exports));
1749
+ const configRegistry = globalThis._mooseConfigRegistry;
1750
+ const { getKafkaProducer: getKafkaProducer2 } = await Promise.resolve().then(() => (init_commons(), commons_exports));
1751
+ const kafkaConfig = await configRegistry.getKafkaConfig();
1752
+ const currentHash = this.createConfigHash(kafkaConfig);
1753
+ if (this._memoizedProducer && this._kafkaConfigHash === currentHash) {
1754
+ return { producer: this._memoizedProducer, kafkaConfig };
1755
+ }
1756
+ if (this._memoizedProducer && this._kafkaConfigHash !== currentHash) {
1757
+ try {
1758
+ await this._memoizedProducer.disconnect();
1759
+ } catch {
1760
+ }
1761
+ this._memoizedProducer = void 0;
1762
+ }
1763
+ const clientId = `moose-sdk-stream-${this.name}`;
1764
+ const logger = {
1765
+ logPrefix: clientId,
1766
+ log: (message) => {
1767
+ console.log(`${clientId}: ${message}`);
1768
+ },
1769
+ error: (message) => {
1770
+ console.error(`${clientId}: ${message}`);
1771
+ },
1772
+ warn: (message) => {
1773
+ console.warn(`${clientId}: ${message}`);
2084
1774
  }
2085
1775
  };
2086
- DeadLetterQueue = class extends Stream {
2087
- constructor(name, config, typeGuard) {
2088
- if (typeGuard === void 0) {
2089
- throw new Error(
2090
- "Supply the type param T so that the schema is inserted by the compiler plugin."
2091
- );
2092
- }
2093
- super(name, config ?? {}, dlqSchema, dlqColumns, void 0, false);
2094
- this.typeGuard = typeGuard;
2095
- getMooseInternal().streams.set(name, this);
1776
+ const producer = await getKafkaProducer2(
1777
+ {
1778
+ clientId,
1779
+ broker: kafkaConfig.broker,
1780
+ securityProtocol: kafkaConfig.securityProtocol,
1781
+ saslUsername: kafkaConfig.saslUsername,
1782
+ saslPassword: kafkaConfig.saslPassword,
1783
+ saslMechanism: kafkaConfig.saslMechanism
1784
+ },
1785
+ logger
1786
+ );
1787
+ this._memoizedProducer = producer;
1788
+ this._kafkaConfigHash = currentHash;
1789
+ return { producer, kafkaConfig };
1790
+ }
1791
+ /**
1792
+ * Closes the memoized Kafka producer if it exists.
1793
+ */
1794
+ async closeProducer() {
1795
+ if (this._memoizedProducer) {
1796
+ try {
1797
+ await this._memoizedProducer.disconnect();
1798
+ } catch {
1799
+ } finally {
1800
+ this._memoizedProducer = void 0;
1801
+ this._kafkaConfigHash = void 0;
2096
1802
  }
2097
- /**
2098
- * Internal type guard function for validating and casting original records.
2099
- *
2100
- * @internal
2101
- */
2102
- typeGuard;
2103
- /**
2104
- * Adds a transformation step for dead letter records.
2105
- * The transformation function receives a DeadLetter<T> with type recovery capabilities.
2106
- *
2107
- * @template U The output type for the transformation
2108
- * @param destination The destination stream for transformed messages
2109
- * @param transformation Function to transform dead letter records
2110
- * @param config Optional transformation configuration
2111
- */
2112
- addTransform(destination, transformation, config) {
2113
- const withValidate = (deadLetter) => {
2114
- attachTypeGuard(deadLetter, this.typeGuard);
2115
- return transformation(deadLetter);
2116
- };
2117
- super.addTransform(destination, withValidate, config);
1803
+ }
1804
+ }
1805
+ /**
1806
+ * Sends one or more records to this stream's Kafka topic.
1807
+ * Values are JSON-serialized as message values.
1808
+ */
1809
+ async send(values) {
1810
+ const flat = Array.isArray(values) ? values : values !== void 0 && values !== null ? [values] : [];
1811
+ if (flat.length === 0) return;
1812
+ const { producer, kafkaConfig } = await this.getMemoizedProducer();
1813
+ const topic = this.buildFullTopicName(kafkaConfig.namespace);
1814
+ const sr = this.config.schemaConfig;
1815
+ if (sr && sr.kind === "JSON") {
1816
+ const schemaRegistryUrl = kafkaConfig.schemaRegistryUrl;
1817
+ if (!schemaRegistryUrl) {
1818
+ throw new Error("Schema Registry URL not configured");
1819
+ }
1820
+ const {
1821
+ default: { SchemaRegistry }
1822
+ } = await import("@kafkajs/confluent-schema-registry");
1823
+ const registry = new SchemaRegistry({ host: schemaRegistryUrl });
1824
+ let schemaId = void 0;
1825
+ if ("id" in sr.reference) {
1826
+ schemaId = sr.reference.id;
1827
+ } else if ("subjectLatest" in sr.reference) {
1828
+ schemaId = await registry.getLatestSchemaId(sr.reference.subjectLatest);
1829
+ } else if ("subject" in sr.reference) {
1830
+ schemaId = await registry.getRegistryId(
1831
+ sr.reference.subject,
1832
+ sr.reference.version
1833
+ );
2118
1834
  }
2119
- /**
2120
- * Adds a consumer for dead letter records.
2121
- * The consumer function receives a DeadLetter<T> with type recovery capabilities.
2122
- *
2123
- * @param consumer Function to process dead letter records
2124
- * @param config Optional consumer configuration
2125
- */
2126
- addConsumer(consumer, config) {
2127
- const withValidate = (deadLetter) => {
2128
- attachTypeGuard(deadLetter, this.typeGuard);
2129
- return consumer(deadLetter);
2130
- };
2131
- super.addConsumer(withValidate, config);
1835
+ if (schemaId === void 0) {
1836
+ throw new Error("Malformed schema reference.");
2132
1837
  }
2133
- /**
2134
- * Adds a multi-stream transformation for dead letter records.
2135
- * The transformation function receives a DeadLetter<T> with type recovery capabilities.
2136
- *
2137
- * @param transformation Function to route dead letter records to multiple destinations
2138
- */
2139
- addMultiTransform(transformation) {
2140
- const withValidate = (deadLetter) => {
2141
- attachTypeGuard(deadLetter, this.typeGuard);
2142
- return transformation(deadLetter);
2143
- };
2144
- super.addMultiTransform(withValidate);
1838
+ const encoded = await Promise.all(
1839
+ flat.map(
1840
+ (v) => registry.encode(schemaId, v)
1841
+ )
1842
+ );
1843
+ await producer.send({
1844
+ topic,
1845
+ messages: encoded.map((value) => ({ value }))
1846
+ });
1847
+ return;
1848
+ } else if (sr !== void 0) {
1849
+ throw new Error("Currently only JSON Schema is supported.");
1850
+ }
1851
+ await producer.send({
1852
+ topic,
1853
+ messages: flat.map((v) => ({ value: JSON.stringify(v) }))
1854
+ });
1855
+ }
1856
+ /**
1857
+ * Adds a transformation step that processes messages from this stream and sends the results to a destination stream.
1858
+ * Multiple transformations to the same destination stream can be added if they have distinct `version` identifiers in their config.
1859
+ *
1860
+ * @template U The data type of the messages in the destination stream.
1861
+ * @param destination The destination stream for the transformed messages.
1862
+ * @param transformation A function that takes a message of type T and returns zero or more messages of type U (or a Promise thereof).
1863
+ * Return `null` or `undefined` or an empty array `[]` to filter out a message. Return an array to emit multiple messages.
1864
+ * @param config Optional configuration for this specific transformation step, like a version.
1865
+ */
1866
+ addTransform(destination, transformation, config) {
1867
+ const sourceFile = getSourceFileFromStack(new Error().stack);
1868
+ const transformConfig = {
1869
+ ...config ?? {},
1870
+ sourceFile
1871
+ };
1872
+ if (transformConfig.deadLetterQueue === void 0) {
1873
+ transformConfig.deadLetterQueue = this.defaultDeadLetterQueue;
1874
+ }
1875
+ if (this._transformations.has(destination.name)) {
1876
+ const existingTransforms = this._transformations.get(destination.name);
1877
+ const hasVersion = existingTransforms.some(
1878
+ ([_, __, cfg]) => cfg.version === transformConfig.version
1879
+ );
1880
+ if (!hasVersion) {
1881
+ existingTransforms.push([destination, transformation, transformConfig]);
2145
1882
  }
1883
+ } else {
1884
+ this._transformations.set(destination.name, [
1885
+ [destination, transformation, transformConfig]
1886
+ ]);
1887
+ }
1888
+ }
1889
+ /**
1890
+ * Adds a consumer function that processes messages from this stream.
1891
+ * Multiple consumers can be added if they have distinct `version` identifiers in their config.
1892
+ *
1893
+ * @param consumer A function that takes a message of type T and performs an action (e.g., side effect, logging). Should return void or Promise<void>.
1894
+ * @param config Optional configuration for this specific consumer, like a version.
1895
+ */
1896
+ addConsumer(consumer, config) {
1897
+ const sourceFile = getSourceFileFromStack(new Error().stack);
1898
+ const consumerConfig = {
1899
+ ...config ?? {},
1900
+ sourceFile
2146
1901
  };
1902
+ if (consumerConfig.deadLetterQueue === void 0) {
1903
+ consumerConfig.deadLetterQueue = this.defaultDeadLetterQueue;
1904
+ }
1905
+ const hasVersion = this._consumers.some(
1906
+ (existing) => existing.config.version === consumerConfig.version
1907
+ );
1908
+ if (!hasVersion) {
1909
+ this._consumers.push({ consumer, config: consumerConfig });
1910
+ }
2147
1911
  }
2148
- });
1912
+ /**
1913
+ * Helper method for `addMultiTransform` to specify the destination and values for a routed message.
1914
+ * @param values The value or values to send to this stream.
1915
+ * @returns A `RoutedMessage` object associating the values with this stream.
1916
+ *
1917
+ * @example
1918
+ * ```typescript
1919
+ * sourceStream.addMultiTransform((record) => [
1920
+ * destinationStream1.routed(transformedRecord1),
1921
+ * destinationStream2.routed([record2a, record2b])
1922
+ * ]);
1923
+ * ```
1924
+ */
1925
+ routed = (values) => new RoutedMessage(this, values);
1926
+ /**
1927
+ * Adds a single transformation function that can route messages to multiple destination streams.
1928
+ * This is an alternative to adding multiple individual `addTransform` calls.
1929
+ * Only one multi-transform function can be added per stream.
1930
+ *
1931
+ * @param transformation A function that takes a message of type T and returns an array of `RoutedMessage` objects,
1932
+ * each specifying a destination stream and the message(s) to send to it.
1933
+ */
1934
+ addMultiTransform(transformation) {
1935
+ this._multipleTransformations = transformation;
1936
+ }
1937
+ };
1938
+ function attachTypeGuard(dl, typeGuard) {
1939
+ dl.asTyped = () => typeGuard(dl.originalRecord);
1940
+ }
1941
+ var DeadLetterQueue = class extends Stream {
1942
+ constructor(name, config, typeGuard) {
1943
+ if (typeGuard === void 0) {
1944
+ throw new Error(
1945
+ "Supply the type param T so that the schema is inserted by the compiler plugin."
1946
+ );
1947
+ }
1948
+ super(name, config ?? {}, dlqSchema, dlqColumns, void 0, false);
1949
+ this.typeGuard = typeGuard;
1950
+ getMooseInternal().streams.set(name, this);
1951
+ }
1952
+ /**
1953
+ * Internal type guard function for validating and casting original records.
1954
+ *
1955
+ * @internal
1956
+ */
1957
+ typeGuard;
1958
+ /**
1959
+ * Adds a transformation step for dead letter records.
1960
+ * The transformation function receives a DeadLetter<T> with type recovery capabilities.
1961
+ *
1962
+ * @template U The output type for the transformation
1963
+ * @param destination The destination stream for transformed messages
1964
+ * @param transformation Function to transform dead letter records
1965
+ * @param config Optional transformation configuration
1966
+ */
1967
+ addTransform(destination, transformation, config) {
1968
+ const withValidate = (deadLetter) => {
1969
+ attachTypeGuard(deadLetter, this.typeGuard);
1970
+ return transformation(deadLetter);
1971
+ };
1972
+ super.addTransform(destination, withValidate, config);
1973
+ }
1974
+ /**
1975
+ * Adds a consumer for dead letter records.
1976
+ * The consumer function receives a DeadLetter<T> with type recovery capabilities.
1977
+ *
1978
+ * @param consumer Function to process dead letter records
1979
+ * @param config Optional consumer configuration
1980
+ */
1981
+ addConsumer(consumer, config) {
1982
+ const withValidate = (deadLetter) => {
1983
+ attachTypeGuard(deadLetter, this.typeGuard);
1984
+ return consumer(deadLetter);
1985
+ };
1986
+ super.addConsumer(withValidate, config);
1987
+ }
1988
+ /**
1989
+ * Adds a multi-stream transformation for dead letter records.
1990
+ * The transformation function receives a DeadLetter<T> with type recovery capabilities.
1991
+ *
1992
+ * @param transformation Function to route dead letter records to multiple destinations
1993
+ */
1994
+ addMultiTransform(transformation) {
1995
+ const withValidate = (deadLetter) => {
1996
+ attachTypeGuard(deadLetter, this.typeGuard);
1997
+ return transformation(deadLetter);
1998
+ };
1999
+ super.addMultiTransform(withValidate);
2000
+ }
2001
+ };
2149
2002
 
2150
2003
  // src/dmv2/sdk/workflow.ts
2151
- var Task, Workflow;
2152
- var init_workflow = __esm({
2153
- "src/dmv2/sdk/workflow.ts"() {
2154
- "use strict";
2155
- init_internal();
2156
- Task = class {
2157
- /**
2158
- * Creates a new Task instance.
2159
- *
2160
- * @param name - Unique identifier for the task
2161
- * @param config - Configuration object defining the task behavior
2162
- *
2163
- * @example
2164
- * ```typescript
2165
- * // No input, no output
2166
- * const task1 = new Task<null, void>("task1", {
2167
- * run: async () => {
2168
- * console.log("No input/output");
2169
- * }
2170
- * });
2171
- *
2172
- * // No input, but has output
2173
- * const task2 = new Task<null, OutputType>("task2", {
2174
- * run: async () => {
2175
- * return someOutput;
2176
- * }
2177
- * });
2178
- *
2179
- * // Has input, no output
2180
- * const task3 = new Task<InputType, void>("task3", {
2181
- * run: async (input: InputType) => {
2182
- * // process input but return nothing
2183
- * }
2184
- * });
2185
- *
2186
- * // Has both input and output
2187
- * const task4 = new Task<InputType, OutputType>("task4", {
2188
- * run: async (input: InputType) => {
2189
- * return process(input);
2190
- * }
2191
- * });
2192
- * ```
2193
- */
2194
- constructor(name, config) {
2195
- this.name = name;
2196
- this.config = config;
2004
+ var Task = class {
2005
+ /**
2006
+ * Creates a new Task instance.
2007
+ *
2008
+ * @param name - Unique identifier for the task
2009
+ * @param config - Configuration object defining the task behavior
2010
+ *
2011
+ * @example
2012
+ * ```typescript
2013
+ * // No input, no output
2014
+ * const task1 = new Task<null, void>("task1", {
2015
+ * run: async () => {
2016
+ * console.log("No input/output");
2017
+ * }
2018
+ * });
2019
+ *
2020
+ * // No input, but has output
2021
+ * const task2 = new Task<null, OutputType>("task2", {
2022
+ * run: async () => {
2023
+ * return someOutput;
2024
+ * }
2025
+ * });
2026
+ *
2027
+ * // Has input, no output
2028
+ * const task3 = new Task<InputType, void>("task3", {
2029
+ * run: async (input: InputType) => {
2030
+ * // process input but return nothing
2031
+ * }
2032
+ * });
2033
+ *
2034
+ * // Has both input and output
2035
+ * const task4 = new Task<InputType, OutputType>("task4", {
2036
+ * run: async (input: InputType) => {
2037
+ * return process(input);
2038
+ * }
2039
+ * });
2040
+ * ```
2041
+ */
2042
+ constructor(name, config) {
2043
+ this.name = name;
2044
+ this.config = config;
2045
+ }
2046
+ };
2047
+ var Workflow = class {
2048
+ /**
2049
+ * Creates a new Workflow instance and registers it with the Moose system.
2050
+ *
2051
+ * @param name - Unique identifier for the workflow
2052
+ * @param config - Configuration object defining the workflow behavior and task orchestration
2053
+ * @throws {Error} When the workflow contains null/undefined tasks or infinite loops
2054
+ */
2055
+ constructor(name, config) {
2056
+ this.name = name;
2057
+ this.config = config;
2058
+ const workflows = getMooseInternal().workflows;
2059
+ if (workflows.has(name)) {
2060
+ throw new Error(`Workflow with name ${name} already exists`);
2061
+ }
2062
+ this.validateTaskGraph(config.startingTask, name);
2063
+ workflows.set(name, this);
2064
+ }
2065
+ /**
2066
+ * Validates the task graph to ensure there are no null tasks or infinite loops.
2067
+ *
2068
+ * @private
2069
+ * @param startingTask - The starting task to begin validation from
2070
+ * @param workflowName - The name of the workflow being validated (for error messages)
2071
+ * @throws {Error} When null/undefined tasks are found or infinite loops are detected
2072
+ */
2073
+ validateTaskGraph(startingTask, workflowName) {
2074
+ if (startingTask === null || startingTask === void 0) {
2075
+ throw new Error(
2076
+ `Workflow "${workflowName}" has a null or undefined starting task`
2077
+ );
2078
+ }
2079
+ const visited = /* @__PURE__ */ new Set();
2080
+ const recursionStack = /* @__PURE__ */ new Set();
2081
+ const validateTask = (task, currentPath) => {
2082
+ if (task === null || task === void 0) {
2083
+ const pathStr = currentPath.length > 0 ? currentPath.join(" -> ") + " -> " : "";
2084
+ throw new Error(
2085
+ `Workflow "${workflowName}" contains a null or undefined task in the task chain: ${pathStr}null`
2086
+ );
2197
2087
  }
2198
- };
2199
- Workflow = class {
2200
- /**
2201
- * Creates a new Workflow instance and registers it with the Moose system.
2202
- *
2203
- * @param name - Unique identifier for the workflow
2204
- * @param config - Configuration object defining the workflow behavior and task orchestration
2205
- * @throws {Error} When the workflow contains null/undefined tasks or infinite loops
2206
- */
2207
- constructor(name, config) {
2208
- this.name = name;
2209
- this.config = config;
2210
- const workflows = getMooseInternal().workflows;
2211
- if (workflows.has(name)) {
2212
- throw new Error(`Workflow with name ${name} already exists`);
2213
- }
2214
- this.validateTaskGraph(config.startingTask, name);
2215
- workflows.set(name, this);
2088
+ const taskName = task.name;
2089
+ if (recursionStack.has(taskName)) {
2090
+ const cycleStartIndex = currentPath.indexOf(taskName);
2091
+ const cyclePath = cycleStartIndex >= 0 ? currentPath.slice(cycleStartIndex).concat(taskName) : currentPath.concat(taskName);
2092
+ throw new Error(
2093
+ `Workflow "${workflowName}" contains an infinite loop in task chain: ${cyclePath.join(" -> ")}`
2094
+ );
2216
2095
  }
2217
- /**
2218
- * Validates the task graph to ensure there are no null tasks or infinite loops.
2219
- *
2220
- * @private
2221
- * @param startingTask - The starting task to begin validation from
2222
- * @param workflowName - The name of the workflow being validated (for error messages)
2223
- * @throws {Error} When null/undefined tasks are found or infinite loops are detected
2224
- */
2225
- validateTaskGraph(startingTask, workflowName) {
2226
- if (startingTask === null || startingTask === void 0) {
2227
- throw new Error(
2228
- `Workflow "${workflowName}" has a null or undefined starting task`
2229
- );
2096
+ if (visited.has(taskName)) {
2097
+ return;
2098
+ }
2099
+ visited.add(taskName);
2100
+ recursionStack.add(taskName);
2101
+ if (task.config.onComplete) {
2102
+ for (const nextTask of task.config.onComplete) {
2103
+ validateTask(nextTask, [...currentPath, taskName]);
2230
2104
  }
2231
- const visited = /* @__PURE__ */ new Set();
2232
- const recursionStack = /* @__PURE__ */ new Set();
2233
- const validateTask = (task, currentPath) => {
2234
- if (task === null || task === void 0) {
2235
- const pathStr = currentPath.length > 0 ? currentPath.join(" -> ") + " -> " : "";
2236
- throw new Error(
2237
- `Workflow "${workflowName}" contains a null or undefined task in the task chain: ${pathStr}null`
2238
- );
2239
- }
2240
- const taskName = task.name;
2241
- if (recursionStack.has(taskName)) {
2242
- const cycleStartIndex = currentPath.indexOf(taskName);
2243
- const cyclePath = cycleStartIndex >= 0 ? currentPath.slice(cycleStartIndex).concat(taskName) : currentPath.concat(taskName);
2244
- throw new Error(
2245
- `Workflow "${workflowName}" contains an infinite loop in task chain: ${cyclePath.join(" -> ")}`
2246
- );
2247
- }
2248
- if (visited.has(taskName)) {
2249
- return;
2250
- }
2251
- visited.add(taskName);
2252
- recursionStack.add(taskName);
2253
- if (task.config.onComplete) {
2254
- for (const nextTask of task.config.onComplete) {
2255
- validateTask(nextTask, [...currentPath, taskName]);
2256
- }
2257
- }
2258
- recursionStack.delete(taskName);
2259
- };
2260
- validateTask(startingTask, []);
2261
2105
  }
2106
+ recursionStack.delete(taskName);
2262
2107
  };
2108
+ validateTask(startingTask, []);
2263
2109
  }
2264
- });
2110
+ };
2265
2111
 
2266
2112
  // src/dmv2/sdk/ingestApi.ts
2267
- var IngestApi;
2268
- var init_ingestApi = __esm({
2269
- "src/dmv2/sdk/ingestApi.ts"() {
2270
- "use strict";
2271
- init_typedBase();
2272
- init_internal();
2273
- IngestApi = class extends TypedBase {
2274
- constructor(name, config, schema, columns, validators, allowExtraFields) {
2275
- super(name, config, schema, columns, void 0, allowExtraFields);
2276
- const ingestApis = getMooseInternal().ingestApis;
2277
- if (ingestApis.has(name)) {
2278
- throw new Error(`Ingest API with name ${name} already exists`);
2279
- }
2280
- ingestApis.set(name, this);
2281
- }
2282
- };
2113
+ var IngestApi = class extends TypedBase {
2114
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
2115
+ super(name, config, schema, columns, void 0, allowExtraFields);
2116
+ const ingestApis = getMooseInternal().ingestApis;
2117
+ if (ingestApis.has(name)) {
2118
+ throw new Error(`Ingest API with name ${name} already exists`);
2119
+ }
2120
+ ingestApis.set(name, this);
2283
2121
  }
2284
- });
2122
+ };
2285
2123
 
2286
2124
  // src/dmv2/sdk/consumptionApi.ts
2287
- var Api, ConsumptionApi;
2288
- var init_consumptionApi = __esm({
2289
- "src/dmv2/sdk/consumptionApi.ts"() {
2290
- "use strict";
2291
- init_typedBase();
2292
- init_internal();
2293
- Api = class extends TypedBase {
2294
- /** @internal The handler function that processes requests and generates responses. */
2295
- _handler;
2296
- /** @internal The JSON schema definition for the response type R. */
2297
- responseSchema;
2298
- constructor(name, handler, config, schema, columns, responseSchema) {
2299
- super(name, config ?? {}, schema, columns);
2300
- this._handler = handler;
2301
- this.responseSchema = responseSchema ?? {
2302
- version: "3.1",
2303
- schemas: [{ type: "array", items: { type: "object" } }],
2304
- components: { schemas: {} }
2305
- };
2306
- const apis = getMooseInternal().apis;
2307
- const key = `${name}${config?.version ? `:${config.version}` : ""}`;
2308
- if (apis.has(key)) {
2309
- throw new Error(
2310
- `Consumption API with name ${name} and version ${config?.version} already exists`
2311
- );
2312
- }
2313
- apis.set(key, this);
2314
- if (config?.path) {
2315
- if (config.version) {
2316
- const pathEndsWithVersion = config.path.endsWith(`/${config.version}`) || config.path === config.version || config.path.endsWith(config.version) && config.path.length > config.version.length && config.path[config.path.length - config.version.length - 1] === "/";
2317
- if (pathEndsWithVersion) {
2318
- if (apis.has(config.path)) {
2319
- const existing = apis.get(config.path);
2320
- throw new Error(
2321
- `Cannot register API "${name}" with path "${config.path}" - this path is already used by API "${existing.name}"`
2322
- );
2323
- }
2324
- apis.set(config.path, this);
2325
- } else {
2326
- const versionedPath = `${config.path.replace(/\/$/, "")}/${config.version}`;
2327
- if (apis.has(versionedPath)) {
2328
- const existing = apis.get(versionedPath);
2329
- throw new Error(
2330
- `Cannot register API "${name}" with path "${versionedPath}" - this path is already used by API "${existing.name}"`
2331
- );
2332
- }
2333
- apis.set(versionedPath, this);
2334
- if (!apis.has(config.path)) {
2335
- apis.set(config.path, this);
2336
- }
2337
- }
2338
- } else {
2339
- if (apis.has(config.path)) {
2340
- const existing = apis.get(config.path);
2341
- throw new Error(
2342
- `Cannot register API "${name}" with custom path "${config.path}" - this path is already used by API "${existing.name}"`
2343
- );
2344
- }
2345
- apis.set(config.path, this);
2346
- }
2347
- }
2348
- }
2349
- /**
2350
- * Retrieves the handler function associated with this Consumption API.
2351
- * @returns The handler function.
2352
- */
2353
- getHandler = () => {
2354
- return this._handler;
2355
- };
2356
- async call(baseUrl, queryParams) {
2357
- let path2;
2358
- if (this.config?.path) {
2359
- if (this.config.version) {
2360
- const pathEndsWithVersion = this.config.path.endsWith(`/${this.config.version}`) || this.config.path === this.config.version || this.config.path.endsWith(this.config.version) && this.config.path.length > this.config.version.length && this.config.path[this.config.path.length - this.config.version.length - 1] === "/";
2361
- if (pathEndsWithVersion) {
2362
- path2 = this.config.path;
2363
- } else {
2364
- path2 = `${this.config.path.replace(/\/$/, "")}/${this.config.version}`;
2365
- }
2366
- } else {
2367
- path2 = this.config.path;
2125
+ var Api = class extends TypedBase {
2126
+ /** @internal The handler function that processes requests and generates responses. */
2127
+ _handler;
2128
+ /** @internal The JSON schema definition for the response type R. */
2129
+ responseSchema;
2130
+ constructor(name, handler, config, schema, columns, responseSchema) {
2131
+ super(name, config ?? {}, schema, columns);
2132
+ this._handler = handler;
2133
+ this.responseSchema = responseSchema ?? {
2134
+ version: "3.1",
2135
+ schemas: [{ type: "array", items: { type: "object" } }],
2136
+ components: { schemas: {} }
2137
+ };
2138
+ const apis = getMooseInternal().apis;
2139
+ const key = `${name}${config?.version ? `:${config.version}` : ""}`;
2140
+ if (apis.has(key)) {
2141
+ throw new Error(
2142
+ `Consumption API with name ${name} and version ${config?.version} already exists`
2143
+ );
2144
+ }
2145
+ apis.set(key, this);
2146
+ if (config?.path) {
2147
+ if (config.version) {
2148
+ const pathEndsWithVersion = config.path.endsWith(`/${config.version}`) || config.path === config.version || config.path.endsWith(config.version) && config.path.length > config.version.length && config.path[config.path.length - config.version.length - 1] === "/";
2149
+ if (pathEndsWithVersion) {
2150
+ if (apis.has(config.path)) {
2151
+ const existing = apis.get(config.path);
2152
+ throw new Error(
2153
+ `Cannot register API "${name}" with path "${config.path}" - this path is already used by API "${existing.name}"`
2154
+ );
2368
2155
  }
2156
+ apis.set(config.path, this);
2369
2157
  } else {
2370
- path2 = this.config?.version ? `${this.name}/${this.config.version}` : this.name;
2371
- }
2372
- const url = new URL(`${baseUrl.replace(/\/$/, "")}/api/${path2}`);
2373
- const searchParams = url.searchParams;
2374
- for (const [key, value] of Object.entries(queryParams)) {
2375
- if (Array.isArray(value)) {
2376
- for (const item of value) {
2377
- if (item !== null && item !== void 0) {
2378
- searchParams.append(key, String(item));
2379
- }
2380
- }
2381
- } else if (value !== null && value !== void 0) {
2382
- searchParams.append(key, String(value));
2383
- }
2384
- }
2385
- const response = await fetch(url, {
2386
- method: "GET",
2387
- headers: {
2388
- Accept: "application/json"
2389
- }
2390
- });
2391
- if (!response.ok) {
2392
- throw new Error(`HTTP error! status: ${response.status}`);
2393
- }
2394
- const data = await response.json();
2395
- return data;
2396
- }
2397
- };
2398
- ConsumptionApi = Api;
2399
- }
2400
- });
2401
-
2402
- // src/dmv2/sdk/ingestPipeline.ts
2403
- var IngestPipeline;
2404
- var init_ingestPipeline = __esm({
2405
- "src/dmv2/sdk/ingestPipeline.ts"() {
2406
- "use strict";
2407
- init_typedBase();
2408
- init_stream();
2409
- init_olapTable();
2410
- init_ingestApi();
2411
- init_types();
2412
- IngestPipeline = class extends TypedBase {
2413
- /**
2414
- * The OLAP table component of the pipeline, if configured.
2415
- * Provides analytical query capabilities for the ingested data.
2416
- * Only present when `config.table` is not `false`.
2417
- */
2418
- table;
2419
- /**
2420
- * The stream component of the pipeline, if configured.
2421
- * Handles real-time data flow and processing between components.
2422
- * Only present when `config.stream` is not `false`.
2423
- */
2424
- stream;
2425
- /**
2426
- * The ingest API component of the pipeline, if configured.
2427
- * Provides HTTP endpoints for data ingestion.
2428
- * Only present when `config.ingestApi` is not `false`.
2429
- */
2430
- ingestApi;
2431
- /** The dead letter queue of the pipeline, if configured. */
2432
- deadLetterQueue;
2433
- constructor(name, config, schema, columns, validators, allowExtraFields) {
2434
- super(name, config, schema, columns, validators, allowExtraFields);
2435
- if (config.ingest !== void 0) {
2436
- console.warn(
2437
- "\u26A0\uFE0F DEPRECATION WARNING: The 'ingest' parameter is deprecated and will be removed in a future version. Please use 'ingestApi' instead."
2438
- );
2439
- if (config.ingestApi === void 0) {
2440
- config.ingestApi = config.ingest;
2158
+ const versionedPath = `${config.path.replace(/\/$/, "")}/${config.version}`;
2159
+ if (apis.has(versionedPath)) {
2160
+ const existing = apis.get(versionedPath);
2161
+ throw new Error(
2162
+ `Cannot register API "${name}" with path "${versionedPath}" - this path is already used by API "${existing.name}"`
2163
+ );
2441
2164
  }
2442
- }
2443
- if (config.table) {
2444
- const tableConfig = typeof config.table === "object" ? {
2445
- ...config.table,
2446
- lifeCycle: config.table.lifeCycle ?? config.lifeCycle,
2447
- ...config.version && { version: config.version }
2448
- } : {
2449
- lifeCycle: config.lifeCycle,
2450
- engine: "MergeTree" /* MergeTree */,
2451
- ...config.version && { version: config.version }
2452
- };
2453
- this.table = new OlapTable(
2454
- name,
2455
- tableConfig,
2456
- this.schema,
2457
- this.columnArray,
2458
- this.validators
2459
- );
2460
- }
2461
- if (config.deadLetterQueue) {
2462
- const streamConfig = {
2463
- destination: void 0,
2464
- ...typeof config.deadLetterQueue === "object" ? {
2465
- ...config.deadLetterQueue,
2466
- lifeCycle: config.deadLetterQueue.lifeCycle ?? config.lifeCycle
2467
- } : { lifeCycle: config.lifeCycle },
2468
- ...config.version && { version: config.version }
2469
- };
2470
- this.deadLetterQueue = new DeadLetterQueue(
2471
- `${name}DeadLetterQueue`,
2472
- streamConfig,
2473
- validators.assert
2474
- );
2475
- }
2476
- if (config.stream) {
2477
- const streamConfig = {
2478
- destination: this.table,
2479
- defaultDeadLetterQueue: this.deadLetterQueue,
2480
- ...typeof config.stream === "object" ? {
2481
- ...config.stream,
2482
- lifeCycle: config.stream.lifeCycle ?? config.lifeCycle
2483
- } : { lifeCycle: config.lifeCycle },
2484
- ...config.version && { version: config.version }
2485
- };
2486
- this.stream = new Stream(
2487
- name,
2488
- streamConfig,
2489
- this.schema,
2490
- this.columnArray,
2491
- void 0,
2492
- this.allowExtraFields
2493
- );
2494
- this.stream.pipelineParent = this;
2495
- }
2496
- const effectiveIngestAPI = config.ingestApi !== void 0 ? config.ingestApi : config.ingest;
2497
- if (effectiveIngestAPI) {
2498
- if (!this.stream) {
2499
- throw new Error("Ingest API needs a stream to write to.");
2165
+ apis.set(versionedPath, this);
2166
+ if (!apis.has(config.path)) {
2167
+ apis.set(config.path, this);
2500
2168
  }
2501
- const ingestConfig = {
2502
- destination: this.stream,
2503
- deadLetterQueue: this.deadLetterQueue,
2504
- ...typeof effectiveIngestAPI === "object" ? effectiveIngestAPI : {},
2505
- ...config.version && { version: config.version },
2506
- ...config.path && { path: config.path }
2507
- };
2508
- this.ingestApi = new IngestApi(
2509
- name,
2510
- ingestConfig,
2511
- this.schema,
2512
- this.columnArray,
2513
- void 0,
2514
- this.allowExtraFields
2169
+ }
2170
+ } else {
2171
+ if (apis.has(config.path)) {
2172
+ const existing = apis.get(config.path);
2173
+ throw new Error(
2174
+ `Cannot register API "${name}" with custom path "${config.path}" - this path is already used by API "${existing.name}"`
2515
2175
  );
2516
- this.ingestApi.pipelineParent = this;
2517
2176
  }
2177
+ apis.set(config.path, this);
2518
2178
  }
2519
- };
2179
+ }
2520
2180
  }
2521
- });
2522
-
2523
- // src/dmv2/sdk/etlPipeline.ts
2524
- var InternalBatcher, ETLPipeline;
2525
- var init_etlPipeline = __esm({
2526
- "src/dmv2/sdk/etlPipeline.ts"() {
2527
- "use strict";
2528
- init_workflow();
2529
- InternalBatcher = class {
2530
- iterator;
2531
- batchSize;
2532
- constructor(asyncIterable, batchSize = 20) {
2533
- this.iterator = asyncIterable[Symbol.asyncIterator]();
2534
- this.batchSize = batchSize;
2535
- }
2536
- async getNextBatch() {
2537
- const items = [];
2538
- for (let i = 0; i < this.batchSize; i++) {
2539
- const { value, done } = await this.iterator.next();
2540
- if (done) {
2541
- return { items, hasMore: false };
2542
- }
2543
- items.push(value);
2181
+ /**
2182
+ * Retrieves the handler function associated with this Consumption API.
2183
+ * @returns The handler function.
2184
+ */
2185
+ getHandler = () => {
2186
+ return this._handler;
2187
+ };
2188
+ async call(baseUrl, queryParams) {
2189
+ let path2;
2190
+ if (this.config?.path) {
2191
+ if (this.config.version) {
2192
+ const pathEndsWithVersion = this.config.path.endsWith(`/${this.config.version}`) || this.config.path === this.config.version || this.config.path.endsWith(this.config.version) && this.config.path.length > this.config.version.length && this.config.path[this.config.path.length - this.config.version.length - 1] === "/";
2193
+ if (pathEndsWithVersion) {
2194
+ path2 = this.config.path;
2195
+ } else {
2196
+ path2 = `${this.config.path.replace(/\/$/, "")}/${this.config.version}`;
2544
2197
  }
2545
- return { items, hasMore: true };
2546
- }
2547
- };
2548
- ETLPipeline = class {
2549
- constructor(name, config) {
2550
- this.name = name;
2551
- this.config = config;
2552
- this.setupPipeline();
2553
- }
2554
- batcher;
2555
- setupPipeline() {
2556
- this.batcher = this.createBatcher();
2557
- const tasks = this.createAllTasks();
2558
- tasks.extract.config.onComplete = [tasks.transform];
2559
- tasks.transform.config.onComplete = [tasks.load];
2560
- new Workflow(this.name, {
2561
- startingTask: tasks.extract,
2562
- retries: 1,
2563
- timeout: "30m"
2564
- });
2565
- }
2566
- createBatcher() {
2567
- const iterable = typeof this.config.extract === "function" ? this.config.extract() : this.config.extract;
2568
- return new InternalBatcher(iterable);
2569
- }
2570
- getDefaultTaskConfig() {
2571
- return {
2572
- retries: 1,
2573
- timeout: "30m"
2574
- };
2575
- }
2576
- createAllTasks() {
2577
- const taskConfig = this.getDefaultTaskConfig();
2578
- return {
2579
- extract: this.createExtractTask(taskConfig),
2580
- transform: this.createTransformTask(taskConfig),
2581
- load: this.createLoadTask(taskConfig)
2582
- };
2583
- }
2584
- createExtractTask(taskConfig) {
2585
- return new Task(`${this.name}_extract`, {
2586
- run: async ({}) => {
2587
- console.log(`Running extract task for ${this.name}...`);
2588
- const batch = await this.batcher.getNextBatch();
2589
- console.log(`Extract task completed with ${batch.items.length} items`);
2590
- return batch;
2591
- },
2592
- retries: taskConfig.retries,
2593
- timeout: taskConfig.timeout
2594
- });
2198
+ } else {
2199
+ path2 = this.config.path;
2595
2200
  }
2596
- createTransformTask(taskConfig) {
2597
- return new Task(
2598
- `${this.name}_transform`,
2599
- {
2600
- // Use new single-parameter context API for handlers
2601
- run: async ({ input }) => {
2602
- const batch = input;
2603
- console.log(
2604
- `Running transform task for ${this.name} with ${batch.items.length} items...`
2605
- );
2606
- const transformedItems = [];
2607
- for (const item of batch.items) {
2608
- const transformed = await this.config.transform(item);
2609
- transformedItems.push(transformed);
2610
- }
2611
- console.log(
2612
- `Transform task completed with ${transformedItems.length} items`
2613
- );
2614
- return { items: transformedItems };
2615
- },
2616
- retries: taskConfig.retries,
2617
- timeout: taskConfig.timeout
2201
+ } else {
2202
+ path2 = this.config?.version ? `${this.name}/${this.config.version}` : this.name;
2203
+ }
2204
+ const url = new URL(`${baseUrl.replace(/\/$/, "")}/api/${path2}`);
2205
+ const searchParams = url.searchParams;
2206
+ for (const [key, value] of Object.entries(queryParams)) {
2207
+ if (Array.isArray(value)) {
2208
+ for (const item of value) {
2209
+ if (item !== null && item !== void 0) {
2210
+ searchParams.append(key, String(item));
2618
2211
  }
2619
- );
2212
+ }
2213
+ } else if (value !== null && value !== void 0) {
2214
+ searchParams.append(key, String(value));
2620
2215
  }
2621
- createLoadTask(taskConfig) {
2622
- return new Task(`${this.name}_load`, {
2623
- run: async ({ input: transformedItems }) => {
2624
- console.log(
2625
- `Running load task for ${this.name} with ${transformedItems.items.length} items...`
2626
- );
2627
- if ("insert" in this.config.load) {
2628
- await this.config.load.insert(transformedItems.items);
2629
- } else {
2630
- await this.config.load(transformedItems.items);
2631
- }
2632
- console.log(`Load task completed`);
2633
- },
2634
- retries: taskConfig.retries,
2635
- timeout: taskConfig.timeout
2636
- });
2216
+ }
2217
+ const response = await fetch(url, {
2218
+ method: "GET",
2219
+ headers: {
2220
+ Accept: "application/json"
2221
+ }
2222
+ });
2223
+ if (!response.ok) {
2224
+ throw new Error(`HTTP error! status: ${response.status}`);
2225
+ }
2226
+ const data = await response.json();
2227
+ return data;
2228
+ }
2229
+ };
2230
+ var ConsumptionApi = Api;
2231
+
2232
+ // src/dmv2/sdk/ingestPipeline.ts
2233
+ var IngestPipeline = class extends TypedBase {
2234
+ /**
2235
+ * The OLAP table component of the pipeline, if configured.
2236
+ * Provides analytical query capabilities for the ingested data.
2237
+ * Only present when `config.table` is not `false`.
2238
+ */
2239
+ table;
2240
+ /**
2241
+ * The stream component of the pipeline, if configured.
2242
+ * Handles real-time data flow and processing between components.
2243
+ * Only present when `config.stream` is not `false`.
2244
+ */
2245
+ stream;
2246
+ /**
2247
+ * The ingest API component of the pipeline, if configured.
2248
+ * Provides HTTP endpoints for data ingestion.
2249
+ * Only present when `config.ingestApi` is not `false`.
2250
+ */
2251
+ ingestApi;
2252
+ /** The dead letter queue of the pipeline, if configured. */
2253
+ deadLetterQueue;
2254
+ constructor(name, config, schema, columns, validators, allowExtraFields) {
2255
+ super(name, config, schema, columns, validators, allowExtraFields);
2256
+ if (config.ingest !== void 0) {
2257
+ console.warn(
2258
+ "\u26A0\uFE0F DEPRECATION WARNING: The 'ingest' parameter is deprecated and will be removed in a future version. Please use 'ingestApi' instead."
2259
+ );
2260
+ if (config.ingestApi === void 0) {
2261
+ config.ingestApi = config.ingest;
2637
2262
  }
2638
- // Execute the entire ETL pipeline
2639
- async run() {
2640
- console.log(`Starting ETL Pipeline: ${this.name}`);
2641
- let batchNumber = 1;
2642
- do {
2643
- console.log(`Processing batch ${batchNumber}...`);
2644
- const batch = await this.batcher.getNextBatch();
2645
- if (batch.items.length === 0) {
2646
- break;
2647
- }
2263
+ }
2264
+ if (config.table) {
2265
+ const tableConfig = typeof config.table === "object" ? {
2266
+ ...config.table,
2267
+ lifeCycle: config.table.lifeCycle ?? config.lifeCycle,
2268
+ ...config.version && { version: config.version }
2269
+ } : {
2270
+ lifeCycle: config.lifeCycle,
2271
+ engine: "MergeTree" /* MergeTree */,
2272
+ ...config.version && { version: config.version }
2273
+ };
2274
+ this.table = new OlapTable(
2275
+ name,
2276
+ tableConfig,
2277
+ this.schema,
2278
+ this.columnArray,
2279
+ this.validators
2280
+ );
2281
+ }
2282
+ if (config.deadLetterQueue) {
2283
+ const streamConfig = {
2284
+ destination: void 0,
2285
+ ...typeof config.deadLetterQueue === "object" ? {
2286
+ ...config.deadLetterQueue,
2287
+ lifeCycle: config.deadLetterQueue.lifeCycle ?? config.lifeCycle
2288
+ } : { lifeCycle: config.lifeCycle },
2289
+ ...config.version && { version: config.version }
2290
+ };
2291
+ this.deadLetterQueue = new DeadLetterQueue(
2292
+ `${name}DeadLetterQueue`,
2293
+ streamConfig,
2294
+ validators.assert
2295
+ );
2296
+ }
2297
+ if (config.stream) {
2298
+ const streamConfig = {
2299
+ destination: this.table,
2300
+ defaultDeadLetterQueue: this.deadLetterQueue,
2301
+ ...typeof config.stream === "object" ? {
2302
+ ...config.stream,
2303
+ lifeCycle: config.stream.lifeCycle ?? config.lifeCycle
2304
+ } : { lifeCycle: config.lifeCycle },
2305
+ ...config.version && { version: config.version }
2306
+ };
2307
+ this.stream = new Stream(
2308
+ name,
2309
+ streamConfig,
2310
+ this.schema,
2311
+ this.columnArray,
2312
+ void 0,
2313
+ this.allowExtraFields
2314
+ );
2315
+ this.stream.pipelineParent = this;
2316
+ }
2317
+ const effectiveIngestAPI = config.ingestApi !== void 0 ? config.ingestApi : config.ingest;
2318
+ if (effectiveIngestAPI) {
2319
+ if (!this.stream) {
2320
+ throw new Error("Ingest API needs a stream to write to.");
2321
+ }
2322
+ const ingestConfig = {
2323
+ destination: this.stream,
2324
+ deadLetterQueue: this.deadLetterQueue,
2325
+ ...typeof effectiveIngestAPI === "object" ? effectiveIngestAPI : {},
2326
+ ...config.version && { version: config.version },
2327
+ ...config.path && { path: config.path }
2328
+ };
2329
+ this.ingestApi = new IngestApi(
2330
+ name,
2331
+ ingestConfig,
2332
+ this.schema,
2333
+ this.columnArray,
2334
+ void 0,
2335
+ this.allowExtraFields
2336
+ );
2337
+ this.ingestApi.pipelineParent = this;
2338
+ }
2339
+ }
2340
+ };
2341
+
2342
+ // src/dmv2/sdk/etlPipeline.ts
2343
+ var InternalBatcher = class {
2344
+ iterator;
2345
+ batchSize;
2346
+ constructor(asyncIterable, batchSize = 20) {
2347
+ this.iterator = asyncIterable[Symbol.asyncIterator]();
2348
+ this.batchSize = batchSize;
2349
+ }
2350
+ async getNextBatch() {
2351
+ const items = [];
2352
+ for (let i = 0; i < this.batchSize; i++) {
2353
+ const { value, done } = await this.iterator.next();
2354
+ if (done) {
2355
+ return { items, hasMore: false };
2356
+ }
2357
+ items.push(value);
2358
+ }
2359
+ return { items, hasMore: true };
2360
+ }
2361
+ };
2362
+ var ETLPipeline = class {
2363
+ constructor(name, config) {
2364
+ this.name = name;
2365
+ this.config = config;
2366
+ this.setupPipeline();
2367
+ }
2368
+ batcher;
2369
+ setupPipeline() {
2370
+ this.batcher = this.createBatcher();
2371
+ const tasks = this.createAllTasks();
2372
+ tasks.extract.config.onComplete = [tasks.transform];
2373
+ tasks.transform.config.onComplete = [tasks.load];
2374
+ new Workflow(this.name, {
2375
+ startingTask: tasks.extract,
2376
+ retries: 1,
2377
+ timeout: "30m"
2378
+ });
2379
+ }
2380
+ createBatcher() {
2381
+ const iterable = typeof this.config.extract === "function" ? this.config.extract() : this.config.extract;
2382
+ return new InternalBatcher(iterable);
2383
+ }
2384
+ getDefaultTaskConfig() {
2385
+ return {
2386
+ retries: 1,
2387
+ timeout: "30m"
2388
+ };
2389
+ }
2390
+ createAllTasks() {
2391
+ const taskConfig = this.getDefaultTaskConfig();
2392
+ return {
2393
+ extract: this.createExtractTask(taskConfig),
2394
+ transform: this.createTransformTask(taskConfig),
2395
+ load: this.createLoadTask(taskConfig)
2396
+ };
2397
+ }
2398
+ createExtractTask(taskConfig) {
2399
+ return new Task(`${this.name}_extract`, {
2400
+ run: async ({}) => {
2401
+ console.log(`Running extract task for ${this.name}...`);
2402
+ const batch = await this.batcher.getNextBatch();
2403
+ console.log(`Extract task completed with ${batch.items.length} items`);
2404
+ return batch;
2405
+ },
2406
+ retries: taskConfig.retries,
2407
+ timeout: taskConfig.timeout
2408
+ });
2409
+ }
2410
+ createTransformTask(taskConfig) {
2411
+ return new Task(
2412
+ `${this.name}_transform`,
2413
+ {
2414
+ // Use new single-parameter context API for handlers
2415
+ run: async ({ input }) => {
2416
+ const batch = input;
2417
+ console.log(
2418
+ `Running transform task for ${this.name} with ${batch.items.length} items...`
2419
+ );
2648
2420
  const transformedItems = [];
2649
- for (const extractedData of batch.items) {
2650
- const transformedData = await this.config.transform(extractedData);
2651
- transformedItems.push(transformedData);
2652
- }
2653
- if ("insert" in this.config.load) {
2654
- await this.config.load.insert(transformedItems);
2655
- } else {
2656
- await this.config.load(transformedItems);
2421
+ for (const item of batch.items) {
2422
+ const transformed = await this.config.transform(item);
2423
+ transformedItems.push(transformed);
2657
2424
  }
2658
2425
  console.log(
2659
- `Completed batch ${batchNumber} with ${batch.items.length} items`
2426
+ `Transform task completed with ${transformedItems.length} items`
2660
2427
  );
2661
- batchNumber++;
2662
- if (!batch.hasMore) {
2663
- break;
2664
- }
2665
- } while (true);
2666
- console.log(`Completed ETL Pipeline: ${this.name}`);
2428
+ return { items: transformedItems };
2429
+ },
2430
+ retries: taskConfig.retries,
2431
+ timeout: taskConfig.timeout
2667
2432
  }
2668
- };
2433
+ );
2669
2434
  }
2670
- });
2435
+ createLoadTask(taskConfig) {
2436
+ return new Task(`${this.name}_load`, {
2437
+ run: async ({ input: transformedItems }) => {
2438
+ console.log(
2439
+ `Running load task for ${this.name} with ${transformedItems.items.length} items...`
2440
+ );
2441
+ if ("insert" in this.config.load) {
2442
+ await this.config.load.insert(transformedItems.items);
2443
+ } else {
2444
+ await this.config.load(transformedItems.items);
2445
+ }
2446
+ console.log(`Load task completed`);
2447
+ },
2448
+ retries: taskConfig.retries,
2449
+ timeout: taskConfig.timeout
2450
+ });
2451
+ }
2452
+ // Execute the entire ETL pipeline
2453
+ async run() {
2454
+ console.log(`Starting ETL Pipeline: ${this.name}`);
2455
+ let batchNumber = 1;
2456
+ do {
2457
+ console.log(`Processing batch ${batchNumber}...`);
2458
+ const batch = await this.batcher.getNextBatch();
2459
+ if (batch.items.length === 0) {
2460
+ break;
2461
+ }
2462
+ const transformedItems = [];
2463
+ for (const extractedData of batch.items) {
2464
+ const transformedData = await this.config.transform(extractedData);
2465
+ transformedItems.push(transformedData);
2466
+ }
2467
+ if ("insert" in this.config.load) {
2468
+ await this.config.load.insert(transformedItems);
2469
+ } else {
2470
+ await this.config.load(transformedItems);
2471
+ }
2472
+ console.log(
2473
+ `Completed batch ${batchNumber} with ${batch.items.length} items`
2474
+ );
2475
+ batchNumber++;
2476
+ if (!batch.hasMore) {
2477
+ break;
2478
+ }
2479
+ } while (true);
2480
+ console.log(`Completed ETL Pipeline: ${this.name}`);
2481
+ }
2482
+ };
2671
2483
 
2672
2484
  // src/dmv2/sdk/materializedView.ts
2673
2485
  function formatTableReference(table) {
@@ -2677,147 +2489,127 @@ function formatTableReference(table) {
2677
2489
  }
2678
2490
  return `\`${table.name}\``;
2679
2491
  }
2680
- var requireTargetTableName, MaterializedView;
2681
- var init_materializedView = __esm({
2682
- "src/dmv2/sdk/materializedView.ts"() {
2683
- "use strict";
2684
- init_types();
2685
- init_sqlHelpers();
2686
- init_olapTable();
2687
- init_internal();
2688
- init_stackTrace();
2689
- requireTargetTableName = (tableName) => {
2690
- if (typeof tableName === "string") {
2691
- return tableName;
2692
- } else {
2693
- throw new Error("Name of targetTable is not specified.");
2694
- }
2695
- };
2696
- MaterializedView = class {
2697
- /** @internal */
2698
- kind = "MaterializedView";
2699
- /** The name of the materialized view */
2700
- name;
2701
- /** The target OlapTable instance where the materialized data is stored. */
2702
- targetTable;
2703
- /** The SELECT SQL statement */
2704
- selectSql;
2705
- /** Names of source tables that the SELECT reads from */
2706
- sourceTables;
2707
- /** Optional metadata for the materialized view */
2708
- metadata;
2709
- constructor(options, targetSchema, targetColumns) {
2710
- let selectStatement = options.selectStatement;
2711
- if (typeof selectStatement !== "string") {
2712
- selectStatement = toStaticQuery(selectStatement);
2713
- }
2714
- if (targetSchema === void 0 || targetColumns === void 0) {
2715
- throw new Error(
2716
- "Supply the type param T so that the schema is inserted by the compiler plugin."
2717
- );
2718
- }
2719
- const targetTable = options.targetTable instanceof OlapTable ? options.targetTable : new OlapTable(
2720
- requireTargetTableName(
2721
- options.targetTable?.name ?? options.tableName
2722
- ),
2723
- {
2724
- orderByFields: options.targetTable?.orderByFields ?? options.orderByFields,
2725
- engine: options.targetTable?.engine ?? options.engine ?? "MergeTree" /* MergeTree */
2726
- },
2727
- targetSchema,
2728
- targetColumns
2729
- );
2730
- if (targetTable.name === options.materializedViewName) {
2731
- throw new Error(
2732
- "Materialized view name cannot be the same as the target table name."
2733
- );
2734
- }
2735
- this.name = options.materializedViewName;
2736
- this.targetTable = targetTable;
2737
- this.selectSql = selectStatement;
2738
- this.sourceTables = options.selectTables.map(
2739
- (t) => formatTableReference(t)
2740
- );
2741
- this.metadata = options.metadata ? { ...options.metadata } : {};
2742
- if (!this.metadata.source) {
2743
- const stack = new Error().stack;
2744
- const sourceInfo = getSourceFileFromStack(stack);
2745
- if (sourceInfo) {
2746
- this.metadata.source = { file: sourceInfo };
2747
- }
2748
- }
2749
- const materializedViews = getMooseInternal().materializedViews;
2750
- if (!isClientOnlyMode() && materializedViews.has(this.name)) {
2751
- throw new Error(`MaterializedView with name ${this.name} already exists`);
2752
- }
2753
- materializedViews.set(this.name, this);
2492
+ var requireTargetTableName = (tableName) => {
2493
+ if (typeof tableName === "string") {
2494
+ return tableName;
2495
+ } else {
2496
+ throw new Error("Name of targetTable is not specified.");
2497
+ }
2498
+ };
2499
+ var MaterializedView = class {
2500
+ /** @internal */
2501
+ kind = "MaterializedView";
2502
+ /** The name of the materialized view */
2503
+ name;
2504
+ /** The target OlapTable instance where the materialized data is stored. */
2505
+ targetTable;
2506
+ /** The SELECT SQL statement */
2507
+ selectSql;
2508
+ /** Names of source tables that the SELECT reads from */
2509
+ sourceTables;
2510
+ /** Optional metadata for the materialized view */
2511
+ metadata;
2512
+ constructor(options, targetSchema, targetColumns) {
2513
+ let selectStatement = options.selectStatement;
2514
+ if (typeof selectStatement !== "string") {
2515
+ selectStatement = toStaticQuery(selectStatement);
2516
+ }
2517
+ if (targetSchema === void 0 || targetColumns === void 0) {
2518
+ throw new Error(
2519
+ "Supply the type param T so that the schema is inserted by the compiler plugin."
2520
+ );
2521
+ }
2522
+ const targetTable = options.targetTable instanceof OlapTable ? options.targetTable : new OlapTable(
2523
+ requireTargetTableName(
2524
+ options.targetTable?.name ?? options.tableName
2525
+ ),
2526
+ {
2527
+ orderByFields: options.targetTable?.orderByFields ?? options.orderByFields,
2528
+ engine: options.targetTable?.engine ?? options.engine ?? "MergeTree" /* MergeTree */
2529
+ },
2530
+ targetSchema,
2531
+ targetColumns
2532
+ );
2533
+ if (targetTable.name === options.materializedViewName) {
2534
+ throw new Error(
2535
+ "Materialized view name cannot be the same as the target table name."
2536
+ );
2537
+ }
2538
+ this.name = options.materializedViewName;
2539
+ this.targetTable = targetTable;
2540
+ this.selectSql = selectStatement;
2541
+ this.sourceTables = options.selectTables.map(
2542
+ (t) => formatTableReference(t)
2543
+ );
2544
+ this.metadata = options.metadata ? { ...options.metadata } : {};
2545
+ if (!this.metadata.source) {
2546
+ const stack = new Error().stack;
2547
+ const sourceInfo = getSourceFileFromStack(stack);
2548
+ if (sourceInfo) {
2549
+ this.metadata.source = { file: sourceInfo };
2754
2550
  }
2755
- };
2551
+ }
2552
+ const materializedViews = getMooseInternal().materializedViews;
2553
+ if (!isClientOnlyMode() && materializedViews.has(this.name)) {
2554
+ throw new Error(`MaterializedView with name ${this.name} already exists`);
2555
+ }
2556
+ materializedViews.set(this.name, this);
2756
2557
  }
2757
- });
2558
+ };
2758
2559
 
2759
2560
  // src/dmv2/sdk/sqlResource.ts
2760
- var SqlResource;
2761
- var init_sqlResource = __esm({
2762
- "src/dmv2/sdk/sqlResource.ts"() {
2763
- "use strict";
2764
- init_internal();
2765
- init_sqlHelpers();
2766
- init_stackTrace();
2767
- SqlResource = class {
2768
- /** @internal */
2769
- kind = "SqlResource";
2770
- /** Array of SQL statements to execute for setting up the resource. */
2771
- setup;
2772
- /** Array of SQL statements to execute for tearing down the resource. */
2773
- teardown;
2774
- /** The name of the SQL resource (e.g., view name, materialized view name). */
2775
- name;
2776
- /** List of OlapTables or Views that this resource reads data from. */
2777
- pullsDataFrom;
2778
- /** List of OlapTables or Views that this resource writes data to. */
2779
- pushesDataTo;
2780
- /** @internal Source file path where this resource was defined */
2781
- sourceFile;
2782
- /** @internal Source line number where this resource was defined */
2783
- sourceLine;
2784
- /** @internal Source column number where this resource was defined */
2785
- sourceColumn;
2786
- /**
2787
- * Creates a new SqlResource instance.
2788
- * @param name The name of the resource.
2789
- * @param setup An array of SQL DDL statements to create the resource.
2790
- * @param teardown An array of SQL DDL statements to drop the resource.
2791
- * @param options Optional configuration for specifying data dependencies.
2792
- * @param options.pullsDataFrom Tables/Views this resource reads from.
2793
- * @param options.pushesDataTo Tables/Views this resource writes to.
2794
- */
2795
- constructor(name, setup, teardown, options) {
2796
- const sqlResources = getMooseInternal().sqlResources;
2797
- if (!isClientOnlyMode() && sqlResources.has(name)) {
2798
- throw new Error(`SqlResource with name ${name} already exists`);
2799
- }
2800
- sqlResources.set(name, this);
2801
- this.name = name;
2802
- this.setup = setup.map(
2803
- (sql3) => typeof sql3 === "string" ? sql3 : toStaticQuery(sql3)
2804
- );
2805
- this.teardown = teardown.map(
2806
- (sql3) => typeof sql3 === "string" ? sql3 : toStaticQuery(sql3)
2807
- );
2808
- this.pullsDataFrom = options?.pullsDataFrom ?? [];
2809
- this.pushesDataTo = options?.pushesDataTo ?? [];
2810
- const stack = new Error().stack;
2811
- const location = getSourceLocationFromStack(stack);
2812
- if (location) {
2813
- this.sourceFile = location.file;
2814
- this.sourceLine = location.line;
2815
- this.sourceColumn = location.column;
2816
- }
2817
- }
2818
- };
2561
+ var SqlResource = class {
2562
+ /** @internal */
2563
+ kind = "SqlResource";
2564
+ /** Array of SQL statements to execute for setting up the resource. */
2565
+ setup;
2566
+ /** Array of SQL statements to execute for tearing down the resource. */
2567
+ teardown;
2568
+ /** The name of the SQL resource (e.g., view name, materialized view name). */
2569
+ name;
2570
+ /** List of OlapTables or Views that this resource reads data from. */
2571
+ pullsDataFrom;
2572
+ /** List of OlapTables or Views that this resource writes data to. */
2573
+ pushesDataTo;
2574
+ /** @internal Source file path where this resource was defined */
2575
+ sourceFile;
2576
+ /** @internal Source line number where this resource was defined */
2577
+ sourceLine;
2578
+ /** @internal Source column number where this resource was defined */
2579
+ sourceColumn;
2580
+ /**
2581
+ * Creates a new SqlResource instance.
2582
+ * @param name The name of the resource.
2583
+ * @param setup An array of SQL DDL statements to create the resource.
2584
+ * @param teardown An array of SQL DDL statements to drop the resource.
2585
+ * @param options Optional configuration for specifying data dependencies.
2586
+ * @param options.pullsDataFrom Tables/Views this resource reads from.
2587
+ * @param options.pushesDataTo Tables/Views this resource writes to.
2588
+ */
2589
+ constructor(name, setup, teardown, options) {
2590
+ const sqlResources = getMooseInternal().sqlResources;
2591
+ if (!isClientOnlyMode() && sqlResources.has(name)) {
2592
+ throw new Error(`SqlResource with name ${name} already exists`);
2593
+ }
2594
+ sqlResources.set(name, this);
2595
+ this.name = name;
2596
+ this.setup = setup.map(
2597
+ (sql3) => typeof sql3 === "string" ? sql3 : toStaticQuery(sql3)
2598
+ );
2599
+ this.teardown = teardown.map(
2600
+ (sql3) => typeof sql3 === "string" ? sql3 : toStaticQuery(sql3)
2601
+ );
2602
+ this.pullsDataFrom = options?.pullsDataFrom ?? [];
2603
+ this.pushesDataTo = options?.pushesDataTo ?? [];
2604
+ const stack = new Error().stack;
2605
+ const location = getSourceLocationFromStack(stack);
2606
+ if (location) {
2607
+ this.sourceFile = location.file;
2608
+ this.sourceLine = location.line;
2609
+ this.sourceColumn = location.column;
2610
+ }
2819
2611
  }
2820
- });
2612
+ };
2821
2613
 
2822
2614
  // src/dmv2/sdk/view.ts
2823
2615
  function formatTableReference2(table) {
@@ -2827,171 +2619,150 @@ function formatTableReference2(table) {
2827
2619
  }
2828
2620
  return `\`${table.name}\``;
2829
2621
  }
2830
- var View;
2831
- var init_view = __esm({
2832
- "src/dmv2/sdk/view.ts"() {
2833
- "use strict";
2834
- init_sqlHelpers();
2835
- init_olapTable();
2836
- init_internal();
2837
- init_stackTrace();
2838
- View = class {
2839
- /** @internal */
2840
- kind = "View";
2841
- /** The name of the view */
2842
- name;
2843
- /** The SELECT SQL statement that defines the view */
2844
- selectSql;
2845
- /** Names of source tables/views that the SELECT reads from */
2846
- sourceTables;
2847
- /** Optional metadata for the view */
2848
- metadata;
2849
- /**
2850
- * Creates a new View instance.
2851
- * @param name The name of the view to be created.
2852
- * @param selectStatement The SQL SELECT statement that defines the view's logic.
2853
- * @param baseTables An array of OlapTable or View objects that the `selectStatement` reads from. Used for dependency tracking.
2854
- * @param metadata Optional metadata for the view (e.g., description, source file).
2855
- */
2856
- constructor(name, selectStatement, baseTables, metadata) {
2857
- if (typeof selectStatement !== "string") {
2858
- selectStatement = toStaticQuery(selectStatement);
2859
- }
2860
- this.name = name;
2861
- this.selectSql = selectStatement;
2862
- this.sourceTables = baseTables.map((t) => formatTableReference2(t));
2863
- this.metadata = metadata ? { ...metadata } : {};
2864
- if (!this.metadata.source) {
2865
- const stack = new Error().stack;
2866
- const sourceInfo = getSourceFileFromStack(stack);
2867
- if (sourceInfo) {
2868
- this.metadata.source = { file: sourceInfo };
2869
- }
2870
- }
2871
- const views = getMooseInternal().views;
2872
- if (!isClientOnlyMode() && views.has(this.name)) {
2873
- throw new Error(`View with name ${this.name} already exists`);
2874
- }
2875
- views.set(this.name, this);
2622
+ var View = class {
2623
+ /** @internal */
2624
+ kind = "View";
2625
+ /** The name of the view */
2626
+ name;
2627
+ /** The SELECT SQL statement that defines the view */
2628
+ selectSql;
2629
+ /** Names of source tables/views that the SELECT reads from */
2630
+ sourceTables;
2631
+ /** Optional metadata for the view */
2632
+ metadata;
2633
+ /**
2634
+ * Creates a new View instance.
2635
+ * @param name The name of the view to be created.
2636
+ * @param selectStatement The SQL SELECT statement that defines the view's logic.
2637
+ * @param baseTables An array of OlapTable or View objects that the `selectStatement` reads from. Used for dependency tracking.
2638
+ * @param metadata Optional metadata for the view (e.g., description, source file).
2639
+ */
2640
+ constructor(name, selectStatement, baseTables, metadata) {
2641
+ if (typeof selectStatement !== "string") {
2642
+ selectStatement = toStaticQuery(selectStatement);
2643
+ }
2644
+ this.name = name;
2645
+ this.selectSql = selectStatement;
2646
+ this.sourceTables = baseTables.map((t) => formatTableReference2(t));
2647
+ this.metadata = metadata ? { ...metadata } : {};
2648
+ if (!this.metadata.source) {
2649
+ const stack = new Error().stack;
2650
+ const sourceInfo = getSourceFileFromStack(stack);
2651
+ if (sourceInfo) {
2652
+ this.metadata.source = { file: sourceInfo };
2876
2653
  }
2877
- };
2654
+ }
2655
+ const views = getMooseInternal().views;
2656
+ if (!isClientOnlyMode() && views.has(this.name)) {
2657
+ throw new Error(`View with name ${this.name} already exists`);
2658
+ }
2659
+ views.set(this.name, this);
2878
2660
  }
2879
- });
2661
+ };
2880
2662
 
2881
2663
  // src/dmv2/sdk/lifeCycle.ts
2882
- var LifeCycle;
2883
- var init_lifeCycle = __esm({
2884
- "src/dmv2/sdk/lifeCycle.ts"() {
2885
- "use strict";
2886
- LifeCycle = /* @__PURE__ */ ((LifeCycle2) => {
2887
- LifeCycle2["FULLY_MANAGED"] = "FULLY_MANAGED";
2888
- LifeCycle2["DELETION_PROTECTED"] = "DELETION_PROTECTED";
2889
- LifeCycle2["EXTERNALLY_MANAGED"] = "EXTERNALLY_MANAGED";
2890
- return LifeCycle2;
2891
- })(LifeCycle || {});
2892
- }
2893
- });
2664
+ var LifeCycle = /* @__PURE__ */ ((LifeCycle2) => {
2665
+ LifeCycle2["FULLY_MANAGED"] = "FULLY_MANAGED";
2666
+ LifeCycle2["DELETION_PROTECTED"] = "DELETION_PROTECTED";
2667
+ LifeCycle2["EXTERNALLY_MANAGED"] = "EXTERNALLY_MANAGED";
2668
+ return LifeCycle2;
2669
+ })(LifeCycle || {});
2894
2670
 
2895
2671
  // src/dmv2/sdk/webApp.ts
2896
- var RESERVED_MOUNT_PATHS, WebApp;
2897
- var init_webApp = __esm({
2898
- "src/dmv2/sdk/webApp.ts"() {
2899
- "use strict";
2900
- init_internal();
2901
- RESERVED_MOUNT_PATHS = [
2902
- "/admin",
2903
- "/api",
2904
- "/consumption",
2905
- "/health",
2906
- "/ingest",
2907
- "/moose",
2908
- // reserved for future use
2909
- "/ready",
2910
- "/workflows"
2911
- ];
2912
- WebApp = class {
2913
- name;
2914
- handler;
2915
- config;
2916
- _rawApp;
2917
- constructor(name, appOrHandler, config) {
2918
- this.name = name;
2919
- this.config = config;
2920
- if (!this.config.mountPath) {
2921
- throw new Error(
2922
- `mountPath is required. Please specify a mount path for your WebApp (e.g., "/myapi").`
2923
- );
2924
- }
2925
- const mountPath = this.config.mountPath;
2926
- if (mountPath === "/") {
2927
- throw new Error(
2928
- `mountPath cannot be "/" as it would allow routes to overlap with reserved paths: ${RESERVED_MOUNT_PATHS.join(", ")}`
2929
- );
2930
- }
2931
- if (mountPath.endsWith("/")) {
2672
+ var RESERVED_MOUNT_PATHS = [
2673
+ "/admin",
2674
+ "/api",
2675
+ "/consumption",
2676
+ "/health",
2677
+ "/ingest",
2678
+ "/moose",
2679
+ // reserved for future use
2680
+ "/ready",
2681
+ "/workflows"
2682
+ ];
2683
+ var WebApp = class {
2684
+ name;
2685
+ handler;
2686
+ config;
2687
+ _rawApp;
2688
+ constructor(name, appOrHandler, config) {
2689
+ this.name = name;
2690
+ this.config = config;
2691
+ if (!this.config.mountPath) {
2692
+ throw new Error(
2693
+ `mountPath is required. Please specify a mount path for your WebApp (e.g., "/myapi").`
2694
+ );
2695
+ }
2696
+ const mountPath = this.config.mountPath;
2697
+ if (mountPath === "/") {
2698
+ throw new Error(
2699
+ `mountPath cannot be "/" as it would allow routes to overlap with reserved paths: ${RESERVED_MOUNT_PATHS.join(", ")}`
2700
+ );
2701
+ }
2702
+ if (mountPath.endsWith("/")) {
2703
+ throw new Error(
2704
+ `mountPath cannot end with a trailing slash. Remove the '/' from: "${mountPath}"`
2705
+ );
2706
+ }
2707
+ for (const reserved of RESERVED_MOUNT_PATHS) {
2708
+ if (mountPath === reserved || mountPath.startsWith(`${reserved}/`)) {
2709
+ throw new Error(
2710
+ `mountPath cannot begin with a reserved path: ${RESERVED_MOUNT_PATHS.join(", ")}. Got: "${mountPath}"`
2711
+ );
2712
+ }
2713
+ }
2714
+ this.handler = this.toHandler(appOrHandler);
2715
+ this._rawApp = typeof appOrHandler === "function" ? void 0 : appOrHandler;
2716
+ const webApps = getMooseInternal().webApps;
2717
+ if (webApps.has(name)) {
2718
+ throw new Error(`WebApp with name ${name} already exists`);
2719
+ }
2720
+ if (this.config.mountPath) {
2721
+ for (const [existingName, existingApp] of webApps) {
2722
+ if (existingApp.config.mountPath === this.config.mountPath) {
2932
2723
  throw new Error(
2933
- `mountPath cannot end with a trailing slash. Remove the '/' from: "${mountPath}"`
2724
+ `WebApp with mountPath "${this.config.mountPath}" already exists (used by WebApp "${existingName}")`
2934
2725
  );
2935
2726
  }
2936
- for (const reserved of RESERVED_MOUNT_PATHS) {
2937
- if (mountPath === reserved || mountPath.startsWith(`${reserved}/`)) {
2938
- throw new Error(
2939
- `mountPath cannot begin with a reserved path: ${RESERVED_MOUNT_PATHS.join(", ")}. Got: "${mountPath}"`
2940
- );
2941
- }
2942
- }
2943
- this.handler = this.toHandler(appOrHandler);
2944
- this._rawApp = typeof appOrHandler === "function" ? void 0 : appOrHandler;
2945
- const webApps = getMooseInternal().webApps;
2946
- if (webApps.has(name)) {
2947
- throw new Error(`WebApp with name ${name} already exists`);
2948
- }
2949
- if (this.config.mountPath) {
2950
- for (const [existingName, existingApp] of webApps) {
2951
- if (existingApp.config.mountPath === this.config.mountPath) {
2952
- throw new Error(
2953
- `WebApp with mountPath "${this.config.mountPath}" already exists (used by WebApp "${existingName}")`
2954
- );
2955
- }
2956
- }
2957
- }
2958
- webApps.set(name, this);
2959
2727
  }
2960
- toHandler(appOrHandler) {
2961
- if (typeof appOrHandler === "function") {
2962
- return appOrHandler;
2963
- }
2964
- const app = appOrHandler;
2965
- if (typeof app.handle === "function") {
2966
- return (req, res) => {
2967
- app.handle(req, res, (err) => {
2968
- if (err) {
2969
- console.error("WebApp handler error:", err);
2970
- if (!res.headersSent) {
2971
- res.writeHead(500, { "Content-Type": "application/json" });
2972
- res.end(JSON.stringify({ error: "Internal Server Error" }));
2973
- }
2974
- }
2975
- });
2976
- };
2977
- }
2978
- if (typeof app.callback === "function") {
2979
- return app.callback();
2980
- }
2981
- if (typeof app.routing === "function") {
2982
- const routing = app.routing;
2983
- const appWithReady = app;
2984
- let readyPromise = null;
2985
- return async (req, res) => {
2986
- if (readyPromise === null) {
2987
- readyPromise = typeof appWithReady.ready === "function" ? appWithReady.ready() : Promise.resolve();
2728
+ }
2729
+ webApps.set(name, this);
2730
+ }
2731
+ toHandler(appOrHandler) {
2732
+ if (typeof appOrHandler === "function") {
2733
+ return appOrHandler;
2734
+ }
2735
+ const app = appOrHandler;
2736
+ if (typeof app.handle === "function") {
2737
+ return (req, res) => {
2738
+ app.handle(req, res, (err) => {
2739
+ if (err) {
2740
+ console.error("WebApp handler error:", err);
2741
+ if (!res.headersSent) {
2742
+ res.writeHead(500, { "Content-Type": "application/json" });
2743
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
2988
2744
  }
2989
- await readyPromise;
2990
- routing(req, res);
2991
- };
2992
- }
2993
- throw new Error(
2994
- `Unable to convert app to handler. The provided object must be:
2745
+ }
2746
+ });
2747
+ };
2748
+ }
2749
+ if (typeof app.callback === "function") {
2750
+ return app.callback();
2751
+ }
2752
+ if (typeof app.routing === "function") {
2753
+ const routing = app.routing;
2754
+ const appWithReady = app;
2755
+ let readyPromise = null;
2756
+ return async (req, res) => {
2757
+ if (readyPromise === null) {
2758
+ readyPromise = typeof appWithReady.ready === "function" ? appWithReady.ready() : Promise.resolve();
2759
+ }
2760
+ await readyPromise;
2761
+ routing(req, res);
2762
+ };
2763
+ }
2764
+ throw new Error(
2765
+ `Unable to convert app to handler. The provided object must be:
2995
2766
  - A function (raw Node.js handler)
2996
2767
  - An object with .handle() method (Express, Connect)
2997
2768
  - An object with .callback() method (Koa)
@@ -3003,14 +2774,12 @@ Examples:
3003
2774
  Fastify: new WebApp("name", fastifyApp)
3004
2775
  Raw: new WebApp("name", (req, res) => { ... })
3005
2776
  `
3006
- );
3007
- }
3008
- getRawApp() {
3009
- return this._rawApp;
3010
- }
3011
- };
2777
+ );
3012
2778
  }
3013
- });
2779
+ getRawApp() {
2780
+ return this._rawApp;
2781
+ }
2782
+ };
3014
2783
 
3015
2784
  // src/dmv2/registry.ts
3016
2785
  function getTables() {
@@ -3088,71 +2857,6 @@ function getViews() {
3088
2857
  function getView(name) {
3089
2858
  return getMooseInternal().views.get(name);
3090
2859
  }
3091
- var init_registry = __esm({
3092
- "src/dmv2/registry.ts"() {
3093
- "use strict";
3094
- init_internal();
3095
- }
3096
- });
3097
-
3098
- // src/dmv2/index.ts
3099
- var dmv2_exports = {};
3100
- __export(dmv2_exports, {
3101
- Api: () => Api,
3102
- ClickHouseEngines: () => ClickHouseEngines,
3103
- ConsumptionApi: () => ConsumptionApi,
3104
- DeadLetterQueue: () => DeadLetterQueue,
3105
- ETLPipeline: () => ETLPipeline,
3106
- IngestApi: () => IngestApi,
3107
- IngestPipeline: () => IngestPipeline,
3108
- LifeCycle: () => LifeCycle,
3109
- MaterializedView: () => MaterializedView,
3110
- OlapTable: () => OlapTable,
3111
- SqlResource: () => SqlResource,
3112
- Stream: () => Stream,
3113
- Task: () => Task,
3114
- View: () => View,
3115
- WebApp: () => WebApp,
3116
- Workflow: () => Workflow,
3117
- getApi: () => getApi,
3118
- getApis: () => getApis,
3119
- getIngestApi: () => getIngestApi,
3120
- getIngestApis: () => getIngestApis,
3121
- getMaterializedView: () => getMaterializedView,
3122
- getMaterializedViews: () => getMaterializedViews,
3123
- getSqlResource: () => getSqlResource,
3124
- getSqlResources: () => getSqlResources,
3125
- getStream: () => getStream,
3126
- getStreams: () => getStreams,
3127
- getTable: () => getTable,
3128
- getTables: () => getTables,
3129
- getView: () => getView,
3130
- getViews: () => getViews,
3131
- getWebApp: () => getWebApp,
3132
- getWebApps: () => getWebApps,
3133
- getWorkflow: () => getWorkflow,
3134
- getWorkflows: () => getWorkflows
3135
- });
3136
- module.exports = __toCommonJS(dmv2_exports);
3137
- var init_dmv2 = __esm({
3138
- "src/dmv2/index.ts"() {
3139
- init_olapTable();
3140
- init_types();
3141
- init_stream();
3142
- init_workflow();
3143
- init_ingestApi();
3144
- init_consumptionApi();
3145
- init_ingestPipeline();
3146
- init_etlPipeline();
3147
- init_materializedView();
3148
- init_sqlResource();
3149
- init_view();
3150
- init_lifeCycle();
3151
- init_webApp();
3152
- init_registry();
3153
- }
3154
- });
3155
- init_dmv2();
3156
2860
  // Annotate the CommonJS export names for ESM import in node:
3157
2861
  0 && (module.exports = {
3158
2862
  Api,