extension-develop 3.12.0 → 3.13.0
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.
- package/README.md +1 -1
- package/dist/{890.cjs → 264.cjs} +179 -4770
- package/dist/324.cjs +21 -3
- package/dist/extension-js-devtools/chrome/background/service_worker.js +1 -1
- package/dist/extension-js-devtools/chromium/background/service_worker.js +1 -1
- package/dist/extension-js-devtools/edge/background/service_worker.js +1 -1
- package/dist/extension-js-devtools/firefox/background/scripts.js +1 -1
- package/dist/module.cjs +349 -5644
- package/dist/preview.cjs +1461 -0
- package/package.json +10 -12
- package/dist/215.cjs +0 -849
- package/dist/323.cjs +0 -1100
- package/webpack/webpack-lib/build-dependencies.json +0 -24
package/dist/323.cjs
DELETED
|
@@ -1,1100 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
exports.ids = [
|
|
3
|
-
"323"
|
|
4
|
-
];
|
|
5
|
-
exports.modules = {
|
|
6
|
-
"./webpack/plugin-browsers/run-chromium/chromium-launch/setup-cdp-after-launch.ts" (__unused_rspack_module, __webpack_exports__, __webpack_require__) {
|
|
7
|
-
__webpack_require__.d(__webpack_exports__, {
|
|
8
|
-
setupCdpAfterLaunch: ()=>setupCdpAfterLaunch
|
|
9
|
-
});
|
|
10
|
-
var messages = __webpack_require__("./webpack/plugin-browsers/browsers-lib/messages.ts");
|
|
11
|
-
var shared_utils = __webpack_require__("./webpack/plugin-browsers/browsers-lib/shared-utils.ts");
|
|
12
|
-
var banner = __webpack_require__("./webpack/plugin-browsers/browsers-lib/banner.ts");
|
|
13
|
-
var external_path_ = __webpack_require__("path");
|
|
14
|
-
var external_fs_ = __webpack_require__("fs");
|
|
15
|
-
var content_script_targets = __webpack_require__("./webpack/plugin-browsers/browsers-lib/content-script-targets.ts");
|
|
16
|
-
var contracts = __webpack_require__("./webpack/plugin-web-extension/feature-scripts/contracts.ts");
|
|
17
|
-
async function deriveExtensionIdFromTargetsHelper(cdp, outPath, maxRetries = 6, backoffMs = 150, profilePath, extensionPaths) {
|
|
18
|
-
let expectedName;
|
|
19
|
-
let expectedVersion;
|
|
20
|
-
let expectedManifestVersion;
|
|
21
|
-
let expectedNameIsMsg = false;
|
|
22
|
-
try {
|
|
23
|
-
const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(outPath, 'manifest.json'), 'utf-8'));
|
|
24
|
-
expectedName = manifest?.name;
|
|
25
|
-
expectedVersion = manifest?.version;
|
|
26
|
-
expectedManifestVersion = manifest?.manifest_version;
|
|
27
|
-
expectedNameIsMsg = 'string' == typeof expectedName && /__MSG_/i.test(expectedName);
|
|
28
|
-
if (expectedNameIsMsg) {
|
|
29
|
-
const defaultLocale = String(manifest?.default_locale || '').trim();
|
|
30
|
-
const msgKeyMatch = String(expectedName || '').match(/__MSG_(.+)__/i);
|
|
31
|
-
const msgKey = msgKeyMatch ? msgKeyMatch[1] : '';
|
|
32
|
-
if (defaultLocale && msgKey) {
|
|
33
|
-
const messagesPath = external_path_.join(outPath, '_locales', defaultLocale, 'messages.json');
|
|
34
|
-
if (external_fs_.existsSync(messagesPath)) {
|
|
35
|
-
const messagesJson = JSON.parse(external_fs_.readFileSync(messagesPath, 'utf-8'));
|
|
36
|
-
const resolved = String(messagesJson?.[msgKey]?.message || '').trim();
|
|
37
|
-
if (resolved) {
|
|
38
|
-
expectedName = resolved;
|
|
39
|
-
expectedNameIsMsg = false;
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
} catch {}
|
|
45
|
-
const trimTrailingSep = (p)=>p.replace(/[\\\/]+$/g, '');
|
|
46
|
-
const normalizePath = (p)=>{
|
|
47
|
-
try {
|
|
48
|
-
const resolved = external_path_.resolve(p);
|
|
49
|
-
if (external_fs_.existsSync(resolved)) return trimTrailingSep(external_fs_.realpathSync(resolved));
|
|
50
|
-
return trimTrailingSep(resolved);
|
|
51
|
-
} catch {
|
|
52
|
-
return trimTrailingSep(external_path_.resolve(p));
|
|
53
|
-
}
|
|
54
|
-
};
|
|
55
|
-
const resolvedOutPath = normalizePath(outPath);
|
|
56
|
-
const normalizedCandidates = Array.isArray(extensionPaths) ? extensionPaths.map((p)=>p ? normalizePath(p) : '').filter(Boolean) : [];
|
|
57
|
-
const resolvedCandidates = normalizedCandidates.length ? normalizedCandidates : [
|
|
58
|
-
resolvedOutPath
|
|
59
|
-
];
|
|
60
|
-
const platformIsCaseInsensitive = 'win32' === process.platform || 'darwin' === process.platform;
|
|
61
|
-
const normalizeForCompare = (p)=>platformIsCaseInsensitive ? p.toLowerCase() : p;
|
|
62
|
-
const matchesAnyCandidate = (p)=>{
|
|
63
|
-
const n = normalizeForCompare(p);
|
|
64
|
-
return resolvedCandidates.some((candidate)=>n === normalizeForCompare(candidate));
|
|
65
|
-
};
|
|
66
|
-
const deriveFromProfile = ()=>{
|
|
67
|
-
if (!profilePath) return null;
|
|
68
|
-
const candidates = [];
|
|
69
|
-
const pushPrefIfExists = (dir)=>{
|
|
70
|
-
const prefPath = external_path_.join(dir, 'Preferences');
|
|
71
|
-
if (external_fs_.existsSync(prefPath)) candidates.push(prefPath);
|
|
72
|
-
};
|
|
73
|
-
try {
|
|
74
|
-
pushPrefIfExists(profilePath);
|
|
75
|
-
pushPrefIfExists(external_path_.join(profilePath, 'Default'));
|
|
76
|
-
const entries = external_fs_.readdirSync(profilePath);
|
|
77
|
-
for (const entry of entries)if (/^Profile\s+\d+$/i.test(entry)) pushPrefIfExists(external_path_.join(profilePath, entry));
|
|
78
|
-
} catch {}
|
|
79
|
-
for (const prefPath of candidates)try {
|
|
80
|
-
if (!external_fs_.existsSync(prefPath)) continue;
|
|
81
|
-
const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
|
|
82
|
-
const settings = prefs?.extensions?.settings;
|
|
83
|
-
if (!settings || 'object' != typeof settings) continue;
|
|
84
|
-
const entries = Object.entries(settings);
|
|
85
|
-
let fallbackId = null;
|
|
86
|
-
for (const [id, info] of entries){
|
|
87
|
-
const storedPath = String(info?.path || '');
|
|
88
|
-
if (!storedPath) continue;
|
|
89
|
-
const normalized = normalizePath(storedPath);
|
|
90
|
-
if (!matchesAnyCandidate(normalized)) continue;
|
|
91
|
-
const manifestName = String(info?.manifest?.name || '');
|
|
92
|
-
const manifestVersion = String(info?.manifest?.version || '');
|
|
93
|
-
if (expectedName && manifestName === expectedName) return id;
|
|
94
|
-
if (expectedVersion && manifestVersion === expectedVersion) return id;
|
|
95
|
-
fallbackId = id;
|
|
96
|
-
}
|
|
97
|
-
if (fallbackId) return fallbackId;
|
|
98
|
-
} catch {}
|
|
99
|
-
return null;
|
|
100
|
-
};
|
|
101
|
-
let retries = 0;
|
|
102
|
-
let deferredFirstEvalId = null;
|
|
103
|
-
let deferredUrlDerivedId = null;
|
|
104
|
-
const hasExpectedManifestIdentity = Boolean(expectedName || expectedVersion || expectedManifestVersion);
|
|
105
|
-
while(retries <= maxRetries){
|
|
106
|
-
try {
|
|
107
|
-
const targets = await cdp.getTargets();
|
|
108
|
-
const profileCandidateId = deriveFromProfile();
|
|
109
|
-
let firstEvalId = null;
|
|
110
|
-
let evalIdCount = 0;
|
|
111
|
-
let urlDerivedId = null;
|
|
112
|
-
for (const t of targets || []){
|
|
113
|
-
const url = String(t?.url || '');
|
|
114
|
-
const type = String(t?.type || '');
|
|
115
|
-
const typeOk = [
|
|
116
|
-
'service_worker',
|
|
117
|
-
'background_page',
|
|
118
|
-
'worker'
|
|
119
|
-
].includes(type);
|
|
120
|
-
if (!typeOk) continue;
|
|
121
|
-
const urlMatch = url.match(/^chrome-extension:\/\/([^\/]+)/);
|
|
122
|
-
if (!urlDerivedId && urlMatch?.[1]) urlDerivedId = String(urlMatch[1]);
|
|
123
|
-
if (url && !url.startsWith('chrome-extension://')) continue;
|
|
124
|
-
const targetId = t?.targetId;
|
|
125
|
-
if (targetId) try {
|
|
126
|
-
const sessionId = await cdp.attachToTarget(targetId);
|
|
127
|
-
if (!sessionId) continue;
|
|
128
|
-
await cdp.sendCommand('Runtime.enable', {}, sessionId);
|
|
129
|
-
const info = await cdp.evaluate(sessionId, '(()=>{try{const m=chrome.runtime.getManifest?.();return {id:chrome.runtime?.id||"",name:m?.name||"",version:m?.version||"",manifestVersion:m?.manifest_version||0}}catch(_){return null}})()');
|
|
130
|
-
const id = String(info?.id || '').trim();
|
|
131
|
-
if (!id) continue;
|
|
132
|
-
evalIdCount += 1;
|
|
133
|
-
if (!firstEvalId) firstEvalId = id;
|
|
134
|
-
if (profileCandidateId && id === profileCandidateId) return id;
|
|
135
|
-
const gotName = String(info?.name || '');
|
|
136
|
-
const gotVersion = String(info?.version || '');
|
|
137
|
-
const gotManifestVersion = Number(info?.manifestVersion || 0);
|
|
138
|
-
const nameMatches = expectedName && !expectedNameIsMsg ? gotName === expectedName : false;
|
|
139
|
-
const versionMatches = expectedVersion ? gotVersion === expectedVersion : false;
|
|
140
|
-
const manifestVersionMatches = expectedManifestVersion ? gotManifestVersion === expectedManifestVersion : false;
|
|
141
|
-
if (nameMatches && (!profileCandidateId || id === profileCandidateId)) return id;
|
|
142
|
-
if (expectedVersion && versionMatches && (expectedManifestVersion ? manifestVersionMatches : true) && (!profileCandidateId || id === profileCandidateId)) return id;
|
|
143
|
-
} catch {}
|
|
144
|
-
}
|
|
145
|
-
if (1 === evalIdCount && firstEvalId) {
|
|
146
|
-
if (!hasExpectedManifestIdentity) return firstEvalId;
|
|
147
|
-
deferredFirstEvalId = deferredFirstEvalId || firstEvalId;
|
|
148
|
-
}
|
|
149
|
-
if (profileCandidateId) return profileCandidateId;
|
|
150
|
-
if (urlDerivedId) {
|
|
151
|
-
if (!hasExpectedManifestIdentity) return urlDerivedId;
|
|
152
|
-
deferredUrlDerivedId = deferredUrlDerivedId || urlDerivedId;
|
|
153
|
-
}
|
|
154
|
-
} catch {}
|
|
155
|
-
await new Promise((r)=>setTimeout(r, backoffMs));
|
|
156
|
-
retries++;
|
|
157
|
-
}
|
|
158
|
-
return deriveFromProfile() || deferredFirstEvalId || deferredUrlDerivedId;
|
|
159
|
-
}
|
|
160
|
-
var cdp_client = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-source-inspection/cdp-client.ts");
|
|
161
|
-
var discovery = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-source-inspection/discovery.ts");
|
|
162
|
-
function isRecoverableBootstrapError(error) {
|
|
163
|
-
const msg = String(error?.message || error || '').toLowerCase();
|
|
164
|
-
return msg.includes('econnreset') || msg.includes('websocket is not open') || msg.includes('cdp connection closed') || msg.includes('socket hang up') || msg.includes('timed out') || msg.includes('no cdp websocket url');
|
|
165
|
-
}
|
|
166
|
-
async function connectToChromeCdp(cdpPort) {
|
|
167
|
-
let retries = 0;
|
|
168
|
-
const maxRetries = 60;
|
|
169
|
-
const backoffMs = 250;
|
|
170
|
-
while(retries < maxRetries){
|
|
171
|
-
const ready = await (0, discovery.z)(cdpPort);
|
|
172
|
-
if (ready) break;
|
|
173
|
-
retries++;
|
|
174
|
-
await new Promise((r)=>setTimeout(r, backoffMs));
|
|
175
|
-
}
|
|
176
|
-
const maxBootstrapAttempts = 4;
|
|
177
|
-
let lastError = null;
|
|
178
|
-
for(let attempt = 1; attempt <= maxBootstrapAttempts; attempt++){
|
|
179
|
-
const cdp = new cdp_client.n(cdpPort, '127.0.0.1');
|
|
180
|
-
try {
|
|
181
|
-
await cdp.connect();
|
|
182
|
-
await cdp.sendCommand('Target.setDiscoverTargets', {
|
|
183
|
-
discover: true
|
|
184
|
-
});
|
|
185
|
-
await cdp.sendCommand('Target.setAutoAttach', {
|
|
186
|
-
autoAttach: true,
|
|
187
|
-
waitForDebuggerOnStart: false,
|
|
188
|
-
flatten: true
|
|
189
|
-
});
|
|
190
|
-
return cdp;
|
|
191
|
-
} catch (error) {
|
|
192
|
-
lastError = error;
|
|
193
|
-
cdp.disconnect();
|
|
194
|
-
const retryable = isRecoverableBootstrapError(error);
|
|
195
|
-
const hasMoreAttempts = attempt < maxBootstrapAttempts;
|
|
196
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) {
|
|
197
|
-
const base = String(error?.message || error);
|
|
198
|
-
console.warn(`[CDP] bootstrap attempt ${attempt}/${maxBootstrapAttempts} failed: ${base}`);
|
|
199
|
-
}
|
|
200
|
-
if (!retryable || !hasMoreAttempts) throw error;
|
|
201
|
-
const delayMs = 120 * attempt;
|
|
202
|
-
await new Promise((r)=>setTimeout(r, delayMs));
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
throw lastError instanceof Error ? lastError : new Error('Failed to bootstrap CDP connection');
|
|
206
|
-
}
|
|
207
|
-
function readManifestInfo(outPath) {
|
|
208
|
-
try {
|
|
209
|
-
const manifestPath = external_path_.join(outPath, 'manifest.json');
|
|
210
|
-
const manifest = JSON.parse(external_fs_.readFileSync(manifestPath, 'utf-8'));
|
|
211
|
-
return {
|
|
212
|
-
name: manifest?.name,
|
|
213
|
-
version: manifest?.version
|
|
214
|
-
};
|
|
215
|
-
} catch {
|
|
216
|
-
return null;
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
function registerAutoEnableLogging(cdp, getExtensionId) {
|
|
220
|
-
cdp.onProtocolEvent((message)=>{
|
|
221
|
-
try {
|
|
222
|
-
if (!message || !message.method) return;
|
|
223
|
-
if ('Target.attachedToTarget' === message.method) {
|
|
224
|
-
const params = message.params || {};
|
|
225
|
-
const targetInfo = params.targetInfo || {};
|
|
226
|
-
const sessionId = params.sessionId;
|
|
227
|
-
const url = String(targetInfo.url || '');
|
|
228
|
-
const type = String(targetInfo.type || '');
|
|
229
|
-
const extId = getExtensionId();
|
|
230
|
-
const matchesExtension = !!(extId && url.includes(`chrome-extension://${extId}/`) || 'service_worker' === type);
|
|
231
|
-
if (sessionId && matchesExtension) {
|
|
232
|
-
cdp.sendCommand('Runtime.enable', {}, sessionId).catch(()=>{});
|
|
233
|
-
cdp.sendCommand('Log.enable', {}, sessionId).catch(()=>{});
|
|
234
|
-
}
|
|
235
|
-
} else if ('Runtime.consoleAPICalled' === message.method || 'Log.entryAdded' === message.method) {
|
|
236
|
-
if ('1' === String(process.env.EXTENSION_VERBOSE || '').trim()) {
|
|
237
|
-
const ts = new Date().toISOString();
|
|
238
|
-
console.log(messages.bvI(ts, message.params));
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
} catch (error) {
|
|
242
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.KK1(String(error?.message || error)));
|
|
243
|
-
}
|
|
244
|
-
});
|
|
245
|
-
}
|
|
246
|
-
function _define_property(obj, key, value) {
|
|
247
|
-
if (key in obj) Object.defineProperty(obj, key, {
|
|
248
|
-
value: value,
|
|
249
|
-
enumerable: true,
|
|
250
|
-
configurable: true,
|
|
251
|
-
writable: true
|
|
252
|
-
});
|
|
253
|
-
else obj[key] = value;
|
|
254
|
-
return obj;
|
|
255
|
-
}
|
|
256
|
-
class CDPExtensionController {
|
|
257
|
-
async connect() {
|
|
258
|
-
if (this.cdp) return;
|
|
259
|
-
await this.connectFreshClient();
|
|
260
|
-
}
|
|
261
|
-
async ensureLoaded() {
|
|
262
|
-
if (!this.cdp) throw new Error('CDP not connected');
|
|
263
|
-
const exists = external_fs_.existsSync(this.outPath);
|
|
264
|
-
if (!exists) throw new Error(`Output path not found: ${this.outPath}`);
|
|
265
|
-
if (!this.extensionId) {
|
|
266
|
-
const id = await this.deriveExtensionIdFromTargets();
|
|
267
|
-
if (id) this.extensionId = id;
|
|
268
|
-
}
|
|
269
|
-
if (this.extensionId) {
|
|
270
|
-
const belongsToOutPath = this.extensionIdBelongsToOutPath(this.extensionId);
|
|
271
|
-
if (false === belongsToOutPath) this.extensionId = null;
|
|
272
|
-
}
|
|
273
|
-
if (this.extensionId) try {
|
|
274
|
-
let info = null;
|
|
275
|
-
try {
|
|
276
|
-
info = await this.cdp.getExtensionInfo(this.extensionId);
|
|
277
|
-
} catch {}
|
|
278
|
-
if (!info) {
|
|
279
|
-
const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(this.outPath, 'manifest.json'), 'utf-8'));
|
|
280
|
-
return {
|
|
281
|
-
extensionId: this.extensionId,
|
|
282
|
-
name: manifest.name,
|
|
283
|
-
version: manifest.version
|
|
284
|
-
};
|
|
285
|
-
}
|
|
286
|
-
return {
|
|
287
|
-
extensionId: this.extensionId,
|
|
288
|
-
name: info?.extensionInfo?.name,
|
|
289
|
-
version: info?.extensionInfo?.version
|
|
290
|
-
};
|
|
291
|
-
} catch {}
|
|
292
|
-
try {
|
|
293
|
-
if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(20, 200);
|
|
294
|
-
if (!this.extensionId) throw new Error('Failed to determine extension ID via CDP');
|
|
295
|
-
await this.enableLogging();
|
|
296
|
-
let name;
|
|
297
|
-
let version;
|
|
298
|
-
try {
|
|
299
|
-
const info = await this.cdp.getExtensionInfo(this.extensionId);
|
|
300
|
-
name = info?.extensionInfo?.name;
|
|
301
|
-
version = info?.extensionInfo?.version;
|
|
302
|
-
} catch (error) {
|
|
303
|
-
try {
|
|
304
|
-
const manifest = readManifestInfo(this.outPath);
|
|
305
|
-
name = String(manifest?.name || '') || void 0;
|
|
306
|
-
version = String(manifest?.version || '') || void 0;
|
|
307
|
-
} catch (e2) {
|
|
308
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn('[CDP] Fallback manifest read failed:', String(e2?.message || e2));
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
return {
|
|
312
|
-
extensionId: this.extensionId,
|
|
313
|
-
name,
|
|
314
|
-
version
|
|
315
|
-
};
|
|
316
|
-
} catch (error) {
|
|
317
|
-
throw new Error(`Failed to load extension from ${external_path_.resolve(this.outPath)}: ${String(error.message || error)}`);
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
async deriveExtensionIdFromTargets(maxRetries = 20, backoffMs = 200) {
|
|
321
|
-
if (!this.cdp) return null;
|
|
322
|
-
return await deriveExtensionIdFromTargetsHelper(this.cdp, this.outPath, maxRetries, backoffMs, this.profilePath, this.extensionPaths);
|
|
323
|
-
}
|
|
324
|
-
normalizePath(input) {
|
|
325
|
-
try {
|
|
326
|
-
return external_fs_.realpathSync(external_path_.resolve(input));
|
|
327
|
-
} catch {
|
|
328
|
-
return external_path_.resolve(input);
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
extensionIdBelongsToOutPath(extensionId) {
|
|
332
|
-
if (!this.profilePath || !extensionId) return null;
|
|
333
|
-
const prefCandidates = [];
|
|
334
|
-
const addPrefCandidate = (dir)=>{
|
|
335
|
-
const prefPath = external_path_.join(dir, 'Preferences');
|
|
336
|
-
if (external_fs_.existsSync(prefPath)) prefCandidates.push(prefPath);
|
|
337
|
-
};
|
|
338
|
-
try {
|
|
339
|
-
addPrefCandidate(this.profilePath);
|
|
340
|
-
addPrefCandidate(external_path_.join(this.profilePath, 'Default'));
|
|
341
|
-
for (const entry of external_fs_.readdirSync(this.profilePath))if (/^Profile\s+\d+$/i.test(entry)) addPrefCandidate(external_path_.join(this.profilePath, entry));
|
|
342
|
-
} catch {}
|
|
343
|
-
if (0 === prefCandidates.length) return null;
|
|
344
|
-
const normalizedOutPath = this.normalizePath(this.outPath);
|
|
345
|
-
for (const prefPath of prefCandidates)try {
|
|
346
|
-
const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
|
|
347
|
-
const settings = prefs?.extensions?.settings;
|
|
348
|
-
const info = settings?.[extensionId];
|
|
349
|
-
const storedPath = String(info?.path || '');
|
|
350
|
-
if (!storedPath) continue;
|
|
351
|
-
return this.normalizePath(storedPath) === normalizedOutPath;
|
|
352
|
-
} catch {}
|
|
353
|
-
return null;
|
|
354
|
-
}
|
|
355
|
-
getDeveloperModeStatus() {
|
|
356
|
-
if (!this.profilePath) return 'unknown';
|
|
357
|
-
const prefCandidates = [];
|
|
358
|
-
const seen = new Set();
|
|
359
|
-
const addPrefCandidate = (dir)=>{
|
|
360
|
-
const prefPath = external_path_.join(dir, 'Preferences');
|
|
361
|
-
if (!external_fs_.existsSync(prefPath)) return;
|
|
362
|
-
const dedupeKey = external_path_.resolve(prefPath);
|
|
363
|
-
if (seen.has(dedupeKey)) return;
|
|
364
|
-
seen.add(dedupeKey);
|
|
365
|
-
prefCandidates.push(prefPath);
|
|
366
|
-
};
|
|
367
|
-
try {
|
|
368
|
-
addPrefCandidate(this.profilePath);
|
|
369
|
-
addPrefCandidate(external_path_.join(this.profilePath, 'Default'));
|
|
370
|
-
for (const entry of external_fs_.readdirSync(this.profilePath))if (/^Profile\s+\d+$/i.test(entry)) addPrefCandidate(external_path_.join(this.profilePath, entry));
|
|
371
|
-
} catch {}
|
|
372
|
-
for (const prefPath of prefCandidates)try {
|
|
373
|
-
const prefs = JSON.parse(external_fs_.readFileSync(prefPath, 'utf-8'));
|
|
374
|
-
const uiFlag = prefs?.extensions?.ui?.developer_mode;
|
|
375
|
-
if ('boolean' == typeof uiFlag) return uiFlag ? 'enabled' : 'disabled';
|
|
376
|
-
const legacyFlag = prefs?.extensions?.developer_mode;
|
|
377
|
-
if ('boolean' == typeof legacyFlag) return legacyFlag ? 'enabled' : 'disabled';
|
|
378
|
-
} catch {}
|
|
379
|
-
return 'unknown';
|
|
380
|
-
}
|
|
381
|
-
getLastRuntimeReinjectionReport() {
|
|
382
|
-
return this.lastRuntimeReinjectionReport;
|
|
383
|
-
}
|
|
384
|
-
async reloadMatchingTabsForContentScripts(rules, options = {}) {
|
|
385
|
-
if (!this.cdp || 0 === rules.length) return 0;
|
|
386
|
-
let reinjectedTabs = 0;
|
|
387
|
-
const targets = await this.cdp.getTargets();
|
|
388
|
-
for (const target of targets || []){
|
|
389
|
-
const targetType = String(target?.type || '');
|
|
390
|
-
const targetId = String(target?.targetId || '');
|
|
391
|
-
const targetUrl = String(target?.url || '');
|
|
392
|
-
if ('page' !== targetType || !targetId || !targetUrl) continue;
|
|
393
|
-
const matchingRules = rules.filter((rule)=>(0, content_script_targets.lM)(targetUrl, [
|
|
394
|
-
rule
|
|
395
|
-
]));
|
|
396
|
-
if (0 !== matchingRules.length) try {
|
|
397
|
-
const sessionId = await this.cdp.attachToTarget(targetId);
|
|
398
|
-
let reinjected = false;
|
|
399
|
-
if (options.preferPageReload) reinjected = await this.reloadPageTarget(sessionId);
|
|
400
|
-
else {
|
|
401
|
-
for (const [index, rule] of matchingRules.entries()){
|
|
402
|
-
const didReinject = await this.reinjectContentScriptRule(sessionId, rule, options.allowCoarseCleanup ?? 0 === index, options.sourceOverridesByBundleId);
|
|
403
|
-
reinjected = reinjected || didReinject;
|
|
404
|
-
}
|
|
405
|
-
if (!reinjected) reinjected = await this.reloadPageTarget(sessionId);
|
|
406
|
-
}
|
|
407
|
-
if (reinjected) reinjectedTabs += 1;
|
|
408
|
-
} catch (error) {
|
|
409
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] Failed to reinject content scripts into ${targetUrl}: ${String(error?.message || error)}`);
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
return reinjectedTabs;
|
|
413
|
-
}
|
|
414
|
-
async reinjectMatchingTabsViaExtensionRuntime(rules) {
|
|
415
|
-
if (!this.cdp || 0 === rules.length) {
|
|
416
|
-
this.lastRuntimeReinjectionReport = {
|
|
417
|
-
phase: 'skipped',
|
|
418
|
-
reason: 'missing_cdp_or_rules',
|
|
419
|
-
hasCdp: !!this.cdp,
|
|
420
|
-
ruleCount: rules.length
|
|
421
|
-
};
|
|
422
|
-
return 0;
|
|
423
|
-
}
|
|
424
|
-
const targets = await this.cdp.getTargets();
|
|
425
|
-
const matchingUrlsByRule = new Map();
|
|
426
|
-
for (const target of targets || []){
|
|
427
|
-
const targetType = String(target?.type || '');
|
|
428
|
-
const targetUrl = String(target?.url || '');
|
|
429
|
-
if ('page' === targetType && targetUrl) for (const rule of rules){
|
|
430
|
-
if (!(0, content_script_targets.lM)(targetUrl, [
|
|
431
|
-
rule
|
|
432
|
-
])) continue;
|
|
433
|
-
const urls = matchingUrlsByRule.get(rule.index) || new Set();
|
|
434
|
-
urls.add(targetUrl);
|
|
435
|
-
matchingUrlsByRule.set(rule.index, urls);
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
const payload = rules.map((rule)=>{
|
|
439
|
-
const jsPath = (0, content_script_targets.nG)(this.outPath, rule.index, 'js');
|
|
440
|
-
const cssPath = (0, content_script_targets.nG)(this.outPath, rule.index, 'css');
|
|
441
|
-
if (!jsPath || !external_fs_.existsSync(jsPath)) return null;
|
|
442
|
-
const jsFile = external_path_.relative(this.outPath, jsPath).replace(/\\/g, '/');
|
|
443
|
-
const cssFile = cssPath && external_fs_.existsSync(cssPath) ? external_path_.relative(this.outPath, cssPath).replace(/\\/g, '/') : null;
|
|
444
|
-
const jsSource = external_fs_.readFileSync(jsPath, 'utf-8');
|
|
445
|
-
const buildTokenMatch = jsSource.match(/__EXTENSIONJS_REINJECT_BUILD_TOKEN\s*=\s*"([^"]+)"/);
|
|
446
|
-
const proofMatch = jsSource.match(/extjs-chromium-live-content-css-modules:script-primary-\d+/) || jsSource.match(/Live Update Proof [A-Za-z0-9_-]+/);
|
|
447
|
-
return {
|
|
448
|
-
index: rule.index,
|
|
449
|
-
world: rule.world,
|
|
450
|
-
matches: [
|
|
451
|
-
...rule.matches
|
|
452
|
-
],
|
|
453
|
-
urls: Array.from(matchingUrlsByRule.get(rule.index) || []).sort(),
|
|
454
|
-
jsFile,
|
|
455
|
-
cssFile,
|
|
456
|
-
buildToken: buildTokenMatch?.[1] || null,
|
|
457
|
-
proofMarker: proofMatch?.[0] || null
|
|
458
|
-
};
|
|
459
|
-
}).filter((entry)=>!!entry && entry.urls.length > 0);
|
|
460
|
-
if (0 === payload.length) {
|
|
461
|
-
this.lastRuntimeReinjectionReport = {
|
|
462
|
-
phase: 'skipped',
|
|
463
|
-
reason: 'no_payload',
|
|
464
|
-
ruleCount: rules.length
|
|
465
|
-
};
|
|
466
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log('[CDP] extension-runtime reinjection skipped: no payload');
|
|
467
|
-
return 0;
|
|
468
|
-
}
|
|
469
|
-
const runtimeTarget = await this.attachToExtensionRuntimeTarget();
|
|
470
|
-
if (!runtimeTarget) {
|
|
471
|
-
const targetSummary = (targets || []).map((target)=>({
|
|
472
|
-
type: String(target?.type || ''),
|
|
473
|
-
url: String(target?.url || '')
|
|
474
|
-
})).filter((entry)=>entry.type || entry.url);
|
|
475
|
-
this.lastRuntimeReinjectionReport = {
|
|
476
|
-
phase: 'unavailable',
|
|
477
|
-
reason: 'no_runtime_target',
|
|
478
|
-
extensionId: this.extensionId,
|
|
479
|
-
targets: targetSummary
|
|
480
|
-
};
|
|
481
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] extension-runtime reinjection unavailable: ${JSON.stringify({
|
|
482
|
-
extensionId: this.extensionId,
|
|
483
|
-
targets: targetSummary
|
|
484
|
-
})}`);
|
|
485
|
-
return 0;
|
|
486
|
-
}
|
|
487
|
-
const result = await this.cdp.evaluate(runtimeTarget.sessionId, `(() => (async () => {
|
|
488
|
-
const payload = ${JSON.stringify(payload)};
|
|
489
|
-
const chromeRuntime =
|
|
490
|
-
typeof globalThis === 'object' && globalThis && globalThis.chrome
|
|
491
|
-
? globalThis.chrome
|
|
492
|
-
: null;
|
|
493
|
-
const runtimeChrome =
|
|
494
|
-
chromeRuntime &&
|
|
495
|
-
chromeRuntime.scripting &&
|
|
496
|
-
chromeRuntime.tabs
|
|
497
|
-
? chromeRuntime
|
|
498
|
-
: null;
|
|
499
|
-
if (!runtimeChrome) {
|
|
500
|
-
return {
|
|
501
|
-
reinjectedTabs: 0,
|
|
502
|
-
hasRuntime: false,
|
|
503
|
-
hasChrome: !!chromeRuntime,
|
|
504
|
-
hasScripting: !!(chromeRuntime && chromeRuntime.scripting),
|
|
505
|
-
hasTabs: !!(chromeRuntime && chromeRuntime.tabs),
|
|
506
|
-
entries: payload.length,
|
|
507
|
-
matches: []
|
|
508
|
-
};
|
|
509
|
-
}
|
|
510
|
-
let reinjectedTabs = 0;
|
|
511
|
-
const matches = [];
|
|
512
|
-
for (const entry of payload) {
|
|
513
|
-
const queriedTabs = await runtimeChrome.tabs.query(
|
|
514
|
-
entry.matches.length > 0 ? { url: entry.matches } : {}
|
|
515
|
-
);
|
|
516
|
-
const matchingTabs = queriedTabs.filter((tab) => {
|
|
517
|
-
if (!tab || typeof tab.id !== 'number') return false;
|
|
518
|
-
if (typeof tab.url !== 'string' || !tab.url) return true;
|
|
519
|
-
return entry.urls.length === 0 || entry.urls.includes(tab.url);
|
|
520
|
-
});
|
|
521
|
-
matches.push({
|
|
522
|
-
index: entry.index,
|
|
523
|
-
queriedTabs: queriedTabs.length,
|
|
524
|
-
matchingTabs: matchingTabs.length
|
|
525
|
-
});
|
|
526
|
-
for (const tab of matchingTabs) {
|
|
527
|
-
const target = { tabId: tab.id, allFrames: false };
|
|
528
|
-
if (entry.cssFile) {
|
|
529
|
-
try {
|
|
530
|
-
await runtimeChrome.scripting.insertCSS({
|
|
531
|
-
target,
|
|
532
|
-
files: [entry.cssFile]
|
|
533
|
-
});
|
|
534
|
-
} catch (error) {}
|
|
535
|
-
}
|
|
536
|
-
await runtimeChrome.scripting.executeScript({
|
|
537
|
-
target,
|
|
538
|
-
files: [entry.jsFile],
|
|
539
|
-
world: entry.world === 'main' ? 'MAIN' : 'ISOLATED'
|
|
540
|
-
});
|
|
541
|
-
reinjectedTabs += 1;
|
|
542
|
-
}
|
|
543
|
-
}
|
|
544
|
-
return {
|
|
545
|
-
reinjectedTabs,
|
|
546
|
-
hasRuntime: true,
|
|
547
|
-
entries: payload.length,
|
|
548
|
-
matches
|
|
549
|
-
};
|
|
550
|
-
})())()`, {
|
|
551
|
-
awaitPromise: true
|
|
552
|
-
});
|
|
553
|
-
this.lastRuntimeReinjectionReport = {
|
|
554
|
-
phase: 'evaluated',
|
|
555
|
-
targetType: runtimeTarget.targetType,
|
|
556
|
-
targetUrl: runtimeTarget.targetUrl,
|
|
557
|
-
result: result && 'object' == typeof result ? JSON.parse(JSON.stringify(result)) : result
|
|
558
|
-
};
|
|
559
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] extension-runtime reinjection result: ${JSON.stringify({
|
|
560
|
-
targetType: runtimeTarget.targetType,
|
|
561
|
-
targetUrl: runtimeTarget.targetUrl,
|
|
562
|
-
result
|
|
563
|
-
})}`);
|
|
564
|
-
if ('number' == typeof result) return result;
|
|
565
|
-
if (result && 'object' == typeof result) {
|
|
566
|
-
const reinjectedTabs = Number(result.reinjectedTabs);
|
|
567
|
-
return Number.isFinite(reinjectedTabs) ? reinjectedTabs : 0;
|
|
568
|
-
}
|
|
569
|
-
return 0;
|
|
570
|
-
}
|
|
571
|
-
async reloadPageTarget(sessionId) {
|
|
572
|
-
if (!this.cdp) return false;
|
|
573
|
-
try {
|
|
574
|
-
await this.cdp.sendCommand('Page.reload', {
|
|
575
|
-
ignoreCache: true
|
|
576
|
-
}, sessionId);
|
|
577
|
-
return true;
|
|
578
|
-
} catch {
|
|
579
|
-
return false;
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
async hardReload() {
|
|
583
|
-
if (!this.extensionId) return false;
|
|
584
|
-
try {
|
|
585
|
-
if (!this.cdp) await this.connectFreshClient();
|
|
586
|
-
if (this.cdp && await this.cdp.forceReloadExtension(this.extensionId)) return true;
|
|
587
|
-
} catch {}
|
|
588
|
-
try {
|
|
589
|
-
await this.reconnectForReload();
|
|
590
|
-
return Boolean(this.cdp && this.extensionId && await this.cdp.forceReloadExtension(this.extensionId));
|
|
591
|
-
} catch {
|
|
592
|
-
return false;
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
async attachToExtensionRuntimeTarget() {
|
|
596
|
-
if (!this.cdp) return;
|
|
597
|
-
if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(10, 150);
|
|
598
|
-
if (!this.extensionId) return;
|
|
599
|
-
const extensionOrigin = `chrome-extension://${this.extensionId}/`;
|
|
600
|
-
for(let attempt = 0; attempt < 20; attempt++){
|
|
601
|
-
const targets = await this.cdp.getTargets();
|
|
602
|
-
const runtimeTargets = (targets || []).filter((target)=>{
|
|
603
|
-
const targetType = String(target?.type || '');
|
|
604
|
-
const targetId = String(target?.targetId || '');
|
|
605
|
-
return ('service_worker' === targetType || 'background_page' === targetType || 'worker' === targetType) && !!targetId;
|
|
606
|
-
});
|
|
607
|
-
const runtimeTarget = runtimeTargets.find((target)=>String(target?.url || '').startsWith(extensionOrigin)) || runtimeTargets.find((target)=>String(target?.url || '').startsWith('chrome-extension://'));
|
|
608
|
-
if (runtimeTarget) try {
|
|
609
|
-
const sessionId = await this.cdp.attachToTarget(String(runtimeTarget.targetId));
|
|
610
|
-
await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
|
|
611
|
-
return {
|
|
612
|
-
sessionId,
|
|
613
|
-
targetType: String(runtimeTarget?.type || ''),
|
|
614
|
-
targetUrl: String(runtimeTarget?.url || '')
|
|
615
|
-
};
|
|
616
|
-
} catch {}
|
|
617
|
-
this.extensionId = await this.deriveExtensionIdFromTargets(4, 100) || this.extensionId;
|
|
618
|
-
await new Promise((resolve)=>setTimeout(resolve, 250));
|
|
619
|
-
}
|
|
620
|
-
}
|
|
621
|
-
async connectFreshClient() {
|
|
622
|
-
this.cdp = await connectToChromeCdp(this.cdpPort);
|
|
623
|
-
try {
|
|
624
|
-
await this.cdp.sendCommand('Target.setDiscoverTargets', {
|
|
625
|
-
discover: true
|
|
626
|
-
});
|
|
627
|
-
await this.cdp.sendCommand('Target.setAutoAttach', {
|
|
628
|
-
autoAttach: true,
|
|
629
|
-
waitForDebuggerOnStart: false,
|
|
630
|
-
flatten: true
|
|
631
|
-
});
|
|
632
|
-
} catch (error) {
|
|
633
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.wXK(String(error?.message || error)));
|
|
634
|
-
}
|
|
635
|
-
registerAutoEnableLogging(this.cdp, ()=>this.extensionId);
|
|
636
|
-
}
|
|
637
|
-
async reconnectForReload() {
|
|
638
|
-
try {
|
|
639
|
-
this.cdp?.disconnect?.();
|
|
640
|
-
} catch {}
|
|
641
|
-
this.cdp = null;
|
|
642
|
-
await this.connectFreshClient();
|
|
643
|
-
try {
|
|
644
|
-
const derivedExtensionId = await this.deriveExtensionIdFromTargets(10, 150);
|
|
645
|
-
if (derivedExtensionId) this.extensionId = derivedExtensionId;
|
|
646
|
-
} catch {}
|
|
647
|
-
}
|
|
648
|
-
onProtocolEvent(cb) {
|
|
649
|
-
if (!this.cdp) throw new Error('CDP not connected');
|
|
650
|
-
this.cdp.onProtocolEvent((raw)=>{
|
|
651
|
-
const evt = raw;
|
|
652
|
-
cb(evt);
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
clearProtocolEventHandler() {
|
|
656
|
-
if (!this.cdp) return;
|
|
657
|
-
}
|
|
658
|
-
async enableUnifiedLogging() {
|
|
659
|
-
if (!this.cdp) return;
|
|
660
|
-
try {
|
|
661
|
-
await this.cdp.enableAutoAttach();
|
|
662
|
-
await this.cdp.enableRuntimeAndLog();
|
|
663
|
-
try {
|
|
664
|
-
const targets = await this.cdp.getTargets();
|
|
665
|
-
for (const t of targets || []){
|
|
666
|
-
const type = String(t?.type || '');
|
|
667
|
-
if ('page' === type || 'service_worker' === type || 'background_page' === type || 'worker' === type) {
|
|
668
|
-
const targetId = String(t?.targetId || '');
|
|
669
|
-
if (!targetId) continue;
|
|
670
|
-
const sessionId = await this.cdp.attachToTarget(targetId);
|
|
671
|
-
await this.cdp.enableRuntimeAndLog(sessionId);
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
} catch {}
|
|
675
|
-
} catch {}
|
|
676
|
-
}
|
|
677
|
-
async enableRuntimeForSession(sessionId) {
|
|
678
|
-
if (!this.cdp) return;
|
|
679
|
-
try {
|
|
680
|
-
await this.cdp.enableRuntimeAndLog(sessionId);
|
|
681
|
-
} catch {}
|
|
682
|
-
}
|
|
683
|
-
async enableLogging() {
|
|
684
|
-
if (!this.cdp) return;
|
|
685
|
-
try {
|
|
686
|
-
const extId = this.extensionId;
|
|
687
|
-
this.onProtocolEvent(async (message)=>{
|
|
688
|
-
try {
|
|
689
|
-
if (!message || !message.method) return;
|
|
690
|
-
if ('Target.attachedToTarget' === message.method) {
|
|
691
|
-
const params = message.params || {};
|
|
692
|
-
const targetInfo = params.targetInfo || {
|
|
693
|
-
url: '',
|
|
694
|
-
type: ''
|
|
695
|
-
};
|
|
696
|
-
const sessionId = params.sessionId;
|
|
697
|
-
const url = String(targetInfo.url || '');
|
|
698
|
-
const type = String(targetInfo.type || '');
|
|
699
|
-
const matchesExtension = !!(this.extensionId && url.includes(`chrome-extension://${this.extensionId}/`) || extId && url.includes(`chrome-extension://${extId}/`) || 'service_worker' === type);
|
|
700
|
-
if (sessionId && matchesExtension) {
|
|
701
|
-
await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
|
|
702
|
-
await this.cdp.sendCommand('Log.enable', {}, sessionId);
|
|
703
|
-
}
|
|
704
|
-
} else if ('Runtime.consoleAPICalled' === message.method || 'Log.entryAdded' === message.method) {
|
|
705
|
-
const ts = new Date().toISOString();
|
|
706
|
-
console.log(messages.bvI(ts, message.params));
|
|
707
|
-
}
|
|
708
|
-
} catch {}
|
|
709
|
-
});
|
|
710
|
-
} catch (e) {
|
|
711
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn('[CDP] enableLogging failed:', String(e));
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
async getInfoBestEffort() {
|
|
715
|
-
try {
|
|
716
|
-
if (!this.cdp) return null;
|
|
717
|
-
if (!this.extensionId) this.extensionId = await this.deriveExtensionIdFromTargets(6, 150);
|
|
718
|
-
if (this.extensionId) {
|
|
719
|
-
const belongsToOutPath = this.extensionIdBelongsToOutPath(this.extensionId);
|
|
720
|
-
if (false === belongsToOutPath) this.extensionId = await this.deriveExtensionIdFromTargets(10, 150);
|
|
721
|
-
}
|
|
722
|
-
if (!this.extensionId) return null;
|
|
723
|
-
let name;
|
|
724
|
-
let version;
|
|
725
|
-
try {
|
|
726
|
-
const info = await this.cdp.getExtensionInfo(this.extensionId);
|
|
727
|
-
name = info?.extensionInfo?.name;
|
|
728
|
-
version = info?.extensionInfo?.version;
|
|
729
|
-
} catch {
|
|
730
|
-
try {
|
|
731
|
-
const manifest = JSON.parse(external_fs_.readFileSync(external_path_.join(this.outPath, 'manifest.json'), 'utf-8'));
|
|
732
|
-
name = manifest?.name;
|
|
733
|
-
version = manifest?.version;
|
|
734
|
-
} catch {}
|
|
735
|
-
}
|
|
736
|
-
return {
|
|
737
|
-
extensionId: this.extensionId,
|
|
738
|
-
name,
|
|
739
|
-
version
|
|
740
|
-
};
|
|
741
|
-
} catch (error) {
|
|
742
|
-
return null;
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
async reinjectContentScriptRule(sessionId, rule, allowCoarseCleanup, sourceOverridesByBundleId) {
|
|
746
|
-
if (!this.cdp) return false;
|
|
747
|
-
const bundleId = (0, contracts.Y0)(rule.index);
|
|
748
|
-
const bundlePath = (0, content_script_targets.nG)(this.outPath, rule.index, 'js');
|
|
749
|
-
if (!bundlePath || !external_fs_.existsSync(bundlePath)) return false;
|
|
750
|
-
const sourceOverride = sourceOverridesByBundleId && 'object' == typeof sourceOverridesByBundleId ? sourceOverridesByBundleId[bundleId] : void 0;
|
|
751
|
-
const source = this.patchReinjectSourceForInvalidatedRuntime('string' == typeof sourceOverride ? sourceOverride : external_fs_.readFileSync(bundlePath, 'utf-8'));
|
|
752
|
-
const buildTokenMatch = source.match(/__EXTENSIONJS_REINJECT_BUILD_TOKEN\s*=\s*"([^"]+)"/);
|
|
753
|
-
const proofMatch = source.match(/extjs-chromium-live-content-css-modules:script-primary-\d+/) || source.match(/Live Update Proof [A-Za-z0-9_-]+/);
|
|
754
|
-
if (!source.trim()) return false;
|
|
755
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] reinject bundle ${bundleId} from ${bundlePath}${proofMatch ? ` (${proofMatch[0]})` : ''} build=${buildTokenMatch?.[1] || '<none>'} sourceOverride=${'string' == typeof sourceOverride}`);
|
|
756
|
-
const contextId = await this.resolveExecutionContextId(sessionId, rule);
|
|
757
|
-
if (!contextId) {
|
|
758
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] No execution context found for ${bundleId} (${rule.world})`);
|
|
759
|
-
return false;
|
|
760
|
-
}
|
|
761
|
-
const result = await this.cdp.evaluateInContext(sessionId, this.buildReinjectExpression(bundleId, source, allowCoarseCleanup), contextId);
|
|
762
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(`[CDP] reinject result ${bundleId}: ${JSON.stringify(result)}`);
|
|
763
|
-
if (result && 'object' == typeof result && 'ok' in result) return false !== result.ok;
|
|
764
|
-
return true;
|
|
765
|
-
}
|
|
766
|
-
buildReinjectExpression(bundleId, source, allowCoarseCleanup) {
|
|
767
|
-
const annotatedSource = `${source}\n//# sourceURL=extension.js-reinject://${bundleId}.js`;
|
|
768
|
-
const extensionBase = this.extensionId ? `chrome-extension://${this.extensionId}/` : '';
|
|
769
|
-
return `(() => {
|
|
770
|
-
const bundleId = ${JSON.stringify(bundleId)};
|
|
771
|
-
const source = ${JSON.stringify(annotatedSource)};
|
|
772
|
-
const extensionBase = ${JSON.stringify(extensionBase)};
|
|
773
|
-
const rootSelector = '[data-extension-root], #extension-root';
|
|
774
|
-
const keyedSelector = '[data-extjs-reinject-key="${bundleId}"]';
|
|
775
|
-
const registry = (typeof globalThis === 'object' && globalThis)
|
|
776
|
-
? (globalThis.__EXTENSIONJS_DEV_REINJECT__ || (globalThis.__EXTENSIONJS_DEV_REINJECT__ = {}))
|
|
777
|
-
: {};
|
|
778
|
-
const existing = registry[bundleId];
|
|
779
|
-
const readGeneration = (entry) => {
|
|
780
|
-
try {
|
|
781
|
-
if (!entry) return 0;
|
|
782
|
-
if (typeof entry === 'function' && typeof entry.__extjsGeneration === 'number') {
|
|
783
|
-
return entry.__extjsGeneration;
|
|
784
|
-
}
|
|
785
|
-
if (typeof entry === 'object') {
|
|
786
|
-
if (typeof entry.__extjsGeneration === 'number') return entry.__extjsGeneration;
|
|
787
|
-
if (typeof entry.generation === 'number') return entry.generation;
|
|
788
|
-
if (typeof entry.cleanup === 'function' && typeof entry.cleanup.__extjsGeneration === 'number') {
|
|
789
|
-
return entry.cleanup.__extjsGeneration;
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
} catch (error) {}
|
|
793
|
-
return 0;
|
|
794
|
-
};
|
|
795
|
-
const previousGeneration = readGeneration(existing);
|
|
796
|
-
try {
|
|
797
|
-
if (typeof existing === 'function') existing();
|
|
798
|
-
if (existing && typeof existing.cleanup === 'function') existing.cleanup();
|
|
799
|
-
} catch (error) {}
|
|
800
|
-
if (${allowCoarseCleanup ? 'true' : 'false'}) {
|
|
801
|
-
try {
|
|
802
|
-
const staleRoots = Array.from(document.querySelectorAll(rootSelector));
|
|
803
|
-
for (const root of staleRoots) {
|
|
804
|
-
if (root && typeof root.remove === 'function') root.remove();
|
|
805
|
-
}
|
|
806
|
-
} catch (error) {}
|
|
807
|
-
}
|
|
808
|
-
const trackedNodes = new Set();
|
|
809
|
-
const trackNode = (node) => {
|
|
810
|
-
try {
|
|
811
|
-
if (!node || typeof Element !== 'function' || !(node instanceof Element)) return;
|
|
812
|
-
const matchesRoot = typeof node.matches === 'function' && node.matches(rootSelector);
|
|
813
|
-
if (!matchesRoot) return;
|
|
814
|
-
trackedNodes.add(node);
|
|
815
|
-
if (typeof node.setAttribute === 'function') {
|
|
816
|
-
node.setAttribute('data-extjs-reinject-key', bundleId);
|
|
817
|
-
}
|
|
818
|
-
} catch (error) {}
|
|
819
|
-
};
|
|
820
|
-
const trackTree = (node) => {
|
|
821
|
-
trackNode(node);
|
|
822
|
-
try {
|
|
823
|
-
if (!node || typeof node.querySelectorAll !== 'function') return;
|
|
824
|
-
const nested = node.querySelectorAll(rootSelector);
|
|
825
|
-
for (const nestedNode of nested) trackNode(nestedNode);
|
|
826
|
-
} catch (error) {}
|
|
827
|
-
};
|
|
828
|
-
const observer = typeof MutationObserver === 'function'
|
|
829
|
-
? new MutationObserver((mutations) => {
|
|
830
|
-
for (const mutation of mutations) {
|
|
831
|
-
const addedNodes = Array.from(mutation.addedNodes || []);
|
|
832
|
-
for (const addedNode of addedNodes) {
|
|
833
|
-
trackTree(addedNode);
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
})
|
|
837
|
-
: null;
|
|
838
|
-
try {
|
|
839
|
-
if (observer && document && document.documentElement) {
|
|
840
|
-
observer.observe(document.documentElement, {childList: true, subtree: true});
|
|
841
|
-
}
|
|
842
|
-
} catch (error) {}
|
|
843
|
-
const cleanupTrackedNodes = () => {
|
|
844
|
-
try {
|
|
845
|
-
if (observer) observer.disconnect();
|
|
846
|
-
} catch (error) {}
|
|
847
|
-
try {
|
|
848
|
-
const keyedNodes = Array.from(document.querySelectorAll(keyedSelector));
|
|
849
|
-
for (const keyedNode of keyedNodes) {
|
|
850
|
-
if (keyedNode && typeof keyedNode.remove === 'function') keyedNode.remove();
|
|
851
|
-
}
|
|
852
|
-
} catch (error) {}
|
|
853
|
-
try {
|
|
854
|
-
for (const trackedNode of trackedNodes) {
|
|
855
|
-
if (trackedNode && trackedNode.isConnected && typeof trackedNode.remove === 'function') {
|
|
856
|
-
trackedNode.remove();
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
} catch (error) {}
|
|
860
|
-
};
|
|
861
|
-
registry[bundleId] = {
|
|
862
|
-
cleanup: cleanupTrackedNodes,
|
|
863
|
-
generation: previousGeneration,
|
|
864
|
-
__extjsGeneration: previousGeneration
|
|
865
|
-
};
|
|
866
|
-
try {
|
|
867
|
-
if (typeof globalThis === 'object' && globalThis && extensionBase) {
|
|
868
|
-
globalThis.__EXTJS_EXTENSION_BASE__ = extensionBase;
|
|
869
|
-
}
|
|
870
|
-
if (typeof document === 'object' && document && document.documentElement && extensionBase) {
|
|
871
|
-
document.documentElement.setAttribute('data-extjs-extension-base', extensionBase);
|
|
872
|
-
}
|
|
873
|
-
(0, eval)(source);
|
|
874
|
-
} catch (error) {
|
|
875
|
-
return {
|
|
876
|
-
ok: false,
|
|
877
|
-
error: String((error && error.stack) || (error && error.message) || error || 'unknown'),
|
|
878
|
-
trackedRoots: trackedNodes.size,
|
|
879
|
-
existingRootCount: (() => {
|
|
880
|
-
try { return document.querySelectorAll(rootSelector).length; } catch (innerError) { return -1; }
|
|
881
|
-
})()
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
setTimeout(() => {
|
|
885
|
-
try {
|
|
886
|
-
const keyedNodes = Array.from(document.querySelectorAll(keyedSelector));
|
|
887
|
-
for (const keyedNode of keyedNodes) trackedNodes.add(keyedNode);
|
|
888
|
-
} catch (error) {}
|
|
889
|
-
}, 0);
|
|
890
|
-
setTimeout(() => {
|
|
891
|
-
try {
|
|
892
|
-
if (observer) observer.disconnect();
|
|
893
|
-
} catch (error) {}
|
|
894
|
-
}, 2000);
|
|
895
|
-
return {
|
|
896
|
-
ok: true,
|
|
897
|
-
trackedRoots: trackedNodes.size,
|
|
898
|
-
existingRootCount: (() => {
|
|
899
|
-
try { return document.querySelectorAll(rootSelector).length; } catch (innerError) { return -1; }
|
|
900
|
-
})(),
|
|
901
|
-
liveRoots: (() => {
|
|
902
|
-
try {
|
|
903
|
-
return Array.from(document.querySelectorAll(rootSelector)).map((node) => ({
|
|
904
|
-
key: node && typeof node.getAttribute === 'function' ? node.getAttribute('data-extjs-reinject-key') || null : null,
|
|
905
|
-
root: node && typeof node.getAttribute === 'function' ? node.getAttribute('data-extension-root') || null : null,
|
|
906
|
-
build: node && typeof node.getAttribute === 'function' ? node.getAttribute('data-extjs-reinject-build') || null : null,
|
|
907
|
-
text: String(node && node.textContent || '').slice(0, 120)
|
|
908
|
-
}));
|
|
909
|
-
} catch (error) {
|
|
910
|
-
return [];
|
|
911
|
-
}
|
|
912
|
-
})(),
|
|
913
|
-
hasChromeRuntime: (() => {
|
|
914
|
-
try { return !!(globalThis && globalThis.chrome && globalThis.chrome.runtime); } catch (error) { return false; }
|
|
915
|
-
})()
|
|
916
|
-
};
|
|
917
|
-
})()`;
|
|
918
|
-
}
|
|
919
|
-
patchReinjectSourceForInvalidatedRuntime(source) {
|
|
920
|
-
return source.replace('__webpack_require__.p = __webpack_require__.webExtRt.runtime.getURL("/");', 'try {\n __webpack_require__.p = __webpack_require__.webExtRt.runtime.getURL("/");\n} catch (_extjsRuntimeError) {\n if (__extjsBase) {\n __webpack_require__.p = __extjsBase.replace(/\\/+$/, "/") + String("/").replace(/^\\/+/, "");\n } else {\n __webpack_require__.p = "";\n }\n}');
|
|
921
|
-
}
|
|
922
|
-
async resolveExecutionContextId(sessionId, rule) {
|
|
923
|
-
if (!this.cdp) return;
|
|
924
|
-
const frameId = await this.getTopFrameId(sessionId);
|
|
925
|
-
const contexts = await this.collectExecutionContexts(sessionId);
|
|
926
|
-
if ('main' === rule.world) {
|
|
927
|
-
const defaultContext = contexts.find((context)=>{
|
|
928
|
-
const auxData = context?.auxData || {};
|
|
929
|
-
return 'default' === auxData.type && true === auxData.isDefault && (!frameId || !auxData.frameId || String(auxData.frameId) === frameId);
|
|
930
|
-
});
|
|
931
|
-
return 'number' == typeof defaultContext?.id ? defaultContext.id : void 0;
|
|
932
|
-
}
|
|
933
|
-
const extensionId = this.extensionId || await this.deriveExtensionIdFromTargets();
|
|
934
|
-
if (!extensionId) return;
|
|
935
|
-
const extensionOrigin = `chrome-extension://${extensionId}`;
|
|
936
|
-
const isolatedContext = contexts.find((context)=>{
|
|
937
|
-
const auxData = context?.auxData || {};
|
|
938
|
-
return 'isolated' === auxData.type && String(context?.origin || '') === extensionOrigin && (!frameId || !auxData.frameId || String(auxData.frameId) === frameId);
|
|
939
|
-
});
|
|
940
|
-
return 'number' == typeof isolatedContext?.id ? isolatedContext.id : void 0;
|
|
941
|
-
}
|
|
942
|
-
async getTopFrameId(sessionId) {
|
|
943
|
-
if (!this.cdp) return;
|
|
944
|
-
try {
|
|
945
|
-
const frameTree = await this.cdp.sendCommand('Page.getFrameTree', {}, sessionId);
|
|
946
|
-
const frameId = frameTree?.frameTree?.frame?.id;
|
|
947
|
-
return 'string' == typeof frameId && frameId ? frameId : void 0;
|
|
948
|
-
} catch {
|
|
949
|
-
return;
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
async collectExecutionContexts(sessionId) {
|
|
953
|
-
if (!this.cdp) return [];
|
|
954
|
-
const contextsById = new Map();
|
|
955
|
-
const unsubscribe = this.cdp.onProtocolEvent((message)=>{
|
|
956
|
-
if (String(message.sessionId || '') !== sessionId) return;
|
|
957
|
-
if ('Runtime.executionContextCreated' !== String(message.method || '')) return;
|
|
958
|
-
const context = message.params?.context;
|
|
959
|
-
const contextId = context?.id;
|
|
960
|
-
if ('number' == typeof contextId) contextsById.set(contextId, context);
|
|
961
|
-
});
|
|
962
|
-
try {
|
|
963
|
-
await this.cdp.sendCommand('Runtime.enable', {}, sessionId);
|
|
964
|
-
await new Promise((resolve)=>setTimeout(resolve, 100));
|
|
965
|
-
} finally{
|
|
966
|
-
unsubscribe();
|
|
967
|
-
}
|
|
968
|
-
return Array.from(contextsById.values());
|
|
969
|
-
}
|
|
970
|
-
constructor(args){
|
|
971
|
-
_define_property(this, "outPath", void 0);
|
|
972
|
-
_define_property(this, "browser", void 0);
|
|
973
|
-
_define_property(this, "cdpPort", void 0);
|
|
974
|
-
_define_property(this, "profilePath", void 0);
|
|
975
|
-
_define_property(this, "extensionPaths", void 0);
|
|
976
|
-
_define_property(this, "cdp", null);
|
|
977
|
-
_define_property(this, "extensionId", null);
|
|
978
|
-
_define_property(this, "lastRuntimeReinjectionReport", null);
|
|
979
|
-
this.outPath = args.outPath;
|
|
980
|
-
this.browser = args.browser;
|
|
981
|
-
this.cdpPort = args.cdpPort;
|
|
982
|
-
this.profilePath = args.profilePath;
|
|
983
|
-
this.extensionPaths = args.extensionPaths;
|
|
984
|
-
}
|
|
985
|
-
}
|
|
986
|
-
var extension_output_path = __webpack_require__("./webpack/plugin-browsers/run-chromium/chromium-launch/extension-output-path.ts");
|
|
987
|
-
async function setupCdpAfterLaunch(compilation, plugin, chromiumArgs) {
|
|
988
|
-
const loadExtensionFlag = chromiumArgs.find((flag)=>flag.startsWith('--load-extension='));
|
|
989
|
-
const extensionOutputPath = (0, extension_output_path.W)(compilation, loadExtensionFlag);
|
|
990
|
-
const extensionPaths = loadExtensionFlag ? loadExtensionFlag.replace('--load-extension=', '').split(',').map((s)=>s.trim()).filter(Boolean) : [];
|
|
991
|
-
const selectedExtensionPaths = extensionOutputPath && extensionOutputPath.length > 0 ? [
|
|
992
|
-
extensionOutputPath
|
|
993
|
-
] : extensionPaths;
|
|
994
|
-
const remoteDebugPortFlag = chromiumArgs.find((flag)=>flag.startsWith('--remote-debugging-port='));
|
|
995
|
-
const chromeRemoteDebugPort = remoteDebugPortFlag ? parseInt(remoteDebugPortFlag.split('=')[1], 10) : (0, shared_utils.jl)(plugin.port, plugin.instanceId);
|
|
996
|
-
const userDataDirFlag = chromiumArgs.find((flag)=>flag.startsWith('--user-data-dir='));
|
|
997
|
-
const userDataDir = userDataDirFlag ? userDataDirFlag.replace('--user-data-dir=', '').replace(/^"|"$/g, '') : '';
|
|
998
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) {
|
|
999
|
-
if (userDataDir) console.log(messages.aIt(userDataDir));
|
|
1000
|
-
console.log(messages.CYH(chromeRemoteDebugPort, chromeRemoteDebugPort));
|
|
1001
|
-
}
|
|
1002
|
-
const cdpExtensionController = new CDPExtensionController({
|
|
1003
|
-
outPath: extensionOutputPath,
|
|
1004
|
-
browser: 'chromium-based' === plugin.browser ? 'chrome' : plugin.browser,
|
|
1005
|
-
cdpPort: chromeRemoteDebugPort,
|
|
1006
|
-
profilePath: userDataDir || void 0,
|
|
1007
|
-
extensionPaths: selectedExtensionPaths
|
|
1008
|
-
});
|
|
1009
|
-
await cdpExtensionController.connect();
|
|
1010
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.log(messages.M3V('127.0.0.1', chromeRemoteDebugPort));
|
|
1011
|
-
const mode = compilation?.options?.mode || 'development';
|
|
1012
|
-
let earlyBannerPrinted = false;
|
|
1013
|
-
if ('development' === mode) try {
|
|
1014
|
-
earlyBannerPrinted = await (0, banner.a)({
|
|
1015
|
-
outPath: extensionOutputPath,
|
|
1016
|
-
browser: plugin.browser,
|
|
1017
|
-
hostPort: {
|
|
1018
|
-
host: '127.0.0.1',
|
|
1019
|
-
port: chromeRemoteDebugPort
|
|
1020
|
-
},
|
|
1021
|
-
getInfo: async ()=>null,
|
|
1022
|
-
browserVersionLine: plugin.browserVersionLine
|
|
1023
|
-
});
|
|
1024
|
-
} catch {}
|
|
1025
|
-
if ('development' === mode) try {
|
|
1026
|
-
earlyBannerPrinted = await (0, banner.a)({
|
|
1027
|
-
outPath: extensionOutputPath,
|
|
1028
|
-
browser: plugin.browser,
|
|
1029
|
-
hostPort: {
|
|
1030
|
-
host: '127.0.0.1',
|
|
1031
|
-
port: chromeRemoteDebugPort
|
|
1032
|
-
},
|
|
1033
|
-
getInfo: async ()=>cdpExtensionController.getInfoBestEffort(),
|
|
1034
|
-
browserVersionLine: plugin.browserVersionLine
|
|
1035
|
-
});
|
|
1036
|
-
} catch {}
|
|
1037
|
-
let extensionControllerInfo = null;
|
|
1038
|
-
try {
|
|
1039
|
-
const ensureLoadedTimeoutMs = 10000;
|
|
1040
|
-
extensionControllerInfo = await Promise.race([
|
|
1041
|
-
cdpExtensionController.ensureLoaded(),
|
|
1042
|
-
new Promise((_, reject)=>{
|
|
1043
|
-
setTimeout(()=>reject(new Error(`ensureLoaded timeout (${ensureLoadedTimeoutMs}ms)`)), ensureLoadedTimeoutMs);
|
|
1044
|
-
})
|
|
1045
|
-
]);
|
|
1046
|
-
} catch (error) {
|
|
1047
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(`[CDP] ensureLoaded failed: ${String(error?.message || error)}`);
|
|
1048
|
-
}
|
|
1049
|
-
try {
|
|
1050
|
-
if ('development' === mode) {
|
|
1051
|
-
if (!earlyBannerPrinted) {
|
|
1052
|
-
const bannerPrinted = await (0, banner.a)({
|
|
1053
|
-
outPath: extensionOutputPath,
|
|
1054
|
-
browser: plugin.browser,
|
|
1055
|
-
hostPort: {
|
|
1056
|
-
host: '127.0.0.1',
|
|
1057
|
-
port: chromeRemoteDebugPort
|
|
1058
|
-
},
|
|
1059
|
-
getInfo: async ()=>extensionControllerInfo,
|
|
1060
|
-
browserVersionLine: plugin.browserVersionLine
|
|
1061
|
-
});
|
|
1062
|
-
if (!bannerPrinted) await (0, banner.a)({
|
|
1063
|
-
outPath: extensionOutputPath,
|
|
1064
|
-
browser: plugin.browser,
|
|
1065
|
-
hostPort: {
|
|
1066
|
-
host: '127.0.0.1',
|
|
1067
|
-
port: chromeRemoteDebugPort
|
|
1068
|
-
},
|
|
1069
|
-
getInfo: async ()=>cdpExtensionController.getInfoBestEffort(),
|
|
1070
|
-
browserVersionLine: plugin.browserVersionLine
|
|
1071
|
-
});
|
|
1072
|
-
}
|
|
1073
|
-
} else if ('production' === mode) {
|
|
1074
|
-
const runtime = extensionControllerInfo ? {
|
|
1075
|
-
extensionId: extensionControllerInfo.extensionId,
|
|
1076
|
-
name: extensionControllerInfo.name,
|
|
1077
|
-
version: extensionControllerInfo.version
|
|
1078
|
-
} : void 0;
|
|
1079
|
-
await (0, banner.M)({
|
|
1080
|
-
browser: plugin.browser,
|
|
1081
|
-
outPath: extensionOutputPath,
|
|
1082
|
-
browserVersionLine: plugin.browserVersionLine,
|
|
1083
|
-
runtime
|
|
1084
|
-
});
|
|
1085
|
-
}
|
|
1086
|
-
} catch (bannerErr) {
|
|
1087
|
-
if ('true' === process.env.EXTENSION_AUTHOR_MODE) console.warn(messages.$wD(String(bannerErr)));
|
|
1088
|
-
try {
|
|
1089
|
-
const mode = compilation?.options?.mode || 'development';
|
|
1090
|
-
if ('production' === mode) await (0, banner.M)({
|
|
1091
|
-
browser: plugin.browser,
|
|
1092
|
-
outPath: extensionOutputPath,
|
|
1093
|
-
browserVersionLine: plugin.browserVersionLine
|
|
1094
|
-
});
|
|
1095
|
-
} catch {}
|
|
1096
|
-
}
|
|
1097
|
-
plugin.cdpController = cdpExtensionController;
|
|
1098
|
-
}
|
|
1099
|
-
}
|
|
1100
|
-
};
|