@zyro-sec/util 1.0.0 → 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.
Files changed (78) hide show
  1. package/docs/layer-node.md +155 -0
  2. package/package.json +12 -15
  3. package/script/build.ts +9 -0
  4. package/script/pack.ts +5 -0
  5. package/src/abort.test.ts +16 -0
  6. package/src/abort.ts +9 -0
  7. package/src/activity-calendar.test.ts +136 -0
  8. package/src/activity-calendar.ts +50 -0
  9. package/src/artifact.test.ts +29 -0
  10. package/src/artifact.ts +95 -0
  11. package/src/base64.test.ts +12 -0
  12. package/src/base64.ts +29 -0
  13. package/src/binary.test.ts +19 -0
  14. package/src/binary.ts +30 -0
  15. package/src/bom.test.ts +21 -0
  16. package/src/bom.ts +46 -0
  17. package/src/cross-spawn-spawner.ts +694 -0
  18. package/src/duration.ts +22 -0
  19. package/src/effect/app-node-platform.ts +40 -0
  20. package/src/effect/app-node.ts +14 -0
  21. package/src/effect/layer-node.ts +360 -0
  22. package/src/effect-flock.ts +313 -0
  23. package/src/encode.test.ts +32 -0
  24. package/src/encode.ts +39 -0
  25. package/src/execute-output.test.ts +36 -0
  26. package/src/execute-output.ts +23 -0
  27. package/src/flock.ts +346 -0
  28. package/src/fs-util.ts +271 -0
  29. package/src/glob.ts +38 -0
  30. package/src/global-roots.ts +19 -0
  31. package/src/global-roots.workerd.ts +16 -0
  32. package/src/global.ts +88 -0
  33. package/src/hash.ts +11 -0
  34. package/src/heap-snapshot.ts +44 -0
  35. package/src/no-timeout-fetch.test.ts +33 -0
  36. package/src/no-timeout-fetch.ts +5 -0
  37. package/src/npm-config.ts +41 -0
  38. package/src/npm.ts +557 -0
  39. package/src/observability/logging.ts +179 -0
  40. package/src/observability/otlp.ts +109 -0
  41. package/src/observability/shared.ts +8 -0
  42. package/src/observability.ts +60 -0
  43. package/src/open.test.ts +16 -0
  44. package/src/open.ts +12 -0
  45. package/src/patch.ts +382 -0
  46. package/src/path.test.ts +89 -0
  47. package/src/path.ts +149 -0
  48. package/src/process-signal.test.ts +38 -0
  49. package/src/process-signal.ts +23 -0
  50. package/src/process.ts +270 -0
  51. package/src/qr.ts +323 -0
  52. package/src/record.ts +3 -0
  53. package/src/retry.test.ts +87 -0
  54. package/src/retry.ts +51 -0
  55. package/src/runtime/import.bun.ts +10 -0
  56. package/src/runtime/import.node.ts +61 -0
  57. package/src/runtime/import.workerd.ts +9 -0
  58. package/src/runtime-import.ts +1 -0
  59. package/src/session-mention.test.ts +19 -0
  60. package/src/session-mention.ts +24 -0
  61. package/src/session-title-fallback.ts +36 -0
  62. package/src/session-turn.test.ts +131 -0
  63. package/src/session-turn.ts +82 -0
  64. package/src/teardown.ts +19 -0
  65. package/src/text-boundary.test.ts +39 -0
  66. package/src/text-boundary.ts +36 -0
  67. package/src/uuid.test.ts +80 -0
  68. package/src/uuid.ts +15 -0
  69. package/test/fixtures/qr.json +625 -0
  70. package/test/glob.test.ts +11 -0
  71. package/test/global-roots.test.ts +62 -0
  72. package/test/global.test.ts +99 -0
  73. package/test/observability-otlp.test.ts +45 -0
  74. package/test/qr.test.ts +113 -0
  75. package/test/session-title-fallback.test.ts +49 -0
  76. package/tsconfig.build.json +12 -0
  77. package/tsconfig.dist.json +10 -0
  78. package/tsconfig.json +14 -0
