@swc/anyformat-utils 0.0.0 → 0.2.0

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/args.js ADDED
@@ -0,0 +1,26 @@
1
+ 'use strict'
2
+
3
+ // Helpers for the checks of arguments.
4
+
5
+ // Describes a value for an error message, as Node.js does.
6
+ function describe(value) {
7
+ if (value === null) return 'null'
8
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
9
+ return `an instance of ${Object.prototype.toString.call(value).slice(8, -1)}`
10
+ }
11
+ if (Array.isArray(value)) return 'an array'
12
+ if (typeof value === 'object') return 'an object'
13
+ return `type ${typeof value}`
14
+ }
15
+
16
+ function invalidType(name, expected, value) {
17
+ const error = new TypeError(`The ${name} must be ${expected}. Received ${describe(value)}`)
18
+ error.code = 'ERR_INVALID_ARG_TYPE'
19
+ return error
20
+ }
21
+
22
+ function isUint8Array(value) {
23
+ return ArrayBuffer.isView(value) && Object.prototype.toString.call(value) === '[object Uint8Array]'
24
+ }
25
+
26
+ module.exports = { describe, invalidType, isUint8Array }
package/index.d.ts CHANGED
@@ -1,3 +1,76 @@
1
- // Types that every anyformat Node.js package shares. The package has no
2
- // exports yet.
3
- export {}
1
+ // Types that every anyformat Node.js package shares. See index.js.
2
+
3
+ import type { ReadableStream } from 'node:stream/web'
4
+
5
+ /** Describes a value for an error message, as Node.js does. */
6
+ export declare function describe(value: unknown): string
7
+
8
+ /**
9
+ * Returns a `TypeError` with the code `ERR_INVALID_ARG_TYPE`. Its message is
10
+ * `The <name> must be <expected>. Received <description of value>`.
11
+ */
12
+ export declare function invalidType(name: string, expected: string, value: unknown): TypeError & {
13
+ code: 'ERR_INVALID_ARG_TYPE'
14
+ }
15
+
16
+ /** Returns true for a `Uint8Array`, for example a `Buffer`. */
17
+ export declare function isUint8Array(value: unknown): value is Uint8Array
18
+
19
+ /**
20
+ * The exports of the generated `binding.js` of a package. The generated
21
+ * loader sets `__napiBindingTarget` to the build that it loaded, for example
22
+ * `'wasm32-wasi'` for the WebAssembly build.
23
+ */
24
+ export interface Binding {
25
+ readonly __napiBindingTarget?: string
26
+ }
27
+
28
+ /**
29
+ * Converts a path argument to a string. A `URL` must use the `file:` scheme.
30
+ * Throws a `TypeError` with the code `ERR_INVALID_ARG_TYPE` for a value of
31
+ * another type.
32
+ *
33
+ * When `binding` is the WebAssembly build, a relative path becomes absolute,
34
+ * because WASI resolves a relative path against the root directory.
35
+ */
36
+ export declare function toPath(path: string | URL, binding?: Binding): string
37
+
38
+ /**
39
+ * Wraps the native function of a synchronous file function. The returned
40
+ * function converts its path argument with `toPath`. `binding` is the
41
+ * exports of the generated `binding.js` that `fn` comes from.
42
+ */
43
+ export declare function fileFunctionSync<T>(
44
+ fn: (path: string) => T,
45
+ binding?: Binding,
46
+ ): (path: string | URL) => T
47
+
48
+ /**
49
+ * Wraps the native function of an asynchronous file function. The returned
50
+ * function converts its path argument with `toPath` and always returns a
51
+ * promise. `binding` is the exports of the generated `binding.js` that `fn`
52
+ * comes from.
53
+ */
54
+ export declare function fileFunction<T>(
55
+ fn: (path: string) => T | Promise<T>,
56
+ binding?: Binding,
57
+ ): (path: string | URL) => Promise<T>
58
+
59
+ /** The result of a stream function. */
60
+ export interface StreamResult<T> {
61
+ /** The result of `detect` for the prefix of the input. */
62
+ result: T
63
+ /** A stream that gives all of the bytes of the input. */
64
+ stream: ReadableStream<Uint8Array>
65
+ }
66
+
67
+ /**
68
+ * Makes a stream function. The function reads chunks until it has the
69
+ * number of bytes that `prefixLen` asks for or the input ends. `prefixLen`
70
+ * can ask for more bytes when it gets more bytes. Then the function calls
71
+ * `detect` on the prefix.
72
+ */
73
+ export declare function streamFunction<T>(
74
+ prefixLen: (prefix: Uint8Array) => number,
75
+ detect: (prefix: Uint8Array) => T,
76
+ ): (stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>) => Promise<StreamResult<T>>
package/index.js CHANGED
@@ -1,5 +1,16 @@
1
1
  'use strict'
