mindee 4.28.0 → 4.29.0-rc2

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 (90) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +22 -167
  3. package/package.json +7 -7
  4. package/src/cli.js +17 -7
  5. package/src/cliProducts.js +17 -7
  6. package/src/client.d.ts +3 -2
  7. package/src/client.js +9 -9
  8. package/src/clientV2.d.ts +190 -0
  9. package/src/clientV2.js +216 -0
  10. package/src/errors/mindeeError.d.ts +8 -0
  11. package/src/errors/mindeeError.js +17 -1
  12. package/src/http/apiSettings.d.ts +2 -8
  13. package/src/http/apiSettings.js +3 -41
  14. package/src/http/apiSettingsV2.d.ts +10 -0
  15. package/src/http/apiSettingsV2.js +46 -0
  16. package/src/http/baseEndpoint.d.ts +2 -2
  17. package/src/http/baseEndpoint.js +3 -3
  18. package/src/http/baseSettings.d.ts +11 -0
  19. package/src/http/baseSettings.js +59 -0
  20. package/src/http/endpoint.js +6 -6
  21. package/src/http/mindeeApiV2.d.ts +34 -0
  22. package/src/http/mindeeApiV2.js +120 -0
  23. package/src/http/workflowEndpoint.js +2 -2
  24. package/src/imageOperations/common/imageExtractor.d.ts +1 -1
  25. package/src/imageOperations/imageCompressor.d.ts +1 -1
  26. package/src/index.d.ts +2 -1
  27. package/src/index.js +20 -8
  28. package/src/input/localResponse.d.ts +13 -0
  29. package/src/input/localResponse.js +36 -7
  30. package/src/input/sources/localInputSource.d.ts +6 -0
  31. package/src/input/sources/localInputSource.js +26 -8
  32. package/src/internal.js +17 -7
  33. package/src/parsing/common/dateParser.d.ts +1 -0
  34. package/src/parsing/common/dateParser.js +12 -0
  35. package/src/parsing/common/execution.d.ts +0 -1
  36. package/src/parsing/common/execution.js +5 -9
  37. package/src/parsing/common/index.d.ts +1 -0
  38. package/src/parsing/common/index.js +20 -8
  39. package/src/parsing/index.d.ts +1 -0
  40. package/src/parsing/index.js +19 -8
  41. package/src/parsing/v2/commonResponse.d.ts +16 -0
  42. package/src/parsing/v2/commonResponse.js +19 -0
  43. package/src/parsing/v2/errorResponse.d.ts +15 -0
  44. package/src/parsing/v2/errorResponse.js +13 -0
  45. package/src/parsing/v2/field/baseField.d.ts +9 -0
  46. package/src/parsing/v2/field/baseField.js +18 -0
  47. package/src/parsing/v2/field/fieldConfidence.d.ts +9 -0
  48. package/src/parsing/v2/field/fieldConfidence.js +13 -0
  49. package/src/parsing/v2/field/fieldFactory.d.ts +8 -0
  50. package/src/parsing/v2/field/fieldFactory.js +22 -0
  51. package/src/parsing/v2/field/fieldLocation.d.ts +13 -0
  52. package/src/parsing/v2/field/fieldLocation.js +18 -0
  53. package/src/parsing/v2/field/index.d.ts +6 -0
  54. package/src/parsing/v2/field/index.js +15 -0
  55. package/src/parsing/v2/field/inferenceFields.d.ts +9 -0
  56. package/src/parsing/v2/field/inferenceFields.js +38 -0
  57. package/src/parsing/v2/field/listField.d.ts +12 -0
  58. package/src/parsing/v2/field/listField.js +36 -0
  59. package/src/parsing/v2/field/objectField.d.ts +9 -0
  60. package/src/parsing/v2/field/objectField.js +18 -0
  61. package/src/parsing/v2/field/simpleField.d.ts +7 -0
  62. package/src/parsing/v2/field/simpleField.js +17 -0
  63. package/src/parsing/v2/index.d.ts +12 -0
  64. package/src/parsing/v2/index.js +27 -0
  65. package/src/parsing/v2/inference.d.ts +24 -0
  66. package/src/parsing/v2/inference.js +26 -0
  67. package/src/parsing/v2/inferenceResponse.d.ts +10 -0
  68. package/src/parsing/v2/inferenceResponse.js +12 -0
  69. package/src/parsing/v2/inferenceResult.d.ts +15 -0
  70. package/src/parsing/v2/inferenceResult.js +25 -0
  71. package/src/parsing/v2/inferenceResultFile.d.ts +13 -0
  72. package/src/parsing/v2/inferenceResultFile.js +16 -0
  73. package/src/parsing/v2/inferenceResultModel.d.ts +8 -0
  74. package/src/parsing/v2/inferenceResultModel.js +9 -0
  75. package/src/parsing/v2/inferenceResultOptions.d.ts +9 -0
  76. package/src/parsing/v2/inferenceResultOptions.js +10 -0
  77. package/src/parsing/v2/job.d.ts +49 -0
  78. package/src/parsing/v2/job.js +29 -0
  79. package/src/parsing/v2/jobResponse.d.ts +10 -0
  80. package/src/parsing/v2/jobResponse.js +12 -0
  81. package/src/parsing/v2/jobResponseWebhook.d.ts +24 -0
  82. package/src/parsing/v2/jobResponseWebhook.js +19 -0
  83. package/src/parsing/v2/rawText.d.ts +15 -0
  84. package/src/parsing/v2/rawText.js +13 -0
  85. package/src/pdf/pdfCompressor.js +17 -7
  86. package/src/product/fr/internal.js +17 -7
  87. package/src/product/ind/internal.js +17 -7
  88. package/src/product/index.js +17 -7
  89. package/src/product/internal.js +17 -7
  90. package/src/product/us/internal.js +17 -7
