@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
@@ -0,0 +1,307 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { watch } from "node:fs";
3
+ import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { isMissingFile } from "./fs-error.js";
6
+ import { assertExtensionRoot, assertProjectOutput, defaultDevUrl, devReloadClientFileName, devSidePanelReloadClientFileName, getArgValue, getProfileDirForExtensions, getProjectPaths, getRelevantExtensionFiles, getRelevantExtensionSourcePath, getRequestedAppUrl, getRequestedExtensions, parseAppUrl } from "./cli.js";
7
+ import { buildChromeLaunchConfig, findLocalChromeForTesting } from "./chrome-discovery.js";
8
+ import { installChromeForTestingForDev } from "./chrome-for-testing.js";
9
+ import { ensureFreshChromeProfileForExtension, getExtensionLaunchSignature, pinChromeExtensionsInProfile, resetChromeProfile } from "./profile.js";
10
+ import { createDevReloadServer } from "./reload-server.js";
11
+ import { createExtensionFileWatcher } from "./watcher.js";
12
+ export async function readFileIfExists(filePath) {
13
+ try {
14
+ const fileStats = await stat(filePath);
15
+ if (fileStats.isDirectory()) {
16
+ const entries = await readdir(filePath);
17
+ const snapshots = await Promise.all(entries
18
+ .toSorted()
19
+ .map(async (entry) => `${entry}\0${await readFileIfExists(path.join(filePath, entry))}`));
20
+ return snapshots.join("\0");
21
+ }
22
+ return await readFile(filePath, "utf8");
23
+ }
24
+ catch (error) {
25
+ if (isMissingFile(error)) {
26
+ return "";
27
+ }
28
+ throw error;
29
+ }
30
+ }
31
+ export async function copyExtensionEntry(sourcePath, targetPath) {
32
+ try {
33
+ const sourceStats = await stat(sourcePath);
34
+ if (sourceStats.isDirectory()) {
35
+ await cp(sourcePath, targetPath, { recursive: true });
36
+ return;
37
+ }
38
+ await mkdir(path.dirname(targetPath), { recursive: true });
39
+ await writeFile(targetPath, await readFile(sourcePath));
40
+ }
41
+ catch (error) {
42
+ if (isMissingFile(error))
43
+ return;
44
+ throw error;
45
+ }
46
+ }
47
+ export function addUniqueItems(items, additions) {
48
+ return [...new Set([...(items ?? []), ...additions])];
49
+ }
50
+ export function buildDevReloadClient({ appOrigin, reloadPort }) {
51
+ return `(() => {
52
+ const appTabUrlPattern = ${JSON.stringify(`${appOrigin}/*`)};
53
+ const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
54
+
55
+ async function injectPageBridgeIntoAppTabs() {
56
+ if (!chrome.tabs?.query || !chrome.scripting?.executeScript) return;
57
+ const tabs = await chrome.tabs.query({ url: appTabUrlPattern });
58
+ await Promise.all(tabs.map(async (tab) => {
59
+ if (!tab?.id) return;
60
+ await chrome.scripting.executeScript({
61
+ target: { tabId: tab.id },
62
+ files: ["page-bridge.js"],
63
+ }).catch(() => null);
64
+ }));
65
+ }
66
+
67
+ function connect() {
68
+ const socket = new WebSocket(reloadSocketUrl);
69
+ socket.addEventListener("message", (event) => {
70
+ try {
71
+ const message = JSON.parse(event.data);
72
+ if (message?.type !== "reload") return;
73
+ chrome.runtime.reload();
74
+ } catch {
75
+ // Ignore malformed dev-server messages.
76
+ }
77
+ });
78
+ socket.addEventListener("close", () => setTimeout(connect, 1000));
79
+ socket.addEventListener("error", () => socket.close());
80
+ }
81
+
82
+ void injectPageBridgeIntoAppTabs();
83
+ connect();
84
+ })();
85
+ `;
86
+ }
87
+ export function buildDevSidePanelReloadClient({ buildLabel, reloadPort }) {
88
+ return `(() => {
89
+ const marker = document.createElement("div");
90
+ marker.id = "ll-dev-build-marker";
91
+ marker.textContent = ${JSON.stringify(`Dev build ${buildLabel}`)};
92
+ marker.style.cssText = "position:fixed;right:62px;bottom:8px;z-index:2147483647;border:1px solid #99f6e4;border-radius:6px;padding:2px 6px;background:#ecfeff;color:#0f766e;font:11px Arial,sans-serif;";
93
+ document.addEventListener("DOMContentLoaded", () => document.body.append(marker), { once: true });
94
+
95
+ const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
96
+ function connect() {
97
+ const socket = new WebSocket(reloadSocketUrl);
98
+ socket.addEventListener("message", (event) => {
99
+ try {
100
+ const message = JSON.parse(event.data);
101
+ if (message?.type !== "reload") return;
102
+ location.reload();
103
+ } catch {
104
+ // Ignore malformed dev-server messages.
105
+ }
106
+ });
107
+ socket.addEventListener("close", () => setTimeout(connect, 1000));
108
+ socket.addEventListener("error", () => socket.close());
109
+ }
110
+
111
+ connect();
112
+ })();
113
+ `;
114
+ }
115
+ function injectDevSidePanelReloadClient(html) {
116
+ const scriptTag = ` <script src="${devSidePanelReloadClientFileName}" defer></script>`;
117
+ if (html.includes(devSidePanelReloadClientFileName))
118
+ return html;
119
+ if (html.includes(" </body>"))
120
+ return html.replace(" </body>", `${scriptTag}\n </body>`);
121
+ return `${html}\n${scriptTag}\n`;
122
+ }
123
+ export async function prepareDevExtension({ appUrl = defaultDevUrl, extensionName, extensionRoot, reloadPort, signal, rootDir = process.cwd(), }) {
124
+ signal?.throwIfAborted();
125
+ const { devExtensionDir, extensionDir } = getProjectPaths(rootDir, extensionName, extensionRoot);
126
+ const relevantExtensionFiles = getRelevantExtensionFiles(rootDir, extensionName, extensionRoot);
127
+ assertProjectOutput(rootDir, devExtensionDir);
128
+ const appOrigin = parseAppUrl(appUrl);
129
+ await rm(devExtensionDir, { recursive: true, force: true });
130
+ await mkdir(devExtensionDir, { recursive: true });
131
+ for (const fileName of relevantExtensionFiles) {
132
+ signal?.throwIfAborted();
133
+ if (fileName === "manifest.json")
134
+ continue;
135
+ await copyExtensionEntry(getRelevantExtensionSourcePath(rootDir, extensionName, fileName, extensionRoot), path.join(devExtensionDir, fileName));
136
+ }
137
+ signal?.throwIfAborted();
138
+ const sourceManifest = JSON.parse(await readFile(path.join(extensionDir, "manifest.json"), "utf8"));
139
+ const devManifest = {
140
+ ...sourceManifest,
141
+ permissions: addUniqueItems(sourceManifest.permissions, ["tabs"]),
142
+ host_permissions: addUniqueItems(sourceManifest.host_permissions, ["<all_urls>", `${appOrigin}/*`]),
143
+ optional_host_permissions: [],
144
+ ...(reloadPort === undefined ? {} : { background: { service_worker: "custom-sidebar-background-dev.js" } }),
145
+ };
146
+ await writeFile(path.join(devExtensionDir, "manifest.json"), `${JSON.stringify(devManifest, null, 2)}\n`, "utf8");
147
+ const copiedSidePanelPath = path.join(devExtensionDir, "side-panel.html");
148
+ const copiedSidePanelHtml = await readFileIfExists(copiedSidePanelPath);
149
+ if (copiedSidePanelHtml && reloadPort !== undefined) {
150
+ await writeFile(copiedSidePanelPath, injectDevSidePanelReloadClient(copiedSidePanelHtml), "utf8");
151
+ }
152
+ await writeFile(path.join(devExtensionDir, "link-light-extension-config.js"), `globalThis.LINK_LIGHT_CONFIG = ${JSON.stringify({ origin: appOrigin })};\n`, "utf8");
153
+ const buildLabel = (await getExtensionLaunchSignature(rootDir, [extensionName], extensionRoot)).slice(0, 12);
154
+ if (reloadPort !== undefined) {
155
+ if (!Number.isInteger(reloadPort) || reloadPort < 1 || reloadPort > 65535)
156
+ throw new Error("INVALID_EXTENSION_RELOAD_PORT");
157
+ await writeFile(path.join(devExtensionDir, "custom-sidebar-background-dev.js"), `importScripts("link-light-extension-config.js", "custom-sidebar-background.js", "${devReloadClientFileName}");\n`, "utf8");
158
+ await writeFile(path.join(devExtensionDir, devReloadClientFileName), buildDevReloadClient({ appOrigin, reloadPort }), "utf8");
159
+ await writeFile(path.join(devExtensionDir, devSidePanelReloadClientFileName), buildDevSidePanelReloadClient({ buildLabel, reloadPort }), "utf8");
160
+ }
161
+ signal?.throwIfAborted();
162
+ return { buildLabel, devExtensionDir };
163
+ }
164
+ export async function runChromeExtensionDev({ argv = process.argv.slice(2), env = process.env, installRunner = spawnSync, chromeInstaller = installChromeForTestingForDev, reloadServerFactory = createDevReloadServer, signal, logger = console.log, runner = spawn, rootDir = process.cwd(), platform = process.platform, watcherFactory = watch, } = {}) {
165
+ signal?.throwIfAborted();
166
+ const withNext = argv.includes("--with-next") && !argv.includes("--no-next");
167
+ const watchExtension = argv.includes("--watch-extension") && !argv.includes("--no-watch-extension");
168
+ if (withNext)
169
+ throw new Error("RETIRED_ROOT_EXTENSION_HOST");
170
+ if (!getArgValue(argv, "--app-url") && !env.LINK_LIGHT_EXTENSION_APP_URL) {
171
+ throw new Error("LEGACY_EXTENSION_BACKEND_REQUIRED");
172
+ }
173
+ const appUrl = getRequestedAppUrl(argv, env);
174
+ const extensionRoot = assertExtensionRoot(rootDir, getArgValue(argv, "--extension-root"));
175
+ const extensionNames = getRequestedExtensions(argv, rootDir);
176
+ const profileDir = getProfileDirForExtensions(rootDir, extensionNames, extensionRoot);
177
+ await mkdir(path.dirname(profileDir), { recursive: true });
178
+ signal?.throwIfAborted();
179
+ if (argv.includes("--reset-profile")) {
180
+ await resetChromeProfile({ extensionNames, rootDir, extensionRoot });
181
+ logger(`Reset Chrome extension debug profile: ${profileDir}`);
182
+ }
183
+ const preparedProfile = await ensureFreshChromeProfileForExtension({ extensionNames, logger, rootDir, extensionRoot });
184
+ signal?.throwIfAborted();
185
+ const closers = [];
186
+ let closePromise;
187
+ const close = () => closePromise ??= (async () => {
188
+ const failures = [];
189
+ for (const closer of closers.toReversed()) {
190
+ try {
191
+ await closer();
192
+ }
193
+ catch (error) {
194
+ failures.push(error);
195
+ }
196
+ }
197
+ if (failures.length)
198
+ throw new AggregateError(failures, "Extension companion cleanup failed.");
199
+ })();
200
+ try {
201
+ if (watchExtension) {
202
+ const reloadServer = await reloadServerFactory({ logger });
203
+ closers.push(async () => reloadServer.close());
204
+ signal?.throwIfAborted();
205
+ logger("Extension watch updates the explicit source root and regenerates dev wrappers; restart this companion after updating its installed tooling package.");
206
+ for (const extensionName of extensionNames) {
207
+ await prepareDevExtension({ appUrl, extensionName, extensionRoot, reloadPort: reloadServer.port, rootDir, signal });
208
+ signal?.throwIfAborted();
209
+ const extensionWatcher = createExtensionFileWatcher({
210
+ logger,
211
+ rootDir,
212
+ extensionName,
213
+ extensionRoot,
214
+ watcherFactory,
215
+ onChange: async () => {
216
+ const prepared = await prepareDevExtension({ appUrl, extensionName, extensionRoot, reloadPort: reloadServer.port, rootDir, signal });
217
+ logger(`Regenerated Link Light dev wrapper for ${extensionName}: ${prepared.buildLabel}.`);
218
+ reloadServer.broadcastReload();
219
+ logger(`Notified Chrome to reload Link Light dev extension: ${extensionName}.`);
220
+ },
221
+ });
222
+ closers.push(async () => extensionWatcher.close());
223
+ }
224
+ }
225
+ if (!watchExtension) {
226
+ for (const extensionName of extensionNames)
227
+ await prepareDevExtension({ appUrl, extensionName, extensionRoot, rootDir, signal });
228
+ }
229
+ signal?.throwIfAborted();
230
+ let config = buildChromeLaunchConfig({ appUrl, argv, env, extensionNames, extensionRoot, platform, profileDir: preparedProfile.profileDir, rootDir });
231
+ if (!config.autoLoadSupported && !argv.includes("--no-auto-install")) {
232
+ try {
233
+ await chromeInstaller({ env, installRunner, logger, platform, rootDir, signal, stdio: "pipe" });
234
+ signal?.throwIfAborted();
235
+ const installedChromePath = findLocalChromeForTesting({ rootDir });
236
+ if (installedChromePath) {
237
+ config = buildChromeLaunchConfig({
238
+ argv,
239
+ appUrl,
240
+ env: { ...env, CHROME_FOR_TESTING_PATH: installedChromePath },
241
+ extensionNames,
242
+ extensionRoot,
243
+ platform,
244
+ profileDir: preparedProfile.profileDir,
245
+ rootDir,
246
+ });
247
+ }
248
+ }
249
+ catch (error) {
250
+ if (signal?.aborted)
251
+ throw error;
252
+ logger(`Chrome for Testing auto-install failed; continuing with manual extension loading in branded Chrome. ${error instanceof Error ? error.message : String(error)}`);
253
+ }
254
+ }
255
+ logger(`Loading Link Light Chrome extension from: ${extensionNames
256
+ .map((extensionName) => getProjectPaths(rootDir, extensionName, extensionRoot).extensionDir)
257
+ .join(", ")}`);
258
+ logger(`Using isolated Chrome profile: ${preparedProfile.profileDir}`);
259
+ const pinnedExtensionIds = await pinChromeExtensionsInProfile({
260
+ extensionDirs: config.launchExtensionDirs,
261
+ platform,
262
+ profileDir: preparedProfile.profileDir,
263
+ });
264
+ signal?.throwIfAborted();
265
+ logger(`Pinned Link Light extension toolbar ids in debug profile: ${pinnedExtensionIds.join(", ")}`);
266
+ if (config.autoLoadSupported) {
267
+ logger(`Using extension debug browser: ${config.chromePath}`);
268
+ }
269
+ else {
270
+ logger("");
271
+ logger("This Chrome build will not auto-load unpacked extensions from the command line.");
272
+ logger("Chrome 137+ branded builds ignore --load-extension for unpacked extensions.");
273
+ logger(`Open the Chrome window that just launched, click "Load unpacked", and select: ${config.manualLoadPath}`);
274
+ logger("Automatic Chrome for Testing setup did not produce a usable chrome executable.");
275
+ }
276
+ signal?.throwIfAborted();
277
+ const child = runner(config.chromePath, config.args, {
278
+ detached: true,
279
+ stdio: "ignore",
280
+ windowsHide: false,
281
+ });
282
+ child.unref();
283
+ return {
284
+ close,
285
+ keepAlive: withNext || watchExtension,
286
+ waitForShutdown: () => new Promise((resolve) => {
287
+ const shutdown = async () => {
288
+ process.off("SIGINT", shutdown);
289
+ process.off("SIGTERM", shutdown);
290
+ await close();
291
+ resolve();
292
+ };
293
+ process.on("SIGINT", shutdown);
294
+ process.on("SIGTERM", shutdown);
295
+ }),
296
+ };
297
+ }
298
+ catch (error) {
299
+ try {
300
+ await close();
301
+ }
302
+ catch (cleanupError) {
303
+ throw new AggregateError([error, cleanupError], "Extension startup and cleanup failed.");
304
+ }
305
+ throw error;
306
+ }
307
+ }
@@ -0,0 +1 @@
1
+ export declare function isMissingFile(error: unknown): boolean;
@@ -0,0 +1,3 @@
1
+ export function isMissingFile(error) {
2
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
3
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { packageChromeExtension } from "./package.js";
3
+ try {
4
+ await packageChromeExtension();
5
+ }
6
+ catch (error) {
7
+ console.error(error instanceof Error ? error.message : error);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,15 @@
1
+ interface PackageOptions {
2
+ argv?: string[];
3
+ rootDir?: string;
4
+ extensionRoot?: string;
5
+ extensionNames?: string[];
6
+ config?: unknown;
7
+ logger?: (message: string) => void;
8
+ }
9
+ export declare function packageChromeExtension({ argv, rootDir, extensionRoot, extensionNames, config, logger }?: PackageOptions): Promise<{
10
+ extensionName: string;
11
+ outputDir: string;
12
+ zipFile: string;
13
+ digest: string;
14
+ }[]>;
15
+ export {};
@@ -0,0 +1,203 @@
1
+ import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { calculateFileIntegritySync } from "@openge/forge-artifact-integrity/node";
4
+ import { assertExtensionRoot, assertExtensionTree, assertProjectOutput, assertSeparateExtensionOutput, assertValidExtensionName, getArgValue, getRequestedExtensions, getSharedAssetsRoot } from "./cli.js";
5
+ function requireString(config, key) {
6
+ const value = config[key];
7
+ if (typeof value !== "string" || value.trim().length === 0) {
8
+ throw new Error(`Missing extension.${key}`);
9
+ }
10
+ return value.trim();
11
+ }
12
+ function normalizeHttpsOrigin(value) {
13
+ let url;
14
+ try {
15
+ url = new URL(value);
16
+ }
17
+ catch {
18
+ throw new Error("extension.origin must be an https:// origin");
19
+ }
20
+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
21
+ throw new Error("extension.origin must be an https:// origin");
22
+ }
23
+ return url.origin;
24
+ }
25
+ function validatePackageConfig(config, rootDir) {
26
+ if (!config || typeof config !== "object" || Array.isArray(config))
27
+ throw new Error("Extension config must contain a JSON object");
28
+ const record = config;
29
+ return {
30
+ origin: normalizeHttpsOrigin(requireString(record, "origin")),
31
+ pluginToken: requireString(record, "pluginToken"),
32
+ outputDir: assertProjectOutput(rootDir, requireString(record, "outputDir")),
33
+ zipFile: assertProjectOutput(rootDir, requireString(record, "zipFile")),
34
+ };
35
+ }
36
+ function configForExtension(config, extensionName, count) {
37
+ if (count === 1)
38
+ return config;
39
+ return { ...config, outputDir: path.join(config.outputDir, extensionName), zipFile: path.join(path.dirname(config.zipFile), `${path.basename(config.zipFile, ".zip")}-${extensionName}.zip`) };
40
+ }
41
+ async function copyExtensionEntries(outputDir, extensionDir) {
42
+ await rm(outputDir, { recursive: true, force: true });
43
+ await mkdir(outputDir, { recursive: true });
44
+ for (const entry of [...(await readdir(extensionDir)).toSorted(), "shared"]) {
45
+ if (entry === "manifest.json" || entry === "link-light-extension-config.js")
46
+ continue;
47
+ const sourcePath = entry === "shared" ? getSharedAssetsRoot() : path.join(extensionDir, entry);
48
+ const targetPath = path.join(outputDir, entry);
49
+ await cp(sourcePath, targetPath, { recursive: true });
50
+ }
51
+ }
52
+ async function writePackagedManifest({ origin, outputDir, extensionDir }) {
53
+ const manifest = JSON.parse(await readFile(path.join(extensionDir, "manifest.json"), "utf8"));
54
+ const packagedManifest = {
55
+ ...manifest,
56
+ host_permissions: [`${origin}/*`],
57
+ };
58
+ await writeFile(path.join(outputDir, "manifest.json"), `${JSON.stringify(packagedManifest, null, 2)}\n`, "utf8");
59
+ }
60
+ async function writePackagedConfig({ origin, outputDir, pluginToken }) {
61
+ const payload = JSON.stringify({ origin, pluginToken });
62
+ await writeFile(path.join(outputDir, "link-light-extension-config.js"), `globalThis.LINK_LIGHT_CONFIG = ${payload};\n`, "utf8");
63
+ }
64
+ const crcTable = Array.from({ length: 256 }, (_unused, index) => {
65
+ let value = index;
66
+ for (let bit = 0; bit < 8; bit += 1) {
67
+ value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
68
+ }
69
+ return value >>> 0;
70
+ });
71
+ function crc32(buffer) {
72
+ let value = 0xffffffff;
73
+ for (const byte of buffer) {
74
+ value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
75
+ }
76
+ return (value ^ 0xffffffff) >>> 0;
77
+ }
78
+ function writeUInt16(value) {
79
+ const buffer = Buffer.alloc(2);
80
+ buffer.writeUInt16LE(value);
81
+ return buffer;
82
+ }
83
+ function writeUInt32(value) {
84
+ const buffer = Buffer.alloc(4);
85
+ buffer.writeUInt32LE(value);
86
+ return buffer;
87
+ }
88
+ async function listFiles(directory, baseDir = directory) {
89
+ const entries = await readdir(directory, { withFileTypes: true });
90
+ const files = [];
91
+ for (const entry of entries.toSorted((left, right) => left.name.localeCompare(right.name))) {
92
+ const entryPath = path.join(directory, entry.name);
93
+ if (entry.isDirectory()) {
94
+ files.push(...(await listFiles(entryPath, baseDir)));
95
+ continue;
96
+ }
97
+ if (entry.isFile()) {
98
+ files.push({
99
+ absolutePath: entryPath,
100
+ zipPath: path.relative(baseDir, entryPath).replaceAll(path.sep, "/"),
101
+ });
102
+ }
103
+ }
104
+ return files;
105
+ }
106
+ async function writeZipFile({ outputDir, zipFile }) {
107
+ const files = await listFiles(outputDir);
108
+ const localParts = [];
109
+ const centralParts = [];
110
+ let offset = 0;
111
+ for (const file of files) {
112
+ const data = await readFile(file.absolutePath);
113
+ const name = Buffer.from(file.zipPath);
114
+ const checksum = crc32(data);
115
+ const localHeader = Buffer.concat([
116
+ writeUInt32(0x04034b50),
117
+ writeUInt16(20),
118
+ writeUInt16(0),
119
+ writeUInt16(0),
120
+ writeUInt16(0),
121
+ writeUInt16(0x0021),
122
+ writeUInt32(checksum),
123
+ writeUInt32(data.length),
124
+ writeUInt32(data.length),
125
+ writeUInt16(name.length),
126
+ writeUInt16(0),
127
+ name,
128
+ ]);
129
+ const centralHeader = Buffer.concat([
130
+ writeUInt32(0x02014b50),
131
+ writeUInt16(20),
132
+ writeUInt16(20),
133
+ writeUInt16(0),
134
+ writeUInt16(0),
135
+ writeUInt16(0),
136
+ writeUInt16(0x0021),
137
+ writeUInt32(checksum),
138
+ writeUInt32(data.length),
139
+ writeUInt32(data.length),
140
+ writeUInt16(name.length),
141
+ writeUInt16(0),
142
+ writeUInt16(0),
143
+ writeUInt16(0),
144
+ writeUInt16(0),
145
+ writeUInt32(0),
146
+ writeUInt32(offset),
147
+ name,
148
+ ]);
149
+ localParts.push(localHeader, data);
150
+ centralParts.push(centralHeader);
151
+ offset += localHeader.length + data.length;
152
+ }
153
+ const centralDirectory = Buffer.concat(centralParts);
154
+ const endOfCentralDirectory = Buffer.concat([
155
+ writeUInt32(0x06054b50),
156
+ writeUInt16(0),
157
+ writeUInt16(0),
158
+ writeUInt16(files.length),
159
+ writeUInt16(files.length),
160
+ writeUInt32(centralDirectory.length),
161
+ writeUInt32(offset),
162
+ writeUInt16(0),
163
+ ]);
164
+ await mkdir(path.dirname(zipFile), { recursive: true });
165
+ await writeFile(zipFile, Buffer.concat([...localParts, centralDirectory, endOfCentralDirectory]));
166
+ }
167
+ async function packageSingleChromeExtension(config, extensionName, extensionRoot, rootDir, logger) {
168
+ const extensionDir = path.join(extensionRoot, extensionName);
169
+ await copyExtensionEntries(config.outputDir, extensionDir);
170
+ await writePackagedManifest({ ...config, extensionDir });
171
+ await writePackagedConfig(config);
172
+ await writeZipFile(config);
173
+ const digest = calculateFileIntegritySync(config.zipFile).sha256.slice(0, 12);
174
+ logger(`Packaged Link Light Chrome extension ${extensionName}: ${path.relative(rootDir, config.zipFile)} (${digest})`);
175
+ return { extensionName, outputDir: config.outputDir, zipFile: config.zipFile, digest };
176
+ }
177
+ export async function packageChromeExtension({ argv = process.argv.slice(2), rootDir = process.cwd(), extensionRoot, extensionNames, config, logger = console.log } = {}) {
178
+ extensionRoot = assertExtensionRoot(rootDir, extensionRoot ?? getArgValue(argv, "--extension-root"));
179
+ extensionNames ??= getRequestedExtensions(argv, rootDir);
180
+ if (!Array.isArray(extensionNames) || !extensionNames.length || new Set(extensionNames).size !== extensionNames.length)
181
+ throw new Error("EXTENSION_SELECTION_REQUIRED");
182
+ for (const extensionName of extensionNames) {
183
+ assertValidExtensionName(extensionName);
184
+ assertExtensionTree(path.join(extensionRoot, extensionName));
185
+ }
186
+ config ??= JSON.parse(await readFile(path.join(rootDir, "config", "local", "extension.local.json"), "utf8"));
187
+ const validated = validatePackageConfig(config, rootDir);
188
+ for (const name of extensionNames) {
189
+ const source = path.join(extensionRoot, name);
190
+ assertSeparateExtensionOutput(source, validated.outputDir);
191
+ assertSeparateExtensionOutput(source, validated.zipFile);
192
+ }
193
+ if (validated.zipFile === validated.outputDir || validated.zipFile.startsWith(validated.outputDir + path.sep))
194
+ throw new Error("EXTENSION_OUTPUT_OVERLAP");
195
+ const results = [];
196
+ for (const name of extensionNames) {
197
+ const selected = configForExtension(validated, name, extensionNames.length);
198
+ assertProjectOutput(rootDir, selected.outputDir);
199
+ assertProjectOutput(rootDir, selected.zipFile);
200
+ results.push(await packageSingleChromeExtension(selected, name, extensionRoot, rootDir, logger));
201
+ }
202
+ return results;
203
+ }
@@ -0,0 +1,34 @@
1
+ import { rm } from "node:fs/promises";
2
+ interface ProfileOptions {
3
+ extensionName?: string;
4
+ extensionNames?: string[];
5
+ extensionRoot?: string;
6
+ rootDir?: string;
7
+ }
8
+ interface ChromePreferences {
9
+ [name: string]: unknown;
10
+ extensions?: {
11
+ [name: string]: unknown;
12
+ pinned_extensions?: unknown[];
13
+ };
14
+ }
15
+ export declare function readJsonFileIfExists(filePath: string): Promise<ChromePreferences>;
16
+ export declare function pinChromeExtensionsInProfile({ extensionDirs, platform, profileDir, }: {
17
+ extensionDirs: readonly string[];
18
+ platform?: NodeJS.Platform;
19
+ profileDir: string;
20
+ }): Promise<string[]>;
21
+ export declare function getExtensionLaunchSignature(rootDir: string, extensionNames: readonly string[], extensionRoot: string | undefined): Promise<string>;
22
+ export declare function getProfileStateFile(rootDir: string, extensionNames: readonly string[], extensionRoot: string | undefined): string;
23
+ export declare function readProfileSignature(stateFile: string): Promise<string | null>;
24
+ export declare function writeProfileSignature(profileDir: string, extensionLaunchSignature: string): Promise<void>;
25
+ export declare function resetChromeProfile({ profileDir, remover, rootDir, extensionName, extensionRoot, extensionNames, }?: ProfileOptions & {
26
+ remover?: typeof rm;
27
+ profileDir?: string;
28
+ }): Promise<void>;
29
+ export declare function ensureFreshChromeProfileForExtension({ extensionName, extensionRoot, extensionNames, logger, rootDir, }?: ProfileOptions & {
30
+ logger?: (message: string) => void;
31
+ }): Promise<{
32
+ profileDir: string;
33
+ }>;
34
+ export {};