mindee 1.4.0 → 2.0.1

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 (89) hide show
  1. package/CHANGELOG.md +37 -19
  2. package/README.md +46 -126
  3. package/bin/mindee.d.ts +2 -0
  4. package/bin/mindee.js +5 -0
  5. package/package.json +68 -58
  6. package/src/api/endpoint.d.ts +29 -0
  7. package/src/api/endpoint.js +151 -0
  8. package/src/api/index.d.ts +2 -0
  9. package/src/api/index.js +18 -0
  10. package/src/api/response.d.ts +52 -0
  11. package/src/api/response.js +107 -0
  12. package/src/cli.d.ts +1 -0
  13. package/src/cli.js +114 -0
  14. package/src/client.d.ts +48 -0
  15. package/src/client.js +123 -0
  16. package/src/constants.d.ts +13 -0
  17. package/src/constants.js +54 -0
  18. package/src/documents/custom.d.ts +14 -0
  19. package/src/documents/custom.js +48 -0
  20. package/src/documents/document.d.ts +38 -0
  21. package/src/documents/document.js +59 -0
  22. package/src/documents/documentConfig.d.ts +44 -0
  23. package/src/documents/documentConfig.js +104 -0
  24. package/src/documents/financialDocument.d.ts +32 -0
  25. package/src/documents/financialDocument.js +133 -0
  26. package/src/documents/index.d.ts +12 -0
  27. package/src/documents/index.js +20 -0
  28. package/src/documents/invoice.d.ts +37 -0
  29. package/src/documents/invoice.js +303 -0
  30. package/src/documents/passport.d.ts +36 -0
  31. package/src/documents/passport.js +218 -0
  32. package/src/documents/receipt.d.ts +24 -0
  33. package/src/documents/receipt.js +157 -0
  34. package/src/errors/handler.d.ts +7 -0
  35. package/src/errors/handler.js +18 -0
  36. package/src/fields/amount.d.ts +13 -0
  37. package/src/fields/amount.js +34 -0
  38. package/src/fields/companyRegistration.d.ts +6 -0
  39. package/src/fields/companyRegistration.js +11 -0
  40. package/src/fields/customDocs.d.ts +42 -0
  41. package/src/fields/customDocs.js +61 -0
  42. package/src/fields/date.d.ts +12 -0
  43. package/src/fields/date.js +25 -0
  44. package/src/fields/field.d.ts +74 -0
  45. package/src/fields/field.js +106 -0
  46. package/src/fields/fullText.d.ts +24 -0
  47. package/src/fields/fullText.js +89 -0
  48. package/src/fields/index.d.ts +11 -0
  49. package/src/fields/index.js +27 -0
  50. package/src/fields/locale.d.ts +13 -0
  51. package/src/fields/locale.js +40 -0
  52. package/src/fields/orientation.d.ts +10 -0
  53. package/src/fields/orientation.js +22 -0
  54. package/src/fields/paymentDetails.d.ts +31 -0
  55. package/src/fields/paymentDetails.js +58 -0
  56. package/src/fields/tax.d.ts +30 -0
  57. package/src/fields/tax.js +50 -0
  58. package/src/geometry.d.ts +59 -0
  59. package/src/geometry.js +113 -0
  60. package/src/index.d.ts +2 -0
  61. package/src/index.js +12 -0
  62. package/src/inputs.d.ts +69 -0
  63. package/src/inputs.js +196 -0
  64. package/src/logger.d.ts +20 -0
  65. package/src/logger.js +35 -0
  66. package/mindee/api/financialDocument.js +0 -47
  67. package/mindee/api/index.js +0 -5
  68. package/mindee/api/invoice.js +0 -53
  69. package/mindee/api/object.js +0 -82
  70. package/mindee/api/receipt.js +0 -39
  71. package/mindee/api/request.js +0 -72
  72. package/mindee/api/response.js +0 -80
  73. package/mindee/documents/document.js +0 -69
  74. package/mindee/documents/fields/amount.js +0 -25
  75. package/mindee/documents/fields/date.js +0 -29
  76. package/mindee/documents/fields/field.js +0 -86
  77. package/mindee/documents/fields/index.js +0 -7
  78. package/mindee/documents/fields/locale.js +0 -30
  79. package/mindee/documents/fields/orientation.js +0 -24
  80. package/mindee/documents/fields/paymentDetails.js +0 -52
  81. package/mindee/documents/fields/tax.js +0 -47
  82. package/mindee/documents/financialDocument.js +0 -269
  83. package/mindee/documents/index.js +0 -5
  84. package/mindee/documents/invoice.js +0 -456
  85. package/mindee/documents/receipt.js +0 -287
  86. package/mindee/errors/handler.js +0 -16
  87. package/mindee/index.js +0 -39
  88. package/mindee/inputs.js +0 -181
  89. package/mindee/logger.js +0 -34
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v2.0.1 - 2022-10-13
4
+ ### Fixes
5
+ * :bug: Fix for packaging and documentation related to commonJS imports
6
+
7
+ ## v2.0.0 - 2022-08-26
8
+ ### Note
9
+ This is a complete rewrite in TypeScript!
10
+
11
+ It's **not** backwards compatible with previous versions.
12
+
13
+ ### Changes
14
+ * :sparkles: Add Passport API support
15
+ * :sparkles: Add custom document support (API builder)
16
+ * :sparkles: Add basic geometry functions
17
+ * :label: everything is typed, in particular response objects.
18
+ Allows for much easier auto-completion in your IDE.
19
+ * :arrow_up: all major dependencies updated
20
+
3
21
  ## v1.4.0
