@jesscss/plugin-js 2.0.0-alpha.5 → 2.0.0-alpha.6
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/lib/index.cjs +437 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +390 -426
- package/package.json +12 -8
- package/lib/index.js.map +0 -1
- package/lib/runtime-worker.js +0 -93
- package/lib/runtime-worker.js.map +0 -1
package/lib/index.js
CHANGED
|
@@ -1,442 +1,406 @@
|
|
|
1
|
-
import { AbstractPlugin } from
|
|
2
|
-
import * as fs from
|
|
3
|
-
import * as net from
|
|
4
|
-
import * as path from
|
|
5
|
-
import { fileURLToPath, pathToFileURL } from
|
|
6
|
-
import { spawn, spawnSync } from
|
|
1
|
+
import { AbstractPlugin } from "@jesscss/core";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as net from "node:net";
|
|
4
|
+
import * as path from "node:path";
|
|
5
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
6
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
7
|
+
//#region src/index.ts
|
|
7
8
|
const SCRIPT_EXTENSIONS = new Set([
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
9
|
+
".js",
|
|
10
|
+
".mjs",
|
|
11
|
+
".cjs",
|
|
12
|
+
".ts",
|
|
13
|
+
".mts",
|
|
14
|
+
".cts"
|
|
14
15
|
]);
|
|
15
16
|
const RUNTIME_MISSING_MESSAGE = [
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
].join(
|
|
21
|
-
const BOOT_TIMEOUT_MS =
|
|
22
|
-
const REQUEST_TIMEOUT_MS =
|
|
17
|
+
"Deno runtime is required for @jesscss/plugin-js, but no usable Deno binary was found.",
|
|
18
|
+
"If using pnpm, approve build scripts for \"deno\" (pnpm approve-builds).",
|
|
19
|
+
"If using npm with ignored scripts, reinstall with lifecycle scripts enabled.",
|
|
20
|
+
"Or install native Deno and ensure \"deno\" is on PATH."
|
|
21
|
+
].join("\n");
|
|
22
|
+
const BOOT_TIMEOUT_MS = 8e3;
|
|
23
|
+
const REQUEST_TIMEOUT_MS = 1e4;
|
|
24
|
+
const IDLE_SHUTDOWN_MS = 5e3;
|
|
23
25
|
const isPathInside = (candidatePath, rootPath) => {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
+
const rel = path.relative(rootPath, candidatePath);
|
|
27
|
+
return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
26
28
|
};
|
|
27
29
|
const canonicalPath = (p) => {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
30
|
+
try {
|
|
31
|
+
return fs.realpathSync.native(p);
|
|
32
|
+
} catch {
|
|
33
|
+
return p;
|
|
34
|
+
}
|
|
34
35
|
};
|
|
35
36
|
const normalizePermissionPath = (value) => {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
catch {
|
|
44
|
-
return value;
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
return value;
|
|
37
|
+
if (!value) return null;
|
|
38
|
+
if (value.startsWith("file://")) try {
|
|
39
|
+
return fileURLToPath(value);
|
|
40
|
+
} catch {
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
return value;
|
|
48
44
|
};
|
|
49
45
|
const isFnsPath = (importPath) => {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|| normalized.startsWith('@jesscss/fns/')
|
|
54
|
-
|| normalized === '#less'
|
|
55
|
-
|| normalized.startsWith('#less/')
|
|
56
|
-
|| normalized === '#sass'
|
|
57
|
-
|| normalized.startsWith('#sass/')
|
|
58
|
-
|| isFnsPackagePath);
|
|
46
|
+
const normalized = importPath.replace(/\\/g, "/");
|
|
47
|
+
const isFnsPackagePath = /(^|\/)(@jesscss\/fns|packages\/fns)(\/|$)/.test(normalized);
|
|
48
|
+
return normalized === "@jesscss/fns" || normalized.startsWith("@jesscss/fns/") || normalized === "#less" || normalized.startsWith("#less/") || normalized === "#sass" || normalized.startsWith("#sass/") || isFnsPackagePath;
|
|
59
49
|
};
|
|
60
50
|
const isJsonValue = (value) => {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
51
|
+
try {
|
|
52
|
+
JSON.stringify(value);
|
|
53
|
+
return true;
|
|
54
|
+
} catch {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
var JsPlugin = class JsPlugin extends AbstractPlugin {
|
|
59
|
+
static cleanupRegistered = false;
|
|
60
|
+
static liveInstances = /* @__PURE__ */ new Set();
|
|
61
|
+
name = "js";
|
|
62
|
+
supportedExtensions = Array.from(SCRIPT_EXTENSIONS);
|
|
63
|
+
runtimeState = { status: "idle" };
|
|
64
|
+
brokerServer;
|
|
65
|
+
brokerSocketPath;
|
|
66
|
+
worker;
|
|
67
|
+
workerBuffer = "";
|
|
68
|
+
nextRequestId = 1;
|
|
69
|
+
pending = /* @__PURE__ */ new Map();
|
|
70
|
+
idleTimer;
|
|
71
|
+
constructor(opts = {}) {
|
|
72
|
+
super();
|
|
73
|
+
this.opts = opts;
|
|
74
|
+
JsPlugin.liveInstances.add(this);
|
|
75
|
+
JsPlugin.registerProcessCleanup();
|
|
76
|
+
}
|
|
77
|
+
prewarm() {
|
|
78
|
+
return this.ensureRuntime().catch(() => void 0);
|
|
79
|
+
}
|
|
80
|
+
static registerProcessCleanup() {
|
|
81
|
+
if (JsPlugin.cleanupRegistered) return;
|
|
82
|
+
JsPlugin.cleanupRegistered = true;
|
|
83
|
+
const cleanup = () => {
|
|
84
|
+
for (const instance of JsPlugin.liveInstances) try {
|
|
85
|
+
instance.dispose();
|
|
86
|
+
} catch {}
|
|
87
|
+
};
|
|
88
|
+
process.once("beforeExit", cleanup);
|
|
89
|
+
process.once("exit", cleanup);
|
|
90
|
+
}
|
|
91
|
+
clearIdleTimer() {
|
|
92
|
+
if (this.idleTimer) {
|
|
93
|
+
clearTimeout(this.idleTimer);
|
|
94
|
+
this.idleTimer = void 0;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
scheduleIdleShutdown() {
|
|
98
|
+
this.clearIdleTimer();
|
|
99
|
+
if (this.pending.size > 0 || this.runtimeState.status !== "ready") return;
|
|
100
|
+
this.idleTimer = setTimeout(() => {
|
|
101
|
+
this.shutdown();
|
|
102
|
+
this.runtimeState = { status: "idle" };
|
|
103
|
+
}, IDLE_SHUTDOWN_MS);
|
|
104
|
+
this.idleTimer.unref?.();
|
|
105
|
+
}
|
|
106
|
+
ensureRuntimeAvailable() {
|
|
107
|
+
if (spawnSync(this.opts.denoCommand ?? "deno", ["--version"], { stdio: "ignore" }).status !== 0) throw new Error(RUNTIME_MISSING_MESSAGE);
|
|
108
|
+
}
|
|
109
|
+
ensureRuntime() {
|
|
110
|
+
if (this.runtimeState.status === "ready") {
|
|
111
|
+
this.clearIdleTimer();
|
|
112
|
+
return Promise.resolve();
|
|
113
|
+
}
|
|
114
|
+
if (this.runtimeState.status === "initializing") return this.runtimeState.promise;
|
|
115
|
+
if (this.runtimeState.status === "failed") return Promise.reject(this.runtimeState.error);
|
|
116
|
+
const promise = this.startRuntime().then(() => {
|
|
117
|
+
this.runtimeState = { status: "ready" };
|
|
118
|
+
this.scheduleIdleShutdown();
|
|
119
|
+
}, (err) => {
|
|
120
|
+
this.runtimeState = {
|
|
121
|
+
status: "failed",
|
|
122
|
+
error: err
|
|
123
|
+
};
|
|
124
|
+
throw err;
|
|
125
|
+
});
|
|
126
|
+
this.runtimeState = {
|
|
127
|
+
status: "initializing",
|
|
128
|
+
promise
|
|
129
|
+
};
|
|
130
|
+
return promise;
|
|
131
|
+
}
|
|
132
|
+
createBrokerPath() {
|
|
133
|
+
if (process.platform === "win32") return `\\\\.\\pipe\\jess-deno-broker-${`${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`}`;
|
|
134
|
+
const rand = Math.floor(Math.random() * 1e4);
|
|
135
|
+
return `/tmp/jd-${process.pid}-${Date.now()}-${rand}.sock`;
|
|
136
|
+
}
|
|
137
|
+
isReadAllowed(value) {
|
|
138
|
+
const normalized = normalizePermissionPath(value);
|
|
139
|
+
if (!normalized) return false;
|
|
140
|
+
const requestedPath = canonicalPath(path.resolve(normalized));
|
|
141
|
+
const jsReadRoot = this.opts.jsReadRoot ? canonicalPath(path.resolve(this.opts.jsReadRoot)) : void 0;
|
|
142
|
+
if (jsReadRoot && isPathInside(requestedPath, jsReadRoot)) return true;
|
|
143
|
+
return requestedPath.includes(`${path.sep}node_modules${path.sep}`);
|
|
144
|
+
}
|
|
145
|
+
isNetAllowed(value) {
|
|
146
|
+
if (!this.opts.allowHttp) return false;
|
|
147
|
+
const allowHosts = this.opts.allowNetHosts ?? [];
|
|
148
|
+
if (allowHosts.length === 0) return true;
|
|
149
|
+
if (!value) return false;
|
|
150
|
+
const host = value.split(":")[0] ?? value;
|
|
151
|
+
return allowHosts.includes(host);
|
|
152
|
+
}
|
|
153
|
+
handleBrokerRequest(request) {
|
|
154
|
+
const deny = (reason) => ({
|
|
155
|
+
id: request.id,
|
|
156
|
+
result: "deny",
|
|
157
|
+
reason
|
|
158
|
+
});
|
|
159
|
+
switch (request.permission) {
|
|
160
|
+
case "read": return this.isReadAllowed(request.value) ? {
|
|
161
|
+
id: request.id,
|
|
162
|
+
result: "allow"
|
|
163
|
+
} : deny("Read access denied by Jess policy.");
|
|
164
|
+
case "net": return this.isNetAllowed(request.value) ? {
|
|
165
|
+
id: request.id,
|
|
166
|
+
result: "allow"
|
|
167
|
+
} : deny("Network access denied by Jess policy.");
|
|
168
|
+
case "env":
|
|
169
|
+
case "run":
|
|
170
|
+
case "ffi":
|
|
171
|
+
case "sys":
|
|
172
|
+
case "write": return deny(`${request.permission} permission denied by Jess policy.`);
|
|
173
|
+
default: return deny(`Permission "${request.permission}" denied by Jess policy.`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async startBroker() {
|
|
177
|
+
const socketPath = this.createBrokerPath();
|
|
178
|
+
if (process.platform !== "win32" && fs.existsSync(socketPath)) fs.unlinkSync(socketPath);
|
|
179
|
+
const server = net.createServer((socket) => {
|
|
180
|
+
let buf = "";
|
|
181
|
+
socket.setEncoding("utf8");
|
|
182
|
+
socket.on("data", (chunk) => {
|
|
183
|
+
buf += chunk;
|
|
184
|
+
let idx = buf.indexOf("\n");
|
|
185
|
+
while (idx >= 0) {
|
|
186
|
+
const line = buf.slice(0, idx).trim();
|
|
187
|
+
buf = buf.slice(idx + 1);
|
|
188
|
+
idx = buf.indexOf("\n");
|
|
189
|
+
if (!line) continue;
|
|
190
|
+
let req;
|
|
191
|
+
try {
|
|
192
|
+
req = JSON.parse(line);
|
|
193
|
+
} catch {
|
|
194
|
+
socket.write(JSON.stringify({
|
|
195
|
+
id: -1,
|
|
196
|
+
result: "deny",
|
|
197
|
+
reason: "Malformed permission request."
|
|
198
|
+
}) + "\n");
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const response = this.handleBrokerRequest(req);
|
|
202
|
+
socket.write(`${JSON.stringify(response)}\n`);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
await new Promise((resolve, reject) => {
|
|
207
|
+
server.once("error", reject);
|
|
208
|
+
server.listen(socketPath, () => resolve());
|
|
209
|
+
});
|
|
210
|
+
this.brokerServer = server;
|
|
211
|
+
this.brokerSocketPath = socketPath;
|
|
212
|
+
return socketPath;
|
|
213
|
+
}
|
|
214
|
+
startWorker(socketPath) {
|
|
215
|
+
const denoCommand = this.opts.denoCommand ?? "deno";
|
|
216
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
217
|
+
const compiledWorkerPath = path.join(moduleDir, "runtime-worker.js");
|
|
218
|
+
const sourceWorkerPath = path.join(moduleDir, "runtime-worker.ts");
|
|
219
|
+
const child = spawn(denoCommand, [
|
|
220
|
+
"run",
|
|
221
|
+
"--no-prompt",
|
|
222
|
+
fs.existsSync(compiledWorkerPath) ? compiledWorkerPath : sourceWorkerPath
|
|
223
|
+
], {
|
|
224
|
+
stdio: [
|
|
225
|
+
"pipe",
|
|
226
|
+
"pipe",
|
|
227
|
+
"pipe"
|
|
228
|
+
],
|
|
229
|
+
env: {
|
|
230
|
+
...process.env,
|
|
231
|
+
DENO_PERMISSION_BROKER_PATH: socketPath
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
this.worker = child;
|
|
235
|
+
child.stdout.setEncoding("utf8");
|
|
236
|
+
child.stderr.setEncoding("utf8");
|
|
237
|
+
child.stdout.on("data", (chunk) => this.onWorkerStdout(chunk));
|
|
238
|
+
child.on("exit", () => {
|
|
239
|
+
const err = /* @__PURE__ */ new Error("Deno worker exited unexpectedly.");
|
|
240
|
+
this.rejectAllPending(err);
|
|
241
|
+
if (this.runtimeState.status !== "failed") this.runtimeState = {
|
|
242
|
+
status: "failed",
|
|
243
|
+
error: err
|
|
244
|
+
};
|
|
245
|
+
});
|
|
246
|
+
return new Promise((resolve, reject) => {
|
|
247
|
+
const timer = setTimeout(() => {
|
|
248
|
+
reject(/* @__PURE__ */ new Error("Timed out waiting for Deno worker startup."));
|
|
249
|
+
}, BOOT_TIMEOUT_MS);
|
|
250
|
+
const onData = (chunk) => {
|
|
251
|
+
this.workerBuffer += chunk;
|
|
252
|
+
let idx = this.workerBuffer.indexOf("\n");
|
|
253
|
+
while (idx >= 0) {
|
|
254
|
+
const line = this.workerBuffer.slice(0, idx).trim();
|
|
255
|
+
this.workerBuffer = this.workerBuffer.slice(idx + 1);
|
|
256
|
+
idx = this.workerBuffer.indexOf("\n");
|
|
257
|
+
if (!line) continue;
|
|
258
|
+
try {
|
|
259
|
+
if (JSON.parse(line).type === "ready") {
|
|
260
|
+
clearTimeout(timer);
|
|
261
|
+
child.stdout.off("data", onData);
|
|
262
|
+
resolve();
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
} catch {}
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
child.stdout.on("data", onData);
|
|
269
|
+
child.once("error", (err) => {
|
|
270
|
+
clearTimeout(timer);
|
|
271
|
+
child.stdout.off("data", onData);
|
|
272
|
+
reject(err);
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
async startRuntime() {
|
|
277
|
+
this.ensureRuntimeAvailable();
|
|
278
|
+
const socketPath = await this.startBroker();
|
|
279
|
+
try {
|
|
280
|
+
await this.startWorker(socketPath);
|
|
281
|
+
} catch (err) {
|
|
282
|
+
this.shutdown();
|
|
283
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
onWorkerStdout(chunk) {
|
|
287
|
+
this.workerBuffer += chunk;
|
|
288
|
+
let idx = this.workerBuffer.indexOf("\n");
|
|
289
|
+
while (idx >= 0) {
|
|
290
|
+
const line = this.workerBuffer.slice(0, idx).trim();
|
|
291
|
+
this.workerBuffer = this.workerBuffer.slice(idx + 1);
|
|
292
|
+
idx = this.workerBuffer.indexOf("\n");
|
|
293
|
+
if (!line) continue;
|
|
294
|
+
let parsed;
|
|
295
|
+
try {
|
|
296
|
+
parsed = JSON.parse(line);
|
|
297
|
+
} catch {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (!parsed || typeof parsed.id !== "number") continue;
|
|
301
|
+
const pending = this.pending.get(parsed.id);
|
|
302
|
+
if (!pending) continue;
|
|
303
|
+
this.pending.delete(parsed.id);
|
|
304
|
+
clearTimeout(pending.timeout);
|
|
305
|
+
pending.resolve(parsed);
|
|
306
|
+
if (this.pending.size === 0) this.scheduleIdleShutdown();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
rejectAllPending(err) {
|
|
310
|
+
for (const pending of this.pending.values()) {
|
|
311
|
+
clearTimeout(pending.timeout);
|
|
312
|
+
pending.reject(err);
|
|
313
|
+
}
|
|
314
|
+
this.pending.clear();
|
|
315
|
+
}
|
|
316
|
+
async callWorker(request) {
|
|
317
|
+
await this.ensureRuntime();
|
|
318
|
+
this.clearIdleTimer();
|
|
319
|
+
if (!this.worker || !this.worker.stdin.writable) throw new Error("Deno worker is not available.");
|
|
320
|
+
const id = this.nextRequestId++;
|
|
321
|
+
const payload = {
|
|
322
|
+
...request,
|
|
323
|
+
id
|
|
324
|
+
};
|
|
325
|
+
return await new Promise((resolve, reject) => {
|
|
326
|
+
const timeout = setTimeout(() => {
|
|
327
|
+
this.pending.delete(id);
|
|
328
|
+
reject(/* @__PURE__ */ new Error("Timed out waiting for Deno worker response."));
|
|
329
|
+
}, REQUEST_TIMEOUT_MS);
|
|
330
|
+
this.pending.set(id, {
|
|
331
|
+
resolve,
|
|
332
|
+
reject,
|
|
333
|
+
timeout
|
|
334
|
+
});
|
|
335
|
+
this.worker.stdin.write(`${JSON.stringify(payload)}\n`);
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
shutdown() {
|
|
339
|
+
this.clearIdleTimer();
|
|
340
|
+
if (this.worker && !this.worker.killed) this.worker.kill();
|
|
341
|
+
this.worker = void 0;
|
|
342
|
+
if (this.brokerServer) {
|
|
343
|
+
this.brokerServer.close();
|
|
344
|
+
this.brokerServer = void 0;
|
|
345
|
+
}
|
|
346
|
+
if (this.brokerSocketPath && process.platform !== "win32") try {
|
|
347
|
+
if (fs.existsSync(this.brokerSocketPath)) fs.unlinkSync(this.brokerSocketPath);
|
|
348
|
+
} catch {}
|
|
349
|
+
this.brokerSocketPath = void 0;
|
|
350
|
+
}
|
|
351
|
+
dispose() {
|
|
352
|
+
this.shutdown();
|
|
353
|
+
this.runtimeState = { status: "idle" };
|
|
354
|
+
}
|
|
355
|
+
assertAllowedPath(absoluteFilePath) {
|
|
356
|
+
const resolvedPath = path.resolve(absoluteFilePath);
|
|
357
|
+
const jsReadRoot = this.opts.jsReadRoot ? path.resolve(this.opts.jsReadRoot) : void 0;
|
|
358
|
+
if (!jsReadRoot) return;
|
|
359
|
+
if (isPathInside(resolvedPath, jsReadRoot)) return;
|
|
360
|
+
if (resolvedPath.includes(`${path.sep}node_modules${path.sep}`)) return;
|
|
361
|
+
throw new Error(`Script path "${resolvedPath}" is outside jsReadRoot "${jsReadRoot}"`);
|
|
362
|
+
}
|
|
363
|
+
async import(absoluteFilePath) {
|
|
364
|
+
const ext = path.extname(absoluteFilePath);
|
|
365
|
+
if (!SCRIPT_EXTENSIONS.has(ext)) throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}"`);
|
|
366
|
+
if (!isFnsPath(absoluteFilePath)) {
|
|
367
|
+
this.assertAllowedPath(absoluteFilePath);
|
|
368
|
+
await this.ensureRuntime();
|
|
369
|
+
const modulePath = path.resolve(absoluteFilePath);
|
|
370
|
+
const loadResult = await this.callWorker({
|
|
371
|
+
type: "load",
|
|
372
|
+
modulePath
|
|
373
|
+
});
|
|
374
|
+
if (!loadResult.ok) throw new Error(loadResult.error);
|
|
375
|
+
const moduleObject = {};
|
|
376
|
+
const exported = loadResult.exports ?? [];
|
|
377
|
+
for (const item of exported) if (item.kind === "function") moduleObject[item.name] = async (...args) => {
|
|
378
|
+
const invokeResult = await this.callWorker({
|
|
379
|
+
type: "invoke",
|
|
380
|
+
modulePath,
|
|
381
|
+
exportName: item.name,
|
|
382
|
+
args
|
|
383
|
+
});
|
|
384
|
+
if (!invokeResult.ok) throw new Error(invokeResult.error);
|
|
385
|
+
return invokeResult.value;
|
|
386
|
+
};
|
|
387
|
+
else moduleObject[item.name] = item.value;
|
|
388
|
+
return moduleObject;
|
|
389
|
+
}
|
|
390
|
+
const module = await import(pathToFileURL(path.resolve(absoluteFilePath)).href);
|
|
391
|
+
const safeModule = {};
|
|
392
|
+
for (const [key, value] of Object.entries(module)) if (typeof value === "function" || isJsonValue(value)) safeModule[key] = value;
|
|
393
|
+
return safeModule;
|
|
394
|
+
}
|
|
68
395
|
};
|
|
69
|
-
export class JsPlugin extends AbstractPlugin {
|
|
70
|
-
opts;
|
|
71
|
-
name = 'js';
|
|
72
|
-
supportedExtensions = Array.from(SCRIPT_EXTENSIONS);
|
|
73
|
-
runtimeState = { status: 'idle' };
|
|
74
|
-
brokerServer;
|
|
75
|
-
brokerSocketPath;
|
|
76
|
-
worker;
|
|
77
|
-
workerBuffer = '';
|
|
78
|
-
nextRequestId = 1;
|
|
79
|
-
pending = new Map();
|
|
80
|
-
constructor(opts = {}) {
|
|
81
|
-
super();
|
|
82
|
-
this.opts = opts;
|
|
83
|
-
}
|
|
84
|
-
prewarm() {
|
|
85
|
-
return this.ensureRuntime().catch(() => undefined);
|
|
86
|
-
}
|
|
87
|
-
ensureRuntimeAvailable() {
|
|
88
|
-
const denoCommand = this.opts.denoCommand ?? 'deno';
|
|
89
|
-
const result = spawnSync(denoCommand, ['--version'], {
|
|
90
|
-
stdio: 'ignore'
|
|
91
|
-
});
|
|
92
|
-
if (result.status !== 0) {
|
|
93
|
-
throw new Error(RUNTIME_MISSING_MESSAGE);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
ensureRuntime() {
|
|
97
|
-
if (this.runtimeState.status === 'ready') {
|
|
98
|
-
return Promise.resolve();
|
|
99
|
-
}
|
|
100
|
-
if (this.runtimeState.status === 'initializing') {
|
|
101
|
-
return this.runtimeState.promise;
|
|
102
|
-
}
|
|
103
|
-
if (this.runtimeState.status === 'failed') {
|
|
104
|
-
return Promise.reject(this.runtimeState.error);
|
|
105
|
-
}
|
|
106
|
-
const promise = this.startRuntime().then(() => {
|
|
107
|
-
this.runtimeState = { status: 'ready' };
|
|
108
|
-
}, (err) => {
|
|
109
|
-
this.runtimeState = { status: 'failed', error: err };
|
|
110
|
-
throw err;
|
|
111
|
-
});
|
|
112
|
-
this.runtimeState = { status: 'initializing', promise };
|
|
113
|
-
return promise;
|
|
114
|
-
}
|
|
115
|
-
createBrokerPath() {
|
|
116
|
-
if (process.platform === 'win32') {
|
|
117
|
-
const rand = `${process.pid}-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
|
|
118
|
-
return `\\\\.\\pipe\\jess-deno-broker-${rand}`;
|
|
119
|
-
}
|
|
120
|
-
// macOS temp dir paths can exceed unix socket limits. Keep this short.
|
|
121
|
-
const rand = Math.floor(Math.random() * 10000);
|
|
122
|
-
return `/tmp/jd-${process.pid}-${Date.now()}-${rand}.sock`;
|
|
123
|
-
}
|
|
124
|
-
isReadAllowed(value) {
|
|
125
|
-
const normalized = normalizePermissionPath(value);
|
|
126
|
-
if (!normalized) {
|
|
127
|
-
return false;
|
|
128
|
-
}
|
|
129
|
-
const requestedPath = canonicalPath(path.resolve(normalized));
|
|
130
|
-
const jsReadRoot = this.opts.jsReadRoot ? canonicalPath(path.resolve(this.opts.jsReadRoot)) : undefined;
|
|
131
|
-
if (jsReadRoot && isPathInside(requestedPath, jsReadRoot)) {
|
|
132
|
-
return true;
|
|
133
|
-
}
|
|
134
|
-
return requestedPath.includes(`${path.sep}node_modules${path.sep}`);
|
|
135
|
-
}
|
|
136
|
-
isNetAllowed(value) {
|
|
137
|
-
if (!this.opts.allowHttp) {
|
|
138
|
-
return false;
|
|
139
|
-
}
|
|
140
|
-
const allowHosts = this.opts.allowNetHosts ?? [];
|
|
141
|
-
if (allowHosts.length === 0) {
|
|
142
|
-
return true;
|
|
143
|
-
}
|
|
144
|
-
if (!value) {
|
|
145
|
-
return false;
|
|
146
|
-
}
|
|
147
|
-
const host = value.split(':')[0] ?? value;
|
|
148
|
-
return allowHosts.includes(host);
|
|
149
|
-
}
|
|
150
|
-
handleBrokerRequest(request) {
|
|
151
|
-
const deny = (reason) => ({
|
|
152
|
-
id: request.id,
|
|
153
|
-
result: 'deny',
|
|
154
|
-
reason
|
|
155
|
-
});
|
|
156
|
-
switch (request.permission) {
|
|
157
|
-
case 'read':
|
|
158
|
-
return this.isReadAllowed(request.value)
|
|
159
|
-
? { id: request.id, result: 'allow' }
|
|
160
|
-
: deny('Read access denied by Jess policy.');
|
|
161
|
-
case 'net':
|
|
162
|
-
return this.isNetAllowed(request.value)
|
|
163
|
-
? { id: request.id, result: 'allow' }
|
|
164
|
-
: deny('Network access denied by Jess policy.');
|
|
165
|
-
case 'env':
|
|
166
|
-
case 'run':
|
|
167
|
-
case 'ffi':
|
|
168
|
-
case 'sys':
|
|
169
|
-
case 'write':
|
|
170
|
-
return deny(`${request.permission} permission denied by Jess policy.`);
|
|
171
|
-
default:
|
|
172
|
-
return deny(`Permission "${request.permission}" denied by Jess policy.`);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
async startBroker() {
|
|
176
|
-
const socketPath = this.createBrokerPath();
|
|
177
|
-
if (process.platform !== 'win32' && fs.existsSync(socketPath)) {
|
|
178
|
-
fs.unlinkSync(socketPath);
|
|
179
|
-
}
|
|
180
|
-
const server = net.createServer((socket) => {
|
|
181
|
-
let buf = '';
|
|
182
|
-
socket.setEncoding('utf8');
|
|
183
|
-
socket.on('data', (chunk) => {
|
|
184
|
-
buf += chunk;
|
|
185
|
-
let idx = buf.indexOf('\n');
|
|
186
|
-
while (idx >= 0) {
|
|
187
|
-
const line = buf.slice(0, idx).trim();
|
|
188
|
-
buf = buf.slice(idx + 1);
|
|
189
|
-
idx = buf.indexOf('\n');
|
|
190
|
-
if (!line) {
|
|
191
|
-
continue;
|
|
192
|
-
}
|
|
193
|
-
let req;
|
|
194
|
-
try {
|
|
195
|
-
req = JSON.parse(line);
|
|
196
|
-
}
|
|
197
|
-
catch {
|
|
198
|
-
socket.write(JSON.stringify({
|
|
199
|
-
id: -1,
|
|
200
|
-
result: 'deny',
|
|
201
|
-
reason: 'Malformed permission request.'
|
|
202
|
-
}) + '\n');
|
|
203
|
-
continue;
|
|
204
|
-
}
|
|
205
|
-
const response = this.handleBrokerRequest(req);
|
|
206
|
-
socket.write(`${JSON.stringify(response)}\n`);
|
|
207
|
-
}
|
|
208
|
-
});
|
|
209
|
-
});
|
|
210
|
-
await new Promise((resolve, reject) => {
|
|
211
|
-
server.once('error', reject);
|
|
212
|
-
server.listen(socketPath, () => resolve());
|
|
213
|
-
});
|
|
214
|
-
this.brokerServer = server;
|
|
215
|
-
this.brokerSocketPath = socketPath;
|
|
216
|
-
return socketPath;
|
|
217
|
-
}
|
|
218
|
-
startWorker(socketPath) {
|
|
219
|
-
const denoCommand = this.opts.denoCommand ?? 'deno';
|
|
220
|
-
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
221
|
-
const compiledWorkerPath = path.join(moduleDir, 'runtime-worker.js');
|
|
222
|
-
const sourceWorkerPath = path.join(moduleDir, 'runtime-worker.ts');
|
|
223
|
-
const workerScriptPath = fs.existsSync(compiledWorkerPath)
|
|
224
|
-
? compiledWorkerPath
|
|
225
|
-
: sourceWorkerPath;
|
|
226
|
-
const child = spawn(denoCommand, ['run', '--no-prompt', workerScriptPath], {
|
|
227
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
228
|
-
env: {
|
|
229
|
-
...process.env,
|
|
230
|
-
DENO_PERMISSION_BROKER_PATH: socketPath
|
|
231
|
-
}
|
|
232
|
-
});
|
|
233
|
-
this.worker = child;
|
|
234
|
-
child.stdout.setEncoding('utf8');
|
|
235
|
-
child.stderr.setEncoding('utf8');
|
|
236
|
-
child.stdout.on('data', chunk => this.onWorkerStdout(chunk));
|
|
237
|
-
child.on('exit', () => {
|
|
238
|
-
const err = new Error('Deno worker exited unexpectedly.');
|
|
239
|
-
this.rejectAllPending(err);
|
|
240
|
-
if (this.runtimeState.status !== 'failed') {
|
|
241
|
-
this.runtimeState = { status: 'failed', error: err };
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
return new Promise((resolve, reject) => {
|
|
245
|
-
const timer = setTimeout(() => {
|
|
246
|
-
reject(new Error('Timed out waiting for Deno worker startup.'));
|
|
247
|
-
}, BOOT_TIMEOUT_MS);
|
|
248
|
-
const onData = (chunk) => {
|
|
249
|
-
this.workerBuffer += chunk;
|
|
250
|
-
let idx = this.workerBuffer.indexOf('\n');
|
|
251
|
-
while (idx >= 0) {
|
|
252
|
-
const line = this.workerBuffer.slice(0, idx).trim();
|
|
253
|
-
this.workerBuffer = this.workerBuffer.slice(idx + 1);
|
|
254
|
-
idx = this.workerBuffer.indexOf('\n');
|
|
255
|
-
if (!line) {
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
try {
|
|
259
|
-
const parsed = JSON.parse(line);
|
|
260
|
-
if (parsed.type === 'ready') {
|
|
261
|
-
clearTimeout(timer);
|
|
262
|
-
child.stdout.off('data', onData);
|
|
263
|
-
resolve();
|
|
264
|
-
return;
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
catch {
|
|
268
|
-
// ignore until ready payload appears
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
};
|
|
272
|
-
child.stdout.on('data', onData);
|
|
273
|
-
child.once('error', (err) => {
|
|
274
|
-
clearTimeout(timer);
|
|
275
|
-
child.stdout.off('data', onData);
|
|
276
|
-
reject(err);
|
|
277
|
-
});
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
async startRuntime() {
|
|
281
|
-
this.ensureRuntimeAvailable();
|
|
282
|
-
const socketPath = await this.startBroker();
|
|
283
|
-
try {
|
|
284
|
-
await this.startWorker(socketPath);
|
|
285
|
-
}
|
|
286
|
-
catch (err) {
|
|
287
|
-
this.shutdown();
|
|
288
|
-
throw err instanceof Error ? err : new Error(String(err));
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
onWorkerStdout(chunk) {
|
|
292
|
-
this.workerBuffer += chunk;
|
|
293
|
-
let idx = this.workerBuffer.indexOf('\n');
|
|
294
|
-
while (idx >= 0) {
|
|
295
|
-
const line = this.workerBuffer.slice(0, idx).trim();
|
|
296
|
-
this.workerBuffer = this.workerBuffer.slice(idx + 1);
|
|
297
|
-
idx = this.workerBuffer.indexOf('\n');
|
|
298
|
-
if (!line) {
|
|
299
|
-
continue;
|
|
300
|
-
}
|
|
301
|
-
let parsed;
|
|
302
|
-
try {
|
|
303
|
-
parsed = JSON.parse(line);
|
|
304
|
-
}
|
|
305
|
-
catch {
|
|
306
|
-
continue;
|
|
307
|
-
}
|
|
308
|
-
if (!parsed || typeof parsed.id !== 'number') {
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
const pending = this.pending.get(parsed.id);
|
|
312
|
-
if (!pending) {
|
|
313
|
-
continue;
|
|
314
|
-
}
|
|
315
|
-
this.pending.delete(parsed.id);
|
|
316
|
-
clearTimeout(pending.timeout);
|
|
317
|
-
pending.resolve(parsed);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
rejectAllPending(err) {
|
|
321
|
-
for (const pending of this.pending.values()) {
|
|
322
|
-
clearTimeout(pending.timeout);
|
|
323
|
-
pending.reject(err);
|
|
324
|
-
}
|
|
325
|
-
this.pending.clear();
|
|
326
|
-
}
|
|
327
|
-
async callWorker(request) {
|
|
328
|
-
await this.ensureRuntime();
|
|
329
|
-
if (!this.worker || !this.worker.stdin.writable) {
|
|
330
|
-
throw new Error('Deno worker is not available.');
|
|
331
|
-
}
|
|
332
|
-
const id = this.nextRequestId++;
|
|
333
|
-
const payload = { ...request, id };
|
|
334
|
-
return await new Promise((resolve, reject) => {
|
|
335
|
-
const timeout = setTimeout(() => {
|
|
336
|
-
this.pending.delete(id);
|
|
337
|
-
reject(new Error('Timed out waiting for Deno worker response.'));
|
|
338
|
-
}, REQUEST_TIMEOUT_MS);
|
|
339
|
-
this.pending.set(id, { resolve, reject, timeout });
|
|
340
|
-
this.worker.stdin.write(`${JSON.stringify(payload)}\n`);
|
|
341
|
-
});
|
|
342
|
-
}
|
|
343
|
-
shutdown() {
|
|
344
|
-
if (this.worker && !this.worker.killed) {
|
|
345
|
-
this.worker.kill();
|
|
346
|
-
}
|
|
347
|
-
this.worker = undefined;
|
|
348
|
-
if (this.brokerServer) {
|
|
349
|
-
this.brokerServer.close();
|
|
350
|
-
this.brokerServer = undefined;
|
|
351
|
-
}
|
|
352
|
-
if (this.brokerSocketPath && process.platform !== 'win32') {
|
|
353
|
-
try {
|
|
354
|
-
if (fs.existsSync(this.brokerSocketPath)) {
|
|
355
|
-
fs.unlinkSync(this.brokerSocketPath);
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
catch {
|
|
359
|
-
// ignore
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
this.brokerSocketPath = undefined;
|
|
363
|
-
}
|
|
364
|
-
dispose() {
|
|
365
|
-
this.shutdown();
|
|
366
|
-
this.runtimeState = { status: 'idle' };
|
|
367
|
-
}
|
|
368
|
-
assertAllowedPath(absoluteFilePath) {
|
|
369
|
-
const resolvedPath = path.resolve(absoluteFilePath);
|
|
370
|
-
const jsReadRoot = this.opts.jsReadRoot ? path.resolve(this.opts.jsReadRoot) : undefined;
|
|
371
|
-
if (!jsReadRoot) {
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
if (isPathInside(resolvedPath, jsReadRoot)) {
|
|
375
|
-
return;
|
|
376
|
-
}
|
|
377
|
-
// pnpm layouts may resolve package files outside project root.
|
|
378
|
-
if (resolvedPath.includes(`${path.sep}node_modules${path.sep}`)) {
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
throw new Error(`Script path "${resolvedPath}" is outside jsReadRoot "${jsReadRoot}"`);
|
|
382
|
-
}
|
|
383
|
-
async import(absoluteFilePath) {
|
|
384
|
-
const ext = path.extname(absoluteFilePath);
|
|
385
|
-
if (!SCRIPT_EXTENSIONS.has(ext)) {
|
|
386
|
-
throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}"`);
|
|
387
|
-
}
|
|
388
|
-
if (!isFnsPath(absoluteFilePath)) {
|
|
389
|
-
this.assertAllowedPath(absoluteFilePath);
|
|
390
|
-
await this.ensureRuntime();
|
|
391
|
-
const modulePath = path.resolve(absoluteFilePath);
|
|
392
|
-
const loadResult = await this.callWorker({ type: 'load', modulePath });
|
|
393
|
-
if (!loadResult.ok) {
|
|
394
|
-
throw new Error(loadResult.error);
|
|
395
|
-
}
|
|
396
|
-
const moduleObject = {};
|
|
397
|
-
const exported = loadResult.exports ?? [];
|
|
398
|
-
for (const item of exported) {
|
|
399
|
-
if (item.kind === 'function') {
|
|
400
|
-
moduleObject[item.name] = async (...args) => {
|
|
401
|
-
const invokeResult = await this.callWorker({
|
|
402
|
-
type: 'invoke',
|
|
403
|
-
modulePath,
|
|
404
|
-
exportName: item.name,
|
|
405
|
-
args
|
|
406
|
-
});
|
|
407
|
-
if (!invokeResult.ok) {
|
|
408
|
-
throw new Error(invokeResult.error);
|
|
409
|
-
}
|
|
410
|
-
return invokeResult.value;
|
|
411
|
-
};
|
|
412
|
-
}
|
|
413
|
-
else {
|
|
414
|
-
moduleObject[item.name] = item.value;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
return moduleObject;
|
|
418
|
-
}
|
|
419
|
-
const modulePath = pathToFileURL(path.resolve(absoluteFilePath)).href;
|
|
420
|
-
const module = await import(modulePath);
|
|
421
|
-
const safeModule = {};
|
|
422
|
-
for (const [key, value] of Object.entries(module)) {
|
|
423
|
-
if (typeof value === 'function' || isJsonValue(value)) {
|
|
424
|
-
safeModule[key] = value;
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
return safeModule;
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
396
|
/**
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
if (typeof globalThis !==
|
|
436
|
-
globalThis[JESS_PLUGIN_JS_GLOBAL] = true;
|
|
437
|
-
}
|
|
397
|
+
* Global flag set when @jesscss/plugin-js is loaded.
|
|
398
|
+
* less-compat checks this before running @plugin scripts (scripts must be run when plugin-js/Deno is present).
|
|
399
|
+
*/
|
|
400
|
+
const JESS_PLUGIN_JS_GLOBAL = "__JESS_PLUGIN_JS_AVAILABLE__";
|
|
401
|
+
if (typeof globalThis !== "undefined") globalThis[JESS_PLUGIN_JS_GLOBAL] = true;
|
|
438
402
|
const jsPlugin = ((opts) => {
|
|
439
|
-
|
|
403
|
+
return new JsPlugin(opts);
|
|
440
404
|
});
|
|
441
|
-
|
|
442
|
-
|
|
405
|
+
//#endregion
|
|
406
|
+
export { JESS_PLUGIN_JS_GLOBAL, JsPlugin, jsPlugin as default };
|