@locker/cli 0.28.3
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.txt +21 -0
- package/README.md +813 -0
- package/bin/lws.mjs +209 -0
- package/dist/index.cjs.d.ts +2 -0
- package/dist/index.cjs.d.ts.map +1 -0
- package/dist/index.cjs.js +5 -0
- package/dist/index.mjs.d.ts +2 -0
- package/dist/index.mjs.d.ts.map +1 -0
- package/dist/index.mjs.js +5 -0
- package/dist/lwc-engine.js +8432 -0
- package/dist/lws-sandbox.js +18781 -0
- package/dist/purify.js +3 -0
- package/package.json +45 -0
- package/src/before-after.mjs +47 -0
- package/src/browser.mjs +186 -0
- package/src/compile-lwc.mjs +181 -0
- package/src/completion.mjs +166 -0
- package/src/constants.mjs +15 -0
- package/src/endowments.mjs +189 -0
- package/src/harness/component.html +14 -0
- package/src/harness/eval.html +12 -0
- package/src/index.ts +1 -0
- package/src/input-resolver.mjs +63 -0
- package/src/lwc-engine-entry.js +8 -0
- package/src/output.mjs +168 -0
- package/src/repl.mjs +527 -0
- package/src/runner.mjs +772 -0
- package/src/sandbox-entry.ts +7 -0
- package/src/server.mjs +256 -0
- package/src/transform.mjs +95 -0
- package/src/version-check.mjs +256 -0
- package/src/watcher.mjs +124 -0
package/src/runner.mjs
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { injectScriptTags, loadScriptFiles } from './before-after.mjs';
|
|
6
|
+
import { Browser } from './browser.mjs';
|
|
7
|
+
import { compileComponent } from './compile-lwc.mjs';
|
|
8
|
+
import {
|
|
9
|
+
COMPLETION_GLOBAL,
|
|
10
|
+
EXIT_HARNESS_FAILURE,
|
|
11
|
+
exitCodeFor,
|
|
12
|
+
humanSummary,
|
|
13
|
+
normalCompletion,
|
|
14
|
+
throwCompletion,
|
|
15
|
+
} from './completion.mjs';
|
|
16
|
+
import { buildEndowmentsRegisterScript, loadEndowments } from './endowments.mjs';
|
|
17
|
+
import { resolveInput } from './input-resolver.mjs';
|
|
18
|
+
import { Output } from './output.mjs';
|
|
19
|
+
import { Server } from './server.mjs';
|
|
20
|
+
import { transform } from './transform.mjs';
|
|
21
|
+
import { awaitAndEmitUpgradeNotice, startVersionCheckForCLI } from './version-check.mjs';
|
|
22
|
+
import { assertWatchableEvalOrigin, rerunBanner, watchPaths } from './watcher.mjs';
|
|
23
|
+
|
|
24
|
+
const require = createRequire(import.meta.url);
|
|
25
|
+
// `private: true` in package.json is the pre-publish signal that skips
|
|
26
|
+
// the version check entirely. `import.meta.url` lets the check tell
|
|
27
|
+
// monorepo-source runs from installed-package runs and skip the former.
|
|
28
|
+
const PACKAGE_JSON = require('../package.json');
|
|
29
|
+
const RUNNER_MODULE_PATH = new URL(import.meta.url).pathname;
|
|
30
|
+
|
|
31
|
+
const EVAL_HARNESS_PATH = '/eval.html';
|
|
32
|
+
const COMPONENT_HARNESS_PATH = '/component.html';
|
|
33
|
+
const COMPONENT_BUNDLE_ROUTE = '/_bundle/component.js';
|
|
34
|
+
|
|
35
|
+
// Single owner of process-exit choreography. SIGINT/SIGTERM trigger an
|
|
36
|
+
// orderly teardown: browser → server → exit. Two components installing
|
|
37
|
+
// handlers independently leads to non-deterministic ordering and partial
|
|
38
|
+
// cleanup, which is why neither browser.mjs nor server.mjs touches signals.
|
|
39
|
+
class SignalLatch {
|
|
40
|
+
constructor() {
|
|
41
|
+
this.triggered = false;
|
|
42
|
+
this.promise = new Promise((resolve) => {
|
|
43
|
+
this.resolve = resolve;
|
|
44
|
+
});
|
|
45
|
+
this.handler = (signal) => {
|
|
46
|
+
this.triggered = signal;
|
|
47
|
+
this.resolve(signal);
|
|
48
|
+
};
|
|
49
|
+
process.once('SIGINT', this.handler);
|
|
50
|
+
process.once('SIGTERM', this.handler);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
detach() {
|
|
54
|
+
process.removeListener('SIGINT', this.handler);
|
|
55
|
+
process.removeListener('SIGTERM', this.handler);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Read the in-page completion global (set by the harness error listener on
|
|
60
|
+
// the first uncaught sandbox throw), build the Completion Report, record it
|
|
61
|
+
// on Output, and return the mapped process exit code. Called on the success
|
|
62
|
+
// path of a run AFTER the run window has closed (addScriptTag settle for
|
|
63
|
+
// eval, render stabilization for component) so a throw, if any, has already
|
|
64
|
+
// been captured. A missing global means the run completed normally.
|
|
65
|
+
//
|
|
66
|
+
// This is distinct from the catch-block path: a thrown error in the runner
|
|
67
|
+
// itself is a harness/infra failure (browser launch, server bind, timeout,
|
|
68
|
+
// interrupt) that produced NO completion, and stays at EXIT_HARNESS_FAILURE.
|
|
69
|
+
async function resolveCompletion(browser, output) {
|
|
70
|
+
let captured = null;
|
|
71
|
+
try {
|
|
72
|
+
captured = await browser.evaluate((prop) => window[prop] ?? null, COMPLETION_GLOBAL);
|
|
73
|
+
} catch {
|
|
74
|
+
// If the page is already torn down or the evaluate fails, treat the
|
|
75
|
+
// run as normal: we have no evidence of a throw. The catch-block
|
|
76
|
+
// path owns genuine harness failures.
|
|
77
|
+
captured = null;
|
|
78
|
+
}
|
|
79
|
+
const completion = captured === null ? normalCompletion() : throwCompletion(captured);
|
|
80
|
+
output.setCompletion(completion);
|
|
81
|
+
if (captured !== null) {
|
|
82
|
+
// A throw completion must flip the legacy envelope to ok:false and
|
|
83
|
+
// populate the legacy `error` field, so `ok`/`error` stay consistent
|
|
84
|
+
// with the new `completion` field (an existing consumer keying on
|
|
85
|
+
// `ok` would otherwise read a security block as success). The staged
|
|
86
|
+
// compiled `result` survives this fail() and still rides the
|
|
87
|
+
// envelope. captured is already shaped { message, name } for fail().
|
|
88
|
+
output.fail(captured);
|
|
89
|
+
const summary = humanSummary(completion);
|
|
90
|
+
if (summary !== null) {
|
|
91
|
+
output.error(summary);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return exitCodeFor(completion);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function runEval(argv) {
|
|
98
|
+
// Watch mode owns a persistent browser/server lifecycle (launch once,
|
|
99
|
+
// re-evaluate on change), which is the inverse of the one-shot path's
|
|
100
|
+
// launch-evaluate-teardown. Branch before any one-shot setup so the
|
|
101
|
+
// existing code path stays exactly as it was for non-watch runs.
|
|
102
|
+
if (argv.watch === true) {
|
|
103
|
+
return runEvalWatch(argv);
|
|
104
|
+
}
|
|
105
|
+
const output = new Output({
|
|
106
|
+
json: argv.json === true,
|
|
107
|
+
verbosity: argv.quiet ? 'quiet' : argv.verbose ? 'verbose' : 'normal',
|
|
108
|
+
});
|
|
109
|
+
// Kick off the npm registry version check in parallel with the
|
|
110
|
+
// command. This overlaps the network round-trip with our actual
|
|
111
|
+
// work, so the user pays no extra latency unless we have to wait
|
|
112
|
+
// at the very end (capped at 1.5s by the check's internal timeout).
|
|
113
|
+
const versionCheckPromise = startVersionCheckForCLI({
|
|
114
|
+
argv,
|
|
115
|
+
packageJson: PACKAGE_JSON,
|
|
116
|
+
installedPath: RUNNER_MODULE_PATH,
|
|
117
|
+
});
|
|
118
|
+
const signals = new SignalLatch();
|
|
119
|
+
let server = null;
|
|
120
|
+
let browser = null;
|
|
121
|
+
|
|
122
|
+
try {
|
|
123
|
+
output.timing.start('total');
|
|
124
|
+
|
|
125
|
+
output.timing.start('input-resolve');
|
|
126
|
+
const { source, origin } = await resolveInput(argv['code-or-file']);
|
|
127
|
+
output.timing.end('input-resolve');
|
|
128
|
+
output.debug(`resolved input from ${origin}`);
|
|
129
|
+
|
|
130
|
+
output.timing.start('compile');
|
|
131
|
+
const transformedSource = await transform({
|
|
132
|
+
source,
|
|
133
|
+
origin,
|
|
134
|
+
sandboxKey: argv.key,
|
|
135
|
+
});
|
|
136
|
+
output.timing.end('compile');
|
|
137
|
+
output.result(transformedSource);
|
|
138
|
+
|
|
139
|
+
output.timing.start('server-startup');
|
|
140
|
+
server = new Server({ port: argv.port });
|
|
141
|
+
await server.start();
|
|
142
|
+
output.timing.end('server-startup');
|
|
143
|
+
output.debug(`server listening at ${server.origin}`);
|
|
144
|
+
|
|
145
|
+
output.timing.start('browser-launch');
|
|
146
|
+
browser = new Browser({
|
|
147
|
+
browser: argv.browser,
|
|
148
|
+
headed: argv.headed === true,
|
|
149
|
+
consoleStream: process.stderr,
|
|
150
|
+
});
|
|
151
|
+
await browser.launch();
|
|
152
|
+
output.timing.end('browser-launch');
|
|
153
|
+
|
|
154
|
+
await browser.goto(`${server.origin}${EVAL_HARNESS_PATH}`, { waitUntil: 'load' });
|
|
155
|
+
// The harness already loaded purify.js + lws-sandbox.js (assigning
|
|
156
|
+
// window.evaluateInSandbox). Verify before injecting user code.
|
|
157
|
+
await browser.evaluate(() => {
|
|
158
|
+
if (typeof window.evaluateInSandbox !== 'function') {
|
|
159
|
+
throw new Error('window.evaluateInSandbox not exposed by harness');
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// Endowments registration runs BEFORE before-scripts and BEFORE
|
|
164
|
+
// the user's transformed bundle. The register script sets
|
|
165
|
+
// `window.__lwsCLIEndowments` to a real JS object literal
|
|
166
|
+
// emitted from the loaded endowments. The CLI wrapper module
|
|
167
|
+
// (lib/evaluator.mjs, bundled into the user's IIFE via the
|
|
168
|
+
// karma-pattern sandboxSpecifier override) reads that window
|
|
169
|
+
// slot at module-init time and snapshots it into module
|
|
170
|
+
// scope. Functions and closures survive end to end because
|
|
171
|
+
// the literal is parsed by the browser as JS, not transported
|
|
172
|
+
// through JSON.stringify.
|
|
173
|
+
const endowments = await loadEndowments(argv.endowments);
|
|
174
|
+
if (endowments !== null) {
|
|
175
|
+
output.timing.start('endowments');
|
|
176
|
+
await browser.withPageErrorTrap(() =>
|
|
177
|
+
browser.addScriptTag({ content: buildEndowmentsRegisterScript(endowments) }),
|
|
178
|
+
);
|
|
179
|
+
output.timing.end('endowments');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// --before files run as system-mode <script> tags BEFORE the
|
|
183
|
+
// sandboxed user code. A throw in any before-script bubbles out
|
|
184
|
+
// of injectScriptTags, fails the run, and the sandbox code
|
|
185
|
+
// never executes. Each file is its own <script> so var/let
|
|
186
|
+
// bindings don't bleed between files.
|
|
187
|
+
const beforeEntries = await loadScriptFiles(argv.before);
|
|
188
|
+
if (beforeEntries.length > 0) {
|
|
189
|
+
output.timing.start('before');
|
|
190
|
+
// pageerror trap: a throw inside an injected before-script
|
|
191
|
+
// does NOT reject Playwright's addScriptTag promise (it only
|
|
192
|
+
// fires `pageerror`), so the run would otherwise silently
|
|
193
|
+
// continue. The trap surfaces the first pageerror as a
|
|
194
|
+
// thrown error, which the outer try/catch routes to
|
|
195
|
+
// `output.fail`.
|
|
196
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, beforeEntries));
|
|
197
|
+
output.timing.end('before');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// --timeout enforcement: race the existing addScriptTag against
|
|
201
|
+
// a setTimeout-driven rejection. The `finally` block already
|
|
202
|
+
// calls browser.close() on any throw, which is the same teardown
|
|
203
|
+
// path SIGINT uses, so a timed-out run cleans up identically to
|
|
204
|
+
// an interrupted run. The setTimeout is unref()'d so its
|
|
205
|
+
// pending state never holds the process open in the no-timeout
|
|
206
|
+
// case (timeout = undefined skips the race entirely).
|
|
207
|
+
const timeoutMs = typeof argv.timeout === 'number' ? argv.timeout : null;
|
|
208
|
+
let timeoutHandle = null;
|
|
209
|
+
const racers = [
|
|
210
|
+
browser.addScriptTag({ content: transformedSource }),
|
|
211
|
+
signals.promise.then((sig) => {
|
|
212
|
+
throw new Error(`interrupted by ${sig}`);
|
|
213
|
+
}),
|
|
214
|
+
];
|
|
215
|
+
if (timeoutMs !== null && timeoutMs > 0) {
|
|
216
|
+
racers.push(
|
|
217
|
+
new Promise((_resolve, reject) => {
|
|
218
|
+
timeoutHandle = setTimeout(() => {
|
|
219
|
+
reject(new Error(`evaluation timed out after ${timeoutMs}ms`));
|
|
220
|
+
}, timeoutMs);
|
|
221
|
+
timeoutHandle.unref?.();
|
|
222
|
+
}),
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// Inject the transformed source as a script tag, the production-
|
|
227
|
+
// faithful path. The transform output is a complete top-level
|
|
228
|
+
// `evaluateInSandbox(key, () => { ... })` call; running it as a
|
|
229
|
+
// script element is what real LWS-secured pages do.
|
|
230
|
+
output.timing.start('evaluation');
|
|
231
|
+
try {
|
|
232
|
+
await Promise.race(racers);
|
|
233
|
+
} finally {
|
|
234
|
+
if (timeoutHandle !== null) {
|
|
235
|
+
clearTimeout(timeoutHandle);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
output.timing.end('evaluation');
|
|
239
|
+
|
|
240
|
+
// --after files run as system-mode <script> tags AFTER the
|
|
241
|
+
// sandboxed user code. A throw in any after-script propagates
|
|
242
|
+
// to the runner and exits non-zero. After-scripts are intended
|
|
243
|
+
// as test-style assertions ("the sandbox failed to mutate state
|
|
244
|
+
// X" / "distortion Y produced the expected outcome"), so a
|
|
245
|
+
// throw is a test failure and the run must reflect that in its
|
|
246
|
+
// exit code.
|
|
247
|
+
const afterEntries = await loadScriptFiles(argv.after);
|
|
248
|
+
if (afterEntries.length > 0) {
|
|
249
|
+
output.timing.start('after');
|
|
250
|
+
// Same pageerror trap as before-scripts: surface throws as
|
|
251
|
+
// run failures rather than silent pageerror logs.
|
|
252
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, afterEntries));
|
|
253
|
+
output.timing.end('after');
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// The evaluation window has closed; read whether the sandbox threw
|
|
257
|
+
// (the harness error listener stashes the first throw on a window
|
|
258
|
+
// global) and map it to a Completion Report + semantic exit code.
|
|
259
|
+
const exitCode = await resolveCompletion(browser, output);
|
|
260
|
+
|
|
261
|
+
if (argv.headed === true) {
|
|
262
|
+
output.info(
|
|
263
|
+
`Sandbox ready at ${server.origin}${EVAL_HARNESS_PATH} — press Ctrl+C to exit`,
|
|
264
|
+
);
|
|
265
|
+
await Promise.race([browser.waitForDisconnect(), signals.promise]);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
output.timing.end('total');
|
|
269
|
+
return exitCode;
|
|
270
|
+
} catch (err) {
|
|
271
|
+
// End the total span if it's still open so the JSON envelope's
|
|
272
|
+
// timing.total reflects the elapsed time up to the failure.
|
|
273
|
+
try {
|
|
274
|
+
output.timing.end('total');
|
|
275
|
+
} catch {
|
|
276
|
+
// total was either never started or already ended; either is fine.
|
|
277
|
+
}
|
|
278
|
+
output.fail(err);
|
|
279
|
+
// A throw in the runner is a harness/infra failure (browser launch,
|
|
280
|
+
// server bind, timeout, interrupt): no completion was produced, so
|
|
281
|
+
// it stays at the generic failure code, NOT a throw-completion code.
|
|
282
|
+
return EXIT_HARNESS_FAILURE;
|
|
283
|
+
} finally {
|
|
284
|
+
// Emit the upgrade notice (if any) BEFORE flushing the JSON
|
|
285
|
+
// envelope. The notice goes to stderr; flush() emits the
|
|
286
|
+
// envelope on stdout. Order matters only for human consumers
|
|
287
|
+
// (the notice and the result text appear on different streams)
|
|
288
|
+
// but keeping the notice first is consistent with "diagnostics
|
|
289
|
+
// before result" output ordering elsewhere.
|
|
290
|
+
await awaitAndEmitUpgradeNotice({
|
|
291
|
+
promise: versionCheckPromise,
|
|
292
|
+
packageJson: PACKAGE_JSON,
|
|
293
|
+
output,
|
|
294
|
+
});
|
|
295
|
+
// flush() is the single sink for JSON-mode envelopes. It runs
|
|
296
|
+
// here so the timing data captured up to the success or failure
|
|
297
|
+
// point is included. Text-mode flush() is a no-op.
|
|
298
|
+
output.flush();
|
|
299
|
+
signals.detach();
|
|
300
|
+
if (browser) {
|
|
301
|
+
await browser.close();
|
|
302
|
+
}
|
|
303
|
+
if (server) {
|
|
304
|
+
await server.stop();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export async function runComponent(argv) {
|
|
310
|
+
if (argv.watch === true) {
|
|
311
|
+
return runComponentWatch(argv);
|
|
312
|
+
}
|
|
313
|
+
const output = new Output({
|
|
314
|
+
json: argv.json === true,
|
|
315
|
+
verbosity: argv.quiet ? 'quiet' : argv.verbose ? 'verbose' : 'normal',
|
|
316
|
+
});
|
|
317
|
+
const versionCheckPromise = startVersionCheckForCLI({
|
|
318
|
+
argv,
|
|
319
|
+
packageJson: PACKAGE_JSON,
|
|
320
|
+
installedPath: RUNNER_MODULE_PATH,
|
|
321
|
+
});
|
|
322
|
+
const signals = new SignalLatch();
|
|
323
|
+
let server = null;
|
|
324
|
+
let browser = null;
|
|
325
|
+
let tmpDir = null;
|
|
326
|
+
|
|
327
|
+
try {
|
|
328
|
+
output.timing.start('total');
|
|
329
|
+
|
|
330
|
+
// Resolve directory against CWD so `lws component ./foo` works from
|
|
331
|
+
// anywhere. Compile failures throw before we touch the browser.
|
|
332
|
+
const directory = path.resolve(process.cwd(), argv.directory);
|
|
333
|
+
|
|
334
|
+
output.timing.start('compile');
|
|
335
|
+
const compiled = await compileComponent({
|
|
336
|
+
directory,
|
|
337
|
+
name: argv.name,
|
|
338
|
+
namespace: argv.namespace,
|
|
339
|
+
sandboxKey: argv.key,
|
|
340
|
+
// yargs gives us the array on argv['lwc-modules'] when --lwc-modules
|
|
341
|
+
// is passed at least once; default to [] when absent.
|
|
342
|
+
lwcModules: argv['lwc-modules'] ?? [],
|
|
343
|
+
});
|
|
344
|
+
output.timing.end('compile');
|
|
345
|
+
tmpDir = compiled.tmpDir;
|
|
346
|
+
output.result(compiled.code);
|
|
347
|
+
output.debug(`compiled component → ${compiled.bundleFile} (tag: ${compiled.tag})`);
|
|
348
|
+
|
|
349
|
+
output.timing.start('server-startup');
|
|
350
|
+
server = new Server({ port: argv.port });
|
|
351
|
+
server.registerBundle(COMPONENT_BUNDLE_ROUTE, compiled.bundleFile);
|
|
352
|
+
await server.start();
|
|
353
|
+
output.timing.end('server-startup');
|
|
354
|
+
output.debug(`server listening at ${server.origin}`);
|
|
355
|
+
|
|
356
|
+
output.timing.start('browser-launch');
|
|
357
|
+
browser = new Browser({
|
|
358
|
+
browser: argv.browser,
|
|
359
|
+
headed: argv.headed === true,
|
|
360
|
+
consoleStream: process.stderr,
|
|
361
|
+
});
|
|
362
|
+
await browser.launch();
|
|
363
|
+
output.timing.end('browser-launch');
|
|
364
|
+
|
|
365
|
+
// Endowments registration must happen BEFORE `browser.goto`
|
|
366
|
+
// because the harness page loads the component bundle via
|
|
367
|
+
// `<script src="/_bundle/component.js">` synchronously during
|
|
368
|
+
// navigation. By the time `goto` returns, the bundle's IIFE
|
|
369
|
+
// has executed and the wrapper module's `cliEndowments`
|
|
370
|
+
// snapshot is locked in. `addInitScript` queues a script to
|
|
371
|
+
// run on every frame BEFORE any other script on the page,
|
|
372
|
+
// which is exactly the timing we need.
|
|
373
|
+
const componentEndowments = await loadEndowments(argv.endowments);
|
|
374
|
+
if (componentEndowments !== null) {
|
|
375
|
+
output.timing.start('endowments');
|
|
376
|
+
await browser.addInitScript({
|
|
377
|
+
content: buildEndowmentsRegisterScript(componentEndowments),
|
|
378
|
+
});
|
|
379
|
+
output.timing.end('endowments');
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Before-scripts inject between harness load and component
|
|
383
|
+
// render. The component bundle is loaded by the harness page
|
|
384
|
+
// itself (a <script src="/_bundle/component.js"> tag), so by
|
|
385
|
+
// the time we arrive here that script has already executed.
|
|
386
|
+
// Before-scripts still run BEFORE the render-stabilization
|
|
387
|
+
// wait: their job is to populate system-mode globals and
|
|
388
|
+
// fixtures that the component (sandboxed) can read through the
|
|
389
|
+
// membrane during its first render cycle.
|
|
390
|
+
await browser.goto(`${server.origin}${COMPONENT_HARNESS_PATH}`, { waitUntil: 'load' });
|
|
391
|
+
|
|
392
|
+
const beforeEntries = await loadScriptFiles(argv.before);
|
|
393
|
+
if (beforeEntries.length > 0) {
|
|
394
|
+
output.timing.start('before');
|
|
395
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, beforeEntries));
|
|
396
|
+
output.timing.end('before');
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// After harness load + component bundle execution, wait for two
|
|
400
|
+
// requestAnimationFrames: the first lets LWC flush its render
|
|
401
|
+
// queue, the second confirms the DOM is stable. This is the
|
|
402
|
+
// standard pattern for "the component has finished its initial
|
|
403
|
+
// render."
|
|
404
|
+
output.timing.start('render');
|
|
405
|
+
await Promise.race([
|
|
406
|
+
browser.evaluate(
|
|
407
|
+
() =>
|
|
408
|
+
new Promise((resolve) => {
|
|
409
|
+
requestAnimationFrame(() => requestAnimationFrame(resolve));
|
|
410
|
+
}),
|
|
411
|
+
),
|
|
412
|
+
signals.promise.then((sig) => {
|
|
413
|
+
throw new Error(`interrupted by ${sig}`);
|
|
414
|
+
}),
|
|
415
|
+
]);
|
|
416
|
+
output.timing.end('render');
|
|
417
|
+
|
|
418
|
+
// After-scripts run AFTER initial render stabilization. They
|
|
419
|
+
// assert against the rendered DOM, distortion outcomes, or
|
|
420
|
+
// post-render state. A throw here is a test failure and exits
|
|
421
|
+
// non-zero.
|
|
422
|
+
const afterEntries = await loadScriptFiles(argv.after);
|
|
423
|
+
if (afterEntries.length > 0) {
|
|
424
|
+
output.timing.start('after');
|
|
425
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, afterEntries));
|
|
426
|
+
output.timing.end('after');
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Render has stabilized; read whether the component threw (module
|
|
430
|
+
// top-level OR an async lifecycle callback like connectedCallback,
|
|
431
|
+
// both of which surface as uncaught window errors the harness
|
|
432
|
+
// listener stashes on a window global) and map it to a Completion
|
|
433
|
+
// Report + semantic exit code.
|
|
434
|
+
const exitCode = await resolveCompletion(browser, output);
|
|
435
|
+
|
|
436
|
+
if (argv.headed === true) {
|
|
437
|
+
output.info(
|
|
438
|
+
`Component rendered at ${server.origin}${COMPONENT_HARNESS_PATH} — press Ctrl+C to exit`,
|
|
439
|
+
);
|
|
440
|
+
await Promise.race([browser.waitForDisconnect(), signals.promise]);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
output.timing.end('total');
|
|
444
|
+
return exitCode;
|
|
445
|
+
} catch (err) {
|
|
446
|
+
try {
|
|
447
|
+
output.timing.end('total');
|
|
448
|
+
} catch {
|
|
449
|
+
// total was either never started or already ended; either is fine.
|
|
450
|
+
}
|
|
451
|
+
output.fail(err);
|
|
452
|
+
return EXIT_HARNESS_FAILURE;
|
|
453
|
+
} finally {
|
|
454
|
+
await awaitAndEmitUpgradeNotice({
|
|
455
|
+
promise: versionCheckPromise,
|
|
456
|
+
packageJson: PACKAGE_JSON,
|
|
457
|
+
output,
|
|
458
|
+
});
|
|
459
|
+
output.flush();
|
|
460
|
+
signals.detach();
|
|
461
|
+
if (browser) {
|
|
462
|
+
await browser.close();
|
|
463
|
+
}
|
|
464
|
+
if (server) {
|
|
465
|
+
await server.stop();
|
|
466
|
+
}
|
|
467
|
+
if (tmpDir) {
|
|
468
|
+
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// Serialize re-runs and never let one re-run's failure tear down the watch
|
|
474
|
+
// session. In iterative development the whole point is to save broken code,
|
|
475
|
+
// read the error, fix it, and save again — so a thrown re-run prints its
|
|
476
|
+
// message and the watcher keeps running. The `running`/`pending` pair
|
|
477
|
+
// coalesces changes that land mid-run into exactly one follow-up run
|
|
478
|
+
// (chokidar's debounce already collapses bursts from a single save; this
|
|
479
|
+
// guards the longer window of an in-flight browser navigation).
|
|
480
|
+
function makeRerunGate(runOnce, output) {
|
|
481
|
+
let running = false;
|
|
482
|
+
let pending = false;
|
|
483
|
+
const tick = async (changedPath) => {
|
|
484
|
+
if (running) {
|
|
485
|
+
pending = true;
|
|
486
|
+
return;
|
|
487
|
+
}
|
|
488
|
+
running = true;
|
|
489
|
+
try {
|
|
490
|
+
await runOnce(changedPath);
|
|
491
|
+
} catch (err) {
|
|
492
|
+
output.error(err.message);
|
|
493
|
+
} finally {
|
|
494
|
+
running = false;
|
|
495
|
+
}
|
|
496
|
+
if (pending) {
|
|
497
|
+
pending = false;
|
|
498
|
+
await tick(changedPath);
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
return tick;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// `lws eval --watch <file>`: launch the browser/server once, then re-read,
|
|
505
|
+
// re-transform, and re-evaluate in a fresh page (= fresh sandbox realm) on
|
|
506
|
+
// every save. Headed mode shows each re-run in the open window; headless
|
|
507
|
+
// mode reprints the transformed source to stdout and forwards console output
|
|
508
|
+
// to stderr. Exits on Ctrl+C (or, in headed mode, when the user closes the
|
|
509
|
+
// browser).
|
|
510
|
+
async function runEvalWatch(argv) {
|
|
511
|
+
const output = new Output({
|
|
512
|
+
// --json is rejected for --watch at argv parse, so watch sessions are
|
|
513
|
+
// always text-mode: a streaming separator-delimited log, not a single
|
|
514
|
+
// envelope.
|
|
515
|
+
json: false,
|
|
516
|
+
verbosity: argv.quiet ? 'quiet' : argv.verbose ? 'verbose' : 'normal',
|
|
517
|
+
});
|
|
518
|
+
const versionCheckPromise = startVersionCheckForCLI({
|
|
519
|
+
argv,
|
|
520
|
+
packageJson: PACKAGE_JSON,
|
|
521
|
+
installedPath: RUNNER_MODULE_PATH,
|
|
522
|
+
});
|
|
523
|
+
const signals = new SignalLatch();
|
|
524
|
+
let server = null;
|
|
525
|
+
let browser = null;
|
|
526
|
+
let watcher = null;
|
|
527
|
+
|
|
528
|
+
try {
|
|
529
|
+
// Resolve once up front to validate the input is a real file — inline
|
|
530
|
+
// source and stdin have nothing to re-read, so reject before launching
|
|
531
|
+
// anything. The resolved origin is the path we watch.
|
|
532
|
+
const { origin } = await resolveInput(argv['code-or-file']);
|
|
533
|
+
assertWatchableEvalOrigin(origin);
|
|
534
|
+
|
|
535
|
+
server = new Server({ port: argv.port });
|
|
536
|
+
await server.start();
|
|
537
|
+
output.debug(`server listening at ${server.origin}`);
|
|
538
|
+
|
|
539
|
+
browser = new Browser({
|
|
540
|
+
browser: argv.browser,
|
|
541
|
+
headed: argv.headed === true,
|
|
542
|
+
consoleStream: process.stderr,
|
|
543
|
+
});
|
|
544
|
+
await browser.launch();
|
|
545
|
+
|
|
546
|
+
// One re-evaluation cycle: re-read the file (it may have changed),
|
|
547
|
+
// re-transform, navigate to a fresh harness page, replay
|
|
548
|
+
// endowments/before, inject the transformed bundle, run after. A fresh
|
|
549
|
+
// `goto` gives a clean realm, satisfying the "fresh sandbox context"
|
|
550
|
+
// requirement without any sandbox-reset API.
|
|
551
|
+
const runOnce = async () => {
|
|
552
|
+
const { source, origin: freshOrigin } = await resolveInput(argv['code-or-file']);
|
|
553
|
+
const transformedSource = await transform({
|
|
554
|
+
source,
|
|
555
|
+
origin: freshOrigin,
|
|
556
|
+
sandboxKey: argv.key,
|
|
557
|
+
});
|
|
558
|
+
output.result(transformedSource);
|
|
559
|
+
|
|
560
|
+
await browser.goto(`${server.origin}${EVAL_HARNESS_PATH}`, { waitUntil: 'load' });
|
|
561
|
+
await browser.evaluate(() => {
|
|
562
|
+
if (typeof window.evaluateInSandbox !== 'function') {
|
|
563
|
+
throw new Error('window.evaluateInSandbox not exposed by harness');
|
|
564
|
+
}
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
const endowments = await loadEndowments(argv.endowments);
|
|
568
|
+
if (endowments !== null) {
|
|
569
|
+
await browser.withPageErrorTrap(() =>
|
|
570
|
+
browser.addScriptTag({ content: buildEndowmentsRegisterScript(endowments) }),
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const beforeEntries = await loadScriptFiles(argv.before);
|
|
575
|
+
if (beforeEntries.length > 0) {
|
|
576
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, beforeEntries));
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
await browser.addScriptTag({ content: transformedSource });
|
|
580
|
+
|
|
581
|
+
const afterEntries = await loadScriptFiles(argv.after);
|
|
582
|
+
if (afterEntries.length > 0) {
|
|
583
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, afterEntries));
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
|
|
587
|
+
// Initial evaluation, as the one-shot path would do it. A failure here
|
|
588
|
+
// is printed but does not abort the session: the user can fix the file
|
|
589
|
+
// and save to trigger a clean re-run.
|
|
590
|
+
try {
|
|
591
|
+
await runOnce();
|
|
592
|
+
} catch (err) {
|
|
593
|
+
output.error(err.message);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
const gate = makeRerunGate(async (changedPath) => {
|
|
597
|
+
output.info(rerunBanner(new Date(), changedPath));
|
|
598
|
+
await runOnce();
|
|
599
|
+
}, output);
|
|
600
|
+
// Create the watcher and wait for its initial census to complete BEFORE
|
|
601
|
+
// announcing the watch. The "Watching..." banner is the signal (to a
|
|
602
|
+
// user and to the integration test) that the next save will be picked
|
|
603
|
+
// up; under polling, an edit landing before the census is folded into
|
|
604
|
+
// the baseline and never fires `change`, so announcing first would
|
|
605
|
+
// silently drop the first save.
|
|
606
|
+
watcher = watchPaths({ paths: origin, onChange: gate });
|
|
607
|
+
await watcher.ready;
|
|
608
|
+
|
|
609
|
+
output.info(
|
|
610
|
+
`Watching ${origin} (${argv.browser}, key="${argv.key}") — press Ctrl+C to exit`,
|
|
611
|
+
);
|
|
612
|
+
|
|
613
|
+
// Hold the session open until Ctrl+C / SIGTERM, or (headed) the user
|
|
614
|
+
// closes the browser window. Either way we fall through to teardown.
|
|
615
|
+
await Promise.race([signals.promise, browser.waitForDisconnect()]);
|
|
616
|
+
return 0;
|
|
617
|
+
} catch (err) {
|
|
618
|
+
output.fail(err);
|
|
619
|
+
return 1;
|
|
620
|
+
} finally {
|
|
621
|
+
await awaitAndEmitUpgradeNotice({
|
|
622
|
+
promise: versionCheckPromise,
|
|
623
|
+
packageJson: PACKAGE_JSON,
|
|
624
|
+
output,
|
|
625
|
+
});
|
|
626
|
+
signals.detach();
|
|
627
|
+
if (watcher) {
|
|
628
|
+
await watcher.close();
|
|
629
|
+
}
|
|
630
|
+
if (browser) {
|
|
631
|
+
await browser.close();
|
|
632
|
+
}
|
|
633
|
+
if (server) {
|
|
634
|
+
await server.stop();
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// `lws component --watch <directory>`: launch once, then re-compile the
|
|
640
|
+
// component and reload the harness on any change inside the directory. Each
|
|
641
|
+
// re-compile produces a fresh tmp bundle; we re-point the bundle route at it,
|
|
642
|
+
// reload the page (fresh realm), and clean up the previous tmp dir.
|
|
643
|
+
async function runComponentWatch(argv) {
|
|
644
|
+
const output = new Output({
|
|
645
|
+
json: false,
|
|
646
|
+
verbosity: argv.quiet ? 'quiet' : argv.verbose ? 'verbose' : 'normal',
|
|
647
|
+
});
|
|
648
|
+
const versionCheckPromise = startVersionCheckForCLI({
|
|
649
|
+
argv,
|
|
650
|
+
packageJson: PACKAGE_JSON,
|
|
651
|
+
installedPath: RUNNER_MODULE_PATH,
|
|
652
|
+
});
|
|
653
|
+
const signals = new SignalLatch();
|
|
654
|
+
const directory = path.resolve(process.cwd(), argv.directory);
|
|
655
|
+
let server = null;
|
|
656
|
+
let browser = null;
|
|
657
|
+
let watcher = null;
|
|
658
|
+
// The tmp dir of the most recent successful compile. Replaced (and the
|
|
659
|
+
// prior one removed) on each re-compile; removed at teardown.
|
|
660
|
+
let currentTmpDir = null;
|
|
661
|
+
|
|
662
|
+
try {
|
|
663
|
+
server = new Server({ port: argv.port });
|
|
664
|
+
await server.start();
|
|
665
|
+
output.debug(`server listening at ${server.origin}`);
|
|
666
|
+
|
|
667
|
+
browser = new Browser({
|
|
668
|
+
browser: argv.browser,
|
|
669
|
+
headed: argv.headed === true,
|
|
670
|
+
consoleStream: process.stderr,
|
|
671
|
+
});
|
|
672
|
+
await browser.launch();
|
|
673
|
+
|
|
674
|
+
// Endowments register via addInitScript, which applies to every
|
|
675
|
+
// subsequent navigation, so register once before the first goto rather
|
|
676
|
+
// than on each re-run. Component-directory changes (the watch target)
|
|
677
|
+
// don't touch the endowments file, so a one-time registration matches
|
|
678
|
+
// the watch scope.
|
|
679
|
+
const componentEndowments = await loadEndowments(argv.endowments);
|
|
680
|
+
if (componentEndowments !== null) {
|
|
681
|
+
await browser.addInitScript({
|
|
682
|
+
content: buildEndowmentsRegisterScript(componentEndowments),
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const runOnce = async () => {
|
|
687
|
+
const compiled = await compileComponent({
|
|
688
|
+
directory,
|
|
689
|
+
name: argv.name,
|
|
690
|
+
namespace: argv.namespace,
|
|
691
|
+
sandboxKey: argv.key,
|
|
692
|
+
lwcModules: argv['lwc-modules'] ?? [],
|
|
693
|
+
});
|
|
694
|
+
output.result(compiled.code);
|
|
695
|
+
output.debug(`compiled component → ${compiled.bundleFile} (tag: ${compiled.tag})`);
|
|
696
|
+
|
|
697
|
+
// Re-point the bundle route at the freshly compiled file, then
|
|
698
|
+
// remove the previous tmp dir. Order matters: register first so a
|
|
699
|
+
// reload that races the cleanup still finds a live bundle.
|
|
700
|
+
server.registerBundle(COMPONENT_BUNDLE_ROUTE, compiled.bundleFile);
|
|
701
|
+
const previousTmpDir = currentTmpDir;
|
|
702
|
+
currentTmpDir = compiled.tmpDir;
|
|
703
|
+
if (previousTmpDir) {
|
|
704
|
+
await fs.rm(previousTmpDir, { recursive: true, force: true }).catch(() => {});
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
await browser.goto(`${server.origin}${COMPONENT_HARNESS_PATH}`, { waitUntil: 'load' });
|
|
708
|
+
|
|
709
|
+
const beforeEntries = await loadScriptFiles(argv.before);
|
|
710
|
+
if (beforeEntries.length > 0) {
|
|
711
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, beforeEntries));
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
await browser.evaluate(
|
|
715
|
+
() =>
|
|
716
|
+
new Promise((resolve) => {
|
|
717
|
+
requestAnimationFrame(() => requestAnimationFrame(resolve));
|
|
718
|
+
}),
|
|
719
|
+
);
|
|
720
|
+
|
|
721
|
+
const afterEntries = await loadScriptFiles(argv.after);
|
|
722
|
+
if (afterEntries.length > 0) {
|
|
723
|
+
await browser.withPageErrorTrap(() => injectScriptTags(browser, afterEntries));
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
try {
|
|
728
|
+
await runOnce();
|
|
729
|
+
} catch (err) {
|
|
730
|
+
output.error(err.message);
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const gate = makeRerunGate(async (changedPath) => {
|
|
734
|
+
output.info(rerunBanner(new Date(), changedPath));
|
|
735
|
+
await runOnce();
|
|
736
|
+
}, output);
|
|
737
|
+
// Wait for the watcher's initial census before announcing the watch, so
|
|
738
|
+
// the "Watching..." banner truthfully means "the next change will be
|
|
739
|
+
// picked up" — see the eval-watch path for the polling rationale.
|
|
740
|
+
watcher = watchPaths({ paths: directory, onChange: gate });
|
|
741
|
+
await watcher.ready;
|
|
742
|
+
|
|
743
|
+
output.info(
|
|
744
|
+
`Watching ${directory} (${argv.browser}, key="${argv.key}") — press Ctrl+C to exit`,
|
|
745
|
+
);
|
|
746
|
+
|
|
747
|
+
await Promise.race([signals.promise, browser.waitForDisconnect()]);
|
|
748
|
+
return 0;
|
|
749
|
+
} catch (err) {
|
|
750
|
+
output.fail(err);
|
|
751
|
+
return 1;
|
|
752
|
+
} finally {
|
|
753
|
+
await awaitAndEmitUpgradeNotice({
|
|
754
|
+
promise: versionCheckPromise,
|
|
755
|
+
packageJson: PACKAGE_JSON,
|
|
756
|
+
output,
|
|
757
|
+
});
|
|
758
|
+
signals.detach();
|
|
759
|
+
if (watcher) {
|
|
760
|
+
await watcher.close();
|
|
761
|
+
}
|
|
762
|
+
if (browser) {
|
|
763
|
+
await browser.close();
|
|
764
|
+
}
|
|
765
|
+
if (server) {
|
|
766
|
+
await server.stop();
|
|
767
|
+
}
|
|
768
|
+
if (currentTmpDir) {
|
|
769
|
+
await fs.rm(currentTmpDir, { recursive: true, force: true }).catch(() => {});
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|