mindee 4.28.0 → 4.29.0-rc1

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 (92) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +0 -21
  3. package/package.json +7 -7
  4. package/src/baseClient.d.ts +38 -0
  5. package/src/baseClient.js +69 -0
  6. package/src/cli.js +17 -7
  7. package/src/cliProducts.js +17 -7
  8. package/src/client.d.ts +3 -37
  9. package/src/client.js +11 -72
  10. package/src/clientV2.d.ts +156 -0
  11. package/src/clientV2.js +155 -0
  12. package/src/errors/mindeeError.d.ts +8 -0
  13. package/src/errors/mindeeError.js +17 -1
  14. package/src/http/apiSettings.d.ts +2 -8
  15. package/src/http/apiSettings.js +3 -41
  16. package/src/http/apiSettingsV2.d.ts +10 -0
  17. package/src/http/apiSettingsV2.js +46 -0
  18. package/src/http/baseEndpoint.d.ts +2 -2
  19. package/src/http/baseEndpoint.js +3 -3
  20. package/src/http/baseSettings.d.ts +11 -0
  21. package/src/http/baseSettings.js +59 -0
  22. package/src/http/endpoint.js +6 -6
  23. package/src/http/mindeeApiV2.d.ts +34 -0
  24. package/src/http/mindeeApiV2.js +120 -0
  25. package/src/http/workflowEndpoint.js +2 -2
  26. package/src/imageOperations/common/imageExtractor.d.ts +1 -1
  27. package/src/imageOperations/imageCompressor.d.ts +1 -1
  28. package/src/index.d.ts +1 -0
  29. package/src/index.js +20 -8
  30. package/src/input/localResponse.d.ts +13 -0
  31. package/src/input/localResponse.js +36 -7
  32. package/src/input/sources/localInputSource.d.ts +6 -0
  33. package/src/input/sources/localInputSource.js +26 -8
  34. package/src/internal.js +17 -7
  35. package/src/parsing/common/dateParser.d.ts +1 -0
  36. package/src/parsing/common/dateParser.js +12 -0
  37. package/src/parsing/common/execution.d.ts +0 -1
  38. package/src/parsing/common/execution.js +5 -9
  39. package/src/parsing/common/index.d.ts +1 -0
  40. package/src/parsing/common/index.js +20 -8
  41. package/src/parsing/index.d.ts +1 -0
  42. package/src/parsing/index.js +19 -8
  43. package/src/parsing/v2/commonResponse.d.ts +16 -0
  44. package/src/parsing/v2/commonResponse.js +19 -0
  45. package/src/parsing/v2/errorResponse.d.ts +15 -0
  46. package/src/parsing/v2/errorResponse.js +13 -0
  47. package/src/parsing/v2/field/baseField.d.ts +9 -0
  48. package/src/parsing/v2/field/baseField.js +18 -0
  49. package/src/parsing/v2/field/fieldConfidence.d.ts +9 -0
  50. package/src/parsing/v2/field/fieldConfidence.js +13 -0
  51. package/src/parsing/v2/field/fieldFactory.d.ts +8 -0
  52. package/src/parsing/v2/field/fieldFactory.js +22 -0
  53. package/src/parsing/v2/field/fieldLocation.d.ts +13 -0
  54. package/src/parsing/v2/field/fieldLocation.js +18 -0
  55. package/src/parsing/v2/field/index.d.ts +6 -0
  56. package/src/parsing/v2/field/index.js +15 -0
  57. package/src/parsing/v2/field/inferenceFields.d.ts +9 -0
  58. package/src/parsing/v2/field/inferenceFields.js +38 -0
  59. package/src/parsing/v2/field/listField.d.ts +12 -0
  60. package/src/parsing/v2/field/listField.js +36 -0
  61. package/src/parsing/v2/field/objectField.d.ts +9 -0
  62. package/src/parsing/v2/field/objectField.js +18 -0
  63. package/src/parsing/v2/field/simpleField.d.ts +7 -0
  64. package/src/parsing/v2/field/simpleField.js +17 -0
  65. package/src/parsing/v2/index.d.ts +12 -0
  66. package/src/parsing/v2/index.js +27 -0
  67. package/src/parsing/v2/inference.d.ts +24 -0
  68. package/src/parsing/v2/inference.js +26 -0
  69. package/src/parsing/v2/inferenceResponse.d.ts +10 -0
  70. package/src/parsing/v2/inferenceResponse.js +12 -0
  71. package/src/parsing/v2/inferenceResult.d.ts +15 -0
  72. package/src/parsing/v2/inferenceResult.js +25 -0
  73. package/src/parsing/v2/inferenceResultFile.d.ts +13 -0
  74. package/src/parsing/v2/inferenceResultFile.js +16 -0
  75. package/src/parsing/v2/inferenceResultModel.d.ts +8 -0
  76. package/src/parsing/v2/inferenceResultModel.js +9 -0
  77. package/src/parsing/v2/inferenceResultOptions.d.ts +9 -0
  78. package/src/parsing/v2/inferenceResultOptions.js +10 -0
  79. package/src/parsing/v2/job.d.ts +49 -0
  80. package/src/parsing/v2/job.js +29 -0
  81. package/src/parsing/v2/jobResponse.d.ts +10 -0
  82. package/src/parsing/v2/jobResponse.js +12 -0
  83. package/src/parsing/v2/jobResponseWebhook.d.ts +24 -0
  84. package/src/parsing/v2/jobResponseWebhook.js +19 -0
  85. package/src/parsing/v2/rawText.d.ts +15 -0
  86. package/src/parsing/v2/rawText.js +13 -0
  87. package/src/pdf/pdfCompressor.js +17 -7
  88. package/src/product/fr/internal.js +17 -7
  89. package/src/product/ind/internal.js +17 -7
  90. package/src/product/index.js +17 -7
  91. package/src/product/internal.js +17 -7
  92. package/src/product/us/internal.js +17 -7