4
22
  ### Fixes
5
23
  * :bug: cut/merge pages of an encrypted PDF leads to unexpected results
@@ -13,24 +31,24 @@
13
31
  ## v1.3.3
14
32
 
15
33
  ### Fixes
16
- * 🐛 reject errors instead of printing them only to the console
34
+ * :bug: reject errors instead of printing them only to the console
17
35
 
18
36
  ## v1.3.2
19
37
 
20
38
  ### Fixes
21
- * 🐛 use PDF length instead of cut PDF size limit
39
+ * :bug: use PDF length instead of cut PDF size limit
22
40
 
23
41
  ## v1.3.1
24
42
 
25
43
  ### Fixes
26
- * 🐛 forward api error to stderr instead of stdout
44
+ * :bug: forward api error to stderr instead of stdout
27
45
 
28
46
  ## v1.3.0
29
47
 
30
48
  ### Changes
31
49
 
32
50
  * :sparkles: allow sending the filename for streams and base64
33
- * fixes :bug: not able to specify MIME type
51
+ * :bug: not able to specify MIME type
34
52
  * :page_facing_up: change license to MIT
35
53
  * :white_check_mark: add node18 to tests
36
54
  * various package updates
@@ -39,43 +57,43 @@
39
57
 
40
58
  ### Fixes
41
59
 
42
- * fix: 🐛 Get `words` values when `includeWords` parameter is `true`
60
+ * :bug: Get `words` values when `includeWords` parameter is `true`
43
61
 
44
62
  ## v1.1.2
45
63
 
46
64
  ### Fixes
47
65
 
48
- * fix: 🐛 Fix returned probability value
49
- * fix: 🐛 Fix returned bbox value
66
+ * :bug: Fix returned probability value
67
+ * :bug: Fix returned bbox value
50
68
 
51
69
  ### new
52
70
 
53
- * new: New Mindee Invoice API V3 support
54
- * new: Add new supplier and customer fields
71
+ * :sparkles: New Mindee Invoice API V3 support
72
+ * :sparkles: Add new supplier and customer fields
55
73
 
56
74
  ## v1.1.0 (2022-01-03)
57
75
 
58
76
  ### new
59
77
 
60
- * chg: :sparkles: New Mindee API V2 support
61
- * chg: :zap: Server side invoice reconstruction from multi-page pdfs
62
- * new: :sparkles: Added OS in User-Agent headers
78
+ * :sparkles: New Mindee API V2 support
79
+ * :zap: Server side invoice reconstruction from multi-page pdfs
80
+ * :sparkles: Added OS in User-Agent headers
63
81
 
64
82
 
65
83
  ## v1.0.9 (2021-12-09)
66
84
 
67
85
  ### Fixes
68
86
 
69
- * fix: 🐛 handle attribute of type array when merging pages
87
+ * :bug: handle attribute of type array when merging pages
70
88
 
71
89
  ## v1.0.8 (2021-11-29)
72
90
 
