@imazeo/mcp 0.0.0-stage → 1.0.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ - Introduces the Imazeo Media MCP server for local stdio clients.
6
+ - Adds project credit quotes, image and PDF processing, QR and barcode generation, conversion jobs, dynamic QR management and project outputs.
7
+ - Adds opt-in local file access, no-overwrite downloads and retained operation recovery.
@@ -0,0 +1,16 @@
1
+ # Contributing
2
+
3
+ Use a supported Node.js release and run the following from the project directory.
4
+
5
+ ```sh
6
+ npm ci
7
+ npm run lint
8
+ npm run typecheck
9
+ npm test
10
+ npm run check:package
11
+ npm run check:registry
12
+ ```
13
+
14
+ The final check downloads the published MCP Registry schema. The other checks run without production Imazeo credentials. Use mock API responses based on the public contract. Keep fixtures synthetic and include coverage for contract changes, data disclosure, idempotency and local file handling as applicable.
15
+
16
+ Keep the public tool surface aligned with the [Imazeo API documentation](https://imazeo.com/docs/). Describe each tool's data, credits and state effects in its description and annotations. Use the official Imazeo TypeScript SDK when it matches deployed behavior. When changing the package version or tool behavior, update the release metadata and affected guides. See [releasing](docs/releasing.md) for the publishing procedure.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Imazeo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,72 @@
1
- # Temporary Holding Version
1
+ # Imazeo Media MCP Server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official Imazeo MCP server connects local AI clients to an Imazeo project over stdio. Process images and PDFs, render Office files and public websites, generate QR codes and barcodes, manage dynamic QR links, and save private outputs. The server is MIT-licensed. Imazeo API usage follows your project's plan, limits, storage quota and credit balance.
4
+
5
+ [Imazeo](https://imazeo.com/) · [API documentation](https://imazeo.com/docs/) · [Customer portal](https://app.imazeo.com/) · [Imazeo on GitHub](https://github.com/Imazeohq)
6
+
7
+ ## Run locally
8
+
9
+ Use Node.js 22.19 or later in the 22.x line, 24.x, or 26.x. Get an Imazeo project API key from the [customer portal](https://app.imazeo.com/). After the npm release, configure your MCP client to run the following command.
10
+
11
+ ~~~sh
12
+ npx --yes @imazeo/mcp@1.0.2
13
+ ~~~
14
+
15
+ For a source checkout, run `npm ci` and `npm run build`. Configure the client to run `node` with the absolute path to `dist/cli.js`.
16
+
17
+ | Environment variable | Purpose |
18
+ | --- | --- |
19
+ | `IMAZEO_API_KEY` | Required project API key. Configure as a secret in the client. |
20
+ | `IMAZEO_INPUT_DIR` | Optional absolute path to an existing directory. Enables local uploads. |
21
+ | `IMAZEO_OUTPUT_DIR` | Optional absolute path to an existing writable directory on a filesystem that supports hard links. Enables local downloads. |
22
+
23
+ See [client configuration](docs/clients.md) for Cursor, Claude Desktop, Claude Code and VS Code. Call `imazeo_project_capabilities` with `{}` to check authentication without processing media.
24
+
25
+ ## Tools
26
+
27
+ All names below have the `imazeo_` prefix in MCP.
28
+
29
+ | Workflow | Tools |
30
+ | --- | --- |
31
+ | Project and credits | project_capabilities, quote_credits, get_operation, get_operation_result |
32
+ | Images | upload_image, list_originals, transform_image |
33
+ | PDF | inspect_pdf, render_pdf, merge_pdfs, extract_pdf_pages |
34
+ | Static codes | generate_qr, generate_barcode |
35
+ | Office and website rendering | submit_conversion, list_conversions, get_conversion, cancel_conversion, save_conversion |
36
+ | Private outputs | list_outputs, download_output, save_artifact |
37
+ | Dynamic QR | list_dynamic_qr, get_dynamic_qr, create_dynamic_qr, update_dynamic_qr, get_dynamic_qr_analytics |
38
+
39
+ ### Generate a QR code
40
+
41
+ 1. Call `imazeo_quote_credits` with `{"kind":"code.qr","units":1}`.
42
+ 2. Review the credit amount and confirm with the user before the quote expires.
43
+ 3. Call `imazeo_generate_qr` with the quote's `id` as `quoteId`, a newly generated UUID v4 as `idempotencyKey`, and `confirm: true`. Use `{"content":"https://example.com","format":"png"}` as `options` and `menu.png` as `output`.
44
+ 4. Open `menu.png` from the configured output directory. The tool returns file metadata and an operation ID when the API provides one.
45
+
46
+ ### Render a DOCX page
47
+
48
+ 1. Put `report.docx` in the configured input directory. Call `imazeo_project_capabilities` with `{"detail":"conversions"}` to check that DOCX is enabled for the project.
49
+ 2. Request a one-unit `docx.render` quote and confirm its cost and file upload.
50
+ 3. Call `imazeo_submit_conversion` with `{"engine":"docx","input":"report.docx","options":{"page":1,"format":"png"}}` as `source`. Supply the reviewed quote ID, a new UUID v4 idempotency key and `confirm: true`.
51
+ 4. Call `imazeo_get_conversion` with a `lookup` object containing `by: "id"` and the returned job ID as `id`. When the status is completed, pass the ID to `imazeo_download_output` with source `conversion` and a new filename such as `report.png`. Use `imazeo_save_conversion` to retain the result in project storage.
52
+
53
+ ### Processing and recovery
54
+
55
+ Get a quote for each processing request. Use one unit for static codes, image transformations, PDF inspection, merging and extraction, and each conversion submission. For PDF rendering, quote the number of pages you select, up to 10. The default is page 1. For a remote image transform, set `remote: true` when quoting `image.transform`. Output files for multi-page PDF rendering receive a `-pN` suffix with the original page number.
56
+
57
+ Keep the idempotency key with the exact request. A network error or MCP cancellation can leave a remote request running. Use `imazeo_get_operation` or `imazeo_get_conversion` with the original key to recover status and retrieve available results. If a quote reports `replayEnabled: false`, synchronous processing may have no durable record. Check project usage before authorizing another attempt. Conversion jobs have their own lookup and cancellation endpoints. A cancellation request can race with completion, so check the returned job.
58
+
59
+ ### Files and privacy
60
+
61
+ Choose directories you control. Provide relative input paths with forward slashes and a single new filename for each output. The server rejects traversal, links and existing output paths. Upload requests send the file's basename, media type, bytes and operation inputs. Tool results return media metadata and local filenames. Uploads, source URLs, dynamic QR destinations and code payloads are sent to Imazeo for the requested action. See [Security](SECURITY.md) for the trust boundary.
62
+
63
+ ## Limits and troubleshooting
64
+
65
+ - Project capabilities and the active plan control what you can use. Check current credits and account usage in the [customer portal](https://app.imazeo.com/). The account usage API requires a browser account session.
66
+ - The server exposes document rendering to images, selected-page PDF rendering, basic static code styling and aggregate dynamic QR analytics. It uses a single project key per process.
67
+ - The local upload limit is 32 MiB per call. Responses from Imazeo are capped at 64 MiB. The server allows two calls in flight and applies a two-minute call deadline. The API or your MCP client can impose lower limits.
68
+ - For authentication failures, check the project key and restart the client after updating its configuration. For a 429 response, wait according to the retry guidance. For a conflict, review the quote expiry, request key, job state or revision before retrying.
69
+ - If a local write fails after processing, check `operationId` and `remoteAccepted` in the error. Recover retained output with a fresh filename when available. For multi-page results, the error can include files already written.
70
+ - Use the client's MCP logs for startup diagnostics. The server emits protocol messages on stdout and diagnostics on stderr.
71
+
72
+ [Architecture and API contract](docs/architecture.md) · [Contributing](CONTRIBUTING.md) · [Releasing](docs/releasing.md)
package/SECURITY.md ADDED
@@ -0,0 +1,13 @@
1
+ # Security
2
+
3
+ Report suspected vulnerabilities privately through [GitHub private vulnerability reporting](https://github.com/Imazeohq/imazeo-mcp/security/advisories/new). Include the package version, Node.js version, operating system, and a minimal reproduction with synthetic data. Omit real API keys, private files and account information.
4
+
5
+ ## Credentials and local files
6
+
7
+ Use a dedicated Imazeo project key and keep it in the MCP client's secret storage or private process configuration. Keep MCP client configuration containing secrets out of source control. Rotate exposed keys through the [Imazeo customer portal](https://app.imazeo.com/).
8
+
9
+ Use dedicated input and output folders controlled by your account. Their contents and relevant parent directories should be protected from changes by other users and processes you do not trust. Upload paths are relative to the input folder. Download paths are new filenames under the output folder. Input names cannot select symbolic links, junctions or hard-linked files. Output files are created with exclusive publication and are never overwritten by the server. Use OS permissions to protect the folders and resulting files.
10
+
11
+ Uploads, URLs and submitted text are sent to the Imazeo API when a relevant tool runs. A remote transform or website capture can also cause Imazeo to fetch the supplied URL. Review the input, recipient, quote and storage effects before authorizing the call. Treat retrieved media and user-supplied fields as untrusted data.
12
+
13
+ This server communicates with its host over stdio and makes HTTPS requests to the production Imazeo API. It reports fixed operational diagnostics on stderr and does not send telemetry.
package/dist/api.js ADDED
@@ -0,0 +1,111 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { Imazeo } from '@imazeo/sdk';
3
+ import { ToolError } from './errors.js';
4
+ const API_ORIGIN = 'https://api.imazeo.com';
5
+ const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
6
+ const UUID_V4 = /^[a-f\d]{8}-[a-f\d]{4}-4[a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/i;
7
+ export const REQUEST_TIMEOUT_MS = 120_000;
8
+ export function createApi(apiKey, fetcher = globalThis.fetch) {
9
+ const scopes = new AsyncLocalStorage();
10
+ const secretForms = new Set([apiKey, encodeURIComponent(apiKey)]);
11
+ let projectId;
12
+ function redact(text) {
13
+ for (const secret of secretForms)
14
+ text = text.replaceAll(secret, '[redacted]');
15
+ return text;
16
+ }
17
+ const boundedFetch = async (input, init) => {
18
+ const url = new URL(input instanceof Request ? input.url : input.toString());
19
+ if (url.origin !== API_ORIGIN || !url.pathname.startsWith('/v1/')) {
20
+ throw new Error('Invalid Imazeo API destination');
21
+ }
22
+ const scope = scopes.getStore();
23
+ const signal = AbortSignal.any([
24
+ AbortSignal.timeout(REQUEST_TIMEOUT_MS),
25
+ ...(scope ? [scope.signal] : []),
26
+ ...(init?.signal ? [init.signal] : []),
27
+ ]);
28
+ signal.throwIfAborted();
29
+ const method = init?.method ?? 'GET';
30
+ const mutation = method === 'PATCH' ||
31
+ (method === 'POST' && !/\/(?:quote|lookup)$/.test(url.pathname));
32
+ if (scope && mutation) {
33
+ scope.mutationSent = true;
34
+ scope.status = undefined;
35
+ scope.requestId = undefined;
36
+ }
37
+ const response = await fetcher(url, { ...init, redirect: 'error', signal });
38
+ if (scope) {
39
+ scope.status = response.status;
40
+ const requestId = response.headers.get('x-request-id');
41
+ scope.requestId = requestId && /^[\w-]{1,120}$/.test(requestId) ? requestId : undefined;
42
+ const operationId = response.headers.get('x-operation-id');
43
+ scope.operationId = operationId && UUID_V4.test(operationId) ? operationId : undefined;
44
+ const retryAfter = response.headers.get('retry-after');
45
+ scope.retryAfter = response.status === 429 && retryAfter &&
46
+ (/^\d{1,8}$/.test(retryAfter) || /^[A-Za-z0-9,: -]{24,40} GMT$/.test(retryAfter))
47
+ ? retryAfter : undefined;
48
+ if (mutation && response.ok)
49
+ scope.mutationAccepted = true;
50
+ }
51
+ // The Imazeo SDK buffers bodies. Apply a decoded-byte cap and keep the
52
+ // cancellation signal active until the body has been read.
53
+ if (!response.body)
54
+ return response;
55
+ const reader = response.body.getReader();
56
+ const chunks = [];
57
+ const maxBytes = response.ok ? MAX_RESPONSE_BYTES : 256 * 1024;
58
+ let bytes = 0;
59
+ try {
60
+ while (true) {
61
+ signal.throwIfAborted();
62
+ const { done, value } = await reader.read();
63
+ if (done)
64
+ break;
65
+ bytes += value.byteLength;
66
+ if (bytes > maxBytes) {
67
+ await reader.cancel();
68
+ if (!response.ok) {
69
+ return new Response(null, { status: response.status, headers: response.headers });
70
+ }
71
+ throw new Error('Imazeo response size limit exceeded');
72
+ }
73
+ chunks.push(value);
74
+ }
75
+ }
76
+ finally {
77
+ reader.releaseLock();
78
+ }
79
+ return new Response(new Blob(chunks), {
80
+ status: response.status,
81
+ headers: response.headers,
82
+ });
83
+ };
84
+ const options = {
85
+ apiKey, baseUrl: API_ORIGIN, timeoutMs: REQUEST_TIMEOUT_MS,
86
+ appName: 'Imazeo-MCP', fetch: boundedFetch,
87
+ };
88
+ const unscoped = new Imazeo(options);
89
+ async function context() {
90
+ const result = await unscoped.context.get();
91
+ if (typeof result.projectId !== 'string' || !UUID_V4.test(result.projectId)) {
92
+ throw new ToolError('INVALID_PROJECT', 'Imazeo returned an invalid project ID.');
93
+ }
94
+ projectId = result.projectId;
95
+ return { projectId };
96
+ }
97
+ return {
98
+ context,
99
+ async project() {
100
+ const id = projectId ?? (await context()).projectId;
101
+ return new Imazeo({ ...options, projectId: id });
102
+ },
103
+ run(scope, action) {
104
+ return scopes.run(scope, action);
105
+ },
106
+ redact,
107
+ containsSecret(text) {
108
+ return [...secretForms].some((secret) => text.includes(secret));
109
+ },
110
+ };
111
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env node
2
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
3
+ import { LocalFiles } from './files.js';
4
+ import { ToolError } from './errors.js';
5
+ import { createServer } from './server.js';
6
+ async function main() {
7
+ const key = process.env.IMAZEO_API_KEY?.trim();
8
+ if (!key || !/^imz_[a-f0-9-]{36}\.[A-Za-z0-9_-]{43}$/.test(key)) {
9
+ throw new ToolError('INVALID_KEY', 'Set IMAZEO_API_KEY to an Imazeo project API key.');
10
+ }
11
+ const files = await LocalFiles.fromEnv(process.env);
12
+ serveStdio(() => createServer({ key, files }), {
13
+ onerror: () => { process.stderr.write('imazeo-mcp: stdio protocol error.\n'); },
14
+ maxSubscriptions: 8,
15
+ });
16
+ }
17
+ try {
18
+ await main();
19
+ }
20
+ catch (error) {
21
+ const message = error instanceof ToolError ? error.message : 'Could not start the server.';
22
+ process.stderr.write('imazeo-mcp: ' + message + '\n');
23
+ process.exitCode = 1;
24
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,52 @@
1
+ import { ImazeoError } from '@imazeo/sdk';
2
+ export class ToolError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ }
8
+ }
9
+ const messages = {
10
+ 400: 'Imazeo rejected the request. Check the inputs and current API limits.',
11
+ 401: 'Imazeo rejected the project key. Check IMAZEO_API_KEY.',
12
+ 402: 'The Imazeo project has insufficient credits.',
13
+ 403: 'The key or project plan does not permit this operation.',
14
+ 404: 'The Imazeo resource was not found or is no longer available.',
15
+ 409: 'Imazeo reported a conflict. Check the current job, quote, revision, or idempotency key.',
16
+ 410: 'The retained Imazeo result is no longer available.',
17
+ 413: 'The upload or output exceeds an Imazeo size limit.',
18
+ 415: 'Imazeo does not support this file type.',
19
+ 422: 'Imazeo could not process the supplied input.',
20
+ 429: 'Imazeo is rate limiting requests. Wait before making another request.',
21
+ 503: 'The Imazeo API or this feature is currently unavailable.',
22
+ };
23
+ const codeMessages = {
24
+ CREDIT_INSUFFICIENT: 'The Imazeo project has insufficient credits.',
25
+ OPERATION_PENDING: 'The operation is pending. Check its status before submitting again.',
26
+ OPERATION_EXPIRED: 'The result expired. The same operation key will not run again.',
27
+ OPERATION_FAILED: 'The operation failed. The same operation key will not run again.',
28
+ QUOTE_EXPIRED: 'The quote expired or does not match the operation.',
29
+ IDEMPOTENCY_CONFLICT: 'The idempotency key was already used with different inputs.',
30
+ };
31
+ export function describeError(error, signal) {
32
+ if (error instanceof ToolError)
33
+ return { code: error.code, message: error.message };
34
+ if (signal.aborted) {
35
+ return {
36
+ code: signal.reason?.name === 'TimeoutError' ? 'TIMEOUT' : 'CANCELLED',
37
+ message: 'The MCP call stopped waiting for Imazeo.',
38
+ };
39
+ }
40
+ if (error instanceof ImazeoError && error.status && error.status >= 400) {
41
+ const code = /^[A-Z][A-Z0-9_]{1,79}$/.test(error.code ?? '') ? error.code : 'IMAZEO_API_ERROR';
42
+ return {
43
+ code,
44
+ status: error.status,
45
+ message: codeMessages[code] ?? messages[error.status] ?? 'Imazeo could not complete the request.',
46
+ };
47
+ }
48
+ return {
49
+ code: 'REQUEST_FAILED',
50
+ message: 'The request could not be completed. Check connectivity and the Imazeo service status.',
51
+ };
52
+ }
package/dist/files.js ADDED
@@ -0,0 +1,245 @@
1
+ import { constants } from 'node:fs';
2
+ import { link, lstat, open, realpath, unlink } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { ToolError } from './errors.js';
6
+ const MAX_UPLOAD_BYTES = 32 * 1024 * 1024;
7
+ const extensions = {
8
+ 'image/png': ['.png'], 'image/jpeg': ['.jpg', '.jpeg'], 'image/webp': ['.webp'],
9
+ 'image/gif': ['.gif'], 'image/avif': ['.avif'],
10
+ 'image/svg+xml': ['.svg'], 'application/pdf': ['.pdf'],
11
+ };
12
+ export const imageTypes = {
13
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
14
+ '.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif',
15
+ };
16
+ export const documentTypes = {
17
+ '.pdf': 'application/pdf',
18
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
19
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
20
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
21
+ };
22
+ function portableName(name) {
23
+ return /^[\p{L}\p{N}_-][\p{L}\p{N} ._()-]{0,119}$/u.test(name) &&
24
+ !/[. ]$/.test(name) &&
25
+ !/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])\s*(?:\.|$)/i.test(name);
26
+ }
27
+ function fileError(code, text) {
28
+ throw new ToolError(code, text);
29
+ }
30
+ async function configureRoot(value, name) {
31
+ if (!value)
32
+ return undefined;
33
+ if (!path.isAbsolute(value) || path.relative(path.parse(value).root, value) === '' ||
34
+ (process.platform === 'win32' && !/^[a-z]:[\\/]/i.test(value))) {
35
+ return fileError('INVALID_ROOT', name + ' must be an absolute path to a dedicated directory.');
36
+ }
37
+ const normalized = path.resolve(value);
38
+ try {
39
+ const actual = await realpath(normalized);
40
+ if (path.relative(normalized, actual) !== '' || !(await lstat(normalized)).isDirectory()) {
41
+ throw new Error();
42
+ }
43
+ return actual;
44
+ }
45
+ catch {
46
+ return fileError('INVALID_ROOT', name + ' must be an existing directory with no symbolic links in its path.');
47
+ }
48
+ }
49
+ async function checkRoot(root, variable) {
50
+ if (!root)
51
+ return fileError('FILE_ACCESS_DISABLED', 'Configure ' + variable + ' to enable this file operation.');
52
+ if (path.relative(root, await realpath(root)) !== '' || !(await lstat(root)).isDirectory()) {
53
+ return fileError('INVALID_ROOT', 'The configured file directory is unavailable.');
54
+ }
55
+ return root;
56
+ }
57
+ export class LocalFiles {
58
+ input;
59
+ output;
60
+ constructor(input, output) {
61
+ this.input = input;
62
+ this.output = output;
63
+ }
64
+ static async fromEnv(env) {
65
+ return new LocalFiles(await configureRoot(env.IMAZEO_INPUT_DIR, 'IMAZEO_INPUT_DIR'), await configureRoot(env.IMAZEO_OUTPUT_DIR, 'IMAZEO_OUTPUT_DIR'));
66
+ }
67
+ async readMany(paths, types, signal) {
68
+ const outputs = [];
69
+ let remaining = MAX_UPLOAD_BYTES;
70
+ for (const relative of paths) {
71
+ signal.throwIfAborted();
72
+ const parts = relative.split('/');
73
+ if (parts.length > 12 || !parts.every(portableName)) {
74
+ fileError('INVALID_INPUT_PATH', 'Use a portable path relative to IMAZEO_INPUT_DIR with forward slashes.');
75
+ }
76
+ const filename = parts.at(-1);
77
+ const extension = path.extname(filename).toLowerCase();
78
+ const contentType = Object.hasOwn(types, extension) ? types[extension] : undefined;
79
+ if (!contentType)
80
+ fileError('INVALID_FILE_TYPE', 'The input file extension is unsupported for this operation.');
81
+ try {
82
+ let target = await checkRoot(this.input, 'IMAZEO_INPUT_DIR');
83
+ for (const part of parts.slice(0, -1)) {
84
+ target = path.join(target, part);
85
+ if (!(await lstat(target)).isDirectory())
86
+ throw new Error();
87
+ }
88
+ target = path.join(target, filename);
89
+ const entry = await lstat(target, { bigint: true });
90
+ if (!entry.isFile() || entry.nlink !== 1n)
91
+ throw new Error();
92
+ if (path.relative(target, await realpath(target)) !== '')
93
+ throw new Error();
94
+ const handle = await open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) |
95
+ (constants.O_NONBLOCK ?? 0));
96
+ try {
97
+ const opened = await handle.stat({ bigint: true });
98
+ if (opened.ino !== entry.ino || opened.dev !== entry.dev ||
99
+ !opened.isFile() || opened.nlink !== 1n ||
100
+ path.relative(target, await realpath(target)) !== '') {
101
+ throw new Error();
102
+ }
103
+ if (opened.size === 0n || opened.size > BigInt(remaining)) {
104
+ fileError('INPUT_SIZE_LIMIT', 'Each input must be nonempty. Total upload size is limited to 32 MiB per call.');
105
+ }
106
+ const data = Buffer.alloc(Number(opened.size));
107
+ for (let offset = 0; offset < data.byteLength;) {
108
+ signal.throwIfAborted();
109
+ const { bytesRead } = await handle.read(data, offset, data.byteLength - offset, offset);
110
+ if (!bytesRead)
111
+ throw new Error();
112
+ offset += bytesRead;
113
+ }
114
+ const after = await handle.stat({ bigint: true });
115
+ if (after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) {
116
+ throw new Error();
117
+ }
118
+ outputs.push({ data, filename, contentType });
119
+ remaining -= data.byteLength;
120
+ }
121
+ finally {
122
+ await handle.close();
123
+ }
124
+ }
125
+ catch (error) {
126
+ signal.throwIfAborted();
127
+ if (error instanceof ToolError)
128
+ throw error;
129
+ fileError('INPUT_UNAVAILABLE', 'The input must be a readable regular file under IMAZEO_INPUT_DIR, without links.');
130
+ }
131
+ }
132
+ return outputs;
133
+ }
134
+ async prepare(name, contentType, pages) {
135
+ if (!portableName(name) || !Object.values(extensions).flat().includes(path.extname(name).toLowerCase())) {
136
+ fileError('INVALID_OUTPUT_NAME', 'Use a single output filename with a supported media extension.');
137
+ }
138
+ if (contentType)
139
+ assertExtension(name, contentType);
140
+ try {
141
+ const root = await checkRoot(this.output, 'IMAZEO_OUTPUT_DIR');
142
+ const parsed = path.parse(name);
143
+ const planned = pages
144
+ ? pages.map((page) => parsed.name + '-p' + page + parsed.ext)
145
+ : [name];
146
+ for (const candidate of planned) {
147
+ if (!portableName(candidate))
148
+ fileError('INVALID_OUTPUT_NAME', 'Use a shorter filename for numbered pages.');
149
+ await assertAbsent(path.join(root, candidate));
150
+ }
151
+ }
152
+ catch (error) {
153
+ if (error instanceof ToolError)
154
+ throw error;
155
+ fileError('OUTPUT_UNAVAILABLE', 'The configured output directory is unavailable.');
156
+ }
157
+ }
158
+ async save(name, outputs, signal, numbered = outputs.length > 1) {
159
+ if (outputs.length < 1 || outputs.length > 10) {
160
+ fileError('INVALID_RESULT', 'Imazeo returned an unexpected number of files.');
161
+ }
162
+ const parsed = path.parse(name);
163
+ const names = numbered
164
+ ? outputs.map(({ pageNumber }) => parsed.name + '-p' + pageNumber + parsed.ext)
165
+ : [name];
166
+ if (new Set(names).size !== names.length ||
167
+ (numbered && outputs.some(({ pageNumber }) => !Number.isSafeInteger(pageNumber) || pageNumber < 1))) {
168
+ fileError('INVALID_RESULT', 'Imazeo returned invalid page numbers.');
169
+ }
170
+ const results = [];
171
+ for (const [index, file] of outputs.entries()) {
172
+ const filename = names[index];
173
+ await this.prepare(filename, file.contentType);
174
+ if (!file.data.byteLength)
175
+ fileError('INVALID_RESULT', 'Imazeo returned an empty file.');
176
+ }
177
+ for (const [index, file] of outputs.entries()) {
178
+ const filename = names[index];
179
+ try {
180
+ signal.throwIfAborted();
181
+ const root = await checkRoot(this.output, 'IMAZEO_OUTPUT_DIR');
182
+ const temporary = path.join(root, '.imazeo-' + randomUUID() + '.tmp');
183
+ const handle = await open(temporary, 'wx', 0o600);
184
+ try {
185
+ try {
186
+ await handle.writeFile(file.data, { signal });
187
+ await handle.sync();
188
+ }
189
+ finally {
190
+ await handle.close();
191
+ }
192
+ signal.throwIfAborted();
193
+ await checkRoot(root, 'IMAZEO_OUTPUT_DIR');
194
+ await link(temporary, path.join(root, filename));
195
+ }
196
+ finally {
197
+ await unlink(temporary).catch(() => undefined);
198
+ }
199
+ results.push({
200
+ name: filename, bytes: file.data.byteLength,
201
+ contentType: file.contentType.split(';')[0],
202
+ pageNumber: file.pageNumber, width: file.width, height: file.height,
203
+ });
204
+ }
205
+ catch (error) {
206
+ if (results.length) {
207
+ return { files: results, complete: false, error: 'Remaining pages were not written. Recover the result and use a new output filename.' };
208
+ }
209
+ signal.throwIfAborted();
210
+ if (error.code === 'EEXIST') {
211
+ fileError('OUTPUT_EXISTS', 'Choose an unused output filename. Existing files are never replaced.');
212
+ }
213
+ fileError('OUTPUT_WRITE_FAILED', 'Could not write the output. Use a writable local directory with hard-link support.');
214
+ }
215
+ }
216
+ return { files: results, complete: true };
217
+ }
218
+ }
219
+ function assertExtension(name, contentType) {
220
+ const type = contentType.toLowerCase().split(';')[0].trim();
221
+ if (!Object.hasOwn(extensions, type) || !extensions[type]?.includes(path.extname(name).toLowerCase())) {
222
+ fileError('OUTPUT_TYPE_MISMATCH', 'Use a filename extension that matches the output media type.');
223
+ }
224
+ }
225
+ async function assertAbsent(target) {
226
+ try {
227
+ await lstat(target);
228
+ fileError('OUTPUT_EXISTS', 'Choose an unused output filename. Existing files are never replaced.');
229
+ }
230
+ catch (error) {
231
+ if (error.code !== 'ENOENT')
232
+ throw error;
233
+ }
234
+ }
235
+ export function pdfPages(pages) {
236
+ if (!Array.isArray(pages) || pages.length < 1 || pages.length > 10) {
237
+ fileError('INVALID_RESULT', 'Imazeo returned an unexpected PDF render result.');
238
+ }
239
+ return pages.map(({ data, ...metadata }) => {
240
+ if (typeof data !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(data) || data.length % 4 !== 0) {
241
+ fileError('INVALID_RESULT', 'Imazeo returned invalid encoded page data.');
242
+ }
243
+ return { ...metadata, data: Buffer.from(data, 'base64') };
244
+ });
245
+ }