tailwind.com 0.4.0 → 0.6.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/js/engine.mjs ADDED
@@ -0,0 +1,285 @@
1
+ // The JavaScript engine of the host for tailwind.wasm: the imports of the
2
+ // module "tailwind_js" (the feature `host-js` of the crate,
3
+ // native/tailwind/src/compat/js/engine.rs). They do what c_src/js.c does
4
+ // with QuickJS in tailwind.com, for `@plugin` and `@config`:
5
+ //
6
+ // - Each engine is a realm: a hidden <iframe> of the page, or a context of
7
+ // node:vm in Node.js (js/node.mjs). The plugin layer changes the globals
8
+ // of its realm (process, Buffer, the timers), so it does not run in the
9
+ // page or the program itself.
10
+ // - JavaScript calls the program with `__host(op, text)`, through the
11
+ // exports tw_host_call and tw_host_release.
12
+ // - The JavaScript files of the program (the plugin layer, the TypeScript
13
+ // transform and the three plugins of the standalone program) are not in
14
+ // tailwind.wasm: `asset` gives them.
15
+ // - A browser cannot import a file that is only in memory: an ES module
16
+ // becomes CommonJS with the `imports` transform of Sucrase.
17
+ // - The plugin layer waits for its promises in `tw_js_call_async`, the
18
+ // only import that suspends the program (JS Promise Integration). The
19
+ // program starts with WebAssembly.promising (js/wasi.mjs).
20
+
21
+ const encoder = new TextEncoder();
22
+ const decoder = new TextDecoder();
23
+
24
+ // True when the browser has JS Promise Integration.
25
+ export const hasPromiseIntegration = typeof WebAssembly.Suspending === 'function' && typeof WebAssembly.promising === 'function';
26
+
27
+ // True when the module has the imports of this engine.
28
+ export function needsEngine(module) {
29
+ return WebAssembly.Module.imports(module).some((item) => item.module === 'tailwind_js');
30
+ }
31
+
32
+ // The engine of one run: { imports, dispose }. `imports` are the imports
33
+ // of the module "tailwind_js". `exports` gives the exports of the instance
34
+ // (after it is made). `asset(name)` gives a JavaScript file of the program
35
+ // by its name ("compat", "typescript", "plugin:@tailwindcss/typography"),
36
+ // or undefined. options.realm makes a realm: { global, dispose } (default:
37
+ // a hidden <iframe> of the page). The program ends with proc_exit and does
38
+ // not free its engines: `dispose` removes their realms after the run.
39
+ export function createEngine(exports, asset = () => undefined, options = {}) {
40
+ const engines = new Map();
41
+ let nextId = 1;
42
+
43
+ const bytes = () => new Uint8Array(exports().memory.buffer);
44
+ const view = () => new DataView(exports().memory.buffer);
45
+
46
+ function readText(pointer, length) {
47
+ if (length === undefined) {
48
+ const memory = bytes();
49
+ let end = pointer;
50
+ while (memory[end] !== 0) end++;
51
+ length = end - pointer;
52
+ }
53
+ return decoder.decode(bytes().slice(pointer, pointer + length));
54
+ }
55
+
56
+ // Text with a NUL at its end, in memory from tw_host_alloc.
57
+ function writeText(text) {
58
+ const data = encoder.encode(String(text).replaceAll('\0', ''));
59
+ const pointer = exports().tw_host_alloc(data.length + 1);
60
+ const memory = bytes();
61
+ memory.set(data, pointer);
62
+ memory[pointer + data.length] = 0;
63
+ return pointer;
64
+ }
65
+
66
+ function setOut(pointer, text) {
67
+ if (pointer) view().setUint32(pointer, text === null || text === undefined ? 0 : writeText(text), true);
68
+ }
69
+
70
+ // The message to `out`, and the name, a line end and the stack to
71
+ // `stack`, as take_exception of js.c.
72
+ function exception(error, out, stack) {
73
+ let message = null;
74
+ let name = '';
75
+ let trace = '';
76
+ if (error !== null && (typeof error === 'object' || typeof error === 'function')) {
77
+ try {
78
+ if (typeof error.message === 'string') message = error.message;
79
+ if (typeof error.name === 'string') name = error.name;
80
+ if (typeof error.stack === 'string') trace = error.stack;
81
+ } catch {}
82
+ }
83
+ if (message === null) {
84
+ try {
85
+ message = String(error);
86
+ } catch {
87
+ message = 'JavaScript exception';
88
+ }
89
+ }
90
+ setOut(out, message);
91
+ setOut(stack, `${name}\n${trace}`);
92
+ return 1;
93
+ }
94
+
95
+ function engine(id) {
96
+ const found = engines.get(id);
97
+ if (!found) throw new Error(`tailwind.com: no JavaScript engine ${id}`);
98
+ return found;
99
+ }
100
+
101
+ // A realm: the window of a hidden <iframe>.
102
+ function frame() {
103
+ if (typeof document === 'undefined') {
104
+ throw new Error('tailwind.com: @plugin and @config need a page or Node.js: a worker has no realm for the plugins.');
105
+ }
106
+ const frame = document.createElement('iframe');
107
+ frame.hidden = true;
108
+ frame.setAttribute('aria-hidden', 'true');
109
+ frame.setAttribute('data-tailwind-com', 'engine');
110
+ document.documentElement.append(frame);
111
+ return { global: frame.contentWindow, dispose: () => frame.remove() };
112
+ }
113
+
114
+ // One macrotask: the jobs of the promises that are pending now run
115
+ // before it ends.
116
+ function nextTask() {
117
+ return new Promise((resolve) => {
118
+ const channel = new MessageChannel();
119
+ channel.port1.onmessage = () => {
120
+ channel.port1.close();
121
+ resolve();
122
+ };
123
+ channel.port2.postMessage(null);
124
+ });
125
+ }
126
+
127
+ const realm = options.realm ?? frame;
128
+
129
+ function create(user) {
130
+ const { global, dispose } = realm();
131
+ let strip = null;
132
+
133
+ // The TypeScript transform of the program, in the realm.
134
+ function transform(source, file, transforms) {
135
+ if (strip === null) {
136
+ const typescript = asset('typescript');
137
+ if (typeof typescript !== 'string') throw new global.Error(`Cannot load '${file}': the TypeScript transform is not loaded.`);
138
+ strip = (0, global.eval)(`${typescript}\n//# sourceURL=tailwindcss/typescript.js`);
139
+ }
140
+ return strip(source, file, transforms);
141
+ }
142
+
143
+ // An ES module (or a TypeScript file that has its syntax) becomes
144
+ // CommonJS: `import.meta` becomes an object of the file.
145
+ function commonJs(file, result) {
146
+ let { format, source } = result;
147
+ const typescript = /\.[cm]?ts$/.test(file);
148
+ let esm = format === 'esm';
149
+ if (!esm && format !== 'json' && (format === 'unknown' || typescript)) {
150
+ try {
151
+ new global.Function(typescript ? transform(source, file, ['typescript']) : source);
152
+ } catch (error) {
153
+ esm = error instanceof global.SyntaxError;
154
+ }
155
+ }
156
+ if (!esm) return result;
157
+ source = transform(source, file, typescript ? ['typescript', 'imports'] : ['imports']);
158
+ source = source.replace(/\bimport\.meta\b/g, '({ url: __tw_file_url(__filename), filename: __filename, dirname: __dirname })');
159
+ return { ...result, format: 'cjs', source };
160
+ }
161
+
162
+ // Call the host function of the program.
163
+ function call(op, text) {
164
+ const api = exports();
165
+ const opPointer = writeText(op);
166
+ const textPointer = writeText(text);
167
+ const errorPointer = api.tw_host_alloc(4);
168
+ view().setInt32(errorPointer, 0, true);
169
+ let result;
170
+ let failed;
171
+ try {
172
+ result = api.tw_host_call(user, opPointer, textPointer, errorPointer);
173
+ failed = view().getInt32(errorPointer, true) !== 0;
174
+ } finally {
175
+ api.tw_host_free(opPointer);
176
+ api.tw_host_free(textPointer);
177
+ api.tw_host_free(errorPointer);
178
+ }
179
+ if (!result) {
180
+ if (failed) throw new global.Error(`The host operation ${op} failed`);
181
+ return undefined;
182
+ }
183
+ const value = readText(result);
184
+ api.tw_host_release(user, result);
185
+ if (failed) throw new global.Error(value);
186
+ return value;
187
+ }
188
+
189
+ global.__host = (op, text) => {
190
+ op = String(op);
191
+ if (op === 'asset') {
192
+ const file = asset(String(text));
193
+ return typeof file === 'string' ? file : undefined;
194
+ }
195
+ const value = call(op, text === undefined ? '' : String(text));
196
+ // The argument is JSON text: the name of the file.
197
+ if (op === 'module.read' && typeof value === 'string') {
198
+ return JSON.stringify(commonJs(String(JSON.parse(text)), JSON.parse(value)));
199
+ }
200
+ return value;
201
+ };
202
+ global.__compile = (source, filename) => (0, global.eval)(`${source}\n//# sourceURL=${filename}`);
203
+ // No synchronous wait here: the plugin layer uses __tw_compat_async.
204
+ global.__await = (value) => {
205
+ if (value !== null && typeof value?.then === 'function') {
206
+ throw new global.Error('This JavaScript engine cannot wait for a promise here.');
207
+ }
208
+ return value;
209
+ };
210
+ global.__tw_yield = () => nextTask();
211
+
212
+ const id = nextId++;
213
+ engines.set(id, { global, dispose });
214
+ return id;
215
+ }
216
+
217
+ function evaluate(id, sourcePointer, length, filenamePointer, isModule, out, stack) {
218
+ setOut(out, null);
219
+ setOut(stack, null);
220
+ try {
221
+ const { global } = engine(id);
222
+ const filename = readText(filenamePointer);
223
+ let source = readText(sourcePointer, length);
224
+ if (isModule) throw new global.Error('This JavaScript engine has no ES modules of the program.');
225
+ // The program gives an empty plugin layer: the host has it.
226
+ if (filename === 'tailwindcss/compat.js' && source === '') {
227
+ const compat = asset('compat');
228
+ if (typeof compat !== 'string') throw new global.Error('The plugin layer of Tailwind CSS is not loaded.');
229
+ source = compat;
230
+ }
231
+ const value = (0, global.eval)(`${source}\n//# sourceURL=${filename}`);
232
+ if (typeof value === 'string') setOut(out, value);
233
+ return 0;
234
+ } catch (error) {
235
+ return exception(error, out, stack);
236
+ }
237
+ }
238
+
239
+ function functionOf(id, namePointer) {
240
+ const { global } = engine(id);
241
+ const fn = global[readText(namePointer)];
242
+ if (typeof fn !== 'function') throw new global.TypeError('not a function');
243
+ return fn;
244
+ }
245
+
246
+ const imports = {
247
+ tw_js_new(_memory, _stack, _host, _release, user) {
248
+ return create(user);
249
+ },
250
+ tw_js_free(id) {
251
+ engines.get(id)?.dispose();
252
+ engines.delete(id);
253
+ },
254
+ tw_js_eval: evaluate,
255
+ tw_js_call(id, namePointer, textPointer, out, stack) {
256
+ setOut(out, null);
257
+ setOut(stack, null);
258
+ try {
259
+ const value = functionOf(id, namePointer)(readText(textPointer));
260
+ if (typeof value === 'string') setOut(out, value);
261
+ return 0;
262
+ } catch (error) {
263
+ return exception(error, out, stack);
264
+ }
265
+ },
266
+ tw_js_call_async: new WebAssembly.Suspending(async (id, namePointer, textPointer, out, stack) => {
267
+ setOut(out, null);
268
+ setOut(stack, null);
269
+ try {
270
+ const value = await functionOf(id, namePointer)(readText(textPointer));
271
+ if (typeof value === 'string') setOut(out, value);
272
+ return 0;
273
+ } catch (error) {
274
+ return exception(error, out, stack);
275
+ }
276
+ }),
277
+ };
278
+
279
+ function dispose() {
280
+ for (const { dispose } of engines.values()) dispose();
281
+ engines.clear();
282
+ }
283
+
284
+ return { imports, dispose };
285
+ }
package/js/node.mjs CHANGED
@@ -29,6 +29,10 @@ export function release() {
29
29
  // The path of the WebAssembly module (WASI preview 1).
30
30
  export const wasmPath = path.join(root, 'runtime', 'tailwind.wasm');
31
31
 
32
+ // The path of the program for a browser (the condition "browser"): no
33
+ // optimizer and no JavaScript engine.
34
+ export const browserWasmPath = path.join(root, 'runtime', 'tailwind-browser.wasm');
35
+
32
36
  // The path of tailwind.com, after a download when it is not in the cache.
33
37
  export function binPath(options = {}) {
34
38
  return ensure(release(), options);
@@ -51,15 +55,61 @@ export async function run(args = [], options = {}) {
51
55
  });
52
56
  }
