mindee 3.5.0 → 3.7.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 (57) hide show
  1. package/CHANGELOG.md +63 -39
  2. package/package.json +3 -3
  3. package/src/api/{response.d.ts → documentResponse.d.ts} +2 -2
  4. package/src/api/endpoint.d.ts +32 -5
  5. package/src/api/endpoint.js +104 -34
  6. package/src/api/index.d.ts +3 -2
  7. package/src/api/index.js +5 -3
  8. package/src/api/predictResponse.d.ts +33 -0
  9. package/src/api/predictResponse.js +52 -0
  10. package/src/cli.js +210 -50
  11. package/src/client.d.ts +20 -4
  12. package/src/client.js +75 -23
  13. package/src/documents/custom/fields.js +1 -1
  14. package/src/documents/custom/lineitems.d.ts +41 -0
  15. package/src/documents/custom/lineitems.js +127 -0
  16. package/src/documents/document.d.ts +1 -1
  17. package/src/documents/documentConfig.d.ts +14 -6
  18. package/src/documents/documentConfig.js +59 -28
  19. package/src/documents/eu/licensePlate/licensePlateV1.js +4 -2
  20. package/src/documents/financialDocument/financialDocumentV0.d.ts +28 -0
  21. package/src/documents/financialDocument/financialDocumentV0.js +140 -0
  22. package/src/documents/financialDocument/financialDocumentV1.d.ts +44 -15
  23. package/src/documents/financialDocument/financialDocumentV1.js +154 -110
  24. package/src/documents/fr/bankAccountDetails/bankAccountDetailsV1.js +3 -2
  25. package/src/documents/fr/carteVitale/carteVitaleV1.js +2 -2
  26. package/src/documents/fr/idCard/idCardV1.js +10 -10
  27. package/src/documents/index.d.ts +5 -1
  28. package/src/documents/index.js +10 -2
  29. package/src/documents/invoice/invoiceV4.d.ts +3 -2
  30. package/src/documents/invoice/invoiceV4.js +85 -86
  31. package/src/documents/invoiceSplitter/invoiceSplitterV1.d.ts +3 -3
  32. package/src/documents/invoiceSplitter/invoiceSplitterV1.js +1 -0
  33. package/src/documents/mindeeVision/mindeeVisionV1.d.ts +8 -0
  34. package/src/documents/mindeeVision/mindeeVisionV1.js +29 -0
  35. package/src/documents/proofOfAddress/proofOfAddressV1.d.ts +24 -0
  36. package/src/documents/proofOfAddress/proofOfAddressV1.js +77 -0
  37. package/src/documents/receipt/receiptV3.d.ts +2 -2
  38. package/src/documents/receipt/receiptV3.js +1 -2
  39. package/src/documents/receipt/receiptV4.d.ts +3 -4
  40. package/src/documents/receipt/receiptV4.js +53 -65
  41. package/src/documents/{shipping_container → shippingContainer}/shippingContainerV1.js +2 -2
  42. package/src/fields/classification.d.ts +8 -0
  43. package/src/fields/classification.js +11 -0
  44. package/src/fields/field.d.ts +2 -2
  45. package/src/fields/field.js +1 -6
  46. package/src/fields/index.d.ts +1 -0
  47. package/src/fields/index.js +3 -1
  48. package/src/geometry.d.ts +18 -4
  49. package/src/geometry.js +40 -3
  50. package/src/index.d.ts +2 -2
  51. package/src/index.js +3 -1
  52. package/src/math/index.d.ts +1 -0
  53. package/src/math/index.js +5 -0
  54. package/src/math/precision.d.ts +1 -0
  55. package/src/math/precision.js +13 -0
  56. /package/src/api/{response.js → documentResponse.js} +0 -0
  57. /package/src/documents/{shipping_container → shippingContainer}/shippingContainerV1.d.ts +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v3.7.0 - 2023-03-31
