@kadoa/node-sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  import { EventEmitter } from 'events';
2
- import globalAxios2, { AxiosError } from 'axios';
2
+ import globalAxios2, { isAxiosError } from 'axios';
3
+ import { URL, URLSearchParams } from 'url';
3
4
  import { merge } from 'es-toolkit/object';
4
- import { URL as URL$1, URLSearchParams } from 'url';
5
5
 
6
- // src/events/index.ts
6
+ // src/core/events/event-emitter.ts
7
7
  var KadoaEventEmitter = class extends EventEmitter {
8
8
  /**
9
9
  * Emit a typed SDK event
@@ -44,8 +44,8 @@ var KadoaEventEmitter = class extends EventEmitter {
44
44
  }
45
45
  };
46
46
 
47
- // src/exceptions/kadoa-sdk.exception.ts
48
- var KadoaSdkException = class _KadoaSdkException extends Error {
47
+ // src/core/exceptions/base.exception.ts
48
+ var _KadoaSdkException = class _KadoaSdkException extends Error {
49
49
  constructor(message, options) {
50
50
  super(message);
51
51
  this.name = "KadoaSdkException";
@@ -74,9 +74,54 @@ var KadoaSdkException = class _KadoaSdkException extends Error {
74
74
  toString() {
75
75
  return [this.name, this.code, this.message].filter(Boolean).join(": ");
76
76
  }
77
+ toDetailedString() {
78
+ const parts = [`${this.name}: ${this.message}`, `Code: ${this.code}`];
79
+ if (this.details && Object.keys(this.details).length > 0) {
80
+ parts.push(`Details: ${JSON.stringify(this.details, null, 2)}`);
81
+ }
82
+ if (this.cause) {
83
+ parts.push(`Cause: ${this.cause}`);
84
+ }
85
+ return parts.join("\n");
86
+ }
87
+ static isInstance(error) {
88
+ return error instanceof _KadoaSdkException;
89
+ }
90
+ static wrap(error, extra) {
91
+ if (error instanceof _KadoaSdkException) return error;
92
+ const message = extra?.message || (error instanceof Error ? error.message : typeof error === "string" ? error : "Unexpected error");
93
+ return new _KadoaSdkException(message, {
94
+ code: "UNKNOWN",
95
+ details: extra?.details,
96
+ cause: error
97
+ });
98
+ }
77
99
  };
78
-
79
- // src/exceptions/http.exception.ts
100
+ _KadoaSdkException.ERROR_MESSAGES = {
101
+ // General errors
102
+ CONFIG_ERROR: "Invalid configuration provided",
103
+ AUTH_FAILED: "Authentication failed. Please check your API key",
104
+ RATE_LIMITED: "Rate limit exceeded. Please try again later",
105
+ NETWORK_ERROR: "Network error occurred",
106
+ SERVER_ERROR: "Server error occurred",
107
+ PARSE_ERROR: "Failed to parse response",
108
+ // Workflow specific errors
109
+ NO_WORKFLOW_ID: "Failed to start extraction process - no ID received",
110
+ WORKFLOW_CREATE_FAILED: "Failed to create workflow",
111
+ WORKFLOW_TIMEOUT: "Workflow processing timed out",
112
+ WORKFLOW_UNEXPECTED_STATUS: "Extraction completed with unexpected status",
113
+ PROGRESS_CHECK_FAILED: "Failed to check extraction progress",
114
+ DATA_FETCH_FAILED: "Failed to retrieve extracted data from workflow",
115
+ // Extraction specific errors
116
+ NO_URLS: "At least one URL is required for extraction",
117
+ NO_API_KEY: "API key is required for entity detection",
118
+ LINK_REQUIRED: "Link is required for entity field detection",
119
+ NO_PREDICTIONS: "No entity predictions returned from the API",
120
+ EXTRACTION_FAILED: "Data extraction failed for the provided URLs",
121
+ ENTITY_FETCH_FAILED: "Failed to fetch entity fields"
122
+ };
123
+ var KadoaSdkException = _KadoaSdkException;
124
+ var ERROR_MESSAGES = KadoaSdkException.ERROR_MESSAGES;
80
125
  var KadoaHttpException = class _KadoaHttpException extends KadoaSdkException {
81
126
  constructor(message, options) {
82
127
  super(message, {
@@ -117,10 +162,43 @@ var KadoaHttpException = class _KadoaHttpException extends KadoaSdkException {
117
162
  responseBody: this.responseBody
118
163
  };
119
164
  }
120
- static mapStatusToCode(error) {
121
- const status = error.response?.status;
165
+ toDetailedString() {
166
+ const parts = [`${this.name}: ${this.message}`, `Code: ${this.code}`];
167
+ if (this.httpStatus) {
168
+ parts.push(`HTTP Status: ${this.httpStatus}`);
169
+ }
170
+ if (this.method && this.endpoint) {
171
+ parts.push(`Request: ${this.method} ${this.endpoint}`);
172
+ }
173
+ if (this.requestId) {
174
+ parts.push(`Request ID: ${this.requestId}`);
175
+ }
176
+ if (this.responseBody) {
177
+ parts.push(
178
+ `Response Body: ${JSON.stringify(this.responseBody, null, 2)}`
179
+ );
180
+ }
181
+ if (this.details && Object.keys(this.details).length > 0) {
182
+ parts.push(`Details: ${JSON.stringify(this.details, null, 2)}`);
183
+ }
184
+ if (this.cause) {
185
+ parts.push(`Cause: ${this.cause}`);
186
+ }
187
+ return parts.join("\n");
188
+ }
189
+ static wrap(error, extra) {
190
+ if (error instanceof _KadoaHttpException) return error;
191
+ if (error instanceof KadoaSdkException) return error;
192
+ if (isAxiosError(error)) {
193
+ return _KadoaHttpException.fromAxiosError(error, extra);
194
+ }
195
+ return KadoaSdkException.wrap(error, extra);
196
+ }
197
+ static mapStatusToCode(errorOrStatus) {
198
+ const status = typeof errorOrStatus === "number" ? errorOrStatus : errorOrStatus.response?.status;
122
199
  if (!status) {
123
- return error.code === "ECONNABORTED" ? "TIMEOUT" : error.request ? "NETWORK_ERROR" : "UNKNOWN";
200
+ if (typeof errorOrStatus === "number") return "UNKNOWN";
201
+ return errorOrStatus.code === "ECONNABORTED" ? "TIMEOUT" : errorOrStatus.request ? "NETWORK_ERROR" : "UNKNOWN";
124
202
  }
125
203
  if (status === 401 || status === 403) return "AUTH_ERROR";
126
204
  if (status === 404) return "NOT_FOUND";
@@ -131,53 +209,6 @@ var KadoaHttpException = class _KadoaHttpException extends KadoaSdkException {
131
209
  return "UNKNOWN";
132
210
  }
133
211
  };
134
- function isKadoaSdkException(error) {
135
- return error instanceof KadoaSdkException;
136
- }
137
- function isKadoaHttpException(error) {
138
- return error instanceof KadoaHttpException;
139
- }
140
- function wrapKadoaError(error, extra) {
141
- if (error instanceof AxiosError)
142
- return KadoaHttpException.fromAxiosError(error, extra);
143
- return KadoaSdkException.from(error, extra?.details);
144
- }
145
-
146
- // src/extraction/constants.ts
147
- var DEFAULT_OPTIONS = {
148
- pollingInterval: 5e3,
149
- maxWaitTime: 3e5,
150
- navigationMode: "single-page",
151
- location: { type: "auto" },
152
- name: "Untitled Workflow",
153
- maxRecords: 99999
154
- };
155
- var TERMINAL_RUN_STATES = /* @__PURE__ */ new Set([
156
- "FINISHED",
157
- "SUCCESS",
158
- "FAILED",
159
- "ERROR",
160
- "STOPPED",
161
- "CANCELLED"
162
- ]);
163
- var SUCCESSFUL_RUN_STATES = /* @__PURE__ */ new Set(["FINISHED", "SUCCESS"]);
164
- var ENTITY_API_ENDPOINT = "/v4/entity";
165
- var DEFAULT_API_BASE_URL = "https://api.kadoa.com";
166
- var ERROR_MESSAGES = {
167
- NO_URLS: "At least one URL is required for extraction",
168
- NO_API_KEY: "API key is required for entity detection",
169
- LINK_REQUIRED: "Link is required for entity field detection",
170
- NO_WORKFLOW_ID: "Failed to start extraction process - no ID received",
171
- NO_PREDICTIONS: "No entity predictions returned from the API",
172
- PARSE_ERROR: "Failed to parse entity response",
173
- NETWORK_ERROR: "Network error while fetching entity fields",
174
- AUTH_FAILED: "Authentication failed. Please check your API key",
175
- RATE_LIMITED: "Rate limit exceeded. Please try again later",
176
- SERVER_ERROR: "Server error while fetching entity fields",
177
- DATA_FETCH_FAILED: "Failed to retrieve extracted data from workflow",
178
- PROGRESS_CHECK_FAILED: "Failed to check extraction progress",
179
- EXTRACTION_FAILED: "Data extraction failed for the provided URLs"
180
- };
181
212
  var BASE_PATH = "https://api.kadoa.com".replace(/\/+$/, "");
182
213
  var BaseAPI = class {
183
214
  constructor(configuration, basePath = BASE_PATH, axios2 = globalAxios2) {
@@ -266,7 +297,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
266
297
  v4ChangesChangeIdGet: async (changeId, xApiKey, authorization, options = {}) => {
267
298
  assertParamExists("v4ChangesChangeIdGet", "changeId", changeId);
268
299
  const localVarPath = `/v4/changes/{changeId}`.replace(`{${"changeId"}}`, encodeURIComponent(String(changeId)));
269
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
300
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
270
301
  let baseOptions;
271
302
  if (configuration) {
272
303
  baseOptions = configuration.baseOptions;
@@ -305,7 +336,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
305
336
  */
306
337
  v4ChangesGet: async (xApiKey, authorization, workflowIds, startDate, endDate, skip, limit, options = {}) => {
307
338
  const localVarPath = `/v4/changes`;
308
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
339
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
309
340
  let baseOptions;
310
341
  if (configuration) {
311
342
  baseOptions = configuration.baseOptions;
@@ -362,7 +393,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
362
393
  */
363
394
  v4WorkflowsGet: async (search, skip, limit, state, tags, monitoring, updateInterval, templateId, includeDeleted, format, options = {}) => {
364
395
  const localVarPath = `/v4/workflows`;
365
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
396
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
366
397
  let baseOptions;
367
398
  if (configuration) {
368
399
  baseOptions = configuration.baseOptions;
@@ -419,7 +450,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
419
450
  v4WorkflowsPost: async (v4WorkflowsPostRequest, options = {}) => {
420
451
  assertParamExists("v4WorkflowsPost", "v4WorkflowsPostRequest", v4WorkflowsPostRequest);
421
452
  const localVarPath = `/v4/workflows`;
422
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
453
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
423
454
  let baseOptions;
424
455
  if (configuration) {
425
456
  baseOptions = configuration.baseOptions;
@@ -449,7 +480,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
449
480
  v4WorkflowsSetupEditPost: async (v4WorkflowsSetupEditPostRequest, options = {}) => {
450
481
  assertParamExists("v4WorkflowsSetupEditPost", "v4WorkflowsSetupEditPostRequest", v4WorkflowsSetupEditPostRequest);
451
482
  const localVarPath = `/v4/workflows/setup/edit`;
452
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
483
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
453
484
  let baseOptions;
454
485
  if (configuration) {
455
486
  baseOptions = configuration.baseOptions;
@@ -478,7 +509,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
478
509
  v4WorkflowsSetupPost: async (v4WorkflowsSetupPostRequest, options = {}) => {
479
510
  assertParamExists("v4WorkflowsSetupPost", "v4WorkflowsSetupPostRequest", v4WorkflowsSetupPostRequest);
480
511
  const localVarPath = `/v4/workflows/setup`;
481
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
512
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
482
513
  let baseOptions;
483
514
  if (configuration) {
484
515
  baseOptions = configuration.baseOptions;
@@ -511,7 +542,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
511
542
  v4WorkflowsWorkflowIdAuditlogGet: async (workflowId, xApiKey, authorization, page, limit, options = {}) => {
512
543
  assertParamExists("v4WorkflowsWorkflowIdAuditlogGet", "workflowId", workflowId);
513
544
  const localVarPath = `/v4/workflows/{workflowId}/auditlog`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
514
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
545
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
515
546
  let baseOptions;
516
547
  if (configuration) {
517
548
  baseOptions = configuration.baseOptions;
@@ -553,7 +584,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
553
584
  v4WorkflowsWorkflowIdComplianceApprovePut: async (workflowId, xApiKey, authorization, options = {}) => {
554
585
  assertParamExists("v4WorkflowsWorkflowIdComplianceApprovePut", "workflowId", workflowId);
555
586
  const localVarPath = `/v4/workflows/{workflowId}/compliance-approve`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
556
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
587
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
557
588
  let baseOptions;
558
589
  if (configuration) {
559
590
  baseOptions = configuration.baseOptions;
@@ -590,7 +621,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
590
621
  assertParamExists("v4WorkflowsWorkflowIdComplianceRejectPut", "workflowId", workflowId);
591
622
  assertParamExists("v4WorkflowsWorkflowIdComplianceRejectPut", "v4WorkflowsWorkflowIdComplianceRejectPutRequest", v4WorkflowsWorkflowIdComplianceRejectPutRequest);
592
623
  const localVarPath = `/v4/workflows/{workflowId}/compliance-reject`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
593
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
624
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
594
625
  let baseOptions;
595
626
  if (configuration) {
596
627
  baseOptions = configuration.baseOptions;
@@ -637,7 +668,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
637
668
  v4WorkflowsWorkflowIdDataGet: async (workflowId, xApiKey, authorization, runId, format, sortBy, order, filters, page, limit, gzip, rowIds, includeAnomalies, options = {}) => {
638
669
  assertParamExists("v4WorkflowsWorkflowIdDataGet", "workflowId", workflowId);
639
670
  const localVarPath = `/v4/workflows/{workflowId}/data`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
640
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
671
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
641
672
  let baseOptions;
642
673
  if (configuration) {
643
674
  baseOptions = configuration.baseOptions;
@@ -701,7 +732,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
701
732
  v4WorkflowsWorkflowIdDelete: async (workflowId, options = {}) => {
702
733
  assertParamExists("v4WorkflowsWorkflowIdDelete", "workflowId", workflowId);
703
734
  const localVarPath = `/v4/workflows/{workflowId}`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
704
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
735
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
705
736
  let baseOptions;
706
737
  if (configuration) {
707
738
  baseOptions = configuration.baseOptions;
@@ -728,7 +759,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
728
759
  v4WorkflowsWorkflowIdGet: async (workflowId, options = {}) => {
729
760
  assertParamExists("v4WorkflowsWorkflowIdGet", "workflowId", workflowId);
730
761
  const localVarPath = `/v4/workflows/{workflowId}`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
731
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
762
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
732
763
  let baseOptions;
733
764
  if (configuration) {
734
765
  baseOptions = configuration.baseOptions;
@@ -755,7 +786,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
755
786
  v4WorkflowsWorkflowIdHistoryGet: async (workflowId, options = {}) => {
756
787
  assertParamExists("v4WorkflowsWorkflowIdHistoryGet", "workflowId", workflowId);
757
788
  const localVarPath = `/v4/workflows/{workflowId}/history`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
758
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
789
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
759
790
  let baseOptions;
760
791
  if (configuration) {
761
792
  baseOptions = configuration.baseOptions;
@@ -784,7 +815,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
784
815
  assertParamExists("v4WorkflowsWorkflowIdMetadataPut", "workflowId", workflowId);
785
816
  assertParamExists("v4WorkflowsWorkflowIdMetadataPut", "v4WorkflowsWorkflowIdMetadataPutRequest", v4WorkflowsWorkflowIdMetadataPutRequest);
786
817
  const localVarPath = `/v4/workflows/{workflowId}/metadata`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
787
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
818
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
788
819
  let baseOptions;
789
820
  if (configuration) {
790
821
  baseOptions = configuration.baseOptions;
@@ -813,7 +844,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
813
844
  v4WorkflowsWorkflowIdPausePut: async (workflowId, options = {}) => {
814
845
  assertParamExists("v4WorkflowsWorkflowIdPausePut", "workflowId", workflowId);
815
846
  const localVarPath = `/v4/workflows/{workflowId}/pause`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
816
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
847
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
817
848
  let baseOptions;
818
849
  if (configuration) {
819
850
  baseOptions = configuration.baseOptions;
@@ -840,7 +871,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
840
871
  v4WorkflowsWorkflowIdResumePut: async (workflowId, options = {}) => {
841
872
  assertParamExists("v4WorkflowsWorkflowIdResumePut", "workflowId", workflowId);
842
873
  const localVarPath = `/v4/workflows/{workflowId}/resume`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
843
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
874
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
844
875
  let baseOptions;
845
876
  if (configuration) {
846
877
  baseOptions = configuration.baseOptions;
@@ -867,7 +898,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
867
898
  v4WorkflowsWorkflowIdRunPut: async (workflowId, options = {}) => {
868
899
  assertParamExists("v4WorkflowsWorkflowIdRunPut", "workflowId", workflowId);
869
900
  const localVarPath = `/v4/workflows/{workflowId}/run`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
870
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
901
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
871
902
  let baseOptions;
872
903
  if (configuration) {
873
904
  baseOptions = configuration.baseOptions;
@@ -896,7 +927,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
896
927
  assertParamExists("v4WorkflowsWorkflowIdSchedulePut", "workflowId", workflowId);
897
928
  assertParamExists("v4WorkflowsWorkflowIdSchedulePut", "v4WorkflowsWorkflowIdSchedulePutRequest", v4WorkflowsWorkflowIdSchedulePutRequest);
898
929
  const localVarPath = `/v4/workflows/{workflowId}/schedule`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
899
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
930
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
900
931
  let baseOptions;
901
932
  if (configuration) {
902
933
  baseOptions = configuration.baseOptions;
@@ -927,7 +958,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
927
958
  v5ChangesChangeIdGet: async (changeId, xApiKey, authorization, options = {}) => {
928
959
  assertParamExists("v5ChangesChangeIdGet", "changeId", changeId);
929
960
  const localVarPath = `/v5/changes/{changeId}`.replace(`{${"changeId"}}`, encodeURIComponent(String(changeId)));
930
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
961
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
931
962
  let baseOptions;
932
963
  if (configuration) {
933
964
  baseOptions = configuration.baseOptions;
@@ -966,7 +997,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
966
997
  */
967
998
  v5ChangesGet: async (xApiKey, authorization, workflowIds, startDate, endDate, skip, limit, options = {}) => {
968
999
  const localVarPath = `/v5/changes`;
969
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
1000
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
970
1001
  let baseOptions;
971
1002
  if (configuration) {
972
1003
  baseOptions = configuration.baseOptions;
@@ -1015,7 +1046,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
1015
1046
  v5WorkflowsIdDelete: async (id, options = {}) => {
1016
1047
  assertParamExists("v5WorkflowsIdDelete", "id", id);
1017
1048
  const localVarPath = `/v5/workflows/{id}`.replace(`{${"id"}}`, encodeURIComponent(String(id)));
1018
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
1049
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
1019
1050
  let baseOptions;
1020
1051
  if (configuration) {
1021
1052
  baseOptions = configuration.baseOptions;
@@ -1043,7 +1074,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
1043
1074
  v5WorkflowsIdGet: async (id, options = {}) => {
1044
1075
  assertParamExists("v5WorkflowsIdGet", "id", id);
1045
1076
  const localVarPath = `/v5/workflows/{id}`.replace(`{${"id"}}`, encodeURIComponent(String(id)));
1046
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
1077
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
1047
1078
  let baseOptions;
1048
1079
  if (configuration) {
1049
1080
  baseOptions = configuration.baseOptions;
@@ -1073,7 +1104,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
1073
1104
  assertParamExists("v5WorkflowsIdPut", "id", id);
1074
1105
  assertParamExists("v5WorkflowsIdPut", "v5WorkflowsIdPutRequest", v5WorkflowsIdPutRequest);
1075
1106
  const localVarPath = `/v5/workflows/{id}`.replace(`{${"id"}}`, encodeURIComponent(String(id)));
1076
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
1107
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
1077
1108
  let baseOptions;
1078
1109
  if (configuration) {
1079
1110
  baseOptions = configuration.baseOptions;
@@ -1103,7 +1134,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
1103
1134
  v5WorkflowsPost: async (v5WorkflowsPostRequest, options = {}) => {
1104
1135
  assertParamExists("v5WorkflowsPost", "v5WorkflowsPostRequest", v5WorkflowsPostRequest);
1105
1136
  const localVarPath = `/v5/workflows`;
1106
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
1137
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
1107
1138
  let baseOptions;
1108
1139
  if (configuration) {
1109
1140
  baseOptions = configuration.baseOptions;
@@ -1137,7 +1168,7 @@ var WorkflowsApiAxiosParamCreator = function(configuration) {
1137
1168
  v5WorkflowsWorkflowIdAuditlogGet: async (workflowId, xApiKey, authorization, page, limit, options = {}) => {
1138
1169
  assertParamExists("v5WorkflowsWorkflowIdAuditlogGet", "workflowId", workflowId);
1139
1170
  const localVarPath = `/v5/workflows/{workflowId}/auditlog`.replace(`{${"workflowId"}}`, encodeURIComponent(String(workflowId)));
1140
- const localVarUrlObj = new URL$1(localVarPath, DUMMY_BASE_URL);
1171
+ const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
1141
1172
  let baseOptions;
1142
1173
  if (configuration) {
1143
1174
  baseOptions = configuration.baseOptions;
@@ -1863,404 +1894,545 @@ var Configuration = class {
1863
1894
  }
1864
1895
  };
1865
1896
 
1866
- // src/api-client.ts
1897
+ // src/core/patterns/command.ts
1898
+ var Command = class {
1899
+ };
1900
+
1901
+ // src/core/http/client-factory.ts
1867
1902
  var workflowsApiCache = /* @__PURE__ */ new WeakMap();
1868
- function getWorkflowsApi(sdk) {
1869
- let api = workflowsApiCache.get(sdk);
1903
+ function getWorkflowsApi(client) {
1904
+ let api = workflowsApiCache.get(client);
1870
1905
  if (!api) {
1871
- api = new WorkflowsApi(sdk.configuration, sdk.baseUrl, sdk.axiosInstance);
1872
- workflowsApiCache.set(sdk, api);
1906
+ api = new WorkflowsApi(
1907
+ client.configuration,
1908
+ client.baseUrl,
1909
+ client.axiosInstance
1910
+ );
1911
+ workflowsApiCache.set(client, api);
1873
1912
  }
1874
1913
  return api;
1875
1914
  }
1876
1915
 
1877
- // src/extraction/data-fetcher.ts
1878
- async function fetchWorkflowData(sdkInstance, workflowId, limit = DEFAULT_OPTIONS.dataLimit) {
1879
- const workflowsApi = getWorkflowsApi(sdkInstance);
1880
- try {
1881
- const response = await workflowsApi.v4WorkflowsWorkflowIdDataGet({
1882
- workflowId,
1883
- limit
1884
- });
1885
- return response.data.data ?? [];
1886
- } catch (error) {
1887
- throw wrapKadoaError(error, {
1888
- message: ERROR_MESSAGES.DATA_FETCH_FAILED,
1889
- details: { workflowId, limit }
1890
- });
1916
+ // src/modules/extraction/services/data-fetcher.service.ts
1917
+ var DataFetcherService = class {
1918
+ constructor(client) {
1919
+ this.client = client;
1891
1920
  }
1892
- }
1921
+ /**
1922
+ * Fetch extracted data from a workflow
1923
+ *
1924
+ * @param workflowId The workflow ID to fetch data from
1925
+ * @param limit Maximum number of records to retrieve
1926
+ * @returns Array of extracted data objects
1927
+ */
1928
+ async fetchWorkflowData(workflowId, limit) {
1929
+ const workflowsApi = getWorkflowsApi(this.client);
1930
+ try {
1931
+ const response = await workflowsApi.v4WorkflowsWorkflowIdDataGet({
1932
+ workflowId,
1933
+ limit
1934
+ });
1935
+ return response.data.data ?? [];
1936
+ } catch (error) {
1937
+ throw KadoaHttpException.wrap(error, {
1938
+ message: ERROR_MESSAGES.DATA_FETCH_FAILED,
1939
+ details: { workflowId, limit }
1940
+ });
1941
+ }
1942
+ }
1943
+ };
1893
1944
 
1894
- // src/extraction/entity-detector.ts
1895
- function validateEntityOptions(options) {
1896
- if (!options.link) {
1897
- throw new KadoaSdkException(ERROR_MESSAGES.LINK_REQUIRED, {
1898
- code: "VALIDATION_ERROR",
1899
- details: { options }
1900
- });
1945
+ // src/core/config/constants.ts
1946
+ var DEFAULT_API_BASE_URL = "https://api.kadoa.com";
1947
+
1948
+ // src/modules/extraction/services/entity-detector.service.ts
1949
+ var ENTITY_API_ENDPOINT = "/v4/entity";
1950
+ var EntityDetectorService = class {
1951
+ constructor(client) {
1952
+ this.client = client;
1901
1953
  }
1902
- }
1903
- async function buildRequestHeaders(config) {
1904
- const headers = {
1905
- "Content-Type": "application/json",
1906
- Accept: "application/json"
1907
- };
1908
- if (config?.apiKey) {
1909
- if (typeof config.apiKey === "function") {
1910
- const apiKeyValue = await config.apiKey("X-API-Key");
1911
- if (apiKeyValue) {
1912
- headers["X-API-Key"] = apiKeyValue;
1913
- }
1914
- } else if (typeof config.apiKey === "string") {
1915
- headers["X-API-Key"] = config.apiKey;
1954
+ /**
1955
+ * Fetches entity fields dynamically from the /v4/entity endpoint.
1956
+ * This is a workaround implementation using native fetch since the endpoint
1957
+ * is not yet included in the OpenAPI specification.
1958
+ *
1959
+ * @param options Request options including the link to analyze
1960
+ * @returns EntityPrediction containing the detected entity type and fields
1961
+ */
1962
+ async fetchEntityFields(options) {
1963
+ this.validateEntityOptions(options);
1964
+ const url = `${this.client.baseUrl || DEFAULT_API_BASE_URL}${ENTITY_API_ENDPOINT}`;
1965
+ const headers = await this.buildRequestHeaders();
1966
+ const requestBody = options;
1967
+ try {
1968
+ const response = await this.client.axiosInstance.post(url, requestBody, {
1969
+ headers
1970
+ });
1971
+ const data = response.data;
1972
+ if (!data.success || !data.entityPrediction || data.entityPrediction.length === 0) {
1973
+ throw new KadoaSdkException(ERROR_MESSAGES.NO_PREDICTIONS, {
1974
+ code: "NOT_FOUND",
1975
+ details: {
1976
+ success: data.success,
1977
+ hasPredictions: !!data.entityPrediction,
1978
+ predictionCount: data.entityPrediction?.length || 0,
1979
+ link: options.link
1980
+ }
1981
+ });
1982
+ }
1983
+ return data.entityPrediction[0];
1984
+ } catch (error) {
1985
+ throw KadoaHttpException.wrap(error, {
1986
+ details: {
1987
+ url,
1988
+ link: options.link
1989
+ }
1990
+ });
1916
1991
  }
1917
- } else {
1918
- throw new KadoaSdkException(ERROR_MESSAGES.NO_API_KEY, {
1919
- code: "AUTH_ERROR",
1920
- details: { hasConfig: !!config, hasApiKey: !!config?.apiKey }
1921
- });
1922
1992
  }
1923
- return headers;
1924
- }
1925
- function getErrorCodeFromStatus(status) {
1926
- if (status === 401 || status === 403) return "AUTH_ERROR";
1927
- if (status === 404) return "NOT_FOUND";
1928
- if (status === 429) return "RATE_LIMITED";
1929
- if (status >= 400 && status < 500) return "VALIDATION_ERROR";
1930
- if (status >= 500) return "HTTP_ERROR";
1931
- return "UNKNOWN";
1932
- }
1933
- async function handleErrorResponse(response, url, link) {
1934
- let errorData;
1935
- let errorText = "";
1936
- try {
1937
- errorText = await response.text();
1938
- errorData = JSON.parse(errorText);
1939
- } catch {
1940
- errorData = { message: errorText || response.statusText };
1941
- }
1942
- const baseErrorOptions = {
1943
- httpStatus: response.status,
1944
- endpoint: url.toString(),
1945
- method: "POST",
1946
- responseBody: errorData,
1947
- details: {
1948
- url: url.toString(),
1949
- link
1993
+ /**
1994
+ * Validates entity request options
1995
+ */
1996
+ validateEntityOptions(options) {
1997
+ if (!options.link) {
1998
+ throw new KadoaSdkException(ERROR_MESSAGES.LINK_REQUIRED, {
1999
+ code: "VALIDATION_ERROR",
2000
+ details: { options }
2001
+ });
1950
2002
  }
1951
- };
1952
- if (response.status === 401) {
1953
- throw new KadoaHttpException(ERROR_MESSAGES.AUTH_FAILED, {
1954
- ...baseErrorOptions,
1955
- code: "AUTH_ERROR"
1956
- });
1957
- }
1958
- if (response.status === 429) {
1959
- throw new KadoaHttpException(ERROR_MESSAGES.RATE_LIMITED, {
1960
- ...baseErrorOptions,
1961
- code: "RATE_LIMITED"
1962
- });
1963
- }
1964
- if (response.status >= 500) {
1965
- throw new KadoaHttpException(ERROR_MESSAGES.SERVER_ERROR, {
1966
- ...baseErrorOptions,
1967
- code: "HTTP_ERROR"
1968
- });
1969
2003
  }
1970
- throw new KadoaHttpException(
1971
- `Failed to fetch entity fields: ${errorData?.message || response.statusText}`,
1972
- {
1973
- ...baseErrorOptions,
1974
- code: getErrorCodeFromStatus(response.status)
2004
+ /**
2005
+ * Builds request headers including API key authentication
2006
+ */
2007
+ async buildRequestHeaders() {
2008
+ const headers = {
2009
+ "Content-Type": "application/json",
2010
+ Accept: "application/json"
2011
+ };
2012
+ const config = this.client.configuration;
2013
+ if (config?.apiKey) {
2014
+ if (typeof config.apiKey === "function") {
2015
+ const apiKeyValue = await config.apiKey("X-API-Key");
2016
+ if (apiKeyValue) {
2017
+ headers["X-API-Key"] = apiKeyValue;
2018
+ }
2019
+ } else if (typeof config.apiKey === "string") {
2020
+ headers["X-API-Key"] = config.apiKey;
2021
+ }
2022
+ } else {
2023
+ throw new KadoaSdkException(ERROR_MESSAGES.NO_API_KEY, {
2024
+ code: "AUTH_ERROR",
2025
+ details: { hasConfig: !!config, hasApiKey: !!config?.apiKey }
2026
+ });
1975
2027
  }
1976
- );
1977
- }
1978
- async function fetchEntityFields(sdk, options) {
1979
- validateEntityOptions(options);
1980
- const url = new URL(ENTITY_API_ENDPOINT, sdk.baseUrl || DEFAULT_API_BASE_URL);
1981
- const headers = await buildRequestHeaders(sdk.configuration);
1982
- const requestBody = options;
1983
- let response;
1984
- try {
1985
- response = await fetch(url.toString(), {
1986
- method: "POST",
1987
- headers,
1988
- body: JSON.stringify(requestBody)
1989
- });
1990
- } catch (error) {
1991
- throw new KadoaSdkException(ERROR_MESSAGES.NETWORK_ERROR, {
1992
- code: "NETWORK_ERROR",
1993
- details: {
1994
- url: url.toString(),
1995
- link: options.link
1996
- },
1997
- cause: error
1998
- });
1999
- }
2000
- if (!response.ok) {
2001
- await handleErrorResponse(response, url, options.link);
2028
+ return headers;
2002
2029
  }
2003
- let data;
2004
- try {
2005
- data = await response.json();
2006
- } catch (error) {
2007
- throw new KadoaSdkException(ERROR_MESSAGES.PARSE_ERROR, {
2008
- code: "INTERNAL_ERROR",
2009
- details: {
2010
- url: url.toString(),
2011
- link: options.link
2012
- },
2013
- cause: error
2014
- });
2030
+ };
2031
+
2032
+ // src/modules/extraction/services/workflow-manager.service.ts
2033
+ var TERMINAL_RUN_STATES = /* @__PURE__ */ new Set([
2034
+ "FINISHED",
2035
+ "SUCCESS",
2036
+ "FAILED",
2037
+ "ERROR",
2038
+ "STOPPED",
2039
+ "CANCELLED"
2040
+ ]);
2041
+ var WorkflowManagerService = class {
2042
+ constructor(client) {
2043
+ this.client = client;
2015
2044
  }
2016
- if (!data.success || !data.entityPrediction || data.entityPrediction.length === 0) {
2017
- throw new KadoaSdkException(ERROR_MESSAGES.NO_PREDICTIONS, {
2018
- code: "NOT_FOUND",
2019
- details: {
2020
- success: data.success,
2021
- hasPredictions: !!data.entityPrediction,
2022
- predictionCount: data.entityPrediction?.length || 0,
2023
- link: options.link
2024
- }
2025
- });
2045
+ /**
2046
+ * Check if a workflow runState is terminal (finished processing)
2047
+ */
2048
+ isTerminalRunState(runState) {
2049
+ if (!runState) return false;
2050
+ return TERMINAL_RUN_STATES.has(runState.toUpperCase());
2026
2051
  }
2027
- return data.entityPrediction[0];
2028
- }
2029
-
2030
- // src/extraction/workflow-manager.ts
2031
- function isTerminalRunState(runState) {
2032
- if (!runState) return false;
2033
- return TERMINAL_RUN_STATES.has(runState.toUpperCase());
2034
- }
2035
- async function createWorkflow(sdkInstance, config) {
2036
- const workflowsApi = getWorkflowsApi(sdkInstance);
2037
- const request = {
2038
- urls: config.urls,
2039
- navigationMode: config.navigationMode,
2040
- entity: config.entity,
2041
- name: config.name,
2042
- fields: config.fields,
2043
- bypassPreview: true,
2044
- limit: config.maxRecords,
2045
- tags: ["sdk"]
2046
- };
2047
- try {
2048
- const response = await workflowsApi.v4WorkflowsPost({
2049
- v4WorkflowsPostRequest: request
2050
- });
2051
- const workflowId = response.data.workflowId;
2052
- if (!workflowId) {
2053
- throw new KadoaSdkException(ERROR_MESSAGES.NO_WORKFLOW_ID, {
2054
- code: "INTERNAL_ERROR",
2055
- details: { urls: config.urls }
2052
+ /**
2053
+ * Creates a new workflow with the provided configuration
2054
+ */
2055
+ async createWorkflow(config) {
2056
+ const workflowsApi = getWorkflowsApi(this.client);
2057
+ const request = {
2058
+ urls: config.urls,
2059
+ navigationMode: config.navigationMode,
2060
+ entity: config.entity,
2061
+ name: config.name,
2062
+ fields: config.fields,
2063
+ bypassPreview: true,
2064
+ limit: config.maxRecords,
2065
+ tags: ["sdk"]
2066
+ };
2067
+ try {
2068
+ const response = await workflowsApi.v4WorkflowsPost({
2069
+ v4WorkflowsPostRequest: request
2070
+ });
2071
+ const workflowId = response.data.workflowId;
2072
+ if (!workflowId) {
2073
+ throw new KadoaSdkException(ERROR_MESSAGES.NO_WORKFLOW_ID, {
2074
+ code: "INTERNAL_ERROR",
2075
+ details: { response: response.data }
2076
+ });
2077
+ }
2078
+ return workflowId;
2079
+ } catch (error) {
2080
+ throw KadoaHttpException.wrap(error, {
2081
+ message: ERROR_MESSAGES.WORKFLOW_CREATE_FAILED,
2082
+ details: config
2056
2083
  });
2057
2084
  }
2058
- return workflowId;
2059
- } catch (error) {
2060
- throw wrapKadoaError(error, {
2061
- message: "Failed to create workflow",
2062
- details: config
2063
- });
2064
2085
  }
2065
- }
2066
- async function getWorkflowStatus(sdkInstance, workflowId) {
2067
- const workflowsApi = getWorkflowsApi(sdkInstance);
2068
- try {
2069
- const response = await workflowsApi.v4WorkflowsWorkflowIdGet({
2070
- workflowId
2071
- });
2072
- return response.data;
2073
- } catch (error) {
2074
- throw wrapKadoaError(error, {
2075
- message: ERROR_MESSAGES.PROGRESS_CHECK_FAILED,
2076
- details: { workflowId }
2077
- });
2086
+ /**
2087
+ * Gets the current status of a workflow
2088
+ */
2089
+ async getWorkflowStatus(workflowId) {
2090
+ const workflowsApi = getWorkflowsApi(this.client);
2091
+ try {
2092
+ const response = await workflowsApi.v4WorkflowsWorkflowIdGet({
2093
+ workflowId
2094
+ });
2095
+ return response.data;
2096
+ } catch (error) {
2097
+ throw KadoaHttpException.wrap(error, {
2098
+ message: ERROR_MESSAGES.PROGRESS_CHECK_FAILED,
2099
+ details: { workflowId }
2100
+ });
2101
+ }
2078
2102
  }
2079
- }
2080
- async function waitForWorkflowCompletion(sdkInstance, workflowId, options) {
2081
- const pollingInterval = options.pollingInterval;
2082
- const maxWaitTime = options.maxWaitTime;
2083
- const startTime = Date.now();
2084
- let previousState;
2085
- let previousRunState;
2086
- while (Date.now() - startTime < maxWaitTime) {
2087
- const workflow = await getWorkflowStatus(sdkInstance, workflowId);
2088
- if (workflow.state !== previousState || workflow.runState !== previousRunState) {
2089
- const statusChange = {
2090
- workflowId,
2091
- previousState,
2092
- previousRunState,
2093
- currentState: workflow.state,
2094
- currentRunState: workflow.runState
2095
- };
2096
- sdkInstance.emit("extraction:status_changed", statusChange, "extraction");
2097
- if (options?.onStatusChange) {
2098
- options.onStatusChange(statusChange);
2103
+ /**
2104
+ * Waits for a workflow to complete processing
2105
+ *
2106
+ * @param workflowId The workflow ID to monitor
2107
+ * @param pollingInterval How often to check the status (in milliseconds)
2108
+ * @param maxWaitTime Maximum time to wait before timing out (in milliseconds)
2109
+ * @param onStatusChange Optional callback for status changes
2110
+ * @returns The final workflow status
2111
+ */
2112
+ async waitForWorkflowCompletion(workflowId, pollingInterval, maxWaitTime, onStatusChange) {
2113
+ const startTime = Date.now();
2114
+ let lastStatus;
2115
+ while (Date.now() - startTime < maxWaitTime) {
2116
+ const currentStatus = await this.getWorkflowStatus(workflowId);
2117
+ if (lastStatus?.state !== currentStatus.state || lastStatus?.runState !== currentStatus.runState) {
2118
+ const eventPayload = {
2119
+ workflowId,
2120
+ previousState: lastStatus?.state,
2121
+ previousRunState: lastStatus?.runState,
2122
+ currentState: currentStatus.state,
2123
+ currentRunState: currentStatus.runState
2124
+ };
2125
+ this.client.emit(
2126
+ "extraction:status_changed",
2127
+ eventPayload,
2128
+ "extraction"
2129
+ );
2130
+ if (onStatusChange) {
2131
+ onStatusChange(lastStatus, currentStatus);
2132
+ }
2099
2133
  }
2100
- previousState = workflow.state;
2101
- previousRunState = workflow.runState;
2102
- }
2103
- if (isTerminalRunState(workflow.runState)) {
2104
- return workflow;
2134
+ if (this.isTerminalRunState(currentStatus.runState)) {
2135
+ return currentStatus;
2136
+ }
2137
+ lastStatus = currentStatus;
2138
+ await new Promise((resolve) => setTimeout(resolve, pollingInterval));
2105
2139
  }
2106
- await new Promise((resolve) => setTimeout(resolve, pollingInterval));
2140
+ throw new KadoaSdkException(ERROR_MESSAGES.WORKFLOW_TIMEOUT, {
2141
+ code: "TIMEOUT",
2142
+ details: {
2143
+ workflowId,
2144
+ maxWaitTime,
2145
+ lastState: lastStatus?.state,
2146
+ lastRunState: lastStatus?.runState
2147
+ }
2148
+ });
2107
2149
  }
2108
- throw new KadoaSdkException(
2109
- `Extraction did not complete within ${maxWaitTime / 1e3} seconds`,
2110
- { code: "TIMEOUT", details: { workflowId, maxWaitTime } }
2111
- );
2112
- }
2150
+ };
2113
2151
 
2114
- // src/extraction/extraction-runner.ts
2115
- function validateExtractionOptions(options) {
2116
- if (!options.urls || options.urls.length === 0) {
2117
- throw new KadoaSdkException(ERROR_MESSAGES.NO_URLS, {
2118
- code: "VALIDATION_ERROR"
2119
- });
2152
+ // src/modules/extraction/commands/run-extraction.command.ts
2153
+ var SUCCESSFUL_RUN_STATES = /* @__PURE__ */ new Set(["FINISHED", "SUCCESS"]);
2154
+ var DEFAULT_OPTIONS = {
2155
+ pollingInterval: 5e3,
2156
+ maxWaitTime: 3e5,
2157
+ navigationMode: "single-page",
2158
+ location: { type: "auto" },
2159
+ name: "Untitled Workflow",
2160
+ maxRecords: 1e3
2161
+ };
2162
+ var RunExtractionCommand = class extends Command {
2163
+ constructor(client) {
2164
+ super();
2165
+ this.client = client;
2166
+ this.dataFetcher = new DataFetcherService(client);
2167
+ this.entityDetector = new EntityDetectorService(client);
2168
+ this.workflowManager = new WorkflowManagerService(client);
2120
2169
  }
2121
- }
2122
- function isExtractionSuccessful(runState) {
2123
- return runState ? SUCCESSFUL_RUN_STATES.has(runState.toUpperCase()) : false;
2124
- }
2125
- async function runExtraction(sdkInstance, options) {
2126
- validateExtractionOptions(options);
2127
- const config = merge(
2128
- DEFAULT_OPTIONS,
2129
- options
2130
- );
2131
- try {
2132
- const entityPrediction = await fetchEntityFields(sdkInstance, {
2133
- link: config.urls[0],
2134
- location: config.location,
2135
- navigationMode: config.navigationMode
2136
- });
2137
- sdkInstance.emit(
2138
- "entity:detected",
2139
- {
2140
- entity: entityPrediction.entity,
2141
- fields: entityPrediction.fields,
2142
- url: config.urls[0]
2143
- },
2144
- "extraction",
2145
- {
2146
- navigationMode: config.navigationMode,
2147
- location: config.location
2148
- }
2149
- );
2150
- const workflowId = await createWorkflow(sdkInstance, {
2151
- entity: entityPrediction.entity,
2152
- fields: entityPrediction.fields,
2153
- ...config
2154
- });
2155
- sdkInstance.emit(
2156
- "extraction:started",
2157
- {
2158
- workflowId,
2159
- name: config.name,
2160
- urls: config.urls
2161
- },
2162
- "extraction"
2170
+ /**
2171
+ * Execute the extraction workflow
2172
+ */
2173
+ async execute(options) {
2174
+ this.validateOptions(options);
2175
+ const config = merge(
2176
+ DEFAULT_OPTIONS,
2177
+ options
2163
2178
  );
2164
- const workflow = await waitForWorkflowCompletion(sdkInstance, workflowId, {
2165
- ...config,
2166
- pollingInterval: config.pollingInterval,
2167
- maxWaitTime: config.maxWaitTime
2168
- });
2169
- let data;
2170
- const isSuccess = isExtractionSuccessful(workflow.runState);
2171
- if (isSuccess) {
2172
- data = await fetchWorkflowData(sdkInstance, workflowId);
2173
- if (data) {
2174
- sdkInstance.emit(
2175
- "extraction:data_available",
2176
- {
2177
- workflowId,
2178
- recordCount: data.length,
2179
- isPartial: false
2180
- },
2181
- "extraction"
2182
- );
2183
- }
2184
- sdkInstance.emit(
2185
- "extraction:completed",
2179
+ try {
2180
+ const entityPrediction = await this.entityDetector.fetchEntityFields({
2181
+ link: config.urls[0],
2182
+ location: config.location,
2183
+ navigationMode: config.navigationMode
2184
+ });
2185
+ this.client.emit(
2186
+ "entity:detected",
2186
2187
  {
2187
- workflowId,
2188
- success: true,
2189
- finalRunState: workflow.runState,
2190
- finalState: workflow.state,
2191
- recordCount: data?.length
2188
+ entity: entityPrediction.entity,
2189
+ fields: entityPrediction.fields,
2190
+ url: config.urls[0]
2192
2191
  },
2193
- "extraction"
2192
+ "extraction",
2193
+ {
2194
+ navigationMode: config.navigationMode,
2195
+ location: config.location
2196
+ }
2194
2197
  );
2195
- } else {
2196
- sdkInstance.emit(
2197
- "extraction:completed",
2198
+ const workflowId = await this.workflowManager.createWorkflow({
2199
+ entity: entityPrediction.entity,
2200
+ fields: entityPrediction.fields,
2201
+ ...config
2202
+ });
2203
+ this.client.emit(
2204
+ "extraction:started",
2198
2205
  {
2199
2206
  workflowId,
2200
- success: false,
2201
- finalRunState: workflow.runState,
2202
- finalState: workflow.state,
2203
- error: `Extraction completed with unexpected status: ${workflow.runState}`
2207
+ name: config.name,
2208
+ urls: config.urls
2204
2209
  },
2205
2210
  "extraction"
2206
2211
  );
2207
- throw new KadoaSdkException(
2208
- `Extraction completed with unexpected status: ${workflow.runState}`,
2209
- {
2210
- code: "INTERNAL_ERROR",
2211
- details: {
2212
+ const workflow = await this.workflowManager.waitForWorkflowCompletion(
2213
+ workflowId,
2214
+ config.pollingInterval,
2215
+ config.maxWaitTime
2216
+ );
2217
+ let data;
2218
+ const isSuccess = this.isExtractionSuccessful(workflow.runState);
2219
+ if (isSuccess) {
2220
+ data = await this.dataFetcher.fetchWorkflowData(
2221
+ workflowId,
2222
+ config.maxRecords
2223
+ );
2224
+ if (data) {
2225
+ this.client.emit(
2226
+ "extraction:data_available",
2227
+ {
2228
+ workflowId,
2229
+ recordCount: data.length,
2230
+ isPartial: false
2231
+ },
2232
+ "extraction"
2233
+ );
2234
+ }
2235
+ this.client.emit(
2236
+ "extraction:completed",
2237
+ {
2238
+ workflowId,
2239
+ success: true,
2240
+ finalRunState: workflow.runState,
2241
+ finalState: workflow.state,
2242
+ recordCount: data?.length
2243
+ },
2244
+ "extraction"
2245
+ );
2246
+ } else {
2247
+ this.client.emit(
2248
+ "extraction:completed",
2249
+ {
2212
2250
  workflowId,
2213
- runState: workflow.runState,
2214
- state: workflow.state
2251
+ success: false,
2252
+ finalRunState: workflow.runState,
2253
+ finalState: workflow.state,
2254
+ error: `Extraction completed with unexpected status: ${workflow.runState}`
2255
+ },
2256
+ "extraction"
2257
+ );
2258
+ throw new KadoaSdkException(
2259
+ `${ERROR_MESSAGES.WORKFLOW_UNEXPECTED_STATUS}: ${workflow.runState}`,
2260
+ {
2261
+ code: "INTERNAL_ERROR",
2262
+ details: {
2263
+ workflowId,
2264
+ runState: workflow.runState,
2265
+ state: workflow.state
2266
+ }
2215
2267
  }
2216
- }
2217
- );
2268
+ );
2269
+ }
2270
+ return {
2271
+ workflowId,
2272
+ workflow,
2273
+ data
2274
+ };
2275
+ } catch (error) {
2276
+ throw KadoaHttpException.wrap(error, {
2277
+ message: ERROR_MESSAGES.EXTRACTION_FAILED,
2278
+ details: { urls: options.urls }
2279
+ });
2218
2280
  }
2219
- return {
2220
- workflowId,
2221
- workflow,
2222
- data
2281
+ }
2282
+ /**
2283
+ * Validates extraction options
2284
+ * @private
2285
+ */
2286
+ validateOptions(options) {
2287
+ if (!options.urls || options.urls.length === 0) {
2288
+ throw new KadoaSdkException(ERROR_MESSAGES.NO_URLS, {
2289
+ code: "VALIDATION_ERROR"
2290
+ });
2291
+ }
2292
+ }
2293
+ /**
2294
+ * Checks if extraction was successful
2295
+ * @private
2296
+ */
2297
+ isExtractionSuccessful(runState) {
2298
+ return runState ? SUCCESSFUL_RUN_STATES.has(runState.toUpperCase()) : false;
2299
+ }
2300
+ };
2301
+
2302
+ // src/modules/extraction/extraction.module.ts
2303
+ var ExtractionModule = class {
2304
+ constructor(client) {
2305
+ this.runExtractionCommand = new RunExtractionCommand(client);
2306
+ }
2307
+ /**
2308
+ * Run extraction workflow using dynamic entity detection
2309
+ *
2310
+ * @param options Extraction configuration options
2311
+ * @returns ExtractionResult containing workflow ID, workflow details, and extracted data
2312
+ *
2313
+ * @example
2314
+ * ```typescript
2315
+ * const result = await client.extraction.run({
2316
+ * urls: ['https://example.com'],
2317
+ * name: 'My Extraction'
2318
+ * });
2319
+ * ```
2320
+ */
2321
+ async run(options) {
2322
+ return this.runExtractionCommand.execute(options);
2323
+ }
2324
+ };
2325
+
2326
+ // src/version.ts
2327
+ var SDK_VERSION = "0.4.0";
2328
+ var SDK_NAME = "kadoa-node-sdk";
2329
+ var SDK_LANGUAGE = "node";
2330
+
2331
+ // src/kadoa-client.ts
2332
+ var KadoaClient = class {
2333
+ constructor(config) {
2334
+ this._baseUrl = config.baseUrl || "https://api.kadoa.com";
2335
+ this._timeout = config.timeout || 3e4;
2336
+ const configParams = {
2337
+ apiKey: config.apiKey,
2338
+ basePath: this._baseUrl,
2339
+ baseOptions: {
2340
+ headers: {
2341
+ "User-Agent": `${SDK_NAME}/${SDK_VERSION}`,
2342
+ "X-SDK-Version": SDK_VERSION,
2343
+ "X-SDK-Language": SDK_LANGUAGE
2344
+ }
2345
+ }
2223
2346
  };
2224
- } catch (error) {
2225
- throw wrapKadoaError(error, {
2226
- message: ERROR_MESSAGES.EXTRACTION_FAILED,
2227
- details: { urls: options.urls }
2347
+ this._configuration = new Configuration(configParams);
2348
+ this._axiosInstance = globalAxios2.create({
2349
+ timeout: this._timeout,
2350
+ headers: {
2351
+ "User-Agent": `${SDK_NAME}/${SDK_VERSION}`,
2352
+ "X-SDK-Version": SDK_VERSION,
2353
+ "X-SDK-Language": SDK_LANGUAGE
2354
+ }
2228
2355
  });
2356
+ this._events = new KadoaEventEmitter();
2357
+ this.extraction = new ExtractionModule(this);
2229
2358
  }
2230
- }
2231
- function initializeSdk(config) {
2232
- const baseUrl = config.baseUrl || "https://api.kadoa.com";
2233
- const configParams = {
2234
- apiKey: config.apiKey,
2235
- basePath: baseUrl
2236
- };
2237
- const configuration = new Configuration(configParams);
2238
- const axiosInstance = globalAxios2.create({
2239
- timeout: config.timeout || 3e4
2240
- });
2241
- const events = new KadoaEventEmitter();
2242
- return {
2243
- configuration,
2244
- axiosInstance,
2245
- baseUrl,
2246
- events,
2247
- emit: (eventName, payload, source, metadata) => {
2248
- events.emit(eventName, payload, source, metadata);
2249
- },
2250
- onEvent: (listener) => {
2251
- events.onEvent(listener);
2252
- },
2253
- offEvent: (listener) => {
2254
- events.offEvent(listener);
2255
- }
2256
- };
2257
- }
2258
- function dispose(sdkInstance) {
2259
- if (sdkInstance?.events) {
2260
- sdkInstance.events.removeAllListeners();
2359
+ /**
2360
+ * Register an event listener
2361
+ *
2362
+ * @param listener Function to handle events
2363
+ */
2364
+ onEvent(listener) {
2365
+ this._events.onEvent(listener);
2261
2366
  }
2262
- }
2367
+ /**
2368
+ * Remove an event listener
2369
+ *
2370
+ * @param listener Function to remove from event handlers
2371
+ */
2372
+ offEvent(listener) {
2373
+ this._events.offEvent(listener);
2374
+ }
2375
+ /**
2376
+ * Emit an event
2377
+ * @internal
2378
+ *
2379
+ * @param eventName The name of the event
2380
+ * @param payload The event payload
2381
+ * @param source Optional source identifier
2382
+ * @param metadata Optional metadata
2383
+ */
2384
+ emit(eventName, payload, source, metadata) {
2385
+ this._events.emit(eventName, payload, source, metadata);
2386
+ }
2387
+ /**
2388
+ * Get the underlying configuration
2389
+ *
2390
+ * @returns The configuration object
2391
+ */
2392
+ get configuration() {
2393
+ return this._configuration;
2394
+ }
2395
+ /**
2396
+ * Get the axios instance
2397
+ *
2398
+ * @returns The axios instance
2399
+ */
2400
+ get axiosInstance() {
2401
+ return this._axiosInstance;
2402
+ }
2403
+ /**
2404
+ * Get the base URL
2405
+ *
2406
+ * @returns The base URL
2407
+ */
2408
+ get baseUrl() {
2409
+ return this._baseUrl;
2410
+ }
2411
+ /**
2412
+ * Get the timeout value
2413
+ *
2414
+ * @returns The timeout in milliseconds
2415
+ */
2416
+ get timeout() {
2417
+ return this._timeout;
2418
+ }
2419
+ /**
2420
+ * Get the event emitter
2421
+ * @internal
2422
+ *
2423
+ * @returns The event emitter
2424
+ */
2425
+ get events() {
2426
+ return this._events;
2427
+ }
2428
+ /**
2429
+ * Dispose of the client and clean up resources
2430
+ */
2431
+ dispose() {
2432
+ this._events?.removeAllListeners();
2433
+ }
2434
+ };
2263
2435
 
2264
- export { KadoaEventEmitter, KadoaHttpException, KadoaSdkException, dispose, initializeSdk, isKadoaHttpException, isKadoaSdkException, runExtraction };
2436
+ export { ERROR_MESSAGES, KadoaClient, KadoaEventEmitter, KadoaHttpException, KadoaSdkException };
2265
2437
  //# sourceMappingURL=index.mjs.map
2266
2438
  //# sourceMappingURL=index.mjs.map