@tbela99/rust-css-parser-wasm 0.0.0-stage → 2.3.1

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.
@@ -0,0 +1,505 @@
1
+ // Runtime shared by the N-API and the WASM backends: the value encoding (see src/bindings/value.rs), the calls to
2
+ // rust, the javascript callbacks called by rust and the async calls driven by javascript.
3
+ //
4
+ // A backend provides:
5
+ // - exchange(capacity): Uint8Array view of the exchange buffer, at least `capacity` bytes
6
+ // - invoke(length): run the call encoded in the exchange buffer, return the result length
7
+ // - column(handle, index, Type): typed array view of an arena column
8
+ // - generation(handle): Uint32Array view of the generation counter of an arena
9
+ // - setHost(fn): the function rust calls to run a callback: (length) => responseLength
10
+
11
+ const encoder = new TextEncoder();
12
+ const decoder = new TextDecoder();
13
+
14
+ const ARENAID = Symbol.for("@tbela99/css-parser/ARENAID");
15
+ const ARENA = Symbol.for("@tbela99/css-parser/ARENA");
16
+
17
+ const TAG = {
18
+ undefined: 0,
19
+ null: 1,
20
+ false: 2,
21
+ true: 3,
22
+ number: 4,
23
+ string: 5,
24
+ bytes: 6,
25
+ array: 7,
26
+ object: 8,
27
+ function: 9,
28
+ arena: 10,
29
+ node: 11,
30
+ promise: 12,
31
+ error: 13,
32
+ output: 14,
33
+ };
34
+
35
+ /**
36
+ * growable output buffer of the encoder
37
+ */
38
+ class Output {
39
+ bytes = new Uint8Array(1 << 12);
40
+ view = new DataView(this.bytes.buffer);
41
+ length = 0;
42
+
43
+ reserve(size) {
44
+ if (this.length + size > this.bytes.length) {
45
+ let capacity = this.bytes.length * 2;
46
+
47
+ while (capacity < this.length + size) {
48
+ capacity *= 2;
49
+ }
50
+
51
+ const bytes = new Uint8Array(capacity);
52
+
53
+ bytes.set(this.bytes.subarray(0, this.length));
54
+ this.bytes = bytes;
55
+ this.view = new DataView(bytes.buffer);
56
+ }
57
+ }
58
+
59
+ u8(v) {
60
+ this.reserve(1);
61
+ this.bytes[this.length++] = v;
62
+ }
63
+
64
+ u32(v) {
65
+ this.reserve(4);
66
+ this.view.setUint32(this.length, v, true);
67
+ this.length += 4;
68
+ }
69
+
70
+ f64(v) {
71
+ this.reserve(8);
72
+ this.view.setFloat64(this.length, v, true);
73
+ this.length += 8;
74
+ }
75
+
76
+ string(s) {
77
+ // at most 3 bytes per utf-16 code unit
78
+ this.reserve(4 + s.length * 3);
79
+ const { written } = encoder.encodeInto(s, this.bytes.subarray(this.length + 4));
80
+ this.view.setUint32(this.length, written, true);
81
+ this.length += 4 + written;
82
+ }
83
+
84
+ raw(bytes) {
85
+ this.u32(bytes.byteLength);
86
+ this.reserve(bytes.byteLength);
87
+ this.bytes.set(bytes, this.length);
88
+ this.length += bytes.byteLength;
89
+ }
90
+ }
91
+
92
+ /**
93
+ * the content of a stream: the resolved values of the callbacks (load()) are read before they are sent to rust
94
+ */
95
+ export async function readAll(value) {
96
+ if (typeof ReadableStream === "undefined" || !(value instanceof ReadableStream)) {
97
+ return value;
98
+ }
99
+
100
+ const chunks = [];
101
+ let length = 0;
102
+ let text = false;
103
+
104
+ for await (const chunk of value) {
105
+ if (typeof chunk === "string") {
106
+ text = true;
107
+ }
108
+
109
+ chunks.push(chunk);
110
+ length += chunk.length;
111
+ }
112
+
113
+ if (text) {
114
+ return chunks.map((chunk) => (typeof chunk === "string" ? chunk : decoder.decode(chunk))).join("");
115
+ }
116
+
117
+ const result = new Uint8Array(length);
118
+ let offset = 0;
119
+
120
+ for (const chunk of chunks) {
121
+ result.set(chunk, offset);
122
+ offset += chunk.length;
123
+ }
124
+
125
+ return result;
126
+ }
127
+
128
+ export class Runtime {
129
+ /**
130
+ * the arena wrappers by handle: an arena returned twice is the same object
131
+ */
132
+ arenas = new Map();
133
+ /**
134
+ * the callbacks passed to rust, by id
135
+ */
136
+ callbacks = new Map();
137
+ callbackIds = new WeakMap();
138
+ nextCallback = 1;
139
+ /**
140
+ * the promises returned by the callbacks, by id
141
+ */
142
+ promises = new Map();
143
+ nextPromise = 1;
144
+ output = new Output();
145
+ depth = 0;
146
+ touched = null;
147
+
148
+ /**
149
+ * @param backend
150
+ * @param classes the classes created from the values: { wrapArena(handle), AstArenaNode, isArena(value), handleOf(arena) }
151
+ */
152
+ constructor(backend, classes) {
153
+ this.backend = backend;
154
+ this.classes = classes;
155
+ backend.setHost((length) => this.host(length));
156
+ }
157
+
158
+ touch(arena) {
159
+ if (this.touched != null && this.classes.isExported(arena) && !this.touched.includes(arena)) {
160
+ this.touched.push(arena);
161
+ }
162
+ }
163
+
164
+ encode(value, out) {
165
+ switch (typeof value) {
166
+ case "undefined":
167
+ out.u8(TAG.undefined);
168
+ return;
169
+ case "boolean":
170
+ out.u8(value ? TAG.true : TAG.false);
171
+ return;
172
+ case "number":
173
+ out.u8(TAG.number);
174
+ out.f64(value);
175
+ return;
176
+ case "bigint":
177
+ out.u8(TAG.number);
178
+ out.f64(Number(value));
179
+ return;
180
+ case "string":
181
+ out.u8(TAG.string);
182
+ out.string(value);
183
+ return;
184
+ case "function": {
185
+ let id = this.callbackIds.get(value);
186
+
187
+ if (id === undefined) {
188
+ id = this.nextCallback++;
189
+ this.callbackIds.set(value, id);
190
+ this.callbacks.set(id, value);
191
+ }
192
+
193
+ out.u8(TAG.function);
194
+ out.u32(id);
195
+ out.string(value.name ?? "");
196
+ return;
197
+ }
198
+ case "symbol":
199
+ out.u8(TAG.undefined);
200
+ return;
201
+ }
202
+
203
+ if (value === null) {
204
+ out.u8(TAG.null);
205
+ return;
206
+ }
207
+
208
+ if (value instanceof Uint8Array) {
209
+ out.u8(TAG.bytes);
210
+ out.raw(value);
211
+ return;
212
+ }
213
+
214
+ if (value instanceof ArrayBuffer) {
215
+ out.u8(TAG.bytes);
216
+ out.raw(new Uint8Array(value));
217
+ return;
218
+ }
219
+
220
+ if (ArrayBuffer.isView(value)) {
221
+ out.u8(TAG.bytes);
222
+ out.raw(new Uint8Array(value.buffer, value.byteOffset, value.byteLength));
223
+ return;
224
+ }
225
+
226
+ if (Array.isArray(value)) {
227
+ out.u8(TAG.array);
228
+ out.u32(value.length);
229
+
230
+ for (const item of value) {
231
+ this.encode(item, out);
232
+ }
233
+
234
+ return;
235
+ }
236
+
237
+ if (this.classes.isArena(value)) {
238
+ this.touch(value);
239
+ out.u8(TAG.arena);
240
+ out.u32(this.classes.handleOf(value, this));
241
+ return;
242
+ }
243
+
244
+ if (value instanceof this.classes.AstArenaNode) {
245
+ this.touch(value[ARENA]);
246
+ out.u8(TAG.node);
247
+ out.u32(this.classes.handleOf(value[ARENA], this));
248
+ out.u32(value[ARENAID]);
249
+ return;
250
+ }
251
+
252
+ if (typeof value.then === "function") {
253
+ const id = this.nextPromise++;
254
+
255
+ this.promises.set(id, value);
256
+ out.u8(TAG.promise);
257
+ out.u32(id);
258
+ return;
259
+ }
260
+
261
+ if (value instanceof Map || value instanceof Set || value instanceof WeakMap) {
262
+ out.u8(TAG.undefined);
263
+ return;
264
+ }
265
+
266
+ // a class instance that knows its encoding (SourceMap, ...)
267
+ if (typeof value.toJSON === "function" && Object.getPrototypeOf(value) !== Object.prototype) {
268
+ this.encode(value.toJSON(), out);
269
+ return;
270
+ }
271
+
272
+ const keys = Object.keys(value);
273
+
274
+ out.u8(TAG.object);
275
+ out.u32(keys.length);
276
+
277
+ for (const key of keys) {
278
+ out.string(key);
279
+ this.encode(value[key], out);
280
+ }
281
+ }
282
+
283
+ decode(bytes, state) {
284
+ const view = state.view;
285
+ const tag = bytes[state.pos++];
286
+
287
+ const u32 = () => {
288
+ const v = view.getUint32(state.pos, true);
289
+ state.pos += 4;
290
+ return v;
291
+ };
292
+
293
+ const string = () => {
294
+ const length = u32();
295
+ const s = decoder.decode(bytes.subarray(state.pos, state.pos + length));
296
+ state.pos += length;
297
+ return s;
298
+ };
299
+
300
+ switch (tag) {
301
+ case TAG.undefined:
302
+ return undefined;
303
+ case TAG.null:
304
+ return null;
305
+ case TAG.false:
306
+ return false;
307
+ case TAG.true:
308
+ return true;
309
+ case TAG.number: {
310
+ const v = view.getFloat64(state.pos, true);
311
+ state.pos += 8;
312
+ return v;
313
+ }
314
+ case TAG.string:
315
+ return string();
316
+ case TAG.bytes: {
317
+ const length = u32();
318
+ // a copy: the exchange buffer is reused by the next call
319
+ const result = bytes.slice(state.pos, state.pos + length);
320
+ state.pos += length;
321
+ return result;
322
+ }
323
+ case TAG.array: {
324
+ const n = u32();
325
+ const result = new Array(n);
326
+
327
+ for (let i = 0; i < n; i++) {
328
+ result[i] = this.decode(bytes, state);
329
+ }
330
+
331
+ return result;
332
+ }
333
+ case TAG.object: {
334
+ const n = u32();
335
+ const result = {};
336
+
337
+ for (let i = 0; i < n; i++) {
338
+ const key = string();
339
+ result[key] = this.decode(bytes, state);
340
+ }
341
+
342
+ return result;
343
+ }
344
+ case TAG.function: {
345
+ const id = u32();
346
+ string();
347
+ return this.callbacks.get(id);
348
+ }
349
+ case TAG.arena:
350
+ return this.classes.wrapArena(u32(), this);
351
+ case TAG.node: {
352
+ const arena = this.classes.wrapArena(u32(), this);
353
+ return new this.classes.AstArenaNode(arena, u32());
354
+ }
355
+ case TAG.promise:
356
+ return this.promises.get(u32());
357
+ case TAG.output: {
358
+ const id = u32();
359
+ const length = u32();
360
+ return new Uint8Array(this.backend.output(id), 0, length);
361
+ }
362
+ case TAG.error: {
363
+ const error = new Error(string());
364
+
365
+ error.fromRust = true;
366
+ return error;
367
+ }
368
+ }
369
+
370
+ throw new Error(`invalid value tag ${tag}`);
371
+ }
372
+
373
+ /**
374
+ * write a value in the exchange buffer. returns the length
375
+ */
376
+ write(value) {
377
+ const out = this.output;
378
+
379
+ out.length = 0;
380
+ this.encode(value, out);
381
+
382
+ const target = this.backend.exchange(out.length);
383
+
384
+ target.set(out.bytes.subarray(0, out.length));
385
+ return out.length;
386
+ }
387
+
388
+ read(length) {
389
+ const bytes = this.backend.exchange(length);
390
+ return this.decode(bytes, { pos: 0, view: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) });
391
+ }
392
+
393
+ /**
394
+ * call a rust function
395
+ */
396
+ call(method, ...args) {
397
+ // the arenas whose columns are javascript buffers (transferred arenas) and that are arguments of the outermost
398
+ // call are synchronized with rust around it
399
+ const outer = this.depth === 0;
400
+ const touched = outer ? (this.touched = []) : null;
401
+ const out = this.output;
402
+
403
+ out.length = 0;
404
+
405
+ try {
406
+ this.encode([method, ...args], out);
407
+ } finally {
408
+ this.touched = null;
409
+ }
410
+
411
+ let request = out.bytes.subarray(0, out.length);
412
+
413
+ if (touched !== null && touched.length > 0) {
414
+ // the synchronization calls reuse the output buffer
415
+ request = request.slice();
416
+ this.depth++;
417
+
418
+ try {
419
+ this.classes.beforeCall(touched);
420
+ } finally {
421
+ this.depth--;
422
+ }
423
+ }
424
+
425
+ this.backend.exchange(request.length).set(request);
426
+ this.depth++;
427
+
428
+ let result;
429
+
430
+ try {
431
+ result = this.read(this.backend.invoke(request.length));
432
+ } finally {
433
+ this.depth--;
434
+
435
+ if (touched !== null && touched.length > 0) {
436
+ this.classes.afterCall(touched);
437
+ }
438
+ }
439
+
440
+ if (result instanceof Error && result.fromRust) {
441
+ delete result.fromRust;
442
+ throw result;
443
+ }
444
+
445
+ return result;
446
+ }
447
+
448
+ /**
449
+ * run a callback for rust: the request is `[callback, arena, ...args]`
450
+ */
451
+ host(length) {
452
+ let result;
453
+
454
+ try {
455
+ const [id, arena, ...args] = this.read(length);
456
+ const callback = this.callbacks.get(id);
457
+
458
+ result = arena === undefined ? callback(...args) : callback(arena, ...args);
459
+ } catch (error) {
460
+ return this.writeError(error);
461
+ }
462
+
463
+ return this.write(result);
464
+ }
465
+
466
+ writeError(error) {
467
+ const out = this.output;
468
+
469
+ out.length = 0;
470
+ out.u8(TAG.error);
471
+ out.string(error?.message ?? String(error));
472
+
473
+ const target = this.backend.exchange(out.length);
474
+
475
+ target.set(out.bytes.subarray(0, out.length));
476
+ return out.length;
477
+ }
478
+
479
+ /**
480
+ * drive an async rust call (parse(), transform()) until it completes
481
+ */
482
+ async run(task) {
483
+ for (;;) {
484
+ const state = this.call("poll", task);
485
+
486
+ if (state.done) {
487
+ return state.value;
488
+ }
489
+
490
+ await Promise.all(
491
+ state.pending.map(async (id) => {
492
+ const promise = this.promises.get(id);
493
+
494
+ this.promises.delete(id);
495
+
496
+ try {
497
+ this.call("settle", id, true, await readAll(await promise));
498
+ } catch (error) {
499
+ this.call("settle", id, false, error?.message ?? String(error));
500
+ }
501
+ }),
502
+ );
503
+ }
504
+ }
505
+ }
@@ -0,0 +1,6 @@
1
+ import { runtimeOf } from "../../core.js";
2
+ import "../../ast/arena.js";
3
+
4
+ export function convertColor(arena, token, to) {
5
+ return runtimeOf(arena).call("convertColor", arena, token, to);
6
+ }
@@ -0,0 +1,10 @@
1
+ import { runtimeOf } from "../../../core.js";
2
+ import "../../../ast/arena.js";
3
+
4
+ export function okLabDistance(arena, color1, color2) {
5
+ return runtimeOf(arena).call("okLabDistance", arena, color1, color2);
6
+ }
7
+
8
+ export function isOkLabClose(arena, color1, color2, threshold) {
9
+ return runtimeOf(arena).call("isOkLabClose", arena, color1, color2, threshold);
10
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export { ResponseType } from "./enums-extra.js";
@@ -0,0 +1,58 @@
1
+ import { rt } from "../core.js";
2
+
3
+ /**
4
+ * reference of a token list of a parsed syntax (a hidden property of the arrays)
5
+ */
6
+ export const SYNTAX = Symbol("syntax");
7
+
8
+ const syntaxes = new Map();
9
+
10
+ /**
11
+ * tag the token lists with their path in the syntax
12
+ */
13
+ function tag(list, handle, path) {
14
+ Object.defineProperty(list, SYNTAX, { value: { handle, path } });
15
+
16
+ for (let i = 0; i < list.length; i++) {
17
+ const token = list[i];
18
+
19
+ for (const field of ["chi", "l", "r", "prelude"]) {
20
+ const value = token?.[field];
21
+
22
+ if (!Array.isArray(value)) {
23
+ continue;
24
+ }
25
+
26
+ const fieldPath = [...path, i, field];
27
+
28
+ if (value.length > 0 && Array.isArray(value[0])) {
29
+ Object.defineProperty(value, SYNTAX, { value: { handle, path: fieldPath } });
30
+ value.forEach((alternative, j) => tag(alternative, handle, [...fieldPath, j]));
31
+ } else {
32
+ tag(value, handle, fieldPath);
33
+ }
34
+ }
35
+ }
36
+
37
+ return list;
38
+ }
39
+
40
+ /**
41
+ * the parsed syntax of a property, a function, ...: the same object is returned for the same syntax
42
+ */
43
+ export function getParsedSyntax(group, key) {
44
+ const result = rt.call("getParsedSyntax", group, key);
45
+
46
+ if (result === null) {
47
+ return null;
48
+ }
49
+
50
+ let tokens = syntaxes.get(result.handle);
51
+
52
+ if (tokens === undefined) {
53
+ tokens = tag(result.tokens, result.handle, []);
54
+ syntaxes.set(result.handle, tokens);
55
+ }
56
+
57
+ return tokens;
58
+ }
@@ -0,0 +1,21 @@
1
+ import { runtimeOf } from "../core.js";
2
+ import "../ast/arena.js";
3
+ import { SYNTAX } from "./config.js";
4
+
5
+ function reference(list) {
6
+ const ref = list?.[SYNTAX];
7
+
8
+ if (ref === undefined) {
9
+ throw new TypeError("the syntax must be a value returned by getParsedSyntax()");
10
+ }
11
+
12
+ return ref;
13
+ }
14
+
15
+ export function matchingAlternatives(arena, alternatives, token) {
16
+ return runtimeOf(arena).call("matchingAlternatives", arena, reference(alternatives), token);
17
+ }
18
+
19
+ export function mayStartWith(arena, syntaxes, token) {
20
+ return runtimeOf(arena).call("mayStartWith", arena, reference(syntaxes), token);
21
+ }
@@ -0,0 +1,5 @@
1
+ import { rt } from "../../core.js";
2
+
3
+ export function parseSyntax(syntax) {
4
+ return rt.call("parseSyntax", syntax);
5
+ }