UNPKG

@roots/bud-extensions

Version:

bud.js core module

106 lines (105 loc) 3.45 kB
import { __decorate } from "tslib"; import { Extension } from '@roots/bud-framework/extension'; import { bind, disabled, expose, label, options, } from '@roots/bud-framework/extension/decorators'; import isString from '@roots/bud-support/isString'; import isUndefined from '@roots/bud-support/isUndefined'; import Value from '@roots/bud-support/value'; /** * Http modules configuration */ let Cdn = class Cdn extends Extension { /** * Whether to cache modules locally */ cacheEnabled = true; /** * CDN key to URL mapping */ sources = new Map([ [`esm.sh`, `https://esm.sh/`], [`gist`, `https://gist.githubusercontent.com/`], [`github`, `https://raw.githubusercontent.com/`], [`skypack`, `https://cdn.skypack.dev/`], [`unpkg`, `https://unpkg.com/`], ]); /** * {@link Extension.buildBefore} */ async buildBefore(bud) { bud.hooks.on(`build.experiments`, experiments => ({ ...(experiments ?? {}), buildHttp: { allowedUris: Array.from(this.allowedUris ?? []), cacheLocation: this.cacheEnabled ? this.cacheLocation : false, frozen: this.frozen, lockfileLocation: this.lockfileLocation, proxy: isString(this.proxy) ? this.proxy : undefined, upgrade: this.upgrade, }, })); Object.entries(bud.build.rules).map(([key, rule]) => { if (key === `js` || key === `ts`) return; rule.setInclude([ ...(!rule.include ? [bud.path()] : Array.isArray(rule.include) ? rule.include : []), ...Array.from(this.allowedUris ?? []), ]); }); const NormalModuleReplacementPlugin = await import(`webpack/lib/NormalModuleReplacementPlugin.js`).then(m => m.default); for (const [ident, url] of this.sources.entries()) { await bud.extensions.add({ make: async () => new NormalModuleReplacementPlugin(new RegExp(`^${ident}:`), result => { result.request = result.request.replace(`${ident}:`, url); }), }); } } disableCache() { this.cacheEnabled = false; return this; } /** * Enable cache */ enableCache(enabled = true) { this.cacheEnabled = enabled; return this; } /** * Prevent bud from fetching updated modules */ freeze(value) { this.setFrozen(!isUndefined(value) ? value : true); return this; } }; __decorate([ bind ], Cdn.prototype, "buildBefore", null); __decorate([ bind ], Cdn.prototype, "disableCache", null); __decorate([ bind ], Cdn.prototype, "enableCache", null); __decorate([ bind ], Cdn.prototype, "freeze", null); Cdn = __decorate([ label(`@roots/bud-extensions/cdn`), expose(`cdn`), options({ allowedUris: new Set([/^http:\/\//, /^https:\/\//]), cacheLocation: Value.make(({ label, path }) => path(`@storage`, label, `modules`)), frozen: false, lockfileLocation: Value.make(({ path }) => path(`bud.lock`)), proxy: Value.make(({ env }) => env.isString(`HTTP_PROXY`) && env.get(`HTTP_PROXY`)), upgrade: true, }), disabled ], Cdn); export default Cdn;