@ultimat3/core 31.6.0 → 31.7.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.
@@ -3,149 +3,30 @@
3
3
  // copy: responsive variants, blur placeholders and PWA icons are the same three steps with
4
4
  // different numbers, and a framework that generated them twice would drift twice.
5
5
 
6
- import { assert } from '../assert';
7
- import { composeOnto, layOut, type ResizeSpec } from './canvas';
8
- import { imageFromBunError, imageUnsupported } from './errors';
9
- import { unshared } from './png-bytes';
10
- import { decodeImage, encodeImage } from './png-pixels';
11
6
  import { IMAGE_MIME_TYPES, type ImageFormat } from './probe';
12
- import { cropRaster, type ImageRegion, MAX_IMAGE_PIXELS } from './raster';
7
+ import { rasterTransform } from './raster-pool';
8
+ import { bunImage, type ImageTransformSpec, run } from './transform-inline';
9
+
10
+ export type { DecodableFormat, EncodableFormat, ImageTransformSpec } from './transform-inline';
11
+ export {
12
+ assertFiniteImageQuality,
13
+ canDecode,
14
+ canEncode,
15
+ DECODABLE_FORMATS,
16
+ DEFAULT_IMAGE_QUALITY,
17
+ ENCODABLE_FORMATS,
18
+ } from './transform-inline';
13
19
 
14
20
  /**
15
- * What the pipeline can produce, on every platform, byte for byte. `Bun.Image` also reaches
16
- * HEIC and AVIF **through an OS codec** — Apple's ImageIO, Windows' WIC — which is a variant
17
- * that exists on the developer's laptop and not on the Linux node that serves it, under a key
18
- * that says nothing about which machine minted it. `backend = 'bun'` below refuses that trade,
19
- * so those two formats are refused HERE rather than silently on one deploy out of two: a caller
20
- * that needs them routes transforms through a driver (`@ultimat3/seo`'s `ImageTransformDriver`).
21
+ * The whole pipeline in one call: decode, resize, compose, encode — in `raster-worker.ts`, off the
22
+ * event loop. Measured on a 4096² source, the inline raster hops blocked the loop 98-1,945 ms; a
23
+ * request waiting behind them waited that long. The bytes are `transformInline`'s, unchanged.
21
24
  */
