mindee 4.0.2 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/package.json +4 -3
  3. package/src/cli.js +36 -66
  4. package/src/client.d.ts +21 -3
  5. package/src/client.js +61 -5
  6. package/src/http/endpoint.d.ts +36 -0
  7. package/src/http/endpoint.js +45 -5
  8. package/src/http/error.d.ts +66 -1
  9. package/src/http/error.js +196 -4
  10. package/src/http/index.d.ts +1 -1
  11. package/src/http/index.js +10 -1
  12. package/src/index.d.ts +1 -0
  13. package/src/index.js +2 -1
  14. package/src/internal.d.ts +5 -0
  15. package/src/internal.js +31 -0
  16. package/src/parsing/common/apiResponse.d.ts +7 -1
  17. package/src/parsing/common/apiResponse.js +8 -1
  18. package/src/product/cropper/internal.d.ts +2 -0
  19. package/src/product/cropper/internal.js +7 -0
  20. package/src/product/custom/internal.d.ts +3 -0
  21. package/src/product/custom/internal.js +9 -0
  22. package/src/product/eu/internal.d.ts +1 -0
  23. package/src/product/eu/internal.js +27 -0
  24. package/src/product/eu/licensePlate/internal.d.ts +2 -0
  25. package/src/product/eu/licensePlate/internal.js +7 -0
  26. package/src/product/financialDocument/internal.d.ts +3 -0
  27. package/src/product/financialDocument/internal.js +9 -0
  28. package/src/product/fr/bankAccountDetails/internal.d.ts +5 -0
  29. package/src/product/fr/bankAccountDetails/internal.js +13 -0
  30. package/src/product/fr/carteVitale/internal.d.ts +2 -0
  31. package/src/product/fr/carteVitale/internal.js +7 -0
  32. package/src/product/fr/idCard/internal.d.ts +3 -0
  33. package/src/product/fr/idCard/internal.js +9 -0
  34. package/src/product/fr/internal.d.ts +3 -0
  35. package/src/product/fr/internal.js +29 -0
  36. package/src/product/index.d.ts +0 -1
  37. package/src/product/index.js +1 -3
  38. package/src/product/internal.d.ts +11 -0
  39. package/src/product/internal.js +37 -0
  40. package/src/product/invoice/internal.d.ts +3 -0
  41. package/src/product/invoice/internal.js +9 -0
  42. package/src/product/invoiceSplitter/internal.d.ts +3 -0
  43. package/src/product/invoiceSplitter/internal.js +9 -0
  44. package/src/product/invoiceSplitter/invoiceSplitterV1Document.d.ts +2 -2
  45. package/src/product/invoiceSplitter/invoiceSplitterV1Document.js +1 -1
  46. package/src/product/invoiceSplitter/invoiceSplitterV1PageGroup.d.ts +1 -1
  47. package/src/product/invoiceSplitter/invoiceSplitterV1PageGroup.js +3 -3
  48. package/src/product/passport/internal.d.ts +2 -0
  49. package/src/product/passport/internal.js +7 -0
  50. package/src/product/proofOfAddress/internal.d.ts +2 -0
  51. package/src/product/proofOfAddress/internal.js +7 -0
  52. package/src/product/receipt/internal.d.ts +5 -0
  53. package/src/product/receipt/internal.js +13 -0
  54. package/src/product/us/bankCheck/internal.d.ts +3 -0
  55. package/src/product/us/bankCheck/internal.js +9 -0
  56. package/src/product/us/driverLicense/internal.d.ts +3 -0
  57. package/src/product/us/driverLicense/internal.js +9 -0
  58. package/src/product/us/internal.d.ts +2 -0
  59. package/src/product/us/internal.js +28 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v4.1.0 - 2023-08-31
4
+ ### Changes
5
+ * :boom: remove support for node versions <16
6
+ * :sparkles: add support for auto-polling in asynchronous calls
7
+ * :sparkles: update HTTP error management system
8
+ * :sparkles: add possibility to access raw server response
9
+ * :arrow_up: add support for node 20
10
+ * :wrench: expose more internal tools
11
+ * :memo: add better technical documentation
12
+ * :recycle: remove deprecated examples
13
+ * :recycle: update linting rules
14
+ * :arrow_up: update testing library
15
+
16
+ ### Fixes
17
+ * :bug: fix miscellaneous bugs related to http parsing issues
18
+
19
+
3
20
  ## v4.0.2 - 2023-08-24