package/src/process.ts ADDED
@@ -0,0 +1,270 @@
1
+ import { Context, Duration, Effect, Fiber, Layer, Schema, Stream } from "effect"
2
+ import type { PlatformError } from "effect/PlatformError"
3
+ import { ChildProcess } from "effect/process"
4
+ import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"
5
+ import { CrossSpawnSpawner } from "./cross-spawn-spawner.js"
6
+ import { makeGlobalNode } from "./effect/app-node.js"
7
+
8
+ export class AppProcessError extends Schema.TaggedError<AppProcessError>()("AppProcessError", {
9
+ command: Schema.String,
10
+ exitCode: Schema.optional(Schema.Number),
11
+ stderr: Schema.optional(Schema.String),
12
+ cause: Schema.optional(Schema.Defect()),
13
+ }) {
14
+ override get message() {
15
+ const detail =
16
+ this.stderr?.trim() || (this.cause instanceof Error ? this.cause.message : this.cause && String(this.cause))
17
+ const status = this.exitCode === undefined ? "" : ` (exit ${this.exitCode})`
18
+ return `Command failed${status}: ${this.command}${detail ? `: ${detail}` : ""}`
19
+ }
20
+ }
21
+
22
+ export interface RunOptions {
23
+ readonly combineOutput?: boolean
24
+ readonly maxOutputBytes?: number
25
+ readonly maxErrorBytes?: number
26
+ readonly signal?: AbortSignal
27
+ readonly timeout?: Duration.Input
28
+ readonly stdin?: string | Uint8Array | Stream.Stream<Uint8Array, PlatformError>
29
+ }
30
+
31
+ export interface RunStreamOptions {
32
+ readonly signal?: AbortSignal
33
+ readonly includeStderr?: boolean
34
+ readonly okExitCodes?: ReadonlyArray<number>
35
+ readonly maxErrorBytes?: number
36
+ }
37
+
38
+ export interface RunResult {
39
+ readonly command: string
40
+ readonly exitCode: number
41
+ readonly output?: Buffer
42
+ readonly stdout: Buffer
43
+ readonly stderr: Buffer
44
+ readonly outputTruncated?: boolean
45
+ readonly stdoutTruncated: boolean
46
+ readonly stderrTruncated: boolean
47
+ }
48
+
49
+ export type Interface = ChildProcessSpawner["Service"] & {
50
+ readonly run: (command: ChildProcess.Command, options?: RunOptions) => Effect.Effect<RunResult, AppProcessError>
51
+ readonly runStream: (
52
+ command: ChildProcess.Command,
53
+ options?: RunStreamOptions,
54
+ ) => Stream.Stream<string, AppProcessError>
55
+ }
56
+
57
+ export class Service extends Context.Service<Service, Interface>()("@zyro-sec/AppProcess") {}
58
+
59
+ export const requireSuccess = (result: RunResult): Effect.Effect<RunResult, AppProcessError> =>
60
+ result.exitCode === 0
61
+ ? Effect.succeed(result)
62
+ : Effect.fail(
63
+ new AppProcessError({
64
+ command: result.command,
65
+ exitCode: result.exitCode,
66
+ stderr: result.stderr.toString("utf8"),
67
+ }),
68
+ )
69
+
70
+ export const requireExitIn =
71
+ (codes: ReadonlyArray<number>) =>
72
+ (result: RunResult): Effect.Effect<RunResult, AppProcessError> =>
73
+ codes.includes(result.exitCode)
74
+ ? Effect.succeed(result)
75
+ : Effect.fail(
76
+ new AppProcessError({
77
+ command: result.command,
78
+ exitCode: result.exitCode,
79
+ stderr: result.stderr.toString("utf8"),
80
+ }),
81
+ )
82
+
83
+ const describeCommand = (command: ChildProcess.Command): string => {
84
+ if (command._tag === "StandardCommand") {
85
+ return command.args.length ? `${command.command} ${command.args.join(" ")}` : command.command
86
+ }
87
+ return `${describeCommand(command.left)} | ${describeCommand(command.right)}`
88
+ }
89
+
90
+ const wrapError = (description: string, cause: unknown): AppProcessError =>
91
+ cause instanceof AppProcessError ? cause : new AppProcessError({ command: description, cause })
92
+
93
+ export const abortError = (signal: AbortSignal): Error => {
94
+ const reason = signal.reason
95
+ if (reason instanceof Error) return reason
96
+ const err = new Error("Aborted")
97
+ err.name = "AbortError"
98
+ return err
99
+ }
100
+
101
+ export const waitForAbort = (signal: AbortSignal) =>
102
+ Effect.callback<never, Error>((resume) => {
103
+ if (signal.aborted) {
104
+ resume(Effect.fail(abortError(signal)))
105
+ return
106
+ }
107
+ const onabort = () => resume(Effect.fail(abortError(signal)))
108
+ signal.addEventListener("abort", onabort, { once: true })
109
+ return Effect.sync(() => signal.removeEventListener("abort", onabort))
110
+ })
111
+
112
+ const normalizeStdin = (
113
+ input: string | Uint8Array | Stream.Stream<Uint8Array, PlatformError>,
114
+ ): Stream.Stream<Uint8Array, PlatformError> =>
115
+ typeof input === "string"
116
+ ? Stream.make(new TextEncoder().encode(input))
117
+ : input instanceof Uint8Array
118
+ ? Stream.make(input)
119
+ : input
120
+
121
+ export const collectStream = (stream: Stream.Stream<Uint8Array, PlatformError>, maxOutputBytes: number | undefined) =>
122
+ Stream.runFold(
123
+ stream,
124
+ () => ({ chunks: [] as Uint8Array[], bytes: 0, truncated: false }),
125
+ (acc, chunk) => {
126
+ if (maxOutputBytes === undefined) {
127
+ acc.chunks.push(chunk)
128
+ acc.bytes += chunk.length
129
+ return acc
130
+ }
131
+ const remaining = maxOutputBytes - acc.bytes
132
+ if (remaining > 0) acc.chunks.push(remaining >= chunk.length ? chunk : chunk.slice(0, remaining))
133
+ acc.bytes += chunk.length
134
+ acc.truncated = acc.truncated || acc.bytes > maxOutputBytes
135
+ return acc
136
+ },
137
+ ).pipe(Effect.map((x) => ({ buffer: Buffer.concat(x.chunks), truncated: x.truncated })))
138
+
139
+ const layer = Layer.effect(
140
+ Service,
141
+ Effect.gen(function* () {
142
+ const spawner = yield* ChildProcessSpawner
143
+
144
+ const runCommand = (command: ChildProcess.Command, options?: RunOptions) => {
145
+ const description = describeCommand(command)
146
+ const collect = Effect.scoped(
147
+ Effect.gen(function* () {
148
+ const handle = yield* spawner.spawn(command)
149
+ if (options?.combineOutput) {
150
+ const [output, exitCode] = yield* Effect.all(
151
+ [collectStream(handle.all, options.maxOutputBytes), handle.exitCode],
152
+ { concurrency: "unbounded" },
153
+ )
154
+ return {
155
+ command: description,
156
+ exitCode,
157
+ output: output.buffer,
158
+ stdout: Buffer.alloc(0),
159
+ stderr: Buffer.alloc(0),
160
+ outputTruncated: output.truncated,
161
+ stdoutTruncated: false,
162
+ stderrTruncated: false,
163
+ } satisfies RunResult
164
+ }
165
+ const [stdout, stderr, exitCode] = yield* Effect.all(
166
+ [
167
+ collectStream(handle.stdout, options?.maxOutputBytes),
168
+ collectStream(handle.stderr, options?.maxErrorBytes),
169
+ handle.exitCode,
170
+ ],
171
+ { concurrency: "unbounded" },
172
+ )
173
+ return {
174
+ command: description,
175
+ exitCode,
176
+ stdout: stdout.buffer,
177
+ stderr: stderr.buffer,
178
+ stdoutTruncated: stdout.truncated,
179
+ stderrTruncated: stderr.truncated,
180
+ } satisfies RunResult
181
+ }),
182
+ )
183
+ const timed = options?.timeout
184
+ ? Effect.timeoutOrElse(collect, {
185
+ duration: options.timeout,
186
+ orElse: () => Effect.fail(new AppProcessError({ command: description, cause: new Error("Timed out") })),
187
+ })
188
+ : collect
189
+ const aborted = options?.signal
190
+ ? timed.pipe(
191
+ Effect.raceFirst(
192
+ waitForAbort(options.signal).pipe(Effect.mapError((cause) => wrapError(description, cause))),
193
+ ),
194
+ )
195
+ : timed
196
+ return aborted.pipe(Effect.mapError((cause) => wrapError(description, cause)))
197
+ }
198
+
199
+ const run = Effect.fn("AppProcess.run")(function* (command: ChildProcess.Command, options?: RunOptions) {
200
+ if (options?.stdin === undefined) return yield* runCommand(command, options)
201
+ if (command._tag !== "StandardCommand") {
202
+ return yield* new AppProcessError({
203
+ command: describeCommand(command),
204
+ cause: new Error("stdin option only supports StandardCommand; received PipedCommand"),
205
+ })
206
+ }
207
+ const next = ChildProcess.make(command.command, command.args, {
208
+ ...command.options,
209
+ stdin: normalizeStdin(options.stdin),
210
+ })
211
+ return yield* runCommand(next, options)
212
+ })
213
+
214
+ const runStream = (
215
+ command: ChildProcess.Command,
216
+ options?: RunStreamOptions,
217
+ ): Stream.Stream<string, AppProcessError> => {
218
+ const description = describeCommand(command)
219
+ const okExitCodes = options?.okExitCodes
220
+ const built: Stream.Stream<string, AppProcessError | PlatformError> = Stream.unwrap(
221
+ Effect.gen(function* () {
222
+ const handle = yield* spawner.spawn(command)
223
+ const streams =
224
+ options?.includeStderr === true
225
+ ? yield* handle.stderr.pipe(
226
+ Stream.broadcastN({ n: 2, capacity: 16 }),
227
+ Effect.map((copies) => ({
228
+ source: Stream.merge(handle.stdout, copies[0]),
229
+ diagnostics: copies[1],
230
+ })),
231
+ )
232
+ : { source: handle.stdout, diagnostics: handle.stderr }
233
+ const stderrFiber = yield* Effect.forkScoped(
234
+ collectStream(streams.diagnostics, options?.maxErrorBytes).pipe(
235
+ Effect.map((x) => x.buffer.toString("utf8")),
236
+ ),
237
+ )
238
+ const lines = streams.source.pipe(
239
+ Stream.decodeText,
240
+ Stream.splitLines,
241
+ Stream.filter((line) => line.length > 0),
242
+ )
243
+ const tail = Stream.unwrap(
244
+ Effect.gen(function* () {
245
+ const code = yield* handle.exitCode
246
+ if (okExitCodes && okExitCodes.length > 0 && !okExitCodes.includes(code)) {
247
+ const stderr = yield* Fiber.join(stderrFiber)
248
+ return Stream.fail(new AppProcessError({ command: description, exitCode: code, stderr }))
249
+ }
250
+ return Stream.empty
251
+ }),
252
+ )
253
+ return Stream.concat(lines, tail) as Stream.Stream<string, AppProcessError | PlatformError>
254
+ }),
255
+ )
256
+ const mapped = built.pipe(Stream.mapError((cause) => wrapError(description, cause)))
257
+ if (!options?.signal) return mapped
258
+ const signal = options.signal
259
+ return mapped.pipe(
260
+ Stream.interruptWhen(waitForAbort(signal).pipe(Effect.mapError((cause) => wrapError(description, cause)))),
261
+ )
262
+ }
263
+
264
+ return Service.of({ ...spawner, run, runStream })
265
+ }),
266
+ )
267
+
268
+ export const node = makeGlobalNode({ service: Service, layer: layer, deps: [CrossSpawnSpawner.node] })
269
+
270
+ export * as AppProcess from "./process.js"
package/src/qr.ts ADDED
@@ -0,0 +1,323 @@
1
+ // QR Code encoder (ISO/IEC 18004) for byte-mode text at error correction level L, following the structure of
2
+ // Project Nayuki's QR Code generator (MIT): https://www.nayuki.io/page/qr-code-generator-library
3
+
4
+ // Error correction codewords per block and block count at level L, for versions 1 to 40.
5
+ const ECC_PER_BLOCK = [
6
+ 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30,
7
+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
8
+ ]
9
+ const BLOCKS = [
10
+ 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19,
11
+ 20, 21, 22, 24, 25,
12
+ ]
13
+
14
+ const MASKS = [
15
+ (x: number, y: number) => (x + y) % 2 === 0,
16
+ (_: number, y: number) => y % 2 === 0,
17
+ (x: number) => x % 3 === 0,
18
+ (x: number, y: number) => (x + y) % 3 === 0,
19
+ (x: number, y: number) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
20
+ (x: number, y: number) => ((x * y) % 2) + ((x * y) % 3) === 0,
21
+ (x: number, y: number) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
22
+ (x: number, y: number) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
23
+ ]
24
+
25
+ type Draw = (x: number, y: number, dark: boolean) => void
26
+
27
+ /** Encodes text as UTF-8 into the smallest QR Code that fits. Rows of modules without a quiet zone; true is dark. */
28
+ export function encode(text: string) {
29
+ const bytes = new TextEncoder().encode(text)
30
+ const version = Array.from({ length: 40 }, (_, i) => i + 1).find(
31
+ (v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8 <= dataCapacity(v) * 8,
32
+ )
33
+ if (version === undefined) throw new RangeError(`Text is too long for a QR Code: ${bytes.length} bytes`)
34
+
35
+ const size = version * 4 + 17
36
+ const modules = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
37
+ const reserved = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
38
+ drawFunctionPatterns(version, size, (x, y, dark) => {
39
+ modules[y][x] = dark
40
+ reserved[y][x] = true
41
+ })
42
+ drawCodewords(modules, reserved, addErrorCorrection(dataCodewords(bytes, version), version))
43
+
44
+ const candidates = MASKS.map((mask, index) => {
45
+ const masked = modules.map((row, y) => row.map((dark, x) => dark !== (!reserved[y][x] && mask(x, y))))
46
+ drawFormat(index, size, (x, y, dark) => {
47
+ masked[y][x] = dark
48
+ })
49
+ return masked
50
+ })
51
+ const scores = candidates.map(penalty)
52
+ return candidates[scores.indexOf(Math.min(...scores))]
53
+ }
54
+
55
+ /** Renders text as an SVG QR Code with 10-unit modules and a quiet zone of `border` modules. */
56
+ export function renderSVG(text: string, options: { border?: number; blackColor?: string; whiteColor?: string } = {}) {
57
+ const modules = addBorder(encode(text), options.border ?? 1)
58
+ const width = modules.length * 10
59
+ const path = modules
60
+ .flatMap((row, y) => row.flatMap((dark, x) => (dark ? [`M${x * 10},${y * 10}h10v10h-10z`] : [])))
61
+ .join("")
62
+ return (
63
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${width}">` +
64
+ `<rect fill="${escapeAttribute(options.whiteColor ?? "white")}" width="${width}" height="${width}"/>` +
65
+ `<path fill="${escapeAttribute(options.blackColor ?? "black")}" d="${path}"/></svg>`
66
+ )
67
+ }
68
+
69
+ /**
70
+ * Renders text as a QR Code for a terminal, two modules per character with half blocks. Light modules draw as blocks
71
+ * and dark modules as the terminal background, rows are joined with "\n", and the quiet zone is `border` modules.
72
+ */
73
+ export function renderUnicodeCompact(text: string, options: { border?: number } = {}) {
74
+ const modules = addBorder(encode(text), options.border ?? 1)
75
+ return Array.from({ length: Math.ceil(modules.length / 2) }, (_, line) =>
76
+ modules[line * 2]
77
+ .map((top, x) => {
78
+ // The symbol has an odd number of rows, so the last line's missing bottom half shows the terminal background.
79
+ const bottom = modules[line * 2 + 1]?.[x] ?? true
80
+ if (top) return bottom ? " " : "\u2584"
81
+ return bottom ? "\u2580" : "\u2588"
82
+ })
83
+ .join(""),
84
+ ).join("\n")
85
+ }
86
+
87
+ function drawFunctionPatterns(version: number, size: number, set: Draw) {
88
+ for (let i = 0; i < size; i++) {
89
+ set(6, i, i % 2 === 0)
90
+ set(i, 6, i % 2 === 0)
91
+ }
92
+ for (const [cx, cy] of [
93
+ [3, 3],
94
+ [size - 4, 3],
95
+ [3, size - 4],
96
+ ])
97
+ for (let dy = -4; dy <= 4; dy++)
98
+ for (let dx = -4; dx <= 4; dx++) {
99
+ const x = cx + dx
100
+ const y = cy + dy
101
+ const distance = Math.max(Math.abs(dx), Math.abs(dy))
102
+ if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, distance !== 2 && distance !== 4)
103
+ }
104
+
105
+ const positions = alignmentPositions(version, size)
106
+ const last = positions.length - 1
107
+ positions.forEach((cx, i) =>
108
+ positions.forEach((cy, j) => {
109
+ // Skip the three corners that hold finder patterns.
110
+ if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return
111
+ for (let dy = -2; dy <= 2; dy++)
112
+ for (let dx = -2; dx <= 2; dx++) set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1)
113
+ }),
114
+ )
115
+
116
+ // Reserves the format areas; the real format bits are drawn once the mask is chosen.
117
+ drawFormat(0, size, set)
118
+ if (version < 7) return
119
+ const bits = bch(version, 12, 0x1f25)
120
+ for (let i = 0; i < 18; i++) {
121
+ const a = size - 11 + (i % 3)
122
+ const b = Math.floor(i / 3)
123
+ const dark = ((bits >>> i) & 1) === 1
124
+ set(a, b, dark)
125
+ set(b, a, dark)
126
+ }
127
+ }
128
+
129
+ function alignmentPositions(version: number, size: number) {
130
+ if (version === 1) return []
131
+ const count = Math.floor(version / 7) + 2
132
+ const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2
133
+ return [6, ...Array.from({ length: count - 1 }, (_, i) => size - 7 - (count - 2 - i) * step)]
134
+ }
135
+
136
+ function drawFormat(mask: number, size: number, set: Draw) {
137
+ // Level L is 0b01 in the format information.
138
+ const bits = bch((1 << 3) | mask, 10, 0x537) ^ 0x5412
139
+ const bit = (i: number) => ((bits >>> i) & 1) === 1
140
+ for (let i = 0; i <= 5; i++) set(8, i, bit(i))
141
+ set(8, 7, bit(6))
142
+ set(8, 8, bit(7))
143
+ set(7, 8, bit(8))
144
+ for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i))
145
+ for (let i = 0; i < 8; i++) set(size - 1 - i, 8, bit(i))
146
+ for (let i = 8; i < 15; i++) set(8, size - 15 + i, bit(i))
147
+ set(8, size - 8, true)
148
+ }
149
+
150
+ // Appends the BCH remainder of `data` for a generator polynomial of the given degree.
151
+ function bch(data: number, degree: number, generator: number) {
152
+ let remainder = data
153
+ for (let i = 0; i < degree; i++) remainder = (remainder << 1) ^ ((remainder >>> (degree - 1)) * generator)
154
+ return (data << degree) | remainder
155
+ }
156
+
157
+ function dataCodewords(bytes: Uint8Array, version: number) {
158
+ const capacity = dataCapacity(version)
159
+ const bits: number[] = []
160
+ const append = (value: number, length: number) => {
161
+ for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1)
162
+ }
163
+ append(0b0100, 4)
164
+ append(bytes.length, version < 10 ? 8 : 16)
165
+ bytes.forEach((byte) => append(byte, 8))
166
+ append(0, Math.min(4, capacity * 8 - bits.length))
167
+ append(0, (8 - (bits.length % 8)) % 8)
168
+ const data = Array.from({ length: bits.length / 8 }, (_, i) =>
169
+ bits.slice(i * 8, i * 8 + 8).reduce((byte, bit) => (byte << 1) | bit, 0),
170
+ )
171
+ return [...data, ...Array.from({ length: capacity - data.length }, (_, i) => (i % 2 === 0 ? 0xec : 0x11))]
172
+ }
173
+
174
+ function addErrorCorrection(data: number[], version: number) {
175
+ const blocks = BLOCKS[version - 1]
176
+ const ecc = ECC_PER_BLOCK[version - 1]
177
+ const raw = Math.floor(rawModules(version) / 8)
178
+ // The first `short` blocks hold one data codeword fewer than the rest.
179
+ const short = blocks - (raw % blocks)
180
+ const shortLength = Math.floor(raw / blocks) - ecc
181
+ const divisor = reedSolomonDivisor(ecc)
182
+ const split = Array.from({ length: blocks }, (_, i) => {
183
+ const start = i * shortLength + Math.max(0, i - short)
184
+ return data.slice(start, start + shortLength + (i < short ? 0 : 1))
185
+ })
186
+ const interleave = (rows: number[][], length: number) =>
187
+ Array.from({ length }, (_, i) => rows.flatMap((row) => (i < row.length ? [row[i]] : []))).flat()
188
+ return [
189
+ ...interleave(split, shortLength + 1),
190
+ ...interleave(
191
+ split.map((block) => reedSolomonRemainder(block, divisor)),
192
+ ecc,
193
+ ),
194
+ ]
195
+ }
196
+
197
+ function drawCodewords(modules: boolean[][], reserved: boolean[][], codewords: number[]) {
198
+ const size = modules.length
199
+ let i = 0
200
+ for (let right = size - 1; right >= 1; right -= 2) {
201
+ // The vertical timing pattern takes column 6, so the column pair shifts left past it.
202
+ if (right === 6) right = 5
203
+ for (let vertical = 0; vertical < size; vertical++)
204
+ for (let j = 0; j < 2; j++) {
205
+ const x = right - j
206
+ const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical
207
+ if (reserved[y][x] || i >= codewords.length * 8) continue
208
+ modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) === 1
209
+ i++
210
+ }
211
+ }
212
+ }
213
+
214
+ function penalty(modules: boolean[][]) {
215
+ const size = modules.length
216
+ const columns = modules.map((_, x) => modules.map((row) => row[x]))
217
+ const lines = [...modules, ...columns].reduce((sum, line) => sum + linePenalty(line), 0)
218
+ // Each 2x2 block of one colour, found from its bottom-right module.
219
+ const boxes = modules
220
+ .slice(1)
221
+ .flatMap((row, y) =>
222
+ row.slice(1).filter((dark, x) => dark === row[x] && dark === modules[y][x] && dark === modules[y][x + 1]),
223
+ ).length
224
+ const dark = modules.flat().filter(Boolean).length
225
+ const total = size * size
226
+ return lines + boxes * 3 + (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10
227
+ }
228
+
229
+ // Scores runs of five or more same-coloured modules, and 1:1:3:1:1 finder-like patterns with 4 light modules on a side.
230
+ function linePenalty(line: boolean[]) {
231
+ const size = line.length
232
+ const history = [0, 0, 0, 0, 0, 0, 0]
233
+ const push = (length: number) => {
234
+ history.pop()
235
+ history.unshift(history[0] === 0 ? length + size : length)
236
+ }
237
+ const finders = () => {
238
+ const n = history[1]
239
+ const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n
240
+ return (
241
+ (core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) +
242
+ (core && history[6] >= n * 4 && history[0] >= n ? 1 : 0)
243
+ )
244
+ }
245
+ let result = 0
246
+ let color = false
247
+ let run = 0
248
+ for (const dark of line) {
249
+ if (dark === color) {
250
+ run++
251
+ if (run === 5) result += 3
252
+ if (run > 5) result++
253
+ continue
254
+ }
255
+ push(run)
256
+ if (!color) result += finders() * 40
257
+ color = dark
258
+ run = 1
259
+ }
260
+ if (color) {
261
+ push(run)
262
+ run = 0
263
+ }
264
+ push(run + size)
265
+ return result + finders() * 40
266
+ }
267
+
268
+ function reedSolomonDivisor(degree: number) {
269
+ const result = Array<number>(degree).fill(0)
270
+ result[degree - 1] = 1
271
+ let root = 1
272
+ for (let i = 0; i < degree; i++) {
273
+ for (let j = 0; j < degree; j++) {
274
+ result[j] = multiply(result[j], root)
275
+ if (j + 1 < degree) result[j] ^= result[j + 1]
276
+ }
277
+ root = multiply(root, 2)
278
+ }
279
+ return result
280
+ }
281
+
282
+ function reedSolomonRemainder(data: number[], divisor: number[]) {
283
+ return data.reduce(
284
+ (remainder, byte) => {
285
+ const factor = byte ^ remainder[0]
286
+ return [...remainder.slice(1), 0].map((value, i) => value ^ multiply(divisor[i], factor))
287
+ },
288
+ divisor.map(() => 0),
289
+ )
290
+ }
291
+
292
+ // Multiplies in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1.
293
+ function multiply(x: number, y: number) {
294
+ let z = 0
295
+ for (let i = 7; i >= 0; i--) {
296
+ z = (z << 1) ^ ((z >>> 7) * 0x11d)
297
+ z ^= ((y >>> i) & 1) * x
298
+ }
299
+ return z
300
+ }
301
+
302
+ function rawModules(version: number) {
303
+ const base = (16 * version + 128) * version + 64
304
+ if (version < 2) return base
305
+ const count = Math.floor(version / 7) + 2
306
+ return base - ((25 * count - 10) * count - 55) - (version >= 7 ? 36 : 0)
307
+ }
308
+
309
+ function dataCapacity(version: number) {
310
+ return Math.floor(rawModules(version) / 8) - ECC_PER_BLOCK[version - 1] * BLOCKS[version - 1]
311
+ }
312
+
313
+ function addBorder(modules: boolean[][], border: number) {
314
+ const width = modules.length + border * 2
315
+ const blank = () => Array<boolean>(width).fill(false)
316
+ const edge = Array.from({ length: border }, blank)
317
+ const padding = Array<boolean>(border).fill(false)
318
+ return [...edge, ...modules.map((row) => [...padding, ...row, ...padding]), ...Array.from({ length: border }, blank)]
319
+ }
320
+
321
+ function escapeAttribute(value: string) {
322
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
323
+ }
package/src/record.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Plain-record narrowing. Excludes arrays so JSON object checks don't accept tuples as key/value bags. */
2
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
3
+ typeof value === "object" && value !== null && !Array.isArray(value)
@@ -0,0 +1,87 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { retry } from "./retry.js"
3
+
4
+ describe("client retry", () => {
5
+ test("retries transient failures up to the configured attempt count", async () => {
6
+ const failures: string[] = []
7
+ const value = await retry(
8
+ async () => {
9
+ failures.push("attempt")
10
+ if (failures.length < 3) throw new Error("Failed to fetch")
11
+ return "ready"
12
+ },
13
+ { delay: 0 },
14
+ )
15
+
16
+ expect(value).toBe("ready")
17
+ expect(failures).toHaveLength(3)
18
+ })
19
+
20
+ test("retries a real network failure wrapped as the cause of a transport error", async () => {
21
+ const server = Bun.listen({
22
+ hostname: "127.0.0.1",
23
+ port: 0,
24
+ socket: {
25
+ // Reset only once the request has arrived. Resetting on accept races the client's request
26
+ // write, and on Windows a lost race surfaces as a write or connect failure instead of a
27
+ // connection reset.
28
+ data(socket) {
29
+ socket.terminate()
30
+ },
31
+ },
32
+ })
33
+ const failures: unknown[] = []
34
+ try {
35
+ await expect(
36
+ retry(
37
+ () =>
38
+ fetch(`http://127.0.0.1:${server.port}/api/project`).catch((cause) => {
39
+ failures.push(cause)
40
+ throw new Error("Transport", { cause })
41
+ }),
42
+ { delay: 0 },
43
+ ),
44
+ ).rejects.toThrow("Transport")
45
+ } finally {
46
+ server.stop(true)
47
+ }
48
+ expect(failures).toHaveLength(3)
49
+ expect(failures.every((cause) => cause instanceof TypeError)).toBe(true)
50
+ })
51
+
52
+ test("does not retry a transport error whose cause is not transient", async () => {
53
+ const failures: string[] = []
54
+ await expect(
55
+ retry(async () => {
56
+ failures.push("attempt")
57
+ throw new Error("Transport", { cause: new Error("invalid response") })
58
+ }),
59
+ ).rejects.toThrow("Transport")
60
+ expect(failures).toHaveLength(1)
61
+ })
62
+
63
+ test("does not retry other failures", async () => {
64
+ const failures: string[] = []
65
+ await expect(
66
+ retry(async () => {
67
+ failures.push("attempt")
68
+ throw new Error("invalid response")
69
+ }),
70
+ ).rejects.toThrow("invalid response")
71
+ expect(failures).toHaveLength(1)
72
+ })
73
+
74
+ test("uses a caller-owned retry condition", async () => {
75
+ const failures: string[] = []
76
+ await expect(
77
+ retry(
78
+ async () => {
79
+ failures.push("attempt")
80
+ throw new Error("retry me")
81
+ },
82
+ { attempts: 2, delay: 0, retryIf: () => true },
83
+ ),
84
+ ).rejects.toThrow("retry me")
85
+ expect(failures).toHaveLength(2)
86
+ })
87
+ })