73
91
  ### Fixes
74
92
 
75
- * 🐛 fix cutPDF for ReadableStream + add it for base64 file string
76
- * 🐛 Updated api Input initialization to specifically declare parameters
77
- * 🐛 prevent error when the mime type isn't detectable
78
- * 🐛 raise proper error when the APi doesn't return a valid JSON
93
+ * :bug: fix cutPDF for ReadableStream + add it for base64 file string
94
+ * :bug: Updated api Input initialization to specifically declare parameters
95
+ * :bug: prevent error when the mime type isn't detectable
96
+ * :bug: raise proper error when the APi doesn't return a valid JSON
79
97
 
80
98
  ### new
81
99
 
@@ -85,7 +103,7 @@
85
103
 
86
104
  ### New
87
105
 
88
- * Added pdf page number parameter for multi-pages pdfs with file
106
+ * :sparkles: Added pdf page number parameter for multi-pages pdfs with file
89
107
 
90
108
  ### Changes
91
109
 
@@ -124,4 +142,4 @@
124
142
 
125
143
  ## v1.0.1 (2021-01-11)
126
144
 
127
- * 🎉 First release
145
+ * :tada: First release
package/README.md CHANGED
@@ -1,150 +1,70 @@
1
- # Mindee Client Library for Node.js
1
+ # Mindee API Helper Library for Node.js
2
+ Quickly and easily connect to Mindee's API services using Node.js.
2
3
 
3
- # Installation
4
+ ## Quick Start
5
+ Here's the TL;DR of getting started.
4
6
 
