mindee 4.18.1 → 4.20.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 (86) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +1 -1
  3. package/src/cli.js +10 -20
  4. package/src/client.d.ts +44 -9
  5. package/src/client.js +24 -0
  6. package/src/http/apiSettings.d.ts +2 -0
  7. package/src/http/apiSettings.js +3 -1
  8. package/src/http/baseEndpoint.d.ts +10 -1
  9. package/src/http/baseEndpoint.js +13 -1
  10. package/src/http/endpoint.d.ts +3 -11
  11. package/src/http/endpoint.js +26 -22
  12. package/src/http/error.js +1 -1
  13. package/src/http/httpParams.d.ts +17 -0
  14. package/src/http/httpParams.js +2 -0
  15. package/src/http/index.d.ts +1 -0
  16. package/src/http/responseValidation.js +6 -0
  17. package/src/http/workflowEndpoint.d.ts +29 -0
  18. package/src/http/workflowEndpoint.js +99 -0
  19. package/src/parsing/common/asyncPredictResponse.d.ts +1 -1
  20. package/src/parsing/common/asyncPredictResponse.js +10 -9
  21. package/src/parsing/common/execution.d.ts +39 -0
  22. package/src/parsing/common/execution.js +32 -0
  23. package/src/parsing/common/executionFile.d.ts +12 -0
  24. package/src/parsing/common/executionFile.js +14 -0
  25. package/src/parsing/common/executionPriority.d.ts +5 -0
  26. package/src/parsing/common/executionPriority.js +9 -0
  27. package/src/parsing/common/index.d.ts +4 -1
  28. package/src/parsing/common/index.js +9 -3
  29. package/src/parsing/common/workflowResponse.d.ts +17 -0
  30. package/src/parsing/common/workflowResponse.js +17 -0
  31. package/src/product/{internationalId/internationalIdV1.d.ts → driverLicense/driverLicenseV1.d.ts} +5 -5
  32. package/src/product/{internationalId/internationalIdV1.js → driverLicense/driverLicenseV1.js} +8 -8
  33. package/src/product/driverLicense/driverLicenseV1Document.d.ts +38 -0
  34. package/src/product/driverLicense/driverLicenseV1Document.js +84 -0
  35. package/src/product/driverLicense/index.d.ts +1 -0
  36. package/src/product/driverLicense/index.js +5 -0
  37. package/src/product/driverLicense/internal.d.ts +2 -0
  38. package/src/product/driverLicense/internal.js +7 -0
  39. package/src/product/fr/healthCard/healthCardV1.d.ts +16 -0
  40. package/src/product/fr/healthCard/healthCardV1.js +27 -0
  41. package/src/product/fr/healthCard/healthCardV1Document.d.ts +20 -0
  42. package/src/product/fr/healthCard/healthCardV1Document.js +43 -0
  43. package/src/product/fr/healthCard/index.d.ts +1 -0
  44. package/src/product/fr/healthCard/index.js +5 -0
  45. package/src/product/fr/healthCard/internal.d.ts +2 -0
  46. package/src/product/fr/healthCard/internal.js +7 -0
  47. package/src/product/fr/index.d.ts +2 -0
  48. package/src/product/fr/index.js +5 -1
  49. package/src/product/fr/internal.d.ts +1 -0
  50. package/src/product/fr/internal.js +2 -1
  51. package/src/product/fr/payslip/index.d.ts +1 -0
  52. package/src/product/fr/payslip/index.js +3 -1
  53. package/src/product/fr/payslip/internal.d.ts +10 -0
  54. package/src/product/fr/payslip/internal.js +21 -1
  55. package/src/product/fr/payslip/payslipV3.d.ts +16 -0
  56. package/src/product/fr/payslip/payslipV3.js +27 -0
  57. package/src/product/fr/payslip/payslipV3BankAccountDetail.d.ts +32 -0
  58. package/src/product/fr/payslip/payslipV3BankAccountDetail.js +62 -0
  59. package/src/product/fr/payslip/payslipV3Document.d.ts +35 -0
  60. package/src/product/fr/payslip/payslipV3Document.js +96 -0
  61. package/src/product/fr/payslip/payslipV3Employee.d.ts +40 -0
  62. package/src/product/fr/payslip/payslipV3Employee.js +82 -0
  63. package/src/product/fr/payslip/payslipV3Employer.d.ts +40 -0
  64. package/src/product/fr/payslip/payslipV3Employer.js +82 -0
  65. package/src/product/fr/payslip/payslipV3Employment.d.ts +40 -0
  66. package/src/product/fr/payslip/payslipV3Employment.js +82 -0
  67. package/src/product/fr/payslip/payslipV3PaidTimeOff.d.ts +36 -0
  68. package/src/product/fr/payslip/payslipV3PaidTimeOff.js +107 -0
  69. package/src/product/fr/payslip/payslipV3PayDetail.d.ts +46 -0
  70. package/src/product/fr/payslip/payslipV3PayDetail.js +168 -0
  71. package/src/product/fr/payslip/payslipV3PayPeriod.d.ts +36 -0
  72. package/src/product/fr/payslip/payslipV3PayPeriod.js +72 -0
  73. package/src/product/fr/payslip/payslipV3SalaryDetail.d.ts +36 -0
  74. package/src/product/fr/payslip/payslipV3SalaryDetail.js +110 -0
  75. package/src/product/ind/indianPassport/indianPassportV1Document.d.ts +1 -1
  76. package/src/product/ind/indianPassport/indianPassportV1Document.js +1 -1
  77. package/src/product/index.d.ts +1 -1
  78. package/src/product/index.js +3 -3
  79. package/src/product/internal.d.ts +1 -0
  80. package/src/product/internal.js +2 -1
  81. package/src/product/internationalId/internal.d.ts +0 -2
  82. package/src/product/internationalId/internal.js +1 -5
  83. package/src/product/resume/resumeV1Document.d.ts +1 -1
  84. package/src/product/resume/resumeV1Document.js +1 -1
  85. package/src/product/internationalId/internationalIdV1Document.d.ts +0 -42
  86. package/src/product/internationalId/internationalIdV1Document.js +0 -101
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v4.20.0 - 2024-11-28
4
+ ### Changes
5
+ * :sparkles: add support for French Health Card V1
6
+ * :sparkles: add support for Driver License V1
7
+ * :sparkles: add support for Payslip FR V3
8
+
9
+
10
+ ## v4.19.0 - 2024-11-27
11
+ ### Changes
12
+ * :coffin: remove support for international ID V1
13
+ * :sparkles: add support for workflows
14
+ * :sparkles: add configurable http request timeout
15
+ ### Fixes
16
+ * :bug: fix http errors improperly showing as 500 in rare instances
17
+
18
+
3
19
  ## v4.18.1 - 2024-11-19