2
2
 
3
- // Helpers that every anyformat Node.js package shares. The package has no
4
- // exports yet.
5
- module.exports = {}
3
+ // Helpers that every anyformat Node.js package shares.
4
+
5
+ const { describe, invalidType, isUint8Array } = require('./args.js')
6
+ const { fileFunction, fileFunctionSync, streamFunction, toPath } = require('./input.js')
7
+
8
+ module.exports = {
9
+ describe,
10
+ fileFunction,
11
+ fileFunctionSync,
12
+ invalidType,
13
+ isUint8Array,
14
+ streamFunction,
15
+ toPath,
16
+ }
package/input.js ADDED
@@ -0,0 +1,151 @@
1
+ 'use strict'
2
+
3
+ // Helpers for the functions that take a file path or a stream.
4
+
5
+ const { isAbsolute, resolve } = require('node:path')
6
+ const { ReadableStream } = require('node:stream/web')
7
+ const { fileURLToPath } = require('node:url')
8
+
9
+ const { invalidType, isUint8Array } = require('./args.js')
10
+
11
+ // Returns true when `binding`, the exports of the generated `binding.js`, is
12
+ // the WebAssembly build.
13
+ function isWasi(binding) {
14
+ return binding !== undefined && binding.__napiBindingTarget === 'wasm32-wasi'
15
+ }
16
+
17
+ // Converts a path argument to a string. A `URL` must use the `file:` scheme.
18
+ //
19
+ // The WebAssembly build reads files through WASI. WASI resolves a relative
20
+ // path against the root directory and not against the working directory of
21
+ // the process. When `binding` is the WebAssembly build, a relative path
22
+ // becomes absolute.
23
+ function toPath(path, binding) {
24
+ if (typeof path === 'string') {
25
+ // An empty path stays empty, so that it gives ENOENT as in Node.js.
26
+ return isWasi(binding) && path !== '' && !isAbsolute(path) ? resolve(path) : path
27
+ }
28
+ if (path instanceof URL) return fileURLToPath(path)
29
+ throw invalidType('"path" argument', 'of type string or an instance of URL', path)
30
+ }
31
+
32
+ // Wraps the native function of a synchronous file function. `binding` is
33
+ // the exports of the generated `binding.js` that `fn` comes from.
34
+ function fileFunctionSync(fn, binding) {
35
+ return function fileFunctionSync(path) {
36
+ return fn(toPath(path, binding))
37
+ }
38
+ }
39
+
40
+ // Wraps the native function of an asynchronous file function. The function
41
+ // always returns a promise. `binding` is the exports of the generated
42
+ // `binding.js` that `fn` comes from.
43
+ function fileFunction(fn, binding) {
44
+ return async function fileFunction(path) {
45
+ return fn(toPath(path, binding))
46
+ }
47
+ }
48
+
49
+ // Returns an object that reads the chunks of a ReadableStream or of an async
50
+ // iterable, for example a Node.js Readable.
51
+ function chunkReader(stream) {
52
+ if (stream !== null && typeof stream === 'object' && typeof stream.getReader === 'function') {
53
+ const reader = stream.getReader()
54
+ return {
55
+ next: () => reader.read(),
56
+ cancel: (reason) => reader.cancel(reason),
57
+ }
58
+ }
59
+ if (stream !== null && typeof stream === 'object' && typeof stream[Symbol.asyncIterator] === 'function') {
60
+ const iterator = stream[Symbol.asyncIterator]()
61
+ return {
62
+ next: () => iterator.next(),
63
+ cancel: async (reason) => {
64
+ if (typeof iterator.return === 'function') await iterator.return(reason)
65
+ },
66
+ }
67
+ }
68
+ throw invalidType('"stream" argument', 'a ReadableStream or an async iterable', stream)
69
+ }
70
+
71
+ function concat(chunks, length) {
72
+ const out = new Uint8Array(length)
73
+ let offset = 0
74
+ for (const chunk of chunks) {
75
+ out.set(chunk, offset)
76
+ offset += chunk.length
77
+ }
78
+ return out
79
+ }
80
+
81
+ // Reads chunks until there are `prefixLen(prefix)` bytes or the input ends.
82
+ // `prefixLen` can ask for more bytes when it gets more bytes.
83
+ async function readPrefix(reader, prefixLen) {
84
+ let prefix = new Uint8Array(0)
85
+ let need = prefixLen(prefix)
86
+ const chunks = []
87
+ let length = 0
88
+ for (;;) {
89
+ while (length < need) {
90
+ const next = await reader.next()
91
+ if (next.done) return { prefix: concat(chunks, length), done: true }
92
+ const chunk = next.value
93
+ if (!isUint8Array(chunk)) {
94
+ const error = invalidType('chunks of the stream', 'Uint8Array objects', chunk)
95
+ await reader.cancel(error).catch(() => {})
96
+ throw error
97
+ }
98
+ // Copy the chunk: an async iterable can reuse its buffer for the next
99
+ // chunk.
100
+ chunks.push(chunk.slice())
101
+ length += chunk.length
102
+ }
103
+ prefix = concat(chunks, length)
104
+ chunks.length = 0
105
+ chunks.push(prefix)
106
+ const more = prefixLen(prefix)
107
+ if (more <= length) return { prefix, done: false }
108
+ need = more
109
+ }
110
+ }
111
+
112
+ // Returns a ReadableStream that gives `prefix` and then the rest of the
113
+ // chunks of `reader`.
114
+ function prepend(prefix, reader, done) {
115
+ let prefixSent = prefix.length === 0
116
+ return new ReadableStream({
117
+ async pull(controller) {
118
+ if (!prefixSent) {
119
+ prefixSent = true
120
+ controller.enqueue(prefix)
121
+ return
122
+ }
123
+ if (done) {
124
+ controller.close()
125
+ return
126
+ }
127
+ const next = await reader.next()
128
+ if (next.done) {
129
+ controller.close()
130
+ } else {
131
+ controller.enqueue(next.value)
132
+ }
133
+ },
134
+ cancel(reason) {
135
+ if (!done) return reader.cancel(reason)
136
+ },
137
+ })
138
+ }
139
+
140
+ // Makes a stream function. It reads the prefix that `prefixLen` asks for,
141
+ // calls `detect` on it, and returns the result and a stream with all of the
142
+ // bytes of the input.
143
+ function streamFunction(prefixLen, detect) {
144
+ return async function streamFunction(stream) {
145
+ const reader = chunkReader(stream)
146
+ const { prefix, done } = await readPrefix(reader, prefixLen)
147
+ return { result: detect(prefix), stream: prepend(prefix, reader, done) }
148
+ }
149
+ }
150
+
151
+ module.exports = { fileFunction, fileFunctionSync, streamFunction, toPath }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swc/anyformat-utils",
3
- "version": "0.0.0",
3
+ "version": "0.2.0",
4
4
  "description": "Shared helpers and types of the anyformat Node.js packages",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -11,8 +11,10 @@
11
11
  "main": "index.js",
12
12
  "types": "index.d.ts",
13
13
  "files": [
14
+ "args.js",
14
15
  "index.js",
15
- "index.d.ts"
16
+ "index.d.ts",
17
+ "input.js"
16
18
  ],
17
19
  "engines": {
18
20
  "node": ">= 18"