4
21
  ### Changes
5
22
  * :recycle: updated technical documentation
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mindee",
3
- "version": "4.0.2",
3
+ "version": "4.1.0",
4
4
  "description": "Mindee Client Library for Node.js",
5
5
  "main": "src/index.js",
6
6
  "bin": "bin/mindee.js",
@@ -23,7 +23,7 @@
23
23
  "CHANGELOG.md"
24
24
  ],
25
25
  "engines": {
26
- "node": ">= 14"
26
+ "node": ">= 16"
27
27
  },
28
28
  "repository": {
29
29
  "type": "git",
@@ -46,9 +46,10 @@
46
46
  "@typescript-eslint/eslint-plugin": "^5.57.1",
47
47
  "@typescript-eslint/parser": "^5.57.1",
48
48
  "chai": "^4.3.7",
49
- "eslint": "^8.32.0",
49
+ "eslint": "^8.47.0",
50
50
  "lint-staged": "^13.2.3",
51
51
  "mocha": "^10.1.0",
52
+ "nock": "^13.3.3",
52
53
  "ts-node": "^10.9.1",
53
54
  "typedoc": "~0.23",
54
55
  "typescript": "^5.0.4"
package/src/cli.js CHANGED
@@ -193,8 +193,7 @@ function getPredictParams(options) {
193
193
  };
194
194
  return predictParams;
195
195
  }
