@travetto/runtime 5.0.0-rc.10

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 ArcSine Technologies
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 ADDED
@@ -0,0 +1,356 @@
1
+ <!-- This file was generated by @travetto/doc and should not be modified directly -->
2
+ <!-- Please modify https://github.com/travetto/travetto/tree/main/module/runtime/DOC.tsx and execute "npx trv doc" to rebuild -->
3
+ # Runtime
4
+
5
+ ## Runtime for travetto applications.
6
+
7
+ **Install: @travetto/runtime**
8
+ ```bash
9
+ npm install @travetto/runtime
10
+
11
+ # or
12
+
13
+ yarn add @travetto/runtime
14
+ ```
15
+
16
+ Runtime is the foundation of all [Travetto](https://travetto.dev) applications. It is intended to be a minimal application set, as well as support for commonly shared functionality. It has support for the following key areas:
17
+ * Runtime Context
18
+ * Environment Support
19
+ * Standard Error Support
20
+ * Console Management
21
+ * Resource Access
22
+ * Common Utilities
23
+ * Time Utilities
24
+ * Process Execution
25
+ * Shutdown Management
26
+ * Path behavior
27
+
28
+ ## Runtime Context
29
+ While running any code within the framework, there are common patterns/goals for interacting with the underlying code repository. These include:
30
+ * Determining attributes of the running environment (e.g., name, debug information, production flags)
31
+ * Resolving paths within the workspace (e.g. standard, tooling, resourcing, modules)
32
+
33
+ **Code: Runtime Shape**
34
+ ```typescript
35
+ class $Runtime {
36
+ constructor(idx: ManifestIndex, resourceOverrides?: Record<string, string>);
37
+ get #moduleAliases(): Record<string, string>;
38
+ /** Get env name, with support for the default env */
39
+ get env(): string | undefined;
40
+ /** Are we in development mode */
41
+ get production(): boolean;
42
+ /** Is the app in dynamic mode? */
43
+ get dynamic(): boolean;
44
+ /** Get debug value */
45
+ get debug(): false | string;
46
+ /** Manifest main */
47
+ get main(): ManifestContext['main'];
48
+ /** Manifest workspace */
49
+ get workspace(): ManifestContext['workspace'];
50
+ /** Are we running from a mono-root? */
51
+ get monoRoot(): boolean;
52
+ /** Main source path */
53
+ get mainSourcePath(): string;
54
+ /** Produce a workspace relative path */
55
+ workspaceRelative(...rel: string[]): string;
56
+ /** Strip off the workspace path from a file */
57
+ stripWorkspacePath(full: string): string;
58
+ /** Produce a workspace path for tooling, with '@' being replaced by node_module/name folder */
59
+ toolPath(...rel: string[]): string;
60
+ /** Resolve single module path */
61
+ modulePath(modulePath: string): string;
62
+ /** Resolve resource paths */
63
+ resourcePaths(paths: string[] = []): string[];
64
+ /** Get source for function */
65
+ getSourceFile(fn: Function): string;
66
+ /** Get import for function */
67
+ getImport(fn: Function): string;
68
+ /** Import from a given path */
69
+ importFrom<T = unknown>(imp?: string): Promise<T>;
70
+ }
71
+ ```
72
+
73
+ ## Environment Support
74
+ The functionality we support for testing and retrieving environment information for known environment variables. They can be accessed directly on the [Env](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L109) object, and will return a scoped [EnvProp](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L6), that is compatible with the property definition. E.g. only showing boolean related fields when the underlying flag supports `true` or `false`
75
+
76
+ **Code: Base Known Environment Flags**
77
+ ```typescript
78
+ interface TravettoEnv {
79
+ /**
80
+ * The node environment we are running in
81
+ * @default development
82
+ */
83
+ NODE_ENV: 'development' | 'production';
84
+ /**
85
+ * Outputs all console.debug messages, defaults to `local` in dev, and `off` in prod.
86
+ */
87
+ DEBUG: boolean | string;
88
+ /**
89
+ * Environment to deploy, defaults to `NODE_ENV` if not `TRV_ENV` is not specified.
90
+ */
91
+ TRV_ENV: string;
92
+ /**
93
+ * Special role to run as, used to access additional files from the manifest during runtime.
94
+ */
95
+ TRV_ROLE: Role;
96
+ /**
97
+ * Whether or not to run the program in dynamic mode, allowing for real-time updates
98
+ */
99
+ TRV_DYNAMIC: boolean;
100
+ /**
101
+ * The folders to use for resource lookup
102
+ */
103
+ TRV_RESOURCES: string[];
104
+ /**
105
+ * Resource path overrides
106
+ * @private
107
+ */
108
+ TRV_RESOURCE_OVERRIDES: Record<string, string>;
109
+ /**
110
+ * The max time to wait for shutdown to finish after initial SIGINT,
111
+ * @default 2s
112
+ */
113
+ TRV_SHUTDOWN_WAIT: TimeSpan | number;
114
+ /**
115
+ * The desired runtime module
116
+ */
117
+ TRV_MODULE: string;
118
+ /**
119
+ * The location of the manifest file
120
+ * @default undefined
121
+ */
122
+ TRV_MANIFEST: string;
123
+ /**
124
+ * trvc log level
125
+ */
126
+ TRV_BUILD: 'none' | 'info' | 'debug' | 'error' | 'warn',
127
+ /**
128
+ * Should break on first line of a method when using the @DebugBreak decorator
129
+ * @default false
130
+ */
131
+ TRV_DEBUG_BREAK: boolean;
132
+ }
133
+ ```
134
+
135
+ ### Environment Property
136
+ For a given [EnvProp](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L6), we support the ability to access different properties as a means to better facilitate environment variable usage.
137
+
138
+ **Code: EnvProp Shape**
139
+ ```typescript
140
+ export class EnvProp<T> {
141
+ constructor(public readonly key: string) { }
142
+ /** Remove value */
143
+ clear(): void;
144
+ /** Export value */
145
+ export(val: T | undefined): Record<string, string>;
146
+ /** Read value as string */
147
+ get val(): string | undefined;
148
+ /** Read value as list */
149
+ get list(): string[] | undefined;
150
+ /** Read value as object */
151
+ get object(): Record<string, string> | undefined;
152
+ /** Add values to list */
153
+ add(...items: string[]): void;
154
+ /** Read value as int */
155
+ get int(): number | undefined;
156
+ /** Read value as boolean */
157
+ get bool(): boolean | undefined;
158
+ /** Determine if the underlying value is truthy */
159
+ get isTrue(): boolean;
160
+ /** Determine if the underlying value is falsy */
161
+ get isFalse(): boolean;
162
+ /** Determine if the underlying value is set */
163
+ get isSet(): boolean;
164
+ }
165
+ ```
166
+
167
+ ## Standard Error Support
168
+ While the framework is 100 % compatible with standard `Error` instances, there are cases in which additional functionality is desired. Within the framework we use [AppError](https://github.com/travetto/travetto/tree/main/module/runtime/src/error.ts#L15) (or its derivatives) to represent framework errors. This class is available for use in your own projects. Some of the additional benefits of using this class is enhanced error reporting, as well as better integration with other modules (e.g. the [RESTful API](https://github.com/travetto/travetto/tree/main/module/rest#readme "Declarative api for RESTful APIs with support for the dependency injection module.") module and HTTP status codes).
169
+
170
+ The [AppError](https://github.com/travetto/travetto/tree/main/module/runtime/src/error.ts#L15) takes in a message, and an optional payload and / or error classification. The currently supported error classifications are:
171
+ * `general` - General purpose errors
172
+ * `system` - Synonym for `general`
173
+ * `data` - Data format, content, etc are incorrect. Generally correlated to bad input.
174
+ * `permission` - Operation failed due to lack of permissions
175
+ * `auth` - Operation failed due to lack of authentication
176
+ * `missing` - Resource was not found when requested
177
+ * `timeout` - Operation did not finish in a timely manner
178
+ * `unavailable` - Resource was unresponsive
179
+
180
+ ## Console Management
181
+ This module provides logging functionality, built upon [console](https://nodejs.org/api/console.html) operations.
182
+
183
+ The supported operations are:
184
+ * `console.error` which logs at the `ERROR` level
185
+ * `console.warn` which logs at the `WARN` level
186
+ * `console.info` which logs at the `INFO` level
187
+ * `console.debug` which logs at the `DEBUG` level
188
+ * `console.log` which logs at the `INFO` level
189
+
190
+ **Note**: All other console methods are excluded, specifically `trace`, `inspect`, `dir`, `time`/`timeEnd`
191
+
192
+ ### How Logging is Instrumented
193
+ All of the logging instrumentation occurs at transpilation time. All `console.*` methods are replaced with a call to a globally defined variable that delegates to the [ConsoleManager](https://github.com/travetto/travetto/tree/main/module/runtime/src/console.ts#L35). This module, hooks into the [ConsoleManager](https://github.com/travetto/travetto/tree/main/module/runtime/src/console.ts#L35) and receives all logging events from all files compiled by the [Travetto](https://travetto.dev).
194
+
195
+ A sample of the instrumentation would be:
196
+
197
+ **Code: Sample logging at various levels**
198
+ ```typescript
199
+ export function work() {
200
+ console.debug('Start Work');
201
+
202
+ try {
203
+ 1 / 0;
204
+ } catch (err) {
205
+ console.error('Divide by zero', { error: err });
206
+ }
207
+ console.debug('End Work');
208
+ }
209
+ ```
210
+
211
+ **Code: Sample After Transpilation**
212
+ ```javascript
213
+ "use strict";
214
+ Object.defineProperty(exports, "__esModule", { value: true });
215
+ exports.work = work;
216
+ const tslib_1 = require("tslib");
217
+ const Ⲑ_function_1 = tslib_1.__importStar(require("@travetto/runtime/src/function.js"));
218
+ const ᚕ_c = tslib_1.__importStar(require("@travetto/runtime/src/console.js"));
219
+ var ᚕm = ["@travetto/runtime", "doc/transpile.ts"];
220
+ function work() {
221
+ ᚕ_c.log({ level: "debug", import: ᚕm, line: 2, scope: "work", args: ['Start Work'] });
222
+ try {
223
+ 1 / 0;
224
+ }
225
+ catch (err) {
226
+ ᚕ_c.log({ level: "error", import: ᚕm, line: 7, scope: "work", args: ['Divide by zero', { error: err }] });
227
+ }
228
+ ᚕ_c.log({ level: "debug", import: ᚕm, line: 9, scope: "work", args: ['End Work'] });
229
+ }
230
+ Ⲑ_function_1.registerFunction(work, ᚕm, { hash: 1030247697, lines: [1, 10, 2] });
231
+ ```
232
+
233
+ #### Filtering Debug
234
+ The `debug` messages can be filtered using the patterns from the [debug](https://www.npmjs.com/package/debug). You can specify wild cards to only `DEBUG` specific modules, folders or files. You can specify multiple, and you can also add negations to exclude specific packages.
235
+
236
+ **Terminal: Sample environment flags**
237
+ ```bash
238
+
239
+ # Debug
240
+ $ DEBUG=-@travetto/model npx trv run app
241
+ $ DEBUG=-@travetto/registry npx trv run app
242
+ $ DEBUG=@travetto/rest npx trv run app
243
+ $ DEBUG=@travetto/*,-@travetto/model npx trv run app
244
+ ```
245
+
246
+ Additionally, the logging framework will merge [debug](https://www.npmjs.com/package/debug) into the output stream, and supports the standard usage
247
+
248
+ **Terminal: Sample environment flags for standard usage**
249
+ ```bash
250
+
251
+ # Debug
252
+ $ DEBUG=express:*,@travetto/rest npx trv run rest
253
+ ```
254
+
255
+ ## Resource Access
256
+ The primary access patterns for resources, is to directly request a file, and to resolve that file either via file-system look up or leveraging the [Manifest](https://github.com/travetto/travetto/tree/main/module/manifest#readme "Support for project indexing, manifesting, along with file watching")'s data for what resources were found at manifesting time.
257
+
258
+ The [FileLoader](https://github.com/travetto/travetto/tree/main/module/runtime/src/file-loader.ts#L11) allows for accessing information about the resources, and subsequently reading the file as text/binary or to access the resource as a `Readable` stream. If a file is not found, it will throw an [AppError](https://github.com/travetto/travetto/tree/main/module/runtime/src/error.ts#L15) with a category of 'notfound'.
259
+
260
+ The [FileLoader](https://github.com/travetto/travetto/tree/main/module/runtime/src/file-loader.ts#L11) also supports tying itself to [Env](https://github.com/travetto/travetto/tree/main/module/runtime/src/env.ts#L109)'s `TRV_RESOURCES` information on where to attempt to find a requested resource.
261
+
262
+ ## Common Utilities
263
+ Common utilities used throughout the framework. Currently [Util](https://github.com/travetto/travetto/tree/main/module/runtime/src/util.ts#L17) includes:
264
+ * `uuid(len: number)` generates a simple uuid for use within the application.
265
+ * `allowDenyMatcher(rules[])` builds a matching function that leverages the rules as an allow/deny list, where order of the rules matters. Negative rules are prefixed by '!'.
266
+ * `hash(text: string, size?: number)` produces a full sha512 hash.
267
+ * `resolvablePromise()` produces a `Promise` instance with the `resolve` and `reject` methods attached to the instance. This is extremely useful for integrating promises into async iterations, or any other situation in which the promise creation and the execution flow don't always match up.
268
+
269
+ **Code: Sample makeTemplate Usage**
270
+ ```typescript
271
+ const tpl = makeTemplate((name: 'age'|'name', val) => `**${name}: ${val}**`);
272
+ tpl`{{age:20}} {{name: 'bob'}}</>;
273
+ // produces
274
+ '**age: 20** **name: bob**'
275
+ ```
276
+
277
+ ## Time Utilities
278
+ [TimeUtil](https://github.com/travetto/travetto/tree/main/module/runtime/src/time.ts#L17) contains general helper methods, created to assist with time-based inputs via environment variables, command line interfaces, and other string-heavy based input.
279
+
280
+ **Code: Time Utilities**
281
+ ```typescript
282
+ export class TimeUtil {
283
+ /**
284
+ * Test to see if a string is valid for relative time
285
+ * @param val
286
+ */
287
+ static isTimeSpan(val: string): val is TimeSpan;
288
+ /**
289
+ * Returns time units convert to ms
290
+ * @param amount Number of units to extend
291
+ * @param unit Time unit to extend ('ms', 's', 'm', 'h', 'd', 'w', 'y')
292
+ */
293
+ static asMillis(amount: Date | number | TimeSpan, unit?: TimeUnit): number;
294
+ /**
295
+ * Returns the time converted to seconds
296
+ * @param date The date to convert
297
+ */
298
+ static asSeconds(date: Date | number | TimeSpan, unit?: TimeUnit): number;
299
+ /**
300
+ * Returns the time converted to a Date
301
+ * @param date The date to convert
302
+ */
303
+ static asDate(date: Date | number | TimeSpan, unit?: TimeUnit): Date;
304
+ /**
305
+ * Resolve time or span to possible time
306
+ */
307
+ static fromValue(value: Date | number | string | undefined): number | undefined;
308
+ /**
309
+ * Returns a new date with `amount` units into the future
310
+ * @param amount Number of units to extend
311
+ * @param unit Time unit to extend ('ms', 's', 'm', 'h', 'd', 'w', 'y')
312
+ */
313
+ static fromNow(amount: number | TimeSpan, unit: TimeUnit = 'ms'): Date;
314
+ /**
315
+ * Returns a pretty timestamp
316
+ * @param time Time in milliseconds
317
+ */
318
+ static asClock(time: number): string;
319
+ }
320
+ ```
321
+
322
+ ## Process Execution
323
+ [ExecUtil](https://github.com/travetto/travetto/tree/main/module/runtime/src/exec.ts#L42) exposes `getResult` as a means to wrap [child_process](https://nodejs.org/api/child_process.html)'s process object. This wrapper allows for a promise-based resolution of the subprocess with the ability to capture the stderr/stdout.
324
+
325
+ A simple example would be:
326
+
327
+ **Code: Running a directory listing via ls**
328
+ ```typescript
329
+ import { spawn } from 'node:child_process';
330
+ import { ExecUtil } from '@travetto/runtime';
331
+
332
+ export async function executeListing() {
333
+ const final = await ExecUtil.getResult(spawn('ls'));
334
+ console.log('Listing', { lines: final.stdout.split('\n') });
335
+ }
336
+ ```
337
+
338
+ ## Shutdown Management
339
+ Another key lifecycle is the process of shutting down. The framework provides centralized functionality for running operations on graceful shutdown. Primarily used by the framework for cleanup operations, this provides a clean interface for registering shutdown handlers. The code intercepts `SIGTERM` and `SIGUSR2`, with a default threshold of 2 seconds. These events will start the shutdown process, but also clear out the pending queue. If a kill signal is sent again, it will complete immediately.
340
+
341
+ As a registered shutdown handler, you can do.
342
+
343
+ **Code: Registering a shutdown handler**
344
+ ```typescript
345
+ import { ShutdownManager } from '@travetto/runtime';
346
+
347
+ export function registerShutdownHandler() {
348
+ ShutdownManager.onGracefulShutdown(async () => {
349
+ // Do important work, the framework will wait until all async
350
+ // operations are completed before finishing shutdown
351
+ });
352
+ }
353
+ ```
354
+
355
+ ## Path Behavior
356
+ To ensure consistency in path usage throughout the framework, imports pointing at $`node:path` and $`path` are rewritten at compile time. These imports are pointing towards [Manifest](https://github.com/travetto/travetto/tree/main/module/manifest#readme "Support for project indexing, manifesting, along with file watching")'s `path` implementation. This allows for seamless import/usage patterns with the reliability needed for cross platform support.
package/__index__.ts ADDED
@@ -0,0 +1,19 @@
1
+ /// <reference path="./src/trv.d.ts" />
2
+ /// <reference path="./src/global.d.ts" />
3
+ export * from './src/binary';
4
+ export * from './src/console';
5
+ export * from './src/context';
6
+ export * from './src/debug';
7
+ export * from './src/error';
8
+ export * from './src/exec';
9
+ export * from './src/env';
10
+ export * from './src/file-loader';
11
+ export * from './src/function';
12
+ export * from './src/manifest-index';
13
+ export * from './src/queue';
14
+ export * from './src/resources';
15
+ export * from './src/shutdown';
16
+ export * from './src/time';
17
+ export * from './src/types';
18
+ export * from './src/watch';
19
+ export * from './src/util';
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@travetto/runtime",
3
+ "version": "5.0.0-rc.10",
4
+ "description": "Runtime for travetto applications.",
5
+ "keywords": [
6
+ "console-manager",
7
+ "runtime",
8
+ "travetto",
9
+ "typescript"
10
+ ],
11
+ "homepage": "https://travetto.io",
12
+ "license": "MIT",
13
+ "author": {
14
+ "email": "travetto.framework@gmail.com",
15
+ "name": "Travetto Framework"
16
+ },
17
+ "files": [
18
+ "__index__.ts",
19
+ "src",
20
+ "support"
21
+ ],
22
+ "main": "__index__.ts",
23
+ "repository": {
24
+ "url": "https://github.com/travetto/travetto.git",
25
+ "directory": "module/runtime"
26
+ },
27
+ "engines": {
28
+ "node": ">=22.0.0"
29
+ },
30
+ "dependencies": {
31
+ "@travetto/manifest": "^5.0.0-rc.5",
32
+ "@types/debug": "^4.1.12",
33
+ "@types/node": "^22.3.0",
34
+ "debug": "^4.3.6"
35
+ },
36
+ "peerDependencies": {
37
+ "@travetto/transformer": "^5.0.0-rc.7"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "@travetto/transformer": {
41
+ "optional": true
42
+ }
43
+ },
44
+ "travetto": {
45
+ "displayName": "Runtime"
46
+ },
47
+ "private": false,
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }
package/src/binary.ts ADDED
@@ -0,0 +1,108 @@
1
+ import path from 'node:path';
2
+ import os from 'node:os';
3
+ import crypto from 'node:crypto';
4
+ import fs from 'node:fs/promises';
5
+ import { PassThrough, Readable, Transform } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { ReadableStream } from 'node:stream/web';
8
+ import { text as toText, arrayBuffer as toBuffer } from 'node:stream/consumers';
9
+
10
+ import { BinaryInput, BlobMeta } from './types';
11
+ import { AppError } from './error';
12
+
13
+ /**
14
+ * Common functions for dealing with binary data/streams
15
+ */
16
+ export class BinaryUtil {
17
+
18
+ /**
19
+ * Generate a proper sha512 hash from a src value
20
+ * @param src The seed value to build the hash from
21
+ * @param len The optional length of the hash to generate
22
+ */
23
+ static hash(src: string, len: number = -1): string {
24
+ const hash = crypto.createHash('sha512');
25
+ hash.update(src);
26
+ const ret = hash.digest('hex');
27
+ return len > 0 ? ret.substring(0, len) : ret;
28
+ }
29
+
30
+ /**
31
+ * Compute hash from an input blob, buffer or readable stream.
32
+ */
33
+ static async hashInput(input: BinaryInput): Promise<string> {
34
+ const hash = crypto.createHash('sha256').setEncoding('hex');
35
+ if (Buffer.isBuffer(input)) {
36
+ hash.write(input);
37
+ } else if (input instanceof Blob) {
38
+ await pipeline(Readable.fromWeb(input.stream()), hash);
39
+ } else {
40
+ await pipeline(input, hash);
41
+ }
42
+ return hash.digest('hex').toString();
43
+ }
44
+
45
+ /**
46
+ * Write file and copy over when ready
47
+ */
48
+ static async bufferedFileWrite(file: string, content: string, checkHash = false): Promise<void> {
49
+ if (checkHash) {
50
+ const current = await fs.readFile(file, 'utf8').catch(() => '');
51
+ if (this.hash(current) === this.hash(content)) {
52
+ return;
53
+ }
54
+ }
55
+
56
+ const temp = path.resolve(os.tmpdir(), `${process.hrtime()[1]}.${path.basename(file)}`);
57
+ await fs.writeFile(temp, content, 'utf8');
58
+ await fs.mkdir(path.dirname(file), { recursive: true });
59
+ await fs.rename(temp, file);
60
+ }
61
+
62
+ /**
63
+ * Make a blob, and assign metadata
64
+ */
65
+ static readableBlob(input: () => (Readable | Promise<Readable>), metadata: BlobMeta): Blob {
66
+ const stream = new PassThrough();
67
+ const go = (): Readable => {
68
+ Promise.resolve(input()).then(v => v.pipe(stream), (err) => stream.destroy(err));
69
+ return stream;
70
+ };
71
+
72
+ const size = metadata.range ? (metadata.range.end - metadata.range.start) + 1 : metadata.size;
73
+ const out: Blob = metadata.filename ?
74
+ new File([], path.basename(metadata.filename), { type: metadata.contentType }) :
75
+ new Blob([], { type: metadata.contentType });
76
+
77
+ Object.defineProperties(out, {
78
+ size: { value: size },
79
+ stream: { value: () => ReadableStream.from(go()) },
80
+ arrayBuffer: { value: () => toBuffer(go()) },
81
+ text: { value: () => toText(go()) },
82
+ bytes: { value: () => toBuffer(go()).then(v => new Uint8Array(v)) },
83
+ });
84
+
85
+ // @ts-expect-error
86
+ out.meta = metadata;
87
+
88
+ return out;
89
+ }
90
+
91
+ /**
92
+ * Write limiter
93
+ * @returns
94
+ */
95
+ static limitWrite(maxSize: number): Transform {
96
+ let read = 0;
97
+ return new Transform({
98
+ transform(chunk, encoding, callback): void {
99
+ read += (Buffer.isBuffer(chunk) || typeof chunk === 'string') ? chunk.length : (chunk instanceof Uint8Array ? chunk.byteLength : 0);
100
+ if (read > maxSize) {
101
+ callback(new AppError('File size exceeded', 'data', { read, size: maxSize }));
102
+ } else {
103
+ callback(null, chunk);
104
+ }
105
+ },
106
+ });
107
+ }
108
+ }