@locker/cli 0.28.3 → 0.28.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,267 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ // Config-file discovery, loading, validation, and the four-layer cascade
6
+ // resolution for the `lws` CLI. The shape mirrors the existing loader
7
+ // conventions in endowments.mjs and input-resolver.mjs: CWD-relative
8
+ // resolution, pathToFileURL + dynamic import (so both ESM `export default`
9
+ // and CJS `module.exports` work through one code path), and clear throws
10
+ // that name the absolute source path on bad input.
11
+ //
12
+ // A config file records a project's preferred CLI settings so they do not
13
+ // have to be retyped on every invocation. Keys are the camelCase forms of
14
+ // the CLI flags (jest convention): `lwcModules`, not `lwc-modules`. The
15
+ // wiring in bin/lws.mjs maps each config key to the corresponding yargs
16
+ // option default, so yargs' native "explicit flag beats default"
17
+ // precedence makes inline CLI args win over config for free.
18
+
19
+ // Candidate filenames probed in each directory during the discovery
20
+ // walk, in priority order. The first that exists in a directory wins.
21
+ // Covering all three extensions means a project can author the config as
22
+ // ESM (.mjs), CJS (.cjs), or let the extension follow the nearest
23
+ // package.json "type" (.js). Node's dynamic import resolves the module
24
+ // system per file, so the loader does not branch on the extension. The
25
+ // name carries "AUTO_DETECTED" to distinguish these from an explicit
26
+ // --config <path>, which is never auto-detected.
27
+ const AUTO_DETECTED_CONFIG_FILENAMES = ['lws.config.js', 'lws.config.mjs', 'lws.config.cjs'];
28
+
29
+ // Marks the project root for the upward discovery walk. Discovery stops
30
+ // at the nearest ancestor that contains this file (inclusive), so a run
31
+ // from a subdirectory inherits the project's config but the walk never
32
+ // escapes into a parent workspace or $HOME.
33
+ const PACKAGE_JSON = 'package.json';
34
+
35
+ // The `config` flag itself is never config-settable: a config file
36
+ // cannot point at another config file. Rejected explicitly so the error
37
+ // is precise rather than folding into the generic unknown-key message.
38
+ const CONFIG_KEY = 'config';
39
+
40
+ // Single source of truth for every config-settable CLI option, mapped to
41
+ // the builtin default value yargs falls back to when neither a config
42
+ // file nor an inline flag supplies one. Keys are camelCase (jest
43
+ // convention): `lwcModules`, which bin/lws.mjs maps to the `lwc-modules`
44
+ // option. A value of `undefined` marks an option with no builtin default
45
+ // (the flag is simply absent unless set), e.g. `timeout`, `name`.
46
+ //
47
+ // INVARIANT: array-typed options default to `[]`, never `undefined`.
48
+ // `before`, `after`, `lwcModules`, `gatesOn`, and `gatesOff` are
49
+ // `array: true` yargs options. Feeding `default: undefined` to an
50
+ // `array: true` option does NOT leave it absent: yargs wraps the scalar
51
+ // default in an array and yields `[null]`, which then flows into the
52
+ // consumer (loadScriptFiles -> resolveInput(null), or parseGateList) and
53
+ // crashes on `null.includes`/`null.split`. `default: []` is the only
54
+ // correct builtin for an array option (absent flag -> `[]`, present flag
55
+ // -> the values). Keep every array option's value here an array.
56
+ //
57
+ // This table is the join point between the two files: bin/lws.mjs sources
58
+ // each yargs `default:` from it (config.X ?? BUILTIN_DEFAULTS.X), and the
59
+ // validation allowlist below is derived from its keys. Because both the
60
+ // defaults and the allowlist come from this one object, they cannot
61
+ // drift: adding an option here makes it both defaultable and settable in
62
+ // a single edit. The positionals (`code-or-file`, `directory`) and the
63
+ // built-in `--help` / `--version` flags are intentionally absent:
64
+ // positionals are per-run inputs, not settings, and the built-ins are not
65
+ // behaviors to persist. The object is frozen so its keys cannot be
66
+ // reassigned; the array values (`before`, `after`, `lwcModules`,
67
+ // `gatesOn`, `gatesOff`) are shared references treated as read-only by
68
+ // every consumer (yargs hands the same array back for the no-flag case,
69
+ // and loadScriptFiles / compileComponent / resolveGates only read it,
70
+ // never push into it).
71
+ export const BUILTIN_DEFAULTS = Object.freeze({
72
+ after: [],
73
+ before: [],
74
+ browser: 'chromium',
75
+ endowments: undefined,
76
+ gatesOff: [],
77
+ gatesOn: [],
78
+ headed: false,
79
+ json: false,
80
+ key: 'cli',
81
+ lwcModules: [],
82
+ name: undefined,
83
+ namespace: 'c',
84
+ port: 0,
85
+ quiet: false,
86
+ timeout: undefined,
87
+ verbose: false,
88
+ watch: false,
89
+ });
90
+
91
+ // The typo guard: a config key outside this set (e.g. `broswer`) is
92
+ // rejected with a message naming the offending key and the source file.
93
+ // Derived from BUILTIN_DEFAULTS so the allowlist and the defaults can
94
+ // never disagree.
95
+ const SETTABLE_KEYS = new Set(Object.keys(BUILTIN_DEFAULTS));
96
+
97
+ async function fileExists(p) {
98
+ try {
99
+ const stat = await fs.stat(p);
100
+ return stat.isFile();
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ function isPlainObject(value) {
107
+ if (value === null || typeof value !== 'object') {
108
+ return false;
109
+ }
110
+ if (Array.isArray(value)) {
111
+ return false;
112
+ }
113
+ const proto = Object.getPrototypeOf(value);
114
+ return proto === null || proto === Object.prototype;
115
+ }
116
+
117
+ // Walk up from `cwd` looking for a config file. In each directory the
118
+ // first existing candidate from AUTO_DETECTED_CONFIG_FILENAMES wins. The
119
+ // walk stops at the project root (the nearest ancestor containing a
120
+ // package.json, inclusive) or the filesystem root, whichever comes
121
+ // first. Returns the absolute path of the discovered file, or null if
122
+ // none is found.
123
+ //
124
+ // Discovery is jest/eslint-style: running `lws` from a nested directory
125
+ // inherits the project's top-level config. `--config` is unaffected by
126
+ // this walk; it always resolves against process.cwd() (see resolveConfig).
127
+ export async function discoverConfigPath(cwd = process.cwd()) {
128
+ let current = path.resolve(cwd);
129
+
130
+ // The loop is bounded by the filesystem: each iteration either returns
131
+ // or moves strictly closer to the filesystem root, where dirname is a
132
+ // fixed point.
133
+ for (;;) {
134
+ for (const filename of AUTO_DETECTED_CONFIG_FILENAMES) {
135
+ const candidate = path.join(current, filename);
136
+ // Sequential by design: the first existing candidate in a
137
+ // directory wins, so probing must stop at it rather than
138
+ // racing all three filenames in parallel.
139
+ // eslint-disable-next-line no-await-in-loop
140
+ if (await fileExists(candidate)) {
141
+ return candidate;
142
+ }
143
+ }
144
+
145
+ // Reaching a package.json-bearing directory ends the walk: the
146
+ // configs in this directory were just probed (inclusive stop), and
147
+ // the walk must not climb past the project boundary. Sequential by
148
+ // design: a parent is only inspected when the current directory
149
+ // yields neither a config nor a package.json, so the climb cannot
150
+ // be parallelized without reading past the project boundary.
151
+ // eslint-disable-next-line no-await-in-loop
152
+ if (await fileExists(path.join(current, PACKAGE_JSON))) {
153
+ return null;
154
+ }
155
+
156
+ const parent = path.dirname(current);
157
+ if (parent === current) {
158
+ return null;
159
+ }
160
+ current = parent;
161
+ }
162
+ }
163
+
164
+ // Dynamic-import a config file by absolute path and return its exported
165
+ // object. Prefers `mod.default` (ESM `export default ...` or, via Node's
166
+ // interop, CJS `module.exports = ...`) and falls back to the module
167
+ // namespace only when no default was declared. Throws a clear, path-
168
+ // bearing error when the file is missing or does not export an object.
169
+ export async function loadConfigFile(absPath) {
170
+ if (!(await fileExists(absPath))) {
171
+ throw new Error(`config file not found: ${absPath}`);
172
+ }
173
+
174
+ // Import via file:// URL: avoids require-cache pollution and works for
175
+ // both ESM and CJS, exactly as loadEndowments does.
176
+ const url = pathToFileURL(absPath).href;
177
+ const mod = await import(url);
178
+ const hasDefault = Object.hasOwn(mod, 'default');
179
+ const value = hasDefault ? mod.default : mod;
180
+
181
+ if (!isPlainObject(value)) {
182
+ const described = value === null ? 'null' : typeof value;
183
+ throw new TypeError(
184
+ `config file must export an object (export default { ... } or module.exports = { ... }), got ${described}: ${absPath}`,
185
+ );
186
+ }
187
+
188
+ return value;
189
+ }
190
+
191
+ // Reject any key the CLI cannot map to an option, plus the `config` key
192
+ // itself. `sourcePath` is woven into every message so the user knows
193
+ // which file to fix. Returns the same object on success for convenience.
194
+ export function validateConfig(obj, sourcePath) {
195
+ if (!isPlainObject(obj)) {
196
+ const described = obj === null ? 'null' : typeof obj;
197
+ throw new TypeError(`config must be an object, got ${described}: ${sourcePath}`);
198
+ }
199
+
200
+ for (const key of Object.keys(obj)) {
201
+ if (key === CONFIG_KEY) {
202
+ throw new Error(
203
+ `config file may not set "config" (a config file cannot point at another config): ${sourcePath}`,
204
+ );
205
+ }
206
+ if (!SETTABLE_KEYS.has(key)) {
207
+ throw new Error(
208
+ `unknown config key "${key}" in ${sourcePath}. Config keys are camelCase CLI options (e.g. browser, headed, key, lwcModules)`,
209
+ );
210
+ }
211
+ }
212
+
213
+ return obj;
214
+ }
215
+
216
+ // Deep-merge `overlay` onto `base`, returning a new object. Nested plain
217
+ // objects merge recursively; every other value type (arrays, primitives,
218
+ // functions) replaces wholesale. Array-replace (not concat) keeps an
219
+ // explicit --config's `before: [...]` winning over discovery's the same
220
+ // way an inline CLI array flag replaces a default array.
221
+ function deepMerge(base, overlay) {
222
+ const result = { ...base };
223
+ for (const key of Object.keys(overlay)) {
224
+ const overlayValue = overlay[key];
225
+ const baseValue = result[key];
226
+ if (isPlainObject(baseValue) && isPlainObject(overlayValue)) {
227
+ result[key] = deepMerge(baseValue, overlayValue);
228
+ } else {
229
+ result[key] = overlayValue;
230
+ }
231
+ }
232
+ return result;
233
+ }
234
+
235
+ // Resolve the effective config object by running the cascade:
236
+ //
237
+ // 1. auto-discovered config (upward walk from cwd), if any
238
+ // 2. explicit --config file (resolved against cwd), if given
239
+ //
240
+ // The explicit file is deep-merged OVER the discovered base, so a CI
241
+ // config can specify only the deltas and inherit everything else. Each
242
+ // file is validated against its own source path so a typo points at the
243
+ // right file. Returns the merged object, or {} when neither file exists.
244
+ //
245
+ // The builtin-defaults layer (layer 1 of the four) and the inline-CLI
246
+ // layer (layer 4) live in bin/lws.mjs: builtins are each option's
247
+ // fallback when the config key is absent, and inline flags win via
248
+ // yargs' native explicit-over-default precedence.
249
+ export async function resolveConfig({ cwd = process.cwd(), explicitPath } = {}) {
250
+ let merged = {};
251
+
252
+ const discoveredPath = await discoverConfigPath(cwd);
253
+ if (discoveredPath !== null) {
254
+ const discovered = await loadConfigFile(discoveredPath);
255
+ validateConfig(discovered, discoveredPath);
256
+ merged = discovered;
257
+ }
258
+
259
+ if (explicitPath !== undefined && explicitPath !== null && explicitPath !== '') {
260
+ const explicitAbsolute = path.resolve(cwd, explicitPath);
261
+ const explicit = await loadConfigFile(explicitAbsolute);
262
+ validateConfig(explicit, explicitAbsolute);
263
+ merged = deepMerge(merged, explicit);
264
+ }
265
+
266
+ return merged;
267
+ }
package/src/gates.mjs ADDED
@@ -0,0 +1,132 @@
1
+ // Feature-gate resolution for a single `lws` run.
2
+ //
3
+ // LWS distortions and behavior changes are gated behind
4
+ // `isGaterEnabledFeature('changesSince.NNN')` (and similarly named
5
+ // feature flags). The gate state is a module-level Set inside the LWS
6
+ // runtime, seeded by `registerGaterEnabledFeatures(string[])`. The CLI's
7
+ // IIFE entry (src/sandbox-entry.ts) reads the resolved list off a window
8
+ // slot at runtime-init and registers it, so the Set is settled before the
9
+ // first `evaluateInSandbox` call builds a SandboxRecord (the moment the
10
+ // gate reads are frozen for a key).
11
+ //
12
+ // This module owns the Node-side resolution: it computes the effective
13
+ // gate list from the canonical baseline plus the user's `--gates-on` /
14
+ // `--gates-off` flags, and emits the window-slot assignment script. The
15
+ // baseline is NOT defined here: it is imported from @locker/shared, the
16
+ // one place karma and the CLI both read it from, so there is no second
17
+ // copy that could drift. sandbox-entry.ts likewise holds no copy (it
18
+ // registers only what the window slot carries).
19
+ import { LWS_DEFAULT_GATER_FEATURES } from '@locker/shared';
20
+
21
+ // The fully-qualified gate-name prefix used by the LWS gater. Mirrors
22
+ // FEATURE_NAME_PREFIX in @locker/shared's GaterFeatures: both the
23
+ // registrar and `isGaterEnabledFeature` prepend it when a name arrives
24
+ // without it, so a short name (`changesSince.264`) and its full form
25
+ // (`com.salesforce.locker.changesSince.264`) address the same gate. We
26
+ // normalize to the full form here so set operations (dedup, off-by-name
27
+ // subtraction) compare apples to apples regardless of how the user typed
28
+ // the flag value.
29
+ const FEATURE_NAME_PREFIX = 'com.salesforce.locker.';
30
+
31
+ // The window slot the runner sets (via addInitScript, before navigation)
32
+ // and sandbox-entry.ts reads (at IIFE-init, before any evaluateInSandbox).
33
+ // The double-underscore prefix matches the sibling window.__lwsCLIEndowments
34
+ // slot: these are CLI-namespaced page globals, not local identifiers.
35
+ export const GATES_WINDOW_SLOT = '__lwsCLIGates';
36
+
37
+ // The CLI's default gate set is the canonical LWS baseline exported by
38
+ // @locker/shared, the same value karma registers in
39
+ // packages/integration-karma/lib/evaluator.js. Running `lws` with no gate
40
+ // flags reproduces what the test harness (and therefore CI) runs under, so
41
+ // the CLI is a faithful triage harness out of the box. `--gates-on` adds
42
+ // to this baseline; `--gates-off` removes from it. We re-export it under
43
+ // the CLI's own name (the CLI adopts the shared baseline; the alias keeps
44
+ // the rest of this module and its callers reading `DEFAULT_GATES`). It is
45
+ // already frozen by @locker/shared.
46
+ export const DEFAULT_GATES = LWS_DEFAULT_GATER_FEATURES;
47
+
48
+ // Normalize a gate name to its fully-qualified form. Idempotent: a name
49
+ // that already carries the prefix is returned unchanged, exactly as
50
+ // @locker/shared's fullName does.
51
+ function fullName(name) {
52
+ return name.startsWith(FEATURE_NAME_PREFIX) ? name : `${FEATURE_NAME_PREFIX}${name}`;
53
+ }
54
+
55
+ // The inverse of fullName: strip the fully-qualified prefix back to the
56
+ // short name engineers actually use and speak (`changesSince.264`, not
57
+ // `com.salesforce.locker.changesSince.264`). Idempotent on names that are
58
+ // already short. We resolve and store gates fully-qualified internally so
59
+ // set operations compare apples to apples, but every place a gate name is
60
+ // shown to a human or handed to a JSON consumer uses the short form.
61
+ function shortName(name) {
62
+ return name.startsWith(FEATURE_NAME_PREFIX) ? name.slice(FEATURE_NAME_PREFIX.length) : name;
63
+ }
64
+
65
+ // Map a resolved (fully-qualified) gate list to the short-name form for
66
+ // display and the --json envelope. The order of the input is preserved.
67
+ export function toShortGateNames(gates) {
68
+ return gates.map(shortName);
69
+ }
70
+
71
+ // Parse a gate-list flag value into an array of normalized full names.
72
+ // The flag is `array: true` (repeatable), so the common input is an array
73
+ // of strings, one per `--gates-on` occurrence; each entry may itself be a
74
+ // comma-separated list, so `--gates-on a,b` and `--gates-on a --gates-on b`
75
+ // resolve identically. A lone string (a config-file `gatesOn: 'a,b'`, or a
76
+ // direct call) is accepted too, and a null/undefined value yields an empty
77
+ // array (the flag was absent). Within every entry, whitespace around each
78
+ // name is trimmed and empty segments are dropped, so `"a, ,b,"` yields two
79
+ // gates and an array carrying a stray null/'' (e.g. yargs' `[null]` default
80
+ // trap) contributes nothing.
81
+ export function parseGateList(value) {
82
+ if (value === undefined || value === null) {
83
+ return [];
84
+ }
85
+ const entries = Array.isArray(value) ? value : [value];
86
+ const names = [];
87
+ for (const entry of entries) {
88
+ if (entry === undefined || entry === null) {
89
+ continue;
90
+ }
91
+ if (typeof entry !== 'string') {
92
+ throw new TypeError(`gate list expects strings, got ${typeof entry}`);
93
+ }
94
+ for (const name of entry.split(',')) {
95
+ const trimmed = name.trim();
96
+ if (trimmed !== '') {
97
+ names.push(fullName(trimmed));
98
+ }
99
+ }
100
+ }
101
+ return names;
102
+ }
103
+
104
+ // Resolve the effective gate list for a run from the karma baseline and
105
+ // the two flag values. Order is load-bearing: defaults first, then the
106
+ // `--gates-on` additions, then the `--gates-off` removals LAST, so a gate
107
+ // named in both flags ends up OFF (off wins). The result is deduped and
108
+ // returned as an array of full names, ready to hand to
109
+ // registerGaterEnabledFeatures inside the page.
110
+ export function resolveGates({ on, off } = {}) {
111
+ const enabled = new Set(DEFAULT_GATES);
112
+ for (const gate of parseGateList(on)) {
113
+ enabled.add(gate);
114
+ }
115
+ for (const gate of parseGateList(off)) {
116
+ enabled.delete(gate);
117
+ }
118
+ return [...enabled];
119
+ }
120
+
121
+ // Build the system-mode <script> source that publishes the resolved gate
122
+ // list on the window slot. The runner injects this via addInitScript
123
+ // BEFORE navigating, so the slot exists when the LWS IIFE's entry reads it
124
+ // at init (before any sandbox is created). The list is embedded as a JSON
125
+ // literal: gate names are plain strings, so JSON.stringify round-trips
126
+ // them safely into the page.
127
+ export function buildGateInitScript(gates) {
128
+ if (!Array.isArray(gates)) {
129
+ throw new TypeError(`gates must be an array, got ${typeof gates}`);
130
+ }
131
+ return `window[${JSON.stringify(GATES_WINDOW_SLOT)}] = ${JSON.stringify(gates)};`;
132
+ }
package/src/output.mjs CHANGED
@@ -70,6 +70,11 @@ export class Output {
70
70
  // the run's outcome is known. Carried additively on the envelope; a
71
71
  // null completion means none was produced (harness/infra failure).
72
72
  this.completion = null;
73
+ // The resolved LWS feature-gate set for this run (short names, the
74
+ // form engineers use), set by the runner once gates are resolved.
75
+ // Carried additively on the envelope so a --json consumer can see
76
+ // which gates were active. null means the runner never recorded one.
77
+ this.gates = null;
73
78
  }
74
79
 
75
80
  info(message) {
@@ -114,6 +119,14 @@ export class Output {
114
119
  this.completion = completion;
115
120
  }
116
121
 
122
+ // Record the resolved feature-gate set (short names) for this run. Set
123
+ // by the runner right after gate resolution; carried additively on the
124
+ // JSON envelope. No-op effect in text mode beyond storage (the runner
125
+ // logs the --verbose `gates:` line itself).
126
+ setGates(gates) {
127
+ this.gates = gates;
128
+ }
129
+
117
130
  fail(error) {
118
131
  if (this.json) {
119
132
  // Replace any pending success envelope: a downstream throw
@@ -162,6 +175,12 @@ export class Output {
162
175
  if (this.completion !== null) {
163
176
  envelope.completion = this.completion;
164
177
  }
178
+ // The resolved gate set is additive too: a short-name array present
179
+ // on both ok and fail envelopes when the runner recorded one. Lets a
180
+ // --json consumer see exactly which feature gates the run honored.
181
+ if (this.gates !== null) {
182
+ envelope.gates = this.gates;
183
+ }
165
184
  this.pendingEnvelope = null;
166
185
  this.stdout.write(`${JSON.stringify(envelope)}\n`);
167
186
  }
@@ -0,0 +1,65 @@
1
+ import { createRequire } from 'node:module';
2
+
3
+ // This module is deliberately Playwright-free: it must load and run when
4
+ // `playwright` is ABSENT, which is the exact condition it exists to
5
+ // report. It uses only Node's module resolver (no import of playwright,
6
+ // no browser launch, no I/O beyond the resolver's filesystem lookup), so
7
+ // importing it never drags the playwright package into the graph.
8
+ //
9
+ // Why a dedicated preflight at all: bin/lws.mjs lazily imports the
10
+ // browser-launching command modules (runner.mjs, repl.mjs), each of which
11
+ // statically imports `playwright`. Loading one of those modules when the
12
+ // package is missing throws a raw `ERR_MODULE_NOT_FOUND: playwright` with
13
+ // a Node stack trace, before any of our code runs. Resolving the package
14
+ // first lets the CLI print actionable guidance and exit cleanly instead.
15
+
16
+ const require = createRequire(import.meta.url);
17
+
18
+ const PLAYWRIGHT_MODULE = 'playwright';
19
+
20
+ // Multi-line, copy-pasteable guidance. `playwright` is a declared
21
+ // dependency, so a plain install restores the package; the binaries
22
+ // Playwright drives are a separate download (`npx playwright install`),
23
+ // so both steps are spelled out for a from-scratch setup. A missing
24
+ // browser binary (package present, binaries not downloaded) is NOT this
25
+ // case: Playwright itself prints an actionable "run npx playwright
26
+ // install" message at launch time, so the preflight stays focused on the
27
+ // package-absent case that would otherwise crash with a raw stack trace.
28
+ export const PLAYWRIGHT_INSTALL_GUIDANCE = [
29
+ 'Playwright is not installed, but the lws CLI needs it to launch a browser and run code inside the LWS sandbox.',
30
+ '',
31
+ 'Install the dependency from your project root:',
32
+ ' npm install (or: yarn install)',
33
+ '',
34
+ 'Then download the browser binaries Playwright drives:',
35
+ ' npx playwright install',
36
+ ].join('\n');
37
+
38
+ // True iff `moduleName` can be resolved from this module. Pure
39
+ // resolution: it does not execute the module, so a resolvable-but-broken
40
+ // package still reports true (a load error would surface later, at the
41
+ // dynamic import). Exported for unit testing against a known-present
42
+ // package (e.g. 'yargs') and a known-absent one.
43
+ export function isModuleInstalled(moduleName) {
44
+ try {
45
+ require.resolve(moduleName);
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+
52
+ export function isPlaywrightInstalled() {
53
+ return isModuleInstalled(PLAYWRIGHT_MODULE);
54
+ }
55
+
56
+ // Throw a friendly, actionable error when Playwright is absent; return
57
+ // (void) when present. The thrown message is the full guidance block, so
58
+ // the caller can write `err.message` straight to stderr. `check` is
59
+ // injectable purely so the absent-path can be unit-tested without
60
+ // uninstalling the package.
61
+ export function assertPlaywrightInstalled({ check = isPlaywrightInstalled } = {}) {
62
+ if (!check()) {
63
+ throw new Error(PLAYWRIGHT_INSTALL_GUIDANCE);
64
+ }
65
+ }
package/src/repl.mjs CHANGED
@@ -7,6 +7,7 @@ import * as acorn from 'acorn';
7
7
  import { injectScriptTags, loadScriptFiles } from './before-after.mjs';
8
8
  import { Browser } from './browser.mjs';
9
9
  import { buildEndowmentsReplAssignments, loadEndowments } from './endowments.mjs';
10
+ import { buildGateInitScript, resolveGates, toShortGateNames } from './gates.mjs';
10
11
  import { Output } from './output.mjs';
11
12
  import { Server } from './server.mjs';
12
13
  import { awaitAndEmitUpgradeNotice, startVersionCheckForCLI } from './version-check.mjs';
@@ -297,6 +298,20 @@ export async function runRepl(argv) {
297
298
  await browser.launch();
298
299
  output.timing.end('browser-launch');
299
300
 
301
+ // Gate init is queued before the goto: addInitScript runs ahead of the
302
+ // harness's lws-sandbox.js, so sandbox-entry.ts reads the resolved gate
303
+ // list off the window slot at IIFE init, before any per-key
304
+ // SandboxRecord (which freezes the gate reads) is built. The set is
305
+ // session-wide: one registration covers every subsequent REPL line.
306
+ const gates = resolveGates({ on: argv.gatesOn, off: argv.gatesOff });
307
+ await browser.addInitScript({ content: buildGateInitScript(gates) });
308
+ // Short names (changesSince.264), the form engineers use, for both
309
+ // the --verbose line and the recorded gate set; the resolved full
310
+ // names went into the init script above.
311
+ const shortNames = toShortGateNames(gates);
312
+ output.setGates(shortNames);
313
+ output.debug(`gates: ${shortNames.join(', ') || '(none)'}`);
314
+
300
315
  await browser.goto(`${server.origin}${EVAL_HARNESS_PATH}`, { waitUntil: 'load' });
301
316
  await browser.evaluate(() => {
302
317
  if (typeof window.evaluateInSandbox !== 'function') {
package/src/runner.mjs CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  throwCompletion,
15
15
  } from './completion.mjs';
16
16
  import { buildEndowmentsRegisterScript, loadEndowments } from './endowments.mjs';
17
+ import { buildGateInitScript, resolveGates, toShortGateNames } from './gates.mjs';
17
18
  import { resolveInput } from './input-resolver.mjs';
18
19
  import { Output } from './output.mjs';
19
20
  import { Server } from './server.mjs';
@@ -94,6 +95,29 @@ async function resolveCompletion(browser, output) {
94
95
  return exitCodeFor(completion);
95
96
  }
96
97
 
98
+ // Queue the feature-gate init script on the browser BEFORE it navigates to
99
+ // a harness page. The script publishes the resolved gate list (karma
100
+ // defaults + --gates-on, minus --gates-off) on the window slot that
101
+ // sandbox-entry.ts reads at IIFE init, so the gater Set is settled before
102
+ // the first evaluateInSandbox builds a SandboxRecord. addInitScript (not
103
+ // addScriptTag) is mandatory: it runs before every page script, including
104
+ // component.html's `<script src="/_bundle/component.js">`, whose
105
+ // evaluateInSandbox call would otherwise freeze the gate reads before any
106
+ // appended <script> could register them. Also records the resolved set on
107
+ // `output` two ways: the --verbose `gates:` stderr line and the additive
108
+ // `gates` field of the --json envelope, both in the short-name form
109
+ // engineers use (`changesSince.264`, not the fully-qualified internal
110
+ // name). Returns the resolved (fully-qualified) list. MUST be called
111
+ // before browser.goto.
112
+ async function injectGates(browser, argv, output) {
113
+ const gates = resolveGates({ on: argv.gatesOn, off: argv.gatesOff });
114
+ await browser.addInitScript({ content: buildGateInitScript(gates) });
115
+ const shortNames = toShortGateNames(gates);
116
+ output.setGates(shortNames);
117
+ output.debug(`gates: ${shortNames.join(', ') || '(none)'}`);
118
+ return gates;
119
+ }
120
+
97
121
  export async function runEval(argv) {
98
122
  // Watch mode owns a persistent browser/server lifecycle (launch once,
99
123
  // re-evaluate on change), which is the inverse of the one-shot path's
@@ -151,6 +175,10 @@ export async function runEval(argv) {
151
175
  await browser.launch();
152
176
  output.timing.end('browser-launch');
153
177
 
178
+ // Gate init runs before navigation so sandbox-entry.ts registers
179
+ // the resolved gates at IIFE init, before any evaluateInSandbox.
180
+ await injectGates(browser, argv, output);
181
+
154
182
  await browser.goto(`${server.origin}${EVAL_HARNESS_PATH}`, { waitUntil: 'load' });
155
183
  // The harness already loaded purify.js + lws-sandbox.js (assigning
156
184
  // window.evaluateInSandbox). Verify before injecting user code.
@@ -362,6 +390,13 @@ export async function runComponent(argv) {
362
390
  await browser.launch();
363
391
  output.timing.end('browser-launch');
364
392
 
393
+ // Gate init, like endowments below, must be queued via
394
+ // addInitScript before goto: the component bundle's
395
+ // evaluateInSandbox runs synchronously during navigation, so the
396
+ // gater Set has to be settled before then. Gates are queued first
397
+ // so the slot exists when sandbox-entry.ts reads it at IIFE init.
398
+ await injectGates(browser, argv, output);
399
+
365
400
  // Endowments registration must happen BEFORE `browser.goto`
366
401
  // because the harness page loads the component bundle via
367
402
  // `<script src="/_bundle/component.js">` synchronously during
@@ -543,6 +578,11 @@ async function runEvalWatch(argv) {
543
578
  });
544
579
  await browser.launch();
545
580
 
581
+ // Gate init is queued ONCE here: addInitScript persists across
582
+ // navigations, and the resolved gate set is fixed for the session,
583
+ // so it applies to every cycle's fresh `goto` below.
584
+ await injectGates(browser, argv, output);
585
+
546
586
  // One re-evaluation cycle: re-read the file (it may have changed),
547
587
  // re-transform, navigate to a fresh harness page, replay
548
588
  // endowments/before, inject the transformed bundle, run after. A fresh
@@ -671,6 +711,12 @@ async function runComponentWatch(argv) {
671
711
  });
672
712
  await browser.launch();
673
713
 
714
+ // Gate init is queued ONCE here, before the endowments script and the
715
+ // first goto: addInitScript persists across reloads and the resolved
716
+ // gate set is fixed for the session, so it applies to every re-compile
717
+ // cycle's navigation below.
718
+ await injectGates(browser, argv, output);
719
+
674
720
  // Endowments register via addInitScript, which applies to every
675
721
  // subsequent navigation, so register once before the first goto rather
676
722
  // than on each re-run. Component-directory changes (the watch target)
@@ -1,7 +1,32 @@
1
1
  import { evaluateInSandbox } from '@locker/sandbox';
2
+ import { registerGaterEnabledFeatures } from '@locker/shared';
2
3
 
3
4
  // Expose evaluateInSandbox on the window global so the browser harness page
4
5
  // (eval.html / component.html) can invoke it against source delivered by the
5
6
  // CLI's local server. This is the minimal, non-Aura entry point for the LWS
6
7
  // sandbox IIFE consumed by @locker/cli.
7
8
  (window as any).evaluateInSandbox = evaluateInSandbox;
9
+
10
+ // Feature-gate registration for a run. The runner resolves the effective
11
+ // gate list on the Node side (gates.mjs: the @locker/shared baseline
12
+ // LWS_DEFAULT_GATER_FEATURES, plus --gates-on, minus --gates-off) and
13
+ // publishes it on this window slot via addInitScript BEFORE the page
14
+ // navigates. Reading and registering it
15
+ // HERE, at IIFE init, is what makes the gates honored: this entry shares
16
+ // the bundled @locker/shared module graph with @locker/sandbox, so
17
+ // registerGaterEnabledFeatures writes into the very same gater Set that
18
+ // the sandbox's internal isGaterEnabledFeature reads. Because the slot is
19
+ // set before navigation and this code runs before any evaluateInSandbox
20
+ // call, the Set is settled before the first SandboxRecord (which freezes
21
+ // the gate reads for a key) is built.
22
+ //
23
+ // The slot name string is the wire contract with gates.mjs GATES_WINDOW_SLOT;
24
+ // the two live in different bundles (this IIFE vs. the Node runner) and
25
+ // cannot import a shared constant, so the literal is duplicated by design.
26
+ // Bracket (string-key) access, not dot access: the slot name is a wire-
27
+ // protocol key, and the bracket form keeps it out of no-underscore-dangle's
28
+ // identifier check, matching how the sibling endowments slot is referenced.
29
+ const gates = (window as any)['__lwsCLIGates'];
30
+ if (Array.isArray(gates)) {
31
+ registerGaterEnabledFeatures(gates);
32
+ }