chromiumly 3.3.0 → 3.3.2

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 (49) hide show
  1. package/README.md +1 -0
  2. package/dist/chromium/converters/html.converter.js +1 -1
  3. package/dist/pdf-engines/utils/pdf-engines.utils.js +5 -5
  4. package/dist/pdf-engines/utils/pdf-engines.utils.js.map +1 -1
  5. package/package.json +13 -10
  6. package/src/.prettierrc.yml +0 -4
  7. package/src/chromium/converters/converter.ts +0 -22
  8. package/src/chromium/converters/html.converter.ts +0 -134
  9. package/src/chromium/converters/markdown.converter.ts +0 -129
  10. package/src/chromium/converters/tests/html.converter.test.ts +0 -190
  11. package/src/chromium/converters/tests/markdown.converter.test.ts +0 -187
  12. package/src/chromium/converters/tests/url.converter.test.ts +0 -164
  13. package/src/chromium/converters/url.converter.ts +0 -125
  14. package/src/chromium/index.ts +0 -6
  15. package/src/chromium/interfaces/common.types.ts +0 -15
  16. package/src/chromium/interfaces/converter.types.ts +0 -45
  17. package/src/chromium/interfaces/screenshot.types.ts +0 -15
  18. package/src/chromium/screenshots/html.screenshot.ts +0 -105
  19. package/src/chromium/screenshots/markdown.screenshot.ts +0 -100
  20. package/src/chromium/screenshots/screenshot.ts +0 -22
  21. package/src/chromium/screenshots/tests/html.screenshot.test.ts +0 -192
  22. package/src/chromium/screenshots/tests/markdown.screenshot.test.ts +0 -176
  23. package/src/chromium/screenshots/tests/url.screenshot.test.ts +0 -166
  24. package/src/chromium/screenshots/url.screenshot.ts +0 -96
  25. package/src/chromium/utils/converter.utils.ts +0 -187
  26. package/src/chromium/utils/screenshot.utils.ts +0 -127
  27. package/src/chromium/utils/tests/converter.utils.test.ts +0 -496
  28. package/src/chromium/utils/tests/screenshot.utils.test.ts +0 -338
  29. package/src/common/constants.ts +0 -9
  30. package/src/common/gotenberg.utils.ts +0 -86
  31. package/src/common/index.ts +0 -3
  32. package/src/common/tests/gotenberg.utils.test.ts +0 -141
  33. package/src/common/types.ts +0 -7
  34. package/src/gotenberg.ts +0 -54
  35. package/src/libre-office/index.ts +0 -1
  36. package/src/libre-office/interfaces/libre-office.types.ts +0 -156
  37. package/src/libre-office/libre-office.ts +0 -61
  38. package/src/libre-office/tests/libre-office.test.ts +0 -56
  39. package/src/libre-office/utils/constants.ts +0 -132
  40. package/src/libre-office/utils/libre-office.utils.ts +0 -128
  41. package/src/libre-office/utils/tests/libre-office.utils.test.ts +0 -156
  42. package/src/main.config.ts +0 -157
  43. package/src/main.ts +0 -13
  44. package/src/pdf-engines/index.ts +0 -1
  45. package/src/pdf-engines/interfaces/pdf-engines.types.ts +0 -10
  46. package/src/pdf-engines/pdf-engines.ts +0 -156
  47. package/src/pdf-engines/tests/pdf.engine.test.ts +0 -163
  48. package/src/pdf-engines/utils/pdf-engines.utils.ts +0 -68
  49. package/src/pdf-engines/utils/tests/pdf-engines.utils.test.ts +0 -71