53
57
 
58
+ // The JavaScript files of the program for the engine of tailwind.wasm
59
+ // (js/engine.mjs), from the disk when the program asks: next to the
60
+ // module (runtime/ of the package), else in the repository.
61
+ function assetReader(wasm) {
62
+ const dirs = [path.dirname(path.resolve(wasm)), path.join(root, 'native', 'tailwind', 'assets')];
63
+ const cache = new Map();
64
+ return (name) => {
65
+ if (!cache.has(name)) {
66
+ const file =
67
+ name === 'compat' ? 'compat.js' : name === 'typescript' ? 'typescript.js' : name.startsWith('plugin:@tailwindcss/') ? `plugins/${name.slice('plugin:@tailwindcss/'.length)}.js` : null;
68
+ let text;
69
+ for (const dir of file ? dirs : []) {
70
+ try {
71
+ text = fs.readFileSync(path.join(dir, file), 'utf8');
72
+ break;
73
+ } catch {}
74
+ }
75
+ cache.set(name, text);
76
+ }
77
+ return cache.get(name);
78
+ };
79
+ }
80
+
81
+ // A realm for the plugins: a context of node:vm.
82
+ async function vmRealm() {
83
+ const vm = await import('node:vm');
84
+ return () => {
85
+ const context = vm.createContext({});
86
+ return { global: vm.runInContext('globalThis', context), dispose() {} };
87
+ };
88
+ }
89
+
90
+ class Exit {
91
+ constructor(code) {
92
+ this.code = code;
93
+ }
94
+ }
95
+
54
96
  // Run the WebAssembly program in this process, with the arguments of the