5
- ## Requirements
7
+ First, get an [API Key](https://developers.mindee.com/docs/create-api-key)
6
8
 
7
- The SDK is officially supported on Node.js LTS _active_ and _maintenance_
8
- [versions](https://nodejs.org/en/about/releases/).
9
-
10
- ## From source code
11
-
12
- Download and decompress or clone the source code from GitHub and then do in your Node.js project:
13
-
14
- ```sh
9
+ Then, install this library:
10
+ ```shell
15
11
  npm install mindee
16
12
  ```
17
13
 
18
- # Usage
14
+ Finally, Node.js away!
19
15
 
20
- You can use the SDK easily by creating a Client like this:
16
+ ### Off-the-Shelf Documents
21
17
 
22
18
  ```js
23
- const { Client } = require("mindee");
24
-
25
- const mindeeClient = new Client({
26
- invoiceToken: "invoiceApiToken",
27
- receiptToken: "receiptExpenseApiToken",
28
- });
29
-
30
- mindeeClient.invoice.parse({ input: "path/to/file", inputType: "file" });
31
- mindeeClient.receipt.parse({ input: base64String, inputType: "base64" });
32
- mindeeClient.financialDocument.parse({
33
- input: base64String,
34
- inputType: "base64",
35
- });
36
- ```
37
-
38
- Three APIs are actually supported: invoice (`ìnvoice`), receipt (`receipt`) and financial document (`financialDocument`)
19
+ const mindee = require("mindee");
20
+ // for TS or modules:
21
+ // import * as mindee from "mindee";
39
22
 
40
- You can find more examples on how to use the SDK into the folder `examples`.
23
+ // Init a new client
24
+ const mindeeClient = new mindee.Client({apiKey: "my-api-key"});
41
25
 
42
- ## MIME Types
43
- When using `stream` or `base64` inputs, the MIME type is guessed using magic numbers.
44
- In some cases, for example with non-standard files, it will not be possible to detect the MIME type in this way.
26
+ // Load a file from disk and parse it
27
+ const invoiceResponse = mindeeClient.docFromPath("/path/to/the/invoice.pdf")
28
+ .parse(mindee.InvoiceResponse);
45
29
 
46
- If you are getting MIME type errors, you will need to specify a file name having the correct extension, for example:
47
- ```js
48
- mindeeClient.invoice.parse({
49
- input: base64String,
50
- inputType: "base64",
51
- filename: "myfile.pdf",
30
+ // Print a brief summary of the parsed data
31
+ invoiceResponse.then((resp) => {
32
+ console.log(resp.document);
52
33
  });
53
34
  ```
54
35
 
55
- ## Client
56
-
57
- The Mindee client can take multiple parameters to be initialize.
58
- Some this parameters can also be set with env variables.
59
- If the env variable and the parameter are both set, the parameter will be the one chosen by the client.
60
- This is a list of them:
61
-
62
- - invoiceToken (env variable : `MINDEE_INVOICE_TOKEN`) The expense api token
63
- - receiptToken (env variable : `MINDEE_RECEIPT_TOKEN`) The invoice api token
64
- - throwOnError (`true` by default) If `true`, the SDK will throw on error
65
- - debug (env variable : `MINDEE_DEBUG`, `false` by default) If `true`, logging will be in debug mode
66
-
67
- Depending on what type of document you want to parse, you need to add specifics auth token for each endpoint.
68
- We suggest storing your credentials as environment variables for security reasons.
69
-
70
- ## Parsing Invoices
71
-
72
- ```js
73
- const { Client } = require("mindee");
74
- const fs = require("fs");
75
-
76
- // Invoice token can be set by Env (MINDEE_INVOICE_TOKEN) or via params (Client({invoiceToken: "token"}))
77
- const mindeeClient = new Client();
78
-
79
- // parsing invoice from pdf
80
- mindeeClient.invoice
81
- .parse({ input: "./documents/invoices/invoice.pdf" }) // see examples for more input types
82
- .then((res) => {
83
- console.log("Success !");
84
- console.log(res.invoices);
85
- console.log(res.invoice);
86
- })
87
- .catch((err) => {
88
- console.error(err);
89
- });
90
- ```
91
-
92
- ## Parsing receipts
36
+ ### Custom Documents (API Builder)
93
37
 
94
38
  ```js
95
- const { Client } = require("mindee");
96
- const fs = require("fs");
97
-
98
- // Receipt token can be set by Env (MINDEE_RECEIPT_TOKEN) or via params (Client({receiptToken: "token"}))
99
- const mindeeClient = new Client();
100
-
101
- // parsing receipt from picture
102
- mindeeClient.receipt
103
- .parse({ input: "./documents/receipts/receipt.jpg" }) // see examples for more input types
104
- .then((res) => {
105
- console.log("Success !");
106
- console.log(res.receipts);
107
- console.log(res.receipt);
108
- })
109
- .catch((err) => {
110
- console.error(err);
111
- });
112
- ```
113
-
114
- ## Parsing a mix of invoices and receipts: Financial document
39
+ const mindee = require("mindee");
40
+ // for TS or modules:
41
+ // import * as mindee from "mindee";
42
+
43
+ // Init a new client and add your document endpoint
44
+ const mindeeClient = new mindee.Client({apiKey: "my-api-key"})
45
+ .addEndpoint({
46
+ accountName: "john",
47
+ documentType: "wsnine",
48
+ });
115
49
 
116
- The Financial document API optimizes the parsing results when you don't know if your file is a receipt or an invoice.
50
+ // Load a file from disk and parse it
51
+ const customResponse = mindeeClient.docFromPath("/path/to/the/wsnine.jpg")
52
+ .parse(mindee.CustomResponse, {docType: "wsnine"});
117
53
 
118
- ```js
119
- const { Client } = require("mindee");
120
-
121
- // Invoice token and Receipt token must be set
122
- // Receipt token can be set by Env (MINDEE_RECEIPT_TOKEN) or via params (Client({receiptToken: "token"}))
123
- // Invoice token can be set by Env (MINDEE_INVOICE_TOKEN) or via params (Client({invoiceToken: "token"}))
124
-
125
- const mindeeClient = new Client();
126
-
127
- // parsing receipt from picture
128
- mindeeClient.financialDocument
129
- .parse({ input: "./documents/receipts/receipt.jpg" })
130
- .then((res) => {
131
- console.log("Success !");
132
- console.log(res.financialDocuments);
133
- console.log(res.financialDocument);
134
- })
135
- .catch((err) => {
136
- console.error(err);
137
- });
54
+ // Print a brief summary of the parsed data
55
+ customResponse.then((resp) => {
56
+ console.log(resp.document);
57
+ });
138
58
  ```
139
59
 
140
- # Tests
141
-
142
- To run the tests, use the command `npm run test`
60
+ ## Further Reading
61
+ There's more to it than that for those that need more features, or want to
62
+ customize the experience.
143
63
 
144
- # Documentation
64
+ All the juicy details are described in the
65
+ **[Official Documentation](https://developers.mindee.com/docs/nodejs-sdk)**.
145
66
 
146
- A basic documentation of the sdk has been done with the help of JSDoc.
147
- If you want to generate it, you can use the command `npm run documentation`.
148
- A folder `docs` will be created with generated documentation.
149
- Open the `index.html` in your browser to read the documentation.
67
+ ## License
68
+ Copyright © Mindee
150
69
 
70
+ Available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/bin/mindee.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const cli_1 = require("../src/cli");
5
+ (0, cli_1.cli)();
package/package.json CHANGED
@@ -1,60 +1,70 @@
1
1
  {
2
- "name": "mindee",
3
- "version": "1.4.0",
4
- "description": "Mindee Client Library for Node.js",
5
- "main": "mindee/index.js",
6
- "license": "MIT",
7
- "scripts": {
8
- "build": "babel mindee -d lib",
9
- "test": "npm run build && mocha tests/*.js tests/**/*.js",
10
- "lint": "eslint 'mindee/**/*.js' 'tests/*.js' --max-warnings=0 --report-unused-disable-directives && echo '✔ Your .js files look good.'",
11
- "documentation": "jsdoc -r mindee -d docs"
12
- },
13
- "files": [
14
- "mindee/",
15
- "LICENSE",
16
- "README.md",
17
- "CHANGELOG.md"
18
- ],
19
- "engines": {
20
- "node": ">= 12.0.0"
21
- },
22
- "repository": {
23
- "type": "git",
24
- "url": "git+https://github.com/mindee/mindee-api-nodejs.git"
25
- },
26
- "author": "@techmindee",
27
- "bugs": {
28
- "url": "https://github.com/mindee/mindee-api-nodejs/issues"
29
- },
30
- "homepage": "https://github.com/mindee/mindee-api-nodejs/#readme",
31
- "devDependencies": {
32
- "@babel/cli": "^7.17.10",
33
- "@babel/core": "^7.17.12",
34
- "@babel/eslint-parser": "^7.12.1",
35
- "@babel/preset-env": "^7.12.7",
36
- "@babel/register": "^7.12.1",
37
- "chai": "^4.2.0",
38
- "eslint": "^7.14.0",
39
- "eslint-config-prettier": "^6.15.0",
40
- "eslint-plugin-prettier": "^3.1.4",
41
- "jsdoc": "^3.6.6",
42
- "mocha": "^8.2.1",
43
- "prettier": "^2.2.0"
44
- },
45
- "dependencies": {
46
- "base64-arraybuffer": "^1.0.2",
47
- "base64-stream": "^1.0.0",
48
- "concat-stream": "^2.0.0",
49
- "file-type": "^16.5.3",
50
- "form-data": "^3.0.1",
51
- "pdf-lib": "^1.17.1"
52
- },
53
- "keywords": [
54
- "javascript",
55
- "mindee",
56
- "api",
57
- "SDK",
58
- "nodejs"
59
- ]
2
+ "name": "mindee",
3
+ "version": "2.0.1",
4
+ "description": "Mindee Client Library for Node.js",
5
+ "main": "src/index.js",
6
+ "bin": "bin/mindee.js",
7
+ "license": "MIT",
8
+ "scripts": {
9
+ "build": "tsc --build && cp LICENSE README.md CHANGELOG.md ./dist",
10
+ "clean": "rm -rf ./dist",
11
+ "test": "mocha 'tests/**/*.spec.ts'",
12
+ "lint-fix": "eslint '**/*.ts' --fix",
13
+ "lint": "eslint '**/*.ts' --report-unused-disable-directives && echo 'Your .ts files look good.'",
14
+ "docs": "jsdoc -r src -d docs"
15
+ },
16
+ "files": [
17
+ "src/*",
18
+ "bin/*",
19
+ "LICENSE",
20
+ "README.md",
21
+ "CHANGELOG.md"
22
+ ],
23
+ "engines": {
24
+ "node": ">= 14"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/mindee/mindee-api-nodejs.git"
29
+ },
30
+ "author": {
31
+ "name": "Mindee",
32
+ "email": "devrel@mindee.com",
33
+ "url": "https://mindee.com/"
34
+ },
35
+ "bugs": {
36
+ "url": "https://github.com/mindee/mindee-api-nodejs/issues"
37
+ },
38
+ "homepage": "https://mindee.com/",
39
+ "devDependencies": {
40
+ "@types/chai": "^4.3.1",
41
+ "@types/mocha": "^9.1.1",
42
+ "@types/node": "^17.0.38",
43
+ "@typescript-eslint/eslint-plugin": "^5.30.0",
44
+ "@typescript-eslint/parser": "^5.30.0",
45
+ "chai": "^4.3.6",
46
+ "eslint": "^8.18.0",
47
+ "eslint-config-prettier": "^8.5.0",
48
+ "eslint-plugin-prettier": "^4.1.0",
49
+ "jsdoc": "^3.6.10",
50
+ "mocha": "^10.0.0",
51
+ "prettier": "^2.7.1",
52
+ "ts-node": "^10.8.1",
53
+ "typescript": "^4.7.4"
54
+ },
55
+ "dependencies": {
56
+ "commander": "^9.4.0",
57
+ "file-type": "^16.5.4",
58
+ "form-data": "^3.0.1",
59
+ "mrz": "^3.1.4",
60
+ "pdf-lib": "^1.17.1"
61
+ },
62
+ "keywords": [
63
+ "typescript",
64
+ "mindee",
65
+ "api",
66
+ "client",
67
+ "client library",
68
+ "nodejs"
69
+ ]
60
70
  }
@@ -0,0 +1,29 @@
1
+ import { Input } from "../inputs";
2
+ export declare const STANDARD_API_OWNER = "mindee";
3
+ export declare const API_KEY_ENVVAR_NAME = "MINDEE_API_KEY";
4
+ export declare class Endpoint {
5
+ apiKey: string;
6
+ urlName: string;
7
+ keyName: string;
8
+ owner: string;
9
+ version: string;
10
+ urlRoot: string;
11
+ constructor(owner: string, urlName: string, version: string, apiKey: string, keyName?: string);
12
+ /**
13
+ * Make a prediction request.
14
+ */
15
+ predictRequest(input: Input, includeWords?: boolean): Promise<unknown>;
16
+ protected apiKeyFromEnv(): string;
17
+ }
18
+ export declare class InvoiceEndpoint extends Endpoint {
19
+ constructor(apiKey: string);
20
+ }
21
+ export declare class ReceiptEndpoint extends Endpoint {
22
+ constructor(apiKey: string);
23
+ }
24
+ export declare class PassportEndpoint extends Endpoint {
25
+ constructor(apiKey: string);
26
+ }
27
+ export declare class CustomEndpoint extends Endpoint {
28
+ constructor(documentType: string, accountName: string, version: string, apiKey: string);
29
+ }
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.CustomEndpoint = exports.PassportEndpoint = exports.ReceiptEndpoint = exports.InvoiceEndpoint = exports.Endpoint = exports.API_KEY_ENVVAR_NAME = exports.STANDARD_API_OWNER = void 0;
30
+ const https = __importStar(require("https"));
31
+ const os = __importStar(require("os"));
32
+ const package_json_1 = require("../../package.json");
33
+ const url_1 = require("url");
34
+ const form_data_1 = __importDefault(require("form-data"));
35
+ const logger_1 = require("../logger");
36
+ const MINDEE_API_URL = "https://api.mindee.net/v1";
37
+ const USER_AGENT = `mindee-api-nodejs@v${package_json_1.version} nodejs-${process.version} ${os.type().toLowerCase()}`;
38
+ exports.STANDARD_API_OWNER = "mindee";
39
+ exports.API_KEY_ENVVAR_NAME = "MINDEE_API_KEY";
40
+ class Endpoint {
41
+ constructor(owner, urlName, version, apiKey, keyName) {
42
+ this.owner = owner;
43
+ this.urlName = urlName;
44
+ this.version = version;
45
+ this.keyName = keyName || urlName;
46
+ this.apiKey = apiKey || this.apiKeyFromEnv();
47
+ this.urlRoot = `${MINDEE_API_URL}/products/${owner}/${urlName}/v${version}`;
48
+ }
49
+ /**
50
+ * Make a prediction request.
51
+ */
52
+ predictRequest(input, includeWords = false) {
53
+ return new Promise((resolve, reject) => {
54
+ const form = new form_data_1.default();
55
+ let body;
56
+ let headers = {
57
+ "User-Agent": USER_AGENT,
58
+ Authorization: `Token ${this.apiKey}`,
59
+ };
60
+ // TODO: redo this section given there should only
61
+ // be a single way of reading the input doc
62
+ if (["path", "stream"].includes(input.inputType)) {
63
+ const fileParams = { filename: input.filename };
64
+ form.append("document", input.fileObject, fileParams);
65
+ if (includeWords) {
66
+ form.append("include_mvision", "true");
67
+ }
68
+ headers = { ...headers, ...form.getHeaders() };
69
+ }
70
+ else if (input.inputType === "base64") {
71
+ const bodyObj = { document: input.fileObject };
72
+ if (includeWords) {
73
+ bodyObj["include_mvision"] = "true";
74
+ }
75
+ body = JSON.stringify(bodyObj);
76
+ headers["Content-Type"] = "application/json";
77
+ headers["Content-Length"] = body.length;
78
+ }
79
+ const uri = new url_1.URL(`${this.urlRoot}/predict`);
80
+ const options = {
81
+ method: "POST",
82
+ headers: headers,
83
+ hostname: uri.hostname,
84
+ path: `${uri.pathname}${uri.search}`,
85
+ };
86
+ logger_1.logger.debug(`Prediction request: ${uri}`);
87
+ const req = https.request(options, function (res) {
88
+ // when the encoding is set, data chunks will be strings
89
+ res.setEncoding("utf-8");
90
+ let responseBody = "";
91
+ res.on("data", function (chunk) {
92
+ responseBody += chunk;
93
+ });
94
+ res.on("end", function () {
95
+ try {
96
+ resolve({
97
+ ...res,
98
+ data: JSON.parse(responseBody),
99
+ });
100
+ }
101
+ catch (error) {
102
+ reject(error);
103
+ }
104
+ });
105
+ });
106
+ req.on("error", (err) => {
107
+ reject(err);
108
+ });
109
+ if (["path", "stream"].includes(input.inputType)) {
110
+ form.pipe(req);
111
+ }
112
+ if (input.inputType === "base64") {
113
+ req.write(body);
114
+ req.end();
115
+ }
116
+ });
117
+ }
118
+ apiKeyFromEnv() {
119
+ const envVarValue = process.env[exports.API_KEY_ENVVAR_NAME];
120
+ if (envVarValue) {
121
+ logger_1.logger.debug(`Set '${this.keyName}' API key from environment: ${exports.API_KEY_ENVVAR_NAME}`);
122
+ return envVarValue;
123
+ }
124
+ return "";
125
+ }
126
+ }
127
+ exports.Endpoint = Endpoint;
128
+ class InvoiceEndpoint extends Endpoint {
129
+ constructor(apiKey) {
130
+ super(exports.STANDARD_API_OWNER, "invoices", "3", apiKey, "invoice");
131
+ }
132
+ }
133
+ exports.InvoiceEndpoint = InvoiceEndpoint;
134
+ class ReceiptEndpoint extends Endpoint {
135
+ constructor(apiKey) {
136
+ super(exports.STANDARD_API_OWNER, "expense_receipts", "3", apiKey, "receipt");
137
+ }
138
+ }
139
+ exports.ReceiptEndpoint = ReceiptEndpoint;
140
+ class PassportEndpoint extends Endpoint {
141
+ constructor(apiKey) {
142
+ super(exports.STANDARD_API_OWNER, "passport", "1", apiKey);
143
+ }
144
+ }
145
+ exports.PassportEndpoint = PassportEndpoint;
146
+ class CustomEndpoint extends Endpoint {
147
+ constructor(documentType, accountName, version, apiKey) {
148
+ super(accountName, documentType, version, apiKey);
149
+ }
150
+ }
151
+ exports.CustomEndpoint = CustomEndpoint;
@@ -0,0 +1,2 @@
1
+ export { Response, InvoiceResponse, ReceiptResponse, FinancialDocResponse, PassportResponse, CustomResponse, } from "./response";
2
+ export { Endpoint, InvoiceEndpoint, ReceiptEndpoint, PassportEndpoint, CustomEndpoint, STANDARD_API_OWNER, API_KEY_ENVVAR_NAME, } from "./endpoint";