@@ -0,0 +1,155 @@
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 handler_1 = require("./errors/handler");
11
+ const logger_1 = require("./logger");
12
+ const promises_1 = require("node:timers/promises");
13
+ const mindeeApiV2_1 = require("./http/mindeeApiV2");
14
+ const baseClient_1 = require("./baseClient");
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 extends baseClient_1.BaseClient {
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
+ super();
31
+ _ClientV2_instances.add(this);
32
+ this.mindeeApi = new mindeeApiV2_1.MindeeApiV2(apiKey);
33
+ handler_1.errorHandler.throwOnError = throwOnError ?? true;
34
+ logger_1.logger.level =
35
+ debug ?? process.env.MINDEE_DEBUG
36
+ ? logger_1.LOG_LEVELS["debug"]
37
+ : logger_1.LOG_LEVELS["warn"];
38
+ logger_1.logger.debug("ClientV2 initialized");
39
+ }
40
+ /**
41
+ * Send the document to an asynchronous endpoint and return its ID in the queue.
42
+ * @param inputSource file to parse.
43
+ * @param params parameters relating to prediction options.
44
+ * @category Asynchronous
45
+ * @returns a `Promise` containing the job (queue) corresponding to a document.
46
+ */
47
+ async enqueueInference(inputSource, params) {
48
+ if (inputSource === undefined) {
49
+ throw new Error("The 'enqueue' function requires an input document.");
50
+ }
51
+ return await this.mindeeApi.reqPostInferenceEnqueue(inputSource, params);
52
+ }
53
+ /**
54
+ * Retrieves an inference.
55
+ *
56
+ * @param inferenceId id of the queue to poll.
57
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
58
+ * @category Asynchronous
59
+ * @returns a `Promise` containing a `Job`, which also contains a `Document` if the
60
+ * parsing is complete.
61
+ */
62
+ async getInference(inferenceId) {
63
+ return await this.mindeeApi.reqGetInference(inferenceId);
64
+ }
65
+ /**
66
+ * Get the status of an inference that was previously enqueued.
67
+ * Can be used for polling.
68
+ *
69
+ * @param jobId id of the queue to poll.
70
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
71
+ * @category Asynchronous
72
+ * @returns a `Promise` containing a `Job`, which also contains a `Document` if the
73
+ * parsing is complete.
74
+ */
75
+ async getJob(jobId) {
76
+ return await this.mindeeApi.reqGetJob(jobId);
77
+ }
78
+ /**
79
+ * Send a document to an endpoint and poll the server until the result is sent or
80
+ * until the maximum number of tries is reached.
81
+ *
82
+ * @param inputDoc document to parse.
83
+ * @param params parameters relating to prediction options.
84
+ *
85
+ * @typeParam T an extension of an `Inference`. Can be omitted as it will be inferred from the `productClass`.
86
+ * @category Synchronous
87
+ * @returns a `Promise` containing parsing results.
88
+ */
89
+ async enqueueAndGetInference(inputDoc, params) {
90
+ const validatedAsyncParams = __classPrivateFieldGet(this, _ClientV2_instances, "m", _ClientV2_setAsyncParams).call(this, params.pollingOptions);
91
+ const enqueueResponse = await this.enqueueInference(inputDoc, params);
92
+ if (enqueueResponse.job.id === undefined || enqueueResponse.job.id.length === 0) {
93
+ logger_1.logger.error(`Failed enqueueing:\n${enqueueResponse.getRawHttp()}`);
94
+ throw Error("Enqueueing of the document failed.");
95
+ }
96
+ const queueId = enqueueResponse.job.id;
97
+ logger_1.logger.debug(`Successfully enqueued document with job id: ${queueId}.`);
98
+ await (0, promises_1.setTimeout)(validatedAsyncParams.initialDelaySec * 1000, undefined, validatedAsyncParams.initialTimerOptions);
99
+ let retryCounter = 1;
100
+ let pollResults = await this.getJob(queueId);
101
+ while (retryCounter < validatedAsyncParams.maxRetries) {
102
+ if (pollResults.job.status === "Failed") {
103
+ break;
104
+ }
105
+ if (pollResults.job.status === "Processed") {
106
+ return this.getInference(pollResults.job.id);
107
+ }
108
+ logger_1.logger.debug(`Polling server for parsing result with queueId: ${queueId}.
109
+ Attempt n°${retryCounter}/${validatedAsyncParams.maxRetries}.
110
+ Job status: ${pollResults.job.status}.`);
111
+ await (0, promises_1.setTimeout)(validatedAsyncParams.delaySec * 1000, undefined, validatedAsyncParams.recurringTimerOptions);
112
+ pollResults = await this.getJob(queueId);
113
+ retryCounter++;
114
+ }
115
+ const error = pollResults.job.error;
116
+ if (error) {
117
+ throw new mindeeError_1.MindeeHttpErrorV2(error.status, error.detail);
118
+ }
119
+ throw Error("Asynchronous parsing request timed out after " +
120
+ validatedAsyncParams.delaySec * retryCounter +
121
+ " seconds");
122
+ }
123
+ }
124
+ exports.ClientV2 = ClientV2;
125
+ _ClientV2_instances = new WeakSet(), _ClientV2_setAsyncParams = function _ClientV2_setAsyncParams(asyncParams = undefined) {
126
+ const minDelaySec = 1;
127
+ const minInitialDelay = 1;
128
+ const minRetries = 2;
129
+ let newAsyncParams;
130
+ if (asyncParams === undefined) {
131
+ newAsyncParams = {
132
+ delaySec: 1.5,
133
+ initialDelaySec: 2,
134
+ maxRetries: 80
135
+ };
136
+ }
137
+ else {
138
+ newAsyncParams = { ...asyncParams };
139
+ if (!newAsyncParams.delaySec ||
140
+ !newAsyncParams.initialDelaySec ||
141
+ !newAsyncParams.maxRetries) {
142
+ throw Error("Invalid polling options.");
143
+ }
144
+ if (newAsyncParams.delaySec < minDelaySec) {
145
+ throw Error(`Cannot set auto-parsing delay to less than ${minDelaySec} second(s).`);
146
+ }
147
+ if (newAsyncParams.initialDelaySec < minInitialDelay) {
148
+ throw Error(`Cannot set initial parsing delay to less than ${minInitialDelay} second(s).`);
149
+ }
150
+ if (newAsyncParams.maxRetries < minRetries) {
151
+ throw Error(`Cannot set retry to less than ${minRetries}.`);
152
+ }
153
+ }
154
+ return newAsyncParams;
155
+ };
@@ -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
+ }
@@ -0,0 +1,120 @@
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 _MindeeApiV2_instances, _MindeeApiV2_processResponse, _MindeeApiV2_documentEnqueuePost, _MindeeApiV2_inferenceResultReqGet;
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.MindeeApiV2 = void 0;
13
+ const apiSettingsV2_1 = require("./apiSettingsV2");
14
+ const v2_1 = require("../parsing/v2");
15
+ const form_data_1 = __importDefault(require("form-data"));
16
+ const baseEndpoint_1 = require("./baseEndpoint");
17
+ const mindeeError_1 = require("../errors/mindeeError");
18
+ const logger_1 = require("../logger");
19
+ class MindeeApiV2 {
20
+ constructor(apiKey) {
21
+ _MindeeApiV2_instances.add(this);
22
+ this.settings = new apiSettingsV2_1.ApiSettingsV2({ apiKey: apiKey });
23
+ }
24
+ /**
25
+ * Sends a file to the inference queue.
26
+ * @param inputDoc Local file loaded as an input.
27
+ * @param params {InferenceParameters} parameters relating to the enqueueing options.
28
+ * @category V2
29
+ * @throws Error if the server's response contains one.
30
+ * @returns a `Promise` containing a job response.
31
+ */
32
+ async reqPostInferenceEnqueue(inputDoc, params) {
33
+ await inputDoc.init();
34
+ if (params.modelId === undefined || params.modelId === null || params.modelId === "") {
35
+ throw new Error("Model ID must be provided");
36
+ }
37
+ const result = await __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_documentEnqueuePost).call(this, inputDoc, params);
38
+ if (result.data.error?.code !== undefined) {
39
+ throw new mindeeError_1.MindeeHttpErrorV2(result.data.error.code, result.data.error.message ?? "Unknown error.");
40
+ }
41
+ return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, result, v2_1.JobResponse);
42
+ }
43
+ /**
44
+ * Requests the job of a queued document from the API.
45
+ * Throws an error if the server's response contains one.
46
+ * @param inferenceId The document's ID in the queue.
47
+ * @category Asynchronous
48
+ * @returns a `Promise` containing either the parsed result, or information on the queue.
49
+ */
50
+ async reqGetInference(inferenceId) {
51
+ const queueResponse = await __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_inferenceResultReqGet).call(this, inferenceId, "inferences");
52
+ return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, queueResponse, v2_1.InferenceResponse);
53
+ }
54
+ /**
55
+ * Requests the results of a queued document from the API.
56
+ * Throws an error if the server's response contains one.
57
+ * @param jobId The document's ID in the queue.
58
+ * @category Asynchronous
59
+ * @returns a `Promise` containing either the parsed result, or information on the queue.
60
+ */
61
+ async reqGetJob(jobId) {
62
+ const queueResponse = await __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_inferenceResultReqGet).call(this, jobId, "jobs");
63
+ return __classPrivateFieldGet(this, _MindeeApiV2_instances, "m", _MindeeApiV2_processResponse).call(this, queueResponse, v2_1.JobResponse);
64
+ }
65
+ }
66
+ exports.MindeeApiV2 = MindeeApiV2;
67
+ _MindeeApiV2_instances = new WeakSet(), _MindeeApiV2_processResponse = function _MindeeApiV2_processResponse(result, responseType) {
68
+ if (result.messageObj?.statusCode && (result.messageObj?.statusCode > 399 || result.messageObj?.statusCode < 200)) {
69
+ if (result.data?.status !== null) {
70
+ throw new mindeeError_1.MindeeHttpErrorV2(result.data?.status, result.data?.detail ?? "Unknown error.");
71
+ }
72
+ throw new mindeeError_1.MindeeHttpErrorV2(result.messageObj?.statusCode ?? -1, result.data?.statusMessage ?? "Unknown error.");
73
+ }
74
+ try {
75
+ return new responseType(result.data);
76
+ }
77
+ catch (e) {
78
+ logger_1.logger.error(`Raised '${e}' Couldn't deserialize response object:\n${JSON.stringify(result.data)}`);
79
+ throw new mindeeError_1.MindeeApiV2Error("Couldn't deserialize response object.");
80
+ }
81
+ }, _MindeeApiV2_documentEnqueuePost = function _MindeeApiV2_documentEnqueuePost(inputDoc, params) {
82
+ const form = new form_data_1.default();
83
+ form.append("model_id", params.modelId);
84
+ if (params.rag) {
85
+ form.append("rag", "true");
86
+ }
87
+ if (params.webhookIds && params.webhookIds.length > 0) {
88
+ form.append("webhook_ids", params.webhookIds.join(","));
89
+ }
90
+ form.append("file", inputDoc.fileObject, {
91
+ filename: inputDoc.filename,
92
+ });
93
+ const path = "/v2/inferences/enqueue";
94
+ const headers = { ...this.settings.baseHeaders, ...form.getHeaders() };
95
+ const options = {
96
+ method: "POST",
97
+ headers: headers,
98
+ hostname: this.settings.hostname,
99
+ path: path,
100
+ timeout: this.settings.timeout,
101
+ };
102
+ return new Promise((resolve, reject) => {
103
+ const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject);
104
+ form.pipe(req);
105
+ // potential ECONNRESET if we don't end the request.
106
+ req.end();
107
+ });
108
+ }, _MindeeApiV2_inferenceResultReqGet = function _MindeeApiV2_inferenceResultReqGet(queueId, slug) {
109
+ return new Promise((resolve, reject) => {
110
+ const options = {
111
+ method: "GET",
112
+ headers: this.settings.baseHeaders,
113
+ hostname: this.settings.hostname,
114
+ path: `/v2/${slug}/${queueId}`,
115
+ };
116
+ const req = baseEndpoint_1.BaseEndpoint.readResponse(options, resolve, reject);
117
+ // potential ECONNRESET if we don't end the request.
118
+ req.end();
119
+ });
120
+ };