@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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present Thierry Bela
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @tbela99/rust-css-parser-wasm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CSS parser, validator, minifier and renderer for Node.js, Deno, Bun and the browsers, with a WebAssembly module: the Rust port of
4
+ [@tbela99/css-parser](https://github.com/tbela99/css-parser), with the same JavaScript API.
5
+
6
+ ```shell
7
+ npm install @tbela99/rust-css-parser-wasm
8
+ # or
9
+ npx jsr add @tbela99/rust-css-parser-wasm
10
+ ```
11
+
12
+ ```js
13
+ import { transform, ColorType } from "@tbela99/rust-css-parser-wasm"; // node, deno, bun
14
+ // import { transform, ColorType } from "@tbela99/rust-css-parser-wasm/web"; // browsers
15
+
16
+ const result = await transform(".a { color: rgb(255 0 0); width: calc(1px + 2px) }", {
17
+ beautify: true,
18
+ convertColor: ColorType.SRGB,
19
+ });
20
+
21
+ console.log(result.code);
22
+ ```
23
+
24
+ See the [guides](https://github.com/tbela99/rust-css-parser/tree/master/files) for the API.
25
+
26
+ ## License
27
+
28
+ [MIT](LICENSE.md)
package/dist/api.js ADDED
@@ -0,0 +1,142 @@
1
+ // Entry points shared by node.js and web.js (port of src/node.ts / src/web.ts and src/utils/sync.ts): the options
2
+ // are completed like the typescript entry points, the work is done by rust.
3
+
4
+ import { readAll, rt as defaultRuntime, runtimeOf } from "./core.js";
5
+ import "./ast/arena.js";
6
+ import { ModuleScopeEnumOptions } from "./ast/types.js";
7
+ import { ResponseType } from "./enums-extra.js";
8
+ import { RenderResult, TransformResult } from "./printer/result.js";
9
+ import { renderResult } from "./printer/render.js";
10
+
11
+ export { readAll };
12
+
13
+ /**
14
+ * the inputs accepted as css: a string or utf-8 bytes
15
+ */
16
+ export function isCssInput(value) {
17
+ return typeof value === "string" || value instanceof ArrayBuffer || ArrayBuffer.isView(value);
18
+ }
19
+
20
+ export function validateSyncArguments(options, prefix = "options.") {
21
+ for (const [key, value] of Object.entries(options)) {
22
+ if (typeof value === "function") {
23
+ if (value instanceof Promise || Object.getPrototypeOf(value).constructor.name == "AsyncFunction") {
24
+ throw new Error(`[${prefix + key}]: Async functions are not supported in sync mode. Use parse() or transform() instead.`);
25
+ }
26
+ } else if (
27
+ value != null &&
28
+ typeof value === "object" &&
29
+ (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
30
+ ) {
31
+ validateSyncArguments(value, prefix + key + ".");
32
+ }
33
+ }
34
+ }
35
+
36
+ function isIcss(options) {
37
+ return (
38
+ (typeof options.module === "number" && options.module & ModuleScopeEnumOptions.ICSS) ||
39
+ (typeof options.module === "object" && options.module != null && typeof options.module.scoped === "number" && options.module.scoped & ModuleScopeEnumOptions.ICSS)
40
+ );
41
+ }
42
+
43
+ function transformResult(result) {
44
+ return new TransformResult(result.parse, renderResult(result.render), result.stats);
45
+ }
46
+
47
+ function transformDefaults(options) {
48
+ options = { ...options };
49
+ options.minify ??= true;
50
+ options.removeEmpty ??= true;
51
+ options.removeCharset ??= true;
52
+ return options;
53
+ }
54
+
55
+ /**
56
+ * the arguments `(input, options)` or `({ input, ...options })`
57
+ */
58
+ function splitArguments(args, stream) {
59
+ if (isCssInput(args[0]) || (stream && typeof ReadableStream !== "undefined" && args[0] instanceof ReadableStream)) {
60
+ return [args[0], args[1], null];
61
+ }
62
+
63
+ const { file, input, ...options } = args[0] ?? {};
64
+ return [input, options, file];
65
+ }
66
+
67
+ /**
68
+ * @param host `{ load, cwd(), runtime }`: the default loader, the current directory of the platform and the runtime of
69
+ * the backend (the default runtime when it is not set)
70
+ */
71
+ export function createApi(host) {
72
+ const { load } = host;
73
+ const rt = host.runtime ?? defaultRuntime;
74
+
75
+ function render(arena, data, options = {}, mapping) {
76
+ return renderResult(runtimeOf(arena).call("render", arena, data, { ...options, cwd: options.cwd ?? host.cwd() }, mapping ?? null, false));
77
+ }
78
+
79
+ function parseSync(...args) {
80
+ const [stream, options] = splitArguments(args, false);
81
+
82
+ if (options != null) {
83
+ validateSyncArguments(options);
84
+ }
85
+
86
+ return rt.call("parseSync", stream, { ...options, cwd: options?.cwd ?? host.cwd() });
87
+ }
88
+
89
+ function transformSync(...args) {
90
+ const [stream, opts] = splitArguments(args, false);
91
+
92
+ if (opts != null) {
93
+ validateSyncArguments(opts);
94
+ }
95
+
96
+ const options = transformDefaults(opts);
97
+
98
+ options.cwd ??= host.cwd();
99
+ return transformResult(rt.call("transformSync", stream, options));
100
+ }
101
+
102
+ function loadFile(file, options) {
103
+ return Promise.resolve(
104
+ options.load != null
105
+ ? options.load(file, "", options.asStream ?? false)
106
+ : load(file, "", options.asStream ? ResponseType.ReadableStream : ResponseType.ArrayBuffer),
107
+ );
108
+ }
109
+
110
+ async function parse(...args) {
111
+ const [stream, options = {}, file] = splitArguments(args, true);
112
+
113
+ if (file != null) {
114
+ return loadFile(file, options).then((stream) => parse(stream, { src: file, ...options }));
115
+ }
116
+
117
+ const input = await readAll(stream);
118
+
119
+ return rt.run(rt.call("parse", input, { ...options, load: options.load ?? load, cwd: options.cwd ?? host.cwd() }));
120
+ }
121
+
122
+ async function transform(...args) {
123
+ const [stream, opts = {}, file] = splitArguments(args, true);
124
+
125
+ if (file != null) {
126
+ return loadFile(file, opts).then((stream) => transform(stream, { src: file, ...opts }));
127
+ }
128
+
129
+ const options = transformDefaults(opts);
130
+
131
+ options.load ??= load;
132
+ options.cwd ??= host.cwd();
133
+
134
+ const input = await readAll(stream);
135
+
136
+ return transformResult(await rt.run(rt.call("transform", input, options)));
137
+ }
138
+
139
+ return { render, parse, parseSync, transform, transformSync };
140
+ }
141
+
142
+ export { isIcss, RenderResult, TransformResult };
@@ -0,0 +1,96 @@
1
+ // Object view of an arena node (port of src/ast/arena-node.ts): the properties are read from and written to the
2
+ // rust arena when they are accessed.
3
+
4
+ import { EnumToken } from "./types.js";
5
+ import { runtimeOf } from "../core.js";
6
+
7
+ export const ARENAID = Symbol.for("@tbela99/css-parser/ARENAID");
8
+ export const ARENA = Symbol.for("@tbela99/css-parser/ARENA");
9
+
10
+ export function isNodeObjectType(typ) {
11
+ switch (typ) {
12
+ case EnumToken.StyleSheetNodeType:
13
+ case EnumToken.RuleNodeType:
14
+ case EnumToken.KeyframesRuleNodeType:
15
+ case EnumToken.AtRuleNodeType:
16
+ case EnumToken.KeyframesAtRuleNodeType:
17
+ case EnumToken.CommentNodeType:
18
+ case EnumToken.CDOCOMMNodeType:
19
+ case EnumToken.DeclarationNodeType:
20
+ case EnumToken.CssVariableTokenType:
21
+ case EnumToken.CssVariableImportTokenType:
22
+ case EnumToken.CssVariableDeclarationMapTokenType:
23
+ return true;
24
+ }
25
+
26
+ return false;
27
+ }
28
+
29
+ function frozen(value) {
30
+ return Array.isArray(value) ? Object.freeze(value) : value;
31
+ }
32
+
33
+ function get(node, key) {
34
+ return frozen(runtimeOf(node[ARENA]).call("a.nodeGet", node[ARENA], node[ARENAID], key));
35
+ }
36
+
37
+ function set(node, key, value) {
38
+ runtimeOf(node[ARENA]).call("a.nodeSet", node[ARENA], node[ARENAID], key, value);
39
+ }
40
+
41
+ export class AstArenaNode {
42
+ constructor(arena, id) {
43
+ this[ARENA] = arena;
44
+ this[ARENAID] = id;
45
+ }
46
+
47
+ get typ() {
48
+ return this[ARENA].dataTypes[this[ARENAID]];
49
+ }
50
+
51
+ set typ(typ) {
52
+ this[ARENA].dataTypes[this[ARENAID]] = typ;
53
+ }
54
+
55
+ toJSON() {
56
+ return runtimeOf(this[ARENA]).call("a.nodeJSON", this[ARENA], this[ARENAID]);
57
+ }
58
+
59
+ [Symbol.for("nodejs.util.inspect.custom")]() {
60
+ return this.toJSON();
61
+ }
62
+ }
63
+
64
+ for (const key of [
65
+ "nam",
66
+ "sel",
67
+ "val",
68
+ "chi",
69
+ "tokens",
70
+ "unit",
71
+ "cal",
72
+ "attr",
73
+ "kin",
74
+ "sign",
75
+ "op",
76
+ "op1",
77
+ "op2",
78
+ "l",
79
+ "r",
80
+ "loc",
81
+ "state",
82
+ "errors",
83
+ "parent",
84
+ ]) {
85
+ Object.defineProperty(AstArenaNode.prototype, key, {
86
+ configurable: true,
87
+ enumerable: false,
88
+ get() {
89
+ const value = get(this, key);
90
+ return key === "loc" && value != null ? Object.freeze(value) : value;
91
+ },
92
+ set(value) {
93
+ set(this, key, value);
94
+ },
95
+ });
96
+ }