4
+ ### Changes
5
+ * :sparkles: add support for asynchronous predictions
6
+ * :sparkles: add **experimental** support for line items in custom documents
7
+ * :art: harmonize bbox and bounding box terminology
8
+ * :arrow_up: update test files, minor updates to string output
9
+ * :label: classification fields are always strings
10
+
11
+ ### Fixes
12
+ * :bug: fix error message for missing API key, document type may be undefined
13
+
14
+
15
+ ## v3.6.0 - 2023-02-01
16
+ ### Changes
17
+ * :sparkles: Add support for the mindee_vision API (for internal testing)
18
+ * :sparkles: support Proof of Address V1
19
+ * :sparkles: Add support for: financial document v1
20
+ * :arrow_up: update jsdoc
21
+
22
+ ### ¡Warning!
23
+ The `FinancialDocumentV1` class now uses an actual API call to the new route `financial_document`.
24
+ Previously, determining whether a document is an invoice or a receipt was done internally by this library.
25
+
26
+ The API call way is **much** better, however some fields have been renamed compared to the internal handling.
27
+ This was done so field names now match exactly `Invoice` and `Receipt` classes.
28
+
29
+ As such, we encourage users to migrate to the new field structure.
30
+
31
+ If this is problematic, it's possible to use the deprecated way.
32
+ Simply pass `FinancialDocumentV0` to the `parse` method.
33
+ Usage is otherwise identical.
34
+
35
+
3
36
  ## v3.5.0 - 2023-01-17
4
37
  ### Changes
5
38
  * :memo: updates to class documentation
@@ -8,6 +41,7 @@
8
41
  ### Fixes
9
42
  * :bug: fix for CLI command option description
10
43
 
44
+
11
45
  ## v3.4.1 - 2023-01-05
12
46
  ### Changes
13
47
  * :label: Added typing information, get rid of `any` type in various places
@@ -17,16 +51,19 @@
17
51
  ### Fixes
18
52
  * :bug: Expose various class and type definitions to improve developer experience
19
53
 
54
+
20
55
  ## v3.4.0 - 2023-01-04
21
56
  ### Changes
22
57
  * :sparkles: Support Receipt V4.1
23
58
  * :sparkles: Support Invoice V4.1
24
59
 
60
+
25
61
  ## v3.3.0 - 2022-12-01
26
62
  ### Changes
27
63
  * :sparkles: Add Invoice V4 with line items
28
64
  * :sparkles: An env variable can be used to change the Mindee base API url
29
65
 
66
+
30
67
  ## v3.2.0 - 2022-11-14
31
68
  ### Changes
32
69
  * :sparkles: Add support for shipping container API V1
@@ -37,19 +74,23 @@
37
74
  * :memo: Export and add comments for method parameters.
38
75
  * :sparkles: Add support for US Bank Check V1
39
76
 
77
+
40
78
  ## v3.1.1 - 2022-11-08
41
79
  ### Changes
42
80
  * :bug: fix proper import and documentation of region-specific documents
43
81
 
82
+
44
83
  ## v3.1.0 - 2022-11-08
45
84
  ### Changes
46
85
  * :sparkles: Add support for French ID cards.
47
86
  * :sparkles: add buffer input source
48
87
 
88
+
49
89
  ## v3.0.1 - 2022-11-02
50
90
  ### Fixes
51
91
  * :bug: Fix for `supplier` property name in `ReceiptV4` document.
52
92
 
93
+
53
94
  ## v3.0.0 - 2022-10-31
54
95
  ### ¡Breaking Changes!
55
96
  * :sparkles: New PDF cut system, which allows specifying exactly which pages to keep or remove.
@@ -62,6 +103,7 @@
62
103
  * :sparkles: New URL input source, `docFromUrl`.
63
104
  * :sparkles: Add support for expense receipts V4
64
105
 
106
+
65
107
  ## v2.1.1 - 2022-10-28
66
108
  ### Fixes
67
109
  * :bug: fix for sending base64 documents.
@@ -76,6 +118,7 @@
76
118
  ### Fixes
77
119
  * :bug: Fix for packaging and documentation related to commonJS imports
78
120
 
121
+
79
122
  ## v2.0.0 - 2022-08-26
80
123
  ### Note
81
124
  This is a complete rewrite in TypeScript!
@@ -90,6 +133,7 @@ It's **not** backwards compatible with previous versions.
90
133
  Allows for much easier auto-completion in your IDE.
