@xlinklight/browser-extension-tools 1.0.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 (69) hide show
  1. package/dist/assets/shared/js/chrome-runtime.js +79 -0
  2. package/dist/assets/shared/js/extension-account-menu.js +212 -0
  3. package/dist/assets/shared/js/extension-i18n.js +35 -0
  4. package/dist/assets/shared/js/extension-session-store.js +40 -0
  5. package/dist/assets/shared/js/extension-tabs.js +27 -0
  6. package/dist/assets/shared/js/link-light-api-client.js +30 -0
  7. package/dist/assets/shared/js/side-panel-account.js +14 -0
  8. package/dist/assets/shared/js/side-panel-api.js +13 -0
  9. package/dist/assets/shared/js/side-panel-bootstrap.js +97 -0
  10. package/dist/assets/shared/js/side-panel-dom.js +14 -0
  11. package/dist/assets/shared/js/side-panel-i18n.js +34 -0
  12. package/dist/assets/shared/js/side-panel-import-preview.js +7 -0
  13. package/dist/assets/shared/js/side-panel-status.js +12 -0
  14. package/dist/assets/shared/js/side-panel-tabs.js +29 -0
  15. package/dist/assets/shared/js/side-panel-translations.js +30 -0
  16. package/dist/src/chrome-discovery.d.ts +57 -0
  17. package/dist/src/chrome-discovery.js +178 -0
  18. package/dist/src/chrome-for-testing.d.ts +66 -0
  19. package/dist/src/chrome-for-testing.js +157 -0
  20. package/dist/src/chrome-install-worker.d.ts +1 -0
  21. package/dist/src/chrome-install-worker.js +8 -0
  22. package/dist/src/cli.d.ts +41 -0
  23. package/dist/src/cli.js +189 -0
  24. package/dist/src/dev-cli.d.ts +2 -0
  25. package/dist/src/dev-cli.js +11 -0
  26. package/dist/src/dev-extension.d.ts +51 -0
  27. package/dist/src/dev-extension.js +307 -0
  28. package/dist/src/fs-error.d.ts +1 -0
  29. package/dist/src/fs-error.js +3 -0
  30. package/dist/src/package-cli.d.ts +2 -0
  31. package/dist/src/package-cli.js +9 -0
  32. package/dist/src/package.d.ts +15 -0
  33. package/dist/src/package.js +203 -0
  34. package/dist/src/profile.d.ts +34 -0
  35. package/dist/src/profile.js +105 -0
  36. package/dist/src/reload-server.d.ts +14 -0
  37. package/dist/src/reload-server.js +96 -0
  38. package/{src/run.mjs → dist/src/run.d.ts} +7 -7
  39. package/dist/src/run.js +7 -0
  40. package/dist/src/watcher.d.ts +17 -0
  41. package/dist/src/watcher.js +30 -0
  42. package/package.json +33 -11
  43. package/assets/shared/js/chrome-runtime.js +0 -87
  44. package/assets/shared/js/extension-account-menu.js +0 -239
  45. package/assets/shared/js/extension-i18n.js +0 -42
  46. package/assets/shared/js/extension-session-store.js +0 -42
  47. package/assets/shared/js/extension-tabs.js +0 -23
  48. package/assets/shared/js/link-light-api-client.js +0 -31
  49. package/assets/shared/js/side-panel-account.js +0 -14
  50. package/assets/shared/js/side-panel-api.js +0 -13
  51. package/assets/shared/js/side-panel-bootstrap.js +0 -127
  52. package/assets/shared/js/side-panel-dom.js +0 -15
  53. package/assets/shared/js/side-panel-i18n.js +0 -37
  54. package/assets/shared/js/side-panel-import-preview.js +0 -7
  55. package/assets/shared/js/side-panel-status.js +0 -13
  56. package/assets/shared/js/side-panel-tabs.js +0 -35
  57. package/assets/shared/js/side-panel-translations.js +0 -41
  58. package/src/chrome-discovery.mjs +0 -231
  59. package/src/chrome-for-testing.mjs +0 -203
  60. package/src/chrome-install-worker.mjs +0 -8
  61. package/src/cli.mjs +0 -171
  62. package/src/dev-cli.mjs +0 -9
  63. package/src/dev-extension.mjs +0 -350
  64. package/src/package-cli.mjs +0 -7
  65. package/src/package.mjs +0 -223
  66. package/src/profile.mjs +0 -144
  67. package/src/reload-server.mjs +0 -108
  68. package/src/watcher.mjs +0 -45
  69. /package/{assets → dist/assets}/shared/css/side-panel.css +0 -0