@@ -1,157 +0,0 @@
1
- import { Gotenberg } from './gotenberg';
2
-
3
- /**
4
- * Enum representing the available Chromium routes for conversion.
5
- * @enum {string}
6
- */
7
- export enum ChromiumRoute {
8
- URL = 'url',
9
- HTML = 'html',
10
- MARKDOWN = 'markdown'
11
- }
12
-
13
- /**
14
- * Enum representing the available routes for the PDF engine.
15
- * @enum {string}
16
- */
17
- enum PdfEngineRoute {
18
- MERGE = 'merge',
19
- READ_METADATA = 'metadata/read',
20
- WRITE_METADATA = 'metadata/write'
21
- }
22
-
23
- /**
24
- * Enum representing the available routes for LibreOffice.
25
- * @enum {string}
26
- */
27
- enum LibreOfficeRoute {
28
- CONVERT = 'convert'
29
- }
30
-
31
- /**
32
- * Class providing constants and routes for interacting with the Gotenberg service and related engines.
33
- */
34
- export class Chromiumly {
35
- /**
36
- * The Gotenberg service endpoint.
37
- * @type {string}
38
- */
39
- private static gotenbergEndpoint: string | undefined = Gotenberg.endpoint;
40
-
41
- /**
42
- * The username for basic authentication with the Gotenberg service.
43
- * @type {string | undefined}
44
- */
45
- private static gotenbergApiBasicAuthUsername: string | undefined =
46
- Gotenberg.username;
47
-
48
- /**
49
- * The password for basic authentication with the Gotenberg service.
50
- * @type {string | undefined}
51
- */
52
- private static gotenbergApiBasicAuthPassword: string | undefined =
53
- Gotenberg.password;
54
-
55
- /**
56
- * The path for Chromium-related conversions.
57
- * @type {string}
58
- */
59
- public static readonly CHROMIUM_CONVERT_PATH = 'forms/chromium/convert';
60
-
61
- /**
62
- * The path for Chromium-related screenshots.
63
- * @type {string}
64
- */
65
- public static readonly CHROMIUM_SCREENSHOT_PATH =
66
- 'forms/chromium/screenshot';
67
-
68
- /**
69
- * The path for PDF engine-related operations.
70
- * @type {string}
71
- */
72
- public static readonly PDF_ENGINES_PATH = 'forms/pdfengines';
73
-
74
- /**
75
- * The path for LibreOffice-related conversions.
76
- * @type {string}
77
- */
78
- public static readonly LIBRE_OFFICE_PATH = 'forms/libreoffice';
79
-
80
- /**
81
- * Routes for Chromium conversions.
82
- * @type {Object}
83
- */
84
- public static readonly CHROMIUM_ROUTES = {
85
- url: ChromiumRoute.URL,
86
- html: ChromiumRoute.HTML,
87
- markdown: ChromiumRoute.MARKDOWN
88
- };
89
-
90
- /**
91
- * Routes for PDF engine operations.
92
- * @type {Object}
93
- */
94
- public static readonly PDF_ENGINE_ROUTES = {
95
- merge: PdfEngineRoute.MERGE,
96
- readMetadata: PdfEngineRoute.READ_METADATA,
97
- writeMetadata: PdfEngineRoute.WRITE_METADATA
98
- };
99
-
100
- /**
101
- * Routes for LibreOffice conversions.
102
- * @type {Object}
103
- */
104
- public static readonly LIBRE_OFFICE_ROUTES = {
105
- convert: LibreOfficeRoute.CONVERT
106
- };
107
-
108
- /**
109
- * Configures the Gotenberg service endpoint and other optional parameters.
110
- * @param {Object} config - Configuration object.
111
- * @param {string} config.endpoint - The Gotenberg service endpoint.
112
- * @param {string} [config.username] - The username for basic authentication.
113
- * @param {string} [config.password] - The password for basic authentication.
114
- */
115
- public static configure(config: {
116
- endpoint: string;
117
- username?: string;
118
- password?: string;
119
- }): void {
120
- this.gotenbergEndpoint = config.endpoint;
121
-
122
- if (config.username !== undefined) {
123
- this.gotenbergApiBasicAuthUsername = config.username;
124
- }
125
- if (config.password !== undefined) {
126
- this.gotenbergApiBasicAuthPassword = config.password;
127
- }
128
- }
129
-
130
- /**
131
- * Gets the Gotenberg service endpoint.
132
- * @returns {string}
133
- */
134
- public static getGotenbergEndpoint(): string {
135
- if (!this.gotenbergEndpoint)
136
- throw new Error(
137
- 'Gotenberg endpoint is not set. Please ensure that the Gotenberg service endpoint is configured correctly in your environment variables or through the configure method.'
138
- );
139
- return this.gotenbergEndpoint;
140
- }
141
-
142
- /**
143
- * Gets the username for basic authentication.
144
- * @returns {string | undefined}
145
- */
146
- public static getGotenbergApiBasicAuthUsername(): string | undefined {
147
- return this.gotenbergApiBasicAuthUsername;
148
- }
149
-
150
- /**
151
- * Gets the password for basic authentication.
152
- * @returns {string | undefined}
153
- */
154
- public static getGotenbergApiBasicAuthPassword(): string | undefined {
155
- return this.gotenbergApiBasicAuthPassword;
156
- }
157
- }
package/src/main.ts DELETED
@@ -1,13 +0,0 @@
1
- export { Chromiumly } from './main.config';
2
-
3
- export { PdfFormat } from './common/constants';
4
- export {
5
- HtmlConverter,
6
- HtmlScreenshot,
7
- MarkdownConverter,
8
- MarkdownScreenshot,
9
- UrlConverter,
10
- UrlScreenshot
11
- } from './chromium';
12
- export { PDFEngines } from './pdf-engines';
13
- export { LibreOffice } from './libre-office';
@@ -1 +0,0 @@
1
- export { PDFEngines } from './pdf-engines';
@@ -1,10 +0,0 @@
1
- import { Metadata, PdfFormat } from '../../common';
2
-
3
- export type ConversionOptions = {
4
- pdfa?: PdfFormat;
5
- pdfUA?: boolean;
6
- };
7
-
8
- export type MergeOptions = ConversionOptions & {
9
- metadata?: Metadata;
10
- };
@@ -1,156 +0,0 @@
1
- import { promises } from 'fs';
2
- import path from 'path';
3
-
4
- import FormData from 'form-data';
5
-
6
- import { Chromiumly } from '../main.config';
7
- import {
8
- GotenbergUtils,
9
- PathLikeOrReadStream,
10
- PdfFormat,
11
- Metadata
12
- } from '../common';
13
- import { PDFEnginesUtils } from './utils/pdf-engines.utils';
14
-
15
- /**
16
- * Class uses PDF engines for various operations such as merging and conversion.
17
- */
18
- export class PDFEngines {
19
- /**
20
- * Merges multiple PDF files into a single PDF document.
21
- *
22
- * @param {Object} options - Options for the merge operation.
23
- * @param {PathLikeOrReadStream[]} options.files - An array of PathLikes or ReadStreams to the PDF files to be merged.
24
- * @returns {Promise<Buffer>} A Promise resolving to the merged PDF content as a Buffer.
25
- */
26
- public static async merge({
27
- files,
28
- pdfa,
29
- pdfUA,
30
- metadata
31
- }: {
32
- files: PathLikeOrReadStream[];
33
- pdfa?: PdfFormat;
34
- pdfUA?: boolean;
35
- metadata?: Metadata;
36
- }): Promise<Buffer> {
37
- const data = new FormData();
38
- await PDFEnginesUtils.addFiles(files, data);
39
- await PDFEnginesUtils.customize(data, {
40
- pdfa,
41
- pdfUA,
42
- metadata
43
- });
44
- const endpoint = `${Chromiumly.getGotenbergEndpoint()}/${Chromiumly.PDF_ENGINES_PATH}/${Chromiumly.PDF_ENGINE_ROUTES.merge}`;
45
- return GotenbergUtils.fetch(
46
- endpoint,
47
- data,
48
- Chromiumly.getGotenbergApiBasicAuthUsername(),
49
- Chromiumly.getGotenbergApiBasicAuthPassword()
50
- );
51
- }
52
-
53
- /**
54
- * Converts various document formats to PDF.
55
- *
56
- * @param {Object} options - Options for the conversion operation.
57
- * @param {PathLikeOrReadStream[]} options.files - An array of PathLikes or ReadStreams to the files to be converted to PDF.
58
- * @param {pdfa} [options.pdfa] - PDF format options.
59
- * @param {boolean} [options.pdfUA] - Indicates whether to generate PDF/UA compliant output.
60
- * @returns {Promise<Buffer>} A Promise resolving to the converted PDF content as a Buffer.
61
- */
62
- public static async convert({
63
- files,
64
- pdfa,
65
- pdfUA
66
- }: {
67
- files: PathLikeOrReadStream[];
68
- pdfa?: PdfFormat;
69
- pdfUA?: boolean;
70
- }): Promise<Buffer> {
71
- const data = new FormData();
72
-
73
- await PDFEnginesUtils.addFiles(files, data);
74
- await PDFEnginesUtils.customize(data, {
75
- pdfa,
76
- pdfUA
77
- });
78
-
79
- const endpoint = `${Chromiumly.getGotenbergEndpoint()}/${Chromiumly.LIBRE_OFFICE_PATH}/${Chromiumly.LIBRE_OFFICE_ROUTES.convert}`;
80
-
81
- return GotenbergUtils.fetch(
82
- endpoint,
83
- data,
84
- Chromiumly.getGotenbergApiBasicAuthUsername(),
85
- Chromiumly.getGotenbergApiBasicAuthPassword()
86
- );
87
- }
88
-
89
- /**
90
- * Reads metadata from the provided files.
91
- *
92
- * @param {PathLikeOrReadStream[]} files An array of PathLikes or ReadStreams to the PDF files.
93
- * @returns {Promise<Buffer>} A Promise resolving to the metadata buffer.
94
- */
95
- public static async readMetadata(
96
- files: PathLikeOrReadStream[]
97
- ): Promise<Buffer> {
98
- const data = new FormData();
99
-
100
- await PDFEnginesUtils.addFiles(files, data);
101
-
102
- const endpoint = `${Chromiumly.getGotenbergEndpoint()}/${Chromiumly.PDF_ENGINES_PATH}/${Chromiumly.PDF_ENGINE_ROUTES.readMetadata}`;
103
-
104
- return GotenbergUtils.fetch(
105
- endpoint,
106
- data,
107
- Chromiumly.getGotenbergApiBasicAuthUsername(),
108
- Chromiumly.getGotenbergApiBasicAuthPassword()
109
- );
110
- }
111
-
112
- /**
113
- * Writes metadata to the provided PDF files.
114
- *
115
- * @param {PathLikeOrReadStream[]} files - An array of PathLikes or ReadStreams to the PDF files.
116
- * @param {Metadata} metadata - Metadata to be written.
117
- * @returns {Promise<Buffer>} A Promise that resolves to the PDF file containing metadata as a buffer.
118
- */
119
- public static async writeMetadata({
120
- files,
121
- metadata
122
- }: {
123
- files: PathLikeOrReadStream[];
124
- metadata: Metadata;
125
- }): Promise<Buffer> {
126
- const data = new FormData();
127
- data.append('metadata', JSON.stringify(metadata));
128
-
129
- await PDFEnginesUtils.addFiles(files, data);
130
-
131
- const endpoint = `${Chromiumly.getGotenbergEndpoint()}/${Chromiumly.PDF_ENGINES_PATH}/${Chromiumly.PDF_ENGINE_ROUTES.writeMetadata}`;
132
-
133
- return GotenbergUtils.fetch(
134
- endpoint,
135
- data,
136
- Chromiumly.getGotenbergApiBasicAuthUsername(),
137
- Chromiumly.getGotenbergApiBasicAuthPassword()
138
- );
139
- }
140
-
141
- /**
142
- * Generates a PDF file from a buffer and saves it to the "__generated__" directory.
143
- *
144
- * @param {string} filename - The filename for the generated PDF.
145
- * @param {Buffer} buffer - The PDF content as a Buffer.
146
- * @returns {Promise<void>} A Promise that resolves once the file is generated and saved.
147
- */
148
- public static async generate(
149
- filename: string,
150
- buffer: Buffer
151
- ): Promise<void> {
152
- const __generated__ = path.resolve(process.cwd(), '__generated__');
153
- await promises.mkdir(path.resolve(__generated__), { recursive: true });
154
- await promises.writeFile(path.resolve(__generated__, filename), buffer);
155
- }
156
- }
@@ -1,163 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2
- import { createReadStream, promises } from 'fs';
3
- import FormData from 'form-data';
4
- import fs from 'fs/promises';
5
- import fetch from 'node-fetch';
6
- import path from 'path';
7
-
8
- import { PdfFormat } from '../../common';
9
- import { PDFEngines } from '../pdf-engines';
10
-
11
- const { Response } = jest.requireActual('node-fetch');
12
- jest.mock('node-fetch', () => jest.fn());
13
-
14
- describe('PDFEngines', () => {
15
- const mockPromisesAccess = jest.spyOn(promises, 'access');
16
- const mockFetch = fetch as jest.MockedFunction<typeof fetch>;
17
- const mockFormDataAppend = jest.spyOn(FormData.prototype, 'append');
18
-
19
- beforeEach(() => {
20
- (createReadStream as jest.Mock) = jest
21
- .fn()
22
- .mockImplementation((file) => file);
23
- });
24
-
25
- afterEach(() => {
26
- jest.resetAllMocks();
27
- });
28
-
29
- describe('convert', () => {
30
- describe('when no properties are passed', () => {
31
- it('should return a buffer', async () => {
32
- mockPromisesAccess.mockResolvedValue();
33
- mockFetch.mockResolvedValue(new Response('content'));
34
- const buffer = await PDFEngines.convert({
35
- files: ['path/to/file_1.pdf', 'path/to/file_2.pdf']
36
- });
37
- expect(buffer).toEqual(Buffer.from('content'));
38
- expect(mockFormDataAppend).toHaveBeenCalledTimes(2);
39
- });
40
- });
41
-
42
- describe('when properties are passed', () => {
43
- it('should return a buffer', async () => {
44
- mockPromisesAccess.mockResolvedValue();
45
- mockFetch.mockResolvedValue(new Response('content'));
46
- const buffer = await PDFEngines.convert({
47
- files: ['path/to/file_1.pdf', 'path/to/file_2.pdf'],
48
- pdfa: PdfFormat.A_2b,
49
- pdfUA: true
50
- });
51
- expect(buffer).toEqual(Buffer.from('content'));
52
- expect(mockFormDataAppend).toHaveBeenCalledTimes(4);
53
- });
54
- });
55
- });
56
-
57
- describe('merge', () => {
58
- it('should return a buffer', async () => {
59
- mockPromisesAccess.mockResolvedValue();
60
- mockFetch.mockResolvedValue(new Response('content'));
61
- const buffer = await PDFEngines.merge({
62
- files: ['path/to/file.pdf', 'path/to/another-file.pdf'],
63
- pdfa: PdfFormat.A_2b,
64
- pdfUA: true,
65
- metadata: { Author: 'John Doe' }
66
- });
67
- expect(buffer).toEqual(Buffer.from('content'));
68
- expect(mockFormDataAppend).toHaveBeenCalledTimes(5);
69
- });
70
- });
71
-
72
- describe('readMetadata', () => {
73
- it('should return a buffer', async () => {
74
- mockPromisesAccess.mockResolvedValue();
75
- mockFetch.mockResolvedValue(new Response('content'));
76
- const buffer = await PDFEngines.readMetadata(['path/to/file.pdf']);
77
- expect(buffer).toEqual(Buffer.from('content'));
78
- expect(mockFormDataAppend).toHaveBeenCalledTimes(1);
79
- });
80
- });
81
-
82
- describe('writeMetadata', () => {
83
- it('should return a buffer', async () => {
84
- mockPromisesAccess.mockResolvedValue();
85
- mockFetch.mockResolvedValue(new Response('content'));
86
- const buffer = await PDFEngines.writeMetadata({
87
- files: ['path/to/file.pdf'],
88
- metadata: {
89
- Author: 'John Doe',
90
- Copyright: 'John Doe',
91
- CreationDate: Date.now(),
92
- Creator: 'Chromiumly',
93
- Keywords: ['first', 'second'],
94
- Marked: true,
95
- ModDate: Date.now(),
96
- PDFVersion: 1.7,
97
- Producer: 'Chromiumly',
98
- Subject: 'Sample',
99
- Title: 'Sample',
100
- Trapped: 'Unknown'
101
- }
102
- });
103
- expect(buffer).toEqual(Buffer.from('content'));
104
- expect(mockFormDataAppend).toHaveBeenCalledTimes(2);
105
- });
106
- });
107
-
108
- describe('generate', () => {
109
- const mockFilename = 'test.pdf';
110
- const mockBuffer = Buffer.from('mock pdf content');
111
-
112
- afterAll(() => {
113
- jest.restoreAllMocks();
114
- });
115
-
116
- it('should generate a PDF file', async () => {
117
- const mockGeneratedDir = path.join(process.cwd(), '__generated__');
118
- const mockGeneratedFilePath = path.join(
119
- mockGeneratedDir,
120
- mockFilename
121
- );
122
-
123
- const mockPromisesMkDir = jest
124
- .spyOn(fs, 'mkdir')
125
- .mockResolvedValueOnce(mockGeneratedDir);
126
-
127
- const mockPromisesWriteFile = jest
128
- .spyOn(fs, 'writeFile')
129
- .mockResolvedValueOnce();
130
-
131
- await PDFEngines.generate(mockFilename, mockBuffer);
132
-
133
- expect(mockPromisesMkDir).toHaveBeenCalledWith(mockGeneratedDir, {
134
- recursive: true
135
- });
136
-
137
- expect(mockPromisesWriteFile).toHaveBeenCalledWith(
138
- mockGeneratedFilePath,
139
- mockBuffer
140
- );
141
- });
142
-
143
- it('should handle errors during file generation', async () => {
144
- jest.spyOn(fs, 'mkdir').mockRejectedValueOnce(
145
- new Error('Cannot create directory')
146
- );
147
-
148
- await expect(
149
- PDFEngines.generate(mockFilename, mockBuffer)
150
- ).rejects.toThrow('Cannot create directory');
151
- });
152
-
153
- it('should handle errors during file writing', async () => {
154
- jest.spyOn(fs, 'writeFile').mockRejectedValueOnce(
155
- new Error('Failed to write to file')
156
- );
157
-
158
- await expect(
159
- PDFEngines.generate(mockFilename, mockBuffer)
160
- ).rejects.toThrow('Failed to write to file');
161
- });
162
- });
163
- });
@@ -1,68 +0,0 @@
1
- import { constants, createReadStream, promises, ReadStream } from 'fs';
2
- import path from 'path';
3
-
4
- import FormData from 'form-data';
5
- import { PathLikeOrReadStream } from '../../common';
6
- import {
7
- ConversionOptions,
8
- MergeOptions
9
- } from '../interfaces/pdf-engines.types';
10
-
11
- /**
12
- * Utility class for handling common tasks related to PDF engine operations.
13
- */
14
- export class PDFEnginesUtils {
15
- /**
16
- * Adds PDF files to the FormData object.
17
- *
18
- * @param {PathLikeOrReadStream[]} files - An array of PDF files to be added to the FormData.
19
- * @param {FormData} data - The FormData object to which PDF files will be added.
20
- * @throws {Error} Throws an error if the file extension is not supported.
21
- */
22
- public static async addFiles(
23
- files: PathLikeOrReadStream[],
24
- data: FormData
25
- ) {
26
- for (const [key, file] of files.entries()) {
27
- const filename = `file${key}.pdf`;
28
- if (Buffer.isBuffer(file)) {
29
- data.append('files', file, filename);
30
- } else if (file instanceof ReadStream) {
31
- data.append('files', file, filename);
32
- } else {
33
- await promises.access(file, constants.R_OK);
34
- const filename = path.basename(file.toString());
35
- const extension = path.extname(filename);
36
- if (extension === '.pdf') {
37
- data.append(filename, createReadStream(file));
38
- } else {
39
- throw new Error(`${extension} is not supported`);
40
- }
41
- }
42
- }
43
- }
44
-
45
- /**
46
- * Customizes the FormData object based on the provided conversion options.
47
- *
48
- * @param {FormData} data - The FormData object to be customized.
49
- * @param {ConversionOptions | MergeOptions} options - The options to apply to the FormData.
50
- * @returns {Promise<void>} A Promise that resolves once the customization is complete.
51
- */
52
- public static async customize(
53
- data: FormData,
54
- options: ConversionOptions | MergeOptions
55
- ): Promise<void> {
56
- if (options.pdfa) {
57
- data.append('pdfa', options.pdfa);
58
- }
59
-
60
- if (options.pdfUA) {
61
- data.append('pdfUA', String(options.pdfUA));
62
- }
63
-
64
- if ('metadata' in options && options.metadata) {
65
- data.append('metadata', JSON.stringify(options.metadata));
66
- }
67
- }
68
- }
@@ -1,71 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2
- import { createReadStream, promises } from 'fs';
3
- import FormData from 'form-data';
4
- import { PDFEnginesUtils } from '../pdf-engines.utils';
5
-
6
- describe('PDFEnginesUtils', () => {
7
- const mockPromisesAccess = jest.spyOn(promises, 'access');
8
- const mockFormDataAppend = jest.spyOn(FormData.prototype, 'append');
9
- const data = new FormData();
10
-
11
- beforeEach(() => {
12
- (createReadStream as jest.Mock) = jest
13
- .fn()
14
- .mockImplementation((file) => file);
15
- });
16
-
17
- afterEach(() => {
18
- jest.resetAllMocks();
19
- });
20
-
21
- describe('addFiles', () => {
22
- describe('when files exist', () => {
23
- describe('when files parameter contains paths', () => {
24
- it('should append each file to data', async () => {
25
- mockPromisesAccess.mockResolvedValue();
26
- await PDFEnginesUtils.addFiles(
27
- ['path/to/file.pdf', 'path/to/another-file.pdf'],
28
- data
29
- );
30
- expect(mockFormDataAppend).toHaveBeenCalledTimes(2);
31
- });
32
- });
33
- describe('when files parameter contains a buffer', () => {
34
- it('should append each file to data', async () => {
35
- mockPromisesAccess.mockResolvedValue();
36
- await PDFEnginesUtils.addFiles(
37
- [Buffer.from('data'), 'path/to/another-file.pdf'],
38
- data
39
- );
40
- expect(mockFormDataAppend).toHaveBeenCalledTimes(2);
41
- });
42
- });
43
- });
44
-
45
- describe('when one of the files is not PDF', () => {
46
- it('should throw an error', async () => {
47
- mockPromisesAccess.mockResolvedValue();
48
- await expect(() =>
49
- PDFEnginesUtils.addFiles(
50
- ['path/to/file.docx', 'path/to/file.pdf'],
51
- data
52
- )
53
- ).rejects.toThrow('.docx is not supported');
54
- });
55
- });
56
-
57
- describe('when one of the files does not exist', () => {
58
- it('should throw an error', async () => {
59
- const errorMessage =
60
- "ENOENT: no such file or directory, access 'path/to/index.html'";
61
- mockPromisesAccess.mockRejectedValue(new Error(errorMessage));
62
- await expect(() =>
63
- PDFEnginesUtils.addFiles(
64
- ['path/to/file.pdf', 'path/to/another-file.pdf'],
65
- data
66
- )
67
- ).rejects.toThrow(errorMessage);
68
- });
69
- });
70
- });
71
- });