@@ -0,0 +1,216 @@
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 _ClientV2_instances, _ClientV2_setAsyncParams;
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ClientV2 = void 0;
10
+ const input_1 = require("./input");
11
+ const handler_1 = require("./errors/handler");
12
+ const logger_1 = require("./logger");
13
+ const promises_1 = require("node:timers/promises");
14
+ const mindeeApiV2_1 = require("./http/mindeeApiV2");
15
+ const mindeeError_1 = require("./errors/mindeeError");
16
+ /**
17
+ * Mindee Client V2 class that centralizes most basic operations.
18
+ *
19
+ * @category ClientV2
20
+ */
21
+ class ClientV2 {
22
+ /**
23
+ * @param {ClientOptions} options options for the initialization of a client.
24
+ */
25
+ constructor({ apiKey, throwOnError, debug } = {
26
+ apiKey: "",
27
+ throwOnError: true,
28
+ debug: false,
29
+ }) {
30
+ _ClientV2_instances.add(this);
31
+ this.mindeeApi = new mindeeApiV2_1.MindeeApiV2(apiKey);
32
+ handler_1.errorHandler.throwOnError = throwOnError ?? true;
33
+ logger_1.logger.level =
34
+ debug ?? process.env.MINDEE_DEBUG
35
+ ? logger_1.LOG_LEVELS["debug"]
36
+ : logger_1.LOG_LEVELS["warn"];
37
+ logger_1.logger.debug("ClientV2 initialized");
38
+ }
39
+ /**
40
+ * Send the document to an asynchronous endpoint and return its ID in the queue.
41
+ * @param inputSource file to parse.
42
+ * @param params parameters relating to prediction options.
43
+ * @category Asynchronous
44
+ * @returns a `Promise` containing the job (queue) corresponding to a document.
45
+ */
46
+ async enqueueInference(inputSource, params) {
47
+ if (inputSource === undefined) {
48
+ throw new Error("The 'enqueue' function requires an input document.");
49
+ }
50
+ return await this.mindeeApi.reqPostInferenceEnqueue(inputSource, params);
51
+ }
52
+ /**
53
+ * Retrieves an inference.
54
+ *
55
+ * @param inferenceId id of the queue to poll.
56
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
57
+ * @category Asynchronous
58
+ * @returns a `Promise` containing a `Job`, which also contains a `Document` if the
59
+ * parsing is complete.
60
+ */
61
+ async getInference(inferenceId) {
62
+ return await this.mindeeApi.reqGetInference(inferenceId);
63
+ }
64
+ /**
65
+ * Get the status of an inference that was previously enqueued.
66
+ * Can be used for polling.
67
+ *
68
+ * @param jobId id of the queue to poll.
69
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
70
+ * @category Asynchronous
71
+ * @returns a `Promise` containing a `Job`, which also contains a `Document` if the
72
+ * parsing is complete.
73
+ */
74
+ async getJob(jobId) {
75
+ return await this.mindeeApi.reqGetJob(jobId);
76
+ }
77
+ /**
78
+ * Send a document to an endpoint and poll the server until the result is sent or
79
+ * until the maximum number of tries is reached.
80
+ *
81
+ * @param inputDoc document to parse.
82
+ * @param params parameters relating to prediction options.
83
+ *
84
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
85
+ * @category Synchronous
86
+ * @returns a `Promise` containing parsing results.
87
+ */
88
+ async enqueueAndGetInference(inputDoc, params) {
89
+ const validatedAsyncParams = __classPrivateFieldGet(this, _ClientV2_instances, "m", _ClientV2_setAsyncParams).call(this, params.pollingOptions);
90
+ const enqueueResponse = await this.enqueueInference(inputDoc, params);
91
+ if (enqueueResponse.job.id === undefined || enqueueResponse.job.id.length === 0) {
92
+ logger_1.logger.error(`Failed enqueueing:\n${enqueueResponse.getRawHttp()}`);
93
+ throw Error("Enqueueing of the document failed.");
94
+ }
95
+ const queueId = enqueueResponse.job.id;
96
+ logger_1.logger.debug(`Successfully enqueued document with job id: ${queueId}.`);
97
+ await (0, promises_1.setTimeout)(validatedAsyncParams.initialDelaySec * 1000, undefined, validatedAsyncParams.initialTimerOptions);
98
+ let retryCounter = 1;
99
+ let pollResults = await this.getJob(queueId);
100
+ while (retryCounter < validatedAsyncParams.maxRetries) {
101
+ if (pollResults.job.status === "Failed") {
102
+ break;
103
+ }
104
+ if (pollResults.job.status === "Processed") {
105
+ return this.getInference(pollResults.job.id);
106
+ }
107
+ logger_1.logger.debug(`Polling server for parsing result with queueId: ${queueId}.
108
+ Attempt n°${retryCounter}/${validatedAsyncParams.maxRetries}.
109
+ Job status: ${pollResults.job.status}.`);
110
+ await (0, promises_1.setTimeout)(validatedAsyncParams.delaySec * 1000, undefined, validatedAsyncParams.recurringTimerOptions);
111
+ pollResults = await this.getJob(queueId);
112
+ retryCounter++;
113
+ }
114
+ const error = pollResults.job.error;
115
+ if (error) {
116
+ throw new mindeeError_1.MindeeHttpErrorV2(error.status, error.detail);
117
+ }
118
+ throw Error("Asynchronous parsing request timed out after " +
119
+ validatedAsyncParams.delaySec * retryCounter +
120
+ " seconds");
121
+ }
122
+ /**
123
+ * Load an input source from a local path.
124
+ * @param inputPath
125
+ */
126
+ sourceFromPath(inputPath) {
127
+ return new input_1.PathInput({
128
+ inputPath: inputPath,
129
+ });
130
+ }
131
+ /**
132
+ * Load an input source from a base64 encoded string.
133
+ * @param inputString input content, as a string.
134
+ * @param filename file name.
135
+ */
136
+ sourceFromBase64(inputString, filename) {
137
+ return new input_1.Base64Input({
138
+ inputString: inputString,
139
+ filename: filename,
140
+ });
141
+ }
142
+ /**
143
+ * Load an input source from a `stream.Readable` object.
144
+ * @param inputStream input content, as a readable stream.
145
+ * @param filename file name.
146
+ */
147
+ sourceFromStream(inputStream, filename) {
148
+ return new input_1.StreamInput({
149
+ inputStream: inputStream,
150
+ filename: filename,
151
+ });
152
+ }
153
+ /**
154
+ * Load an input source from bytes.
155
+ * @param inputBytes input content, as a Uint8Array or Buffer.
156
+ * @param filename file name.
157
+ */
158
+ sourceFromBytes(inputBytes, filename) {
159
+ return new input_1.BytesInput({
160
+ inputBytes: inputBytes,
161
+ filename: filename,
162
+ });
163
+ }
164
+ /**
165
+ * Load an input source from a Buffer.
166
+ * @param buffer input content, as a buffer.
167
+ * @param filename file name.
168
+ */
169
+ sourceFromBuffer(buffer, filename) {
170
+ return new input_1.BufferInput({
171
+ buffer: buffer,
172
+ filename: filename,
173
+ });
174
+ }
175
+ /**
176
+ * Load an input source from a URL.
177
+ * @param url input url. Must be HTTPS.
178
+ */
179
+ sourceFromUrl(url) {
180
+ return new input_1.UrlInput({
181
+ url: url,
182
+ });
183
+ }
184
+ }
185
+ exports.ClientV2 = ClientV2;
186
+ _ClientV2_instances = new WeakSet(), _ClientV2_setAsyncParams = function _ClientV2_setAsyncParams(asyncParams = undefined) {
187
+ const minDelaySec = 1;
188
+ const minInitialDelay = 1;
189
+ const minRetries = 2;
190
+ let newAsyncParams;
191
+ if (asyncParams === undefined) {
192
+ newAsyncParams = {
193
+ delaySec: 1.5,
194
+ initialDelaySec: 2,
195
+ maxRetries: 80
196
+ };
197
+ }
198
+ else {
199
+ newAsyncParams = { ...asyncParams };
200
+ if (!newAsyncParams.delaySec ||
201
+ !newAsyncParams.initialDelaySec ||
202
+ !newAsyncParams.maxRetries) {
203
+ throw Error("Invalid polling options.");
204
+ }
205
+ if (newAsyncParams.delaySec < minDelaySec) {
206
+ throw Error(`Cannot set auto-parsing delay to less than ${minDelaySec} second(s).`);
207
+ }
208
+ if (newAsyncParams.initialDelaySec < minInitialDelay) {
209
+ throw Error(`Cannot set initial parsing delay to less than ${minInitialDelay} second(s).`);
210
+ }
211
+ if (newAsyncParams.maxRetries < minRetries) {
212
+ throw Error(`Cannot set retry to less than ${minRetries}.`);
213
+ }
214
+ }
215
+ return newAsyncParams;
216
+ };
@@ -16,3 +16,11 @@ export declare class MindeeImageError extends MindeeError {
16
16
  export declare class MindeePdfError extends MindeeError {
17
17
  constructor(message: string);
18
18
  }
19
+ export declare class MindeeApiV2Error extends MindeeError {
20
+ constructor(message: string);
21
+ }
22
+ export declare class MindeeHttpErrorV2 extends MindeeError {
23
+ status: number;
24
+ detail: string;
25
+ constructor(status: number, detail: string);
26
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MindeePdfError = exports.MindeeImageError = exports.MindeeMimeTypeError = exports.MindeeError = void 0;
3
+ exports.MindeeHttpErrorV2 = exports.MindeeApiV2Error = exports.MindeePdfError = exports.MindeeImageError = exports.MindeeMimeTypeError = exports.MindeeError = void 0;
4
4
  /**
5
5
  * Main Mindee Error custom class.
6
6
  */
@@ -35,3 +35,19 @@ class MindeePdfError extends MindeeError {
35
35
  }
36
36
  }
37
37
  exports.MindeePdfError = MindeePdfError;
38
+ class MindeeApiV2Error extends MindeeError {
39
+ constructor(message) {
40
+ super(message);
41
+ this.name = "MindeeApiV2Error";
42
+ }
43
+ }
44
+ exports.MindeeApiV2Error = MindeeApiV2Error;
45
+ class MindeeHttpErrorV2 extends MindeeError {
46
+ constructor(status, detail) {
47
+ super(`HTTP ${status} - ${detail}`);
48
+ this.status = status;
49
+ this.detail = detail;
50
+ this.name = "MindeeHttpErrorV2";
51
+ }
52
+ }
53
+ exports.MindeeHttpErrorV2 = MindeeHttpErrorV2;
@@ -1,18 +1,12 @@
1
+ import { BaseSettings, MindeeApiConstructorProps } from "./baseSettings";
1
2
  export declare const API_KEY_ENVVAR_NAME: string;
2
3
  export declare const API_HOST_ENVVAR_NAME: string;
3
4
  export declare const STANDARD_API_OWNER: string;
4
5
  export declare const TIMEOUT_DEFAULT: number;
5
- interface MindeeApiConstructorProps {
6
- apiKey: string;
7
- }
8
- export declare class ApiSettings {
6
+ export declare class ApiSettings extends BaseSettings {
9
7
  apiKey: string;
10
8
  baseHeaders: Record<string, string>;
11
- hostname: string;
12
- timeout: number;
13
9
  constructor({ apiKey, }: MindeeApiConstructorProps);
14
- protected getUserAgent(): string;
15
10
  protected apiKeyFromEnv(): string;
16
11
  protected hostnameFromEnv(): string;
17
12
  }
18
- export {};
@@ -1,40 +1,17 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
26
3
  exports.ApiSettings = exports.TIMEOUT_DEFAULT = exports.STANDARD_API_OWNER = exports.API_HOST_ENVVAR_NAME = exports.API_KEY_ENVVAR_NAME = void 0;
27
4
  /* eslint-disable @typescript-eslint/naming-convention */
28
5
  const logger_1 = require("../logger");
29
- const package_json_1 = require("../../package.json");
30
- const os = __importStar(require("os"));
6
+ const baseSettings_1 = require("./baseSettings");
31
7
  exports.API_KEY_ENVVAR_NAME = "MINDEE_API_KEY";
32
8
  exports.API_HOST_ENVVAR_NAME = "MINDEE_API_HOST";
33
9
  exports.STANDARD_API_OWNER = "mindee";
34
10
  exports.TIMEOUT_DEFAULT = 120;
35
11
  const DEFAULT_MINDEE_API_HOST = "api.mindee.net";
36
- class ApiSettings {
12
+ class ApiSettings extends baseSettings_1.BaseSettings {
37
13
  constructor({ apiKey = "", }) {
14
+ super();
38
15
  if (!apiKey || apiKey.length === 0) {
39
16
  this.apiKey = this.apiKeyFromEnv();
40
17
  }
@@ -49,21 +26,6 @@ class ApiSettings {
49
26
  "User-Agent": this.getUserAgent(),
50
27
  Authorization: `Token ${this.apiKey}`,
51
28
  };
52
- this.hostname = this.hostnameFromEnv();
53
- this.timeout = process.env.MINDEE_REQUEST_TIMEOUT ? parseInt(process.env.MINDEE_REQUEST_TIMEOUT) : exports.TIMEOUT_DEFAULT;
54
- }
55
- getUserAgent() {
56
- let platform = os.type().toLowerCase();
57
- if (platform.includes("darwin")) {
58
- platform = "macos";
59
- }
60
- else if (platform.includes("window")) {
61
- platform = "windows";
62
- }
63
- else if (platform.includes("bsd")) {
64
- platform = "bsd";
65
- }
66
- return `mindee-api-nodejs@v${package_json_1.version} nodejs-${process.version} ${platform}`;
67
29
  }
68
30
  apiKeyFromEnv() {
69
31
  const envVarValue = process.env[exports.API_KEY_ENVVAR_NAME];
@@ -0,0 +1,10 @@
1
+ import { BaseSettings, MindeeApiConstructorProps } from "./baseSettings";
2
+ export declare const API_V2_KEY_ENVVAR_NAME: string;
3
+ export declare const API_V2_HOST_ENVVAR_NAME: string;
4
+ export declare class ApiSettingsV2 extends BaseSettings {
5
+ apiKey: string;
6
+ baseHeaders: Record<string, string>;
7
+ constructor({ apiKey, }: MindeeApiConstructorProps);
8
+ protected apiKeyFromEnv(): string;
9
+ protected hostnameFromEnv(): string;
10
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiSettingsV2 = exports.API_V2_HOST_ENVVAR_NAME = exports.API_V2_KEY_ENVVAR_NAME = void 0;
4
+ /* eslint-disable @typescript-eslint/naming-convention */
5
+ const logger_1 = require("../logger");
6
+ const baseSettings_1 = require("./baseSettings");
7
+ const mindeeError_1 = require("../errors/mindeeError");
8
+ exports.API_V2_KEY_ENVVAR_NAME = "MINDEE_V2_API_KEY";
9
+ exports.API_V2_HOST_ENVVAR_NAME = "MINDEE_V2_API_HOST";
10
+ const DEFAULT_MINDEE_API_HOST = "api-v2.mindee.net";
11
+ class ApiSettingsV2 extends baseSettings_1.BaseSettings {
12
+ constructor({ apiKey = "", }) {
13
+ super();
14
+ if (!apiKey || apiKey.length === 0) {
15
+ this.apiKey = this.apiKeyFromEnv();
16
+ }
17
+ else {
18
+ this.apiKey = apiKey;
19
+ }
20
+ if (!this.apiKey || this.apiKey.length === 0) {
21
+ throw new mindeeError_1.MindeeApiV2Error("Your API V2 key could not be set, check your Client Configuration\n."
22
+ + `You can set this using the ${exports.API_V2_KEY_ENVVAR_NAME} environment variable.`);
23
+ }
24
+ this.baseHeaders = {
25
+ "User-Agent": this.getUserAgent(),
26
+ Authorization: `${apiKey}`,
27
+ };
28
+ }
29
+ apiKeyFromEnv() {
30
+ const envVarValue = process.env[exports.API_V2_KEY_ENVVAR_NAME];
31
+ if (envVarValue) {
32
+ logger_1.logger.debug(`Set API key from environment: ${exports.API_V2_KEY_ENVVAR_NAME}`);
33
+ return envVarValue;
34
+ }
35
+ return "";
36
+ }
37
+ hostnameFromEnv() {
38
+ const envVarValue = process.env[exports.API_V2_HOST_ENVVAR_NAME];
39
+ if (envVarValue) {
40
+ logger_1.logger.debug(`Set the API hostname to ${envVarValue}`);
41
+ return envVarValue;
42
+ }
43
+ return DEFAULT_MINDEE_API_HOST;
44
+ }
45
+ }
46
+ exports.ApiSettingsV2 = ApiSettingsV2;
@@ -22,7 +22,7 @@ export declare abstract class BaseEndpoint {
22
22
  * @param inputDoc input document.
23
23
  * @param pageOptions page cutting options.
24
24
  */
25
- protected cutDocPages(inputDoc: InputSource, pageOptions: PageOptions): Promise<void>;
25
+ static cutDocPages(inputDoc: InputSource, pageOptions: PageOptions): Promise<void>;
26
26
  /**
27
27
  * Reads a response from the API and processes it.
28
28
  * @param options options related to the request itself.
@@ -30,5 +30,5 @@ export declare abstract class BaseEndpoint {
30
30
  * @param reject promise rejection reason.
31
31
  * @returns the processed request.
32
32
  */
33
- protected readResponse(options: RequestOptions, resolve: (value: EndpointResponse | PromiseLike<EndpointResponse>) => void, reject: (reason?: any) => void): ClientRequest;
33
+ static readResponse(options: RequestOptions, resolve: (value: EndpointResponse | PromiseLike<EndpointResponse>) => void, reject: (reason?: any) => void): ClientRequest;
34
34
  }
@@ -17,9 +17,9 @@ class BaseEndpoint {
17
17
  * @param inputDoc input document.
18
18
  * @param pageOptions page cutting options.
19
19
  */
20
- async cutDocPages(inputDoc, pageOptions) {
20
+ static async cutDocPages(inputDoc, pageOptions) {
21
21
  if (inputDoc instanceof input_1.LocalInputSource && inputDoc.isPdf()) {
22
- await inputDoc.cutPdf(pageOptions);
22
+ await inputDoc.applyPageOptions(pageOptions);
23
23
  }
24
24
  }
25
25
  /**
@@ -29,7 +29,7 @@ class BaseEndpoint {
29
29
  * @param reject promise rejection reason.
30
30
  * @returns the processed request.
31
31
  */
32
- readResponse(options, resolve, reject) {
32
+ static readResponse(options, resolve, reject) {
33
33
  logger_1.logger.debug(`${options.method}: https://${options.hostname}${options.path}`);
34
34
  const req = (0, https_1.request)(options, function (res) {
35
35
  // when the encoding is set, data chunks will be strings
@@ -0,0 +1,11 @@
1
+ export interface MindeeApiConstructorProps {
2
+ apiKey?: string;
3
+ }
4
+ export declare abstract class BaseSettings {
5
+ hostname: string;
6
+ timeout: number;
7
+ protected constructor();
8
+ protected getUserAgent(): string;
9
+ protected abstract apiKeyFromEnv(): string;
10
+ protected abstract hostnameFromEnv(): string;
11
+ }
@@ -0,0 +1,59 @@
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 () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.BaseSettings = void 0;
37
+ const package_json_1 = require("../../package.json");
38
+ const os = __importStar(require("os"));
39
+ const apiSettings_1 = require("./apiSettings");
40
+ class BaseSettings {
41
+ constructor() {
42
+ this.hostname = this.hostnameFromEnv();
43
+ this.timeout = process.env.MINDEE_REQUEST_TIMEOUT ? parseInt(process.env.MINDEE_REQUEST_TIMEOUT) : apiSettings_1.TIMEOUT_DEFAULT;
44
+ }
45
+ getUserAgent() {
46
+ let platform = os.type().toLowerCase();
47
+ if (platform.includes("darwin")) {
48
+ platform = "macos";
49
+ }
50
+ else if (platform.includes("window")) {
51
+ platform = "windows";
52
+ }
53
+ else if (platform.includes("bsd")) {
54
+ platform = "bsd";
55
+ }
56
+ return `mindee-api-nodejs@v${package_json_1.version} nodejs-${process.version} ${platform}`;
57
+ }
58
+ }
59
+ exports.BaseSettings = BaseSettings;
@@ -44,7 +44,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
44
44
  async predict(params) {
45
45
  await params.inputDoc.init();
46
46
  if (params.pageOptions !== undefined) {
47
- await super.cutDocPages(params.inputDoc, params.pageOptions);
47
+ await baseEndpoint_1.BaseEndpoint.cutDocPages(params.inputDoc, params.pageOptions);
48
48
  }
49
49
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictReqPost).call(this, params.inputDoc, params.includeWords, params.fullText, params.cropper);
50
50
  if (!(0, responseValidation_1.isValidSyncResponse)(response)) {
@@ -62,7 +62,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
62
62
  async predictAsync(params) {
63
63
  await params.inputDoc.init();
64
64
  if (params.pageOptions !== undefined) {
65
- await super.cutDocPages(params.inputDoc, params.pageOptions);
65
+ await baseEndpoint_1.BaseEndpoint.cutDocPages(params.inputDoc, params.pageOptions);
66
66
  }
67
67
  const response = await __classPrivateFieldGet(this, _Endpoint_instances, "m", _Endpoint_predictAsyncReqPost).call(this, params.inputDoc, params.includeWords, params.fullText, params.cropper, params.rag, params.workflowId);
68
68
  if (!(0, responseValidation_1.isValidAsyncResponse)(response)) {
@@ -181,7 +181,7 @@ class Endpoint extends baseEndpoint_1.BaseEndpoint {
181
181
  path: path,
182
182
  timeout: this.settings.timeout,
183
183
  };
184
- const req = this.readResponse(options, resolve, reject);
184
+ const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject);
185
185
  form.pipe(req);
186
186
  // potential ECONNRESET if we don't end the request.
187
187
  req.end();
@@ -211,7 +211,7 @@ input, includeWords = false, fullText = false, cropper = false, rag = false, wor
211
211
  hostname: this.settings.hostname,
212
212
  path: `${this.urlRoot}/documents/queue/${queueId}`,
213
213
  };
214
- const req = this.readResponse(options, resolve, reject);
214
+ const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject);
215
215
  // potential ECONNRESET if we don't end the request.
216
216
  req.end();
217
217
  });
@@ -223,7 +223,7 @@ input, includeWords = false, fullText = false, cropper = false, rag = false, wor
223
223
  hostname: this.settings.hostname,
224
224
  path: `${this.urlRoot}/documents/${documentId}`,
225
225
  };
226
- const req = this.readResponse(options, resolve, reject);
226
+ const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject);
227
227
  // potential ECONNRESET if we don't end the request.
228
228
  req.end();
229
229
  });
@@ -235,7 +235,7 @@ input, includeWords = false, fullText = false, cropper = false, rag = false, wor
235
235
  hostname: this.settings.hostname,
236
236
  path: `/v1/documents/${documentId}/feedback`,
237
237
  };
238
- const req = this.readResponse(options, resolve, reject);
238
+ const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject);
239
239
  req.write(JSON.stringify(feedback));
240
240
  // potential ECONNRESET if we don't end the request.
241
241
  req.end();
@@ -0,0 +1,34 @@
1
+ import { ApiSettingsV2 } from "./apiSettingsV2";
2
+ import { InferenceParameters } from "../clientV2";
3
+ import { InferenceResponse, JobResponse } from "../parsing/v2";
4
+ import { LocalInputSource } from "../input";
5
+ export declare class MindeeApiV2 {
6
+ #private;
7
+ settings: ApiSettingsV2;
8
+ constructor(apiKey?: string);
9
+ /**
10
+ * Sends a file to the inference queue.
11
+ * @param inputDoc Local file loaded as an input.
12
+ * @param params {InferenceParameters} parameters relating to the enqueueing options.
13
+ * @category V2
14
+ * @throws Error if the server's response contains one.
15
+ * @returns a `Promise` containing a job response.
16
+ */
17
+ reqPostInferenceEnqueue(inputDoc: LocalInputSource, params: InferenceParameters): Promise<JobResponse>;
18
+ /**
19
+ * Requests the job of a queued document from the API.
20
+ * Throws an error if the server's response contains one.
21
+ * @param inferenceId The document's ID in the queue.
22
+ * @category Asynchronous
23
+ * @returns a `Promise` containing either the parsed result, or information on the queue.
24
+ */
25
+ reqGetInference(inferenceId: string): Promise<InferenceResponse>;
26
+ /**
27
+ * Requests the results of a queued document from the API.
28
+ * Throws an error if the server's response contains one.
29
+ * @param jobId The document's ID in the queue.
30
+ * @category Asynchronous
31
+ * @returns a `Promise` containing either the parsed result, or information on the queue.
32
+ */
33
+ reqGetJob(jobId: string): Promise<JobResponse>;
34
+ }