91
134
  * :arrow_up: all major dependencies updated
92
135
 
136
+
93
137
  ## v1.4.0
94
138
  ### Fixes
95
139
  * :bug: cut/merge pages of an encrypted PDF leads to unexpected results
@@ -100,118 +144,98 @@ It's **not** backwards compatible with previous versions.
100
144
  * :sparkles: Add TIFF and HEIC support
101
145
  * :white_check_mark: fully test PDF cut function
102
146
 
103
- ## v1.3.3
104
147
 
148
+ ## v1.3.3
105
149
  ### Fixes
106
150
  * :bug: reject errors instead of printing them only to the console
107
151
 
108
- ## v1.3.2
109
152
 
153
+ ## v1.3.2
110
154
  ### Fixes
111
155
  * :bug: use PDF length instead of cut PDF size limit
112
156
 
113
- ## v1.3.1
114
157
 
158
+ ## v1.3.1
115
159
  ### Fixes
116
160
  * :bug: forward api error to stderr instead of stdout
117
161
 
118
- ## v1.3.0
119
162
 
163
+ ## v1.3.0
120
164
  ### Changes
121
-
122
165
  * :sparkles: allow sending the filename for streams and base64
123
166
  * :bug: not able to specify MIME type
124
167
  * :page_facing_up: change license to MIT
125
168
  * :white_check_mark: add node18 to tests
126
169
  * various package updates
127
170
 
128
- ## v1.2.0
129
171
 
172
+ ## v1.2.0
130
173
  ### Fixes
131
-
132
174
  * :bug: Get `words` values when `includeWords` parameter is `true`
133
175
 
176
+
134
177
  ## v1.1.2
178
+ ### Changes
179
+ * :sparkles: New Mindee Invoice API V3 support
180
+ * :sparkles: Add new supplier and customer fields
135
181
 
136
182
  ### Fixes
137
-
138
183
  * :bug: Fix returned probability value
139
184
  * :bug: Fix returned bbox value
140
185
 
141
- ### new
142
-
143
- * :sparkles: New Mindee Invoice API V3 support
144
- * :sparkles: Add new supplier and customer fields
145
186
 
146
187
  ## v1.1.0 (2022-01-03)
147
-
148
- ### new
149
-
188
+ ### Changes
150
189
  * :sparkles: New Mindee API V2 support
151
190
  * :zap: Server side invoice reconstruction from multi-page pdfs
152
191
  * :sparkles: Added OS in User-Agent headers
153
192
 
154
193
 
155
194
  ## v1.0.9 (2021-12-09)
156
-
157
195
  ### Fixes
158
-
159
196
  * :bug: handle attribute of type array when merging pages
160
197
 
198
+
161
199
  ## v1.0.8 (2021-11-29)
200
+ ### Changes
201
+ * :see_no_evil: add .DS_Store to ignore file
162
202
 
163
203
  ### Fixes
164
-
165
204
  * :bug: fix cutPDF for ReadableStream + add it for base64 file string
166
205
  * :bug: Updated api Input initialization to specifically declare parameters
167
206
  * :bug: prevent error when the mime type isn't detectable
168
207
  * :bug: raise proper error when the APi doesn't return a valid JSON
169
208
 
170
- ### new
171
-
172
- * :see_no_evil: add .DS_Store to ignore file
173
209
 
174
210
  ## v1.0.7 (2021-11-25)
175
-
176
- ### New
177
-
178
- * :sparkles: Added pdf page number parameter for multi-pages pdfs with file
179
-
180
211
  ### Changes
181
-
212
+ * :sparkles: Added pdf page number parameter for multi-pages pdfs with file
182
213
  * :arrow_up: upgrade path-parse dependency
183
214
  * :arrow_up: upgrade browserslist dependency
184
215
  * :arrow_up: upgrade lodash dependency
185
216
  * :arrow_up: upgrade y18n dependency
186
217
 
187
- ## v1.0.4 (2021-02-18)
188
-
189
- ### New
190
-
191
- * :sparkles: :zap: Add a parameter `filename` and a default filename for streams
192
218
 