55
97
  // command line program. The directory cwd (default: the current
56
98
  // directory) is the root "/" of the program: it sees no file outside it.
57
- // options: cwd, env (default: empty), input (the text of stdin).
99
+ // options: cwd, env (default: empty), input (the text of stdin), wasm
100
+ // (the file of the module).
58
101
  // The result is { status, stdout, stderr } with the output as text.
59
102
  // --watch does not end: use run() for a watch.
103
+ //
104
+ // tailwind.wasm runs the plugins of @plugin and @config in QuickJS. The
105
+ // program for a browser (browserWasmPath) has no JavaScript engine: with
106
+ // it, the plugins run in the JavaScript engine of Node.js, in a context of
107
+ // node:vm (js/engine.mjs). That needs JS Promise Integration: Node.js 24
108
+ // or later (Node.js 22 with --experimental-wasm-jspi).
60
109
  export async function runWasm(args = [], options = {}) {
61
110
  const { WASI } = await import('node:wasi');
62
111
  const cwd = path.resolve(options.cwd ?? '.');
112
+ const wasm = options.wasm ?? wasmPath;
63
113
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tailwind-wasm-'));
64
114
  const files = { stdin: path.join(tmp, 'stdin'), stdout: path.join(tmp, 'stdout'), stderr: path.join(tmp, 'stderr') };
65
115
  fs.writeFileSync(files.stdin, options.input ?? '');
@@ -68,25 +118,60 @@ export async function runWasm(args = [], options = {}) {
68
118
  stdout: fs.openSync(files.stdout, 'w'),
69
119
  stderr: fs.openSync(files.stderr, 'w'),
70
120
  };
121
+ let engine = null;
71
122
  try {
72
123
  const wasi = new WASI({
73
124
  version: 'preview1',
74
125
  args: ['tailwind', ...args],
75
126
  env: { PWD: '/', ...(options.env ?? {}) },
76
127
  preopens: { '/': cwd },
77
- returnOnExit: true,
78
128
  ...fds,
79
129
  });
80
- const module = await WebAssembly.compile(fs.readFileSync(options.wasm ?? wasmPath));
81
- const instance = await WebAssembly.instantiate(module, wasi.getImportObject());
82
- const status = wasi.start(instance);
83
- for (const fd of Object.values(fds)) fs.closeSync(fd);
130
+ const module = await WebAssembly.compile(fs.readFileSync(wasm));
131
+ const imports = wasi.getImportObject();
132
+ // The exit status: proc_exit ends the run with an exception.
133
+ imports.wasi_snapshot_preview1 = {
134
+ ...imports.wasi_snapshot_preview1,
135
+ proc_exit: (code) => {
136
+ throw new Exit(code);
137
+ },
138
+ };
139
+ let instance = null;
140
+ let promising = false;
141
+ const { createEngine, hasPromiseIntegration, needsEngine } = await import('./engine.mjs');
142
+ if (needsEngine(module)) {
143
+ if (hasPromiseIntegration) {
144
+ engine = createEngine(() => instance.exports, assetReader(wasm), { realm: await vmRealm() });
145
+ imports.tailwind_js = engine.imports;
146
+ promising = true;
147
+ } else {
148
+ const missing = () => {
149
+ throw new Error('tailwind.com: @plugin and @config need JS Promise Integration: Node.js 24 or later.');
150
+ };
151
+ imports.tailwind_js = { tw_js_new: missing, tw_js_free: missing, tw_js_eval: missing, tw_js_call: missing, tw_js_call_async: missing };
152
+ }
153
+ }
154
+ instance = await WebAssembly.instantiate(module, imports);
155
+ // node:wasi sets the memory and calls _start. With JS Promise
156
+ // Integration, _start gives a promise: the run ends when it settles.
157
+ let running = null;
158
+ let status = 0;
159
+ try {
160
+ const start = promising ? WebAssembly.promising(instance.exports._start) : instance.exports._start;
161
+ wasi.start({ exports: { memory: instance.exports.memory, _start: () => void (running = start()) } });
162
+ await running;
163
+ } catch (error) {
164
+ if (!(error instanceof Exit)) throw error;
165
+ status = error.code;
166
+ }
84
167
  return {
85
168
  status,
86
169
  stdout: fs.readFileSync(files.stdout, 'utf8'),
87
170
  stderr: fs.readFileSync(files.stderr, 'utf8'),
88
171
  };
89
172
  } finally {
173
+ engine?.dispose();
174
+ for (const fd of Object.values(fds)) fs.closeSync(fd);
90
175
  fs.rmSync(tmp, { recursive: true, force: true });
91
176
  }
92
177
  }