/
web-ext-emulator.ts
216 lines (197 loc) · 6.31 KB
/
web-ext-emulator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { existsSync, mkdirSync, readFileSync, createReadStream } from 'fs';
import { createContext, runInContext } from 'vm';
import { join } from 'path';
import { createInterface } from 'readline';
import * as setGlobalVars from 'indexeddbshim';
import * as indexedDB from 'fake-indexeddb';
import * as IDBKeyRange from 'fake-indexeddb/lib/FDBKeyRange';
import createChrome from './chrome';
import createWindow, { WindowConfig } from './window'
import MockBrowser from './mock-browser'
export interface EmulatorConfig extends WindowConfig {
injectWebextenionPolyfill?: boolean
chromeStoragePath?: string
indexedDBPath?: string
}
const DEFAULT_CONFIG: EmulatorConfig = {
quiet: false,
injectWebextenionPolyfill: false,
chromeStoragePath: './storage',
indexedDBPath: './idb',
}
interface Global {
[key: string]: any
}
export default class WebExtensionEmulator {
extensionBaseDir: string
options: EmulatorConfig
probes: {
[key: string]: any[]
}
chrome: Global
window: Global
sandbox: Global
mock: MockBrowser
constructor(extensionBaseDir: string, options: EmulatorConfig) {
this.extensionBaseDir = extensionBaseDir;
this.options = Object.assign({}, DEFAULT_CONFIG, options);
this.probes = {};
const probeFn = this.options.probe || this._probe.bind(this);
this.chrome = createChrome({
extensionDir: this.extensionBaseDir,
storageDir: this.options.chromeStoragePath,
probe: probeFn,
});
this.window = createWindow({
fetchBaseDirectory: this.extensionBaseDir,
probe: probeFn,
...options,
});
this.window.chrome = this.chrome;
this.window.browser = this.chrome;
this.mock = new MockBrowser(this.window, this.chrome);
}
addChromeApi(name, value) {
this.chrome[name] = value;
}
createSandbox() {
const sandbox = {
get window() {
return sandbox
},
get self() {
return sandbox
},
get global() {
return sandbox
},
...this.window
};
// create mock Indexeddb
if (this.options.indexedDBPath) {
if (!existsSync(this.options.indexedDBPath)) {
mkdirSync(this.options.indexedDBPath);
}
setGlobalVars(sandbox, {
checkOrigin: false,
databaseBasePath: this.options.indexedDBPath,
replaceNonIDBGlobals: true,
});
} else {
sandbox.indexedDB = indexedDB;
sandbox.IDBKeyRange = IDBKeyRange;
}
createContext(sandbox);
this.sandbox = sandbox;
if (this.options.injectWebextenionPolyfill) {
const polyfill = require.resolve('webextension-polyfill');
this._runScriptInSandbox(polyfill);
}
return this.sandbox;
}
_runScriptInSandbox(scriptPath: string) {
const code = readFileSync(scriptPath, { encoding: 'utf8' });
this._runCodeInSandbox(scriptPath, code)
}
_runCodeInSandbox(scriptPath: string, code: string) {
runInContext(code, this.sandbox, {
filename: scriptPath,
displayErrors: true,
});
}
_probe(key: string, value: any) {
if (!this.probes[key]) {
this.probes[key] = []
}
this.probes[key].push(value);
}
startExtension() {
this.chrome.runtime.getManifest().background.scripts.forEach(script => {
this._runScriptInSandbox(join(this.extensionBaseDir, script));
});
}
stopExtension() {
this.window.unload();
}
probeStorage() {
this._probe('storage.local.size', this.chrome.storage.local.size());
this._probe('storage.local.writes', this.chrome.storage.local.writes);
this._probe('storage.sync.size', this.chrome.storage.sync.size());
}
emulateSession(sessionFile: string, filterApis?: Set<string>): Promise<void> {
return new Promise((resolve) => {
const start = Date.now();
let firstTs = null;
const lineReader = createInterface({
input: createReadStream(sessionFile),
});
let tick: Promise<{}> = Promise.resolve({});
lineReader.on('line', (line) => {
const { api, event, args, ts } = JSON.parse(line);
if (!firstTs) {
firstTs = ts;
}
// console.log(api, event, args);
if (!this.chrome[api]) {
console.error('api missing', api)
return;
}
if (!this.chrome[api][event]) {
console.error('event missing', api, event);
return
}
if (filterApis && filterApis.has(api)) {
return;
} else if (api === 'runtime') {
if (event === 'onConnect') {
const port = Object.assign(args[0], this.chrome.runtime.connect());
args[0] = port;
} else if (event === 'onMessage') {
// add respond function
args[2] = () => {
this._probe('chrome.runtime.onMessage', `${args[0].module}.${args[0].action}`);
};
}
}
tick = tick.then(() => {
const virtualElapsed = ts - firstTs;
const actualElapsed = Date.now() - start;
const runEventAt = virtualElapsed / this.options.timeMultiplier;
const nextEventIn = runEventAt - actualElapsed;
if (nextEventIn < 1) {
this.chrome[api][event].trigger(...args);
} else {
return new Promise((resolve) => {
setTimeout(() => {
try {
this.chrome[api][event].trigger(...args);
} catch (e) {
console.error(e);
}
resolve();
}, nextEventIn);
});
}
});
});
lineReader.on('close', () => {
tick.then(() => {
resolve();
});
});
});
}
getProbeSummary() {
const get = (key: string) => this.probes[key] || [];
const sum = (a: number, b: number): number => a + b;
return {
memory: Math.max(...get('memory.heap')),
httpRequests: get('xmlhttprequest.remote.url').length + get('fetch.remote.url').length,
networkData: get('xmlhttprequest.remote.size').reduce(sum, 0) + get('fetch.remote.size').reduce(sum, 0),
contentMessages: get('chrome.tabs.message').length + get('chrome.tabs.postMessage').length + get('chrome.runtime.postMessage').length,
runtimeMessagesResponded: get('chrome.runtime.onMessage').length,
storage: get('storage.local.size')[0],
storageWrites: get('storage.local.writes')[0],
}
}
}