@@ -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 {};
@@ -0,0 +1,105 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { 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 { assertProjectOutput, getProfileDirForExtensions, getRelevantExtensionFiles, getRelevantExtensionSourcePath, profileStateFileName } from "./cli.js";
7
+ import { getChromeExtensionIdForPath, samePath } from "./chrome-discovery.js";
8
+ async function readFileIfExists(filePath) {
9
+ try {
10
+ const stats = await stat(filePath);
11
+ if (stats.isDirectory()) {
12
+ const names = (await readdir(filePath)).toSorted();
13
+ return Buffer.concat(await Promise.all(names.map(async (name) => Buffer.concat([Buffer.from(name + "\0"), Buffer.from(await readFileIfExists(path.join(filePath, name)))]))));
14
+ }
15
+ return await readFile(filePath);
16
+ }
17
+ catch (error) {
18
+ if (isMissingFile(error))
19
+ return "";
20
+ throw error;
21
+ }
22
+ }
23
+ export async function readJsonFileIfExists(filePath) {
24
+ try {
25
+ return JSON.parse(await readFile(filePath, "utf8"));
26
+ }
27
+ catch (error) {
28
+ if (isMissingFile(error)) {
29
+ return {};
30
+ }
31
+ throw error;
32
+ }
33
+ }
34
+ export async function pinChromeExtensionsInProfile({ extensionDirs, platform = process.platform, profileDir, }) {
35
+ const defaultProfileDir = path.join(profileDir, "Default");
36
+ const preferencesPath = path.join(defaultProfileDir, "Preferences");
37
+ const preferences = await readJsonFileIfExists(preferencesPath);
38
+ const pinnedExtensionIds = extensionDirs.map((extensionDir) => getChromeExtensionIdForPath(extensionDir, { platform }));
39
+ const existingPinnedExtensionIds = Array.isArray(preferences.extensions?.pinned_extensions)
40
+ ? preferences.extensions.pinned_extensions
41
+ : [];
42
+ preferences.extensions = {
43
+ ...(preferences.extensions ?? {}),
44
+ pinned_extensions: [...new Set([...existingPinnedExtensionIds, ...pinnedExtensionIds])],
45
+ };
46
+ await mkdir(defaultProfileDir, { recursive: true });
47
+ await writeFile(preferencesPath, `${JSON.stringify(preferences)}\n`, "utf8");
48
+ return [...new Set(pinnedExtensionIds)];
49
+ }
50
+ export async function getExtensionLaunchSignature(rootDir, extensionNames, extensionRoot) {
51
+ const hash = createHash("sha256");
52
+ for (const extensionName of extensionNames) {
53
+ hash.update(extensionName);
54
+ hash.update("\0");
55
+ for (const fileName of getRelevantExtensionFiles(rootDir, extensionName, extensionRoot)) {
56
+ hash.update(fileName);
57
+ hash.update("\0");
58
+ hash.update(await readFileIfExists(getRelevantExtensionSourcePath(rootDir, extensionName, fileName, extensionRoot)));
59
+ hash.update("\0");
60
+ }
61
+ }
62
+ return hash.digest("hex");
63
+ }
64
+ export function getProfileStateFile(rootDir, extensionNames, extensionRoot) {
65
+ return path.join(getProfileDirForExtensions(rootDir, extensionNames, extensionRoot), profileStateFileName);
66
+ }
67
+ export async function readProfileSignature(stateFile) {
68
+ try {
69
+ return JSON.parse(await readFile(stateFile, "utf8"))?.extensionLaunchSignature ?? null;
70
+ }
71
+ catch (error) {
72
+ if (isMissingFile(error)) {
73
+ return null;
74
+ }
75
+ throw error;
76
+ }
77
+ }
78
+ export async function writeProfileSignature(profileDir, extensionLaunchSignature) {
79
+ await mkdir(profileDir, { recursive: true });
80
+ await writeFile(path.join(profileDir, profileStateFileName), `${JSON.stringify({ extensionLaunchSignature }, null, 2)}\n`, "utf8");
81
+ }
82
+ export async function resetChromeProfile({ profileDir, remover = rm, rootDir = process.cwd(), extensionName, extensionRoot, extensionNames = extensionName === undefined ? [] : [extensionName], } = {}) {
83
+ const expectedProfileDir = getProfileDirForExtensions(rootDir, extensionNames, extensionRoot);
84
+ assertProjectOutput(rootDir, expectedProfileDir);
85
+ const targetProfileDir = profileDir ?? expectedProfileDir;
86
+ if (!samePath(targetProfileDir, expectedProfileDir)) {
87
+ throw new Error(`Refusing to reset Chrome profile outside ${expectedProfileDir}`);
88
+ }
89
+ await remover(expectedProfileDir, { recursive: true, force: true });
90
+ }
91
+ export async function ensureFreshChromeProfileForExtension({ extensionName, extensionRoot, extensionNames = extensionName === undefined ? [] : [extensionName], logger = console.log, rootDir = process.cwd(), } = {}) {
92
+ const profileDir = getProfileDirForExtensions(rootDir, extensionNames, extensionRoot);
93
+ assertProjectOutput(rootDir, profileDir);
94
+ const stateFile = getProfileStateFile(rootDir, extensionNames, extensionRoot);
95
+ const nextSignature = await getExtensionLaunchSignature(rootDir, extensionNames, extensionRoot);
96
+ const previousSignature = await readProfileSignature(stateFile);
97
+ if (previousSignature && previousSignature !== nextSignature) {
98
+ logger(`Extension launch signature changed; kept existing Chrome extension debug profile: ${profileDir}. Run with --reset-profile if manifest or permission state looks stale.`);
99
+ }
100
+ else if (!previousSignature && existsSync(profileDir)) {
101
+ logger(`Legacy Chrome extension debug profile detected; kept existing Chrome extension debug profile: ${profileDir}. Run with --reset-profile if manifest or permission state looks stale.`);
102
+ }
103
+ await writeProfileSignature(profileDir, nextSignature);
104
+ return { profileDir };
105
+ }
@@ -0,0 +1,14 @@
1
+ export declare function addUniqueItems<T>(items: readonly T[] | undefined, additions: readonly T[]): T[];
2
+ export declare function buildDevReloadClient({ reloadPort }: {
3
+ reloadPort: number;
4
+ }): string;
5
+ export declare function encodeWebSocketTextFrame(text: string): Buffer<ArrayBuffer>;
6
+ export declare function createDevReloadServer({ host, logger, port }?: {
7
+ host?: string | undefined;
8
+ logger?: ((...data: any[]) => void) | undefined;
9
+ port?: number | undefined;
10
+ }): Promise<{
11
+ port: number;
12
+ broadcastReload: () => void;
13
+ close: () => Promise<void>;
14
+ }>;
@@ -0,0 +1,96 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ export function addUniqueItems(items, additions) {
4
+ return [...new Set([...(items ?? []), ...additions])];
5
+ }
6
+ export function buildDevReloadClient({ reloadPort }) {
7
+ return `(() => {
8
+ const reloadSocketUrl = "ws://127.0.0.1:${reloadPort}";
9
+
10
+ function connect() {
11
+ const socket = new WebSocket(reloadSocketUrl);
12
+ socket.addEventListener("message", (event) => {
13
+ try {
14
+ const message = JSON.parse(event.data);
15
+ if (message?.type !== "reload") return;
16
+ chrome.runtime.reload();
17
+ } catch {
18
+ // Ignore malformed dev-server messages.
19
+ }
20
+ });
21
+ socket.addEventListener("close", () => setTimeout(connect, 1000));
22
+ socket.addEventListener("error", () => socket.close());
23
+ }
24
+
25
+ connect();
26
+ })();
27
+ `;
28
+ }
29
+ export function encodeWebSocketTextFrame(text) {
30
+ const payload = Buffer.from(text);
31
+ if (payload.length < 126) {
32
+ return Buffer.concat([Buffer.from([0x81, payload.length]), payload]);
33
+ }
34
+ if (payload.length <= 0xffff) {
35
+ const header = Buffer.alloc(4);
36
+ header[0] = 0x81;
37
+ header[1] = 126;
38
+ header.writeUInt16BE(payload.length, 2);
39
+ return Buffer.concat([header, payload]);
40
+ }
41
+ const header = Buffer.alloc(10);
42
+ header[0] = 0x81;
43
+ header[1] = 127;
44
+ header.writeBigUInt64BE(BigInt(payload.length), 2);
45
+ return Buffer.concat([header, payload]);
46
+ }
47
+ export async function createDevReloadServer({ host = "127.0.0.1", logger = console.log, port = 0 } = {}) {
48
+ const clients = new Set();
49
+ const server = createServer();
50
+ server.on("upgrade", (request, socket) => {
51
+ const key = request.headers["sec-websocket-key"];
52
+ if (!key) {
53
+ socket.destroy();
54
+ return;
55
+ }
56
+ const accept = createHash("sha1")
57
+ .update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`)
58
+ .digest("base64");
59
+ socket.write([
60
+ "HTTP/1.1 101 Switching Protocols",
61
+ "Upgrade: websocket",
62
+ "Connection: Upgrade",
63
+ `Sec-WebSocket-Accept: ${accept}`,
64
+ "",
65
+ "",
66
+ ].join("\r\n"));
67
+ clients.add(socket);
68
+ socket.on("close", () => clients.delete(socket));
69
+ socket.on("error", () => clients.delete(socket));
70
+ });
71
+ await new Promise((resolve, reject) => {
72
+ server.once("error", reject);
73
+ server.listen(port, host, () => {
74
+ server.off("error", reject);
75
+ resolve();
76
+ });
77
+ });
78
+ const address = server.address();
79
+ const selectedPort = typeof address === "object" && address ? address.port : port;
80
+ logger(`Extension dev reload server listening on ws://${host}:${selectedPort}`);
81
+ return {
82
+ port: selectedPort,
83
+ broadcastReload: () => {
84
+ const frame = encodeWebSocketTextFrame(JSON.stringify({ type: "reload" }));
85
+ for (const client of clients) {
86
+ client.write(frame);
87
+ }
88
+ },
89
+ close: () => new Promise((resolve, reject) => {
90
+ for (const client of clients) {
91
+ client.destroy();
92
+ }
93
+ server.close((error) => (error ? reject(error) : resolve()));
94
+ }),
95
+ };
96
+ }
@@ -1,7 +1,7 @@
1
- export * from "./cli.mjs";
2
- export { buildChromeLaunchConfig, findChromePath, findLocalChromeForTesting, getChromeExtensionIdForPath } from "./chrome-discovery.mjs";
3
- export { getChromeForTestingInstallStep, installChromeForTesting } from "./chrome-for-testing.mjs";
4
- export { prepareDevExtension, runChromeExtensionDev } from "./dev-extension.mjs";
5
- export { ensureFreshChromeProfileForExtension, pinChromeExtensionsInProfile, resetChromeProfile } from "./profile.mjs";
6
- export { createDevReloadServer } from "./reload-server.mjs";
7
- export { createExtensionFileWatcher } from "./watcher.mjs";
1
+ export * from "./cli.js";
2
+ export { buildChromeLaunchConfig, findChromePath, findLocalChromeForTesting, getChromeExtensionIdForPath } from "./chrome-discovery.js";
3
+ export { getChromeForTestingInstallStep, installChromeForTesting } from "./chrome-for-testing.js";
4
+ export { prepareDevExtension, runChromeExtensionDev } from "./dev-extension.js";
5
+ export { ensureFreshChromeProfileForExtension, pinChromeExtensionsInProfile, resetChromeProfile } from "./profile.js";
6
+ export { createDevReloadServer } from "./reload-server.js";
7
+ export { createExtensionFileWatcher } from "./watcher.js";
@@ -0,0 +1,7 @@
1
+ export * from "./cli.js";
2
+ export { buildChromeLaunchConfig, findChromePath, findLocalChromeForTesting, getChromeExtensionIdForPath } from "./chrome-discovery.js";
3
+ export { getChromeForTestingInstallStep, installChromeForTesting } from "./chrome-for-testing.js";
4
+ export { prepareDevExtension, runChromeExtensionDev } from "./dev-extension.js";
5
+ export { ensureFreshChromeProfileForExtension, pinChromeExtensionsInProfile, resetChromeProfile } from "./profile.js";
6
+ export { createDevReloadServer } from "./reload-server.js";
7
+ export { createExtensionFileWatcher } from "./watcher.js";
@@ -0,0 +1,17 @@
1
+ interface WatchOptions {
2
+ clearTimeoutFn?: typeof clearTimeout;
3
+ setTimeoutFn?: typeof setTimeout;
4
+ debounceMs?: number;
5
+ logger?: (message: string) => void;
6
+ onChange: () => void | Promise<void>;
7
+ rootDir?: string;
8
+ extensionName: string;
9
+ extensionRoot?: string;
10
+ watcherFactory?: (sourcePath: string, listener: () => void) => {
11
+ close(): void;
12
+ };
13
+ }
14
+ export declare function createExtensionFileWatcher({ clearTimeoutFn, debounceMs, logger, onChange, rootDir, extensionName, extensionRoot, setTimeoutFn, watcherFactory, }: WatchOptions): {
15
+ close: () => void;
16
+ };
17
+ export {};
@@ -0,0 +1,30 @@
1
+ import { watch } from "node:fs";
2
+ import { getExistingRelevantExtensionSourcePaths } from "./cli.js";
3
+ export function createExtensionFileWatcher({ clearTimeoutFn = clearTimeout, debounceMs = 100, logger = console.log, onChange, rootDir = process.cwd(), extensionName, extensionRoot, setTimeoutFn = setTimeout, watcherFactory = watch, }) {
4
+ let pendingTimer = null;
5
+ function scheduleReload() {
6
+ if (pendingTimer) {
7
+ clearTimeoutFn(pendingTimer);
8
+ }
9
+ pendingTimer = setTimeoutFn(async () => {
10
+ pendingTimer = null;
11
+ try {
12
+ await onChange();
13
+ }
14
+ catch (error) {
15
+ logger(error instanceof Error ? error.message : String(error));
16
+ }
17
+ }, debounceMs);
18
+ }
19
+ const watchers = getExistingRelevantExtensionSourcePaths(rootDir, extensionName, extensionRoot).map((sourcePath) => watcherFactory(sourcePath, scheduleReload));
20
+ return {
21
+ close: () => {
22
+ if (pendingTimer) {
23
+ clearTimeoutFn(pendingTimer);
24
+ }
25
+ for (const fileWatcher of watchers) {
26
+ fileWatcher.close();
27
+ }
28
+ },
29
+ };
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xlinklight/browser-extension-tools",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -15,20 +15,41 @@
15
15
  "type": "module",
16
16
  "private": false,
17
17
  "files": [
18
- "src",
19
- "assets",
18
+ "dist/src",
19
+ "dist/assets",
20
20
  "README.md"
21
21
  ],
22
22
  "bin": {
23
- "link-light-extension-dev": "src/dev-cli.mjs",
24
- "link-light-extension-package": "src/package-cli.mjs"
23
+ "link-light-extension-dev": "dist/src/dev-cli.js",
24
+ "link-light-extension-package": "dist/src/package-cli.js"
25
25
  },
26
26
  "exports": {
27
- "./dev": "./src/run.mjs",
28
- "./cli": "./src/cli.mjs",
29
- "./package": "./src/package.mjs",
30
- "./installer": "./src/chrome-for-testing.mjs",
31
- "./shared/*": "./assets/shared/*"
27
+ "./dev": {
28
+ "types": "./dist/src/run.d.ts",
29
+ "import": "./dist/src/run.js",
30
+ "default": "./dist/src/run.js"
31
+ },
32
+ "./cli": {
33
+ "types": "./dist/src/cli.d.ts",
34
+ "import": "./dist/src/cli.js",
35
+ "default": "./dist/src/cli.js"
36
+ },
37
+ "./package": {
38
+ "types": "./dist/src/package.d.ts",
39
+ "import": "./dist/src/package.js",
40
+ "default": "./dist/src/package.js"
41
+ },
42
+ "./installer": {
43
+ "types": "./dist/src/chrome-for-testing.d.ts",
44
+ "import": "./dist/src/chrome-for-testing.js",
45
+ "default": "./dist/src/chrome-for-testing.js"
46
+ },
47
+ "./shared/*": "./dist/assets/shared/*"
48
+ },
49
+ "devDependencies": {
50
+ "@testing-library/jest-dom": "^6.9.1",
51
+ "jsdom": "^29.1.1",
52
+ "vitest": "^4.1.9"
32
53
  },
33
54
  "dependencies": {
34
55
  "@openge/forge-artifact-integrity": "0.1.0",
@@ -39,6 +60,7 @@
39
60
  "node": ">=22.14.0"
40
61
  },
41
62
  "scripts": {
42
- "test": "node --test tests/*.test.mjs"
63
+ "build": "tsc -p tsconfig.build.json && tsc -p tsconfig.assets.json && node dist/scripts/copy-assets.js",
64
+ "test": "pnpm run build && tsc -p tsconfig.tests.json && node --test dist/tests/public-api.test.js && vitest run --config vitest.config.ts"
43
65
  }
44
66
  }