@xlinklight/browser-extension-tools 1.0.0-rc.0 → 1.0.1

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.
Files changed (71) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +33 -33
  3. package/{assets → dist/assets}/shared/css/side-panel.css +94 -94
  4. package/dist/assets/shared/js/chrome-runtime.js +79 -0
  5. package/dist/assets/shared/js/extension-account-menu.js +212 -0
  6. package/dist/assets/shared/js/extension-i18n.js +35 -0
  7. package/dist/assets/shared/js/extension-session-store.js +40 -0
  8. package/dist/assets/shared/js/extension-tabs.js +27 -0
  9. package/dist/assets/shared/js/link-light-api-client.js +30 -0
  10. package/dist/assets/shared/js/side-panel-account.js +14 -0
  11. package/dist/assets/shared/js/side-panel-api.js +13 -0
  12. package/dist/assets/shared/js/side-panel-bootstrap.js +97 -0
  13. package/dist/assets/shared/js/side-panel-dom.js +14 -0
  14. package/dist/assets/shared/js/side-panel-i18n.js +34 -0
  15. package/dist/assets/shared/js/side-panel-import-preview.js +7 -0
  16. package/dist/assets/shared/js/side-panel-status.js +12 -0
  17. package/dist/assets/shared/js/side-panel-tabs.js +29 -0
  18. package/dist/assets/shared/js/side-panel-translations.js +30 -0
  19. package/dist/src/chrome-discovery.d.ts +57 -0
  20. package/dist/src/chrome-discovery.js +178 -0
  21. package/dist/src/chrome-for-testing.d.ts +66 -0
  22. package/dist/src/chrome-for-testing.js +157 -0
  23. package/dist/src/chrome-install-worker.d.ts +1 -0
  24. package/dist/src/chrome-install-worker.js +8 -0
  25. package/dist/src/cli.d.ts +41 -0
  26. package/dist/src/cli.js +189 -0
  27. package/dist/src/dev-cli.d.ts +2 -0
  28. package/dist/src/dev-cli.js +11 -0
  29. package/dist/src/dev-extension.d.ts +51 -0
  30. package/dist/src/dev-extension.js +307 -0
  31. package/dist/src/fs-error.d.ts +1 -0
  32. package/dist/src/fs-error.js +3 -0
  33. package/dist/src/package-cli.d.ts +2 -0
  34. package/dist/src/package-cli.js +9 -0
  35. package/dist/src/package.d.ts +15 -0
  36. package/dist/src/package.js +203 -0
  37. package/dist/src/profile.d.ts +34 -0
  38. package/dist/src/profile.js +105 -0
  39. package/dist/src/reload-server.d.ts +14 -0
  40. package/dist/src/reload-server.js +96 -0
  41. package/{src/run.mjs → dist/src/run.d.ts} +7 -7
  42. package/dist/src/run.js +7 -0
  43. package/dist/src/watcher.d.ts +17 -0
  44. package/dist/src/watcher.js +30 -0
  45. package/package.json +33 -11
  46. package/assets/shared/js/chrome-runtime.js +0 -87
  47. package/assets/shared/js/extension-account-menu.js +0 -239
  48. package/assets/shared/js/extension-i18n.js +0 -42
  49. package/assets/shared/js/extension-session-store.js +0 -42
  50. package/assets/shared/js/extension-tabs.js +0 -23
  51. package/assets/shared/js/link-light-api-client.js +0 -31
  52. package/assets/shared/js/side-panel-account.js +0 -14
  53. package/assets/shared/js/side-panel-api.js +0 -13
  54. package/assets/shared/js/side-panel-bootstrap.js +0 -127
  55. package/assets/shared/js/side-panel-dom.js +0 -15
  56. package/assets/shared/js/side-panel-i18n.js +0 -37
  57. package/assets/shared/js/side-panel-import-preview.js +0 -7
  58. package/assets/shared/js/side-panel-status.js +0 -13
  59. package/assets/shared/js/side-panel-tabs.js +0 -35
  60. package/assets/shared/js/side-panel-translations.js +0 -41
  61. package/src/chrome-discovery.mjs +0 -231
  62. package/src/chrome-for-testing.mjs +0 -203
  63. package/src/chrome-install-worker.mjs +0 -8
  64. package/src/cli.mjs +0 -171
  65. package/src/dev-cli.mjs +0 -9
  66. package/src/dev-extension.mjs +0 -350
  67. package/src/package-cli.mjs +0 -7
  68. package/src/package.mjs +0 -223
  69. package/src/profile.mjs +0 -144
  70. package/src/reload-server.mjs +0 -108
  71. package/src/watcher.mjs +0 -45
