-
Notifications
You must be signed in to change notification settings - Fork 209
/
worker-thread.ts
273 lines (250 loc) · 7.07 KB
/
worker-thread.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { WebPHP, WebPHPEndpoint, exposeAPI } from '@php-wasm/web';
import { EmscriptenDownloadMonitor } from '@php-wasm/progress';
import { setURLScope } from '@php-wasm/scopes';
import { DOCROOT, wordPressSiteUrl } from './config';
import {
getWordPressModuleDetails,
LatestSupportedWordPressVersion,
SupportedWordPressVersions,
} from '@wp-playground/wordpress-builds';
import {
envPHP_to_loadMuPlugins,
playgroundMuPlugin,
wordPressRewriteRules,
} from '@wp-playground/wordpress';
import {
PHPRequestHandler,
proxyFileSystem,
writeFiles,
} from '@php-wasm/universal';
import {
SyncProgressCallback,
bindOpfs,
playgroundAvailableInOpfs,
} from './opfs/bind-opfs';
import {
defineSiteUrl,
defineWpConfigConsts,
unzip,
} from '@wp-playground/blueprints';
/** @ts-ignore */
import transportFetch from './playground-mu-plugin/playground-includes/wp_http_fetch.php?raw';
/** @ts-ignore */
import transportDummy from './playground-mu-plugin/playground-includes/wp_http_dummy.php?raw';
/** @ts-ignore */
import playgroundWebMuPlugin from './playground-mu-plugin/0-playground.php?raw';
import { joinPaths, randomString } from '@php-wasm/util';
import {
requestedWPVersion,
createPhp,
startupOptions,
monitoredFetch,
downloadMonitor,
} from './worker-utils';
import {
FilesystemOperation,
journalFSEvents,
replayFSJournal,
} from '@php-wasm/fs-journal';
const scope = Math.random().toFixed(16);
// post message to parent
self.postMessage('worker-script-started');
let virtualOpfsRoot: FileSystemDirectoryHandle | undefined;
let virtualOpfsDir: FileSystemDirectoryHandle | undefined;
let lastOpfsDir: FileSystemDirectoryHandle | undefined;
let wordPressAvailableInOPFS = false;
if (
startupOptions.storage === 'browser' &&
// @ts-ignore
typeof navigator?.storage?.getDirectory !== 'undefined'
) {
virtualOpfsRoot = await navigator.storage.getDirectory();
virtualOpfsDir = await virtualOpfsRoot.getDirectoryHandle('wordpress', {
create: true,
});
// eslint-disable-next-line @typescript-eslint/no-unused-vars
lastOpfsDir = virtualOpfsDir;
wordPressAvailableInOPFS = await playgroundAvailableInOpfs(virtualOpfsDir!);
}
// Start downloading WordPress if needed
let wordPressRequest = null;
if (!wordPressAvailableInOPFS) {
if (requestedWPVersion.startsWith('http')) {
// We don't know the size upfront, but we can still monitor the download.
// monitorFetch will read the content-length response header when available.
wordPressRequest = monitoredFetch(requestedWPVersion);
} else {
const wpDetails = getWordPressModuleDetails(startupOptions.wpVersion);
downloadMonitor.expectAssets({
[wpDetails.url]: wpDetails.size,
});
wordPressRequest = monitoredFetch(wpDetails.url);
}
}
/** @inheritDoc PHPClient */
export class PlaygroundWorkerEndpoint extends WebPHPEndpoint {
/**
* A string representing the scope of the Playground instance.
*/
scope: string;
/**
* A string representing the version of WordPress being used.
*/
wordPressVersion: string;
constructor(
requestHandler: PHPRequestHandler<WebPHP>,
monitor: EmscriptenDownloadMonitor,
scope: string,
wordPressVersion: string
) {
super(requestHandler, monitor);
this.scope = scope;
this.wordPressVersion = wordPressVersion;
}
/**
* @returns WordPress module details, including the static assets directory and default theme.
*/
async getWordPressModuleDetails() {
return {
majorVersion: this.wordPressVersion,
staticAssetsDirectory: `wp-${this.wordPressVersion.replace(
'_',
'.'
)}`,
};
}
async getSupportedWordPressVersions() {
return {
all: SupportedWordPressVersions,
latest: LatestSupportedWordPressVersion,
};
}
async resetVirtualOpfs() {
if (!virtualOpfsRoot) {
throw new Error('No virtual OPFS available.');
}
await virtualOpfsRoot.removeEntry(virtualOpfsDir!.name, {
recursive: true,
});
}
async reloadFilesFromOpfs() {
await this.bindOpfs(lastOpfsDir!);
}
async bindOpfs(
opfs: FileSystemDirectoryHandle,
onProgress?: SyncProgressCallback
) {
lastOpfsDir = opfs;
await bindOpfs({
php: this.__internal_getPHP()!,
opfs,
onProgress,
});
}
async journalFSEvents(
root: string,
callback: (op: FilesystemOperation) => void
) {
return journalFSEvents(this.__internal_getPHP()!, root, callback);
}
async replayFSJournal(events: FilesystemOperation[]) {
return replayFSJournal(this.__internal_getPHP()!, events);
}
}
const scopedSiteUrl = setURLScope(wordPressSiteUrl, scope).toString();
const requestHandler = new PHPRequestHandler({
phpFactory: async ({ isPrimary }) => {
const php = await createPhp(requestHandler);
php.defineConstant('SCOPED_SITE_PATH', new URL(scopedSiteUrl).pathname);
if (isPrimary) {
php.writeFile(
'/internal/shared/preload/env.php',
envPHP_to_loadMuPlugins
);
php.writeFile(
'/internal/shared/preload/phpinfo.php',
`<?php
// Render PHPInfo if the requested page is /phpinfo.php
if ( SCOPED_SITE_PATH . '/phpinfo.php' === $_SERVER['REQUEST_URI'] ) {
phpinfo();
exit;
}
`
);
} else {
proxyFileSystem(await requestHandler.getPrimaryPhp(), php, [
'/tmp',
requestHandler.documentRoot,
'/internal/shared',
]);
}
return php;
},
documentRoot: DOCROOT,
absoluteUrl: scopedSiteUrl,
rewriteRules: wordPressRewriteRules,
});
const apiEndpoint = new PlaygroundWorkerEndpoint(
requestHandler,
downloadMonitor,
scope,
startupOptions.wpVersion
);
const [setApiReady, setAPIError] = exposeAPI(apiEndpoint);
try {
const primaryPhp = await requestHandler.getPrimaryPhp();
await apiEndpoint.setPrimaryPHP(primaryPhp);
// If WordPress isn't already installed, download and extract it from
// the zip file.
if (!wordPressAvailableInOPFS) {
await unzip(primaryPhp, {
zipFile: new File(
[await (await wordPressRequest!).blob()],
'wp.zip'
),
extractToPath: requestHandler.documentRoot,
});
// Randomize the WordPress secrets
await defineWpConfigConsts(primaryPhp, {
consts: {
WP_DEBUG: true,
WP_DEBUG_LOG: true,
WP_DEBUG_DISPLAY: false,
AUTH_KEY: randomString(40),
SECURE_AUTH_KEY: randomString(40),
LOGGED_IN_KEY: randomString(40),
NONCE_KEY: randomString(40),
AUTH_SALT: randomString(40),
SECURE_AUTH_SALT: randomString(40),
LOGGED_IN_SALT: randomString(40),
NONCE_SALT: randomString(40),
},
});
}
// Always install the playground mu-plugin, even if WordPress is loaded
// from the OPFS. This ensures:
// * The mu-plugin is always there, even when a custom WordPress directory
// is mounted.
// * The mu-plugin is always up to date.
await writeFiles(primaryPhp, joinPaths('/internal/shared/mu-plugins'), {
'0-playground.php': playgroundMuPlugin,
'1-playground-web.php': playgroundWebMuPlugin,
'playground-includes/wp_http_dummy.php': transportDummy,
'playground-includes/wp_http_fetch.php': transportFetch,
});
if (virtualOpfsDir) {
await bindOpfs({
php: primaryPhp,
opfs: virtualOpfsDir!,
wordPressAvailableInOPFS,
});
}
// Always setup the current site URL.
await defineSiteUrl(primaryPhp, {
siteUrl: scopedSiteUrl,
});
setApiReady();
} catch (e) {
setAPIError(e as Error);
throw e;
}