Files
node-pkg-express-utils/src/polyfill.ts
Sebastian Seedorf 40b148b7c7 Enforce single quotes
2020-11-19 20:40:21 +01:00

56 lines
1.5 KiB
TypeScript

import {RequestHandler} from 'express';
import * as polyfillLibrary from 'polyfill-library';
import {DefaultConfig, Logger, WaitForSync} from '.';
import {spawn, Thread, Worker} from 'threads';
import {WorkerFunction} from 'threads/dist/types/worker';
export type PolyfillFeatureList = {
[featureName: string]: {
flags?: string[]
}
};
export type PolyfillOptions = {
minify: boolean,
unknown: 'polyfill'|'ignore',
features: PolyfillFeatureList,
excludes: string[],
uaString: string,
rum: boolean,
}
function getRouter(fileToWatch: string, opts?: Partial<PolyfillOptions>): RequestHandler {
const features = new WaitForSync<PolyfillFeatureList>();
(async () => {
const worker = await spawn<WorkerFunction>(new Worker('./polyfill-worker'));
const feats = await worker(fileToWatch) as PolyfillFeatureList;
await Thread.terminate(worker);
return feats;
})()
.then(feats => {
feats['fetch'] = {};
Logger.debug('Polyfill analysed:', Object.keys(feats));
features.setData(feats);
})
.catch(err => features.setError(err));
const options: Partial<PolyfillOptions> = {
minify: DefaultConfig.isProduction,
unknown: 'polyfill',
...opts,
};
return async (req, res) => {
const polyfillBundle = await polyfillLibrary.getPolyfillString({
...options,
uaString: req.header('user-agent'),
features: await features.resolve(),
stream: false,
});
res.setHeader('Content-Type', 'text/javascript');
res.send(polyfillBundle);
};
}
export const Polyfill = {
getRouter: getRouter,
};