@typfolio/workers 0.0.0-stage → 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/LICENSE +202 -0
- package/README.md +52 -2
- package/dist/batch.d.ts +8 -0
- package/dist/batch.js +102 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +309 -0
- package/dist/protocol.d.ts +34 -0
- package/dist/protocol.js +104 -0
- package/dist/runtime.d.ts +1 -0
- package/dist/runtime.js +2 -0
- package/dist/snapshot.d.ts +16 -0
- package/dist/snapshot.js +94 -0
- package/dist/types.d.ts +82 -0
- package/dist/types.js +10 -0
- package/dist/worker-runtime.d.ts +6 -0
- package/dist/worker-runtime.js +65 -0
- package/package.json +36 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @typfolio/workers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-independent module-worker execution for `@typfolio/core`. The package provides a lazy bounded pool, FIFO scheduling, a finite queue, per-job `AbortSignal` cancellation, timeouts, worker replacement, incremental batches, and deterministic disposal.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { createWorkerClient } from '@typfolio/workers';
|
|
7
|
+
import wasmUrl from '@typfolio/wasm/compiler.wasm?url';
|
|
8
|
+
|
|
9
|
+
const client = createWorkerClient({
|
|
10
|
+
compiler: { wasm: wasmUrl, fonts: ['/fonts/report.otf'] },
|
|
11
|
+
workerCount: 2,
|
|
12
|
+
queueLimit: 16,
|
|
13
|
+
timeoutMs: 30_000,
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
const result = await client.compile(request, { signal });
|
|
18
|
+
// result.bytes is transferred from the worker without copying it again.
|
|
19
|
+
} finally {
|
|
20
|
+
await client.dispose();
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Stream a large batch in completion order without retaining every PDF:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { compileBatch } from '@typfolio/workers';
|
|
28
|
+
|
|
29
|
+
for await (const outcome of compileBatch(client, jobs, { signal })) {
|
|
30
|
+
if (outcome.status === 'success') {
|
|
31
|
+
await upload(outcome.id, outcome.result.bytes);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Use `collectBatch(client, jobs)` when the caller needs all outcomes in input order.
|
|
37
|
+
|
|
38
|
+
The built-in factory creates a module worker from the packaged runtime. `workerFactory` is available for tests or hosts with custom worker construction. The client owns every worker returned by that factory and terminates it during hard cancellation, transport recovery, or disposal.
|
|
39
|
+
|
|
40
|
+
## Semantics
|
|
41
|
+
|
|
42
|
+
- Calls are snapshotted synchronously and compiled FIFO, with one active compile per worker.
|
|
43
|
+
- Cancelling a waiting job removes only that job. Cancelling or timing out the active synchronous WASM call terminates its worker; the next queued job receives a fresh worker/compiler.
|
|
44
|
+
- A Typst compilation error rejects that job but keeps the worker healthy. A malformed message or worker crash rejects the active job and replaces the worker lazily.
|
|
45
|
+
- `queueLimit` counts waiting jobs, not the active compile. Timeouts include queue time.
|
|
46
|
+
- `dispose()` is idempotent, rejects all unsettled work with `DISPOSED`, and terminates the owned worker.
|
|
47
|
+
- Errors crossing the realm boundary become `TypfolioWorkerError` with stable `code`, `message`, and `diagnostics` fields.
|
|
48
|
+
|
|
49
|
+
`fonts` takes `Uint8Array | string | URL`, as in `@typfolio/core`, and `createWorkerClient` stays synchronous. Give fonts as URLs and each worker fetches them itself while it initializes, so the font bytes never cross the worker boundary (bytes are structured-cloned into every worker). A `URL` is sent as its `href`; a string is resolved against the page URL on the client thread before it is sent, because inside a worker a relative string would resolve against the worker script. Without a page URL (for example in Node) a string must be absolute, otherwise `createWorkerClient` throws a `TypeError`. A font that cannot be fetched in the worker fails initialization: the job rejects with a `TypfolioWorkerError` whose `code` is `INITIALIZATION` and whose message names the URL.
|
|
50
|
+
|
|
51
|
+
Worker transport accepts a WASM URL string, `ArrayBuffer`, `Uint8Array`, or compiled `WebAssembly.Module`. `Request` and `Response` are intentionally excluded because they are not consistently structured-cloneable across browsers. Asset bytes are copied once, on the client thread, when `compile` snapshots the request, so the caller's buffers stay intact and reusable. That private copy is then transferred to the worker (not cloned again), and the worker mounts it as received without copying it a third time. A `SharedArrayBuffer`-backed asset cannot be transferred and still travels by structured clone. `compileBatch` snapshots each job once and passes that snapshot straight to the client.
|
|
52
|
+
|
|
53
|
+
The package uses Effect internally for interruptible jobs, timeout/abort races, scoped client disposal, and bounded completion-order batch streams. The public contract deliberately remains framework-neutral: consumers use Promises, `AbortSignal`, async iterables, and `TypfolioWorkerError`, without needing Effect in application code. The worker wire protocol and explicit `Worker.terminate()` slot recovery remain Typfolio-owned because hard cancellation must stop synchronous WASM.
|
package/dist/batch.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type PdfBatchJob, type PdfBatchOptions, type PdfBatchOutcome, type PdfWorkerClient } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Compiles a batch with at most `client.workerCount` submitted jobs at once.
|
|
4
|
+
* Events are yielded in completion order and results are not retained here.
|
|
5
|
+
*/
|
|
6
|
+
export declare function compileBatch<Id>(client: PdfWorkerClient, jobs: readonly PdfBatchJob<Id>[], options?: PdfBatchOptions<Id>): AsyncIterable<PdfBatchOutcome<Id>>;
|
|
7
|
+
/** Collects batch events into input order. Prefer `compileBatch` for large outputs. */
|
|
8
|
+
export declare function collectBatch<Id>(client: PdfWorkerClient, jobs: readonly PdfBatchJob<Id>[], options?: PdfBatchOptions<Id>): Promise<readonly PdfBatchOutcome<Id>[]>;
|
package/dist/batch.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import * as Effect from 'effect/Effect';
|
|
2
|
+
import * as Stream from 'effect/Stream';
|
|
3
|
+
import { snapshotRequest } from './snapshot.js';
|
|
4
|
+
import { TypfolioWorkerError, } from './types.js';
|
|
5
|
+
function capture(job, index) {
|
|
6
|
+
try {
|
|
7
|
+
return { id: job.id, index, request: snapshotRequest(job.request), timeoutMs: job.timeoutMs };
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
if (error instanceof TypfolioWorkerError && error.code === 'INVALID_INPUT')
|
|
11
|
+
return { id: job.id, index, rejected: error };
|
|
12
|
+
throw error;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function cancelled(job) {
|
|
16
|
+
return { id: job.id, index: job.index, status: 'cancelled' };
|
|
17
|
+
}
|
|
18
|
+
function normalizeError(error) {
|
|
19
|
+
return error instanceof TypfolioWorkerError
|
|
20
|
+
? error
|
|
21
|
+
: new TypfolioWorkerError('WORKER', error instanceof Error ? error.message : String(error), [], { cause: error });
|
|
22
|
+
}
|
|
23
|
+
const run = Effect.fnUntraced(function* (client, job, batchSignal) {
|
|
24
|
+
if (batchSignal?.aborted)
|
|
25
|
+
return cancelled(job);
|
|
26
|
+
if (job.request === undefined)
|
|
27
|
+
return { id: job.id, index: job.index, status: 'error', error: job.rejected };
|
|
28
|
+
const request = job.request;
|
|
29
|
+
return yield* Effect.tryPromise({
|
|
30
|
+
try: effectSignal => {
|
|
31
|
+
const controller = new AbortController();
|
|
32
|
+
const abortFromEffect = () => controller.abort(effectSignal.reason);
|
|
33
|
+
const abortFromBatch = () => controller.abort(batchSignal?.reason);
|
|
34
|
+
effectSignal.addEventListener('abort', abortFromEffect, { once: true });
|
|
35
|
+
batchSignal?.addEventListener('abort', abortFromBatch, { once: true });
|
|
36
|
+
if (effectSignal.aborted)
|
|
37
|
+
abortFromEffect();
|
|
38
|
+
if (batchSignal?.aborted)
|
|
39
|
+
abortFromBatch();
|
|
40
|
+
return client.compile(request, {
|
|
41
|
+
signal: controller.signal,
|
|
42
|
+
timeoutMs: job.timeoutMs,
|
|
43
|
+
}).finally(() => {
|
|
44
|
+
effectSignal.removeEventListener('abort', abortFromEffect);
|
|
45
|
+
batchSignal?.removeEventListener('abort', abortFromBatch);
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
catch: normalizeError,
|
|
49
|
+
}).pipe(Effect.match({
|
|
50
|
+
onFailure: error => error.code === 'ABORTED'
|
|
51
|
+
? cancelled(job)
|
|
52
|
+
: { id: job.id, index: job.index, status: 'error', error },
|
|
53
|
+
onSuccess: (result) => ({
|
|
54
|
+
id: job.id,
|
|
55
|
+
index: job.index,
|
|
56
|
+
status: 'success',
|
|
57
|
+
result,
|
|
58
|
+
}),
|
|
59
|
+
}));
|
|
60
|
+
});
|
|
61
|
+
function initialProgress(total) {
|
|
62
|
+
return { total, completed: 0, succeeded: 0, failed: 0, cancelled: 0 };
|
|
63
|
+
}
|
|
64
|
+
function advance(progress, outcome) {
|
|
65
|
+
return {
|
|
66
|
+
total: progress.total,
|
|
67
|
+
completed: progress.completed + 1,
|
|
68
|
+
succeeded: progress.succeeded + (outcome.status === 'success' ? 1 : 0),
|
|
69
|
+
failed: progress.failed + (outcome.status === 'error' ? 1 : 0),
|
|
70
|
+
cancelled: progress.cancelled + (outcome.status === 'cancelled' ? 1 : 0),
|
|
71
|
+
latestJobId: outcome.id,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Compiles a batch with at most `client.workerCount` submitted jobs at once.
|
|
76
|
+
* Events are yielded in completion order and results are not retained here.
|
|
77
|
+
*/
|
|
78
|
+
export function compileBatch(client, jobs, options = {}) {
|
|
79
|
+
const captured = jobs.map(capture);
|
|
80
|
+
return (async function* stream() {
|
|
81
|
+
let progress = initialProgress(captured.length);
|
|
82
|
+
options.onProgress?.(progress);
|
|
83
|
+
const outcomes = Stream.fromIterable(captured).pipe(Stream.mapEffect(job => run(client, job, options.signal), {
|
|
84
|
+
concurrency: client.workerCount,
|
|
85
|
+
unordered: true,
|
|
86
|
+
}), Stream.tap(outcome => Effect.sync(() => {
|
|
87
|
+
progress = advance(progress, outcome);
|
|
88
|
+
options.onProgress?.(progress);
|
|
89
|
+
options.onItemSettled?.(outcome, progress);
|
|
90
|
+
})));
|
|
91
|
+
for await (const outcome of Stream.toAsyncIterable(outcomes)) {
|
|
92
|
+
yield outcome;
|
|
93
|
+
}
|
|
94
|
+
})();
|
|
95
|
+
}
|
|
96
|
+
/** Collects batch events into input order. Prefer `compileBatch` for large outputs. */
|
|
97
|
+
export async function collectBatch(client, jobs, options = {}) {
|
|
98
|
+
const outcomes = new Array(jobs.length);
|
|
99
|
+
for await (const outcome of compileBatch(client, jobs, options))
|
|
100
|
+
outcomes[outcome.index] = outcome;
|
|
101
|
+
return outcomes;
|
|
102
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type CreateWorkerClientOptions, type PdfWorkerClient } from './types.js';
|
|
2
|
+
export { TypfolioWorkerError, type CreateWorkerClientOptions, type PdfWorkerClient, type WorkerCompileOptions, type WorkerCompilerOptions, type WorkerErrorCode, type WorkerFontSource, type WorkerWasmSource, type PdfBatchJob, type PdfBatchOptions, type PdfBatchOutcome, type PdfBatchProgress, } from './types.js';
|
|
3
|
+
export { collectBatch, compileBatch } from './batch.js';
|
|
4
|
+
export declare function createWorkerClient(options: CreateWorkerClientOptions): PdfWorkerClient;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import * as Effect from 'effect/Effect';
|
|
2
|
+
import * as Layer from 'effect/Layer';
|
|
3
|
+
import * as ManagedRuntime from 'effect/ManagedRuntime';
|
|
4
|
+
import { decodeRuntimeMessage, protocolVersion } from './protocol.js';
|
|
5
|
+
import { isSnapshot, snapshotRequest, snapshotValidation, transferableBuffers } from './snapshot.js';
|
|
6
|
+
import { TypfolioWorkerError, } from './types.js';
|
|
7
|
+
export { TypfolioWorkerError, } from './types.js';
|
|
8
|
+
export { collectBatch, compileBatch } from './batch.js';
|
|
9
|
+
const maximumTimer = 2_147_483_647;
|
|
10
|
+
function positiveInteger(value, fallback, name) {
|
|
11
|
+
const result = value ?? fallback;
|
|
12
|
+
if (!Number.isInteger(result) || result < 1)
|
|
13
|
+
throw new RangeError(`${name} must be a positive integer`);
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
function timeout(value, name) {
|
|
17
|
+
if (value === undefined)
|
|
18
|
+
return undefined;
|
|
19
|
+
if (!Number.isInteger(value) || value < 1 || value > maximumTimer) {
|
|
20
|
+
throw new RangeError(`${name} must be an integer from 1 through ${maximumTimer}`);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function snapshotWasm(value) {
|
|
25
|
+
if (typeof value === 'string' || value instanceof WebAssembly.Module)
|
|
26
|
+
return value;
|
|
27
|
+
if (value instanceof ArrayBuffer)
|
|
28
|
+
return value.slice(0);
|
|
29
|
+
if (value instanceof Uint8Array)
|
|
30
|
+
return new Uint8Array(value);
|
|
31
|
+
throw new TypeError('compiler.wasm must be a URL string, ArrayBuffer, Uint8Array, or WebAssembly.Module');
|
|
32
|
+
}
|
|
33
|
+
/** Bytes are copied; a URL becomes its `href`; a string is resolved here, because in a worker it would resolve against the worker script. */
|
|
34
|
+
function snapshotFont(font, index) {
|
|
35
|
+
const at = `compiler.fonts[${index}]`;
|
|
36
|
+
if (font instanceof Uint8Array) {
|
|
37
|
+
if (!font.length)
|
|
38
|
+
throw new TypeError(`${at} must not be empty`);
|
|
39
|
+
return new Uint8Array(font);
|
|
40
|
+
}
|
|
41
|
+
if (font instanceof URL)
|
|
42
|
+
return font.href;
|
|
43
|
+
if (typeof font !== 'string' || !font.trim())
|
|
44
|
+
throw new TypeError(`${at} must be a Uint8Array, a URL, or a non-empty URL string`);
|
|
45
|
+
const base = globalThis.location?.href;
|
|
46
|
+
try {
|
|
47
|
+
return (base === undefined ? new URL(font) : new URL(font, base)).href;
|
|
48
|
+
}
|
|
49
|
+
catch (cause) {
|
|
50
|
+
throw new TypeError(`${at} cannot be resolved to a URL${base === undefined ? ' without a page URL; use an absolute URL' : ''}: ${JSON.stringify(font)}`, { cause });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function snapshotCompiler(value) {
|
|
54
|
+
if (!value || !Array.isArray(value.fonts) || !value.fonts.length) {
|
|
55
|
+
throw new TypeError('compiler.fonts must contain at least one Uint8Array, URL, or URL string');
|
|
56
|
+
}
|
|
57
|
+
return { wasm: snapshotWasm(value.wasm), fonts: value.fonts.map(snapshotFont) };
|
|
58
|
+
}
|
|
59
|
+
function workerError(message, cause) {
|
|
60
|
+
return new TypfolioWorkerError('WORKER', message, [], cause === undefined ? undefined : { cause });
|
|
61
|
+
}
|
|
62
|
+
function defaultWorkerFactory(name) {
|
|
63
|
+
return index => new Worker(new URL('./runtime.js', import.meta.url), { type: 'module', name: `${name}-${index + 1}` });
|
|
64
|
+
}
|
|
65
|
+
export function createWorkerClient(options) {
|
|
66
|
+
const compiler = snapshotCompiler(options.compiler);
|
|
67
|
+
const workerCount = positiveInteger(options.workerCount, 1, 'workerCount');
|
|
68
|
+
const queueLimit = positiveInteger(options.queueLimit, 32, 'queueLimit');
|
|
69
|
+
const defaultTimeout = timeout(options.timeoutMs, 'timeoutMs');
|
|
70
|
+
const createWorker = options.workerFactory ?? defaultWorkerFactory(options.workerName ?? 'typfolio-pdf');
|
|
71
|
+
const queue = [];
|
|
72
|
+
const slots = new Array(workerCount);
|
|
73
|
+
let nextId = 1;
|
|
74
|
+
let poolDisposed = false;
|
|
75
|
+
let clientDisposed = false;
|
|
76
|
+
let disposal;
|
|
77
|
+
function settle(job, result) {
|
|
78
|
+
if (job.settled)
|
|
79
|
+
return;
|
|
80
|
+
job.settled = true;
|
|
81
|
+
job.resume(result);
|
|
82
|
+
}
|
|
83
|
+
function terminateWorker(current) {
|
|
84
|
+
if (!current)
|
|
85
|
+
return;
|
|
86
|
+
if (slots[current.index] === current)
|
|
87
|
+
slots[current.index] = undefined;
|
|
88
|
+
current.worker.terminate();
|
|
89
|
+
}
|
|
90
|
+
function dispatchSoon() {
|
|
91
|
+
queueMicrotask(dispatch);
|
|
92
|
+
}
|
|
93
|
+
function failActive(error, current) {
|
|
94
|
+
if (slots[current.index] !== current)
|
|
95
|
+
return;
|
|
96
|
+
const job = current.active;
|
|
97
|
+
current.active = undefined;
|
|
98
|
+
terminateWorker(current);
|
|
99
|
+
const failed = job ?? queue.shift();
|
|
100
|
+
if (failed)
|
|
101
|
+
settle(failed, Effect.fail(error));
|
|
102
|
+
dispatchSoon();
|
|
103
|
+
}
|
|
104
|
+
function handleMessage(current, value) {
|
|
105
|
+
if (poolDisposed || slots[current.index] !== current)
|
|
106
|
+
return;
|
|
107
|
+
let message;
|
|
108
|
+
try {
|
|
109
|
+
message = decodeRuntimeMessage(value);
|
|
110
|
+
}
|
|
111
|
+
catch (cause) {
|
|
112
|
+
failActive(workerError('Typfolio worker returned an invalid message', cause), current);
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (message.type === 'ready') {
|
|
116
|
+
if (current.ready) {
|
|
117
|
+
failActive(workerError('Typfolio worker initialized more than once'), current);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
current.ready = true;
|
|
121
|
+
dispatch();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (message.type === 'failure' && message.id === undefined) {
|
|
125
|
+
const error = new TypfolioWorkerError(message.error.code, message.error.message, message.error.diagnostics);
|
|
126
|
+
failActive(error, current);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const job = current.active;
|
|
130
|
+
if (!job || message.id !== job.id)
|
|
131
|
+
return;
|
|
132
|
+
current.active = undefined;
|
|
133
|
+
if (message.type === 'result') {
|
|
134
|
+
settle(job, Effect.succeed(message.result));
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
settle(job, Effect.fail(new TypfolioWorkerError(message.error.code, message.error.message, message.error.diagnostics)));
|
|
138
|
+
}
|
|
139
|
+
dispatch();
|
|
140
|
+
}
|
|
141
|
+
function createSlot(index) {
|
|
142
|
+
let worker;
|
|
143
|
+
try {
|
|
144
|
+
worker = createWorker(index);
|
|
145
|
+
}
|
|
146
|
+
catch (cause) {
|
|
147
|
+
const job = queue.shift();
|
|
148
|
+
if (job)
|
|
149
|
+
settle(job, Effect.fail(workerError('Could not create Typfolio worker', cause)));
|
|
150
|
+
dispatchSoon();
|
|
151
|
+
return false;
|
|
152
|
+
}
|
|
153
|
+
const current = { worker, index, ready: false };
|
|
154
|
+
slots[index] = current;
|
|
155
|
+
worker.addEventListener('message', event => handleMessage(current, event.data));
|
|
156
|
+
worker.addEventListener('error', event => {
|
|
157
|
+
failActive(workerError(event.message || 'Typfolio worker failed'), current);
|
|
158
|
+
});
|
|
159
|
+
worker.addEventListener('messageerror', () => {
|
|
160
|
+
failActive(workerError('Typfolio worker returned an unreadable message'), current);
|
|
161
|
+
});
|
|
162
|
+
const message = { protocol: protocolVersion, type: 'initialize', compiler };
|
|
163
|
+
try {
|
|
164
|
+
worker.postMessage(message);
|
|
165
|
+
}
|
|
166
|
+
catch (cause) {
|
|
167
|
+
failActive(workerError('Could not initialize Typfolio worker', cause), current);
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
function ensureCapacity() {
|
|
172
|
+
if (poolDisposed || !queue.length)
|
|
173
|
+
return;
|
|
174
|
+
const activeCount = slots.reduce((count, current) => count + (current?.active ? 1 : 0), 0);
|
|
175
|
+
const target = Math.min(workerCount, activeCount + queue.length);
|
|
176
|
+
let existing = slots.reduce((count, current) => count + (current ? 1 : 0), 0);
|
|
177
|
+
for (let index = 0; index < slots.length && existing < target; index += 1) {
|
|
178
|
+
if (!slots[index]) {
|
|
179
|
+
if (!createSlot(index))
|
|
180
|
+
break;
|
|
181
|
+
existing += 1;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
function dispatch() {
|
|
186
|
+
if (poolDisposed || !queue.length)
|
|
187
|
+
return;
|
|
188
|
+
ensureCapacity();
|
|
189
|
+
for (const current of slots) {
|
|
190
|
+
if (!current?.ready || current.active)
|
|
191
|
+
continue;
|
|
192
|
+
const job = queue.shift();
|
|
193
|
+
if (!job)
|
|
194
|
+
return;
|
|
195
|
+
current.active = job;
|
|
196
|
+
const message = { protocol: protocolVersion, type: 'compile', id: job.id, request: job.request };
|
|
197
|
+
try {
|
|
198
|
+
// A job is posted once: failed, cancelled, timed-out and crashed jobs are rejected, never re-posted, and a
|
|
199
|
+
// queued job leaves the queue as it is posted. So the snapshot's buffers can be transferred, not cloned.
|
|
200
|
+
current.worker.postMessage(message, transferableBuffers(job.request));
|
|
201
|
+
}
|
|
202
|
+
catch (cause) {
|
|
203
|
+
failActive(workerError('Could not send work to Typfolio worker', cause), current);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function interruptJob(job) {
|
|
208
|
+
if (job.settled)
|
|
209
|
+
return;
|
|
210
|
+
job.settled = true;
|
|
211
|
+
const current = slots.find(candidate => candidate?.active === job);
|
|
212
|
+
if (current) {
|
|
213
|
+
current.active = undefined;
|
|
214
|
+
terminateWorker(current);
|
|
215
|
+
dispatchSoon();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const index = queue.indexOf(job);
|
|
219
|
+
if (index !== -1)
|
|
220
|
+
queue.splice(index, 1);
|
|
221
|
+
}
|
|
222
|
+
const compileJob = Effect.fnUntraced(function* (request) {
|
|
223
|
+
return yield* Effect.callback(resume => {
|
|
224
|
+
if (poolDisposed) {
|
|
225
|
+
resume(Effect.fail(new TypfolioWorkerError('DISPOSED', 'The worker client is disposed')));
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (queue.length >= queueLimit) {
|
|
229
|
+
resume(Effect.fail(new TypfolioWorkerError('QUEUE_FULL', `The worker queue limit of ${queueLimit} was reached`)));
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const job = { id: nextId++, request, resume, settled: false };
|
|
233
|
+
queue.push(job);
|
|
234
|
+
dispatch();
|
|
235
|
+
return Effect.sync(() => interruptJob(job));
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
function waitForAbort(signal) {
|
|
239
|
+
return Effect.callback(resume => {
|
|
240
|
+
const abort = () => resume(Effect.fail(new TypfolioWorkerError('ABORTED', 'Compilation was cancelled', [], { cause: signal.reason })));
|
|
241
|
+
if (signal.aborted) {
|
|
242
|
+
abort();
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
246
|
+
return Effect.sync(() => signal.removeEventListener('abort', abort));
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const disposePool = Effect.sync(() => {
|
|
250
|
+
if (poolDisposed)
|
|
251
|
+
return;
|
|
252
|
+
poolDisposed = true;
|
|
253
|
+
const error = new TypfolioWorkerError('DISPOSED', 'The worker client is disposed');
|
|
254
|
+
for (const current of slots) {
|
|
255
|
+
if (current?.active) {
|
|
256
|
+
const job = current.active;
|
|
257
|
+
current.active = undefined;
|
|
258
|
+
settle(job, Effect.fail(error));
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
for (const job of queue.splice(0))
|
|
262
|
+
settle(job, Effect.fail(error));
|
|
263
|
+
for (const current of slots)
|
|
264
|
+
terminateWorker(current);
|
|
265
|
+
});
|
|
266
|
+
const runtime = ManagedRuntime.make(Layer.effectDiscard(Effect.acquireRelease(Effect.void, () => disposePool)));
|
|
267
|
+
return {
|
|
268
|
+
workerCount,
|
|
269
|
+
compile(request, compileOptions = {}) {
|
|
270
|
+
if (clientDisposed)
|
|
271
|
+
return Promise.reject(new TypfolioWorkerError('DISPOSED', 'The worker client is disposed'));
|
|
272
|
+
if (compileOptions.signal?.aborted) {
|
|
273
|
+
return Promise.reject(new TypfolioWorkerError('ABORTED', 'Compilation was cancelled', [], { cause: compileOptions.signal.reason }));
|
|
274
|
+
}
|
|
275
|
+
let captured;
|
|
276
|
+
let duration;
|
|
277
|
+
try {
|
|
278
|
+
// A snapshot (from compileBatch) is already client-owned; copying it again would copy every asset twice.
|
|
279
|
+
captured = isSnapshot(request) ? request : snapshotRequest(request);
|
|
280
|
+
duration = timeout(compileOptions.timeoutMs, 'compile timeoutMs') ?? defaultTimeout;
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
return Promise.reject(error);
|
|
284
|
+
}
|
|
285
|
+
let program = compileJob(captured);
|
|
286
|
+
const validation = snapshotValidation(captured);
|
|
287
|
+
if (validation) {
|
|
288
|
+
const checked = captured;
|
|
289
|
+
program = Effect.flatMap(Effect.tryPromise({ try: () => validation, catch: error => error }), () => compileJob(checked));
|
|
290
|
+
}
|
|
291
|
+
if (duration !== undefined) {
|
|
292
|
+
program = Effect.timeoutOrElse(program, {
|
|
293
|
+
duration,
|
|
294
|
+
orElse: () => Effect.fail(new TypfolioWorkerError('TIMEOUT', `Compilation exceeded its ${duration} ms timeout`)),
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
if (compileOptions.signal) {
|
|
298
|
+
program = Effect.raceFirst(program, waitForAbort(compileOptions.signal));
|
|
299
|
+
}
|
|
300
|
+
return runtime.runPromise(program);
|
|
301
|
+
},
|
|
302
|
+
dispose() {
|
|
303
|
+
if (disposal)
|
|
304
|
+
return disposal;
|
|
305
|
+
clientDisposed = true;
|
|
306
|
+
return disposal = Effect.runPromise(disposePool).then(() => runtime.dispose());
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Diagnostic, PdfRequest, PdfResult } from '@typfolio/core';
|
|
2
|
+
import type { SerializedCompilerOptions, WorkerErrorCode } from './types.js';
|
|
3
|
+
export declare const protocolVersion = 1;
|
|
4
|
+
export type HostMessage = {
|
|
5
|
+
readonly protocol: 1;
|
|
6
|
+
readonly type: 'initialize';
|
|
7
|
+
readonly compiler: SerializedCompilerOptions;
|
|
8
|
+
} | {
|
|
9
|
+
readonly protocol: 1;
|
|
10
|
+
readonly type: 'compile';
|
|
11
|
+
readonly id: number;
|
|
12
|
+
readonly request: PdfRequest<unknown>;
|
|
13
|
+
};
|
|
14
|
+
export interface SerializedError {
|
|
15
|
+
readonly code: WorkerErrorCode;
|
|
16
|
+
readonly message: string;
|
|
17
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
18
|
+
}
|
|
19
|
+
export type RuntimeMessage = {
|
|
20
|
+
readonly protocol: 1;
|
|
21
|
+
readonly type: 'ready';
|
|
22
|
+
} | {
|
|
23
|
+
readonly protocol: 1;
|
|
24
|
+
readonly type: 'result';
|
|
25
|
+
readonly id: number;
|
|
26
|
+
readonly result: PdfResult;
|
|
27
|
+
} | {
|
|
28
|
+
readonly protocol: 1;
|
|
29
|
+
readonly type: 'failure';
|
|
30
|
+
readonly id?: number;
|
|
31
|
+
readonly error: SerializedError;
|
|
32
|
+
};
|
|
33
|
+
export declare function decodeHostMessage(value: unknown): HostMessage;
|
|
34
|
+
export declare function decodeRuntimeMessage(value: unknown): RuntimeMessage;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
export const protocolVersion = 1;
|
|
2
|
+
function record(value, at) {
|
|
3
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
4
|
+
throw new TypeError(`${at} must be an object`);
|
|
5
|
+
}
|
|
6
|
+
return value;
|
|
7
|
+
}
|
|
8
|
+
function wasmSource(value) {
|
|
9
|
+
if (typeof value === 'string' || value instanceof ArrayBuffer || value instanceof Uint8Array || value instanceof WebAssembly.Module) {
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
throw new TypeError('compiler.wasm cannot cross the worker boundary');
|
|
13
|
+
}
|
|
14
|
+
function compilerOptions(value) {
|
|
15
|
+
const options = record(value, 'compiler');
|
|
16
|
+
if (!Array.isArray(options.fonts) || options.fonts.some(font => !(font instanceof Uint8Array || typeof font === 'string'))) {
|
|
17
|
+
throw new TypeError('compiler.fonts must contain Uint8Array or string values');
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
wasm: wasmSource(options.wasm),
|
|
21
|
+
fonts: options.fonts.map((font) => typeof font === 'string' ? font : new Uint8Array(font)),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
export function decodeHostMessage(value) {
|
|
25
|
+
const message = record(value, 'worker message');
|
|
26
|
+
if (message.protocol !== protocolVersion)
|
|
27
|
+
throw new TypeError('Unsupported Typfolio worker protocol');
|
|
28
|
+
if (message.type === 'initialize') {
|
|
29
|
+
return { protocol: protocolVersion, type: 'initialize', compiler: compilerOptions(message.compiler) };
|
|
30
|
+
}
|
|
31
|
+
if (message.type === 'compile' && Number.isSafeInteger(message.id)) {
|
|
32
|
+
const request = record(message.request, 'request');
|
|
33
|
+
return { protocol: protocolVersion, type: 'compile', id: Number(message.id), request };
|
|
34
|
+
}
|
|
35
|
+
throw new TypeError('Unknown Typfolio worker message');
|
|
36
|
+
}
|
|
37
|
+
function diagnostic(value) {
|
|
38
|
+
const item = record(value, 'diagnostic');
|
|
39
|
+
if (typeof item.severity !== 'string' || typeof item.message !== 'string')
|
|
40
|
+
throw new TypeError('Invalid worker diagnostic');
|
|
41
|
+
return {
|
|
42
|
+
severity: item.severity,
|
|
43
|
+
message: item.message,
|
|
44
|
+
path: typeof item.path === 'string' ? item.path : undefined,
|
|
45
|
+
range: typeof item.range === 'string' ? item.range : undefined,
|
|
46
|
+
package: typeof item.package === 'string' ? item.package : undefined,
|
|
47
|
+
...(typeof item.code === 'string' ? { code: item.code } : {}),
|
|
48
|
+
...(typeof item.file === 'string' ? { file: item.file } : {}),
|
|
49
|
+
...(typeof item.text === 'string' ? { text: item.text } : {}),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function serializedError(value) {
|
|
53
|
+
const error = record(value, 'worker error');
|
|
54
|
+
if (typeof error.code !== 'string' || typeof error.message !== 'string' || !Array.isArray(error.diagnostics)) {
|
|
55
|
+
throw new TypeError('Invalid worker error');
|
|
56
|
+
}
|
|
57
|
+
const codes = [
|
|
58
|
+
'INITIALIZATION', 'INVALID_REQUEST', 'INVALID_INPUT', 'UNSUPPORTED_OPTION', 'BUSY', 'DISPOSED',
|
|
59
|
+
'ABORTED', 'COMPILATION', 'ENGINE', 'WORKER', 'TIMEOUT', 'QUEUE_FULL',
|
|
60
|
+
];
|
|
61
|
+
const code = codes.find(candidate => candidate === error.code);
|
|
62
|
+
if (!code)
|
|
63
|
+
throw new TypeError('Invalid worker error code');
|
|
64
|
+
return {
|
|
65
|
+
code,
|
|
66
|
+
message: error.message,
|
|
67
|
+
diagnostics: error.diagnostics.map(diagnostic),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
function result(value) {
|
|
71
|
+
const item = record(value, 'worker result');
|
|
72
|
+
const bytes = item.bytes instanceof Uint8Array
|
|
73
|
+
? item.bytes
|
|
74
|
+
: item.bytes instanceof ArrayBuffer ? new Uint8Array(item.bytes) : undefined;
|
|
75
|
+
if (!bytes || !Array.isArray(item.diagnostics))
|
|
76
|
+
throw new TypeError('Invalid worker PDF result');
|
|
77
|
+
const metadata = record(item.metadata, 'worker result metadata');
|
|
78
|
+
if (metadata.title !== undefined && typeof metadata.title !== 'string')
|
|
79
|
+
throw new TypeError('Invalid worker PDF title');
|
|
80
|
+
return {
|
|
81
|
+
bytes,
|
|
82
|
+
diagnostics: item.diagnostics.map(diagnostic),
|
|
83
|
+
metadata: { title: metadata.title },
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export function decodeRuntimeMessage(value) {
|
|
87
|
+
const message = record(value, 'runtime message');
|
|
88
|
+
if (message.protocol !== protocolVersion)
|
|
89
|
+
throw new TypeError('Unsupported Typfolio worker protocol');
|
|
90
|
+
if (message.type === 'ready')
|
|
91
|
+
return { protocol: protocolVersion, type: 'ready' };
|
|
92
|
+
if (message.type === 'result' && Number.isSafeInteger(message.id)) {
|
|
93
|
+
return { protocol: protocolVersion, type: 'result', id: Number(message.id), result: result(message.result) };
|
|
94
|
+
}
|
|
95
|
+
if (message.type === 'failure' && (message.id === undefined || Number.isSafeInteger(message.id))) {
|
|
96
|
+
return {
|
|
97
|
+
protocol: protocolVersion,
|
|
98
|
+
type: 'failure',
|
|
99
|
+
id: message.id === undefined ? undefined : Number(message.id),
|
|
100
|
+
error: serializedError(message.error),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
throw new TypeError('Unknown Typfolio runtime message');
|
|
104
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type AnyPdfRequest, type DocumentsRequest, type PdfRequest } from '@typfolio/core';
|
|
2
|
+
/** The pending schema check of a snapshot, if its template's schemas validate asynchronously. */
|
|
3
|
+
export declare function snapshotValidation(snapshot: object): Promise<void> | undefined;
|
|
4
|
+
export declare function isSnapshot(request: unknown): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* A copy of the request the client owns. A request for a defined template is first checked against its
|
|
7
|
+
* schemas and turned into its low-level form (schemas are functions and cannot cross the boundary).
|
|
8
|
+
*/
|
|
9
|
+
export declare function snapshotRequest(request: AnyPdfRequest): PdfRequest<unknown> | DocumentsRequest;
|
|
10
|
+
/**
|
|
11
|
+
* The buffers of a snapshot's assets that `postMessage` can transfer, each once. Buffers that cannot be
|
|
12
|
+
* transferred (a `SharedArrayBuffer`, which structured clone shares instead of copying, or one that is already
|
|
13
|
+
* detached) are left out and travel by the ordinary clone. Only call this with a snapshot: transferring detaches
|
|
14
|
+
* the buffers, which would break a caller's request.
|
|
15
|
+
*/
|
|
16
|
+
export declare function transferableBuffers(snapshot: PdfRequest<unknown> | DocumentsRequest): ArrayBuffer[];
|
package/dist/snapshot.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { TypstPdfError } from '@typfolio/core';
|
|
2
|
+
import { resolveRequest } from '@typfolio/core/internal';
|
|
3
|
+
import { TypfolioWorkerError } from './types.js';
|
|
4
|
+
function inspectCloneable(value, ancestors, at) {
|
|
5
|
+
if (typeof value === 'function' || typeof value === 'symbol') {
|
|
6
|
+
throw new TypeError(`${at} cannot cross the worker boundary`);
|
|
7
|
+
}
|
|
8
|
+
if (typeof value !== 'object' || value === null || value instanceof Uint8Array || value instanceof ArrayBuffer)
|
|
9
|
+
return;
|
|
10
|
+
if (ancestors.has(value))
|
|
11
|
+
throw new TypeError(`${at} contains a cycle`);
|
|
12
|
+
if (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
|
|
13
|
+
throw new TypeError(`${at} must contain only plain objects, arrays, and Uint8Array assets`);
|
|
14
|
+
}
|
|
15
|
+
if (Object.getOwnPropertySymbols(value).length)
|
|
16
|
+
throw new TypeError(`${at} contains symbol keys`);
|
|
17
|
+
ancestors.add(value);
|
|
18
|
+
try {
|
|
19
|
+
for (const key of Object.keys(value)) {
|
|
20
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
21
|
+
if (!descriptor || !('value' in descriptor))
|
|
22
|
+
throw new TypeError(`${at}.${key} contains an accessor`);
|
|
23
|
+
inspectCloneable(descriptor.value, ancestors, `${at}.${key}`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
ancestors.delete(value);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
// Every request returned by snapshotRequest. The client owns these (nothing else holds their buffers), so it
|
|
31
|
+
// neither snapshots them again nor hesitates to transfer them.
|
|
32
|
+
const snapshots = new WeakSet();
|
|
33
|
+
// A schema that validates asynchronously: its check, which the client awaits before dispatching.
|
|
34
|
+
const validations = new WeakMap();
|
|
35
|
+
// Errors from core (an input that fails its schema, a missing partial) as the client's own error type.
|
|
36
|
+
function asWorkerError(error) {
|
|
37
|
+
return error instanceof TypstPdfError
|
|
38
|
+
? new TypfolioWorkerError(error.code, error.message, error.diagnostics, { cause: error })
|
|
39
|
+
: error;
|
|
40
|
+
}
|
|
41
|
+
/** The pending schema check of a snapshot, if its template's schemas validate asynchronously. */
|
|
42
|
+
export function snapshotValidation(snapshot) {
|
|
43
|
+
return validations.get(snapshot);
|
|
44
|
+
}
|
|
45
|
+
export function isSnapshot(request) {
|
|
46
|
+
return typeof request === 'object' && request !== null && snapshots.has(request);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A copy of the request the client owns. A request for a defined template is first checked against its
|
|
50
|
+
* schemas and turned into its low-level form (schemas are functions and cannot cross the boundary).
|
|
51
|
+
*/
|
|
52
|
+
export function snapshotRequest(request) {
|
|
53
|
+
let resolved;
|
|
54
|
+
try {
|
|
55
|
+
resolved = resolveRequest(request);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
throw asWorkerError(error);
|
|
59
|
+
}
|
|
60
|
+
let snapshot;
|
|
61
|
+
try {
|
|
62
|
+
inspectCloneable(resolved.request, new Set(), 'request');
|
|
63
|
+
snapshot = structuredClone(resolved.request);
|
|
64
|
+
snapshots.add(snapshot);
|
|
65
|
+
}
|
|
66
|
+
catch (cause) {
|
|
67
|
+
throw new TypfolioWorkerError('INVALID_REQUEST', 'The PDF request cannot cross the worker boundary', [], { cause });
|
|
68
|
+
}
|
|
69
|
+
if (resolved.validated) {
|
|
70
|
+
const validation = resolved.validated.catch(error => { throw asWorkerError(error); });
|
|
71
|
+
// A batch job may wait its turn before the client awaits this: a failure is not unhandled meanwhile.
|
|
72
|
+
validation.catch(() => { });
|
|
73
|
+
validations.set(snapshot, validation);
|
|
74
|
+
}
|
|
75
|
+
return snapshot;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The buffers of a snapshot's assets that `postMessage` can transfer, each once. Buffers that cannot be
|
|
79
|
+
* transferred (a `SharedArrayBuffer`, which structured clone shares instead of copying, or one that is already
|
|
80
|
+
* detached) are left out and travel by the ordinary clone. Only call this with a snapshot: transferring detaches
|
|
81
|
+
* the buffers, which would break a caller's request.
|
|
82
|
+
*/
|
|
83
|
+
export function transferableBuffers(snapshot) {
|
|
84
|
+
const buffers = new Set();
|
|
85
|
+
for (const bytes of Object.values(snapshot.assets ?? {})) {
|
|
86
|
+
if (!ArrayBuffer.isView(bytes))
|
|
87
|
+
continue; // Not an asset; the worker's validation rejects it.
|
|
88
|
+
const buffer = bytes.buffer;
|
|
89
|
+
if (Object.prototype.toString.call(buffer) === '[object ArrayBuffer]' && !buffer.detached) {
|
|
90
|
+
buffers.add(buffer);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return [...buffers];
|
|
94
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { AnyPdfRequest, CheckedRequest, Diagnostic, ErrorCode, PdfClient, PdfResult } from '@typfolio/core';
|
|
2
|
+
/** WASM sources that the structured-clone worker protocol can carry reliably. */
|
|
3
|
+
export type WorkerWasmSource = string | ArrayBuffer | Uint8Array | WebAssembly.Module;
|
|
4
|
+
/**
|
|
5
|
+
* Font bytes, or a URL that each worker fetches itself, so the bytes never cross the worker boundary.
|
|
6
|
+
* A string is resolved against the page URL on the client thread before it is sent.
|
|
7
|
+
*/
|
|
8
|
+
export type WorkerFontSource = Uint8Array | string | URL;
|
|
9
|
+
export interface WorkerCompilerOptions {
|
|
10
|
+
readonly wasm: WorkerWasmSource;
|
|
11
|
+
readonly fonts: readonly WorkerFontSource[];
|
|
12
|
+
}
|
|
13
|
+
/** What crosses the worker boundary: a `URL` has become its absolute `href`. */
|
|
14
|
+
export interface SerializedCompilerOptions {
|
|
15
|
+
readonly wasm: WorkerWasmSource;
|
|
16
|
+
readonly fonts: readonly (Uint8Array | string)[];
|
|
17
|
+
}
|
|
18
|
+
export interface WorkerCompileOptions {
|
|
19
|
+
readonly signal?: AbortSignal;
|
|
20
|
+
/** Includes time spent waiting in the queue. */
|
|
21
|
+
readonly timeoutMs?: number;
|
|
22
|
+
}
|
|
23
|
+
export interface PdfWorkerClient extends PdfClient {
|
|
24
|
+
readonly workerCount: number;
|
|
25
|
+
/** A plain request, or one for a defined template: its inputs are checked against their schemas on this thread. */
|
|
26
|
+
compile<R extends AnyPdfRequest>(request: R & CheckedRequest<R>, options?: WorkerCompileOptions): Promise<PdfResult>;
|
|
27
|
+
/** Rejects queued/active jobs and terminates all owned workers. Idempotent. */
|
|
28
|
+
dispose(): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export interface CreateWorkerClientOptions {
|
|
31
|
+
readonly compiler: WorkerCompilerOptions;
|
|
32
|
+
/** Maximum parallel compilations. Workers are created lazily. Defaults to one. */
|
|
33
|
+
readonly workerCount?: number;
|
|
34
|
+
/** Maximum number of waiting jobs, excluding the active compilation. */
|
|
35
|
+
readonly queueLimit?: number;
|
|
36
|
+
/** Default per-job timeout, including queue time. Omit for no timeout. */
|
|
37
|
+
readonly timeoutMs?: number;
|
|
38
|
+
/** Used by the built-in module-worker factory. */
|
|
39
|
+
readonly workerName?: string;
|
|
40
|
+
/** Test/custom-host escape hatch. The client owns and terminates each worker. */
|
|
41
|
+
readonly workerFactory?: (index: number) => Worker;
|
|
42
|
+
}
|
|
43
|
+
export interface PdfBatchJob<Id> {
|
|
44
|
+
readonly id: Id;
|
|
45
|
+
readonly request: AnyPdfRequest;
|
|
46
|
+
readonly timeoutMs?: number;
|
|
47
|
+
}
|
|
48
|
+
export type PdfBatchOutcome<Id> = {
|
|
49
|
+
readonly id: Id;
|
|
50
|
+
readonly index: number;
|
|
51
|
+
readonly status: 'success';
|
|
52
|
+
readonly result: PdfResult;
|
|
53
|
+
} | {
|
|
54
|
+
readonly id: Id;
|
|
55
|
+
readonly index: number;
|
|
56
|
+
readonly status: 'error';
|
|
57
|
+
readonly error: TypfolioWorkerError;
|
|
58
|
+
} | {
|
|
59
|
+
readonly id: Id;
|
|
60
|
+
readonly index: number;
|
|
61
|
+
readonly status: 'cancelled';
|
|
62
|
+
};
|
|
63
|
+
export interface PdfBatchProgress<Id> {
|
|
64
|
+
readonly total: number;
|
|
65
|
+
readonly completed: number;
|
|
66
|
+
readonly succeeded: number;
|
|
67
|
+
readonly failed: number;
|
|
68
|
+
readonly cancelled: number;
|
|
69
|
+
readonly latestJobId?: Id;
|
|
70
|
+
}
|
|
71
|
+
export interface PdfBatchOptions<Id> {
|
|
72
|
+
readonly signal?: AbortSignal;
|
|
73
|
+
readonly onItemSettled?: (outcome: PdfBatchOutcome<Id>, progress: PdfBatchProgress<Id>) => void;
|
|
74
|
+
readonly onProgress?: (progress: PdfBatchProgress<Id>) => void;
|
|
75
|
+
}
|
|
76
|
+
export type WorkerErrorCode = ErrorCode | 'WORKER' | 'TIMEOUT' | 'QUEUE_FULL';
|
|
77
|
+
export declare class TypfolioWorkerError extends Error {
|
|
78
|
+
readonly code: WorkerErrorCode;
|
|
79
|
+
readonly diagnostics: readonly Diagnostic[];
|
|
80
|
+
readonly name = "TypfolioWorkerError";
|
|
81
|
+
constructor(code: WorkerErrorCode, message: string, diagnostics?: readonly Diagnostic[], options?: ErrorOptions);
|
|
82
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type RuntimeMessage } from './protocol.js';
|
|
2
|
+
export interface WorkerRuntimeScope {
|
|
3
|
+
addEventListener(type: 'message', listener: (event: MessageEvent<unknown>) => void): void;
|
|
4
|
+
postMessage(message: RuntimeMessage, transfer?: readonly Transferable[]): void;
|
|
5
|
+
}
|
|
6
|
+
export declare function installWorkerRuntime(scope: WorkerRuntimeScope): void;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createCompiler, TypstPdfError } from '@typfolio/core';
|
|
2
|
+
import { decodeHostMessage, protocolVersion } from './protocol.js';
|
|
3
|
+
function errorMessage(error) {
|
|
4
|
+
if (error instanceof Error)
|
|
5
|
+
return error.message;
|
|
6
|
+
return String(error);
|
|
7
|
+
}
|
|
8
|
+
function serializeError(error) {
|
|
9
|
+
if (error instanceof TypstPdfError) {
|
|
10
|
+
return { code: error.code, message: error.message, diagnostics: error.diagnostics };
|
|
11
|
+
}
|
|
12
|
+
return { code: 'WORKER', message: errorMessage(error), diagnostics: [] };
|
|
13
|
+
}
|
|
14
|
+
function transferable(bytes) {
|
|
15
|
+
return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
|
|
16
|
+
}
|
|
17
|
+
export function installWorkerRuntime(scope) {
|
|
18
|
+
let compiler;
|
|
19
|
+
let initializing;
|
|
20
|
+
scope.addEventListener('message', event => {
|
|
21
|
+
let requestId;
|
|
22
|
+
try {
|
|
23
|
+
const message = decodeHostMessage(event.data);
|
|
24
|
+
if (message.type === 'initialize') {
|
|
25
|
+
if (initializing || compiler)
|
|
26
|
+
throw new Error('Typfolio worker is already initialized');
|
|
27
|
+
// The request is owned by this worker (a transferred snapshot), so core need not copy its assets again.
|
|
28
|
+
initializing = createCompiler({ ...message.compiler, copyAssets: false }).then(value => {
|
|
29
|
+
compiler = value;
|
|
30
|
+
scope.postMessage({ protocol: protocolVersion, type: 'ready' });
|
|
31
|
+
}).catch(error => {
|
|
32
|
+
scope.postMessage({ protocol: protocolVersion, type: 'failure', error: serializeError(error) });
|
|
33
|
+
});
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
requestId = message.id;
|
|
37
|
+
if (!compiler)
|
|
38
|
+
throw new Error('Typfolio worker is not ready');
|
|
39
|
+
void compiler.compile(message.request).then(result => {
|
|
40
|
+
const bytes = transferable(result.bytes);
|
|
41
|
+
scope.postMessage({
|
|
42
|
+
protocol: protocolVersion,
|
|
43
|
+
type: 'result',
|
|
44
|
+
id: message.id,
|
|
45
|
+
result: { ...result, bytes },
|
|
46
|
+
}, [bytes.buffer]);
|
|
47
|
+
}).catch(error => {
|
|
48
|
+
scope.postMessage({
|
|
49
|
+
protocol: protocolVersion,
|
|
50
|
+
type: 'failure',
|
|
51
|
+
id: message.id,
|
|
52
|
+
error: serializeError(error),
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
scope.postMessage({
|
|
58
|
+
protocol: protocolVersion,
|
|
59
|
+
type: 'failure',
|
|
60
|
+
id: requestId,
|
|
61
|
+
error: serializeError(error),
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@typfolio/workers",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Framework-independent Web Worker execution for Typfolio PDF compilation",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"keywords": ["typst", "pdf", "wasm", "webassembly", "web-worker", "browser", "concurrency"],
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/HelioCampus/typfolio.git",
|
|
11
|
+
"directory": "packages/workers"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/HelioCampus/typfolio#readme",
|
|
14
|
+
"bugs": { "url": "https://github.com/HelioCampus/typfolio/issues" },
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"exports": {
|
|
21
|
+
".": {
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js"
|
|
24
|
+
},
|
|
25
|
+
"./runtime": "./dist/runtime.js"
|
|
26
|
+
},
|
|
27
|
+
"dependencies": {
|
|
28
|
+
"@typfolio/core": "^0.2.0",
|
|
29
|
+
"effect": "4.0.0-rc.118"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"engines": { "node": ">=22" },
|
|
35
|
+
"sideEffects": [
|
|
36
|
+
"./dist/runtime.js"
|
|
37
|
+
]
|
|
38
|
+
}
|