4
20
  ### Fixes
5
21
  * :bug: fix composed API server response not properly filling full_text_ocr in pages
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mindee",
3
- "version": "4.18.1",
3
+ "version": "4.20.0",
4
4
  "description": "Mindee Client Library for Node.js",
5
5
  "main": "src/index.js",
6
6
  "bin": "bin/mindee.js",
package/src/cli.js CHANGED
@@ -109,13 +109,13 @@ const CLI_COMMAND_CONFIG = new Map([
109
109
  },
110
110
  ],
111
111
  [
112
- "fr-carte-vitale",
112
+ "fr-health-card",
113
113
  {
114
- displayName: "FR Carte Vitale",
115
- docClass: product.fr.CarteVitaleV1,
114
+ displayName: "FR Health Card",
115
+ docClass: product.fr.HealthCardV1,
116
116
  allWords: false,
117
- async: false,
118
- sync: true,
117
+ async: true,
118
+ sync: false,
119
119
  },
120
120
  ],
121
121
  [
@@ -139,13 +139,13 @@ const CLI_COMMAND_CONFIG = new Map([
139
139
  },
140
140
  ],
141
141
  [
142
- "eu-driver-license",
142
+ "driver-license",
143
143
  {
144
- displayName: "EU Driver License",
145
- docClass: product.eu.DriverLicenseV1,
144
+ displayName: "Driver License",
145
+ docClass: product.DriverLicenseV1,
146
146
  allWords: false,
147
- async: false,
148
- sync: true,
147
+ async: true,
148
+ sync: false,
149
149
  },
150
150
  ],
151
151
  [
@@ -228,16 +228,6 @@ const CLI_COMMAND_CONFIG = new Map([
228
228
  sync: true,
229
229
  },
230
230
  ],
231
- [
232
- "us-driver-license",
233
- {
234
- displayName: "US Driver License",
235
- docClass: product.us.DriverLicenseV1,
236
- allWords: false,
237
- async: false,
238
- sync: true,
239
- },
240
- ],
241
231
  [
242
232
  "us-healthcare-card",
243
233
  {
package/src/client.d.ts CHANGED
@@ -1,11 +1,27 @@
1
1
  import { Readable } from "stream";
2
2
  import { Base64Input, BufferInput, BytesInput, InputSource, LocalResponse, PageOptions, PathInput, StreamInput, UrlInput } from "./input";
3
3
  import { Endpoint } from "./http";
4
- import { AsyncPredictResponse, FeedbackResponse, Inference, PredictResponse, StringDict } from "./parsing/common";
4
+ import { AsyncPredictResponse, ExecutionPriority, FeedbackResponse, Inference, PredictResponse, StringDict } from "./parsing/common";
5
+ import { GeneratedV1 } from "./product";
6
+ import { WorkflowResponse } from "./parsing/common/workflowResponse";
7
+ /**
8
+ * Common options for workflows & predictions.
9
+ */
10
+ interface BaseOptions {
11
+ /**
12
+ * Whether to include the full ocr text. Only available on compatible APIs.
13
+ */
14
+ fullText?: boolean;
15
+ /**
16
+ * If set, remove pages from the document as specified.
17
+ * This is done before sending the file to the server and is useful to avoid page limitations.
18
+ */
19
+ pageOptions?: PageOptions;
20
+ }
5
21
  /**
6
22
  * Options relating to predictions.
7
23
  */
8
- export interface PredictOptions {
24
+ export interface PredictOptions extends BaseOptions {
9
25
  /** A custom endpoint. */
10
26
  endpoint?: Endpoint;
11
27
  /**
@@ -14,19 +30,28 @@ export interface PredictOptions {
14
30
  * This performs a full OCR operation on the server and will increase response time.
15
31
  */
16
32
  allWords?: boolean;
17
- /**
18
- * Whether to include the full ocr text. Only available on compatible APIs.
19
- */
20
- fullText?: boolean;
21
33
  /**
22
34
  * Whether to include cropper results for each page.
23
35
  */
24
36
  cropper?: boolean;
37
+ }
38
+ /**
39
+ * Options relating to workflows.
40
+ * @category Workflow
41
+ */
42
+ export interface WorkflowOptions extends BaseOptions {
25
43
  /**
26
- * If set, remove pages from the document as specified.
27
- * This is done before sending the file to the server and is useful to avoid page limitations.
44
+ * Alias to give to the document.
28
45
  */
29
- pageOptions?: PageOptions;
46
+ alias?: string;
47
+ /**
48
+ * Priority to give to the document.
49
+ */
50
+ priority?: ExecutionPriority;
51
+ /**
52
+ * A unique, encrypted URL for accessing the document validation interface without requiring authentication.
53
+ */
54
+ publicUrl?: string;
30
55
  }
31
56
  /**
32
57
  * Asynchronous polling parameters.
@@ -111,6 +136,15 @@ export declare class Client {
111
136
  */
112
137
  parseQueued<T extends Inference>(productClass: new (httpResponse: StringDict) => T, queueId: string, params?: PredictOptions): Promise<AsyncPredictResponse<T>>;
113
138
  loadPrediction<T extends Inference>(productClass: new (httpResponse: StringDict) => T, localResponse: LocalResponse): Promise<AsyncPredictResponse<T> | PredictResponse<T>>;
139
+ /**
140
+ * Send the document to an asynchronous endpoint and return its ID in the queue.
141
+ * @param inputSource file to send to the API.
142
+ * @param workflowId ID of the workflow.
143
+ * @param params parameters relating to prediction options.
144
+ * @category Workflow
145
+ * @returns a `Promise` containing the job (queue) corresponding to a document.
146
+ */
147
+ executeWorkflow(inputSource: InputSource, workflowId: string, params?: WorkflowOptions): Promise<WorkflowResponse<GeneratedV1>>;
114
148
  /**
115
149
  * Fetch prediction results from a document already processed.
116
150
  *
@@ -204,3 +238,4 @@ export declare class Client {
204
238
  */
205
239
  docFromBuffer(buffer: Buffer, filename: string): BufferInput;
206
240
  }
241
+ export {};
package/src/client.js CHANGED
@@ -16,6 +16,8 @@ const inference_1 = require("./parsing/common/inference");
16
16
  const product_1 = require("./product");
17
17
  const promises_1 = require("node:timers/promises");
18
18
  const errors_1 = require("./errors");
19
+ const workflowResponse_1 = require("./parsing/common/workflowResponse");
20
+ const workflowEndpoint_1 = require("./http/workflowEndpoint");
19
21
  /**
20
22
  * Mindee Client class that centralizes most basic operations.
21
23
  *
@@ -126,6 +128,28 @@ class Client {
126
128
  throw new errors_1.MindeeError("No prediction found in local response.");
127
129
  }
128
130
  }
131
+ /**
132
+ * Send the document to an asynchronous endpoint and return its ID in the queue.
133
+ * @param inputSource file to send to the API.
134
+ * @param workflowId ID of the workflow.
135
+ * @param params parameters relating to prediction options.
136
+ * @category Workflow
137
+ * @returns a `Promise` containing the job (queue) corresponding to a document.
138
+ */
139
+ async executeWorkflow(inputSource, workflowId, params = {}) {
140
+ const workflowEndpoint = new workflowEndpoint_1.WorkflowEndpoint(__classPrivateFieldGet(this, _Client_instances, "m", _Client_buildApiSettings).call(this), workflowId);
141
+ if (inputSource === undefined) {
142
+ throw new Error("The 'parse' function requires an input document.");
143
+ }
144
+ const rawResponse = await workflowEndpoint.executeWorkflow({
145
+ inputDoc: inputSource,
146
+ alias: params.alias,
147
+ priority: params.priority,
148
+ pageOptions: params?.pageOptions,
149
+ fullText: this.getBooleanParam(params.fullText),
150
+ });
151
+ return new workflowResponse_1.WorkflowResponse(product_1.GeneratedV1, rawResponse.data);
152
+ }
129
153
  /**
130
154
  * Fetch prediction results from a document already processed.
131
155
  *
@@ -1,6 +1,7 @@
1
1
  export declare const API_KEY_ENVVAR_NAME: string;
2
2
  export declare const API_HOST_ENVVAR_NAME: string;
3
3
  export declare const STANDARD_API_OWNER: string;
4
+ export declare const TIMEOUT_DEFAULT: number;
4
5
  interface MindeeApiConstructorProps {
5
6
  apiKey: string;
6
7
  }
@@ -8,6 +9,7 @@ export declare class ApiSettings {
8
9
  apiKey: string;
9
10
  baseHeaders: Record<string, string>;
10
11
  hostname: string;
12
+ timeout: number;
11
13
  constructor({ apiKey, }: MindeeApiConstructorProps);
12
14
  protected apiKeyFromEnv(): string;
13
15
  protected hostnameFromEnv(): string;
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.ApiSettings = exports.STANDARD_API_OWNER = exports.API_HOST_ENVVAR_NAME = exports.API_KEY_ENVVAR_NAME = void 0;
26
+ exports.ApiSettings = exports.TIMEOUT_DEFAULT = exports.STANDARD_API_OWNER = exports.API_HOST_ENVVAR_NAME = exports.API_KEY_ENVVAR_NAME = void 0;
27
27
  /* eslint-disable @typescript-eslint/naming-convention */
28
28
  const logger_1 = require("../logger");
29
29
  const package_json_1 = require("../../package.json");
@@ -31,6 +31,7 @@ const os = __importStar(require("os"));
31
31
  exports.API_KEY_ENVVAR_NAME = "MINDEE_API_KEY";
32
32
  exports.API_HOST_ENVVAR_NAME = "MINDEE_API_HOST";
33
33
  exports.STANDARD_API_OWNER = "mindee";
34
+ exports.TIMEOUT_DEFAULT = 120;
34
35
  const DEFAULT_MINDEE_API_HOST = "api.mindee.net";
35
36
  const USER_AGENT = `mindee-api-nodejs@v${package_json_1.version} nodejs-${process.version} ${os.type().toLowerCase()}`;
36
37
  class ApiSettings {
@@ -50,6 +51,7 @@ class ApiSettings {
50
51
  Authorization: `Token ${this.apiKey}`,
51
52
  };
52
53
  this.hostname = this.hostnameFromEnv();
54
+ this.timeout = process.env.MINDEE_REQUEST_TIMEOUT ? parseInt(process.env.MINDEE_REQUEST_TIMEOUT) : exports.TIMEOUT_DEFAULT;
53
55
  }
54
56
  apiKeyFromEnv() {
55
57
  const envVarValue = process.env[exports.API_KEY_ENVVAR_NAME];
@@ -1,6 +1,7 @@
1
1
  import { ApiSettings } from "./apiSettings";
2
2
  import { IncomingMessage, ClientRequest } from "http";
3
3
  import { RequestOptions } from "https";
4
+ import { InputSource, PageOptions } from "../input";
4
5
  export interface EndpointResponse {
5
6
  messageObj: IncomingMessage;
6
7
  data: {
@@ -13,7 +14,15 @@ export interface EndpointResponse {
13
14
  export declare abstract class BaseEndpoint {
14
15
  /** Settings relating to the API. */
15
16
  settings: ApiSettings;
16
- protected constructor(settings: ApiSettings);
17
+ /** Entire root of the URL for API calls. */
18
+ urlRoot: string;
19
+ protected constructor(settings: ApiSettings, urlRoot: string);
20
+ /**
21
+ * Cuts a document's pages according to the given options.
22
+ * @param inputDoc input document.
23
+ * @param pageOptions page cutting options.
24
+ */
25
+ protected cutDocPages(inputDoc: InputSource, pageOptions: PageOptions): Promise<void>;
17
26
  /**
18
27
  * Reads a response from the API and processes it.
19
28
  * @param options options related to the request itself.
@@ -3,12 +3,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseEndpoint = void 0;
4
4
  const logger_1 = require("../logger");
5
5
  const https_1 = require("https");
6
+ const base_1 = require("../input/base");
6
7
  /**
7
8
  * Base endpoint for the Mindee API.
8
9
  */
9
10
  class BaseEndpoint {
10
- constructor(settings) {
11
+ constructor(settings, urlRoot) {
11
12
  this.settings = settings;
13
+ this.urlRoot = urlRoot;
14
+ }
15
+ /**
16
+ * Cuts a document's pages according to the given options.
17
+ * @param inputDoc input document.
18
+ * @param pageOptions page cutting options.
19
+ */
20
+ async cutDocPages(inputDoc, pageOptions) {
21
+ if (inputDoc instanceof base_1.LocalInputSource && inputDoc.isPdf()) {
22
+ await inputDoc.cutPdf(pageOptions);
23
+ }
12
24
  }
13
25
  /**
14
26
  * Reads a response from the API and processes it.
@@ -1,15 +1,8 @@
1
1
  import { InputSource } from "../input";
2
- import { PageOptions } from "../input";
3
2
  import { ApiSettings } from "./apiSettings";
4
3
  import { BaseEndpoint, EndpointResponse } from "./baseEndpoint";
5
4
  import { StringDict } from "../parsing/common";
6
- export interface PredictParams {
7
- inputDoc: InputSource;
8
- includeWords: boolean;
9
- fullText: boolean;
10
- pageOptions?: PageOptions;
11
- cropper: boolean;
12
- }
5
+ import { PredictParams } from "./httpParams";
13
6
  /**
14
7
  * Endpoint for a product (OTS or Custom).
15
8
  */
@@ -21,11 +14,9 @@ export declare class Endpoint extends BaseEndpoint {
21
14
  owner: string;
22
15
  /** Product's version, as a string. */
23
16
  version: string;
24
- /** Entire root of the URL for API calls. */
25
- urlRoot: string;
26
17
  constructor(urlName: string, owner: string, version: string, settings: ApiSettings);
27
18
  /**
28
- * Sends a prediction to the API and parses out the result.
19
+ * Sends a document to the API and parses out the result.
29
20
  * Throws an error if the server's response contains one.
30
21
  * @param {PredictParams} params parameters relating to prediction options.
31
22
  * @category Synchronous
@@ -40,6 +31,7 @@ export declare class Endpoint extends BaseEndpoint {
40
31
  * @returns a `Promise` containing queue data.
41
32
  */
42
33
  predictAsync(params: PredictParams): Promise<EndpointResponse>;
34
+ private extractStatusMessage;
43
35
  /**
44
36
  * Requests the results of a queued document from the API.
45
37
  * Throws an error if the server's response contains one.
@@ -7,7 +7,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
7
7
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
8
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
9
  };
10
- var _Endpoint_instances, _Endpoint_cutDocPages, _Endpoint_predictReqPost, _Endpoint_predictAsyncReqPost, _Endpoint_documentQueueReqGet, _Endpoint_documentGetReq, _Endpoint_documentFeedbackPutReq;
10
+ var _Endpoint_instances, _Endpoint_predictReqPost, _Endpoint_predictAsyncReqPost, _Endpoint_documentQueueReqGet, _Endpoint_documentGetReq, _Endpoint_documentFeedbackPutReq;
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.Endpoint = void 0;
13
13
  const url_1 = require("url");
@@ -21,15 +21,14 @@ const responseValidation_1 = require("./responseValidation");
21
21
  */
22
22
  class Endpoint extends baseEndpoint_1.BaseEndpoint {
23
23
  constructor(urlName, owner, version, settings) {
24
- super(settings);
24
+ super(settings, `/v1/products/${owner}/${urlName}/v${version}`);
25
25
  _Endpoint_instances.add(this);
26
26
  this.owner = owner;
27
27
  this.urlName = urlName;
28
28
  this.version = version;
29
- this.urlRoot = `/v1/products/${owner}/${urlName}/v${version}`;
30
29
  }
31
30
  /**
32
- * Sends a prediction to the API and parses out the result.
31
+ * Sends a document to the API and parses out the result.
33
32
  * Throws an error if the server's response contains one.
34
33
  * @param {PredictParams} params parameters relating to prediction options.
35
34
  * @category Synchronous
@@ -38,11 +37,11 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
38
37
  async predict(params) {
39
38
  await params.inputDoc.init();
40
39
  if (params.pageOptions !== undefined) {
41
- await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_cutDocPages).call(this, params.inputDoc, params.pageOptions);
40
+ await super.cutDocPages(params.inputDoc, params.pageOptions);
42
41
  }
43
42
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictReqPost).call(this, params.inputDoc, params.includeWords, params.fullText, params.cropper);
44
43
  if (!(0, responseValidation_1.isValidSyncResponse)(response)) {
45
- (0, error_1.handleError)(this.urlName, response, response.messageObj?.statusMessage);
44
+ (0, error_1.handleError)(this.urlName, response, this.extractStatusMessage(response));
46
45
  }
47
46
  return response;
48
47
  }
@@ -56,14 +55,28 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
56
55
  async predictAsync(params) {
57
56
  await params.inputDoc.init();
58
57
  if (params.pageOptions !== undefined) {
59
- await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_cutDocPages).call(this, params.inputDoc, params.pageOptions);
58
+ await super.cutDocPages(params.inputDoc, params.pageOptions);
60
59
  }
61
60
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictAsyncReqPost).call(this, params.inputDoc, params.includeWords, params.fullText, params.cropper);
62
61
  if (!(0, responseValidation_1.isValidAsyncResponse)(response)) {
63
- (0, error_1.handleError)(this.urlName, response, response.messageObj?.statusMessage);
62
+ (0, error_1.handleError)(this.urlName, response, this.extractStatusMessage(response));
64
63
  }
65
64
  return response;
66
65
  }
66
+ extractStatusMessage(response) {
67
+ if (response.messageObj?.statusMessage !== undefined && response.messageObj?.statusMessage !== null) {
68
+ return response.messageObj?.statusMessage;
69
+ }
70
+ const errorDetail = response.data?.api_request?.error?.detail;
71
+ if (errorDetail) {
72
+ return JSON.stringify(errorDetail);
73
+ }
74
+ const errorMessage = response.data?.api_request?.error?.message;
75
+ if (errorMessage) {
76
+ return JSON.stringify(errorMessage);
77
+ }
78
+ return undefined;
79
+ }
67
80
  /**
68
81
  * Requests the results of a queued document from the API.
69
82
  * Throws an error if the server's response contains one.
@@ -75,7 +88,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
75
88
  const queueResponse = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentQueueReqGet).call(this, queueId);
76
89
  const queueStatusCode = queueResponse.messageObj.statusCode;
77
90
  if (!(0, responseValidation_1.isValidAsyncResponse)(queueResponse)) {
78
- (0, error_1.handleError)(this.urlName, queueResponse, queueResponse.messageObj?.statusMessage);
91
+ (0, error_1.handleError)(this.urlName, queueResponse, this.extractStatusMessage(queueResponse));
79
92
  }
80
93
  if (queueStatusCode === 302 &&
81
94
  queueResponse.messageObj.headers.location !== undefined) {
@@ -93,7 +106,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
93
106
  async getDocument(documentId) {
94
107
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentGetReq).call(this, documentId);
95
108
  if (!(0, responseValidation_1.isValidAsyncResponse)(response)) {
96
- (0, error_1.handleError)("document", response, response.messageObj?.statusMessage);
109
+ (0, error_1.handleError)("document", response, this.extractStatusMessage(response));
97
110
  }
98
111
  return response;
99
112
  }
@@ -105,7 +118,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
105
118
  async sendFeedback(documentId, feedback) {
106
119
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_documentFeedbackPutReq).call(this, documentId, feedback);
107
120
  if (!(0, responseValidation_1.isValidSyncResponse)(response)) {
108
- (0, error_1.handleError)("feedback", response, response.messageObj?.statusMessage);
121
+ (0, error_1.handleError)("feedback", response, this.extractStatusMessage(response));
109
122
  }
110
123
  return response;
111
124
  }
@@ -148,6 +161,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
148
161
  headers: headers,
149
162
  hostname: this.settings.hostname,
150
163
  path: path,
164
+ timeout: this.settings.timeout,
151
165
  };
152
166
  const req = this.readResponse(options, resolve, reject);
153
167
  form.pipe(req);
@@ -157,17 +171,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
157
171
  }
158
172
  }
159
173
  exports.Endpoint = Endpoint;
160
- _Endpoint_instances = new WeakSet(), _Endpoint_cutDocPages =
161
- /**
162
- * Cuts a document's pages according to the given options.
163
- * @param inputDoc input document.
164
- * @param pageOptions page cutting options.
165
- */
166
- async function _Endpoint_cutDocPages(inputDoc, pageOptions) {
167
- if (inputDoc instanceof base_1.LocalInputSource && inputDoc.isPdf()) {
168
- await inputDoc.cutPdf(pageOptions);
169
- }
170
- }, _Endpoint_predictReqPost = function _Endpoint_predictReqPost(input, includeWords = false, fullText = false, cropper = false) {
174
+ _Endpoint_instances = new WeakSet(), _Endpoint_predictReqPost = function _Endpoint_predictReqPost(input, includeWords = false, fullText = false, cropper = false) {
171
175
  return this.sendFileForPrediction(input, "predict", includeWords, fullText, cropper);
172
176
  }, _Endpoint_predictAsyncReqPost = function _Endpoint_predictAsyncReqPost(input, includeWords = false, fullText = false, cropper = false) {
173
177
  return this.sendFileForPrediction(input, "predict_async", includeWords, fullText, cropper);
package/src/http/error.js CHANGED
@@ -11,7 +11,7 @@ function handleError(urlName, response, serverError) {
11
11
  code = 500;
12
12
  response.data.api_request.error = response.data.job.error;
13
13
  }
14
- else {
14
+ else if (response.data) {
15
15
  code = response.data.api_request["status_code"];
16
16
  }
17
17
  }
@@ -0,0 +1,17 @@
1
+ import { InputSource, PageOptions } from "../input";
2
+ import { ExecutionPriority } from "../parsing/common";
3
+ interface HTTPParams {
4
+ inputDoc: InputSource;
5
+ fullText: boolean;
6
+ pageOptions?: PageOptions;
7
+ }
8
+ export interface PredictParams extends HTTPParams {
9
+ includeWords: boolean;
10
+ cropper: boolean;
11
+ }
12
+ export interface WorkflowParams extends HTTPParams {
13
+ alias?: string;
14
+ priority?: ExecutionPriority;
15
+ publicUrl?: string;
16
+ }
17
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -3,3 +3,4 @@ export { EndpointResponse } from "./baseEndpoint";
3
3
  export { STANDARD_API_OWNER, API_KEY_ENVVAR_NAME, ApiSettings, } from "./apiSettings";
4
4
  export { MindeeHttpError, MindeeHttp400Error, MindeeHttp401Error, MindeeHttp403Error, MindeeHttp404Error, MindeeHttp413Error, MindeeHttp429Error, MindeeHttp500Error, MindeeHttp504Error, handleError, } from "./error";
5
5
  export { isValidSyncResponse, isValidAsyncResponse, cleanRequestData, } from "./responseValidation";
6
+ export { PredictParams, WorkflowParams } from "./httpParams";
@@ -13,6 +13,12 @@ function isValidSyncResponse(response) {
13
13
  if (!response.messageObj || !response.messageObj.statusCode) {
14
14
  return false;
15
15
  }
16
+ if (response.data &&
17
+ response.data["api_request"] &&
18
+ response.data["api_request"]["status_code"] &&
19
+ response.data["api_request"]["status_code"] > 399) {
20
+ return false;
21
+ }
16
22
  return !(isNaN(response.messageObj.statusCode) ||
17
23
  parseInt(response.messageObj.statusCode.toString()) < 200 ||
18
24
  parseInt(response.messageObj.statusCode.toString()) > 302);
@@ -0,0 +1,29 @@
1
+ import { BaseEndpoint, EndpointResponse } from "./baseEndpoint";
2
+ import { ApiSettings } from "./apiSettings";
3
+ import { InputSource } from "../input";
4
+ import { WorkflowParams } from "./httpParams";
5
+ import { ExecutionPriority } from "../parsing/common";
6
+ /**
7
+ * Endpoint for a workflow.
8
+ */
9
+ export declare class WorkflowEndpoint extends BaseEndpoint {
10
+ #private;
11
+ constructor(settings: ApiSettings, workflowId: string);
12
+ /**
13
+ * Sends a document to a workflow execution.
14
+ * Throws an error if the server's response contains one.
15
+ * @param {WorkflowParams} params parameters relating to prediction options.
16
+ * @category Synchronous
17
+ * @returns a `Promise` containing parsing results.
18
+ */
19
+ executeWorkflow(params: WorkflowParams): Promise<EndpointResponse>;
20
+ /**
21
+ * Send a file to a prediction API.
22
+ * @param input
23
+ * @param alias
24
+ * @param priority
25
+ * @param fullText
26
+ * @param publicUrl
27
+ */
28
+ protected sendFileForPrediction(input: InputSource, alias?: string | null, priority?: ExecutionPriority | null, fullText?: boolean, publicUrl?: string | null): Promise<EndpointResponse>;
29
+ }
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ var _WorkflowEndpoint_instances, _WorkflowEndpoint_workflowReqPost;
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.WorkflowEndpoint = void 0;
13
+ const baseEndpoint_1 = require("./baseEndpoint");
14
+ const url_1 = require("url");
15
+ const form_data_1 = __importDefault(require("form-data"));
16
+ const base_1 = require("../input/base");
17
+ const responseValidation_1 = require("./responseValidation");
18
+ const error_1 = require("./error");
19
+ /**
20
+ * Endpoint for a workflow.
21
+ */
22
+ class WorkflowEndpoint extends baseEndpoint_1.BaseEndpoint {
23
+ constructor(settings, workflowId) {
24
+ super(settings, `/v1/workflows/${workflowId}/executions`);
25
+ _WorkflowEndpoint_instances.add(this);
26
+ }
27
+ /**
28
+ * Sends a document to a workflow execution.
29
+ * Throws an error if the server's response contains one.
30
+ * @param {WorkflowParams} params parameters relating to prediction options.
31
+ * @category Synchronous
32
+ * @returns a `Promise` containing parsing results.
33
+ */
34
+ async executeWorkflow(params) {
35
+ await params.inputDoc.init();
36
+ if (params.pageOptions !== undefined) {
37
+ await super.cutDocPages(params.inputDoc, params.pageOptions);
38
+ }
39
+ const response = await __classPrivateFieldGet(this, _WorkflowEndpoint_instances, "m", _WorkflowEndpoint_workflowReqPost).call(this, params.inputDoc, params.alias, params.priority, params.fullText, params.publicUrl);
40
+ if (!(0, responseValidation_1.isValidSyncResponse)(response)) {
41
+ (0, error_1.handleError)(this.urlRoot, response, response.messageObj?.statusMessage);
42
+ }
43
+ return response;
44
+ }
45
+ /**
46
+ * Send a file to a prediction API.
47
+ * @param input
48
+ * @param alias
49
+ * @param priority
50
+ * @param fullText
51
+ * @param publicUrl
52
+ */
53
+ sendFileForPrediction(input, alias = null, priority = null, fullText = false, publicUrl = null) {
54
+ return new Promise((resolve, reject) => {
55
+ const searchParams = new url_1.URLSearchParams();
56
+ if (fullText) {
57
+ searchParams.append("full_text_ocr", "true");
58
+ }
59
+ const form = new form_data_1.default();
60
+ if (input instanceof base_1.LocalInputSource && input.fileObject instanceof Buffer) {
61
+ form.append("document", input.fileObject, {
62
+ filename: input.filename,
63
+ });
64
+ }
65
+ else {
66
+ form.append("document", input.fileObject);
67
+ }
68
+ if (alias) {
69
+ form.append("alias", alias);
70
+ }
71
+ if (publicUrl) {
72
+ form.append("public_url", publicUrl);
73
+ }
74
+ if (priority) {
75
+ form.append("priority", priority.toString());
76
+ }
77
+ const headers = { ...this.settings.baseHeaders, ...form.getHeaders() };
78
+ let path = this.urlRoot;
79
+ if (searchParams.toString().length > 0) {
80
+ path += `?${searchParams}`;
81
+ }
82
+ const options = {
83
+ method: "POST",
84
+ headers: headers,
85
+ hostname: this.settings.hostname,
86
+ path: path,
87
+ timeout: this.settings.timeout,
88
+ };
89
+ const req = this.readResponse(options, resolve, reject);
90
+ form.pipe(req);
91
+ // potential ECONNRESET if we don't end the request.
92
+ req.end();
93
+ });
94
+ }
95
+ }
96
+ exports.WorkflowEndpoint = WorkflowEndpoint;
97
+ _WorkflowEndpoint_instances = new WeakSet(), _WorkflowEndpoint_workflowReqPost = function _WorkflowEndpoint_workflowReqPost(input, alias = null, priority = null, fullText = false, publicUrl = null) {
98
+ return this.sendFileForPrediction(input, alias, priority, fullText, publicUrl);
99
+ };
@@ -21,8 +21,8 @@ export declare class Job {
21
21
  /** The time taken to process the job, in milliseconds. */
22
22
  milliSecsTaken?: number;
23
23
  constructor(jsonResponse: StringDict);
24
- protected datetimeWithTimezone(date: string): Date;
25
24
  }
25
+ export declare function datetimeWithTimezone(date: string): Date;
26
26
  /** Wrapper for asynchronous jobs and parsing results.
27
27
  *
28
28
  * @category API Response