196
- async function callParse(command, inputPath, options) {
197
- const conf = getConfig(command);
196
+ async function callParse(productClass, command, inputPath, options) {
198
197
  const mindeeClient = initClient(options);
199
198
  const predictParams = getPredictParams(options);
200
199
  const pageOptions = getPageOptions(options);
@@ -202,7 +201,7 @@ async function callParse(command, inputPath, options) {
202
201
  let response;
203
202
  if (command === COMMAND_CUSTOM) {
204
203
  const customEndpoint = mindeeClient.createEndpoint(options.endpoint, options.account, options.version);
205
- response = await mindeeClient.parse(conf.docClass, inputSource, {
204
+ response = await mindeeClient.parse(productClass, inputSource, {
206
205
  endpoint: customEndpoint,
207
206
  pageOptions: pageOptions,
208
207
  allWords: predictParams.allWords,
@@ -210,7 +209,7 @@ async function callParse(command, inputPath, options) {
210
209
  });
211
210
  }
212
211
  else {
213
- response = await mindeeClient.parse(conf.docClass, inputSource, {
212
+ response = await mindeeClient.parse(productClass, inputSource, {
214
213
  pageOptions: pageOptions,
215
214
  allWords: predictParams.allWords,
216
215
  cropper: predictParams.cropper,
@@ -218,8 +217,7 @@ async function callParse(command, inputPath, options) {
218
217
  }
219
218
  printResponse(response.document, options);
220
219
  }
221
- async function callEnqueue(command, inputPath, options) {
222
- const conf = getConfig(command);
220
+ async function callEnqueueAndParse(productClass, command, inputPath, options) {
223
221
  const mindeeClient = initClient(options);
224
222
  const predictParams = getPredictParams(options);
225
223
  const pageOptions = getPageOptions(options);
@@ -227,32 +225,30 @@ async function callEnqueue(command, inputPath, options) {
227
225
  let response;
228
226
  if (command === COMMAND_CUSTOM) {
229
227
  const customEndpoint = mindeeClient.createEndpoint(options.endpoint, options.account, options.version);
230
- response = await mindeeClient.enqueue(conf.docClass, inputSource, {
228
+ response = await mindeeClient.enqueueAndParse(productClass, inputSource, {
231
229
  endpoint: customEndpoint,
232
230
  pageOptions: pageOptions,
233
231
  allWords: predictParams.allWords,
234
232
  cropper: predictParams.cropper,
233
+ initialDelaySec: 6,
234
+ delaySec: 3,
235
+ maxRetries: 10,
235
236
  });
236
237
  }
237
238
  else {
238
- response = await mindeeClient.enqueue(conf.docClass, inputSource, {
239
+ response = await mindeeClient.enqueueAndParse(productClass, inputSource, {
239
240
  pageOptions: pageOptions,
240
241
  allWords: predictParams.allWords,
241
242
  cropper: predictParams.cropper,
243
+ initialDelaySec: 6,
244
+ delaySec: 3,
245
+ maxRetries: 10,
242
246
  });
243
- }
244
- console.log(response.job);
245
- }
246
- async function callParseQueued(command, queueId, options) {
247
- const conf = getConfig(command);
248
- const mindeeClient = initClient(options);
249
- const response = await mindeeClient.parseQueued(conf.docClass, queueId);
250
- if (response.document !== undefined) {
247
+ if (!response.document) {
248
+ throw Error("Document could not be retrieved");
249
+ }
251
250
  printResponse(response.document, options);
252
251
  }
253
- else {
254
- console.log(response.job);
255
- }
256
252
  }
257
253
  function printResponse(document, options) {
258
254
  if (options.allWords) {
@@ -291,20 +287,11 @@ function addDisplayOptions(prog) {
291
287
  prog.option("-p, --pages", "show content of individual pages");
292
288
  }
293
289
  function routeSwitchboard(command, inputPath, allOptions) {
294
- switch (command.parent?.name()) {
295
- case "parse": {
296
- return callParse(command.name(), inputPath, allOptions);
297
- }
298
- case "enqueue": {
299
- return callEnqueue(command.name(), inputPath, allOptions);
300
- }
301
- case "parse-queued": {
302
- return callParseQueued(command.name(), inputPath, allOptions);
303
- }
304
- default: {
305
- throw new Error("Unhandled parent command.");
306
- }
290
+ const docClass = getConfig(command.name()).docClass;
291
+ if ("async" in command.opts() && command.opts()["async"]) {
292
+ return callEnqueueAndParse(docClass, command.name(), inputPath, allOptions);
307
293
  }
294
+ return callParse(docClass, command.name(), inputPath, allOptions);
308
295
  }
309
296
  function addAction(prog) {
310
297
  if (prog.name() === COMMAND_CUSTOM) {
@@ -333,44 +320,27 @@ function addAction(prog) {
333
320
  function cli() {
334
321
  program.name("mindee");
335
322
  program.option("-d, --debug", "high verbosity mode");
336
- const predict = program.command("parse").description("Parse synchronously.");
337
- addMainOptions(predict);
338
- const enqueue = program
339
- .command("enqueue")
340
- .description("Add to async parse queue.");
341
- addMainOptions(enqueue);
342
- const parseQueued = program
343
- .command("parse-queued")
344
- .description("Parse from async queue.");
345
- addMainOptions(parseQueued);
346
323
  CLI_COMMAND_CONFIG.forEach((info, name) => {
347
- if (info.sync) {
348
- const prog = predict
349
- .command(name)
350
- .description(`Parse an ${info.displayName}.`);
351
- if (name === COMMAND_CUSTOM) {
352
- addCustomPostOptions(prog);
353
- }
354
- addDisplayOptions(prog);
355
- addPostOptions(prog, info);
356
- addAction(prog);
357
- }
324
+ const prog = program.command(name);
325
+ prog.description(`${info.displayName} document`);
358
326
  if (info.async) {
359
- const progEnqueue = enqueue
360
- .command(name)
361
- .description(`Add an ${info.displayName} to the queue.`);
362
- if (name === COMMAND_CUSTOM) {
363
- addCustomPostOptions(progEnqueue);
327
+ const asyncOpt = new commander_1.Option("-A, --async", "Call asynchronously");
328
+ if (info.sync) {
329
+ asyncOpt.default(false);
330
+ }
331
+ else {
332
+ asyncOpt.default(true);
333
+ asyncOpt.hideHelp();
364
334
  }
365
- addPostOptions(progEnqueue, info);
366
- addAction(progEnqueue);
367
- const progParse = parseQueued
368
- .command(name)
369
- .description(`Parse an ${info.displayName} from the queue.`)
370
- .argument("<doc_id>", "ID of the document");
371
- addDisplayOptions(progParse);
372
- addAction(progParse);
335
+ prog.addOption(asyncOpt);
336
+ }
337
+ if (name === COMMAND_CUSTOM) {
338
+ addCustomPostOptions(prog);
373
339
  }
340
+ addMainOptions(prog);
341
+ addDisplayOptions(prog);
342
+ addPostOptions(prog, info);
343
+ addAction(prog);
374
344
  });
375
345
  program.parse(process.argv);
376
346
  }
package/src/client.d.ts CHANGED
@@ -28,6 +28,14 @@ export interface PredictOptions {
28
28
  */
29
29
  pageOptions?: PageOptions;
30
30
  }
31
+ /**
32
+ * Asynchronous polling parameters.
33
+ */
34
+ export interface AsyncOptions extends PredictOptions {
35
+ initialDelaySec: number;
36
+ delaySec: number;
37
+ maxRetries: number;
38
+ }
31
39
  export interface ClientOptions {
32
40
  /** Your API key for all endpoints. */
33
41
  apiKey?: string;
@@ -55,7 +63,6 @@ export declare class Client {
55
63
  * @param productClass product class to use for calling the API and parsing the response.
56
64
  * @param inputSource document to parse.
57
65
  * @param params parameters relating to prediction options.
58
- *
59
66
  * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
60
67
  * @category Synchronous
61
68
  * @returns a `Promise` containing parsing results.
@@ -66,7 +73,6 @@ export declare class Client {
66
73
  * @param productClass product class to use for calling the API and parsing the response.
67
74
  * @param params parameters relating to prediction options.
68
75
  * @category Asynchronous
69
- *
70
76
  * @returns a `Promise` containing the job (queue) corresponding to a document.
71
77
  */
72
78
  enqueue<T extends Inference>(productClass: new (httpResponse: StringDict) => T, inputSource: InputSource, params?: PredictOptions): Promise<AsyncPredictResponse<T>>;
@@ -78,11 +84,23 @@ export declare class Client {
78
84
  * @param params parameters relating to prediction options.
79
85
  * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
80
86
  * @category Asynchronous
81
- *
82
87
  * @returns a `Promise` containing a `Job`, which also contains a `Document` if the
83
88
  * parsing is complete.
84
89
  */
85
90
  parseQueued<T extends Inference>(productClass: new (httpResponse: StringDict) => T, queueId: string, params?: PredictOptions): Promise<AsyncPredictResponse<T>>;
91
+ /**
92
+ * Send a document to an asynchronous endpoint and poll the server until the result is sent or
93
+ * until the maximum amount of tries is reached.
94
+ *
95
+ * @param productClass product class to use for calling the API and parsing the response.
96
+ * @param inputSource document to parse.
97
+ * @param asyncParams parameters relating to prediction options.
98
+ *
99
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
100
+ * @category Synchronous
101
+ * @returns a `Promise` containing parsing results.
102
+ */
103
+ enqueueAndParse<T extends Inference>(productClass: new (httpResponse: StringDict) => T, inputSource: InputSource, asyncParams?: AsyncOptions): Promise<AsyncPredictResponse<T>>;
86
104
  /**
87
105
  * Forces boolean coercion on truthy/falsy parameters.
88
106
  * @param param input parameter to check.
package/src/client.js CHANGED
@@ -4,7 +4,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
4
4
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
5
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
6
  };
7
- var _Client_instances, _Client_buildEndpoint, _Client_initializeOTSEndpoint, _Client_cleanAccountName, _Client_getEndpoint;
7
+ var _Client_instances, _Client_validateAsyncParams, _Client_buildEndpoint, _Client_initializeOTSEndpoint, _Client_cleanAccountName, _Client_getEndpoint;
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.Client = void 0;
10
10
  const input_1 = require("./input");
@@ -14,6 +14,7 @@ const handler_1 = require("./errors/handler");
14
14
  const logger_1 = require("./logger");
15
15
  const inference_1 = require("./parsing/common/inference");
16
16
  const product_1 = require("./product");
17
+ const promises_1 = require("node:timers/promises");
17
18
  /**
18
19
  * Mindee Client class that centralizes most basic operations.
19
20
  *
@@ -43,7 +44,6 @@ class Client {
43
44
  * @param productClass product class to use for calling the API and parsing the response.
44
45
  * @param inputSource document to parse.
45
46
  * @param params parameters relating to prediction options.
46
- *
47
47
  * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
48
48
  * @category Synchronous
49
49
  * @returns a `Promise` containing parsing results.
@@ -71,7 +71,6 @@ class Client {
71
71
  * @param productClass product class to use for calling the API and parsing the response.
72
72
  * @param params parameters relating to prediction options.
73
73
  * @category Asynchronous
74
- *
75
74
  * @returns a `Promise` containing the job (queue) corresponding to a document.
76
75
  */
77
76
  async enqueue(productClass, inputSource, params = {}) {
@@ -95,7 +94,6 @@ class Client {
95
94
  * @param params parameters relating to prediction options.
96
95
  * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
97
96
  * @category Asynchronous
98
- *
99
97
  * @returns a `Promise` containing a `Job`, which also contains a `Document` if the
100
98
  * parsing is complete.
101
99
  */
@@ -104,6 +102,54 @@ class Client {
104
102
  const docResponse = await endpoint.getQueuedDocument(queueId);
105
103
  return new common_1.AsyncPredictResponse(productClass, docResponse.data);
106
104
  }
105
+ /**
106
+ * Send a document to an asynchronous endpoint and poll the server until the result is sent or
107
+ * until the maximum amount of tries is reached.
108
+ *
109
+ * @param productClass product class to use for calling the API and parsing the response.
110
+ * @param inputSource document to parse.
111
+ * @param asyncParams parameters relating to prediction options.
112
+ *
113
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
114
+ * @category Synchronous
115
+ * @returns a `Promise` containing parsing results.
116
+ */
117
+ async enqueueAndParse(productClass, inputSource, asyncParams = {
118
+ endpoint: undefined,
119
+ allWords: undefined,
120
+ cropper: undefined,
121
+ pageOptions: undefined,
122
+ initialDelaySec: 6,
123
+ delaySec: 3,
124
+ maxRetries: 10,
125
+ }) {
126
+ __classPrivateFieldGet(this, _Client_instances, "m", _Client_validateAsyncParams).call(this, asyncParams);
127
+ const enqueueResponse = await this.enqueue(productClass, inputSource, asyncParams);
128
+ if (enqueueResponse.job.id === undefined || enqueueResponse.job.id.length === 0) {
129
+ throw Error("Enqueueing of the document failed.");
130
+ }
131
+ const queueId = enqueueResponse.job.id;
132
+ logger_1.logger.debug(`Successfully enqueued document with job id: ${queueId}.`);
133
+ await (0, promises_1.setTimeout)(asyncParams.initialDelaySec * 1000);
134
+ let retryCounter = 1;
135
+ let pollResults;
136
+ pollResults = await this.parseQueued(productClass, queueId, asyncParams);
137
+ while (retryCounter < asyncParams.maxRetries) {
138
+ logger_1.logger.debug(`Polling server for parsing result with queueId: ${queueId}.
139
+ Attempt n°${retryCounter}/${asyncParams.maxRetries}.
140
+ Job status: ${pollResults.job.status}.`);
141
+ if (pollResults.job.status === "completed") {
142
+ break;
143
+ }
144
+ await (0, promises_1.setTimeout)(asyncParams.delaySec * 1000);
145
+ pollResults = await this.parseQueued(productClass, queueId, asyncParams);
146
+ retryCounter++;
147
+ }
148
+ if (pollResults.job.status !== "completed") {
149
+ throw Error(`Asynchronous parsing request timed out after ${asyncParams.delaySec * retryCounter} seconds`);
150
+ }
151
+ return pollResults;
152
+ }
107
153
  /**
108
154
  * Forces boolean coercion on truthy/falsy parameters.
109
155
  * @param param input parameter to check.
@@ -201,7 +247,17 @@ class Client {
201
247
  }
202
248
  }
203
249
  exports.Client = Client;
204
- _Client_instances = new WeakSet(), _Client_buildEndpoint = function _Client_buildEndpoint(endpointName, accountName, endpointVersion) {
250
+ _Client_instances = new WeakSet(), _Client_validateAsyncParams = function _Client_validateAsyncParams(asyncParams) {
251
+ if (asyncParams.delaySec < 2) {
252
+ throw Error("Cannot set auto-parsing delay to less than 2 seconds.");
253
+ }
254
+ if (asyncParams.initialDelaySec < 4) {
255
+ throw Error("Cannot set initial parsing delay to less than 4 seconds.");
256
+ }
257
+ if (!Number.isInteger(asyncParams.maxRetries)) {
258
+ throw Error("Retry amount must be an integer.");
259
+ }
260
+ }, _Client_buildEndpoint = function _Client_buildEndpoint(endpointName, accountName, endpointVersion) {
205
261
  const apiSettings = new http_1.MindeeApi({
206
262
  apiKey: this.apiKey,
207
263
  urlName: endpointName,
@@ -11,26 +11,55 @@ export interface EndpointResponse {
11
11
  [key: string]: any;
12
12
  };
13
13
  }
14
+ /**
15
+ * Endpoint object class wrapper.
16
+ */
14
17
  export declare class Endpoint {
15
18
  #private;
19
+ /** URL of a product. */
16
20
  urlName: string;
21
+ /** Account owning the product. */
17
22
  owner: string;
23
+ /** Product's version, as a string. */
18
24
  version: string;
25
+ /** Entire root of the URL for API calls. */
19
26
  urlRoot: string;
27
+ /** Settings relating to the API. */
20
28
  settings: MindeeApi;
21
29
  constructor(urlName: string, owner: string, version: string, settings: MindeeApi);
30
+ /**
31
+ * Sends a prediction to the API and parses out the result.
32
+ * Throws an error if the server's response contains one.
33
+ * @param params parameters relating to prediction options.
34
+ * @category Synchronous
35
+ * @returns a `Promise` containing parsing results.
36
+ */
22
37
  predict(params: {
23
38
  inputDoc: InputSource;
24
39
  includeWords: boolean;
25
40
  pageOptions?: PageOptions;
26
41
  cropper: boolean;
27
42
  }): Promise<EndpointResponse>;
43
+ /**
44
+ * Enqueues a prediction to the API.
45
+ * Throws an error if the server's response contains one.
46
+ * @param params parameters relating to prediction options.
47
+ * @category Asynchronous
48
+ * @returns a `Promise` containing queue data.
49
+ */
28
50
  predictAsync(params: {
29
51
  inputDoc: InputSource;
30
52
  includeWords: boolean;
31
53
  pageOptions?: PageOptions;
32
54
  cropper: boolean;
33
55
  }): Promise<EndpointResponse>;
56
+ /**
57
+ * Requests the results of a queued document from the API.
58
+ * Throws an error if the server's response contains one.
59
+ * @param params parameters relating to prediction options.
60
+ * @category Asynchronous
61
+ * @returns a `Promise` containing the parsed result.
62
+ */
34
63
  getQueuedDocument(queueId: string): Promise<EndpointResponse>;
35
64
  /**
36
65
  * Send a file to a prediction API.
@@ -40,5 +69,12 @@ export declare class Endpoint {
40
69
  * @param cropper
41
70
  */
42
71
  protected sendFileForPrediction(input: InputSource, predictUrl: string, includeWords?: boolean, cropper?: boolean): Promise<EndpointResponse>;
72
+ /**
73
+ * Reads a response from the API and processes it.
74
+ * @param options options related to the request itself.
75
+ * @param resolve the resolved response
76
+ * @param reject promise rejection reason.
77
+ * @returns the processed request.
78
+ */
43
79
  protected readResponse(options: RequestOptions, resolve: (value: EndpointResponse | PromiseLike<EndpointResponse>) => void, reject: (reason?: any) => void): ClientRequest;
44
80
  }
@@ -16,6 +16,9 @@ const form_data_1 = __importDefault(require("form-data"));
16
16
  const logger_1 = require("../logger");
17
17
  const base_1 = require("../input/base");
18
18
  const error_1 = require("./error");
19
+ /**
20
+ * Endpoint object class wrapper.
21
+ */
19
22
  class Endpoint {
20
23
  constructor(urlName, owner, version, settings) {
21
24
  _Endpoint_instances.add(this);
@@ -25,6 +28,13 @@ class Endpoint {
25
28
  this.settings = settings;
26
29
  this.urlRoot = `/v1/products/${owner}/${urlName}/v${version}`;
27
30
  }
31
+ /**
32
+ * Sends a prediction to the API and parses out the result.
33
+ * Throws an error if the server's response contains one.
34
+ * @param params parameters relating to prediction options.
35
+ * @category Synchronous
36
+ * @returns a `Promise` containing parsing results.
37
+ */
28
38
  async predict(params) {
29
39
  await params.inputDoc.init();
30
40
  if (params.pageOptions !== undefined) {
@@ -33,10 +43,17 @@ class Endpoint {
33
43
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictReqPost).call(this, params.inputDoc, params.includeWords, params.cropper);
34
44
  const statusCode = response.messageObj.statusCode;
35
45
  if (statusCode === undefined || statusCode >= 400) {
36
- (0, error_1.handleError)(this.urlName, response, statusCode);
46
+ (0, error_1.handleError)(this.urlName, response, statusCode, response.messageObj?.statusMessage);
37
47
  }
38
48
  return response;
39
49
  }
50
+ /**
51
+ * Enqueues a prediction to the API.
52
+ * Throws an error if the server's response contains one.
53
+ * @param params parameters relating to prediction options.
54
+ * @category Asynchronous
55
+ * @returns a `Promise` containing queue data.
56
+ */
40
57
  async predictAsync(params) {
41
58
  await params.inputDoc.init();
42
59
  if (params.pageOptions !== undefined) {
@@ -45,17 +62,24 @@ class Endpoint {
45
62
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictAsyncReqPost).call(this, params.inputDoc, params.includeWords, params.cropper);
46
63
  const statusCode = response.messageObj.statusCode;
47
64
  if (statusCode === undefined || statusCode >= 400) {
48
- (0, error_1.handleError)(this.urlName, response, statusCode);
65
+ (0, error_1.handleError)(this.urlName, response, statusCode, response.messageObj?.statusMessage);
49
66
  }
50
67
  return response;
51
68
  }
69
+ /**
70
+ * Requests the results of a queued document from the API.
71
+ * Throws an error if the server's response contains one.
72
+ * @param params parameters relating to prediction options.
73
+ * @category Asynchronous
74
+ * @returns a `Promise` containing the parsed result.
75
+ */
52
76
  async getQueuedDocument(queueId) {
53
77
  const queueResponse = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentQueueReqGet).call(this, queueId);
54
78
  const queueStatusCode = queueResponse.messageObj.statusCode;
55
79
  if (queueStatusCode === undefined ||
56
80
  queueStatusCode < 200 ||
57
81
  queueStatusCode > 400) {
58
- (0, error_1.handleError)(this.urlName, queueResponse, queueStatusCode);
82
+ (0, error_1.handleError)(this.urlName, queueResponse, queueStatusCode, queueResponse.messageObj?.statusMessage);
59
83
  }
60
84
  if (queueStatusCode === 302 &&
61
85
  queueResponse.messageObj.headers.location !== undefined) {
@@ -108,6 +132,13 @@ class Endpoint {
108
132
  req.end();
109
133
  });
110
134
  }
135
+ /**
136
+ * Reads a response from the API and processes it.
137
+ * @param options options related to the request itself.
138
+ * @param resolve the resolved response
139
+ * @param reject promise rejection reason.
140
+ * @returns the processed request.
141
+ */
111
142
  readResponse(options, resolve, reject) {
112
143
  logger_1.logger.debug(`${options.method}: https://${options.hostname}${options.path}`);
113
144
  const req = (0, https_1.request)(options, function (res) {
@@ -140,7 +171,10 @@ class Endpoint {
140
171
  catch (error) {
141
172
  logger_1.logger.error("Could not parse the return as JSON.");
142
173
  logger_1.logger.debug(responseBody);
143
- reject(error);
174
+ resolve({
175
+ messageObj: res,
176
+ data: { reconstructedResponse: responseBody },
177
+ });
144
178
  }
145
179
  });
146
180
  });
@@ -151,7 +185,13 @@ class Endpoint {
151
185
  }
152
186
  }
153
187
  exports.Endpoint = Endpoint;
154
- _Endpoint_instances = new WeakSet(), _Endpoint_cutDocPages = async function _Endpoint_cutDocPages(inputDoc, pageOptions) {
188
+ _Endpoint_instances = new WeakSet(), _Endpoint_cutDocPages =
189
+ /**
190
+ * Cuts a document's pages according to the given options.
191
+ * @param inputDoc input document.
192
+ * @param pageOptions page cutting options.
193
+ */
194
+ async function _Endpoint_cutDocPages(inputDoc, pageOptions) {
155
195
  if (inputDoc instanceof base_1.LocalInputSource && inputDoc.isPdf()) {
156
196
  await inputDoc.cutPdf(pageOptions);
157
197
  }
@@ -1,2 +1,67 @@
1
+ import { MindeeError } from "../errors";
2
+ import { StringDict } from "../parsing/common";
1
3
  import { EndpointResponse } from "./endpoint";
2
- export declare function handleError(url: string, response: EndpointResponse, statusCode?: number): void;
4
+ export declare function handleError(url: string, response: EndpointResponse, code?: number, serverError?: string): void;
5
+ /**
6
+ * `Error` wrapper for server (HTTP) errors.
7
+ * Is used when an error is lacking a handled error code.
8
+ */
9
+ export declare class MindeeHttpError extends MindeeError {
10
+ /** Description of the error. */
11
+ message: string;
12
+ /** Additional details on the error. */
13
+ details: string | StringDict;
14
+ /** Standard HTTP error code. */
15
+ code?: number;
16
+ constructor(httpError: StringDict, url: string, code?: number);
17
+ }
18
+ /**
19
+ * Generic client errors.
20
+ * Can include errors like InvalidQuery.
21
+ */
22
+ export declare class MindeeHttp400Error extends MindeeHttpError {
23
+ constructor(httpError: StringDict, url: string, code?: number);
24
+ }
25
+ /**
26
+ * Can include errors like NoTokenSet or InvalidToken.
27
+ */
28
+ export declare class MindeeHttp401Error extends MindeeHttpError {
29
+ constructor(httpError: StringDict, url: string, code?: number);
30
+ }
31
+ /**
32
+ * Regular AccessForbidden error.
33
+ * Can also include errors like PlanLimitReached, AsyncRequestDisallowed or SyncRequestDisallowed.
34
+ */
35
+ export declare class MindeeHttp403Error extends MindeeHttpError {
36
+ constructor(httpError: StringDict, url: string, code?: number);
37
+ }
38
+ export declare class MindeeHttp404Error extends MindeeHttpError {
39
+ constructor(httpError: StringDict, url: string, code?: number);
40
+ }
41
+ /**
42
+ * Rare error.
43
+ * Can occasionally happen when unusually large documents are passed.
44
+ */
45
+ export declare class MindeeHttp413Error extends MindeeHttpError {
46
+ constructor(httpError: StringDict, url: string, code?: number);
47
+ }
48
+ /**
49
+ * Usually contains TooManyRequests errors.
50
+ * Arises whenever too many calls to the API are made in quick succession.
51
+ */
52
+ export declare class MindeeHttp429Error extends MindeeHttpError {
53
+ constructor(httpError: StringDict, url: string, code?: number);
54
+ }
55
+ /**
56
+ * Generic server errors.
57
+ */
58
+ export declare class MindeeHttp500Error extends MindeeHttpError {
59
+ constructor(httpError: StringDict, url: string, code?: number);
60
+ }
61
+ /**
62
+ * Miscellaneous server errors.
63
+ * Can include errors like RequestTimeout or GatewayTimeout.
64
+ */
65
+ export declare class MindeeHttp504Error extends MindeeHttpError {
66
+ constructor(httpError: StringDict, url: string, code?: number);
67
+ }