@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.
@@ -0,0 +1,7 @@
1
+ import { evaluateInSandbox } from '@locker/sandbox';
2
+
3
+ // Expose evaluateInSandbox on the window global so the browser harness page
4
+ // (eval.html / component.html) can invoke it against source delivered by the
5
+ // CLI's local server. This is the minimal, non-Aura entry point for the LWS
6
+ // sandbox IIFE consumed by @locker/cli.
7
+ (window as any).evaluateInSandbox = evaluateInSandbox;
package/src/server.mjs ADDED
@@ -0,0 +1,256 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import http from 'node:http';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ import { COMPLETION_GLOBAL } from './completion.mjs';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+
11
+ // Harness pages (eval.html, component.html) live in src/harness/ — the
12
+ // server's "default" namespace. Other things in src/ (runtime modules,
13
+ // rollup entry files) are not served. Anchoring the default-route root
14
+ // to src/harness/ rather than src/ keeps the URL surface tight and
15
+ // prevents accidental exposure of build-time files.
16
+ const HARNESS_DIR = path.resolve(__dirname, 'harness');
17
+
18
+ // Distinguishable rewrites: `/<file>` → `dist/<file>` for the harness's
19
+ // production-faithful URLs. The harness pages (D3) load purify.js,
20
+ // lws-sandbox.js, and lwc-engine.js as root-relative URLs. The build
21
+ // places all three under dist/ — the IIFE bundles via rollup, purify.js
22
+ // via a copy step from dompurify's published browser build. This set
23
+ // maps each harness URL to its dist/ location.
24
+ const ROOT_TO_DIST_ALIASES = new Set(['/lws-sandbox.js', '/lwc-engine.js', '/purify.js']);
25
+
26
+ const MIME_TYPES = {
27
+ '.html': 'text/html; charset=utf-8',
28
+ '.js': 'application/javascript; charset=utf-8',
29
+ '.mjs': 'application/javascript; charset=utf-8',
30
+ '.css': 'text/css; charset=utf-8',
31
+ '.json': 'application/json; charset=utf-8',
32
+ '.map': 'application/json; charset=utf-8',
33
+ };
34
+
35
+ const HTML_EXTENSIONS = new Set(['.html', '.htm']);
36
+
37
+ // Production-matching CSP. PLAN.md §"Content Security Policy" pins this
38
+ // string as the value LWS uses in production Salesforce orgs. The harness
39
+ // pages depend on this header being present (no <meta http-equiv> fallback).
40
+ // Cross-reference: packages/integration-karma/configs/base.js carries the
41
+ // same string for karma's customHeaders. The unit test drift-checks against
42
+ // it so divergence fails CI rather than skewing silently.
43
+ export const PRODUCTION_CSP =
44
+ "default-src 'self'; " +
45
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; " +
46
+ "object-src 'self'; " +
47
+ "style-src 'self' blob: 'unsafe-inline'; " +
48
+ "img-src 'self' http: https: data: blob:; " +
49
+ "media-src 'self' blob:; " +
50
+ "frame-ancestors 'self'; " +
51
+ "frame-src 'self' blob: https:; " +
52
+ "font-src 'self' https: data:; " +
53
+ "connect-src 'self' blob:; " +
54
+ "base-uri 'self'";
55
+
56
+ const DIST_PREFIX = '/dist/';
57
+ const BUNDLE_PREFIX = '/_bundle/';
58
+
59
+ // Runtime wrapper served before the user's bundle. Installs
60
+ // `window.evaluateInSandboxForCLI` and reads `window.__lwsCLIEndowments`
61
+ // at install time. Externalized from the user bundle so the user's IIFE
62
+ // only carries a call site, not the wrapper definition.
63
+ //
64
+ // It also installs a single `window` error listener that captures the first
65
+ // uncaught throw from sandboxed code and stashes `{ message, name }` on the
66
+ // COMPLETION_GLOBAL window property. The runner reads that property with a
67
+ // single browser.evaluate() once the run window closes. This is the only
68
+ // reliable capture path: a sandbox throw reaches the runner CSP-side as an
69
+ // opaque `Proxy(Object)` (its message is destroyed crossing the near-membrane
70
+ // boundary), but in-page the listener holds the live error and reads the
71
+ // intact message (including the "Lightning Web Security: " prefix that marks
72
+ // a LockerSecurityError). The runner arbitrates normal-vs-throw by whether
73
+ // the property is set after the run window; the in-page code stays a dumb
74
+ // reporter of "a throw happened". A window global (rather than the console
75
+ // channel) makes the read race-free: it does not depend on Playwright's
76
+ // asynchronous console-event delivery timing.
77
+ const RUNTIME_EVALUATOR_PATH = '/_runtime/evaluator.js';
78
+ const RUNTIME_EVALUATOR_BODY = `(function () {
79
+ 'use strict';
80
+ var COMPLETION_GLOBAL = ${JSON.stringify(COMPLETION_GLOBAL)};
81
+ window.addEventListener('error', function (event) {
82
+ // Record only the first uncaught error: the completion model is a
83
+ // single outcome per run, and the first throw is the one that
84
+ // halted sandboxed execution.
85
+ if (window[COMPLETION_GLOBAL]) {
86
+ return;
87
+ }
88
+ var err = event.error;
89
+ var message = '';
90
+ var name = 'Error';
91
+ try {
92
+ message = err && err.message != null ? String(err.message) : String(event.message);
93
+ } catch (e) {
94
+ message = '';
95
+ }
96
+ try {
97
+ name = err && err.name != null ? String(err.name) : 'Error';
98
+ } catch (e) {
99
+ name = 'Error';
100
+ }
101
+ window[COMPLETION_GLOBAL] = { message: message, name: name };
102
+ });
103
+ var nativeEvaluateInSandbox = window.evaluateInSandbox;
104
+ window.evaluateInSandbox = function evaluateInSandbox(key, source, context, endowments) {
105
+ var cliEndowments = window.__lwsCLIEndowments || {};
106
+ return nativeEvaluateInSandbox(key, source, context, Object.assign({}, cliEndowments, endowments == null ? {} : endowments));
107
+ };
108
+ })();
109
+ `;
110
+
111
+ function mimeFor(filename) {
112
+ return MIME_TYPES[path.extname(filename).toLowerCase()] || 'application/octet-stream';
113
+ }
114
+
115
+ function isHTML(filename) {
116
+ return HTML_EXTENSIONS.has(path.extname(filename).toLowerCase());
117
+ }
118
+
119
+ function send(res, status, body, headers = {}) {
120
+ res.writeHead(status, headers);
121
+ res.end(body);
122
+ }
123
+
124
+ async function readSafe(filePath) {
125
+ try {
126
+ return await fs.readFile(filePath);
127
+ } catch (err) {
128
+ if (err.code === 'ENOENT') {
129
+ return null;
130
+ }
131
+ throw err;
132
+ }
133
+ }
134
+
135
+ export class Server {
136
+ constructor({ port = 0, distDir, bundles = new Map() } = {}) {
137
+ this.port = port;
138
+ this.distDir = distDir ?? path.resolve(__dirname, '..', 'dist');
139
+ this.bundles = bundles;
140
+ this.server = null;
141
+ }
142
+
143
+ registerBundle(routePath, absoluteFilePath) {
144
+ if (!routePath.startsWith(BUNDLE_PREFIX)) {
145
+ throw new Error(`bundle route must start with ${BUNDLE_PREFIX}, got: ${routePath}`);
146
+ }
147
+ this.bundles.set(routePath, absoluteFilePath);
148
+ }
149
+
150
+ async handle(req, res) {
151
+ const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
152
+ const { pathname } = url;
153
+
154
+ // Browsers (especially Chrome) auto-request /favicon.ico on every
155
+ // page load. The harness doesn't ship one; returning 204 (No Content)
156
+ // tells the browser "stop asking" via the right protocol-level signal,
157
+ // silencing the otherwise-noisy "Failed to load resource: 404" the
158
+ // page-console listener would otherwise forward to stderr.
159
+ if (pathname === '/favicon.ico') {
160
+ return send(res, 204, '');
161
+ }
162
+
163
+ if (pathname === RUNTIME_EVALUATOR_PATH) {
164
+ return send(res, 200, RUNTIME_EVALUATOR_BODY, {
165
+ 'Content-Type': MIME_TYPES['.js'],
166
+ });
167
+ }
168
+
169
+ if (this.bundles.has(pathname)) {
170
+ const file = this.bundles.get(pathname);
171
+ const body = await readSafe(file);
172
+ if (body === null) {
173
+ return send(res, 404, 'Not Found');
174
+ }
175
+ return send(res, 200, body, { 'Content-Type': mimeFor(file) });
176
+ }
177
+
178
+ if (ROOT_TO_DIST_ALIASES.has(pathname)) {
179
+ const file = path.resolve(this.distDir, pathname.slice(1));
180
+ const body = await readSafe(file);
181
+ if (body === null) {
182
+ return send(res, 404, 'Not Found');
183
+ }
184
+ return send(res, 200, body, { 'Content-Type': mimeFor(file) });
185
+ }
186
+
187
+ if (pathname.startsWith(DIST_PREFIX)) {
188
+ const rel = pathname.slice(DIST_PREFIX.length);
189
+ const file = path.resolve(this.distDir, rel);
190
+ if (!file.startsWith(this.distDir + path.sep) && file !== this.distDir) {
191
+ return send(res, 403, 'Forbidden');
192
+ }
193
+ const body = await readSafe(file);
194
+ if (body === null) {
195
+ return send(res, 404, 'Not Found');
196
+ }
197
+ return send(res, 200, body, { 'Content-Type': mimeFor(file) });
198
+ }
199
+
200
+ const rel = pathname === '/' ? 'index.html' : pathname.slice(1);
201
+ const file = path.resolve(HARNESS_DIR, rel);
202
+ if (!file.startsWith(HARNESS_DIR + path.sep) && file !== HARNESS_DIR) {
203
+ return send(res, 403, 'Forbidden');
204
+ }
205
+ const body = await readSafe(file);
206
+ if (body === null) {
207
+ return send(res, 404, 'Not Found');
208
+ }
209
+
210
+ const headers = { 'Content-Type': mimeFor(file) };
211
+ if (isHTML(file)) {
212
+ headers['Content-Security-Policy'] = PRODUCTION_CSP;
213
+ }
214
+ return send(res, 200, body, headers);
215
+ }
216
+
217
+ start() {
218
+ return new Promise((resolve, reject) => {
219
+ this.server = http.createServer((req, res) => {
220
+ this.handle(req, res).catch((err) => {
221
+ send(res, 500, `Internal Server Error: ${err.message}`);
222
+ });
223
+ });
224
+ this.server.once('error', reject);
225
+ this.server.listen(this.port, '127.0.0.1', () => {
226
+ this.server.removeListener('error', reject);
227
+ this.port = this.server.address().port;
228
+ resolve(this);
229
+ });
230
+ });
231
+ }
232
+
233
+ get origin() {
234
+ if (!this.server) {
235
+ return null;
236
+ }
237
+ return `http://127.0.0.1:${this.port}`;
238
+ }
239
+
240
+ stop() {
241
+ return new Promise((resolve, reject) => {
242
+ if (!this.server) {
243
+ resolve();
244
+ return;
245
+ }
246
+ this.server.close((err) => {
247
+ if (err) {
248
+ reject(err);
249
+ return;
250
+ }
251
+ this.server = null;
252
+ resolve();
253
+ });
254
+ });
255
+ }
256
+ }
@@ -0,0 +1,95 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ import { rollup } from 'rollup';
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const lockerRollupPlugin = require('@locker/rollup-plugin');
10
+
11
+ const VIRTUAL_ID = 'lws-cli:input';
12
+
13
+ // Rollup plugin: serve the user source as a virtual module so we don't need
14
+ // a real file on disk for inline-string inputs. The user's "filename" is
15
+ // derived from the input origin (e.g. "<inline>", "<stdin>", or a real path)
16
+ // for diagnostics and source maps.
17
+ function virtualSourcePlugin({ source, virtualPath }) {
18
+ return {
19
+ name: 'lws-cli-virtual-source',
20
+ resolveId(id) {
21
+ if (id === VIRTUAL_ID) {
22
+ return virtualPath;
23
+ }
24
+ return null;
25
+ },
26
+ load(id) {
27
+ if (id === virtualPath) {
28
+ return source;
29
+ }
30
+ return null;
31
+ },
32
+ };
33
+ }
34
+
35
+ export async function transform({ source, origin, sandboxKey = 'cli' }) {
36
+ // Use a real-looking path so @locker/compiler's source-URL machinery has
37
+ // something stable to anchor on. Origin "<inline>" / "<stdin>" become
38
+ // synthetic paths under os.tmpdir().
39
+ const isRealPath = origin && !origin.startsWith('<');
40
+ const virtualPath = isRealPath
41
+ ? origin
42
+ : path.join(os.tmpdir(), `lws-cli-${origin?.replace(/[<>]/g, '') ?? 'input'}.js`);
43
+
44
+ const bundle = await rollup({
45
+ input: VIRTUAL_ID,
46
+ plugins: [
47
+ virtualSourcePlugin({ source, virtualPath }),
48
+ lockerRollupPlugin({
49
+ sandboxKey,
50
+ include: [virtualPath],
51
+ }),
52
+ ],
53
+ // `@locker/sandbox` resolves to `window.evaluateInSandbox` at
54
+ // runtime via the globals mapping below. The harness page
55
+ // installs a wrapping `evaluateInSandbox` (in
56
+ // /_runtime/evaluator.js) that merges CLI-supplied endowments
57
+ // before delegating to the original. So the user's bundle calls
58
+ // plain `evaluateInSandbox` and the merging happens at the
59
+ // window boundary, never inline.
60
+ external: ['@locker/sandbox'],
61
+ // Disable tree-shaking. The user's source is *meant* to
62
+ // execute; tree-shaking would strip console.log calls and
63
+ // other side effects rollup deems "pure" by default.
64
+ treeshake: false,
65
+ });
66
+
67
+ const { output } = await bundle.generate({
68
+ format: 'iife',
69
+ globals: { '@locker/sandbox': 'window' },
70
+ });
71
+ await bundle.close();
72
+
73
+ if (output.length !== 1) {
74
+ throw new Error(`expected exactly one chunk, got ${output.length}`);
75
+ }
76
+ return cleanIifeWrapper(output[0].code);
77
+ }
78
+
79
+ // Rewrite the rollup-emitted IIFE wrapper so the user-facing bundle reads
80
+ // `window.evaluateInSandbox(...)` directly instead of going through a
81
+ // `(function (sandbox) { ... sandbox.evaluateInSandbox(...) })(window)`
82
+ // shim that arises from rollup's iife-format `globals` mapping.
83
+ function cleanIifeWrapper(code) {
84
+ return code
85
+ .replace(/\(function \(sandbox\) \{/, '(function () {')
86
+ .replace(/sandbox\.evaluateInSandbox\(/g, 'window.evaluateInSandbox(')
87
+ .replace(/\}\)\(window\);\s*$/, '})();\n');
88
+ }
89
+
90
+ // Test-only export: lets the unit suite write a fixture to disk and round-trip
91
+ // through the same transform path the runner uses.
92
+ export async function transformFile({ filePath, sandboxKey = 'cli' }) {
93
+ const source = await fs.readFile(filePath, 'utf8');
94
+ return transform({ source, origin: filePath, sandboxKey });
95
+ }
@@ -0,0 +1,256 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+
5
+ // 24-hour cache window. Within this window, repeated invocations read the
6
+ // cached result instead of hitting the npm registry. The window is
7
+ // generous because:
8
+ // - The cost of being one day stale on an upgrade notice is low.
9
+ // - Many users invoke `lws` in tight loops (per-file watches, CI smoke
10
+ // suites). Hitting the registry on every invocation would be both
11
+ // impolite and slow on flaky connections.
12
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
13
+
14
+ // Hard cap on the network request. The check is non-blocking by design:
15
+ // if the registry is unreachable, we write a placeholder cache entry so
16
+ // later runs don't keep retrying, and the user never sees the failure.
17
+ // The cap is short enough that even a fully-hung fetch can't add visible
18
+ // latency to the user's command.
19
+ const FETCH_TIMEOUT_MS = 1500;
20
+
21
+ // Where the cache lives. ~/.cache/lws-cli/ is portable across Linux and
22
+ // macOS (and works on Windows under msys/mingw). On platforms without a
23
+ // real homedir, the path resolves to /<empty>/.cache/lws-cli/, which
24
+ // fails the writeFile and is treated like any other I/O error: silent
25
+ // skip, no notice.
26
+ const CACHE_DIR = path.join(os.homedir(), '.cache', 'lws-cli');
27
+ const CACHE_FILE = path.join(CACHE_DIR, 'version-check.json');
28
+
29
+ const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
30
+
31
+ // Parse a semver MAJOR.MINOR.PATCH triple. Returns null if the input
32
+ // doesn't look like a semver (so we conservatively skip the upgrade
33
+ // notice on unparseable inputs rather than guess).
34
+ function parseVersion(value) {
35
+ if (typeof value !== 'string') {
36
+ return null;
37
+ }
38
+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(value);
39
+ if (!match) {
40
+ return null;
41
+ }
42
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
43
+ }
44
+
45
+ // Returns true iff `latest` is strictly newer than `running` on the
46
+ // MAJOR.MINOR.PATCH triple. Pre-release suffixes are ignored (the
47
+ // registry's `latest` tag is by convention a stable release; if the
48
+ // running version is a prerelease the strict-newer comparison will
49
+ // surface the stable upgrade).
50
+ export function isUpgradeAvailable(running, latest) {
51
+ const r = parseVersion(running);
52
+ const l = parseVersion(latest);
53
+ if (r === null || l === null) {
54
+ return false;
55
+ }
56
+ for (let i = 0; i < 3; i += 1) {
57
+ if (l[i] > r[i]) {
58
+ return true;
59
+ }
60
+ if (l[i] < r[i]) {
61
+ return false;
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+
67
+ async function readCache(now = Date.now()) {
68
+ try {
69
+ const raw = await fs.readFile(CACHE_FILE, 'utf8');
70
+ const data = JSON.parse(raw);
71
+ if (typeof data?.checkedAt !== 'number') {
72
+ return null;
73
+ }
74
+ if (now - data.checkedAt > CACHE_TTL_MS) {
75
+ return null;
76
+ }
77
+ return data;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ async function writeCache(data) {
84
+ try {
85
+ await fs.mkdir(CACHE_DIR, { recursive: true });
86
+ await fs.writeFile(CACHE_FILE, JSON.stringify(data), 'utf8');
87
+ } catch {
88
+ // Cache write failures are non-fatal: the worst case is we
89
+ // re-fetch on the next invocation. We don't want a read-only
90
+ // homedir or a quota error to surface to the user.
91
+ }
92
+ }
93
+
94
+ async function fetchLatestVersion(packageName) {
95
+ const controller = new AbortController();
96
+ const timeoutHandle = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
97
+ timeoutHandle.unref?.();
98
+ try {
99
+ const url = `${NPM_REGISTRY_URL}/${packageName}/latest`;
100
+ const response = await fetch(url, {
101
+ signal: controller.signal,
102
+ headers: { Accept: 'application/json' },
103
+ });
104
+ if (!response.ok) {
105
+ return null;
106
+ }
107
+ const data = await response.json();
108
+ if (typeof data?.version !== 'string') {
109
+ return null;
110
+ }
111
+ return data.version;
112
+ } catch {
113
+ // Network failure, abort, JSON parse error: all treated as "no
114
+ // result" so the upgrade notice silently skips on this run.
115
+ return null;
116
+ } finally {
117
+ clearTimeout(timeoutHandle);
118
+ }
119
+ }
120
+
121
+ // Detect whether the CLI is running from an installed location (under a
122
+ // `node_modules` directory) vs. directly from monorepo source. The
123
+ // version check should only fire for installed copies: when contributors
124
+ // run `node bin/lws.mjs ...` from `packages/@locker/cli/`, there is no
125
+ // "latest published version to compare against" relative to a working
126
+ // tree. The check is also useless during CLI smoke tests, which run the
127
+ // bin directly from the repo.
128
+ //
129
+ // `installedPath` is typically the absolute path to the package's
130
+ // installation root (e.g. `import.meta.url` resolved to the file). The
131
+ // function returns true iff that path contains a `node_modules` segment
132
+ // at any depth.
133
+ export function isRunningFromInstall(installedPath) {
134
+ if (typeof installedPath !== 'string') {
135
+ return false;
136
+ }
137
+ return installedPath.includes(`${path.sep}node_modules${path.sep}`);
138
+ }
139
+
140
+ // Public entry point. Kicks off the version check and returns a promise
141
+ // that resolves to either:
142
+ // - { hasUpgrade: true, running, latest }
143
+ // - { hasUpgrade: false }
144
+ // The promise NEVER rejects: any error inside the check is swallowed and
145
+ // surfaces as { hasUpgrade: false }. Callers can safely await with no
146
+ // try/catch.
147
+ //
148
+ // Skip conditions (return { hasUpgrade: false } without any I/O):
149
+ // - The package's package.json declares `"private": true`. This is the
150
+ // load-bearing pre-publish signal: while the package is not on a
151
+ // registry, there is no "latest" to compare against, so the check
152
+ // would burn a guaranteed-404 round trip on every invocation.
153
+ // Flipping `private` to false (or removing the flag) is the
154
+ // explicit unlock once the package is published.
155
+ // - The package is running from a path that doesn't include
156
+ // node_modules (i.e. monorepo source, contributor dev loop). Even
157
+ // if `private` is somehow false during a contributor build, the
158
+ // path-based skip prevents the check from firing.
159
+ //
160
+ // Caller is expected to:
161
+ // 1. Call startVersionCheck() at the top of the command, NOT await it
162
+ // (so the network round-trip overlaps with the actual command).
163
+ // 2. Await the returned promise just before exit, then pass the
164
+ // result to formatUpgradeNotice() to render a stderr-friendly
165
+ // string and write it via output.error.
166
+ export async function startVersionCheck({
167
+ packageName,
168
+ currentVersion,
169
+ isPrivate = false,
170
+ installedPath = null,
171
+ now = Date.now(),
172
+ }) {
173
+ if (typeof packageName !== 'string' || typeof currentVersion !== 'string') {
174
+ return { hasUpgrade: false };
175
+ }
176
+ if (isPrivate === true) {
177
+ return { hasUpgrade: false };
178
+ }
179
+ if (installedPath !== null && !isRunningFromInstall(installedPath)) {
180
+ return { hasUpgrade: false };
181
+ }
182
+
183
+ const cached = await readCache(now);
184
+ if (cached !== null) {
185
+ const latest = cached.latestVersion;
186
+ if (typeof latest === 'string' && isUpgradeAvailable(currentVersion, latest)) {
187
+ return { hasUpgrade: true, running: currentVersion, latest };
188
+ }
189
+ return { hasUpgrade: false };
190
+ }
191
+
192
+ const latest = await fetchLatestVersion(packageName);
193
+ // Always persist a cache entry, even when the fetch yielded null.
194
+ // The placeholder prevents subsequent invocations within the TTL
195
+ // window from re-attempting a failed network request.
196
+ await writeCache({ checkedAt: now, latestVersion: latest });
197
+ if (latest !== null && isUpgradeAvailable(currentVersion, latest)) {
198
+ return { hasUpgrade: true, running: currentVersion, latest };
199
+ }
200
+ return { hasUpgrade: false };
201
+ }
202
+
203
+ // Format an upgrade notice for stderr. Single-line, package-agnostic so
204
+ // it can be reused if the CLI ever wraps another package.
205
+ export function formatUpgradeNotice({ packageName, running, latest }) {
206
+ const upgrade = `npm i -g ${packageName}`;
207
+ return `Update available for ${packageName}: ${running} -> ${latest}. Run \`${upgrade}\` to upgrade.`;
208
+ }
209
+
210
+ // CLI-side helper. Encapsulates the "kick off / await later / write to
211
+ // stderr" pattern so runEval, runComponent, and runRepl don't each have
212
+ // to thread package metadata through. Returns either:
213
+ // - null: skip the check entirely (--quiet, private package, monorepo
214
+ // source). The corresponding `awaitAndEmitUpgradeNotice` becomes a
215
+ // no-op for null inputs.
216
+ // - a Promise that resolves to the version-check result.
217
+ //
218
+ // Caller passes:
219
+ // - argv: yargs argv (quiet bit is consulted)
220
+ // - packageJson: the parsed package.json object (name, version, private)
221
+ // - installedPath: the absolute path of the calling module, used to
222
+ // detect monorepo-source vs. installed (under node_modules)
223
+ //
224
+ // The promise NEVER rejects.
225
+ export function startVersionCheckForCLI({ argv, packageJson, installedPath }) {
226
+ if (argv.quiet === true) {
227
+ return null;
228
+ }
229
+ return startVersionCheck({
230
+ packageName: packageJson.name,
231
+ currentVersion: packageJson.version,
232
+ isPrivate: packageJson.private === true,
233
+ installedPath,
234
+ });
235
+ }
236
+
237
+ // Companion to startVersionCheckForCLI. Awaits the promise returned by
238
+ // the kick-off helper and writes the notice to stderr via output.error
239
+ // if there's an upgrade available. No-op when the promise is null
240
+ // (suppressed by --quiet, etc.) or when no upgrade is available.
241
+ export async function awaitAndEmitUpgradeNotice({ promise, packageJson, output }) {
242
+ if (promise === null) {
243
+ return;
244
+ }
245
+ const result = await promise;
246
+ if (!result.hasUpgrade) {
247
+ return;
248
+ }
249
+ output.error(
250
+ formatUpgradeNotice({
251
+ packageName: packageJson.name,
252
+ running: result.running,
253
+ latest: result.latest,
254
+ }),
255
+ );
256
+ }