22
- export const ENCODABLE_FORMATS = ['png', 'jpeg', 'webp'] as const;
23
- /** What the static codecs read. `svg` is markup, and `probeImage` measures it without decoding. */
24
- export const DECODABLE_FORMATS = ['png', 'jpeg', 'webp', 'gif'] as const;
25
-
26
- export type DecodableFormat = (typeof DECODABLE_FORMATS)[number];
27
- export type EncodableFormat = (typeof ENCODABLE_FORMATS)[number];
28
-
29
- export const canDecode = (format: string): format is DecodableFormat =>
30
- (DECODABLE_FORMATS as readonly string[]).includes(format);
31
-
32
- export const canEncode = (format: string): format is EncodableFormat =>
33
- (ENCODABLE_FORMATS as readonly string[]).includes(format);
34
-
35
- /** 1-100, lossy formats only. Bun's own default, pinned here so output cannot drift with it. */
36
- export const DEFAULT_IMAGE_QUALITY = 80;
37
-
38
- /**
39
- * The encoder CLAMPS and never refuses, which is why this is a screen and not a comment. Exported
40
- * because `@ultimat3/storage` mints a variant KEY from the same number without ever reaching this
41
- * pipeline — two screens that refuse different qualities would mint `q150` keys for bytes this
42
- * encoder goes on to refuse, which is the dead-on-arrival shape `buildSignedUrl`'s own
43
- * `finiteCount` screen already exists for — that package held a private `assertFiniteSignedUrlBound`
44
- * until this sweep collapsed it onto the tier-0 check. Measured
45
- * on a 3x2 PNG re-encoded as JPEG: quality 80 wrote 663 bytes, and `NaN`, `-5` and `0` each wrote
46
- * 635 — the worst encoding the codec can make — while `Infinity` and `1e9` each wrote 719. Every
47
- * one of them silently. `Number(url.searchParams.get('q'))` is `NaN` when the parameter is absent,
48
- * so the degraded image is the one an unparameterised URL gets.
49
- */
50
- export const assertFiniteImageQuality = (quality: number): number => {
51
- assert(
52
- Number.isInteger(quality) && quality >= 1 && quality <= 100,
53
- `image quality is ${String(quality)}, and the encoder clamps rather than refusing: it must be a whole number from 1 to 100`,
54
- `pass a whole quality from 1 to 100 — transformImageBytes(bytes, { quality: ${String(DEFAULT_IMAGE_QUALITY)} }) — and parse a query value before you pass it`,
55
- );
56
- return quality;
57
- };
58
-
59
- const encodeFix =
60
- "request 'png', 'jpeg' or 'webp', or route the transform through an ImageTransformDriver (a " +
61
- 'CDN or an external encoder) that can produce it';
62
-
63
- export interface ImageTransformSpec extends ResizeSpec {
64
- /** Defaults to the source's format when the pipeline can write it, PNG otherwise. */
65
- readonly format?: ImageFormat | undefined;
66
- /** 1-100, lossy formats only. */
67
- readonly quality?: number | undefined;
68
- }
69
-
70
- /**
71
- * `backend = 'bun'` is set on every call, not once at import. It forces the statically-linked
72
- * codecs and the Highway geometry kernels on every OS, which is what makes the same source and
73
- * the same spec the same BYTES on a laptop and on the node — and `variantKey` is content-
74
- * addressed, so a variant that re-encoded differently per platform would be a cache that never
75
- * hits and a hash that never agrees. Per call rather than at import because the property is
76
- * process-global and writable: an app that flips it back would otherwise silently win.
77
- */
78
- function bunImage(bytes: Uint8Array): Bun.Image {
79
- Bun.Image.backend = 'bun';
80
- // The decompression-bomb ceiling, enforced by the decoder from the header before it allocates
81
- // — the same number `probeImage` refuses at, so the two answers cannot disagree.
82
- return new Bun.Image(unshared(bytes), { maxPixels: MAX_IMAGE_PIXELS });
83
- }
84
-
85
- function withFormat(image: Bun.Image, format: EncodableFormat, quality: number): Bun.Image {
86
- if (format === 'png') return image.png();
87
- if (format === 'jpeg') return image.jpeg({ quality });
88
- return image.webp({ quality });
89
- }
90
-
91
- /** Every rejection from `Bun.Image` becomes one of the three `X_IMAGE_*` codes, never a bare one. */
92
- async function run<T>(doing: string, work: () => Promise<T>): Promise<T> {
93
- try {
94
- return await work();
95
- } catch (error) {
96
- throw imageFromBunError(error, doing);
97
- }
98
- }
99
-
100
- /**
101
- * `region` of the source as PNG. `Bun.Image` has no crop, so the source is decoded to a raster
102
- * (within the same `MAX_IMAGE_PIXELS` its header was held to) and the region copied out of it.
103
- */
104
- async function croppedPng(bytes: Uint8Array, region: ImageRegion): Promise<Uint8Array> {
105
- const whole = await run('decoding the image', () => bunImage(bytes).png().bytes());
106
- return encodeImage(cropRaster(decodeImage(whole), region));
107
- }
108
-
109
- /** The whole pipeline in one call: decode, resize, compose, encode. */
110
- export async function transformImageBytes(
25
+ export function transformImageBytes(
111
26
  bytes: Uint8Array,
112
27
  spec: ImageTransformSpec = {},
113
28
  ): Promise<Uint8Array> {
114
- const { format } = spec;
115
- // The spec alone answers "can this be written?", so answer it here — decoding and resampling
116
- // 64 megapixels first, only to refuse at the encoder, is work nobody can use.
117
- if (format !== undefined && !canEncode(format)) {
118
- throw imageUnsupported(`encoding ${format} is not built in`, encodeFix, { format });
119
- }
120
- const quality = assertFiniteImageQuality(spec.quality ?? DEFAULT_IMAGE_QUALITY);
121
- const source = await run('reading the image header', () => bunImage(bytes).metadata());
122
- const output: EncodableFormat = format ?? (canEncode(source.format) ? source.format : 'png');
123
- const layout = layOut(source, spec);
124
- const { box, drawn, crop } = layout;
125
- // The cropped region stands in for the source from here on: what is resampled is what shows.
126
- const input = crop === undefined ? bytes : await croppedPng(bytes, crop);
127
- const inputSize = crop ?? source;
128
-
129
- if (!layout.needsCanvas) {
130
- return run('transforming the image', () => {
131
- const image = bunImage(input);
132
- if (box.width !== inputSize.width || box.height !== inputSize.height) {
133
- image.resize(box.width, box.height, { fit: 'fill' });
134
- }
135
- return withFormat(image, output, quality).bytes();
136
- });
137
- }
138
-
139
- // The letterbox / padding / crop path. `Bun.Image` resamples but has no compositor, so the
140
- // artwork comes back as PNG, is placed on the canvas here, and goes back through Bun to be
141
- // written. Back through Bun even when the output IS png: `png-pixels.ts` writes filter 0, which
142
- // is 1.2-1.8x libspng's bytes on a real icon (measured), and one writer for everything this
143
- // function returns is also what makes "same input, same bytes" rest on the static codecs alone.
144
- const art = await run('resampling the image', () =>
145
- bunImage(input).resize(drawn.width, drawn.height, { fit: 'fill' }).png().bytes(),
146
- );
147
- const composed = encodeImage(composeOnto(decodeImage(art), layout));
148
- return run('encoding the image', () => withFormat(bunImage(composed), output, quality).bytes());
29
+ return rasterTransform(bytes, spec);
149
30
  }
150
31
 
151
32
  /** Chunked because spreading a whole image into `String.fromCharCode` overflows the stack. */
@@ -0,0 +1,185 @@
1
+ // Single responsibility: where `transformImageBytes` runs — one lazy `raster-worker.ts` Worker,
2
+ // requests answered by id, held open only while one is pending. Where no Worker can start, inline
3
+ // on this thread, and on the web role only under `RASTER_SYNC_PIXELS`.
4
+
5
+ import { isCompiledBundle } from '../bunfs';
6
+ import { renderThrowable } from '../error-render';
7
+ import { UltimateError } from '../errors';
8
+ import { logger } from '../logger';
9
+ import { type Role, resolveRole } from '../roles';
10
+ import { errorFromWire, isRasterAnswer, isRasterReady, type RasterRequest } from './raster-wire';
11
+ import { RASTER_WORKER_DEFINE } from './raster-worker-bundle';
12
+ import { type ImageTransformSpec, transformInline } from './transform-inline';
13
+
14
+ /**
15
+ * The most pixels the web role's event loop inflates plus deflates inline. Measured on a 4096²
16
+ * source (2026-11-11): deflate up to 116 ms per megapixel on noisy pixels, inflate up to 58. At
17
+ * the worse rate, 409,600 pixels (640²) is ≤ 48 ms — under the 50 ms the plan holds the loop to.
18
+ */
19
+ export const RASTER_SYNC_PIXELS = 409_600;
20
+
21
+ export interface RasterPoolOptions {
22
+ /** Builds the Worker. Injected by tests; one that throws is "no Worker can start here". */
23
+ readonly spawn?: (() => Worker) | undefined;
24
+ /** This process's role, read per inline call. Default `resolveRole()`. */
25
+ readonly role?: (() => Role) | undefined;
26
+ }
27
+
28
+ export interface RasterPool {
29
+ transform(bytes: Uint8Array, spec: ImageTransformSpec): Promise<Uint8Array>;
30
+ /** Ends the Worker; the next transform starts a new one. */
31
+ close(): void;
32
+ }
33
+
34
+ interface Pending {
35
+ /** The CALLER's bytes, never the transferred copy: the inline fallback runs on these. */
36
+ readonly bytes: Uint8Array;
37
+ readonly spec: ImageTransformSpec;
38
+ readonly resolve: (bytes: Uint8Array) => void;
39
+ readonly reject: (error: unknown) => void;
40
+ }
41
+
42
+ /**
43
+ * Bun's `Worker` has `ref()`/`unref()`; the DOM lib type this tree compiles against declares
44
+ * neither, so they are read off the value rather than claimed by a cast.
45
+ */
46
+ function setHeld(worker: Worker, held: boolean): void {
47
+ const method: unknown = Reflect.get(worker, held ? 'ref' : 'unref');
48
+ if (typeof method === 'function') method.call(worker);
49
+ }
50
+
51
+ // Replaced with the worker's embedded path by a compile that adds `rasterWorkerBundle()`'s
52
+ // entrypoint; declared by nothing at run time, hence the `typeof` guard.
53
+ declare const ULTIMATE_RASTER_WORKER: string | undefined;
54
+
55
+ function spawnRasterWorker(): Worker {
56
+ if (!isCompiledBundle(import.meta.dir)) {
57
+ return new Worker(new URL('./raster-worker.ts', import.meta.url).href);
58
+ }
59
+ // Bundled, `import.meta.url` is the EXECUTABLE's, so the worker is found by the path its compile
60
+ // embedded it at — and a compile that never added it has no worker to find.
61
+ if (typeof ULTIMATE_RASTER_WORKER === 'string') return new Worker(ULTIMATE_RASTER_WORKER);
62
+ throw new UltimateError({
63
+ code: 'X_INTERNAL',
64
+ cause: `this executable was compiled without the raster worker entrypoint, so ${RASTER_WORKER_DEFINE} is not defined`,
65
+ fix: 'rasterWorkerBundle([entry]) # from @ultimat3/core: add its entrypoint beside the compile entry and merge its define (packages/core/src/image/raster-worker-bundle.ts)',
66
+ });
67
+ }
68
+
69
+ /** Said once per pool, at warn: a process that degrades to inline must never do it silently. */
70
+ function warnInline(reason: unknown): void {
71
+ logger.warn('image.raster_worker_unavailable', {
72
+ reason: renderThrowable(reason),
73
+ effect: `transforms run inline on this thread; the web role refuses a raster hop over ${RASTER_SYNC_PIXELS} pixels (X_IMAGE_RASTER_BUDGET)`,
74
+ });
75
+ }
76
+
77
+ export function rasterPool(options: RasterPoolOptions = {}): RasterPool {
78
+ const spawn = options.spawn ?? spawnRasterWorker;
79
+ const roleOf = options.role ?? (() => resolveRole());
80
+ const pending = new Map<number, Pending>();
81
+ let worker: Worker | undefined;
82
+ /** Set by the Worker's ready message: it LOADED, so a later death is a crash, not a missing file. */
83
+ let loaded = false;
84
+ let inline = false;
85
+ let nextId = 0;
86
+
87
+ const runInline = (bytes: Uint8Array, spec: ImageTransformSpec): Promise<Uint8Array> =>
88
+ transformInline(bytes, spec, roleOf() === 'web' ? RASTER_SYNC_PIXELS : undefined);
89
+
90
+ const settle = (id: number): Pending | undefined => {
91
+ const one = pending.get(id);
92
+ pending.delete(id);
93
+ if (pending.size === 0 && worker !== undefined) setHeld(worker, false);
94
+ return one;
95
+ };
96
+
97
+ /**
98
+ * The Worker is gone — an uncaught error, an exit with none, or `close()` — so everything it
99
+ * owed settles now: a promise left pending is a caller hung forever and a Worker held open.
100
+ * Once per Worker: `gone` ignores the second of its `error` + `close` pair.
101
+ */
102
+ const lost = (gone: Worker, reason: string, closing: boolean): void => {
103
+ if (worker !== gone) return;
104
+ worker = undefined;
105
+ const failed = [...pending.values()];
106
+ pending.clear();
107
+ gone.terminate();
108
+ // Never said ready: the file could not load, so it never will — this process goes inline, and
109
+ // what was waiting runs inline now rather than failing for a thread that was never there.
110
+ if (!loaded && !closing) {
111
+ inline = true;
112
+ warnInline(reason);
113
+ for (const one of failed) runInline(one.bytes, one.spec).then(one.resolve, one.reject);
114
+ return;
115
+ }
116
+ const crash = new UltimateError({
117
+ code: 'X_INTERNAL',
118
+ cause: `the raster worker ended with ${failed.length} transform(s) in flight: ${reason}`,
119
+ fix: 'bun test ./packages/core/src/image/ # reproduces the transform if it repeats; one failure alone is retried as is — the next transform starts a new worker',
120
+ });
121
+ for (const one of failed) one.reject(crash);
122
+ };
123
+
124
+ const listen = (target: Worker): void => {
125
+ target.addEventListener('message', (event: MessageEvent<unknown>) => {
126
+ if (isRasterReady(event.data)) {
127
+ loaded = true;
128
+ return;
129
+ }
130
+ if (!isRasterAnswer(event.data)) return;
131
+ const one = settle(event.data.id);
132
+ if (one === undefined) return;
133
+ if (event.data.ok) one.resolve(event.data.bytes);
134
+ else one.reject(errorFromWire(event.data.error));
135
+ });
136
+ target.addEventListener('error', (event: ErrorEvent) => lost(target, event.message, false));
137
+ target.addEventListener('close', () => lost(target, 'it exited', false));
138
+ };
139
+
140
+ const started = (): Worker | undefined => {
141
+ if (inline) return undefined;
142
+ if (worker !== undefined) return worker;
143
+ loaded = false;
144
+ try {
145
+ worker = spawn();
146
+ } catch (error) {
147
+ inline = true;
148
+ warnInline(error);
149
+ return undefined;
150
+ }
151
+ listen(worker);
152
+ setHeld(worker, false);
153
+ return worker;
154
+ };
155
+
156
+ return {
157
+ transform(bytes, spec) {
158
+ const target = started();
159
+ if (target === undefined) return runInline(bytes, spec);
160
+ return new Promise<Uint8Array>((resolve, reject) => {
161
+ nextId += 1;
162
+ // The caller keeps its bytes (`warmVariants` reuses one source), so the Worker gets a COPY
163
+ // of the VIEW, transferred: structured-cloning it instead blocked this thread ~60 ms on a
164
+ // 42 MB PNG (measured). `new Uint8Array(view)`, never `.slice()` — a Node `Buffer`'s slice
165
+ // is a subarray, so transferring it detached the caller's whole parent buffer.
166
+ const request: RasterRequest = { id: nextId, bytes: new Uint8Array(bytes), spec };
167
+ pending.set(request.id, { bytes, spec, resolve, reject });
168
+ // Held open only while an answer is owed: an idle Worker never keeps a process alive.
169
+ if (pending.size === 1) setHeld(target, true);
170
+ target.postMessage(request, [request.bytes.buffer]);
171
+ });
172
+ },
173
+ close() {
174
+ if (worker !== undefined) lost(worker, 'the pool was closed', true);
175
+ },
176
+ };
177
+ }
178
+
179
+ let shared: RasterPool | undefined;
180
+
181
+ /** The process's one pool, built at the first transform — nothing runs at import. */
182
+ export function rasterTransform(bytes: Uint8Array, spec: ImageTransformSpec): Promise<Uint8Array> {
183
+ shared ??= rasterPool();
184
+ return shared.transform(bytes, spec);
185
+ }
@@ -0,0 +1,100 @@
1
+ // Single responsibility: what crosses the raster Worker's boundary, both ways — the request, the
2
+ // answer, and a coded error flattened to a clonable record and rebuilt as the SAME class on the
3
+ // other side, so `instanceof ImageUnsupportedError` holds whichever thread raised it.
4
+
5
+ import { renderThrowable } from '../error-render';
6
+ import { isUltimateError, UltimateError } from '../errors';
7
+ import { isJsonObject } from '../json-object';
8
+ import {
9
+ ImageDecodeFailedError,
10
+ ImageRasterBudgetError,
11
+ ImageTooLargeError,
12
+ ImageUnsupportedError,
13
+ } from './errors';
14
+ import type { ImageTransformSpec } from './transform-inline';
15
+
16
+ export interface RasterRequest {
17
+ readonly id: number;
18
+ readonly bytes: Uint8Array;
19
+ readonly spec: ImageTransformSpec;
20
+ }
21
+
22
+ export interface WireError {
23
+ readonly code: string;
24
+ readonly cause: string;
25
+ readonly fix: string;
26
+ readonly meta?: Readonly<Record<string, unknown>> | undefined;
27
+ }
28
+
29
+ export type RasterAnswer =
30
+ | { readonly id: number; readonly ok: true; readonly bytes: Uint8Array }
31
+ | { readonly id: number; readonly ok: false; readonly error: WireError };
32
+
33
+ /**
34
+ * The spec's FIELDS are not checked here: `transformInline` screens every one of them (dimension,
35
+ * padding, colour, quality, format) and refuses with its own code — a second screen would be a
36
+ * second set of messages for the same mistakes.
37
+ */
38
+ export function isRasterRequest(value: unknown): value is RasterRequest {
39
+ return (
40
+ isJsonObject(value) &&
41
+ typeof value['id'] === 'number' &&
42
+ value['bytes'] instanceof Uint8Array &&
43
+ isJsonObject(value['spec'])
44
+ );
45
+ }
46
+
47
+ /** The Worker's first message: its module evaluated, so it is a Worker that can answer. */
48
+ export const RASTER_READY = Object.freeze({ ready: true });
49
+
50
+ export function isRasterReady(value: unknown): boolean {
51
+ return isJsonObject(value) && value['ready'] === true;
52
+ }
53
+
54
+ export function isRasterAnswer(value: unknown): value is RasterAnswer {
55
+ if (!isJsonObject(value) || typeof value['id'] !== 'number') return false;
56
+ if (value['ok'] === true) return value['bytes'] instanceof Uint8Array;
57
+ return value['ok'] === false && isWireError(value['error']);
58
+ }
59
+
60
+ function isWireError(value: unknown): value is WireError {
61
+ return (
62
+ isJsonObject(value) &&
63
+ typeof value['code'] === 'string' &&
64
+ typeof value['cause'] === 'string' &&
65
+ typeof value['fix'] === 'string' &&
66
+ (value['meta'] === undefined || isJsonObject(value['meta']))
67
+ );
68
+ }
69
+
70
+ /** A thrown value as a record `postMessage` can clone. Uncoded is a defect: `X_INTERNAL`. */
71
+ export function wireError(error: unknown): WireError {
72
+ if (isUltimateError(error)) {
73
+ return { code: error.code, cause: error.cause, fix: error.fix, meta: error.meta };
74
+ }
75
+ return {
76
+ code: 'X_INTERNAL',
77
+ cause: `the raster worker threw an uncoded ${renderThrowable(error)}`,
78
+ fix: 'bun test ./packages/core/src/image/ # an uncoded throw in the transform is a framework defect; the failing case names it',
79
+ };
80
+ }
81
+
82
+ type ImageErrorClass = new (
83
+ cause: string,
84
+ fix: string,
85
+ meta?: Readonly<Record<string, unknown>>,
86
+ ) => UltimateError;
87
+
88
+ const IMAGE_CLASSES: Readonly<Record<string, ImageErrorClass>> = {
89
+ [ImageDecodeFailedError.code]: ImageDecodeFailedError,
90
+ [ImageRasterBudgetError.code]: ImageRasterBudgetError,
91
+ [ImageTooLargeError.code]: ImageTooLargeError,
92
+ [ImageUnsupportedError.code]: ImageUnsupportedError,
93
+ };
94
+
95
+ /** The record rebuilt on this side: an image code as its own class, any other as its code. */
96
+ export function errorFromWire(wire: WireError): UltimateError {
97
+ const imageClass = Object.hasOwn(IMAGE_CLASSES, wire.code) ? IMAGE_CLASSES[wire.code] : undefined;
98
+ if (imageClass !== undefined) return new imageClass(wire.cause, wire.fix, wire.meta);
99
+ return new UltimateError({ code: wire.code, cause: wire.cause, fix: wire.fix, meta: wire.meta });
100
+ }
@@ -0,0 +1,85 @@
1
+ // Single responsibility: what a `bun build --compile` that BUNDLES core adds so the raster Worker
2
+ // starts inside the executable — the worker file as an extra entrypoint, the build `root`, and the
3
+ // define naming where Bun puts it. Bun detects no `new Worker(…)` target on its own (measured, 1.4.4).
4
+
5
+ // why: Bun has no path primitives; the embedded path is a relative() between two real paths.
6
+ import * as hostPath from 'node:path';
7
+ import { assert } from '../assert';
8
+
9
+ /** A path flavour — `node:path` itself, or its `win32` / `posix` twin. */
10
+ type PlatformPath = typeof hostPath.posix;
11
+
12
+ /** The define `raster-pool.ts` reads inside a compiled executable — one name, both sides. */
13
+ export const RASTER_WORKER_DEFINE = 'ULTIMATE_RASTER_WORKER';
14
+
15
+ /** The worker file on disk: the extra entrypoint. */
16
+ export const RASTER_WORKER_ENTRY: string = hostPath.resolve(import.meta.dir, 'raster-worker.ts');
17
+
18
+ export interface RasterWorkerBundle {
19
+ /** Pass beside the executable's own entry: `entrypoints: [entry, bundle.entrypoint]`. */
20
+ readonly entrypoint: string;
21
+ /**
22
+ * Pass as `Bun.build`'s `root`. Stated rather than left to Bun's inference: the define is a path
23
+ * relative to it, and a guessed root that differs by one directory is a Worker that never loads.
24
+ */
25
+ readonly root: string;
26
+ /** Merge into the build's `define`. */
27
+ readonly define: Readonly<Record<string, string>>;
28
+ }
29
+
30
+ /**
31
+ * The deepest directory holding every path, or `undefined` when they share none — two Windows
32
+ * drives. A drive root keeps its separator: `D:` alone means "the current directory on D:".
33
+ */
34
+ function commonDirectory(path: PlatformPath, paths: readonly string[]): string | undefined {
35
+ const { sep } = path;
36
+ // Windows compares paths without case (`C:\` is `c:\`); POSIX does not.
37
+ const samePart = (a: string | undefined, b: string | undefined): boolean =>
38
+ sep === '\\' ? a?.toLowerCase() === b?.toLowerCase() : a === b;
39
+ const split = paths.map((one) => one.split(sep));
40
+ const first = split[0] ?? [];
41
+ let depth = 0;
42
+ // Every path is a FILE, so its last segment never counts as a shared directory.
43
+ while (
44
+ depth < first.length - 1 &&
45
+ split.every((parts) => depth < parts.length - 1 && samePart(parts[depth], first[depth]))
46
+ ) {
47
+ depth += 1;
48
+ }
49
+ if (depth === 0) return undefined;
50
+ const joined = first.slice(0, depth).join(sep);
51
+ return depth === 1 ? `${joined}${sep}` : joined;
52
+ }
53
+
54
+ /**
55
+ * For a compile whose own entrypoints are `entrypoints`: the worker entrypoint to add, the root to
56
+ * build from, and the define that tells the bundled `raster-pool.ts` its path. Bun embeds each
57
+ * entrypoint at its path relative to `root` and resolves a `./` specifier from there (measured:
58
+ * with `root` set, `new Worker('./proj/b/w.ts')` starts the worker compiled from
59
+ * `<root>/proj/b/w.ts`, and `./b/w.ts` does not).
60
+ */
61
+ export function rasterWorkerBundle(entrypoints: readonly string[]): RasterWorkerBundle {
62
+ return workerLayout(hostPath, entrypoints, RASTER_WORKER_ENTRY);
63
+ }
64
+
65
+ /** The rule with the platform's path flavour passed in, so the Windows half is tested on any host. */
66
+ export function workerLayout(
67
+ path: PlatformPath,
68
+ entrypoints: readonly string[],
69
+ worker: string,
70
+ ): RasterWorkerBundle {
71
+ const all = [...entrypoints.map((entry) => path.resolve(entry)), worker];
72
+ const root = commonDirectory(path, all);
73
+ assert(
74
+ root !== undefined,
75
+ `the compile's entrypoints and @ultimat3/core share no directory (${all.join(', ')}), so no build root embeds the raster worker at a path the executable can name`,
76
+ 'move the entry onto the same drive as node_modules/@ultimat3/core, then compile again: bun run scripts/compile-x.ts --outfile <path>',
77
+ );
78
+ // Forward slashes on every platform: it is a module specifier, not a file-system path.
79
+ const inside = path.relative(root, worker).split(path.sep).join('/');
80
+ return {
81
+ entrypoint: worker,
82
+ root,
83
+ define: { [RASTER_WORKER_DEFINE]: JSON.stringify(`./${inside}`) },
84
+ };
85
+ }
@@ -0,0 +1,46 @@
1
+ // Single responsibility: the raster Worker's entry — one `transformInline` per request, answered by
2
+ // id. Its own thread, so the inflate and deflate in `png-pixels.ts` block nobody's event loop.
3
+ // Loaded by `raster-pool.ts` through `new Worker(url)`; starts itself only off the main thread, so a
4
+ // test imports it and drives `startRasterWorker` with a stand-in scope.
5
+
6
+ import { isRasterRequest, RASTER_READY, type RasterAnswer, wireError } from './raster-wire';
7
+ import { transformInline } from './transform-inline';
8
+
9
+ /** The two globals a Worker talks through — the real `self`, or a test's stand-in. */
10
+ export interface RasterWorkerScope {
11
+ postMessage(message: unknown, options?: { readonly transfer?: Transferable[] }): void;
12
+ addEventListener(type: 'message', listener: (event: MessageEvent<unknown>) => void): void;
13
+ }
14
+
15
+ function answer(scope: RasterWorkerScope, message: RasterAnswer, transfer: Transferable[]): void {
16
+ try {
17
+ scope.postMessage(message, { transfer });
18
+ } catch (error) {
19
+ // A `meta` that cannot be cloned loses only itself: the code, cause and fix still arrive.
20
+ if (message.ok) throw error;
21
+ scope.postMessage({ ...message, error: { ...message.error, meta: undefined } });
22
+ }
23
+ }
24
+
25
+ /** One request, one answer. Anything that is not a request has no id to answer, so it is dropped. */
26
+ export async function handleRasterMessage(scope: RasterWorkerScope, data: unknown): Promise<void> {
27
+ if (!isRasterRequest(data)) return;
28
+ try {
29
+ const bytes = await transformInline(data.bytes, data.spec);
30
+ // Transferred, not copied: these bytes are the worker's own, and the copy would be on the
31
+ // receiving thread — the one this file exists to keep free.
32
+ answer(scope, { id: data.id, ok: true, bytes }, [bytes.buffer as ArrayBuffer]);
33
+ } catch (error) {
34
+ answer(scope, { id: data.id, ok: false, error: wireError(error) }, []);
35
+ }
36
+ }
37
+
38
+ /** Listens, then says ready — the pool counts a Worker as LOADED from that message on. */
39
+ export function startRasterWorker(scope: RasterWorkerScope): void {
40
+ scope.addEventListener('message', (event) => {
41
+ void handleRasterMessage(scope, event.data);
42
+ });
43
+ scope.postMessage(RASTER_READY);
44
+ }
45
+
46
+ if (!Bun.isMainThread) startRasterWorker(globalThis);