@@ -1,41 +0,0 @@
1
- (function initializeLinkLightSidePanelTranslations(global) {
2
- function applySidePanelTranslations({
3
- documentRef = global.document,
4
- t,
5
- locale,
6
- titleKey = "extensionName",
7
- languageInput,
8
- languagePreference,
9
- safetyNote,
10
- onAfterStaticTranslations,
11
- }) {
12
- documentRef.documentElement.lang = locale;
13
- documentRef.title = t(titleKey);
14
-
15
- for (const element of documentRef.querySelectorAll("[data-i18n]")) {
16
- element.textContent = t(element.dataset.i18n);
17
- }
18
-
19
- for (const element of documentRef.querySelectorAll("[data-i18n-placeholder]")) {
20
- element.setAttribute("placeholder", t(element.dataset.i18nPlaceholder));
21
- }
22
-
23
- for (const element of documentRef.querySelectorAll("[data-i18n-aria-label]")) {
24
- element.setAttribute("aria-label", t(element.dataset.i18nAriaLabel));
25
- }
26
-
27
- for (const element of documentRef.querySelectorAll("[data-i18n-title]")) {
28
- const values = {};
29
- if (element.dataset.i18nTitleFeatureKey) {
30
- values.feature = t(element.dataset.i18nTitleFeatureKey);
31
- }
32
- element.setAttribute("title", t(element.dataset.i18nTitle, values));
33
- }
34
-
35
- if (safetyNote) safetyNote.textContent = t("safetyNote");
36
- if (languageInput) languageInput.value = languagePreference;
37
- if (typeof onAfterStaticTranslations === "function") onAfterStaticTranslations();
38
- }
39
-
40
- global.LinkLightSidePanelTranslations = { applySidePanelTranslations };
41
- })(globalThis);
@@ -1,231 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { existsSync, readdirSync, statSync } from "node:fs";
3
- import path from "node:path";
4
- import { chromeExtensionsUrl, getArgValue, getChromeLaunchExtensionDirs, getProfileDirForExtensions, getProjectPaths, getRequestedAppUrl, getRequestedBrowser, getRequestedExtensions } from "./cli.mjs";
5
-
6
- export function normalizeChromeExtensionPath(extensionPath, platform) {
7
- const pathApi = platform === "win32" ? path.win32 : path.posix;
8
- const resolvedPath = pathApi.resolve(extensionPath);
9
-
10
- if (platform !== "win32") {
11
- return resolvedPath;
12
- }
13
-
14
- return resolvedPath.replace(/^([a-z]):/, (_, driveLetter) => `${driveLetter.toUpperCase()}:`);
15
- }
16
-
17
- export function getChromeExtensionIdForPath(extensionPath, { platform = process.platform } = {}) {
18
- const normalizedPath = normalizeChromeExtensionPath(extensionPath, platform);
19
- const pathBytes = platform === "win32" ? Buffer.from(normalizedPath, "utf16le") : Buffer.from(normalizedPath);
20
- const digest = createHash("sha256").update(pathBytes).digest("hex").slice(0, 32);
21
-
22
- return digest.replace(/[0-9a-f]/g, (character) => "abcdefghijklmnop"[Number.parseInt(character, 16)]);
23
- }
24
-
25
- export function getChromeExecutableName(platform) {
26
- if (platform === "win32") return "chrome.exe";
27
- if (platform === "darwin") return "Google Chrome for Testing";
28
- return "chrome";
29
- }
30
-
31
- export function findExecutableBelow(directory, executableName) {
32
- const entries = readdirSync(directory, { withFileTypes: true });
33
-
34
- for (const entry of entries) {
35
- const entryPath = path.join(directory, entry.name);
36
- if (entry.isFile() && entry.name === executableName) {
37
- return entryPath;
38
- }
39
- if (entry.isDirectory()) {
40
- const foundPath = findExecutableBelow(entryPath, executableName);
41
- if (foundPath) return foundPath;
42
- }
43
- }
44
-
45
- return null;
46
- }
47
-
48
- export function findLocalChromeForTesting({
49
- rootDir = process.cwd(),
50
- platform = process.platform,
51
- exists = existsSync,
52
- } = {}) {
53
- const { chromeForTestingDir } = getProjectPaths(rootDir);
54
- if (!exists(chromeForTestingDir)) {
55
- return null;
56
- }
57
-
58
- try {
59
- if (!statSync(chromeForTestingDir).isDirectory()) {
60
- return null;
61
- }
62
- return findExecutableBelow(chromeForTestingDir, getChromeExecutableName(platform));
63
- } catch (error) {
64
- if (error?.code === "ENOENT") {
65
- return null;
66
- }
67
- throw error;
68
- }
69
- }
70
-
71
- export function isLikelyGoogleChromeOrChromeForTesting(chromePath) {
72
- const normalizedPath = chromePath.toLowerCase().replaceAll("\\", "/");
73
-
74
- return (
75
- normalizedPath.includes("chrome for testing") ||
76
- normalizedPath.includes("chrome-for-testing") ||
77
- normalizedPath.includes("chrome-win64") ||
78
- normalizedPath.includes("/google/chrome/application/chrome.exe") ||
79
- normalizedPath.endsWith("/google chrome")
80
- );
81
- }
82
-
83
- export function candidateChromePaths({ browser, env, platform }) {
84
- if (platform === "win32") {
85
- if (browser === "chrome") {
86
- return [
87
- env.CHROME_FOR_TESTING_PATH,
88
- env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
89
- env.PROGRAMFILES && path.join(env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
90
- env["PROGRAMFILES(X86)"] && path.join(env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
91
- String.raw`C:\Program Files\Google\Chrome\Application\chrome.exe`,
92
- String.raw`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
93
- ].filter(Boolean);
94
- }
95
-
96
- return [
97
- env.CHROME_FOR_TESTING_PATH,
98
- env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "Chromium", "Application", "chrome.exe"),
99
- env.PROGRAMFILES && path.join(env.PROGRAMFILES, "Chromium", "Application", "chrome.exe"),
100
- env["PROGRAMFILES(X86)"] && path.join(env["PROGRAMFILES(X86)"], "Chromium", "Application", "chrome.exe"),
101
- env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "Microsoft", "Edge", "Application", "msedge.exe"),
102
- env.PROGRAMFILES && path.join(env.PROGRAMFILES, "Microsoft", "Edge", "Application", "msedge.exe"),
103
- env["PROGRAMFILES(X86)"] && path.join(env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe"),
104
- env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
105
- env.PROGRAMFILES && path.join(env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
106
- env["PROGRAMFILES(X86)"] && path.join(env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
107
- String.raw`C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
108
- String.raw`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
109
- String.raw`C:\Program Files\Google\Chrome\Application\chrome.exe`,
110
- String.raw`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
111
- ].filter(Boolean);
112
- }
113
-
114
- if (platform === "darwin") {
115
- return ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"];
116
- }
117
-
118
- if (browser === "chrome") {
119
- return ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
120
- }
121
-
122
- return ["/usr/bin/chromium", "/snap/bin/chromium", "/usr/bin/microsoft-edge", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
123
- }
124
-
125
- export function findChromePath({
126
- argv = process.argv.slice(2),
127
- env = process.env,
128
- exists = existsSync,
129
- platform = process.platform,
130
- rootDir = process.cwd(),
131
- } = {}) {
132
- const requestedBrowser = getRequestedBrowser(argv);
133
- const explicitChromePath = getArgValue(argv, "--chrome-path") || env.CHROME_FOR_TESTING_PATH;
134
- if (explicitChromePath?.trim()) {
135
- return explicitChromePath.trim();
136
- }
137
-
138
- const localChromeForTestingPath = findLocalChromeForTesting({ rootDir, platform, exists });
139
- if (localChromeForTestingPath) {
140
- return localChromeForTestingPath;
141
- }
142
-
143
- if (
144
- env.CHROME_PATH?.trim() &&
145
- (!requestedBrowser || isLikelyGoogleChromeOrChromeForTesting(env.CHROME_PATH.trim()))
146
- ) {
147
- return env.CHROME_PATH.trim();
148
- }
149
-
150
- const foundPath = candidateChromePaths({ browser: requestedBrowser, env, platform }).find((candidate) => exists(candidate));
151
- if (foundPath) {
152
- return foundPath;
153
- }
154
-
155
- throw new Error(
156
- "Chrome executable was not found. Set CHROME_PATH or pass --chrome-path=<path-to-chrome>.",
157
- );
158
- }
159
-
160
- export function isLikelyBrandedChrome(chromePath) {
161
- const normalizedPath = chromePath.toLowerCase().replaceAll("\\", "/");
162
-
163
- if (normalizedPath.includes("chrome for testing") || normalizedPath.includes("chrome-for-testing")) {
164
- return false;
165
- }
166
- if (normalizedPath.includes("chrome-win64") || normalizedPath.includes("chromium") || normalizedPath.includes("/microsoft/edge/")) {
167
- return false;
168
- }
169
-
170
- return normalizedPath.includes("/google/chrome/application/chrome.exe") || normalizedPath.endsWith("/google chrome");
171
- }
172
-
173
- export function buildChromeLaunchConfig({
174
- argv = process.argv.slice(2),
175
- env = process.env,
176
- existsSync: exists = existsSync,
177
- platform = process.platform,
178
- rootDir = process.cwd(),
179
- extensionRoot = getArgValue(argv, "--extension-root"),
180
- extensionName,
181
- extensionNames = extensionName ? [extensionName] : getRequestedExtensions(argv, rootDir),
182
- appUrl = getRequestedAppUrl(argv, env),
183
- profileDir = getProfileDirForExtensions(rootDir, extensionNames, extensionRoot),
184
- } = {}) {
185
- const launchExtensionDirs = getChromeLaunchExtensionDirs({ extensionNames, rootDir, extensionRoot });
186
- const launchExtensionArg = launchExtensionDirs.join(",");
187
- const url = getArgValue(argv, "--url") || appUrl;
188
- const chromePath = findChromePath({ argv, env, exists, platform, rootDir });
189
- const autoLoadSupported = argv.includes("--allow-branded-chrome") || !isLikelyBrandedChrome(chromePath);
190
- const baseArgs = [
191
- `--user-data-dir=${profileDir}`,
192
- "--new-window",
193
- "--no-first-run",
194
- "--no-default-browser-check",
195
- ];
196
-
197
- if (!autoLoadSupported) {
198
- return {
199
- autoLoadSupported,
200
- chromePath,
201
- launchExtensionDirs,
202
- args: [...baseArgs, chromeExtensionsUrl, url],
203
- manualLoadPath: launchExtensionDirs.join(", "),
204
- resetProfile: argv.includes("--reset-profile"),
205
- unsupportedAutoLoadReason:
206
- "Automatic unpacked extension loading is disabled in current branded Chrome builds. Use Chrome for Testing for one-command loading, or load the unpacked extension manually.",
207
- };
208
- }
209
-
210
- return {
211
- autoLoadSupported,
212
- chromePath,
213
- launchExtensionDirs,
214
- args: [
215
- ...baseArgs,
216
- `--load-extension=${launchExtensionArg}`,
217
- `--disable-extensions-except=${launchExtensionArg}`,
218
- chromeExtensionsUrl,
219
- url,
220
- ],
221
- resetProfile: argv.includes("--reset-profile"),
222
- };
223
- }
224
-
225
- export function samePath(left, right) {
226
- const resolvedLeft = path.resolve(left);
227
- const resolvedRight = path.resolve(right);
228
- return process.platform === "win32"
229
- ? resolvedLeft.toLowerCase() === resolvedRight.toLowerCase()
230
- : resolvedLeft === resolvedRight;
231
- }
@@ -1,203 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { fileURLToPath } from "node:url";
3
- import path from "node:path";
4
- import { createNodeCommandRunner } from "@openge/forge-command-runner/node";
5
- import { createPosixProcessControl, createWindowsProcessControl } from "@openge/forge-process-control-node";
6
- import { chromeForTestingOfficialBaseUrl, defaultChromeForTestingFallbackBuildId, getProjectPaths } from "./cli.mjs";
7
-
8
- function createInstallerCommandRunner(platform) {
9
- return createNodeCommandRunner({
10
- platform: platform === "win32" ? "win32" : "posix",
11
- processControl: platform === "win32" ? createWindowsProcessControl({ listenerBackend: "powershell" }) : createPosixProcessControl({ listenerBackend: "lsof" }),
12
- terminationPolicy: { mode: platform === "win32" ? "force" : "graceful" },
13
- identityAcquisition: { timeoutMs: platform === "win32" ? 8_000 : 2_000, pollIntervalMs: 20 },
14
- terminationTimeoutMs: platform === "win32" ? 15_000 : 5_000,
15
- });
16
- }
17
-
18
- export function trimOutput(value, maxLength = 2400) {
19
- const normalized = value.trim();
20
- if (normalized.length <= maxLength) return normalized;
21
- return normalized.slice(-maxLength);
22
- }
23
-
24
- export function stringifyProcessOutput(value) {
25
- if (!value) return "";
26
- return Buffer.isBuffer(value) ? value.toString("utf8") : String(value);
27
- }
28
-
29
- export function getProcessOutputErrorReason(result) {
30
- const output = [result.stderr, result.stdout].map(stringifyProcessOutput).filter(Boolean).join("\n");
31
- const errorMatch = output.match(/\bError:\s*([^\r\n]+)/);
32
- return errorMatch?.[1]?.trim() || "";
33
- }
34
-
35
- export function formatChromeForTestingInstallFailure(result) {
36
- if (result.error) return result.error.message;
37
-
38
- const reason = getProcessOutputErrorReason(result);
39
- if (typeof result.status === "number" && result.status !== 0) {
40
- return `exit code ${result.status}${reason ? `: ${reason}` : ""}`;
41
- }
42
-
43
- return reason || "unknown error";
44
- }
45
-
46
- export function getPackageRunner({ env, platform }) {
47
- const userAgent = env.npm_config_user_agent ?? "";
48
- const execPath = env.npm_execpath ?? "";
49
- const commandSuffix = platform === "win32" ? ".cmd" : "";
50
-
51
- if (userAgent.startsWith("pnpm/") || /[\\/]pnpm(?:\.cjs|\.js|\.cmd)?$/i.test(execPath)) {
52
- return { command: `pnpm${commandSuffix}`, argsPrefix: ["dlx"] };
53
- }
54
-
55
- return { command: `npx${commandSuffix}`, argsPrefix: [] };
56
- }
57
-
58
- export function getChromeForTestingInstallStep({
59
- env = process.env,
60
- platform = process.platform,
61
- rootDir = process.cwd(),
62
- } = {}) {
63
- const { chromeForTestingDir } = getProjectPaths(rootDir);
64
- const packageRunner = getPackageRunner({ env, platform });
65
-
66
- return {
67
- command: packageRunner.command,
68
- args: [
69
- ...packageRunner.argsPrefix,
70
- "@puppeteer/browsers",
71
- "install",
72
- "chrome@stable",
73
- "--path",
74
- chromeForTestingDir,
75
- ],
76
- };
77
- }
78
-
79
- export function getChromeForTestingFallbackBuildId(env = process.env) {
80
- return env.LINK_LIGHT_CHROME_FOR_TESTING_BUILD_ID?.trim() || defaultChromeForTestingFallbackBuildId;
81
- }
82
-
83
- export function getChromeForTestingDirectInstallStep({
84
- env = process.env,
85
- platform = process.platform,
86
- rootDir = process.cwd(),
87
- } = {}) {
88
- if (platform !== "win32") return null;
89
-
90
- const { chromeForTestingDir } = getProjectPaths(rootDir);
91
- const packageRunner = getPackageRunner({ env, platform });
92
- const buildId = getChromeForTestingFallbackBuildId(env);
93
-
94
- return {
95
- command: packageRunner.command,
96
- args: [
97
- ...packageRunner.argsPrefix,
98
- "@puppeteer/browsers",
99
- "install",
100
- `chrome@${buildId}`,
101
- "--platform",
102
- "win64",
103
- "--base-url",
104
- chromeForTestingOfficialBaseUrl,
105
- "--path",
106
- chromeForTestingDir,
107
- ],
108
- route: "official exact build fallback",
109
- };
110
- }
111
-
112
- export function getChromeForTestingInstallSteps({
113
- env = process.env,
114
- platform = process.platform,
115
- rootDir = process.cwd(),
116
- } = {}) {
117
- return [
118
- { ...getChromeForTestingInstallStep({ env, platform, rootDir }), route: "stable channel" },
119
- getChromeForTestingDirectInstallStep({ env, platform, rootDir }),
120
- ].filter(Boolean);
121
- }
122
-
123
- export function installChromeForTesting({
124
- env = process.env,
125
- installRunner = spawnSync,
126
- logger = console.log,
127
- maxAttempts = 3,
128
- platform = process.platform,
129
- rootDir = process.cwd(),
130
- stdio = "inherit",
131
- } = {}) {
132
- const steps = getChromeForTestingInstallSteps({ env, platform, rootDir });
133
- let lastFailure = null;
134
-
135
- for (const step of steps) {
136
- logger(`Using Chrome for Testing install route: ${step.route}.`);
137
-
138
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
139
- const attemptLabel = maxAttempts > 1 ? ` (${attempt}/${maxAttempts})` : "";
140
- logger(`Installing Chrome for Testing${attemptLabel} with: ${[step.command, ...step.args].join(" ")}`);
141
- const result = installRunner(step.command, step.args, {
142
- stdio,
143
- shell: platform === "win32",
144
- });
145
-
146
- if (result.error) {
147
- const failureMessage = formatChromeForTestingInstallFailure(result);
148
- lastFailure = failureMessage;
149
- if (attempt === maxAttempts) {
150
- logger(`Chrome for Testing install route "${step.route}" failed with ${failureMessage}.`);
151
- break;
152
- }
153
- logger(`Chrome for Testing install failed with ${failureMessage}. Retrying.`);
154
- continue;
155
- }
156
- if (typeof result.status === "number" && result.status !== 0) {
157
- const failureMessage = formatChromeForTestingInstallFailure(result);
158
- lastFailure = failureMessage;
159
- if (attempt === maxAttempts) {
160
- logger(`Chrome for Testing install route "${step.route}" failed with ${failureMessage}.`);
161
- break;
162
- }
163
- logger(`Chrome for Testing install failed with ${failureMessage}. Retrying.`);
164
- continue;
165
- }
166
-
167
- return;
168
- }
169
- }
170
-
171
- throw new Error(`Chrome for Testing install failed with ${lastFailure || "unknown error"}`);
172
- }
173
-
174
- // 同步安装器保留原有重试策略;主 dev 在独立 Node 进程中等待它,确保可以取消整个安装树。
175
- export async function installChromeForTestingForDev({
176
- env = process.env,
177
- logger = console.log,
178
- maxAttempts = 3,
179
- platform = process.platform,
180
- rootDir = process.cwd(),
181
- signal,
182
- commandRunner = createInstallerCommandRunner(platform),
183
- ...options
184
- } = {}) {
185
- if (!signal) return installChromeForTesting({ ...options, env, logger, maxAttempts, platform, rootDir });
186
- signal.throwIfAborted();
187
- const result = await commandRunner.run({
188
- command: process.execPath,
189
- args: [path.join(path.dirname(fileURLToPath(import.meta.url)), "chrome-install-worker.mjs"), String(maxAttempts)],
190
- cwd: rootDir,
191
- signal,
192
- environment: { mode: "replace", values: Object.fromEntries(Object.entries(env).filter(([, value]) => value !== undefined)) },
193
- output: { mode: "capture", maxBytesPerStream: 1024 * 1024, overflow: "truncate" },
194
- });
195
- for (const bytes of [result.stdout, result.stderr]) {
196
- if (bytes?.length) logger(Buffer.from(bytes).toString("utf8"));
197
- }
198
- if (result.diagnostics.length) throw new Error(result.diagnostics.map(item => item.code).join(", "));
199
- signal.throwIfAborted();
200
- if (result.terminationReason !== "exit" || result.exitCode !== 0) {
201
- throw new Error("Chrome for Testing install command ended: " + result.terminationReason + " (" + result.exitCode + ").");
202
- }
203
- }
@@ -1,8 +0,0 @@
1
- import { installChromeForTesting } from "./chrome-for-testing.mjs";
2
-
3
- try {
4
- installChromeForTesting({ maxAttempts: Number(process.argv[2]), stdio: "inherit" });
5
- } catch (error) {
6
- console.error(error instanceof Error ? error.message : String(error));
7
- process.exitCode = 1;
8
- }
package/src/cli.mjs DELETED
@@ -1,171 +0,0 @@
1
- import { existsSync, lstatSync, readdirSync } from "node:fs";
2
- import path from "node:path";
3
- import { fileURLToPath } from "node:url";
4
-
5
- export const defaultDevUrl = "http://localhost:3000";
6
- export const chromeExtensionsUrl = "chrome://extensions/";
7
- export const devReloadClientFileName = "link-light-dev-reload-client.js";
8
- export const devSidePanelReloadClientFileName = "link-light-dev-side-panel-reload-client.js";
9
- export const defaultChromeForTestingFallbackBuildId = "149.0.7827.22";
10
- export const chromeForTestingOfficialBaseUrl = "https://storage.googleapis.com/chrome-for-testing-public";
11
- export const profileStateFileName = ".link-light-extension-dev-state.json";
12
-
13
- export function getSharedAssetsRoot() {
14
- return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../assets/shared");
15
- }
16
-
17
- function within(root, target) {
18
- const relative = path.relative(path.resolve(root), path.resolve(target));
19
- return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
20
- }
21
-
22
- export function assertUnlinkedPath(target) {
23
- for (let current = path.resolve(target);; current = path.dirname(current)) {
24
- let entry;
25
- try { entry = lstatSync(current); } catch (error) { if (error.code !== "ENOENT") throw error; }
26
- if (entry?.isSymbolicLink()) throw new Error(`LINKED_EXTENSION_PATH ${current}`);
27
- if (current === path.dirname(current)) break;
28
- }
29
- return path.resolve(target);
30
- }
31
-
32
- export function assertExtensionRoot(rootDir, extensionRoot) {
33
- if (typeof extensionRoot !== "string" || !extensionRoot) throw new Error("EXTENSION_ROOT_REQUIRED");
34
- const root = path.resolve(rootDir);
35
- const target = path.resolve(root, extensionRoot);
36
- if (!within(root, target)) throw new Error("EXTENSION_ROOT_SCOPE");
37
- assertUnlinkedPath(target);
38
- if (!lstatSync(target).isDirectory()) throw new Error("EXTENSION_ROOT_DIRECTORY_REQUIRED");
39
- return target;
40
- }
41
-
42
- export function assertExtensionTree(directory) {
43
- const entry = lstatSync(assertUnlinkedPath(directory));
44
- if (!entry.isDirectory()) throw new Error("EXTENSION_DIRECTORY_REQUIRED");
45
- for (const name of readdirSync(directory)) {
46
- if ([".git", "node_modules", "shared"].includes(name)) throw new Error(`UNEXPECTED_EXTENSION_ENTRY ${name}`);
47
- const source = path.join(directory, name);
48
- const stat = lstatSync(source);
49
- if (stat.isSymbolicLink()) throw new Error(`LINKED_EXTENSION_PATH ${source}`);
50
- if (stat.isDirectory()) assertExtensionTree(source);
51
- else if (!stat.isFile()) throw new Error(`UNSUPPORTED_EXTENSION_ENTRY ${source}`);
52
- }
53
- }
54
-
55
- export function assertProjectOutput(rootDir, target) {
56
- const root = path.resolve(rootDir);
57
- const output = path.resolve(root, target);
58
- const top = path.relative(root, output).split(path.sep)[0];
59
- if (!within(root, output) || ![".tmp", "dist"].includes(top) || output === path.join(root, top)) throw new Error("EXTENSION_OUTPUT_SCOPE");
60
- assertUnlinkedPath(output);
61
- if (existsSync(output) && lstatSync(output).isFile() && lstatSync(output).nlink > 1) throw new Error("SHARED_EXTENSION_OUTPUT_FILE");
62
- return output;
63
- }
64
-
65
- export function assertSeparateExtensionOutput(source, output) {
66
- if (path.relative(source, output) === "" || within(source, output) || within(output, source)) throw new Error("EXTENSION_SOURCE_OUTPUT_OVERLAP");
67
- }
68
-
69
- export function getArgValue(argv, name) {
70
- const prefix = `${name}=`;
71
- return argv.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);
72
- }
73
-
74
- export function parseAppUrl(value) {
75
- let parsed;
76
- try { parsed = new URL(value); } catch { throw new Error(`Invalid app URL: ${value}`); }
77
- if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password) throw new Error(`Invalid app URL: ${value}`);
78
- if (parsed.pathname !== "/" || parsed.search || parsed.hash) throw new Error("App URL must be an origin without path, search, or hash.");
79
- return parsed.origin;
80
- }
81
-
82
- export function getRequestedAppUrl(argv, env = process.env) {
83
- return parseAppUrl(getArgValue(argv, "--app-url") || env.LINK_LIGHT_EXTENSION_APP_URL || defaultDevUrl);
84
- }
85
-
86
- export function assertValidExtensionName(name) {
87
- if (typeof name !== "string" || !/^[a-z][a-z0-9-]{0,79}$/.test(name)) throw new Error("Extension name must contain only lowercase letters, numbers, and hyphens.");
88
- }
89
-
90
- export function getRequestedExtension(argv) {
91
- const name = getArgValue(argv, "--extension");
92
- if (!name) throw new Error("EXTENSION_SELECTION_REQUIRED");
93
- assertValidExtensionName(name);
94
- return name;
95
- }
96
-
97
- export function discoverExtensionNames(extensionRoot) {
98
- assertUnlinkedPath(extensionRoot);
99
- return readdirSync(extensionRoot, { withFileTypes: true })
100
- .filter(entry => entry.isDirectory() && existsSync(path.join(extensionRoot, entry.name, "manifest.json")))
101
- .map(entry => entry.name).toSorted();
102
- }
103
-
104
- export function getRequestedExtensions(argv, rootDir = process.cwd()) {
105
- const extensionRoot = assertExtensionRoot(rootDir, getArgValue(argv, "--extension-root"));
106
- const multiple = getArgValue(argv, "--extensions");
107
- const single = getArgValue(argv, "--extension");
108
- if (multiple && single) throw new Error("Use either --extension or --extensions, not both.");
109
- const names = multiple === "all" ? discoverExtensionNames(extensionRoot)
110
- : multiple ? multiple.split(",").map(value => value.trim()).filter(Boolean) : [getRequestedExtension(argv)];
111
- if (!names.length) throw new Error("No Chrome extensions found under the explicit extension root.");
112
- if (new Set(names).size !== names.length) throw new Error("DUPLICATE_EXTENSION_SELECTION");
113
- for (const name of names) {
114
- assertValidExtensionName(name);
115
- const source = path.join(extensionRoot, name);
116
- assertExtensionTree(source);
117
- if (!lstatSync(path.join(source, "manifest.json")).isFile()) throw new Error("EXTENSION_MANIFEST_REQUIRED");
118
- }
119
- return names;
120
- }
121
-
122
- export function getRequestedBrowser(argv) {
123
- const browser = getArgValue(argv, "--browser");
124
- if (!browser) return null;
125
- if (browser === "chrome") return browser;
126
- throw new Error(`Unsupported browser "${browser}". Supported values: chrome.`);
127
- }
128
-
129
- export function getProjectPaths(rootDir, extensionName, extensionRoot) {
130
- const outputRoot = path.join(path.resolve(rootDir), ".tmp", "browser-extensions");
131
- const browser = { chromeForTestingDir: path.join(outputRoot, "chrome-for-testing") };
132
- if (extensionName === undefined) return browser;
133
- assertValidExtensionName(extensionName);
134
- const sourceRoot = assertExtensionRoot(rootDir, extensionRoot);
135
- const devExtensionDir = path.join(outputRoot, extensionName, "unpacked");
136
- const extensionDir = path.join(sourceRoot, extensionName);
137
- assertSeparateExtensionOutput(extensionDir, devExtensionDir);
138
- return {
139
- ...browser,
140
- devExtensionDir,
141
- extensionDir,
142
- profileDir: path.join(outputRoot, "profiles", extensionName),
143
- };
144
- }
145
-
146
- export function getRelevantExtensionFiles(rootDir, extensionName, extensionRoot) {
147
- const { extensionDir } = getProjectPaths(rootDir, extensionName, extensionRoot);
148
- assertExtensionTree(extensionDir);
149
- return [...readdirSync(extensionDir).toSorted(), "shared"];
150
- }
151
-
152
- export function getRelevantExtensionSourcePath(rootDir, extensionName, fileName, extensionRoot) {
153
- if (fileName === "shared") return getSharedAssetsRoot();
154
- if (path.basename(fileName) !== fileName) throw new Error("EXTENSION_ENTRY_SCOPE");
155
- return path.join(getProjectPaths(rootDir, extensionName, extensionRoot).extensionDir, fileName);
156
- }
157
-
158
- export function getExistingRelevantExtensionSourcePaths(rootDir, extensionName, extensionRoot) {
159
- return getRelevantExtensionFiles(rootDir, extensionName, extensionRoot)
160
- .map(file => getRelevantExtensionSourcePath(rootDir, extensionName, file, extensionRoot));
161
- }
162
-
163
- export function getProfileDirForExtensions(rootDir, extensionNames, extensionRoot) {
164
- if (!Array.isArray(extensionNames) || !extensionNames.length) throw new Error("EXTENSION_SELECTION_REQUIRED");
165
- if (extensionNames.length === 1) return getProjectPaths(rootDir, extensionNames[0], extensionRoot).profileDir;
166
- return path.join(path.resolve(rootDir), ".tmp", "browser-extensions", "profiles", "multiple");
167
- }
168
-
169
- export function getChromeLaunchExtensionDirs({ extensionNames, rootDir, extensionRoot }) {
170
- return extensionNames.map(name => getProjectPaths(rootDir, name, extensionRoot).devExtensionDir);
171
- }
package/src/dev-cli.mjs DELETED
@@ -1,9 +0,0 @@
1
- #!/usr/bin/env node
2
- import { runChromeExtensionDev } from "./run.mjs";
3
- try {
4
- const controller = await runChromeExtensionDev();
5
- if (controller.keepAlive) await controller.waitForShutdown();
6
- } catch (error) {
7
- console.error(error instanceof Error ? error.message : error);
8
- process.exitCode = 1;
9
- }