@snyxex/pipex 1.0.2 → 1.0.3
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/LICENSE +1 -1
- package/README.md +238 -139
- package/dist/compression-2mm0MhWY.mjs +1 -0
- package/dist/compression-CtrHxa9G.d.mts +38 -0
- package/dist/compression-DnVFu8TM.d.cts +38 -0
- package/dist/compression-DrgzribA.cjs +1 -0
- package/dist/compression.cjs +1 -0
- package/dist/compression.d.cts +2 -0
- package/dist/compression.d.mts +2 -0
- package/dist/compression.mjs +1 -0
- package/dist/core-BOdvxKBq.mjs +2 -0
- package/dist/core-B_z1gN5W.cjs +2 -0
- package/dist/dataEngine-4m6GTOLe.mjs +1 -0
- package/dist/dataEngine-Bvl6amzP.cjs +1 -0
- package/dist/dataEngine-D-fIXgE7.d.cts +232 -0
- package/dist/dataEngine-DUEmWp7a.d.mts +232 -0
- package/dist/encryption-BmmNECIc.d.cts +44 -0
- package/dist/encryption-CnSL1BEY.d.mts +44 -0
- package/dist/encryption-CqxtoqAD.mjs +1 -0
- package/dist/encryption-DdP1zFYl.cjs +1 -0
- package/dist/encryption.cjs +1 -0
- package/dist/encryption.d.cts +2 -0
- package/dist/encryption.d.mts +2 -0
- package/dist/encryption.mjs +1 -0
- package/dist/hashing-B6xGcbQR.d.mts +33 -0
- package/dist/hashing-ChrADfcH.mjs +1 -0
- package/dist/hashing-JtOHPybU.cjs +1 -0
- package/dist/hashing-LY-8x66g.d.cts +33 -0
- package/dist/hashing.cjs +1 -0
- package/dist/hashing.d.cts +2 -0
- package/dist/hashing.d.mts +2 -0
- package/dist/hashing.mjs +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +302 -0
- package/dist/index.d.mts +87 -550
- package/dist/index.mjs +1 -3
- package/dist/kms.cjs +1 -0
- package/dist/kms.d.cts +3 -0
- package/dist/kms.d.mts +3 -0
- package/dist/kms.mjs +1 -0
- package/dist/kms_encryption-Da-KqjKI.d.mts +33 -0
- package/dist/kms_encryption-Dh1LEHhk.d.cts +33 -0
- package/dist/kms_encryption-R9auKGW4.mjs +1 -0
- package/dist/kms_encryption-xyWi65rZ.cjs +1 -0
- package/dist/native.cjs +1 -0
- package/dist/native.d.cts +2 -0
- package/dist/native.d.mts +2 -0
- package/dist/native.mjs +1 -0
- package/dist/parallel.cjs +1 -0
- package/dist/parallel.d.cts +2 -0
- package/dist/parallel.d.mts +2 -0
- package/dist/parallel.mjs +1 -0
- package/dist/plugin-C9Kd9coY.d.cts +16 -0
- package/dist/plugin-CE94-p8P.d.mts +16 -0
- package/dist/resourceLimits-C1HHDwXQ.mjs +1 -0
- package/dist/resourceLimits-CI0Qrqdf.cjs +1 -0
- package/dist/types-Bytga6zd.d.mts +155 -0
- package/dist/types-ia4x-Dvp.d.cts +155 -0
- package/dist/validation-CqmhNHdW.d.cts +32 -0
- package/dist/validation-D17IkoHy.d.mts +32 -0
- package/dist/validation-P5WRSAUK.mjs +1 -0
- package/dist/validation-pEeJmCad.cjs +1 -0
- package/dist/validation.cjs +1 -0
- package/dist/validation.d.cts +2 -0
- package/dist/validation.d.mts +2 -0
- package/dist/validation.mjs +1 -0
- package/dist/worker-CbuCpSNc.d.cts +37 -0
- package/dist/worker-CgCC-BWG.d.mts +37 -0
- package/dist/worker-I_kqxWeK.cjs +1 -0
- package/dist/worker-c0_VZ9c7.mjs +1 -0
- package/package.json +120 -23
- package/SECURITY.md +0 -41
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/docs/architecture.md +0 -124
- package/docs/encryption-v4-migration.md +0 -45
- package/docs/enterprise.md +0 -280
package/LICENSE
CHANGED
package/README.md
CHANGED
|
@@ -1,221 +1,320 @@
|
|
|
1
1
|
# PipeX
|
|
2
2
|
|
|
3
|
-
PipeX
|
|
3
|
+
PipeX composes compression, authenticated encryption, and HMAC integrity checks into reversible data-processing pipelines for Node.js buffers, files, and streams.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
-
|
|
5
|
+
[](https://www.npmjs.com/package/@snyxex/pipex)
|
|
6
|
+
[](https://github.com/Snyxex/PipeX/blob/main/LICENSE)
|
|
7
|
+
[](https://github.com/Snyxex/PipeX/commits/main/)
|
|
8
|
+
[](https://github.com/Snyxex/PipeX/blob/main/package.json)
|
|
9
|
+
[](https://www.npmjs.com/package/@snyxex/pipex)
|
|
9
10
|
|
|
10
11
|
## Installation
|
|
11
12
|
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
```sh
|
|
14
|
+
npm install @snyxex/pipex
|
|
15
|
+
```
|
|
14
16
|
|
|
15
|
-
|
|
17
|
+
Requires **Node.js 22 or newer** and ESM. PipeX uses Node.js streams, cryptography, and filesystem facilities; it does not provide a browser build.
|
|
16
18
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
This in-memory example requires no native filesystem bindings.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { DataEngine, CompressionPlugin } from '@snyxex/pipex';
|
|
25
|
+
|
|
26
|
+
const engine = new DataEngine().use(
|
|
27
|
+
new CompressionPlugin({ type: 'gzip', level: 6 }),
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
const encoded = await engine.binary.run({ id: 42, status: 'ready' });
|
|
31
|
+
const original = await engine.binary.undo<{ id: number; status: string }>(encoded);
|
|
32
|
+
|
|
33
|
+
console.log(original); // { id: 42, status: 'ready' }
|
|
19
34
|
```
|
|
20
35
|
|
|
21
|
-
|
|
36
|
+
## Core Concepts
|
|
37
|
+
|
|
38
|
+
- **DataEngine:** Owns the configured plugin chain, resource limits, operation lifecycle, and binary/file/stream controllers.
|
|
39
|
+
- **Controllers:** `engine.binary` processes in-memory values, `engine.file` works with paths under an allowed root, and `engine.stream` connects Node.js streams.
|
|
40
|
+
- **Plugin:** Implements `process(Buffer, context)` and optionally `reverse` or `createStream`.
|
|
41
|
+
- **Transformation:** Plugins run in registration order. Reverse transformations execute reversible plugins in the opposite order.
|
|
42
|
+
- **Capabilities:** Query whether a plugin supports processing, reversal, or native/fallback streaming.
|
|
43
|
+
- **Execution context:** Request-scoped metadata, cancellation signal, limits, and optional logging/tracing.
|
|
44
|
+
- **Source and destination:** The input and output objects passed to the relevant controller; they are concepts, not exported PipeX classes.
|
|
45
|
+
|
|
46
|
+
`pack()` and `unpack()` are **serialization-only** operations; they do not apply the transformation pipeline.
|
|
47
|
+
|
|
48
|
+
## Transformation Examples
|
|
49
|
+
|
|
50
|
+
### Compression
|
|
22
51
|
|
|
23
|
-
```
|
|
24
|
-
|
|
52
|
+
```ts
|
|
53
|
+
import { DataEngine, CompressionPlugin } from '@snyxex/pipex';
|
|
54
|
+
|
|
55
|
+
const engine = new DataEngine().use(new CompressionPlugin({ type: 'brotli', level: 5 }));
|
|
56
|
+
const result = await engine.binary.run('Repeated application data');
|
|
57
|
+
console.log(await engine.binary.undo<string>(result));
|
|
25
58
|
```
|
|
26
59
|
|
|
27
|
-
|
|
28
|
-
Do not install it expecting this project.
|
|
60
|
+
Compression types: `gzip`, `brotli`, and `none`.
|
|
29
61
|
|
|
30
|
-
|
|
62
|
+
### Encryption
|
|
31
63
|
|
|
32
64
|
```ts
|
|
33
65
|
import { randomBytes } from 'node:crypto';
|
|
34
|
-
import { DataEngine,
|
|
66
|
+
import { DataEngine, EncryptionPlugin } from '@snyxex/pipex';
|
|
67
|
+
|
|
68
|
+
// Demonstration only: retain this key securely to decrypt persisted data.
|
|
69
|
+
const key = randomBytes(32);
|
|
70
|
+
const engine = new DataEngine().use(new EncryptionPlugin({
|
|
71
|
+
algorithm: 'aes-256-gcm',
|
|
72
|
+
key,
|
|
73
|
+
allowLegacyDecrypt: false,
|
|
74
|
+
}));
|
|
75
|
+
|
|
76
|
+
const encrypted = await engine.binary.run('confidential');
|
|
77
|
+
const plaintext = await engine.binary.undo<string>(encrypted);
|
|
78
|
+
console.log(plaintext);
|
|
79
|
+
```
|
|
35
80
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
81
|
+
Alternative algorithm: `chacha20-poly1305`. Both require a 32-byte key.
|
|
82
|
+
|
|
83
|
+
### Hashing / HMAC integrity
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { DataEngine, HashingPlugin } from '@snyxex/pipex';
|
|
87
|
+
|
|
88
|
+
const engine = new DataEngine().use(new HashingPlugin({
|
|
89
|
+
algorithm: 'sha256',
|
|
90
|
+
secret: process.env.PIPEX_HMAC_SECRET ?? (() => { throw new Error('Missing HMAC key'); })(),
|
|
91
|
+
}));
|
|
92
|
+
|
|
93
|
+
const signed = await engine.binary.run('message');
|
|
94
|
+
const verified = await engine.binary.undo<string>(signed);
|
|
95
|
+
console.log(verified);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
`HashingPlugin` **appends a keyed HMAC** and verifies it during reversal. It is not a standalone, one-way digest API. The secret must contain at least 16 characters; use a high-entropy secret in production.
|
|
99
|
+
|
|
100
|
+
### Combined reversible pipeline
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { randomBytes } from 'node:crypto';
|
|
104
|
+
import { DataEngine, CompressionPlugin, EncryptionPlugin, HashingPlugin } from '@snyxex/pipex';
|
|
105
|
+
|
|
106
|
+
const encryptionKey = randomBytes(32);
|
|
107
|
+
const hmacSecret = randomBytes(32).toString('hex');
|
|
108
|
+
const engine = new DataEngine()
|
|
40
109
|
.use(new CompressionPlugin({ type: 'gzip', level: 6 }))
|
|
41
|
-
.use(new EncryptionPlugin({ algorithm: 'aes-256-gcm', key:
|
|
110
|
+
.use(new EncryptionPlugin({ algorithm: 'aes-256-gcm', key: encryptionKey }))
|
|
111
|
+
.use(new HashingPlugin({ algorithm: 'sha512', secret: hmacSecret }));
|
|
42
112
|
|
|
43
|
-
const result = await engine.binary.run({
|
|
44
|
-
const restored = await engine.binary.undo
|
|
113
|
+
const result = await engine.binary.run({ event: 'example' });
|
|
114
|
+
const restored = await engine.binary.undo<{ event: string }>(result);
|
|
115
|
+
console.log(restored);
|
|
45
116
|
```
|
|
46
117
|
|
|
47
|
-
Keep
|
|
48
|
-
Generic KMS adapters expose queryable operation capabilities and receive an
|
|
49
|
-
`AbortSignal` governed by the engine deadline. See
|
|
50
|
-
[Production operations](./docs/enterprise.md#encryption-and-key-management).
|
|
118
|
+
Keep keys outside code and configuration repositories. The HMAC in this example is an optional additional integrity layer; authenticated encryption already authenticates encrypted data.
|
|
51
119
|
|
|
52
|
-
##
|
|
120
|
+
## Data Interfaces
|
|
53
121
|
|
|
54
|
-
|
|
|
122
|
+
| Controller | Use | Runtime considerations |
|
|
55
123
|
| --- | --- | --- |
|
|
56
|
-
|
|
|
57
|
-
|
|
|
58
|
-
|
|
|
59
|
-
| Encode object frames to a file | `file.pack()` / `file.unpack()` | Serialization only; includes a manifest |
|
|
60
|
-
| Transform Node.js byte streams | `stream.pipe()` | Applies plugins with backpressure |
|
|
61
|
-
| Encode object streams | `stream.pack()` / `stream.unpack()` | Serialization only; includes a manifest |
|
|
124
|
+
| `engine.binary` | Values and buffers held in memory | Does not load native file bindings |
|
|
125
|
+
| `engine.file` | Files on disk | Uses Koffi-based native filesystem operations |
|
|
126
|
+
| `engine.stream` | Large streams, pipes, sockets | Uses Node.js backpressure and supports `AbortSignal` |
|
|
62
127
|
|
|
63
|
-
|
|
128
|
+
### Binary
|
|
64
129
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
130
|
+
```ts
|
|
131
|
+
const encoded = await engine.binary.run({ ok: true });
|
|
132
|
+
const decoded = await engine.binary.undo(encoded);
|
|
133
|
+
const serialized = engine.binary.pack({ ok: true });
|
|
134
|
+
const parsed = engine.binary.unpack<{ ok: boolean }>(serialized);
|
|
135
|
+
```
|
|
71
136
|
|
|
72
|
-
|
|
137
|
+
For data reconstructed after transport or storage, supply a trusted `expectedType` to `undo`; never trust unverified type metadata.
|
|
73
138
|
|
|
74
|
-
|
|
139
|
+
### Files
|
|
75
140
|
|
|
76
141
|
```ts
|
|
77
|
-
await engine.file.process('./data/
|
|
78
|
-
await engine.file.reverse('./data/
|
|
142
|
+
await engine.file.process('./data/source.bin', './data/source.px', './data');
|
|
143
|
+
await engine.file.reverse('./data/source.px', './data/restored.bin', './data');
|
|
79
144
|
```
|
|
80
145
|
|
|
81
|
-
|
|
82
|
-
input/output files. File sessions acquire native handles before plugins run.
|
|
83
|
-
Windows uses root-relative opens and handle-based replacement; POSIX uses
|
|
84
|
-
no-follow directory-relative opens and a private temporary directory. Outputs
|
|
85
|
-
are replaced only after successful processing. Koffi supplies the native bindings
|
|
86
|
-
and is loaded only when using the file controller. Keep roots under the service
|
|
87
|
-
account's exclusive control; see [File-system boundary](./docs/enterprise.md#file-system-boundary).
|
|
146
|
+
Output is staged and atomically replaced. Paths are restricted to `allowedRoot`; create the parent directories first.
|
|
88
147
|
|
|
89
|
-
|
|
148
|
+
### Streams
|
|
90
149
|
|
|
91
150
|
```ts
|
|
92
151
|
import { createReadStream, createWriteStream } from 'node:fs';
|
|
93
152
|
|
|
94
153
|
const controller = new AbortController();
|
|
95
154
|
await engine.stream.pipe(
|
|
96
|
-
createReadStream('./
|
|
97
|
-
createWriteStream('./output.
|
|
155
|
+
createReadStream('./source.bin'),
|
|
156
|
+
createWriteStream('./output.px'),
|
|
98
157
|
false,
|
|
99
158
|
{ signal: controller.signal, timeoutMs: 30_000 },
|
|
100
159
|
);
|
|
101
160
|
```
|
|
102
161
|
|
|
103
|
-
|
|
104
|
-
frames before releasing each frame. A final authenticated frame detects
|
|
105
|
-
truncation, while sequence numbers detect reordering and duplication. HMAC
|
|
106
|
-
verification still withholds the complete bounded message because its appended
|
|
107
|
-
digest authenticates the stream only at EOF.
|
|
162
|
+
The `reverse` argument is `true` when decoding. Serialization-only stream adapters are `engine.stream.pack()` and `engine.stream.unpack()`.
|
|
108
163
|
|
|
109
|
-
|
|
110
|
-
`maxFrameBytes`). Its v4 writer never emits the old unversioned format. The
|
|
111
|
-
legacy reader is enabled temporarily for migration and can be disabled with
|
|
112
|
-
`allowLegacyDecrypt: false`. See [Encryption v4 migration](./docs/encryption-v4-migration.md).
|
|
164
|
+
## Plugins
|
|
113
165
|
|
|
114
|
-
|
|
166
|
+
### Built-in plugins
|
|
115
167
|
|
|
116
|
-
|
|
168
|
+
| Plugin | Purpose | Notes |
|
|
169
|
+
| --- | --- | --- |
|
|
170
|
+
| `CompressionPlugin` | Gzip/Brotli transformations | Reversible; native streaming |
|
|
171
|
+
| `EncryptionPlugin` | AES-256-GCM / ChaCha20-Poly1305 | Reversible authenticated frames |
|
|
172
|
+
| `HashingPlugin` | HMAC-SHA-256 / HMAC-SHA-512 | Appends and verifies a keyed digest |
|
|
173
|
+
| `BenchmarkPlugin` | Processing metrics | Observes transformation timings |
|
|
174
|
+
| `ValidationPlugin` | Application schema validation | Integrates Zod |
|
|
175
|
+
| `WorkerPoolPlugin` | Caller-supplied worker module transforms | Opt-in local Piscina pool |
|
|
176
|
+
| `KmsEncryptionPlugin` | Envelope encryption using caller-supplied KMS | Binary-only; needs KMS provider |
|
|
117
177
|
|
|
118
|
-
|
|
119
|
-
const engine = await DataEngine.fromConfig({
|
|
120
|
-
limits: { maxInputBytes: 32 * 1024 * 1024, operationTimeoutMs: 15_000 },
|
|
121
|
-
logger,
|
|
122
|
-
auditLogger,
|
|
123
|
-
plugins: [
|
|
124
|
-
{ name: 'compression', options: { type: 'brotli', level: 5 } },
|
|
125
|
-
{ name: 'hashing', options: { algorithm: 'sha256', secret: process.env.PIPEX_HMAC_SECRET } },
|
|
126
|
-
],
|
|
127
|
-
});
|
|
178
|
+
The `Plugins` object exposes these constructors under their shortened names, e.g. `Plugins.Compression`.
|
|
128
179
|
|
|
129
|
-
|
|
130
|
-
// ['compression@3.0.0', 'hashing@3.0.0']
|
|
131
|
-
```
|
|
180
|
+
### Plugin lifecycle
|
|
132
181
|
|
|
133
|
-
|
|
182
|
+
Register with `engine.use(plugin)` in the intended order, or use `DataEngine.fromConfig()` with registered plugin names. Third-party plugins may implement `ProcessorPlugin` or extend `BasePlugin`. Registration validates capability declarations; pipeline configuration cannot change during an active operation. Reverse operations reject pipelines containing non-reversible plugins rather than silently skipping a step.
|
|
134
183
|
|
|
135
|
-
|
|
136
|
-
bounded threads, queue admission, task deadlines, and deterministic shutdown.
|
|
137
|
-
See [Local worker pools](./docs/enterprise.md#local-worker-pools).
|
|
184
|
+
Read [the full API reference](docs/api.md) for the plugin contract, constructor options, and error types.
|
|
138
185
|
|
|
139
|
-
|
|
186
|
+
## Streaming & Backpressure
|
|
140
187
|
|
|
141
|
-
|
|
188
|
+
`stream.pipe(source, destination, reverse?, options?)` connects a source to the configured transform chain and destination, awaiting completion. Node.js backpressure propagates across native stream plugins. `stream.into(destination)` and `stream.reverseInto(destination)` expose writable adapters for use with Node.js pipelines.
|
|
142
189
|
|
|
143
|
-
|
|
190
|
+
Plugins lacking `createStream()` use a per-chunk fallback **only when chunk independence is valid**. Such a fallback is not suitable for algorithms requiring whole-message authentication or global framing.
|
|
144
191
|
|
|
145
|
-
|
|
192
|
+
Authenticated encryption emits bounded frames, each verified before its plaintext is released. Previously authenticated frames can already have been consumed if a later frame or final marker fails: **treat successful stream completion as the transaction commit point**. HMAC verification, unlike per-frame AEAD, withholds complete bounded plaintext until its final digest verifies.
|
|
193
|
+
|
|
194
|
+
Cancellation uses `AbortSignal`; operation limits and deadlines apply to stream processing.
|
|
195
|
+
|
|
196
|
+
### Lifecycle, cancellation, and cleanup
|
|
197
|
+
|
|
198
|
+
PipeX runs byte-stream transformations through Node.js `stream/promises.pipeline()`. This awaits completion, propagates failures from the source, any plugin transform, or the destination, and destroys connected streams when a stage fails or the operation is aborted.
|
|
146
199
|
|
|
147
200
|
```ts
|
|
148
|
-
import {
|
|
201
|
+
import { createReadStream, createWriteStream } from 'node:fs';
|
|
202
|
+
import { DataEngine, CompressionPlugin } from '@snyxex/pipex';
|
|
149
203
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
readonly version = '1.0.0';
|
|
204
|
+
const controller = new AbortController();
|
|
205
|
+
const engine = new DataEngine().use(new CompressionPlugin({ type: 'gzip' }));
|
|
153
206
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
207
|
+
await engine.stream.pipe(
|
|
208
|
+
createReadStream('./input.bin'),
|
|
209
|
+
createWriteStream('./output.px'),
|
|
210
|
+
false,
|
|
211
|
+
{ signal: controller.signal, timeoutMs: 30_000 },
|
|
212
|
+
);
|
|
157
213
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
214
|
+
// controller.abort() cancels an operation in progress.
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
For a destination you already own, `stream.into(destination, options)` and `stream.reverseInto(destination, options)` expose a writable endpoint. Connect external sources using `pipeline()`, **not** unguarded `.pipe()`:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
import { pipeline } from 'node:stream/promises';
|
|
221
|
+
|
|
222
|
+
await pipeline(
|
|
223
|
+
createReadStream('./input.bin'),
|
|
224
|
+
engine.stream.into(createWriteStream('./output.px'), { signal: controller.signal }),
|
|
225
|
+
{ signal: controller.signal },
|
|
226
|
+
);
|
|
162
227
|
```
|
|
163
228
|
|
|
164
|
-
|
|
229
|
+
Backpressure propagates through the transforms: a slow downstream writable pauses upstream reads instead of buffering the entire input. Memory still depends on configured frame limits and plugin implementations; `binary.run()` is deliberately in-memory, and HMAC verification may hold a bounded complete message until its digest is verified.
|
|
230
|
+
|
|
231
|
+
**Lifecycle rules:** Each invocation requires fresh source and destination stream instances; the same `DataEngine` may process multiple operations. On abort or failure, the source, plugin streams, and destination are destroyed. A failed destination can contain partial output: use the file controller's atomic-output operations when partial files must not become visible. Set `timeoutMs` and resource limits appropriate for large inputs. A caller-owned `AbortSignal` is supported by binary, stream, and file controllers; aborted operations reject rather than producing partial success.
|
|
232
|
+
|
|
233
|
+
## API Reference
|
|
165
234
|
|
|
166
|
-
|
|
235
|
+
See **[docs/api.md](docs/api.md)** for public entry points, signatures, options, return values, error classes, and serialization semantics.
|
|
167
236
|
|
|
168
|
-
|
|
169
|
-
bounded retries, deadlines, concurrency limits, and an optional caller-provided
|
|
170
|
-
failure sink. The existing `dlq`/`setDlq()` names remain supported for
|
|
171
|
-
compatibility. See [Failure-sink semantics](./docs/enterprise.md#retries-and-caller-provided-failure-sink)
|
|
172
|
-
before routing potentially sensitive chunks. Observer callback failures are
|
|
173
|
-
isolated from data processing.
|
|
237
|
+
Primary operations:
|
|
174
238
|
|
|
175
239
|
```ts
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
240
|
+
new DataEngine(limits?)
|
|
241
|
+
DataEngine.fromConfig(config)
|
|
242
|
+
engine.use(plugin)
|
|
243
|
+
engine.binary.run(input, options?)
|
|
244
|
+
engine.binary.undo(result, options?)
|
|
245
|
+
engine.binary.pack(data)
|
|
246
|
+
engine.binary.unpack(buffer)
|
|
247
|
+
engine.file.process(inputPath, outputPath, allowedRoot?, options?)
|
|
248
|
+
engine.file.reverse(inputPath, outputPath, allowedRoot?, options?)
|
|
249
|
+
engine.stream.pipe(source, destination, reverse?, options?)
|
|
179
250
|
```
|
|
180
251
|
|
|
181
|
-
|
|
252
|
+
## Security
|
|
253
|
+
|
|
254
|
+
**Hashing is not encryption.** HMAC detects unauthorized modification when its key remains secret; it does not conceal contents. Authenticated encryption provides confidentiality and integrity. Complete-message integrity for framed encrypted streams is confirmed only after the final authenticated frame and successful completion.
|
|
182
255
|
|
|
183
|
-
|
|
256
|
+
- **Encryption:** AES-256-GCM and ChaCha20-Poly1305 with 32-byte keys; authenticated framing uses the `PXAE` v4 format.
|
|
257
|
+
- **Authentication tags:** A frame is not emitted as plaintext until its AEAD tag verifies. Sequence numbers and a final authenticated frame detect reordering, duplication, and truncation.
|
|
258
|
+
- **Key handling:** Supply keys through a secret manager or application-managed KMS. PipeX is not a key vault. Do not reuse a randomly generated per-process key for data requiring later decryption.
|
|
259
|
+
- **HMAC:** SHA-256 or SHA-512 with a caller-owned secret. A mismatched or truncated digest rejects reversal.
|
|
260
|
+
- **Limits:** Input, output, frame, concurrency, and timeout limits protect the host; configure them for the deployment.
|
|
261
|
+
- **KMS:** External providers are supplied by the application; the KMS plugin is binary-only and requires a working `generateDataKey` capability.
|
|
184
262
|
|
|
185
|
-
|
|
263
|
+
**Compatibility:** Version 4 encryption writes framed `PXAE` only. Reading legacy unversioned v3 encrypted data is a temporary migration option (`allowLegacyDecrypt`, default `false`; explicitly enable it only during migration); disable it after migration. Format compatibility is not a promise that all future versions or arbitrary plugin combinations can read every older payload. Keep original plugin configuration and secrets where reversibility is required.
|
|
186
264
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
265
|
+
See [Encryption migration](docs/encryption-v4-migration.md) and [Production security](docs/enterprise.md).
|
|
266
|
+
|
|
267
|
+
## Error Handling
|
|
268
|
+
|
|
269
|
+
Operations reject on invalid configuration, unsupported reverse/stream operations, resource-limit violations, authentication failures, aborted operations, timeouts, and underlying stream/filesystem errors. Typed errors include `PipeXError`, `UnsupportedReverseError`, `UnsupportedStreamingError`, `OperationAbortedError`, `OperationTimeoutError`, and worker/KMS errors. Check `error.code` on `PipeXError` when branching on supported classifications; other errors may be ordinary `Error` instances.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { OperationTimeoutError } from '@snyxex/pipex';
|
|
273
|
+
|
|
274
|
+
try {
|
|
275
|
+
await engine.binary.run('data', { timeoutMs: 1000 });
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (error instanceof OperationTimeoutError) {
|
|
278
|
+
console.error('Transformation timed out');
|
|
279
|
+
} else {
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
192
283
|
```
|
|
193
284
|
|
|
194
|
-
|
|
195
|
-
integration, security, package, consumer, and short performance suites.
|
|
196
|
-
Jenkins is the only configured CI system; the root `Jenkinsfile` tests PRs
|
|
197
|
-
and branches and archives an npm tarball but does not publish it.
|
|
285
|
+
## Optional Features
|
|
198
286
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
287
|
+
- **Worker Threads:** `WorkerPoolPlugin` is opt-in at runtime, but `piscina` is presently installed as a regular dependency. Workers execute caller-provided module exports, not a built-in job scheduler.
|
|
288
|
+
- **Native file operations:** `engine.file` uses `koffi`, currently a regular dependency. Binary and stream controllers do not load these native bindings. File operations fail if required native bindings are unavailable; there is no path-only fallback.
|
|
289
|
+
- **KMS:** `KmsEncryptionPlugin` requires a provider implementation supplied by your application.
|
|
290
|
+
- **Validation and observability:** Zod validation, logging, tracing, audit logging, and caller-owned failure sinks are integrated only when configured.
|
|
203
291
|
|
|
204
|
-
|
|
205
|
-
CI. Run it manually with `npm run benchmark:large` and
|
|
206
|
-
`PIPEX_BENCHMARK_BYTES` as needed.
|
|
292
|
+
## Performance & Resource Limits
|
|
207
293
|
|
|
208
|
-
|
|
294
|
+
Streaming reduces whole-payload buffering, but some operations (including HMAC verification and binary processing) necessarily retain bounded data in memory. The engine enforces finite defaults for input/output bytes, frames, concurrent operations, retry attempts, and deadlines.
|
|
209
295
|
|
|
210
|
-
|
|
296
|
+
```ts
|
|
297
|
+
const limited = new DataEngine({
|
|
298
|
+
maxInputBytes: 64 * 1024 * 1024,
|
|
299
|
+
maxOutputBytes: 256 * 1024 * 1024,
|
|
300
|
+
maxFrameBytes: 8 * 1024 * 1024,
|
|
301
|
+
maxConcurrentOperations: 32,
|
|
302
|
+
operationTimeoutMs: 30_000,
|
|
303
|
+
});
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
These are example limits, not all defaults. See [resource-limit details](docs/enterprise.md#resource-limits).
|
|
211
307
|
|
|
212
|
-
##
|
|
308
|
+
## Documentation
|
|
213
309
|
|
|
214
|
-
- [
|
|
215
|
-
- [
|
|
216
|
-
- [
|
|
217
|
-
- [
|
|
310
|
+
- [Complete public API reference](docs/api.md)
|
|
311
|
+
- [Architecture](docs/architecture.md)
|
|
312
|
+
- [Production operations and security](docs/enterprise.md)
|
|
313
|
+
- [Encryption v4 migration](docs/encryption-v4-migration.md)
|
|
218
314
|
- [Changelog](CHANGELOG.md)
|
|
219
|
-
- [Release preparation](docs/releasing.md)
|
|
220
315
|
|
|
221
|
-
|
|
316
|
+
## Contributing & License
|
|
317
|
+
|
|
318
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md), [SUPPORT.md](SUPPORT.md), and [SECURITY.md](SECURITY.md). Report vulnerabilities privately according to the security policy, not in public issues.
|
|
319
|
+
|
|
320
|
+
MIT © Snyxex.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{p as e}from"./core-BOdvxKBq.mjs";import{b as t,i as n,n as r,o as i,r as a}from"./resourceLimits-C1HHDwXQ.mjs";import{Duplex as o,PassThrough as s,Readable as c,Transform as l,compose as u}from"node:stream";import{brotliCompress as d,brotliDecompress as f,constants as p,createBrotliCompress as m,createBrotliDecompress as h,createGunzip as g,createGzip as _,gunzip as v,gzip as y}from"node:zlib";import{promisify as b}from"node:util";const x={none:0,gzip:1,brotli:2},S={0:`none`,1:`gzip`,2:`brotli`},C=b(y),w=b(v),T=b(d),E=b(f);var D=class extends n{name=`compression`;version=`3.0.0`;constructor(e){if(super(e),this.options=e,!(e.type in x))throw new t({transformName:`compression`,stage:`configuration`});if(e.level!==void 0&&!Number.isInteger(e.level)||e.type===`gzip`&&e.level!==void 0&&(e.level<0||e.level>9)||e.type===`brotli`&&e.level!==void 0&&(e.level<0||e.level>11)||e.type===`none`&&e.level!==void 0)throw new i({transformName:`compression`})}async process(e,t){let n=r(t),o=a(t);if(e.length>n)throw new i({transformName:`compression`,stage:`input`});let{type:s,level:c}=this.options,l=Buffer.from([x[s]]);if(e.length>o-l.length&&s===`none`||o<=l.length&&s!==`none`)throw new i({transformName:`compression`,stage:`output`});let u;return u=s===`gzip`?await C(e,{level:c??6,maxOutputLength:o-l.length}):s===`brotli`?await T(e,{params:{[p.BROTLI_PARAM_QUALITY]:c??11},maxOutputLength:o-l.length}):e,Buffer.concat([l,u])}async reverse(e,n){let o=r(n),s=a(n);if(e.length>o)throw new i({transformName:`compression`,stage:`input`});if(e.length<1)throw new i({transformName:`compression`});let c=S[e.readUInt8(0)],l=e.subarray(1);if(c===`gzip`)return await w(l,{maxOutputLength:s});if(c===`brotli`)return await E(l,{maxOutputLength:s});if(c!==`none`)throw new t({transformName:`compression`,stage:`configuration`});if(l.length>s)throw new i({transformName:`compression`,stage:`output`});return l}createStream(n,d){let{type:f,level:v}=this.options,y=r(d),b=a(d);if(n===`compress`){let t=f===`gzip`?_({level:v??6}):f===`brotli`?m({params:{[p.BROTLI_PARAM_QUALITY]:v??11}}):new s,n=!1,r=new l({transform(e,t,r){n||(n=!0,this.push(Buffer.from([x[f]]))),r(null,e)},flush(e){n||this.push(Buffer.from([x[f]])),e()}});return u(e(y,`compression input`),t,r,e(b,`compression output`))}return o.from(async function*(e){let n=e[Symbol.asyncIterator](),r,a=0,o=0;for(;!r;){let e=await n.next();if(e.done)throw new i({transformName:`compression`});let t=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(t.length>y-a)throw new i({transformName:`compression`,stage:`input`});a+=t.length,t.length>0&&(r=t)}let l=S[r.readUInt8(0)];if(!l)throw new t({transformName:`compression`,stage:`decompress`});let d=l===`gzip`?g():l===`brotli`?h():new s;async function*f(){let e=r.subarray(1);for(e.length>0&&(yield e);;){let e=await n.next();if(e.done)return;let t=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(t.length>y-a)throw new i({transformName:`compression`,stage:`input`});a+=t.length,t.length>0&&(yield t)}}try{for await(let e of u(c.from(f()),d)){let t=Buffer.isBuffer(e)?e:Buffer.from(e);if(t.length>b-o)throw new i({transformName:`compression`,stage:`output`});o+=t.length,yield t}}finally{d.destroy();try{await n.return?.()}catch{}}})}};export{D as t};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { C as StreamPluginContext, _ as ProcessorContext } from "./types-Bytga6zd.mjs";
|
|
2
|
+
import { t as BasePlugin } from "./plugin-CE94-p8P.mjs";
|
|
3
|
+
import { Duplex } from "node:stream";
|
|
4
|
+
|
|
5
|
+
//#region src/plugin/compression.d.ts
|
|
6
|
+
type CompressionType = 'gzip' | 'brotli' | 'none';
|
|
7
|
+
/** Gzip level is validated at runtime to be within 0–9. */
|
|
8
|
+
interface GzipCompressionOptions {
|
|
9
|
+
readonly type: 'gzip';
|
|
10
|
+
readonly level?: number;
|
|
11
|
+
}
|
|
12
|
+
/** Brotli quality is validated at runtime to be within 0–11. */
|
|
13
|
+
interface BrotliCompressionOptions {
|
|
14
|
+
readonly type: 'brotli';
|
|
15
|
+
readonly level?: number;
|
|
16
|
+
}
|
|
17
|
+
/** Pass-through compression never accepts a level option. */
|
|
18
|
+
interface NoCompressionOptions {
|
|
19
|
+
readonly type: 'none';
|
|
20
|
+
readonly level?: never;
|
|
21
|
+
}
|
|
22
|
+
/** Algorithm-discriminated compression configuration. */
|
|
23
|
+
type CompressionOptions = GzipCompressionOptions | BrotliCompressionOptions | NoCompressionOptions;
|
|
24
|
+
/**
|
|
25
|
+
* CompressionPlugin — Standard library plugin for Gzip and Brotli.
|
|
26
|
+
* Prepends a 1-byte header to identify the compression type.
|
|
27
|
+
*/
|
|
28
|
+
declare class CompressionPlugin extends BasePlugin {
|
|
29
|
+
protected options: CompressionOptions;
|
|
30
|
+
readonly name = "compression";
|
|
31
|
+
readonly version = "3.0.0";
|
|
32
|
+
constructor(options: CompressionOptions);
|
|
33
|
+
process(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
|
|
34
|
+
reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
|
|
35
|
+
createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { GzipCompressionOptions as a, CompressionType as i, CompressionOptions as n, NoCompressionOptions as o, CompressionPlugin as r, BrotliCompressionOptions as t };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { C as StreamPluginContext, _ as ProcessorContext } from "./types-ia4x-Dvp.cjs";
|
|
2
|
+
import { t as BasePlugin } from "./plugin-C9Kd9coY.cjs";
|
|
3
|
+
import { Duplex } from "node:stream";
|
|
4
|
+
|
|
5
|
+
//#region src/plugin/compression.d.ts
|
|
6
|
+
type CompressionType = 'gzip' | 'brotli' | 'none';
|
|
7
|
+
/** Gzip level is validated at runtime to be within 0–9. */
|
|
8
|
+
interface GzipCompressionOptions {
|
|
9
|
+
readonly type: 'gzip';
|
|
10
|
+
readonly level?: number;
|
|
11
|
+
}
|
|
12
|
+
/** Brotli quality is validated at runtime to be within 0–11. */
|
|
13
|
+
interface BrotliCompressionOptions {
|
|
14
|
+
readonly type: 'brotli';
|
|
15
|
+
readonly level?: number;
|
|
16
|
+
}
|
|
17
|
+
/** Pass-through compression never accepts a level option. */
|
|
18
|
+
interface NoCompressionOptions {
|
|
19
|
+
readonly type: 'none';
|
|
20
|
+
readonly level?: never;
|
|
21
|
+
}
|
|
22
|
+
/** Algorithm-discriminated compression configuration. */
|
|
23
|
+
type CompressionOptions = GzipCompressionOptions | BrotliCompressionOptions | NoCompressionOptions;
|
|
24
|
+
/**
|
|
25
|
+
* CompressionPlugin — Standard library plugin for Gzip and Brotli.
|
|
26
|
+
* Prepends a 1-byte header to identify the compression type.
|
|
27
|
+
*/
|
|
28
|
+
declare class CompressionPlugin extends BasePlugin {
|
|
29
|
+
protected options: CompressionOptions;
|
|
30
|
+
readonly name = "compression";
|
|
31
|
+
readonly version = "3.0.0";
|
|
32
|
+
constructor(options: CompressionOptions);
|
|
33
|
+
process(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
|
|
34
|
+
reverse(data: Buffer, ctx: ProcessorContext): Promise<Buffer>;
|
|
35
|
+
createStream(mode: 'compress' | 'decompress', context?: StreamPluginContext): Duplex;
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
export { GzipCompressionOptions as a, CompressionType as i, CompressionOptions as n, NoCompressionOptions as o, CompressionPlugin as r, BrotliCompressionOptions as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require(`./core-B_z1gN5W.cjs`),t=require(`./resourceLimits-CI0Qrqdf.cjs`);let n=require(`node:stream`),r=require(`node:zlib`),i=require(`node:util`);const a={none:0,gzip:1,brotli:2},o={0:`none`,1:`gzip`,2:`brotli`},s=(0,i.promisify)(r.gzip),c=(0,i.promisify)(r.gunzip),l=(0,i.promisify)(r.brotliCompress),u=(0,i.promisify)(r.brotliDecompress);var d=class extends t.i{name=`compression`;version=`3.0.0`;constructor(e){if(super(e),this.options=e,!(e.type in a))throw new t.b({transformName:`compression`,stage:`configuration`});if(e.level!==void 0&&!Number.isInteger(e.level)||e.type===`gzip`&&e.level!==void 0&&(e.level<0||e.level>9)||e.type===`brotli`&&e.level!==void 0&&(e.level<0||e.level>11)||e.type===`none`&&e.level!==void 0)throw new t.o({transformName:`compression`})}async process(e,n){let i=t.n(n),o=t.r(n);if(e.length>i)throw new t.o({transformName:`compression`,stage:`input`});let{type:c,level:u}=this.options,d=Buffer.from([a[c]]);if(e.length>o-d.length&&c===`none`||o<=d.length&&c!==`none`)throw new t.o({transformName:`compression`,stage:`output`});let f;return f=c===`gzip`?await s(e,{level:u??6,maxOutputLength:o-d.length}):c===`brotli`?await l(e,{params:{[r.constants.BROTLI_PARAM_QUALITY]:u??11},maxOutputLength:o-d.length}):e,Buffer.concat([d,f])}async reverse(e,n){let r=t.n(n),i=t.r(n);if(e.length>r)throw new t.o({transformName:`compression`,stage:`input`});if(e.length<1)throw new t.o({transformName:`compression`});let a=o[e.readUInt8(0)],s=e.subarray(1);if(a===`gzip`)return await c(s,{maxOutputLength:i});if(a===`brotli`)return await u(s,{maxOutputLength:i});if(a!==`none`)throw new t.b({transformName:`compression`,stage:`configuration`});if(s.length>i)throw new t.o({transformName:`compression`,stage:`output`});return s}createStream(i,s){let{type:c,level:l}=this.options,u=t.n(s),d=t.r(s);if(i===`compress`){let t=c===`gzip`?(0,r.createGzip)({level:l??6}):c===`brotli`?(0,r.createBrotliCompress)({params:{[r.constants.BROTLI_PARAM_QUALITY]:l??11}}):new n.PassThrough,i=!1,o=new n.Transform({transform(e,t,n){i||(i=!0,this.push(Buffer.from([a[c]]))),n(null,e)},flush(e){i||this.push(Buffer.from([a[c]])),e()}});return(0,n.compose)(e.p(u,`compression input`),t,o,e.p(d,`compression output`))}return n.Duplex.from(async function*(e){let i=e[Symbol.asyncIterator](),a,s=0,c=0;for(;!a;){let e=await i.next();if(e.done)throw new t.o({transformName:`compression`});let n=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(n.length>u-s)throw new t.o({transformName:`compression`,stage:`input`});s+=n.length,n.length>0&&(a=n)}let l=o[a.readUInt8(0)];if(!l)throw new t.b({transformName:`compression`,stage:`decompress`});let f=l===`gzip`?(0,r.createGunzip)():l===`brotli`?(0,r.createBrotliDecompress)():new n.PassThrough;async function*p(){let e=a.subarray(1);for(e.length>0&&(yield e);;){let e=await i.next();if(e.done)return;let n=Buffer.isBuffer(e.value)?e.value:Buffer.from(e.value);if(n.length>u-s)throw new t.o({transformName:`compression`,stage:`input`});s+=n.length,n.length>0&&(yield n)}}try{for await(let e of(0,n.compose)(n.Readable.from(p()),f)){let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(n.length>d-c)throw new t.o({transformName:`compression`,stage:`output`});c+=n.length,yield n}}finally{f.destroy();try{await i.return?.()}catch{}}})}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return d}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./compression-DrgzribA.cjs`);exports.CompressionPlugin=e.t;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as GzipCompressionOptions, i as CompressionType, n as CompressionOptions, o as NoCompressionOptions, r as CompressionPlugin, t as BrotliCompressionOptions } from "./compression-DnVFu8TM.cjs";
|
|
2
|
+
export { type BrotliCompressionOptions, type CompressionOptions, CompressionPlugin, type CompressionType, type GzipCompressionOptions, type NoCompressionOptions };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as GzipCompressionOptions, i as CompressionType, n as CompressionOptions, o as NoCompressionOptions, r as CompressionPlugin, t as BrotliCompressionOptions } from "./compression-CtrHxa9G.mjs";
|
|
2
|
+
export { type BrotliCompressionOptions, type CompressionOptions, CompressionPlugin, type CompressionType, type GzipCompressionOptions, type NoCompressionOptions };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./compression-2mm0MhWY.mjs";export{e as CompressionPlugin};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{C as e,S as t,_ as n,d as r,g as i,i as a,t as o}from"./resourceLimits-C1HHDwXQ.mjs";import{randomUUID as s}from"node:crypto";import{pipeline as c}from"node:stream/promises";import{Transform as l}from"node:stream";import{Packr as u,PackrStream as d,Unpackr as f,UnpackrStream as p}from"msgpackr";import"zod";import m from"node:path";import{existsSync as h,realpathSync as g}from"node:fs";function _(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.__pipex_v===1&&Array.isArray(t.plugins)&&t.plugins.length<=256&&t.plugins.every(e=>typeof e==`string`&&e.length<=256)&&typeof t.ts==`number`&&Number.isSafeInteger(t.ts)&&t.ts>=0}var v=class{#e;#t;#n=0;#r=1;#i=0;#a=!1;#o;#s=0;constructor(e,t){this.#e=e,this.#t=t}scan(e){let t=[],n=0;for(;n<e.length;){if(this.#i>0){if(this.#a){this.#c(1);let r=e[n];n++,this.#i--,this.#a=!1,r===101||r===115||r===120?(this.#u(1),this.#l(this.#i)):r!==0&&r!==66&&r!==116&&r!==255&&this.#v(),this.#i===0&&this.#g(n,t);continue}let r=Math.min(this.#i,e.length-n);this.#c(r),this.#i-=r,n+=r,this.#i>0&&this.#n===this.#e&&this.#_(),this.#i===0&&this.#g(n,t);continue}if(this.#o){let r=this.#o;if(this.#c(1),r.value=r.value*256+e[n],n++,r.read++,r.read===r.bytes){let{kind:e,value:i}=r;this.#o=void 0,this.#m(e,i),this.#g(n,t)}continue}this.#c(1);let r=e[n];n++,this.#r--,this.#r<0&&this.#v(),this.#h(r),this.#g(n,t)}return t}finish(){if(this.#n!==0||this.#o||this.#i!==0)throw Error(`[PipeX] Invalid MessagePack input: incomplete frame`)}#c(e){e>this.#e-this.#n&&this.#_(),this.#n+=e}#l(e=0){let t=this.#e-this.#n;(e>t||this.#r>t-e)&&this.#_()}#u(e){(!Number.isSafeInteger(e)||e<0||e>2**53-1-this.#r)&&this.#v(),this.#r+=e,this.#l()}#d(e){(!Number.isSafeInteger(e)||e<0)&&this.#v(),this.#l(e),this.#i=e}#f(e){this.#d(e+1),this.#a=!0}#p(e,t){this.#o={kind:e,bytes:t,read:0,value:0}}#m(e,t){e===`array`?this.#u(t):e===`map`?this.#u(t*2):(this.#d(t+ +(e===`extension`)),this.#a=e===`extension`)}#h(e){if(e<=127||e>=224||e>=192&&e<=195){e===193&&this.#v();return}if(e>=128&&e<=143)return this.#u((e&15)*2);if(e>=144&&e<=159)return this.#u(e&15);if(e>=160&&e<=191)return this.#d(e&31);switch(e){case 196:return this.#p(`payload`,1);case 197:return this.#p(`payload`,2);case 198:return this.#p(`payload`,4);case 199:return this.#p(`extension`,1);case 200:return this.#p(`extension`,2);case 201:return this.#p(`extension`,4);case 202:return this.#d(4);case 203:return this.#d(8);case 204:case 208:return this.#d(1);case 205:case 209:return this.#d(2);case 206:case 210:return this.#d(4);case 207:case 211:return this.#d(8);case 212:return this.#f(1);case 213:return this.#f(2);case 214:return this.#f(4);case 215:return this.#f(8);case 216:return this.#f(16);case 217:return this.#p(`payload`,1);case 218:return this.#p(`payload`,2);case 219:return this.#p(`payload`,4);case 220:return this.#p(`array`,2);case 221:return this.#p(`array`,4);case 222:return this.#p(`map`,2);case 223:return this.#p(`map`,4);default:return this.#v()}}#g(e,t){if(!(this.#o||this.#i>0||this.#r!==0)){if(this.#s++,this.#s>this.#t)throw Error(`[PipeX] Frame count exceeds ${this.#t}`);t.push(e),this.#n=0,this.#r=1,this.#a=!1}}#_(){throw Error(`[PipeX] MessagePack frame exceeds ${this.#e} bytes`)}#v(){throw Error(`[PipeX] Invalid MessagePack input`)}};function y(e,t,n=2**53-1){let r=new v(t,n),i=r.scan(Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength));return r.finish(),i.length}function ee(e,t){let n=new v(e,t),r=[],i=0;return new l({transform(e,t,a){try{let t=Buffer.isBuffer(e)?e:Buffer.from(e),o=n.scan(t),s=0;for(let e of o){let n=t.subarray(s,e);n.length>0&&(r.push(n),i+=n.length),this.push(r.length===1?r[0]:Buffer.concat(r,i)),r=[],i=0,s=e}if(s<t.length){let e=t.subarray(s);r.push(e),i+=e.length}a()}catch(e){a(e)}},flush(e){try{n.finish(),e()}catch(t){e(t)}}})}const b=new WeakMap;function x(e,t){t>0&&b.set(e,Date.now()+t)}function S(e){return e.reason instanceof n||e.reason instanceof i?e.reason:e.reason instanceof Error&&e.reason.name===`TimeoutError`?new n:new i}function C(e){if(!e)return;if(e.aborted)throw S(e);let t=b.get(e);if(t!==void 0&&Date.now()>=t)throw new n}async function w(e,t,r){let i=Promise.resolve(e);return r?.(i),t?new Promise((e,r)=>{let a=!1,o,s=()=>{t.removeEventListener(`abort`,l),o&&clearTimeout(o)},c=e=>{a||(a=!0,s(),r(e))},l=()=>c(S(t));t.addEventListener(`abort`,l,{once:!0});let u=b.get(t);u!==void 0&&(o=setTimeout(()=>c(new n),Math.max(0,u-Date.now()))),i.then(n=>{if(!a){try{C(t)}catch(e){c(e);return}a=!0,s(),e(n)}},c);try{C(t)}catch(e){c(e)}}):i}function T(e){try{Promise.resolve(e()).catch(()=>void 0)}catch{}}function E(e){if(e)return{info:(t,n)=>T(()=>e.info(t,n)),warn:(t,n)=>T(()=>e.warn(t,n)),error:(t,n)=>T(()=>e.error(t,n)),debug:(t,n)=>T(()=>e.debug(t,n))}}function D(e){if(e)return{startSpan(t,n){let r;try{let i=e.startSpan(t,n);i&&typeof i.then==`function`?T(()=>i):r=i}catch{}let i=!1,a={setAttribute(e,t){return T(()=>r?.setAttribute(e,t)),a},addEvent(e,t){return T(()=>r?.addEvent(e,t)),a},end(){i||(i=!0,T(()=>r?.end()))}};return a}}}async function O(e,t,n,r){n=E(n);let{attempts:i=1,backoff:a=`fixed`,delayMs:o=0}=t??{},s=r?.limits?.maxRetryAttempts??5,c=r?.limits?.maxRetryDelayMs??3e4;if(!Number.isSafeInteger(i)||i<1||i>s)throw Error(`[PipeX] Invalid retry attempts: ${i}`);if(!Number.isSafeInteger(o)||o<0||o>c)throw Error(`[PipeX] Invalid retry delay: ${o}`);let l;for(let t=0;t<i;t++){C(r?.signal);try{return await w(e(),r?.signal,r?.track)}catch(e){if(C(r?.signal),l=e instanceof Error?e:Error(String(e)),t<i-1){let e=a===`exponential`?o*2**t:o;n?.debug(`[PipeX] Retry ${t+1}/${i} after ${e}ms`,{error:l.message}),e>0&&await new Promise((t,n)=>{let i=()=>r?.signal?.removeEventListener(`abort`,o),a=setTimeout(()=>{i(),t()},Math.min(e,c)),o=()=>{clearTimeout(a),i(),n(r?.signal?.reason??Error(`[PipeX] Operation aborted`))};r?.signal?.addEventListener(`abort`,o,{once:!0}),r?.signal?.aborted&&o()})}}}throw l}const k=`__pipex_v`,A=new u({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1}),j=new f({useRecords:!1,structuredClone:!1}),te=256*1024*1024,M=64*1024;function N(e){return typeof e.createStream==`function`}function P(e){let t=`${e.name}@${e.version}`,n=e.reversible,i=e.streaming,o=e.reverse,s=e.createStream,c=typeof o==`function`&&o!==a.prototype.reverse;if(n!==void 0&&typeof n!=`boolean`)throw new r(t,`reversible`,`MUST_BE_BOOLEAN`);if(i!==void 0&&typeof i!=`boolean`)throw new r(t,`streaming`,`MUST_BE_BOOLEAN`);if(n===!0&&!c)throw new r(t,`reversible`,`MISSING_IMPLEMENTATION`);if(i===!1&&typeof s==`function`)throw new r(t,`streaming`,`CONFLICTING_IMPLEMENTATION`);let l=n!==!1&&c,u=i!==!1;return Object.freeze({process:!0,reverse:l,streaming:u,streamMode:u?typeof s==`function`?`native`:`fallback`:`none`})}function F(e,t){let n=P(e);switch(t){case`process`:return n.process;case`reverse`:return n.reverse;case`stream`:return n.streaming;default:throw TypeError(`[PipeX] Unknown plugin operation`)}}function I(e){return F(e,`reverse`)}function L(e){let n=e.find(e=>!I(e));if(n)throw new t(`${n.name}@${n.version}`)}function R(t){let n=t.find(e=>!F(e,`stream`));if(n)throw new e(`${n.name}@${n.version}`)}function z(e){return e===null?`null`:Buffer.isBuffer(e)?`buffer`:Array.isArray(e)?`array`:typeof e==`object`?`object`:typeof e}function ne(e){return Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):typeof e==`object`&&e?A.pack(e):typeof e==`number`||typeof e==`boolean`?Buffer.from(String(e)):Buffer.from(String(e??``),`utf-8`)}const B=Object.freeze([`buffer`,`object`,`array`,`string`,`number`,`boolean`,`null`,`undefined`,`bigint`,`json`]);function V(e){if(typeof e!=`string`||!B.includes(e))throw Error(`[PipeX] Unsupported original type`)}function H(e,t,n=o.maxFrameBytes){if(V(t),!Buffer.isBuffer(e))throw Error(`[PipeX] Invalid binary payload`);switch(t){case`array`:case`object`:{y(e,n,1);let r;try{r=j.unpack(e)}catch{throw Error(`[PipeX] fromBuffer: invalid MessagePack input`)}if(t===`array`?!Array.isArray(r):typeof r!=`object`||!r||Array.isArray(r))throw Error(`[PipeX] Decoded value does not match the expected type`);return r}case`json`:try{return JSON.parse(e.toString(`utf-8`))}catch{throw Error(`[PipeX] fromBuffer: invalid JSON input`)}case`number`:{let t=Number(e.toString(`utf-8`));if(Number.isNaN(t))throw Error(`[PipeX] fromBuffer: invalid number`);return t}case`bigint`:try{return BigInt(e.toString(`utf-8`))}catch{throw Error(`[PipeX] fromBuffer: invalid bigint`)}case`boolean`:{let t=e.toString(`utf-8`);if(t!==`true`&&t!==`false`)throw Error(`[PipeX] fromBuffer: invalid boolean`);return t===`true`}case`string`:return e.toString(`utf-8`);case`null`:case`undefined`:if(e.length!==0)throw Error(`[PipeX] Payload does not match the expected empty type`);return t===`null`?null:void 0;default:return e}}function U(e,t={},n,r,i,a){return{requestId:e,timestamp:Date.now(),metadata:t,logger:n,span:r,signal:i,limits:a}}function W(e){return{__pipex_v:1,plugins:e.map(e=>`${e.name}@${e.version}`),ts:Date.now()}}function G(e){let t=!1,n=Buffer.from(A.pack(e));return new l({transform(e,r,i){t||(t=!0,this.push(n)),i(null,e)},flush(e){t||this.push(n),e()}})}function K(e){let t=!1;return new l({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(!t&&(t=!0,_(n))){try{e(n),i()}catch(e){i(e)}return}i(null,n)}})}var q=class extends p{#e=0;#t;constructor(e={},t=o.maxInputBytes){super(e),this.#t=t}_transform(e,t,n){if(e.length>this.#t-this.#e){n(Error(`[PipeX] Serialized input exceeds ${this.#t} bytes`));return}this.#e+=e.length,super._transform(e,t,e=>{n(e?Error(`[PipeX] Invalid MessagePack input`):void 0)})}};function J(){return new d({useRecords:!1,moreTypes:!0,structuredClone:!1,bundleStrings:!1})}function Y(e=o.maxInputBytes){return new q({useRecords:!1,structuredClone:!1},e)}function X(e,t){let n=0;return new l({transform(r,i,a){if(r.length>e-n){a(Error(`[PipeX] ${t} exceeds ${e} bytes`));return}n+=r.length,a(null,r)}})}function re(e){let t=0;return new l({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){if(t>=e){i(Error(`[PipeX] Application frame count exceeds ${e}`));return}t++,i(null,n)}})}function Z(e,t,n){let r=typeof e==`string`?Buffer.byteLength(e):Buffer.isBuffer(e)||ArrayBuffer.isView(e)||e instanceof ArrayBuffer?e.byteLength:void 0;if(r!==void 0&&r>t)throw Error(`[PipeX] ${n} exceeds ${t} bytes`)}function ie(e,t){return new l({writableObjectMode:!0,readableObjectMode:!0,transform(n,r,i){try{Z(n,e,t),i(null,n)}catch(e){i(e)}}})}function Q(e,n,r,i,a,c,u){i=E(i),a=D(a);let d=u?.requestId??`stream-${s()}`;return new l({async transform(s,l,f){let p=a?.startSpan(`plugin:${e.name}`,{requestId:d});p?.setAttribute(`plugin.version`,e.version),p?.setAttribute(`mode`,n?`reverse`:`process`);try{u?.signal.throwIfAborted();let a=U(d,{},i,p,u?.signal,u?.limits);if(n&&!I(e))throw new t(`${e.name}@${e.version}`);let c=n?e.reverse.bind(e):e.process.bind(e),l=await O(()=>c(s,a),e.retryOptions,i,{signal:u?.signal,limits:u?.limits,track:u?.track}),m=u?.limits.maxOutputBytes??o.maxOutputBytes;if(!Buffer.isBuffer(l)||l.length>m)throw Error(`[PipeX] Plugin output exceeds ${m} bytes`);r?.(l.length),p?.addEvent(`processed`,{bytes:l.length}),f(null,l)}catch(t){let n=t instanceof Error?t:Error(String(t));if(i?.error(`[PipeX] Plugin ${e.name} failed after retries`,{requestId:d,error:n.message}),p?.setAttribute(`error`,!0),p?.addEvent(`error`,{message:n.message}),c&&c.writable){i?.warn(`[PipeX] Diverting failed chunk to DLQ`,{requestId:d,plugin:e.name});try{c.write(s)||await new Promise((e,t)=>{let n=()=>{o(),e()},r=e=>{o(),t(e)},i=()=>{o(),t(u?.signal.reason instanceof Error?u.signal.reason:Error(`[PipeX] Operation aborted`))},a=()=>{o(),t(Error(`[PipeX] Stream closed while writing to DLQ`))},o=()=>{c.off(`drain`,n),c.off(`error`,r),u?.signal.removeEventListener(`abort`,i),this.off(`close`,a)};c.once(`drain`,n),c.once(`error`,r),this.once(`close`,a),u?.signal.aborted?i():u?.signal.addEventListener(`abort`,i,{once:!0})}),f(n)}catch(e){f(e)}}else f(n)}finally{p?.end()}}})}function ae(){return new l({writableObjectMode:!0,readableObjectMode:!1,transform(e,t,n){try{n(null,JSON.stringify(e)+`
|
|
2
|
+
`)}catch(e){n(Error(`[PipeX] NDJSON: ${e.message}`))}}})}function oe(e,t,n=!1,r,i,a,s,c){return i=E(i),a=D(a),R(e),n&&L(e),(n?[...e].reverse():e).flatMap((e,u)=>{let d=N(e)?e.createStream(t,c):Q(e,n,r,i,a,s,c),f=X(c?.limits.maxOutputBytes??o.maxOutputBytes,`output after plugin ${e.name}#${u}`);if(!N(e))return[d,f];let p=a?.startSpan(`plugin:${e.name}`,{requestId:c?.requestId??`stream`}),m=!1,h=e=>{m||(m=!0,e&&p?.setAttribute(`error`,!0),p?.end())};return[d,new l({transform(e,t,n){r?.(e.length),p?.addEvent(`processed`,{bytes:e.length}),n(null,e)},final(e){h(),e()},destroy(e,t){h(e),t(e)}}),f]})}async function se(e,t,n,r){await c(e,...t,n,r??{})}function $(e,t){let n=m.relative(t,e);if(n===`..`||n.startsWith(`..${m.sep}`)||m.isAbsolute(n))throw Error(`[PipeX] Path is outside the allowed root`)}function ce(e,t){let n=m.resolve(e);if(!h(n))throw Error(`[PipeX] File not found: ${n}`);let r=g.native(m.resolve(t??process.cwd())),i=g.native(n);return $(i,r),i}function le(e,t){let n=g.native(m.resolve(t??process.cwd())),r=m.resolve(e),i=g.native(m.dirname(r));$(i,n);let a=m.join(i,m.basename(r));return h(a)&&$(g.native(a),n),a}export{se as A,C as B,Y as C,N as D,P as E,T as F,ee as H,E as I,D as L,I as M,ne as N,U as O,O as P,w as R,J as S,H as T,_ as U,y as V,K as _,A as a,re as b,ce as c,L as d,R as f,W as g,ie as h,B as i,F as j,le as k,Z as l,Q as m,q as n,k as o,X as p,te as r,j as s,M as t,V as u,G as v,z as w,oe as x,ae as y,x as z};
|