219
+ ## v1.0.4 (2021-02-18)
193
220
  ### Changes
194
-
221
+ * :sparkles: :zap: Add a parameter `filename` and a default filename for streams
195
222
  * :zap: Change parse function to use an object instead of multiples parameters
196
223
 
197
- ## v1.0.3 (2021-02-01)
198
224
 
225
+ ## v1.0.3 (2021-02-01)
199
226
  ### Fixes
200
-
201
227
  * :bug: \_request parameters
202
228
  * :bug: `pageNumber` default value
203
229
  * :bug: reconstruction method set fields to probability
204
230
 
205
- ## v1.0.2 (2021-02-01)
206
231
 
232
+ ## v1.0.2 (2021-02-01)
207
233
  ### Changes
208
-
209
234
  * :zap: Better coverage for total tax
210
235
 
211
236
  ### Fixes
212
-
213
237
  * :bug: `includeWords` is now working
214
238
 
215
- ## v1.0.1 (2021-01-11)
216
239
 
240
+ ## v1.0.1 (2021-01-11)
217
241
  * :tada: First release
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mindee",
3
- "version": "3.5.0",
3
+ "version": "3.7.0",
4
4
  "description": "Mindee Client Library for Node.js",
5
5
  "main": "src/index.js",
6
6
  "bin": "bin/mindee.js",
@@ -12,7 +12,7 @@
12
12
  "test": "mocha 'tests/**/*.spec.ts'",
13
13
  "lint-fix": "eslint '**/*.ts' --fix",
14
14
  "lint": "eslint '**/*.ts' --report-unused-disable-directives && echo 'Your .ts files look good.'",
15
- "docs": "jsdoc -r src -d docs"
15
+ "docs": "jsdoc -r dist/src -d docs"
16
16
  },
