-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathresources.ts
426 lines (382 loc) · 9.67 KB
/
resources.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import {
cloneResponseMonitorProgress,
ProgressTracker,
} from '@php-wasm/progress';
import { UniversalPHP } from '@php-wasm/universal';
import { Semaphore } from '@php-wasm/util';
import { zipNameToHumanName } from './utils/zip-name-to-human-name';
export const ResourceTypes = [
'vfs',
'literal',
'wordpress.org/themes',
'wordpress.org/plugins',
'url',
] as const;
export type VFSReference = {
/** Identifies the file resource as Virtual File System (VFS) */
resource: 'vfs';
/** The path to the file in the VFS */
path: string;
};
export type LiteralReference = {
/** Identifies the file resource as a literal file */
resource: 'literal';
/** The name of the file */
name: string;
/** The contents of the file */
contents: string | Uint8Array;
};
export type CoreThemeReference = {
/** Identifies the file resource as a WordPress Core theme */
resource: 'wordpress.org/themes';
/** The slug of the WordPress Core theme */
slug: string;
};
export type CorePluginReference = {
/** Identifies the file resource as a WordPress Core plugin */
resource: 'wordpress.org/plugins';
/** The slug of the WordPress Core plugin */
slug: string;
};
export type UrlReference = {
/** Identifies the file resource as a URL */
resource: 'url';
/** The URL of the file */
url: string;
/** Optional caption for displaying a progress message */
caption?: string;
};
export type FileReference =
| VFSReference
| LiteralReference
| CoreThemeReference
| CorePluginReference
| UrlReference;
export function isFileReference(ref: any): ref is FileReference {
return (
ref &&
typeof ref === 'object' &&
typeof ref.resource === 'string' &&
ResourceTypes.includes(ref.resource)
);
}
export interface ResourceOptions {
/** Optional semaphore to limit concurrent downloads */
semaphore?: Semaphore;
progress?: ProgressTracker;
}
export abstract class Resource {
/** Optional progress tracker to monitor progress */
public abstract progress?: ProgressTracker;
/** A Promise that resolves to the file contents */
protected promise?: Promise<File>;
protected playground?: UniversalPHP;
/**
* Creates a new Resource based on the given file reference
*
* @param ref The file reference to create the Resource for
* @param options Additional options for the Resource
* @returns A new Resource instance
*/
static create(
ref: FileReference,
{ semaphore, progress }: ResourceOptions
): Resource {
let resource: Resource;
switch (ref.resource) {
case 'vfs':
resource = new VFSResource(ref, progress);
break;
case 'literal':
resource = new LiteralResource(ref, progress);
break;
case 'wordpress.org/themes':
resource = new CoreThemeResource(ref, progress);
break;
case 'wordpress.org/plugins':
resource = new CorePluginResource(ref, progress);
break;
case 'url':
resource = new UrlResource(ref, progress);
break;
default:
throw new Error(`Invalid resource: ${ref}`);
}
resource = new CachedResource(resource);
if (semaphore) {
resource = new SemaphoreResource(resource, semaphore);
}
return resource;
}
setPlayground(playground: UniversalPHP) {
this.playground = playground;
}
/**
* Resolves the file contents
* @returns The resolved file.
*/
abstract resolve(): Promise<File>;
/** The name of the referenced file */
abstract get name(): string;
/** Whether this Resource is loaded asynchronously */
get isAsync(): boolean {
return false;
}
}
/**
* A `Resource` that represents a file in the VFS (virtual file system) of the playground.
*/
export class VFSResource extends Resource {
/**
* Creates a new instance of `VFSResource`.
* @param playground The playground client.
* @param resource The VFS reference.
* @param progress The progress tracker.
*/
constructor(
private resource: VFSReference,
public override progress?: ProgressTracker
) {
super();
}
/** @inheritDoc */
async resolve() {
const buffer = await this.playground!.readFileAsBuffer(
this.resource.path
);
this.progress?.set(100);
return new File([buffer], this.name);
}
/** @inheritDoc */
get name() {
return this.resource.path.split('/').pop() || '';
}
}
/**
* A `Resource` that represents a literal file.
*/
export class LiteralResource extends Resource {
/**
* Creates a new instance of `LiteralResource`.
* @param resource The literal reference.
* @param progress The progress tracker.
*/
constructor(
private resource: LiteralReference,
public override progress?: ProgressTracker
) {
super();
}
/** @inheritDoc */
async resolve() {
this.progress?.set(100);
return new File([this.resource.contents], this.resource.name);
}
/** @inheritDoc */
get name() {
return this.resource.name;
}
}
/**
* A base class for `Resource`s that require fetching data from a remote URL.
*/
export abstract class FetchResource extends Resource {
/**
* Creates a new instance of `FetchResource`.
* @param progress The progress tracker.
*/
constructor(public override progress?: ProgressTracker) {
super();
}
/** @inheritDoc */
async resolve() {
this.progress?.setCaption(this.caption);
const url = this.getURL();
try {
let response = await fetch(url);
if (!response.ok) {
throw new Error(`Could not download "${url}"`);
}
response = await cloneResponseMonitorProgress(
response,
this.progress?.loadingListener ?? noop
);
if (response.status !== 200) {
throw new Error(`Could not download "${url}"`);
}
return new File([await response.blob()], this.name);
} catch (e) {
throw new Error(`
Could not download "${url}".
Check if the URL is correct and the server is reachable.
If it's reachable, the server might be blocking the request.
Check the console and network for more information.
In case of a CORS error, you can try using a proxy server.
Error:
${e}`);
}
}
/**
* Gets the URL to fetch the data from.
* @returns The URL.
*/
protected abstract getURL(): string;
/**
* Gets the caption for the progress tracker.
* @returns The caption.
*/
protected get caption() {
return `Downloading ${this.name}`;
}
/** @inheritDoc */
get name() {
try {
return new URL(this.getURL(), 'http://example.com').pathname
.split('/')
.pop()!;
} catch (e) {
return this.getURL();
}
}
/** @inheritDoc */
override get isAsync(): boolean {
return true;
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = (() => {}) as any;
/**
* A `Resource` that represents a file available from a URL.
*/
export class UrlResource extends FetchResource {
/**
* Creates a new instance of `UrlResource`.
* @param resource The URL reference.
* @param progress The progress tracker.
*/
constructor(private resource: UrlReference, progress?: ProgressTracker) {
super(progress);
}
/** @inheritDoc */
getURL() {
return this.resource.url;
}
/** @inheritDoc */
protected override get caption() {
return this.resource.caption ?? super.caption;
}
}
/**
* A `Resource` that represents a WordPress core theme.
*/
export class CoreThemeResource extends FetchResource {
constructor(
private resource: CoreThemeReference,
progress?: ProgressTracker
) {
super(progress);
}
override get name() {
return zipNameToHumanName(this.resource.slug);
}
getURL() {
const zipName = toDirectoryZipName(this.resource.slug);
return `https://downloads.wordpress.org/theme/${zipName}`;
}
}
/**
* A resource that fetches a WordPress plugin from wordpress.org.
*/
export class CorePluginResource extends FetchResource {
constructor(
private resource: CorePluginReference,
progress?: ProgressTracker
) {
super(progress);
}
/** @inheritDoc */
override get name() {
return zipNameToHumanName(this.resource.slug);
}
/** @inheritDoc */
getURL() {
const zipName = toDirectoryZipName(this.resource.slug);
return `https://downloads.wordpress.org/plugin/${zipName}`;
}
}
/**
* Transforms a plugin slug into a directory zip name.
* If the input already ends with ".zip", returns it unchanged.
* Otherwise, appends ".latest-stable.zip".
*/
export function toDirectoryZipName(rawInput: string) {
if (!rawInput) {
return rawInput;
}
if (rawInput.endsWith('.zip')) {
return rawInput;
}
return rawInput + '.latest-stable.zip';
}
/**
* A decorator for a resource that adds functionality such as progress tracking and caching.
*/
export class DecoratedResource<T extends Resource> extends Resource {
constructor(private resource: T) {
super();
}
/** @inheritDoc */
async resolve() {
return this.resource.resolve();
}
/** @inheritDoc */
override async setPlayground(playground: UniversalPHP) {
return this.resource.setPlayground(playground);
}
/** @inheritDoc */
get progress() {
return this.resource.progress;
}
/** @inheritDoc */
set progress(value) {
this.resource.progress = value;
}
/** @inheritDoc */
get name() {
return this.resource.name;
}
/** @inheritDoc */
override get isAsync() {
return this.resource.isAsync;
}
}
/**
* A decorator for a resource that adds caching functionality.
*/
export class CachedResource<T extends Resource> extends DecoratedResource<T> {
protected override promise?: Promise<File>;
/** @inheritDoc */
override async resolve() {
if (!this.promise) {
this.promise = super.resolve();
}
return this.promise;
}
}
/**
* A decorator for a resource that adds concurrency control functionality through a semaphore.
*/
export class SemaphoreResource<
T extends Resource
> extends DecoratedResource<T> {
constructor(resource: T, private readonly semaphore: Semaphore) {
super(resource);
}
/** @inheritDoc */
override async resolve() {
if (!this.isAsync) {
return super.resolve();
}
return this.semaphore.run(() => super.resolve());
}
}