17
17
  "files": [
18
18
  "src/*",
@@ -47,7 +47,7 @@
47
47
  "eslint": "^8.31.0",
48
48
  "eslint-config-prettier": "^8.6.0",
49
49
  "eslint-plugin-prettier": "^4.2.1",
50
- "jsdoc": "^3.6.11",
50
+ "jsdoc": "~4.0",
51
51
  "mocha": "^10.1.0",
52
52
  "prettier": "^2.8.1",
53
53
  "ts-node": "^10.9.1",
@@ -4,7 +4,7 @@ import { InputSource } from "../inputs";
4
4
  export interface ResponseProps {
5
5
  httpResponse: any;
6
6
  documentType?: string;
7
- input: InputSource;
7
+ input?: InputSource;
8
8
  error: boolean;
9
9
  }
10
10
  export type ResponseSig<DocType extends Document> = {
@@ -15,7 +15,7 @@ export type ResponseSig<DocType extends Document> = {
15
15
  */
16
16
  export declare class Response<DocType extends Document> {
17
17
  httpResponse: any;
18
- inputFile: InputSource;
18
+ inputFile?: InputSource;
19
19
  document?: DocType;
20
20
  pages: Array<DocType>;
21
21
  readonly documentClass: DocumentSig<DocType>;
@@ -1,10 +1,10 @@
1
1
  /// <reference types="node" />
2
2
  import { InputSource } from "../inputs";
3
- import { IncomingMessage } from "http";
3
+ import { IncomingMessage, RequestOptions, ClientRequest } from "http";
4
4
  export declare const STANDARD_API_OWNER = "mindee";
5
5
  export declare const API_KEY_ENVVAR_NAME = "MINDEE_API_KEY";
6
- export declare const API_BASE_URL_ENVVAR_NAME = "MINDEE_BASE_URL";
7
- export interface predictResponse {
6
+ export declare const API_HOST_ENVVAR_NAME = "MINDEE_API_HOST";
7
+ export interface EndpointResponse {
8
8
  messageObj: IncomingMessage;
9
9
  data: {
10
10
  [key: string]: any;
@@ -15,6 +15,7 @@ export declare class Endpoint {
15
15
  urlName: string;
16
16
  owner: string;
17
17
  version: string;
18
+ hostname: string;
18
19
  urlRoot: string;
19
20
  private readonly baseHeaders;
20
21
  constructor(owner: string, urlName: string, version: string, apiKey: string);
@@ -24,9 +25,35 @@ export declare class Endpoint {
24
25
  * @param includeWords
25
26
  * @param cropper
26
27
  */
27
- predictReqPost(input: InputSource, includeWords?: boolean, cropper?: boolean): Promise<predictResponse>;
28
+ predictReqPost(input: InputSource, includeWords?: boolean, cropper?: boolean): Promise<EndpointResponse>;
29
+ /**
30
+ * Make a request to POST a document for async prediction.
31
+ * @param input
32
+ * @param includeWords
33
+ * @param cropper
34
+ */
35
+ predictAsyncReqPost(input: InputSource, includeWords?: boolean, cropper?: boolean): Promise<EndpointResponse>;
36
+ /**
37
+ * Make a request to GET the status of a document in the queue.
38
+ * @param queueId
39
+ */
40
+ documentQueueReqGet(queueId: string): Promise<EndpointResponse>;
41
+ /**
42
+ * Make a request to GET a document.
43
+ * @param documentId
44
+ */
45
+ documentGetReq(documentId: string): Promise<EndpointResponse>;
46
+ /**
47
+ * Send a file to a prediction API.
48
+ * @param input
49
+ * @param predictUrl
50
+ * @param includeWords
51
+ * @param cropper
52
+ */
53
+ protected sendFileForPrediction(input: InputSource, predictUrl: string, includeWords?: boolean, cropper?: boolean): Promise<EndpointResponse>;
54
+ protected readResponse(options: RequestOptions, resolve: (value: EndpointResponse | PromiseLike<EndpointResponse>) => void, reject: (reason?: any) => void): ClientRequest;
28
55
  protected apiKeyFromEnv(): string;
29
- protected baseUrlFromEnv(): string;
56
+ protected hostnameFromEnv(): string;
30
57
  }
31
58
  export declare class StandardEndpoint extends Endpoint {
32
59
  constructor(endpointName: string, version: string, apiKey: string);
@@ -26,25 +26,26 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.CustomEndpoint = exports.StandardEndpoint = exports.Endpoint = exports.API_BASE_URL_ENVVAR_NAME = exports.API_KEY_ENVVAR_NAME = exports.STANDARD_API_OWNER = void 0;
29
+ exports.CustomEndpoint = exports.StandardEndpoint = exports.Endpoint = exports.API_HOST_ENVVAR_NAME = exports.API_KEY_ENVVAR_NAME = exports.STANDARD_API_OWNER = void 0;
30
30
  const https = __importStar(require("https"));
31
31
  const os = __importStar(require("os"));
32
32
  const package_json_1 = require("../../package.json");
33
33
  const url_1 = require("url");
34
34
  const form_data_1 = __importDefault(require("form-data"));
35
35
  const logger_1 = require("../logger");
36
- const DEFAULT_MINDEE_API_URL = "https://api.mindee.net/v1";
36
+ const DEFAULT_MINDEE_API_HOST = "api.mindee.net";
37
37
  const USER_AGENT = `mindee-api-nodejs@v${package_json_1.version} nodejs-${process.version} ${os.type().toLowerCase()}`;
38
38
  exports.STANDARD_API_OWNER = "mindee";
39
39
  exports.API_KEY_ENVVAR_NAME = "MINDEE_API_KEY";
40
- exports.API_BASE_URL_ENVVAR_NAME = "MINDEE_BASE_URL";
40
+ exports.API_HOST_ENVVAR_NAME = "MINDEE_API_HOST";
41
41
  class Endpoint {
42
42
  constructor(owner, urlName, version, apiKey) {
43
43
  this.owner = owner;
44
44
  this.urlName = urlName;
45
45
  this.version = version;
46
46
  this.apiKey = apiKey || this.apiKeyFromEnv();
47
- this.urlRoot = `${this.baseUrlFromEnv()}/products/${owner}/${urlName}/v${version}`;
47
+ this.hostname = this.hostnameFromEnv();
48
+ this.urlRoot = `/v1/products/${owner}/${urlName}/v${version}`;
48
49
  this.baseHeaders = {
49
50
  "User-Agent": USER_AGENT,
50
51
  Authorization: `Token ${this.apiKey}`,
@@ -57,12 +58,64 @@ class Endpoint {
57
58
  * @param cropper
58
59
  */
59
60
  predictReqPost(input, includeWords = false, cropper = false) {
61
+ return this.sendFileForPrediction(input, "predict", includeWords, cropper);
62
+ }
63
+ /**
64
+ * Make a request to POST a document for async prediction.
65
+ * @param input
66
+ * @param includeWords
67
+ * @param cropper
68
+ */
69
+ predictAsyncReqPost(input, includeWords = false, cropper = false) {
70
+ return this.sendFileForPrediction(input, "predict_async", includeWords, cropper);
71
+ }
72
+ /**
73
+ * Make a request to GET the status of a document in the queue.
74
+ * @param queueId
75
+ */
76
+ documentQueueReqGet(queueId) {
77
+ return new Promise((resolve, reject) => {
78
+ const options = {
79
+ method: "GET",
80
+ headers: this.baseHeaders,
81
+ hostname: this.hostname,
82
+ path: `${this.urlRoot}/documents/queue/${queueId}`,
83
+ };
84
+ const req = this.readResponse(options, resolve, reject);
85
+ // potential ECONNRESET if we don't end the request.
86
+ req.end();
87
+ });
88
+ }
89
+ /**
90
+ * Make a request to GET a document.
91
+ * @param documentId
92
+ */
93
+ documentGetReq(documentId) {
60
94
  return new Promise((resolve, reject) => {
61
- const uri = new url_1.URL(`${this.urlRoot}/predict`);
95
+ const options = {
96
+ method: "GET",
97
+ headers: this.baseHeaders,
98
+ hostname: this.hostname,
99
+ path: `${this.urlRoot}/documents/${documentId}`,
100
+ };
101
+ const req = this.readResponse(options, resolve, reject);
102
+ // potential ECONNRESET if we don't end the request.
103
+ req.end();
104
+ });
105
+ }
106
+ /**
107
+ * Send a file to a prediction API.
108
+ * @param input
109
+ * @param predictUrl
110
+ * @param includeWords
111
+ * @param cropper
112
+ */
113
+ sendFileForPrediction(input, predictUrl, includeWords = false, cropper = false) {
114
+ return new Promise((resolve, reject) => {
115
+ const searchParams = new url_1.URLSearchParams();
62
116
  if (cropper) {
63
- uri.searchParams.append("cropper", "true");
117
+ searchParams.append("cropper", "true");
64
118
  }
65
- logger_1.logger.debug(`Request URI: ${uri}`);
66
119
  const form = new form_data_1.default();
67
120
  if (input.fileObject instanceof Buffer) {
68
121
  form.append("document", input.fileObject, { filename: input.filename });
@@ -74,36 +127,53 @@ class Endpoint {
74
127
  form.append("include_mvision", "true");
75
128
  }
76
129
  const headers = { ...this.baseHeaders, ...form.getHeaders() };
130
+ let path = `${this.urlRoot}/${predictUrl}`;
131
+ if (searchParams.keys.length > 0) {
132
+ path += `?${searchParams}`;
133
+ }
77
134
  const options = {
78
135
  method: "POST",
79
136
  headers: headers,
80
- hostname: uri.hostname,
81
- path: `${uri.pathname}${uri.search}`,
137
+ hostname: this.hostname,
138
+ path: path,
82
139
  };
83
- const req = https.request(options, function (res) {
84
- // when the encoding is set, data chunks will be strings
85
- res.setEncoding("utf-8");
86
- let responseBody = "";
87
- res.on("data", function (chunk) {
88
- responseBody += chunk;
89
- });
90
- res.on("end", function () {
91
- try {
92
- resolve({
93
- messageObj: res,
94
- data: JSON.parse(responseBody),
95
- });
96
- }
97
- catch (error) {
98
- reject(error);
99
- }
100
- });
101
- });
140
+ const req = this.readResponse(options, resolve, reject);
102
141
  form.pipe(req);
103
- req.on("error", (err) => {
104
- reject(err);
142
+ // potential ECONNRESET if we don't end the request.
143
+ req.end();
144
+ });
145
+ }
146
+ readResponse(options, resolve, reject) {
147
+ logger_1.logger.debug(`${options.method}: https://${options.hostname}${options.path}`);
148
+ const req = https.request(options, function (res) {
149
+ // when the encoding is set, data chunks will be strings
150
+ res.setEncoding("utf-8");
151
+ let responseBody = "";
152
+ res.on("data", function (chunk) {
153
+ logger_1.logger.debug("receiving data ...");
154
+ responseBody += chunk;
105
155
  });
156
+ res.on("end", function () {
157
+ // handle empty responses from server, for example in the case of redirects
158
+ if (!responseBody) {
159
+ responseBody = "{}";
160
+ }
161
+ try {
162
+ resolve({
163
+ messageObj: res,
164
+ data: JSON.parse(responseBody),
165
+ });
166
+ }
167
+ catch (error) {
168
+ logger_1.logger.debug(responseBody);
169
+ reject(error);
170
+ }
171
+ });
172
+ });
173
+ req.on("error", (err) => {
174
+ reject(err);
106
175
  });
176
+ return req;
107
177
  }
108
178
  apiKeyFromEnv() {
109
179
  const envVarValue = process.env[exports.API_KEY_ENVVAR_NAME];
@@ -113,13 +183,13 @@ class Endpoint {
113
183
  }
114
184
  return "";
115
185
  }
116
- baseUrlFromEnv() {
117
- const envVarValue = process.env[exports.API_BASE_URL_ENVVAR_NAME];
186
+ hostnameFromEnv() {
187
+ const envVarValue = process.env[exports.API_HOST_ENVVAR_NAME];
118
188
  if (envVarValue) {
119
- logger_1.logger.debug(`Set the API base URL to ${envVarValue}`);
189
+ logger_1.logger.debug(`Set the API hostname to ${envVarValue}`);
120
190
  return envVarValue;
121
191
  }
122
- return DEFAULT_MINDEE_API_URL;
192
+ return DEFAULT_MINDEE_API_HOST;
123
193
  }
124
194
  }
125
195
  exports.Endpoint = Endpoint;
@@ -1,2 +1,3 @@
1
- export { Response, ResponseSig } from "./response";
2
- export { Endpoint, CustomEndpoint, StandardEndpoint, predictResponse, STANDARD_API_OWNER, API_KEY_ENVVAR_NAME, } from "./endpoint";
1
+ export { Response, ResponseSig } from "./documentResponse";
2
+ export { Endpoint, CustomEndpoint, StandardEndpoint, EndpointResponse, STANDARD_API_OWNER, API_KEY_ENVVAR_NAME, } from "./endpoint";
3
+ export { AsyncPredictResponse } from "./predictResponse";
package/src/api/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.API_KEY_ENVVAR_NAME = exports.STANDARD_API_OWNER = exports.StandardEndpoint = exports.CustomEndpoint = exports.Endpoint = exports.Response = void 0;
4
- var response_1 = require("./response");
5
- Object.defineProperty(exports, "Response", { enumerable: true, get: function () { return response_1.Response; } });
3
+ exports.AsyncPredictResponse = exports.API_KEY_ENVVAR_NAME = exports.STANDARD_API_OWNER = exports.StandardEndpoint = exports.CustomEndpoint = exports.Endpoint = exports.Response = void 0;
4
+ var documentResponse_1 = require("./documentResponse");
5
+ Object.defineProperty(exports, "Response", { enumerable: true, get: function () { return documentResponse_1.Response; } });
6
6
  var endpoint_1 = require("./endpoint");
7
7
  Object.defineProperty(exports, "Endpoint", { enumerable: true, get: function () { return endpoint_1.Endpoint; } });
8
8
  Object.defineProperty(exports, "CustomEndpoint", { enumerable: true, get: function () { return endpoint_1.CustomEndpoint; } });
9
9
  Object.defineProperty(exports, "StandardEndpoint", { enumerable: true, get: function () { return endpoint_1.StandardEndpoint; } });
10
10
  Object.defineProperty(exports, "STANDARD_API_OWNER", { enumerable: true, get: function () { return endpoint_1.STANDARD_API_OWNER; } });
11
11
  Object.defineProperty(exports, "API_KEY_ENVVAR_NAME", { enumerable: true, get: function () { return endpoint_1.API_KEY_ENVVAR_NAME; } });
12
+ var predictResponse_1 = require("./predictResponse");
13
+ Object.defineProperty(exports, "AsyncPredictResponse", { enumerable: true, get: function () { return predictResponse_1.AsyncPredictResponse; } });
@@ -0,0 +1,33 @@
1
+ import { StringDict } from "../fields";
2
+ import { Document } from "../documents";
3
+ import { Response } from "./documentResponse";
4
+ export declare class Job {
5
+ issuedAt: Date;
6
+ availableAt?: Date;
7
+ id?: string;
8
+ status?: "waiting" | "processing" | "completed";
9
+ /**
10
+ * The time taken to process the job, in milliseconds.
11
+ */
12
+ milliSecsTaken?: number;
13
+ constructor(jsonResponse: StringDict);
14
+ protected datetimeWithTimezone(date: string): Date;
15
+ }
16
+ export declare class ApiRequest {
17
+ error: StringDict;
18
+ resources: string[];
19
+ status: "failure" | "success";
20
+ /** HTTP status code */
21
+ statusCode: number;
22
+ url: string;
23
+ constructor(serverResponse: StringDict);
24
+ }
25
+ export declare class BasePredictResponse {
26
+ apiRequest: ApiRequest;
27
+ constructor(serverResponse: StringDict);
28
+ }
29
+ export declare class AsyncPredictResponse<DocType extends Document> extends BasePredictResponse {
30
+ job: Job;
31
+ document?: Response<DocType>;
32
+ constructor(serverResponse: StringDict, document?: Response<DocType>);
33
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AsyncPredictResponse = exports.BasePredictResponse = exports.ApiRequest = exports.Job = void 0;
4
+ class Job {
5
+ constructor(jsonResponse) {
6
+ this.issuedAt = this.datetimeWithTimezone(jsonResponse["issued_at"]);
7
+ if (jsonResponse["available_at"] !== undefined &&
8
+ jsonResponse["available_at"] !== null) {
9
+ this.availableAt = this.datetimeWithTimezone(jsonResponse["available_at"]);
10
+ }
11
+ this.id = jsonResponse["id"];
12
+ this.status = jsonResponse["status"];
13
+ if (this.availableAt !== undefined) {
14
+ this.milliSecsTaken =
15
+ this.availableAt.getTime() - this.issuedAt.getTime();
16
+ }
17
+ }
18
+ // Hideous thing to make sure dates sent back by the server are parsed correctly in UTC.
19
+ datetimeWithTimezone(date) {
20
+ if (date.search(/\+[0-9]{2}:[0-9]{2}$/) === -1) {
21
+ date += "+00:00";
22
+ }
23
+ return new Date(date);
24
+ }
25
+ }
26
+ exports.Job = Job;
27
+ class ApiRequest {
28
+ constructor(serverResponse) {
29
+ this.error = serverResponse["error"];
30
+ this.resources = serverResponse["resources"];
31
+ this.status = serverResponse["status"];
32
+ this.statusCode = serverResponse["status_code"];
33
+ this.url = serverResponse["url"];
34
+ }
35
+ }
36
+ exports.ApiRequest = ApiRequest;
37
+ // For upcoming v4, use this as the base for all responses.
38
+ // To not break compatibility, in v3.x, we will only use it as the base for async responses.
39
+ class BasePredictResponse {
40
+ constructor(serverResponse) {
41
+ this.apiRequest = new ApiRequest(serverResponse["api_request"]);
42
+ }
43
+ }
44
+ exports.BasePredictResponse = BasePredictResponse;
45
+ class AsyncPredictResponse extends BasePredictResponse {
46
+ constructor(serverResponse, document) {
47
+ super(serverResponse);
48
+ this.job = new Job(serverResponse["job"]);
49
+ this.document = document;
50
+ }
51
+ }
52
+ exports.AsyncPredictResponse = AsyncPredictResponse;