feat: frontend PWA scaffolding with React and Tailwind

This commit is contained in:
Daniel Bedeleanu
2026-04-10 14:05:50 +03:00
parent 373652e8b8
commit 7f8b24aabb
33622 changed files with 4317382 additions and 0 deletions

19
frontend/node_modules/workbox-webpack-plugin/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright 2018 Google LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1 @@
This module's documentation can be found at https://developer.chrome.com/docs/workbox/modules/workbox-webpack-plugin/

View File

@@ -0,0 +1,72 @@
import webpack from 'webpack';
import { ManifestEntry, WebpackGenerateSWOptions } from 'workbox-build';
export interface GenerateSWConfig extends WebpackGenerateSWOptions {
manifestEntries?: Array<ManifestEntry>;
}
/**
* This class supports creating a new, ready-to-use service worker file as
* part of the webpack compilation process.
*
* Use an instance of `GenerateSW` in the
* [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
* webpack config.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* new GenerateSW({
* exclude: [/.../, '...'],
* maximumFileSizeToCacheInBytes: ...,
* navigateFallback: '...',
* runtimeCaching: [{
* // Routing via a matchCallback function:
* urlPattern: ({request, url}) => ...,
* handler: '...',
* options: {
* cacheName: '...',
* expiration: {
* maxEntries: ...,
* },
* },
* }, {
* // Routing via a RegExp:
* urlPattern: new RegExp('...'),
* handler: '...',
* options: {
* cacheName: '...',
* plugins: [..., ...],
* },
* }],
* skipWaiting: ...,
* });
* ```
*
* @memberof module:workbox-webpack-plugin
*/
declare class GenerateSW {
protected config: GenerateSWConfig;
private alreadyCalled;
/**
* Creates an instance of GenerateSW.
*/
constructor(config?: GenerateSWConfig);
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
propagateWebpackConfig(compiler: webpack.Compiler): void;
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
apply(compiler: webpack.Compiler): void;
/**
* @param {Object} compilation The webpack compilation.
*
* @private
*/
addAssets(compilation: webpack.Compilation): Promise<void>;
}
export { GenerateSW };

View File

@@ -0,0 +1,189 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GenerateSW = void 0;
const validate_options_1 = require("workbox-build/build/lib/validate-options");
const bundle_1 = require("workbox-build/build/lib/bundle");
const populate_sw_template_1 = require("workbox-build/build/lib/populate-sw-template");
const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
const webpack_1 = __importDefault(require("webpack"));
const get_script_files_for_chunks_1 = require("./lib/get-script-files-for-chunks");
const get_manifest_entries_from_compilation_1 = require("./lib/get-manifest-entries-from-compilation");
const relative_to_output_path_1 = require("./lib/relative-to-output-path");
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
const { RawSource } = webpack_1.default.sources || require('webpack-sources');
// Used to keep track of swDest files written by *any* instance of this plugin.
// See https://github.com/GoogleChrome/workbox/issues/2181
const _generatedAssetNames = new Set();
/**
* This class supports creating a new, ready-to-use service worker file as
* part of the webpack compilation process.
*
* Use an instance of `GenerateSW` in the
* [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
* webpack config.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* new GenerateSW({
* exclude: [/.../, '...'],
* maximumFileSizeToCacheInBytes: ...,
* navigateFallback: '...',
* runtimeCaching: [{
* // Routing via a matchCallback function:
* urlPattern: ({request, url}) => ...,
* handler: '...',
* options: {
* cacheName: '...',
* expiration: {
* maxEntries: ...,
* },
* },
* }, {
* // Routing via a RegExp:
* urlPattern: new RegExp('...'),
* handler: '...',
* options: {
* cacheName: '...',
* plugins: [..., ...],
* },
* }],
* skipWaiting: ...,
* });
* ```
*
* @memberof module:workbox-webpack-plugin
*/
class GenerateSW {
/**
* Creates an instance of GenerateSW.
*/
constructor(config = {}) {
this.config = config;
this.alreadyCalled = false;
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
propagateWebpackConfig(compiler) {
// Because this.config is listed last, properties that are already set
// there take precedence over derived properties from the compiler.
this.config = Object.assign({
mode: compiler.options.mode,
sourcemap: Boolean(compiler.options.devtool),
}, this.config);
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
apply(compiler) {
this.propagateWebpackConfig(compiler);
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
if (webpack_1.default.version.startsWith('4.')) {
compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) => this.addAssets(compilation).catch((error) => {
compilation.errors.push(error);
}));
}
else {
const { PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER } = webpack_1.default.Compilation;
// Specifically hook into thisCompilation, as per
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
compilation.hooks.processAssets.tapPromise({
name: this.constructor.name,
// TODO(jeffposnick): This may need to change eventually.
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
}, () => this.addAssets(compilation).catch((error) => {
compilation.errors.push(error);
}));
});
}
}
/**
* @param {Object} compilation The webpack compilation.
*
* @private
*/
async addAssets(compilation) {
var _a;
// See https://github.com/GoogleChrome/workbox/issues/1790
if (this.alreadyCalled) {
const warningMessage = `${this.constructor.name} has been called ` +
`multiple times, perhaps due to running webpack in --watch mode. The ` +
`precache manifest generated after the first call may be inaccurate! ` +
`Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
`more information.`;
if (!compilation.warnings.some((warning) => warning instanceof Error && warning.message === warningMessage)) {
compilation.warnings.push(Error(warningMessage));
}
}
else {
this.alreadyCalled = true;
}
let config = {};
try {
// emit might be called multiple times; instead of modifying this.config,
// use a validated copy.
// See https://github.com/GoogleChrome/workbox/issues/2158
config = (0, validate_options_1.validateWebpackGenerateSWOptions)(this.config);
}
catch (error) {
if (error instanceof Error) {
throw new Error(`Please check your ${this.constructor.name} plugin ` +
`configuration:\n${error.message}`);
}
}
// Ensure that we don't precache any of the assets generated by *any*
// instance of this plugin.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
config.exclude.push(({ asset }) => _generatedAssetNames.has(asset.name));
if (config.importScriptsViaChunks) {
// Anything loaded via importScripts() is implicitly cached by the service
// worker, and should not be added to the precache manifest.
config.excludeChunks = (config.excludeChunks || []).concat(config.importScriptsViaChunks);
const scripts = (0, get_script_files_for_chunks_1.getScriptFilesForChunks)(compilation, config.importScriptsViaChunks);
config.importScripts = (config.importScripts || []).concat(scripts);
}
const { size, sortedEntries } = await (0, get_manifest_entries_from_compilation_1.getManifestEntriesFromCompilation)(compilation, config);
config.manifestEntries = sortedEntries;
const unbundledCode = (0, populate_sw_template_1.populateSWTemplate)(config);
const files = await (0, bundle_1.bundle)({
babelPresetEnvTargets: config.babelPresetEnvTargets,
inlineWorkboxRuntime: config.inlineWorkboxRuntime,
mode: config.mode,
sourcemap: config.sourcemap,
swDest: (0, relative_to_output_path_1.relativeToOutputPath)(compilation, config.swDest),
unbundledCode,
});
for (const file of files) {
compilation.emitAsset(file.name, new RawSource(Buffer.from(file.contents)), {
// See https://github.com/webpack-contrib/compression-webpack-plugin/issues/218#issuecomment-726196160
minimized: config.mode === 'production',
});
_generatedAssetNames.add(file.name);
}
if (compilation.getLogger) {
const logger = compilation.getLogger(this.constructor.name);
logger.info(`The service worker at ${(_a = config.swDest) !== null && _a !== void 0 ? _a : ''} will precache
${config.manifestEntries.length} URLs, totaling ${(0, pretty_bytes_1.default)(size)}.`);
}
}
}
exports.GenerateSW = GenerateSW;

View File

@@ -0,0 +1,11 @@
import { GenerateSW, GenerateSWConfig } from './generate-sw';
import { InjectManifest } from './inject-manifest';
/**
* @module workbox-webpack-plugin
*/
export { GenerateSW, GenerateSWConfig, InjectManifest };
declare const _default: {
GenerateSW: typeof GenerateSW;
InjectManifest: typeof InjectManifest;
};
export default _default;

View File

@@ -0,0 +1,17 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.InjectManifest = exports.GenerateSW = void 0;
const generate_sw_1 = require("./generate-sw");
Object.defineProperty(exports, "GenerateSW", { enumerable: true, get: function () { return generate_sw_1.GenerateSW; } });
const inject_manifest_1 = require("./inject-manifest");
Object.defineProperty(exports, "InjectManifest", { enumerable: true, get: function () { return inject_manifest_1.InjectManifest; } });
// TODO: remove this in v7.
// See https://github.com/GoogleChrome/workbox/issues/3033
exports.default = { GenerateSW: generate_sw_1.GenerateSW, InjectManifest: inject_manifest_1.InjectManifest };

View File

@@ -0,0 +1,74 @@
import webpack from 'webpack';
import { WebpackInjectManifestOptions } from 'workbox-build';
/**
* This class supports compiling a service worker file provided via `swSrc`,
* and injecting into that service worker a list of URLs and revision
* information for precaching based on the webpack asset pipeline.
*
* Use an instance of `InjectManifest` in the
* [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
* webpack config.
*
* In addition to injecting the manifest, this plugin will perform a compilation
* of the `swSrc` file, using the options from the main webpack configuration.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* new InjectManifest({
* exclude: [/.../, '...'],
* maximumFileSizeToCacheInBytes: ...,
* swSrc: '...',
* });
* ```
*
* @memberof module:workbox-webpack-plugin
*/
declare class InjectManifest {
protected config: WebpackInjectManifestOptions;
private alreadyCalled;
/**
* Creates an instance of InjectManifest.
*/
constructor(config: WebpackInjectManifestOptions);
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
propagateWebpackConfig(compiler: webpack.Compiler): void;
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
apply(compiler: webpack.Compiler): void;
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
performChildCompilation(compilation: webpack.Compilation, parentCompiler: webpack.Compiler): Promise<void>;
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
addSrcToAssets(compilation: webpack.Compilation, parentCompiler: webpack.Compiler): void;
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
handleMake(compilation: webpack.Compilation, parentCompiler: webpack.Compiler): Promise<void>;
/**
* @param {Object} compilation The webpack compilation.
*
* @private
*/
addAssets(compilation: webpack.Compilation): Promise<void>;
}
export { InjectManifest };

View File

@@ -0,0 +1,270 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InjectManifest = void 0;
const escape_regexp_1 = require("workbox-build/build/lib/escape-regexp");
const replace_and_update_source_map_1 = require("workbox-build/build/lib/replace-and-update-source-map");
const validate_options_1 = require("workbox-build/build/lib/validate-options");
const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
const fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
const upath_1 = __importDefault(require("upath"));
const webpack_1 = __importDefault(require("webpack"));
const get_manifest_entries_from_compilation_1 = require("./lib/get-manifest-entries-from-compilation");
const get_sourcemap_asset_name_1 = require("./lib/get-sourcemap-asset-name");
const relative_to_output_path_1 = require("./lib/relative-to-output-path");
// Used to keep track of swDest files written by *any* instance of this plugin.
// See https://github.com/GoogleChrome/workbox/issues/2181
const _generatedAssetNames = new Set();
// SingleEntryPlugin in v4 was renamed to EntryPlugin in v5.
const SingleEntryPlugin = webpack_1.default.EntryPlugin || webpack_1.default.SingleEntryPlugin;
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
const { RawSource } = webpack_1.default.sources || require('webpack-sources');
/**
* This class supports compiling a service worker file provided via `swSrc`,
* and injecting into that service worker a list of URLs and revision
* information for precaching based on the webpack asset pipeline.
*
* Use an instance of `InjectManifest` in the
* [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
* webpack config.
*
* In addition to injecting the manifest, this plugin will perform a compilation
* of the `swSrc` file, using the options from the main webpack configuration.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* new InjectManifest({
* exclude: [/.../, '...'],
* maximumFileSizeToCacheInBytes: ...,
* swSrc: '...',
* });
* ```
*
* @memberof module:workbox-webpack-plugin
*/
class InjectManifest {
/**
* Creates an instance of InjectManifest.
*/
constructor(config) {
this.config = config;
this.alreadyCalled = false;
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
propagateWebpackConfig(compiler) {
// Because this.config is listed last, properties that are already set
// there take precedence over derived properties from the compiler.
this.config = Object.assign({
mode: compiler.options.mode,
// Use swSrc with a hardcoded .js extension, in case swSrc is a .ts file.
swDest: upath_1.default.parse(this.config.swSrc).name + '.js',
}, this.config);
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
apply(compiler) {
var _a;
this.propagateWebpackConfig(compiler);
compiler.hooks.make.tapPromise(this.constructor.name, (compilation) => this.handleMake(compilation, compiler).catch((error) => {
compilation.errors.push(error);
}));
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
if ((_a = webpack_1.default.version) === null || _a === void 0 ? void 0 : _a.startsWith('4.')) {
compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) => this.addAssets(compilation).catch((error) => {
compilation.errors.push(error);
}));
}
else {
const { PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER } = webpack_1.default.Compilation;
// Specifically hook into thisCompilation, as per
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => {
compilation.hooks.processAssets.tapPromise({
name: this.constructor.name,
// TODO(jeffposnick): This may need to change eventually.
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
}, () => this.addAssets(compilation).catch((error) => {
compilation.errors.push(error);
}));
});
}
}
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
async performChildCompilation(compilation, parentCompiler) {
const outputOptions = {
path: parentCompiler.options.output.path,
filename: this.config.swDest,
};
const childCompiler = compilation.createChildCompiler(this.constructor.name, outputOptions, []);
childCompiler.context = parentCompiler.context;
childCompiler.inputFileSystem = parentCompiler.inputFileSystem;
childCompiler.outputFileSystem = parentCompiler.outputFileSystem;
if (Array.isArray(this.config.webpackCompilationPlugins)) {
for (const plugin of this.config.webpackCompilationPlugins) {
// plugin has a generic type, eslint complains for an unsafe
// assign and unsafe use
// eslint-disable-next-line
plugin.apply(childCompiler);
}
}
new SingleEntryPlugin(parentCompiler.context, this.config.swSrc, this.constructor.name).apply(childCompiler);
await new Promise((resolve, reject) => {
childCompiler.runAsChild((error, _entries, childCompilation) => {
var _a, _b;
if (error) {
reject(error);
}
else {
compilation.warnings = compilation.warnings.concat((_a = childCompilation === null || childCompilation === void 0 ? void 0 : childCompilation.warnings) !== null && _a !== void 0 ? _a : []);
compilation.errors = compilation.errors.concat((_b = childCompilation === null || childCompilation === void 0 ? void 0 : childCompilation.errors) !== null && _b !== void 0 ? _b : []);
resolve();
}
});
});
}
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
addSrcToAssets(compilation, parentCompiler) {
// eslint-disable-next-line
const source = parentCompiler.inputFileSystem.readFileSync(this.config.swSrc);
compilation.emitAsset(this.config.swDest, new RawSource(source));
}
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
async handleMake(compilation, parentCompiler) {
try {
this.config = (0, validate_options_1.validateWebpackInjectManifestOptions)(this.config);
}
catch (error) {
if (error instanceof Error) {
throw new Error(`Please check your ${this.constructor.name} plugin ` +
`configuration:\n${error.message}`);
}
}
this.config.swDest = (0, relative_to_output_path_1.relativeToOutputPath)(compilation, this.config.swDest);
_generatedAssetNames.add(this.config.swDest);
if (this.config.compileSrc) {
await this.performChildCompilation(compilation, parentCompiler);
}
else {
this.addSrcToAssets(compilation, parentCompiler);
// This used to be a fatal error, but just warn at runtime because we
// can't validate it easily.
if (Array.isArray(this.config.webpackCompilationPlugins) &&
this.config.webpackCompilationPlugins.length > 0) {
compilation.warnings.push(new Error('compileSrc is false, so the ' +
'webpackCompilationPlugins option will be ignored.'));
}
}
}
/**
* @param {Object} compilation The webpack compilation.
*
* @private
*/
async addAssets(compilation) {
var _a, _b, _c, _d, _e;
// See https://github.com/GoogleChrome/workbox/issues/1790
if (this.alreadyCalled) {
const warningMessage = `${this.constructor.name} has been called ` +
`multiple times, perhaps due to running webpack in --watch mode. The ` +
`precache manifest generated after the first call may be inaccurate! ` +
`Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
`more information.`;
if (!compilation.warnings.some((warning) => warning instanceof Error && warning.message === warningMessage)) {
compilation.warnings.push(new Error(warningMessage));
}
}
else {
this.alreadyCalled = true;
}
const config = Object.assign({}, this.config);
// Ensure that we don't precache any of the assets generated by *any*
// instance of this plugin.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
config.exclude.push(({ asset }) => _generatedAssetNames.has(asset.name));
// See https://webpack.js.org/contribute/plugin-patterns/#monitoring-the-watch-graph
const absoluteSwSrc = upath_1.default.resolve(this.config.swSrc);
compilation.fileDependencies.add(absoluteSwSrc);
const swAsset = compilation.getAsset(config.swDest);
const swAssetString = swAsset.source.source().toString();
const globalRegexp = new RegExp((0, escape_regexp_1.escapeRegExp)(config.injectionPoint), 'g');
const injectionResults = swAssetString.match(globalRegexp);
if (!injectionResults) {
throw new Error(`Can't find ${(_a = config.injectionPoint) !== null && _a !== void 0 ? _a : ''} in your SW source.`);
}
if (injectionResults.length !== 1) {
throw new Error(`Multiple instances of ${(_b = config.injectionPoint) !== null && _b !== void 0 ? _b : ''} were ` +
`found in your SW source. Include it only once. For more info, see ` +
`https://github.com/GoogleChrome/workbox/issues/2681`);
}
const { size, sortedEntries } = await (0, get_manifest_entries_from_compilation_1.getManifestEntriesFromCompilation)(compilation, config);
let manifestString = (0, fast_json_stable_stringify_1.default)(sortedEntries);
if (this.config.compileSrc &&
// See https://github.com/GoogleChrome/workbox/issues/2729
!(((_c = compilation.options) === null || _c === void 0 ? void 0 : _c.devtool) === 'eval-cheap-source-map' &&
((_d = compilation.options.optimization) === null || _d === void 0 ? void 0 : _d.minimize))) {
// See https://github.com/GoogleChrome/workbox/issues/2263
manifestString = manifestString.replace(/"/g, `'`);
}
const sourcemapAssetName = (0, get_sourcemap_asset_name_1.getSourcemapAssetName)(compilation, swAssetString, config.swDest);
if (sourcemapAssetName) {
_generatedAssetNames.add(sourcemapAssetName);
const sourcemapAsset = compilation.getAsset(sourcemapAssetName);
const { source, map } = await (0, replace_and_update_source_map_1.replaceAndUpdateSourceMap)({
jsFilename: config.swDest,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
originalMap: JSON.parse(sourcemapAsset.source.source().toString()),
originalSource: swAssetString,
replaceString: manifestString,
searchString: config.injectionPoint,
});
compilation.updateAsset(sourcemapAssetName, new RawSource(map));
compilation.updateAsset(config.swDest, new RawSource(source));
}
else {
// If there's no sourcemap associated with swDest, a simple string
// replacement will suffice.
compilation.updateAsset(config.swDest, new RawSource(swAssetString.replace(config.injectionPoint, manifestString)));
}
if (compilation.getLogger) {
const logger = compilation.getLogger(this.constructor.name);
logger.info(`The service worker at ${(_e = config.swDest) !== null && _e !== void 0 ? _e : ''} will precache
${sortedEntries.length} URLs, totaling ${(0, pretty_bytes_1.default)(size)}.`);
}
}
}
exports.InjectManifest = InjectManifest;

View File

@@ -0,0 +1,8 @@
import type { Asset } from 'webpack';
/**
* @param {Asset} asset
* @return {string} The MD5 hash of the asset's source.
*
* @private
*/
export declare function getAssetHash(asset: Asset): string | null;

View File

@@ -0,0 +1,32 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAssetHash = void 0;
const crypto_1 = __importDefault(require("crypto"));
/**
* @param {Asset} asset
* @return {string} The MD5 hash of the asset's source.
*
* @private
*/
function getAssetHash(asset) {
// If webpack has the asset marked as immutable, then we don't need to
// use an out-of-band revision for it.
// See https://github.com/webpack/webpack/issues/9038
if (asset.info && asset.info.immutable) {
return null;
}
return crypto_1.default.createHash('md5')
.update(Buffer.from(asset.source.source()))
.digest('hex');
}
exports.getAssetHash = getAssetHash;

View File

@@ -0,0 +1,6 @@
import { Compilation } from 'webpack';
import { WebpackGenerateSWOptions, WebpackInjectManifestOptions, ManifestEntry } from 'workbox-build';
export declare function getManifestEntriesFromCompilation(compilation: Compilation, config: WebpackGenerateSWOptions | WebpackInjectManifestOptions): Promise<{
size: number;
sortedEntries: ManifestEntry[];
}>;

View File

@@ -0,0 +1,188 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getManifestEntriesFromCompilation = void 0;
const webpack_1 = require("webpack");
const transform_manifest_1 = require("workbox-build/build/lib/transform-manifest");
const get_asset_hash_1 = require("./get-asset-hash");
const resolve_webpack_url_1 = require("./resolve-webpack-url");
/**
* For a given asset, checks whether at least one of the conditions matches.
*
* @param {Asset} asset The webpack asset in question. This will be passed
* to any functions that are listed as conditions.
* @param {Compilation} compilation The webpack compilation. This will be passed
* to any functions that are listed as conditions.
* @param {Array<string|RegExp|Function>} conditions
* @return {boolean} Whether or not at least one condition matches.
* @private
*/
function checkConditions(asset, compilation, conditions = []) {
for (const condition of conditions) {
if (typeof condition === 'function') {
return condition({ asset, compilation });
//return compilation !== null;
}
else {
if (webpack_1.ModuleFilenameHelpers.matchPart(asset.name, condition)) {
return true;
}
}
}
// We'll only get here if none of the conditions applied.
return false;
}
/**
* Returns the names of all the assets in all the chunks in a chunk group,
* if provided a chunk group name.
* Otherwise, if provided a chunk name, return all the assets in that chunk.
* Otherwise, if there isn't a chunk group or chunk with that name, return null.
*
* @param {Compilation} compilation
* @param {string} chunkOrGroup
* @return {Array<string>|null}
* @private
*/
function getNamesOfAssetsInChunkOrGroup(compilation, chunkOrGroup) {
const chunkGroup = compilation.namedChunkGroups &&
compilation.namedChunkGroups.get(chunkOrGroup);
if (chunkGroup) {
const assetNames = [];
for (const chunk of chunkGroup.chunks) {
assetNames.push(...getNamesOfAssetsInChunk(chunk));
}
return assetNames;
}
else {
const chunk = compilation.namedChunks && compilation.namedChunks.get(chunkOrGroup);
if (chunk) {
return getNamesOfAssetsInChunk(chunk);
}
}
// If we get here, there's no chunkGroup or chunk with that name.
return null;
}
/**
* Returns the names of all the assets in a chunk.
*
* @param {Chunk} chunk
* @return {Array<string>}
* @private
*/
function getNamesOfAssetsInChunk(chunk) {
const assetNames = [];
assetNames.push(...chunk.files);
// This only appears to be set in webpack v5.
if (chunk.auxiliaryFiles) {
assetNames.push(...chunk.auxiliaryFiles);
}
return assetNames;
}
/**
* Filters the set of assets out, based on the configuration options provided:
* - chunks and excludeChunks, for chunkName-based criteria.
* - include and exclude, for more general criteria.
*
* @param {Compilation} compilation The webpack compilation.
* @param {Object} config The validated configuration, obtained from the plugin.
* @return {Set<Asset>} The assets that should be included in the manifest,
* based on the criteria provided.
* @private
*/
function filterAssets(compilation, config) {
const filteredAssets = new Set();
const assets = compilation.getAssets();
const allowedAssetNames = new Set();
// See https://github.com/GoogleChrome/workbox/issues/1287
if (Array.isArray(config.chunks)) {
for (const name of config.chunks) {
// See https://github.com/GoogleChrome/workbox/issues/2717
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(compilation, name);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
allowedAssetNames.add(assetName);
}
}
else {
compilation.warnings.push(new Error(`The chunk '${name}' was ` +
`provided in your Workbox chunks config, but was not found in the ` +
`compilation.`));
}
}
}
const deniedAssetNames = new Set();
if (Array.isArray(config.excludeChunks)) {
for (const name of config.excludeChunks) {
// See https://github.com/GoogleChrome/workbox/issues/2717
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(compilation, name);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
deniedAssetNames.add(assetName);
}
} // Don't warn if the chunk group isn't found.
}
}
for (const asset of assets) {
// chunk based filtering is funky because:
// - Each asset might belong to one or more chunks.
// - If *any* of those chunk names match our config.excludeChunks,
// then we skip that asset.
// - If the config.chunks is defined *and* there's no match
// between at least one of the chunkNames and one entry, then
// we skip that assets as well.
if (deniedAssetNames.has(asset.name)) {
continue;
}
if (Array.isArray(config.chunks) && !allowedAssetNames.has(asset.name)) {
continue;
}
// Next, check asset-level checks via includes/excludes:
const isExcluded = checkConditions(asset, compilation, config.exclude);
if (isExcluded) {
continue;
}
// Treat an empty config.includes as an implicit inclusion.
const isIncluded = !Array.isArray(config.include) ||
checkConditions(asset, compilation, config.include);
if (!isIncluded) {
continue;
}
// If we've gotten this far, then add the asset.
filteredAssets.add(asset);
}
return filteredAssets;
}
async function getManifestEntriesFromCompilation(compilation, config) {
const filteredAssets = filterAssets(compilation, config);
const { publicPath } = compilation.options.output;
const fileDetails = Array.from(filteredAssets).map((asset) => {
return {
file: (0, resolve_webpack_url_1.resolveWebpackURL)(publicPath, asset.name),
hash: (0, get_asset_hash_1.getAssetHash)(asset),
size: asset.source.size() || 0,
};
});
const { manifestEntries, size, warnings } = await (0, transform_manifest_1.transformManifest)({
fileDetails,
additionalManifestEntries: config.additionalManifestEntries,
dontCacheBustURLsMatching: config.dontCacheBustURLsMatching,
manifestTransforms: config.manifestTransforms,
maximumFileSizeToCacheInBytes: config.maximumFileSizeToCacheInBytes,
modifyURLPrefix: config.modifyURLPrefix,
transformParam: compilation,
});
// See https://github.com/GoogleChrome/workbox/issues/2790
for (const warning of warnings) {
compilation.warnings.push(new Error(warning));
}
// Ensure that the entries are properly sorted by URL.
const sortedEntries = manifestEntries.sort((a, b) => a.url === b.url ? 0 : a.url > b.url ? 1 : -1);
return { size, sortedEntries };
}
exports.getManifestEntriesFromCompilation = getManifestEntriesFromCompilation;

View File

@@ -0,0 +1,2 @@
import { Compilation } from 'webpack';
export declare function getScriptFilesForChunks(compilation: Compilation, chunkNames: Array<string>): Array<string>;

View File

@@ -0,0 +1,42 @@
"use strict";
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getScriptFilesForChunks = void 0;
const upath_1 = __importDefault(require("upath"));
const resolve_webpack_url_1 = require("./resolve-webpack-url");
function getScriptFilesForChunks(compilation, chunkNames) {
var _a;
const { chunks } = compilation.getStats().toJson({ chunks: true });
const { publicPath } = compilation.options.output;
const scriptFiles = new Set();
for (const chunkName of chunkNames) {
const chunk = chunks.find((chunk) => { var _a; return (_a = chunk.names) === null || _a === void 0 ? void 0 : _a.includes(chunkName); });
if (chunk) {
for (const file of (_a = chunk === null || chunk === void 0 ? void 0 : chunk.files) !== null && _a !== void 0 ? _a : []) {
// See https://github.com/GoogleChrome/workbox/issues/2161
if (upath_1.default.extname(file) === '.js') {
scriptFiles.add((0, resolve_webpack_url_1.resolveWebpackURL)(publicPath, file));
}
}
}
else {
compilation.warnings.push(new Error(`${chunkName} was provided to ` +
`importScriptsViaChunks, but didn't match any named chunks.`));
}
}
if (scriptFiles.size === 0) {
compilation.warnings.push(new Error(`There were no assets matching ` +
`importScriptsViaChunks: [${chunkNames.join(' ')}].`));
}
return Array.from(scriptFiles);
}
exports.getScriptFilesForChunks = getScriptFilesForChunks;

View File

@@ -0,0 +1,20 @@
import type { Compilation } from 'webpack';
/**
* If our bundled swDest file contains a sourcemap, we would invalidate that
* mapping if we just replaced injectionPoint with the stringified manifest.
* Instead, we need to update the swDest contents as well as the sourcemap
* at the same time.
*
* See https://github.com/GoogleChrome/workbox/issues/2235
*
* @param {Object} compilation The current webpack compilation.
* @param {string} swContents The contents of the swSrc file, which may or
* may not include a valid sourcemap comment.
* @param {string} swDest The configured swDest value.
* @return {string|undefined} If the swContents contains a valid sourcemap
* comment pointing to an asset present in the compilation, this will return the
* name of that asset. Otherwise, it will return undefined.
*
* @private
*/
export declare function getSourcemapAssetName(compilation: Compilation, swContents: string, swDest: string): string | undefined;

View File

@@ -0,0 +1,51 @@
"use strict";
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSourcemapAssetName = void 0;
const get_source_map_url_1 = require("workbox-build/build/lib/get-source-map-url");
const upath_1 = __importDefault(require("upath"));
/**
* If our bundled swDest file contains a sourcemap, we would invalidate that
* mapping if we just replaced injectionPoint with the stringified manifest.
* Instead, we need to update the swDest contents as well as the sourcemap
* at the same time.
*
* See https://github.com/GoogleChrome/workbox/issues/2235
*
* @param {Object} compilation The current webpack compilation.
* @param {string} swContents The contents of the swSrc file, which may or
* may not include a valid sourcemap comment.
* @param {string} swDest The configured swDest value.
* @return {string|undefined} If the swContents contains a valid sourcemap
* comment pointing to an asset present in the compilation, this will return the
* name of that asset. Otherwise, it will return undefined.
*
* @private
*/
function getSourcemapAssetName(compilation, swContents, swDest) {
const url = (0, get_source_map_url_1.getSourceMapURL)(swContents);
if (url) {
// Translate the relative URL to what the presumed name for the webpack
// asset should be.
// This *might* not be a valid asset if the sourcemap URL that was found
// was added by another module incidentally.
// See https://github.com/GoogleChrome/workbox/issues/2250
const swAssetDirname = upath_1.default.dirname(swDest);
const sourcemapURLAssetName = upath_1.default.normalize(upath_1.default.join(swAssetDirname, url));
// Not sure if there's a better way to check for asset existence?
if (compilation.getAsset(sourcemapURLAssetName)) {
return sourcemapURLAssetName;
}
}
return undefined;
}
exports.getSourcemapAssetName = getSourcemapAssetName;

View File

@@ -0,0 +1,11 @@
import type { Compilation } from 'webpack';
/**
* @param {Object} compilation The webpack compilation.
* @param {string} swDest The original swDest value.
*
* @return {string} If swDest was not absolute, the returns swDest as-is.
* Otherwise, returns swDest relative to the compilation's output path.
*
* @private
*/
export declare function relativeToOutputPath(compilation: Compilation, swDest: string): string;

View File

@@ -0,0 +1,32 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.relativeToOutputPath = void 0;
const upath_1 = __importDefault(require("upath"));
/**
* @param {Object} compilation The webpack compilation.
* @param {string} swDest The original swDest value.
*
* @return {string} If swDest was not absolute, the returns swDest as-is.
* Otherwise, returns swDest relative to the compilation's output path.
*
* @private
*/
function relativeToOutputPath(compilation, swDest) {
// See https://github.com/jantimon/html-webpack-plugin/pull/266/files#diff-168726dbe96b3ce427e7fedce31bb0bcR38
if (upath_1.default.resolve(swDest) === upath_1.default.normalize(swDest)) {
return upath_1.default.relative(compilation.options.output.path, swDest);
}
// Otherwise, return swDest as-is.
return swDest;
}
exports.relativeToOutputPath = relativeToOutputPath;

View File

@@ -0,0 +1,14 @@
/**
* Resolves a url in the way that webpack would (with string concatenation)
*
* Use publicPath + filePath instead of url.resolve(publicPath, filePath) see:
* https://webpack.js.org/configuration/output/#output-publicpath
*
* @function resolveWebpackURL
* @param {string} publicPath The publicPath value from webpack's compilation.
* @param {Array<string>} paths File paths to join
* @return {string} Joined file path
*
* @private
*/
export declare function resolveWebpackURL(publicPath: string, ...paths: Array<string>): string;

View File

@@ -0,0 +1,34 @@
"use strict";
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveWebpackURL = void 0;
/**
* Resolves a url in the way that webpack would (with string concatenation)
*
* Use publicPath + filePath instead of url.resolve(publicPath, filePath) see:
* https://webpack.js.org/configuration/output/#output-publicpath
*
* @function resolveWebpackURL
* @param {string} publicPath The publicPath value from webpack's compilation.
* @param {Array<string>} paths File paths to join
* @return {string} Joined file path
*
* @private
*/
function resolveWebpackURL(publicPath, ...paths) {
// This is a change in webpack v5.
// See https://github.com/jantimon/html-webpack-plugin/pull/1516
if (publicPath === 'auto') {
return paths.join('');
}
else {
return [publicPath, ...paths].join('');
}
}
exports.resolveWebpackURL = resolveWebpackURL;

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,230 @@
# webpack-sources
Contains multiple classes which represent a `Source`. A `Source` can be asked for source code, size, source map and hash.
## `Source`
Base class for all sources.
### Public methods
All methods should be considered as expensive as they may need to do computations.
#### `source`
``` js
Source.prototype.source() -> String | ArrayBuffer
```
Returns the represented source code as string.
#### `size`
``` js
Source.prototype.size() -> Number
```
Returns the size in chars of the represented source code.
#### `map`
``` js
Source.prototype.map(options: Object) -> Object | null
```
Returns the SourceMap of the represented source code as JSON. May return `null` if no SourceMap is available.
The `options` object can contain the following keys:
* `columns: Boolean` (default `true`): If set to false the implementation may omit mappings for columns.
* `module: Boolean` (default `true`): If set to false the implementation may omit inner mappings for modules.
#### `sourceAndMap`
``` js
Source.prototype.sourceAndMap(options: Object) -> {
source: String,
map: Object
}
```
Returns both, source code (like `Source.prototype.source()` and SourceMap (like `Source.prototype.map()`). This method could have better performance than calling `source()` and `map()` separately.
See `map()` for `options`.
#### `updateHash`
``` js
Source.prototype.updateHash(hash: Hash) -> void
```
Updates the provided `Hash` object with the content of the represented source code. (`Hash` is an object with an `update` method, which is called with string values)
#### `node` (optional)
``` js
Source.prototype.node(options: Object) -> SourceNode
```
This is an optional method. It may be `null` if not implemented.
Returns a `SourceNode` (see source-map library) for the represented source code.
See `map()` for `options`.
#### `listNode` (optional)
``` js
Source.prototype.listNode(options: Object) -> SourceNode
```
This is an optional method. It may be `null` if not implemented.
Returns a `SourceListMap` (see source-list-map library) for the represented source code.
See `map()` for `options`.
## `RawSource`
Represents source code without SourceMap.
``` js
new RawSource(sourceCode: String)
```
## `OriginalSource`
Represents source code, which is a copy of the original file.
``` js
new OriginalSource(
sourceCode: String,
name: String
)
```
* `sourceCode`: The source code.
* `name`: The filename of the original source code.
OriginalSource tries to create column mappings if requested, by splitting the source code at typical statement borders (`;`, `{`, `}`).
## `SourceMapSource`
Represents source code with SourceMap, optionally having an additional SourceMap for the original source.
``` js
new SourceMapSource(
sourceCode: String,
name: String,
sourceMap: Object | String,
originalSource?: String,
innerSourceMap?: Object | String,
removeOriginalSource?: boolean
)
```
* `sourceCode`: The source code.
* `name`: The filename of the original source code.
* `sourceMap`: The SourceMap for the source code.
* `originalSource`: The source code of the original file. Can be omitted if the `sourceMap` already contains the original source code.
* `innerSourceMap`: The SourceMap for the `originalSource`/`name`.
* `removeOriginalSource`: Removes the source code for `name` from the final map, keeping only the deeper mappings for that file.
The `SourceMapSource` supports "identity" mappings for the `innerSourceMap`.
When original source matches generated source for a mapping it's assumed to be mapped char by char allowing to keep finer mappings from `sourceMap`.
## `LineToLineMappedSource`
Represents source code, which is mapped line by line to the original file.
``` js
new LineToLineMappedSource(
sourceCode: String,
name: String,
originalSource: String
)
```
* `sourceCode`: The source code.
* `name`: The filename of the original source code.
* `originalSource`: The original source code.
## `CachedSource`
Decorates a `Source` and caches returned results of `map`, `source`, `size` and `sourceAndMap` in memory. Every other operation is delegated to the wrapped `Source`.
``` js
new CachedSource(source: Source)
```
## `PrefixSource`
Prefix every line of the decorated `Source` with a provided string.
``` js
new PrefixSource(
prefix: String,
source: Source
)
```
## `ConcatSource`
Concatenate multiple `Source`s or strings to a single source.
``` js
new ConcatSource(
...items?: Source | String
)
```
### Public methods
#### `add`
``` js
ConcatSource.prototype.add(item: Source | String)
```
Adds an item to the source.
## `ReplaceSource`
Decorates a `Source` with replacements and insertions of source code.
The `ReplaceSource` supports "identity" mappings for child source.
When original source matches generated source for a mapping it's assumed to be mapped char by char allowing to split mappings at replacements/insertions.
### Public methods
#### `replace`
``` js
ReplaceSource.prototype.replace(
start: Number,
end: Number,
replacement: String
)
```
Replaces chars from `start` (0-indexed, inclusive) to `end` (0-indexed, inclusive) with `replacement`.
Locations represents locations in the original source and are not influenced by other replacements or insertions.
#### `insert`
``` js
ReplaceSource.prototype.insert(
pos: Number,
insertion: String
)
```
Inserts the `insertion` before char `pos` (0-indexed).
Location represents location in the original source and is not influenced by other replacements or insertions.
#### `original`
Get decorated `Source`.

View File

@@ -0,0 +1,80 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Source = require("./Source");
class CachedSource extends Source {
constructor(source) {
super();
this._source = source;
this._cachedSource = undefined;
this._cachedSize = undefined;
this._cachedMaps = {};
if(source.node) this.node = function(options) {
return this._source.node(options);
};
if(source.listMap) this.listMap = function(options) {
return this._source.listMap(options);
};
}
source() {
if(typeof this._cachedSource !== "undefined") return this._cachedSource;
return this._cachedSource = this._source.source();
}
size() {
if(typeof this._cachedSize !== "undefined") return this._cachedSize;
if(typeof this._cachedSource !== "undefined") {
if(Buffer.from.length === 1) return new Buffer(this._cachedSource).length;
return this._cachedSize = Buffer.byteLength(this._cachedSource);
}
return this._cachedSize = this._source.size();
}
sourceAndMap(options) {
const key = JSON.stringify(options);
if(typeof this._cachedSource !== "undefined" && key in this._cachedMaps)
return {
source: this._cachedSource,
map: this._cachedMaps[key]
};
else if(typeof this._cachedSource !== "undefined") {
return {
source: this._cachedSource,
map: this._cachedMaps[key] = this._source.map(options)
};
} else if(key in this._cachedMaps) {
return {
source: this._cachedSource = this._source.source(),
map: this._cachedMaps[key]
};
}
const result = this._source.sourceAndMap(options);
this._cachedSource = result.source;
this._cachedMaps[key] = result.map;
return {
source: this._cachedSource,
map: this._cachedMaps[key]
};
}
map(options) {
if(!options) options = {};
const key = JSON.stringify(options);
if(key in this._cachedMaps)
return this._cachedMaps[key];
return this._cachedMaps[key] = this._source.map();
}
updateHash(hash) {
this._source.updateHash(hash);
}
}
module.exports = CachedSource;

View File

@@ -0,0 +1,91 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const SourceNode = require("source-map").SourceNode;
const SourceListMap = require("source-list-map").SourceListMap;
const Source = require("./Source");
class ConcatSource extends Source {
constructor() {
super();
this.children = [];
for(var i = 0; i < arguments.length; i++) {
var item = arguments[i];
if(item instanceof ConcatSource) {
var children = item.children;
for(var j = 0; j < children.length; j++)
this.children.push(children[j]);
} else {
this.children.push(item);
}
}
}
add(item) {
if(item instanceof ConcatSource) {
var children = item.children;
for(var j = 0; j < children.length; j++)
this.children.push(children[j]);
} else {
this.children.push(item);
}
}
source() {
let source = "";
const children = this.children;
for(let i = 0; i < children.length; i++) {
const child = children[i];
source += typeof child === "string" ? child : child.source();
}
return source;
}
size() {
let size = 0;
const children = this.children;
for(let i = 0; i < children.length; i++) {
const child = children[i];
size += typeof child === "string" ? child.length : child.size();
}
return size;
}
node(options) {
const node = new SourceNode(null, null, null, this.children.map(function(item) {
return typeof item === "string" ? item : item.node(options);
}));
return node;
}
listMap(options) {
const map = new SourceListMap();
var children = this.children;
for(var i = 0; i < children.length; i++) {
var item = children[i];
if(typeof item === "string")
map.add(item);
else
map.add(item.listMap(options));
}
return map;
}
updateHash(hash) {
var children = this.children;
for(var i = 0; i < children.length; i++) {
var item = children[i];
if(typeof item === "string")
hash.update(item);
else
item.updateHash(hash);
}
}
}
require("./SourceAndMapMixin")(ConcatSource.prototype);
module.exports = ConcatSource;

View File

@@ -0,0 +1,49 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var SourceNode = require("source-map").SourceNode;
var SourceMapConsumer = require("source-map").SourceMapConsumer;
var SourceListMap = require("source-list-map").SourceListMap;
var Source = require("./Source");
class LineToLineMappedSource extends Source {
constructor(value, name, originalSource) {
super();
this._value = value;
this._name = name;
this._originalSource = originalSource;
}
source() {
return this._value;
}
node(options) {
var value = this._value;
var name = this._name;
var lines = value.split("\n");
var node = new SourceNode(null, null, null,
lines.map(function(line, idx) {
return new SourceNode(idx + 1, 0, name, (line + (idx != lines.length - 1 ? "\n" : "")));
})
);
node.setSourceContent(name, this._originalSource);
return node;
}
listMap(options) {
return new SourceListMap(this._value, this._name, this._originalSource)
}
updateHash(hash) {
hash.update(this._value);
hash.update(this._originalSource);
}
}
require("./SourceAndMapMixin")(LineToLineMappedSource.prototype);
module.exports = LineToLineMappedSource;

View File

@@ -0,0 +1,70 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var SourceNode = require("source-map").SourceNode;
var SourceMapConsumer = require("source-map").SourceMapConsumer;
var SourceListMap = require("source-list-map").SourceListMap;
var Source = require("./Source");
var SPLIT_REGEX = /(?!$)[^\n\r;{}]*[\n\r;{}]*/g;
function _splitCode(code) {
return code.match(SPLIT_REGEX) || [];
}
class OriginalSource extends Source {
constructor(value, name) {
super();
this._value = value;
this._name = name;
}
source() {
return this._value;
}
node(options) {
options = options || {};
var sourceMap = this._sourceMap;
var value = this._value;
var name = this._name;
var lines = value.split("\n");
var node = new SourceNode(null, null, null,
lines.map(function(line, idx) {
var pos = 0;
if(options.columns === false) {
var content = line + (idx != lines.length - 1 ? "\n" : "");
return new SourceNode(idx + 1, 0, name, content);
}
return new SourceNode(null, null, null,
_splitCode(line + (idx != lines.length - 1 ? "\n" : "")).map(function(item) {
if(/^\s*$/.test(item)) {
pos += item.length;
return item;
}
var res = new SourceNode(idx + 1, pos, name, item);
pos += item.length;
return res;
})
);
})
);
node.setSourceContent(name, value);
return node;
}
listMap(options) {
return new SourceListMap(this._value, this._name, this._value)
}
updateHash(hash) {
hash.update(this._value);
}
}
require("./SourceAndMapMixin")(OriginalSource.prototype);
module.exports = OriginalSource;

View File

@@ -0,0 +1,95 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var Source = require("./Source");
var SourceNode = require("source-map").SourceNode;
var REPLACE_REGEX = /\n(?=.|\s)/g;
function cloneAndPrefix(node, prefix, append) {
if(typeof node === "string") {
var result = node.replace(REPLACE_REGEX, "\n" + prefix);
if(append.length > 0) result = append.pop() + result;
if(/\n$/.test(node)) append.push(prefix);
return result;
} else {
var newNode = new SourceNode(
node.line,
node.column,
node.source,
node.children.map(function(node) {
return cloneAndPrefix(node, prefix, append);
}),
node.name
);
newNode.sourceContents = node.sourceContents;
return newNode;
}
};
class PrefixSource extends Source {
constructor(prefix, source) {
super();
this._source = source;
this._prefix = prefix;
}
source() {
var node = typeof this._source === "string" ? this._source : this._source.source();
var prefix = this._prefix;
return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
}
node(options) {
var node = this._source.node(options);
var prefix = this._prefix;
var output = [];
var result = new SourceNode();
node.walkSourceContents(function(source, content) {
result.setSourceContent(source, content);
});
var needPrefix = true;
node.walk(function(chunk, mapping) {
var parts = chunk.split(/(\n)/);
for(var i = 0; i < parts.length; i += 2) {
var nl = i + 1 < parts.length;
var part = parts[i] + (nl ? "\n" : "");
if(part) {
if(needPrefix) {
output.push(prefix);
}
output.push(new SourceNode(mapping.line, mapping.column, mapping.source, part, mapping.name));
needPrefix = nl;
}
}
});
result.add(output);
return result;
}
listMap(options) {
var prefix = this._prefix;
var map = this._source.listMap(options);
return map.mapGeneratedCode(function(code) {
return prefix + code.replace(REPLACE_REGEX, "\n" + prefix);
});
}
updateHash(hash) {
if(typeof this._source === "string")
hash.update(this._source);
else
this._source.updateHash(hash);
if(typeof this._prefix === "string")
hash.update(this._prefix);
else
this._prefix.updateHash(hash);
}
}
require("./SourceAndMapMixin")(PrefixSource.prototype);
module.exports = PrefixSource;

View File

@@ -0,0 +1,38 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var Source = require("./Source");
var SourceNode = require("source-map").SourceNode;
var SourceListMap = require("source-list-map").SourceListMap;
class RawSource extends Source {
constructor(value) {
super();
this._value = value;
}
source() {
return this._value;
}
map(options) {
return null;
}
node(options) {
return new SourceNode(null, null, null, this._value);
}
listMap(options) {
return new SourceListMap(this._value);
}
updateHash(hash) {
hash.update(this._value);
}
}
module.exports = RawSource;

View File

@@ -0,0 +1,330 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var Source = require("./Source");
var SourceNode = require("source-map").SourceNode;
class Replacement {
constructor(start, end, content, insertIndex, name) {
this.start = start;
this.end = end;
this.content = content;
this.insertIndex = insertIndex;
this.name = name;
}
}
class ReplaceSource extends Source {
constructor(source, name) {
super();
this._source = source;
this._name = name;
/** @type {Replacement[]} */
this.replacements = [];
}
replace(start, end, newValue, name) {
if(typeof newValue !== "string")
throw new Error("insertion must be a string, but is a " + typeof newValue);
this.replacements.push(new Replacement(start, end, newValue, this.replacements.length, name));
}
insert(pos, newValue, name) {
if(typeof newValue !== "string")
throw new Error("insertion must be a string, but is a " + typeof newValue + ": " + newValue);
this.replacements.push(new Replacement(pos, pos - 1, newValue, this.replacements.length, name));
}
source(options) {
return this._replaceString(this._source.source());
}
original() {
return this._source;
}
_sortReplacements() {
this.replacements.sort(function(a, b) {
var diff = b.end - a.end;
if(diff !== 0)
return diff;
diff = b.start - a.start;
if(diff !== 0)
return diff;
return b.insertIndex - a.insertIndex;
});
}
_replaceString(str) {
if(typeof str !== "string")
throw new Error("str must be a string, but is a " + typeof str + ": " + str);
this._sortReplacements();
var result = [str];
this.replacements.forEach(function(repl) {
var remSource = result.pop();
var splitted1 = this._splitString(remSource, Math.floor(repl.end + 1));
var splitted2 = this._splitString(splitted1[0], Math.floor(repl.start));
result.push(splitted1[1], repl.content, splitted2[0]);
}, this);
// write out result array in reverse order
let resultStr = "";
for(let i = result.length - 1; i >= 0; --i) {
resultStr += result[i];
}
return resultStr;
}
node(options) {
var node = this._source.node(options);
if(this.replacements.length === 0) {
return node;
}
this._sortReplacements();
var replace = new ReplacementEnumerator(this.replacements);
var output = [];
var position = 0;
var sources = Object.create(null);
var sourcesInLines = Object.create(null);
// We build a new list of SourceNodes in "output"
// from the original mapping data
var result = new SourceNode();
// We need to add source contents manually
// because "walk" will not handle it
node.walkSourceContents(function(sourceFile, sourceContent) {
result.setSourceContent(sourceFile, sourceContent);
sources["$" + sourceFile] = sourceContent;
});
var replaceInStringNode = this._replaceInStringNode.bind(this, output, replace, function getOriginalSource(mapping) {
var key = "$" + mapping.source;
var lines = sourcesInLines[key];
if(!lines) {
var source = sources[key];
if(!source) return null;
lines = source.split("\n").map(function(line) {
return line + "\n";
});
sourcesInLines[key] = lines;
}
// line is 1-based
if(mapping.line > lines.length) return null;
var line = lines[mapping.line - 1];
return line.substr(mapping.column);
});
node.walk(function(chunk, mapping) {
position = replaceInStringNode(chunk, position, mapping);
});
// If any replacements occur after the end of the original file, then we append them
// directly to the end of the output
var remaining = replace.footer();
if(remaining) {
output.push(remaining);
}
result.add(output);
return result;
}
listMap(options) {
this._sortReplacements();
var map = this._source.listMap(options);
var currentIndex = 0;
var replacements = this.replacements;
var idxReplacement = replacements.length - 1;
var removeChars = 0;
map = map.mapGeneratedCode(function(str) {
var newCurrentIndex = currentIndex + str.length;
if(removeChars > str.length) {
removeChars -= str.length;
str = "";
} else {
if(removeChars > 0) {
str = str.substr(removeChars);
currentIndex += removeChars;
removeChars = 0;
}
var finalStr = "";
while(idxReplacement >= 0 && replacements[idxReplacement].start < newCurrentIndex) {
var repl = replacements[idxReplacement];
var start = Math.floor(repl.start);
var end = Math.floor(repl.end + 1);
var before = str.substr(0, Math.max(0, start - currentIndex));
if(end <= newCurrentIndex) {
var after = str.substr(Math.max(0, end - currentIndex));
finalStr += before + repl.content;
str = after;
currentIndex = Math.max(currentIndex, end);
} else {
finalStr += before + repl.content;
str = "";
removeChars = end - newCurrentIndex;
}
idxReplacement--;
}
str = finalStr + str;
}
currentIndex = newCurrentIndex;
return str;
});
var extraCode = "";
while(idxReplacement >= 0) {
extraCode += replacements[idxReplacement].content;
idxReplacement--;
}
if(extraCode) {
map.add(extraCode);
}
return map;
}
_splitString(str, position) {
return position <= 0 ? ["", str] : [str.substr(0, position), str.substr(position)];
}
_replaceInStringNode(output, replace, getOriginalSource, node, position, mapping) {
var original = undefined;
do {
var splitPosition = replace.position - position;
// If multiple replaces occur in the same location then the splitPosition may be
// before the current position for the subsequent splits. Ensure it is >= 0
if(splitPosition < 0) {
splitPosition = 0;
}
if(splitPosition >= node.length || replace.done) {
if(replace.emit) {
var nodeEnd = new SourceNode(
mapping.line,
mapping.column,
mapping.source,
node,
mapping.name
);
output.push(nodeEnd);
}
return position + node.length;
}
var originalColumn = mapping.column;
// Try to figure out if generated code matches original code of this segement
// If this is the case we assume that it's allowed to move mapping.column
// Because getOriginalSource can be expensive we only do it when neccessary
var nodePart;
if(splitPosition > 0) {
nodePart = node.slice(0, splitPosition);
if(original === undefined) {
original = getOriginalSource(mapping);
}
if(original && original.length >= splitPosition && original.startsWith(nodePart)) {
mapping.column += splitPosition;
original = original.substr(splitPosition);
}
}
var emit = replace.next();
if(!emit) {
// Stop emitting when we have found the beginning of the string to replace.
// Emit the part of the string before splitPosition
if(splitPosition > 0) {
var nodeStart = new SourceNode(
mapping.line,
originalColumn,
mapping.source,
nodePart,
mapping.name
);
output.push(nodeStart);
}
// Emit the replacement value
if(replace.value) {
output.push(new SourceNode(
mapping.line,
mapping.column,
mapping.source,
replace.value,
mapping.name || replace.name
));
}
}
// Recurse with remainder of the string as there may be multiple replaces within a single node
node = node.substr(splitPosition);
position += splitPosition;
} while (true);
}
}
class ReplacementEnumerator {
/**
* @param {Replacement[]} replacements list of replacements
*/
constructor(replacements) {
this.replacements = replacements || [];
this.index = this.replacements.length;
this.done = false;
this.emit = false;
// Set initial start position
this.next();
}
next() {
if(this.done)
return true;
if(this.emit) {
// Start point found. stop emitting. set position to find end
var repl = this.replacements[this.index];
var end = Math.floor(repl.end + 1);
this.position = end;
this.value = repl.content;
this.name = repl.name;
} else {
// End point found. start emitting. set position to find next start
this.index--;
if(this.index < 0) {
this.done = true;
} else {
var nextRepl = this.replacements[this.index];
var start = Math.floor(nextRepl.start);
this.position = start;
}
}
if(this.position < 0)
this.position = 0;
this.emit = !this.emit;
return this.emit;
}
footer() {
if(!this.done && !this.emit)
this.next(); // If we finished _replaceInNode mid emit we advance to next entry
if(this.done) {
return [];
} else {
var resultStr = "";
for(var i = this.index; i >= 0; i--) {
var repl = this.replacements[i];
// this doesn't need to handle repl.name, because in SourceMaps generated code
// without pointer to original source can't have a name
resultStr += repl.content;
}
return resultStr;
}
}
}
require("./SourceAndMapMixin")(ReplaceSource.prototype);
module.exports = ReplaceSource;

View File

@@ -0,0 +1,46 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var SourceNode = require("source-map").SourceNode;
var SourceMapConsumer = require("source-map").SourceMapConsumer;
class Source {
source() {
throw new Error("Abstract");
}
size() {
if(Buffer.from.length === 1) return new Buffer(this.source()).length;
return Buffer.byteLength(this.source())
}
map(options) {
return null;
}
sourceAndMap(options) {
return {
source: this.source(),
map: this.map()
};
}
node() {
throw new Error("Abstract");
}
listNode() {
throw new Error("Abstract");
}
updateHash(hash) {
var source = this.source();
hash.update(source || "");
}
}
module.exports = Source;

View File

@@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
module.exports = function mixinSourceAndMap(proto) {
proto.map = function(options) {
options = options || {};
if(options.columns === false) {
return this.listMap(options).toStringWithSourceMap({
file: "x"
}).map;
}
return this.node(options).toStringWithSourceMap({
file: "x"
}).map.toJSON();
};
proto.sourceAndMap = function(options) {
options = options || {};
if(options.columns === false) {
return this.listMap(options).toStringWithSourceMap({
file: "x"
});
}
var res = this.node(options).toStringWithSourceMap({
file: "x"
});
return {
source: res.code,
map: res.map.toJSON()
};
};
}

View File

@@ -0,0 +1,57 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var SourceNode = require("source-map").SourceNode;
var SourceMapConsumer = require("source-map").SourceMapConsumer;
var SourceMapGenerator = require("source-map").SourceMapGenerator;
var SourceListMap = require("source-list-map").SourceListMap;
var fromStringWithSourceMap = require("source-list-map").fromStringWithSourceMap;
var Source = require("./Source");
var applySourceMap = require("./applySourceMap");
class SourceMapSource extends Source {
constructor(value, name, sourceMap, originalSource, innerSourceMap, removeOriginalSource) {
super();
this._value = value;
this._name = name;
this._sourceMap = sourceMap;
this._originalSource = originalSource;
this._innerSourceMap = innerSourceMap;
this._removeOriginalSource = removeOriginalSource;
}
source() {
return this._value;
}
node(options) {
var sourceMap = this._sourceMap;
var node = SourceNode.fromStringWithSourceMap(this._value, new SourceMapConsumer(sourceMap));
node.setSourceContent(this._name, this._originalSource);
var innerSourceMap = this._innerSourceMap;
if(innerSourceMap) {
node = applySourceMap(node, new SourceMapConsumer(innerSourceMap), this._name, this._removeOriginalSource);
}
return node;
}
listMap(options) {
options = options || {};
if(options.module === false)
return new SourceListMap(this._value, this._name, this._value);
return fromStringWithSourceMap(this._value, typeof this._sourceMap === "string" ? JSON.parse(this._sourceMap) : this._sourceMap);
}
updateHash(hash) {
hash.update(this._value);
if(this._originalSource)
hash.update(this._originalSource);
}
}
require("./SourceAndMapMixin")(SourceMapSource.prototype);
module.exports = SourceMapSource;

View File

@@ -0,0 +1,185 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var SourceNode = require("source-map").SourceNode;
var SourceMapConsumer = require("source-map").SourceMapConsumer;
var applySourceMap = function(
sourceNode,
sourceMapConsumer,
sourceFile,
removeGeneratedCodeForSourceFile
) {
// The following notations are used to name stuff:
// Left <------------> Middle <-------------------> Right
// Input arguments:
// sourceNode - Code mapping from Left to Middle
// sourceFile - Name of a Middle file
// sourceMapConsumer - Code mapping from Middle to Right
// Variables:
// l2m m2r
// Left <-----------------------------------------> Right
// Variables:
// l2r
var l2rResult = new SourceNode();
var l2rOutput = [];
var middleSourceContents = {};
var m2rMappingsByLine = {};
var rightSourceContentsSet = {};
var rightSourceContentsLines = {};
// Store all mappings by generated line
sourceMapConsumer.eachMapping(
function(mapping) {
(m2rMappingsByLine[mapping.generatedLine] =
m2rMappingsByLine[mapping.generatedLine] || []).push(mapping);
},
null,
SourceMapConsumer.GENERATED_ORDER
);
// Store all source contents
sourceNode.walkSourceContents(function(source, content) {
middleSourceContents["$" + source] = content;
});
var middleSource = middleSourceContents["$" + sourceFile];
var middleSourceLines = middleSource ? middleSource.split("\n") : undefined;
// Walk all left to middle mappings
sourceNode.walk(function(chunk, middleMapping) {
var source;
// Find a mapping from middle to right
if(
middleMapping.source === sourceFile &&
middleMapping.line &&
m2rMappingsByLine[middleMapping.line]
) {
var m2rBestFit;
var m2rMappings = m2rMappingsByLine[middleMapping.line];
// Note: if this becomes a performance problem, use binary search
for(var i = 0; i < m2rMappings.length; i++) {
if(m2rMappings[i].generatedColumn <= middleMapping.column) {
m2rBestFit = m2rMappings[i];
}
}
if(m2rBestFit) {
var allowMiddleName = false;
var middleLine;
var rightSourceContent;
var rightSourceContentLines;
var rightSource = m2rBestFit.source;
// Check if we have middle and right source for this mapping
// Then we could have an "identify" mapping
if(
middleSourceLines &&
rightSource &&
(middleLine = middleSourceLines[m2rBestFit.generatedLine - 1]) &&
((rightSourceContentLines = rightSourceContentsLines[rightSource]) ||
(rightSourceContent = sourceMapConsumer.sourceContentFor(
rightSource,
true
)))
) {
if(!rightSourceContentLines) {
rightSourceContentLines = rightSourceContentsLines[
rightSource
] = rightSourceContent.split("\n");
}
var rightLine = rightSourceContentLines[m2rBestFit.originalLine - 1];
if(rightLine) {
var offset = middleMapping.column - m2rBestFit.generatedColumn;
if(offset > 0) {
var middlePart = middleLine.slice(
m2rBestFit.generatedColumn,
middleMapping.column
);
var rightPart = rightLine.slice(
m2rBestFit.originalColumn,
m2rBestFit.originalColumn + offset
);
if(middlePart === rightPart) {
// When original and generated code is equal we assume we have an "identity" mapping
// In this case we can offset the original position
m2rBestFit = Object.assign({}, m2rBestFit, {
originalColumn: m2rBestFit.originalColumn + offset,
generatedColumn: middleMapping.column
});
}
}
if(!m2rBestFit.name && middleMapping.name) {
allowMiddleName =
rightLine.slice(
m2rBestFit.originalColumn,
m2rBestFit.originalColumn + middleMapping.name.length
) === middleMapping.name;
}
}
}
// Construct a left to right node from the found middle to right mapping
source = m2rBestFit.source;
l2rOutput.push(
new SourceNode(
m2rBestFit.originalLine,
m2rBestFit.originalColumn,
source,
chunk,
allowMiddleName ? middleMapping.name : m2rBestFit.name
)
);
// Set the source contents once
if(!("$" + source in rightSourceContentsSet)) {
rightSourceContentsSet["$" + source] = true;
var sourceContent = sourceMapConsumer.sourceContentFor(source, true);
if(sourceContent) {
l2rResult.setSourceContent(source, sourceContent);
}
}
return;
}
}
if((removeGeneratedCodeForSourceFile && middleMapping.source === sourceFile) || !middleMapping.source) {
// Construct a left to middle node with only generated code
// Because user do not want mappings to middle sources
// Or this chunk has no mapping
l2rOutput.push(chunk);
return;
}
// Construct a left to middle node
source = middleMapping.source;
l2rOutput.push(
new SourceNode(
middleMapping.line,
middleMapping.column,
source,
chunk,
middleMapping.name
)
);
if("$" + source in middleSourceContents) {
if(!("$" + source in rightSourceContentsSet)) {
l2rResult.setSourceContent(source, middleSourceContents["$" + source]);
delete middleSourceContents["$" + source];
}
}
});
// Put output into the resulting SourceNode
l2rResult.add(l2rOutput);
return l2rResult;
};
module.exports = applySourceMap;

View File

@@ -0,0 +1,15 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
exports.Source = require("./Source");
exports.RawSource = require("./RawSource");
exports.OriginalSource = require("./OriginalSource");
exports.SourceMapSource = require("./SourceMapSource");
exports.LineToLineMappedSource = require("./LineToLineMappedSource");
exports.CachedSource = require("./CachedSource");
exports.ConcatSource = require("./ConcatSource");
exports.ReplaceSource = require("./ReplaceSource");
exports.PrefixSource = require("./PrefixSource");

View File

@@ -0,0 +1,50 @@
{
"name": "webpack-sources",
"version": "1.4.3",
"description": "Source code handling classes for webpack",
"main": "./lib/index.js",
"scripts": {
"pretest": "npm run lint && npm run beautify-lint",
"test": "mocha --full-trace --check-leaks",
"travis": "npm run cover -- --report lcovonly",
"lint": "eslint lib test",
"beautify-lint": "beautify-lint lib/**.js test/**.js",
"beautify": "beautify-rewrite lib/**.js test/**.js",
"precover": "npm run lint && npm run beautify-lint",
"cover": "istanbul cover node_modules/mocha/bin/_mocha",
"publish-patch": "npm test && npm version patch && git push && git push --tags && npm publish"
},
"dependencies": {
"source-list-map": "^2.0.0",
"source-map": "~0.6.1"
},
"devDependencies": {
"beautify-lint": "^1.0.3",
"codecov.io": "^0.1.6",
"coveralls": "^2.11.6",
"eslint": "^4.18.2",
"eslint-plugin-nodeca": "^1.0.3",
"istanbul": "^0.4.1",
"js-beautify": "^1.5.10",
"mocha": "^3.4.2",
"should": "^11.2.1",
"sourcemap-validator": "^1.1.0"
},
"files": [
"lib/"
],
"repository": {
"type": "git",
"url": "git+https://github.com/webpack/webpack-sources.git"
},
"keywords": [
"webpack",
"source-map"
],
"author": "Tobias Koppers @sokra",
"license": "MIT",
"bugs": {
"url": "https://github.com/webpack/webpack-sources/issues"
},
"homepage": "https://github.com/webpack/webpack-sources#readme"
}

View File

@@ -0,0 +1,43 @@
{
"name": "workbox-webpack-plugin",
"version": "6.6.0",
"description": "A plugin for your Webpack build process, helping you generate a manifest of local files that workbox-sw should precache.",
"keywords": [
"workbox",
"workboxjs",
"webpack",
"service worker",
"caching",
"fetch requests",
"offline",
"file manifest"
],
"workbox": {
"packageType": "node_ts"
},
"main": "build/index.js",
"types": "build/index.d.ts",
"engines": {
"node": ">=10.0.0"
},
"dependencies": {
"fast-json-stable-stringify": "^2.1.0",
"pretty-bytes": "^5.4.1",
"upath": "^1.2.0",
"webpack-sources": "^1.4.3",
"workbox-build": "6.6.0"
},
"peerDependencies": {
"webpack": "^4.4.0 || ^5.9.0"
},
"devDependencies": {
"@types/node": "^18.15.11",
"@types/webpack": "^5.28.1"
},
"author": "Google's Web DevRel Team",
"license": "MIT",
"repository": "googlechrome/workbox",
"bugs": "https://github.com/GoogleChrome/workbox/issues",
"homepage": "https://github.com/GoogleChrome/workbox",
"gitHead": "252644491d9bb5a67518935ede6df530107c9475"
}

View File

@@ -0,0 +1,243 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {validateWebpackGenerateSWOptions} from 'workbox-build/build/lib/validate-options';
import {bundle} from 'workbox-build/build/lib/bundle';
import {populateSWTemplate} from 'workbox-build/build/lib/populate-sw-template';
import prettyBytes from 'pretty-bytes';
import webpack from 'webpack';
import {ManifestEntry, WebpackGenerateSWOptions} from 'workbox-build';
import {getScriptFilesForChunks} from './lib/get-script-files-for-chunks';
import {getManifestEntriesFromCompilation} from './lib/get-manifest-entries-from-compilation';
import {relativeToOutputPath} from './lib/relative-to-output-path';
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
const {RawSource} = webpack.sources || require('webpack-sources');
// Used to keep track of swDest files written by *any* instance of this plugin.
// See https://github.com/GoogleChrome/workbox/issues/2181
const _generatedAssetNames = new Set<string>();
export interface GenerateSWConfig extends WebpackGenerateSWOptions {
manifestEntries?: Array<ManifestEntry>;
}
/**
* This class supports creating a new, ready-to-use service worker file as
* part of the webpack compilation process.
*
* Use an instance of `GenerateSW` in the
* [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
* webpack config.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* new GenerateSW({
* exclude: [/.../, '...'],
* maximumFileSizeToCacheInBytes: ...,
* navigateFallback: '...',
* runtimeCaching: [{
* // Routing via a matchCallback function:
* urlPattern: ({request, url}) => ...,
* handler: '...',
* options: {
* cacheName: '...',
* expiration: {
* maxEntries: ...,
* },
* },
* }, {
* // Routing via a RegExp:
* urlPattern: new RegExp('...'),
* handler: '...',
* options: {
* cacheName: '...',
* plugins: [..., ...],
* },
* }],
* skipWaiting: ...,
* });
* ```
*
* @memberof module:workbox-webpack-plugin
*/
class GenerateSW {
protected config: GenerateSWConfig;
private alreadyCalled: boolean;
/**
* Creates an instance of GenerateSW.
*/
constructor(config: GenerateSWConfig = {}) {
this.config = config;
this.alreadyCalled = false;
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
propagateWebpackConfig(compiler: webpack.Compiler): void {
// Because this.config is listed last, properties that are already set
// there take precedence over derived properties from the compiler.
this.config = Object.assign(
{
mode: compiler.options.mode,
sourcemap: Boolean(compiler.options.devtool),
},
this.config,
);
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
apply(compiler: webpack.Compiler): void {
this.propagateWebpackConfig(compiler);
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
if (webpack.version.startsWith('4.')) {
compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) =>
this.addAssets(compilation).catch((error) => {
compilation.errors.push(error);
}),
);
} else {
const {PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER} = webpack.Compilation;
// Specifically hook into thisCompilation, as per
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
compiler.hooks.thisCompilation.tap(
this.constructor.name,
(compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: this.constructor.name,
// TODO(jeffposnick): This may need to change eventually.
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
},
() =>
this.addAssets(compilation).catch(
(error: webpack.WebpackError) => {
compilation.errors.push(error);
},
),
);
},
);
}
}
/**
* @param {Object} compilation The webpack compilation.
*
* @private
*/
async addAssets(compilation: webpack.Compilation): Promise<void> {
// See https://github.com/GoogleChrome/workbox/issues/1790
if (this.alreadyCalled) {
const warningMessage =
`${this.constructor.name} has been called ` +
`multiple times, perhaps due to running webpack in --watch mode. The ` +
`precache manifest generated after the first call may be inaccurate! ` +
`Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
`more information.`;
if (
!compilation.warnings.some(
(warning) =>
warning instanceof Error && warning.message === warningMessage,
)
) {
compilation.warnings.push(
Error(warningMessage) as webpack.WebpackError,
);
}
} else {
this.alreadyCalled = true;
}
let config: GenerateSWConfig = {};
try {
// emit might be called multiple times; instead of modifying this.config,
// use a validated copy.
// See https://github.com/GoogleChrome/workbox/issues/2158
config = validateWebpackGenerateSWOptions(this.config);
} catch (error) {
if (error instanceof Error) {
throw new Error(
`Please check your ${this.constructor.name} plugin ` +
`configuration:\n${error.message}`,
);
}
}
// Ensure that we don't precache any of the assets generated by *any*
// instance of this plugin.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
config.exclude!.push(({asset}) => _generatedAssetNames.has(asset.name));
if (config.importScriptsViaChunks) {
// Anything loaded via importScripts() is implicitly cached by the service
// worker, and should not be added to the precache manifest.
config.excludeChunks = (config.excludeChunks || []).concat(
config.importScriptsViaChunks,
);
const scripts = getScriptFilesForChunks(
compilation,
config.importScriptsViaChunks,
);
config.importScripts = (config.importScripts || []).concat(scripts);
}
const {size, sortedEntries} = await getManifestEntriesFromCompilation(
compilation,
config,
);
config.manifestEntries = sortedEntries;
const unbundledCode = populateSWTemplate(config);
const files = await bundle({
babelPresetEnvTargets: config.babelPresetEnvTargets,
inlineWorkboxRuntime: config.inlineWorkboxRuntime,
mode: config.mode,
sourcemap: config.sourcemap,
swDest: relativeToOutputPath(compilation, config.swDest!),
unbundledCode,
});
for (const file of files) {
compilation.emitAsset(
file.name,
new RawSource(Buffer.from(file.contents)),
{
// See https://github.com/webpack-contrib/compression-webpack-plugin/issues/218#issuecomment-726196160
minimized: config.mode === 'production',
},
);
_generatedAssetNames.add(file.name);
}
if (compilation.getLogger) {
const logger = compilation.getLogger(this.constructor.name);
logger.info(`The service worker at ${config.swDest ?? ''} will precache
${config.manifestEntries.length} URLs, totaling ${prettyBytes(size)}.`);
}
}
}
export {GenerateSW};

View File

@@ -0,0 +1,19 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {GenerateSW, GenerateSWConfig} from './generate-sw';
import {InjectManifest} from './inject-manifest';
/**
* @module workbox-webpack-plugin
*/
export {GenerateSW, GenerateSWConfig, InjectManifest};
// TODO: remove this in v7.
// See https://github.com/GoogleChrome/workbox/issues/3033
export default {GenerateSW, InjectManifest};

View File

@@ -0,0 +1,371 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {escapeRegExp} from 'workbox-build/build/lib/escape-regexp';
import {replaceAndUpdateSourceMap} from 'workbox-build/build/lib/replace-and-update-source-map';
import {validateWebpackInjectManifestOptions} from 'workbox-build/build/lib/validate-options';
import prettyBytes from 'pretty-bytes';
import stringify from 'fast-json-stable-stringify';
import upath from 'upath';
import webpack from 'webpack';
import {getManifestEntriesFromCompilation} from './lib/get-manifest-entries-from-compilation';
import {getSourcemapAssetName} from './lib/get-sourcemap-asset-name';
import {relativeToOutputPath} from './lib/relative-to-output-path';
import {WebpackInjectManifestOptions} from 'workbox-build';
// Used to keep track of swDest files written by *any* instance of this plugin.
// See https://github.com/GoogleChrome/workbox/issues/2181
const _generatedAssetNames = new Set<string>();
// SingleEntryPlugin in v4 was renamed to EntryPlugin in v5.
const SingleEntryPlugin = webpack.EntryPlugin || webpack.SingleEntryPlugin;
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-686607633
const {RawSource} = webpack.sources || require('webpack-sources');
/**
* This class supports compiling a service worker file provided via `swSrc`,
* and injecting into that service worker a list of URLs and revision
* information for precaching based on the webpack asset pipeline.
*
* Use an instance of `InjectManifest` in the
* [`plugins` array](https://webpack.js.org/concepts/plugins/#usage) of a
* webpack config.
*
* In addition to injecting the manifest, this plugin will perform a compilation
* of the `swSrc` file, using the options from the main webpack configuration.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* new InjectManifest({
* exclude: [/.../, '...'],
* maximumFileSizeToCacheInBytes: ...,
* swSrc: '...',
* });
* ```
*
* @memberof module:workbox-webpack-plugin
*/
class InjectManifest {
protected config: WebpackInjectManifestOptions;
private alreadyCalled: boolean;
/**
* Creates an instance of InjectManifest.
*/
constructor(config: WebpackInjectManifestOptions) {
this.config = config;
this.alreadyCalled = false;
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
propagateWebpackConfig(compiler: webpack.Compiler): void {
// Because this.config is listed last, properties that are already set
// there take precedence over derived properties from the compiler.
this.config = Object.assign(
{
mode: compiler.options.mode,
// Use swSrc with a hardcoded .js extension, in case swSrc is a .ts file.
swDest: upath.parse(this.config.swSrc).name + '.js',
},
this.config,
);
}
/**
* @param {Object} [compiler] default compiler object passed from webpack
*
* @private
*/
apply(compiler: webpack.Compiler): void {
this.propagateWebpackConfig(compiler);
compiler.hooks.make.tapPromise(this.constructor.name, (compilation) =>
this.handleMake(compilation, compiler).catch(
(error: webpack.WebpackError) => {
compilation.errors.push(error);
},
),
);
// webpack v4/v5 compatibility:
// https://github.com/webpack/webpack/issues/11425#issuecomment-690387207
if (webpack.version?.startsWith('4.')) {
compiler.hooks.emit.tapPromise(this.constructor.name, (compilation) =>
this.addAssets(compilation).catch((error: webpack.WebpackError) => {
compilation.errors.push(error);
}),
);
} else {
const {PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER} = webpack.Compilation;
// Specifically hook into thisCompilation, as per
// https://github.com/webpack/webpack/issues/11425#issuecomment-690547848
compiler.hooks.thisCompilation.tap(
this.constructor.name,
(compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: this.constructor.name,
// TODO(jeffposnick): This may need to change eventually.
// See https://github.com/webpack/webpack/issues/11822#issuecomment-726184972
stage: PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - 10,
},
() =>
this.addAssets(compilation).catch(
(error: webpack.WebpackError) => {
compilation.errors.push(error);
},
),
);
},
);
}
}
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
async performChildCompilation(
compilation: webpack.Compilation,
parentCompiler: webpack.Compiler,
): Promise<void> {
const outputOptions = {
path: parentCompiler.options.output.path,
filename: this.config.swDest,
};
const childCompiler = compilation.createChildCompiler(
this.constructor.name,
outputOptions,
[],
);
childCompiler.context = parentCompiler.context;
childCompiler.inputFileSystem = parentCompiler.inputFileSystem;
childCompiler.outputFileSystem = parentCompiler.outputFileSystem;
if (Array.isArray(this.config.webpackCompilationPlugins)) {
for (const plugin of this.config.webpackCompilationPlugins) {
// plugin has a generic type, eslint complains for an unsafe
// assign and unsafe use
// eslint-disable-next-line
plugin.apply(childCompiler);
}
}
new SingleEntryPlugin(
parentCompiler.context,
this.config.swSrc,
this.constructor.name,
).apply(childCompiler);
await new Promise<void>((resolve, reject) => {
childCompiler.runAsChild((error, _entries, childCompilation) => {
if (error) {
reject(error);
} else {
compilation.warnings = compilation.warnings.concat(
childCompilation?.warnings ?? [],
);
compilation.errors = compilation.errors.concat(
childCompilation?.errors ?? [],
);
resolve();
}
});
});
}
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
addSrcToAssets(
compilation: webpack.Compilation,
parentCompiler: webpack.Compiler,
): void {
// eslint-disable-next-line
const source = (parentCompiler.inputFileSystem as any).readFileSync(
this.config.swSrc,
);
compilation.emitAsset(this.config.swDest!, new RawSource(source));
}
/**
* @param {Object} compilation The webpack compilation.
* @param {Object} parentCompiler The webpack parent compiler.
*
* @private
*/
async handleMake(
compilation: webpack.Compilation,
parentCompiler: webpack.Compiler,
): Promise<void> {
try {
this.config = validateWebpackInjectManifestOptions(this.config);
} catch (error) {
if (error instanceof Error) {
throw new Error(
`Please check your ${this.constructor.name} plugin ` +
`configuration:\n${error.message}`,
);
}
}
this.config.swDest = relativeToOutputPath(compilation, this.config.swDest!);
_generatedAssetNames.add(this.config.swDest);
if (this.config.compileSrc) {
await this.performChildCompilation(compilation, parentCompiler);
} else {
this.addSrcToAssets(compilation, parentCompiler);
// This used to be a fatal error, but just warn at runtime because we
// can't validate it easily.
if (
Array.isArray(this.config.webpackCompilationPlugins) &&
this.config.webpackCompilationPlugins.length > 0
) {
compilation.warnings.push(
new Error(
'compileSrc is false, so the ' +
'webpackCompilationPlugins option will be ignored.',
) as webpack.WebpackError,
);
}
}
}
/**
* @param {Object} compilation The webpack compilation.
*
* @private
*/
async addAssets(compilation: webpack.Compilation): Promise<void> {
// See https://github.com/GoogleChrome/workbox/issues/1790
if (this.alreadyCalled) {
const warningMessage =
`${this.constructor.name} has been called ` +
`multiple times, perhaps due to running webpack in --watch mode. The ` +
`precache manifest generated after the first call may be inaccurate! ` +
`Please see https://github.com/GoogleChrome/workbox/issues/1790 for ` +
`more information.`;
if (
!compilation.warnings.some(
(warning) =>
warning instanceof Error && warning.message === warningMessage,
)
) {
compilation.warnings.push(
new Error(warningMessage) as webpack.WebpackError,
);
}
} else {
this.alreadyCalled = true;
}
const config = Object.assign({}, this.config);
// Ensure that we don't precache any of the assets generated by *any*
// instance of this plugin.
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
config.exclude!.push(({asset}) => _generatedAssetNames.has(asset.name));
// See https://webpack.js.org/contribute/plugin-patterns/#monitoring-the-watch-graph
const absoluteSwSrc = upath.resolve(this.config.swSrc);
compilation.fileDependencies.add(absoluteSwSrc);
const swAsset = compilation.getAsset(config.swDest!);
const swAssetString = swAsset!.source.source().toString();
const globalRegexp = new RegExp(escapeRegExp(config.injectionPoint!), 'g');
const injectionResults = swAssetString.match(globalRegexp);
if (!injectionResults) {
throw new Error(
`Can't find ${config.injectionPoint ?? ''} in your SW source.`,
);
}
if (injectionResults.length !== 1) {
throw new Error(
`Multiple instances of ${config.injectionPoint ?? ''} were ` +
`found in your SW source. Include it only once. For more info, see ` +
`https://github.com/GoogleChrome/workbox/issues/2681`,
);
}
const {size, sortedEntries} = await getManifestEntriesFromCompilation(
compilation,
config,
);
let manifestString = stringify(sortedEntries);
if (
this.config.compileSrc &&
// See https://github.com/GoogleChrome/workbox/issues/2729
!(
compilation.options?.devtool === 'eval-cheap-source-map' &&
compilation.options.optimization?.minimize
)
) {
// See https://github.com/GoogleChrome/workbox/issues/2263
manifestString = manifestString.replace(/"/g, `'`);
}
const sourcemapAssetName = getSourcemapAssetName(
compilation,
swAssetString,
config.swDest!,
);
if (sourcemapAssetName) {
_generatedAssetNames.add(sourcemapAssetName);
const sourcemapAsset = compilation.getAsset(sourcemapAssetName);
const {source, map} = await replaceAndUpdateSourceMap({
jsFilename: config.swDest!,
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
originalMap: JSON.parse(sourcemapAsset!.source.source().toString()),
originalSource: swAssetString,
replaceString: manifestString,
searchString: config.injectionPoint!,
});
compilation.updateAsset(sourcemapAssetName, new RawSource(map));
compilation.updateAsset(config.swDest!, new RawSource(source));
} else {
// If there's no sourcemap associated with swDest, a simple string
// replacement will suffice.
compilation.updateAsset(
config.swDest!,
new RawSource(
swAssetString.replace(config.injectionPoint!, manifestString),
),
);
}
if (compilation.getLogger) {
const logger = compilation.getLogger(this.constructor.name);
logger.info(`The service worker at ${config.swDest ?? ''} will precache
${sortedEntries.length} URLs, totaling ${prettyBytes(size)}.`);
}
}
}
export {InjectManifest};

View File

@@ -0,0 +1,29 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import crypto from 'crypto';
import type {Asset} from 'webpack';
/**
* @param {Asset} asset
* @return {string} The MD5 hash of the asset's source.
*
* @private
*/
export function getAssetHash(asset: Asset): string | null {
// If webpack has the asset marked as immutable, then we don't need to
// use an out-of-band revision for it.
// See https://github.com/webpack/webpack/issues/9038
if (asset.info && asset.info.immutable) {
return null;
}
return crypto.createHash('md5')
.update(Buffer.from(asset.source.source()))
.digest('hex');
}

View File

@@ -0,0 +1,252 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {
Asset,
Chunk,
Compilation,
ModuleFilenameHelpers,
WebpackError,
} from 'webpack';
import {transformManifest} from 'workbox-build/build/lib/transform-manifest';
import {
WebpackGenerateSWOptions,
WebpackInjectManifestOptions,
ManifestEntry,
FileDetails,
} from 'workbox-build';
import {getAssetHash} from './get-asset-hash';
import {resolveWebpackURL} from './resolve-webpack-url';
/**
* For a given asset, checks whether at least one of the conditions matches.
*
* @param {Asset} asset The webpack asset in question. This will be passed
* to any functions that are listed as conditions.
* @param {Compilation} compilation The webpack compilation. This will be passed
* to any functions that are listed as conditions.
* @param {Array<string|RegExp|Function>} conditions
* @return {boolean} Whether or not at least one condition matches.
* @private
*/
function checkConditions(
asset: Asset,
compilation: Compilation,
conditions: Array<
//eslint-disable-next-line @typescript-eslint/ban-types
string | RegExp | ((arg0: any) => boolean)
> = [],
): boolean {
for (const condition of conditions) {
if (typeof condition === 'function') {
return condition({asset, compilation});
//return compilation !== null;
} else {
if (ModuleFilenameHelpers.matchPart(asset.name, condition)) {
return true;
}
}
}
// We'll only get here if none of the conditions applied.
return false;
}
/**
* Returns the names of all the assets in all the chunks in a chunk group,
* if provided a chunk group name.
* Otherwise, if provided a chunk name, return all the assets in that chunk.
* Otherwise, if there isn't a chunk group or chunk with that name, return null.
*
* @param {Compilation} compilation
* @param {string} chunkOrGroup
* @return {Array<string>|null}
* @private
*/
function getNamesOfAssetsInChunkOrGroup(
compilation: Compilation,
chunkOrGroup: string,
): Array<string> | null {
const chunkGroup =
compilation.namedChunkGroups &&
compilation.namedChunkGroups.get(chunkOrGroup);
if (chunkGroup) {
const assetNames = [];
for (const chunk of chunkGroup.chunks) {
assetNames.push(...getNamesOfAssetsInChunk(chunk));
}
return assetNames;
} else {
const chunk =
compilation.namedChunks && compilation.namedChunks.get(chunkOrGroup);
if (chunk) {
return getNamesOfAssetsInChunk(chunk);
}
}
// If we get here, there's no chunkGroup or chunk with that name.
return null;
}
/**
* Returns the names of all the assets in a chunk.
*
* @param {Chunk} chunk
* @return {Array<string>}
* @private
*/
function getNamesOfAssetsInChunk(chunk: Chunk): Array<string> {
const assetNames: Array<string> = [];
assetNames.push(...chunk.files);
// This only appears to be set in webpack v5.
if (chunk.auxiliaryFiles) {
assetNames.push(...chunk.auxiliaryFiles);
}
return assetNames;
}
/**
* Filters the set of assets out, based on the configuration options provided:
* - chunks and excludeChunks, for chunkName-based criteria.
* - include and exclude, for more general criteria.
*
* @param {Compilation} compilation The webpack compilation.
* @param {Object} config The validated configuration, obtained from the plugin.
* @return {Set<Asset>} The assets that should be included in the manifest,
* based on the criteria provided.
* @private
*/
function filterAssets(
compilation: Compilation,
config: WebpackInjectManifestOptions | WebpackGenerateSWOptions,
): Set<Asset> {
const filteredAssets = new Set<Asset>();
const assets = compilation.getAssets();
const allowedAssetNames = new Set<string>();
// See https://github.com/GoogleChrome/workbox/issues/1287
if (Array.isArray(config.chunks)) {
for (const name of config.chunks) {
// See https://github.com/GoogleChrome/workbox/issues/2717
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(
compilation,
name,
);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
allowedAssetNames.add(assetName);
}
} else {
compilation.warnings.push(
new Error(
`The chunk '${name}' was ` +
`provided in your Workbox chunks config, but was not found in the ` +
`compilation.`,
) as WebpackError,
);
}
}
}
const deniedAssetNames = new Set();
if (Array.isArray(config.excludeChunks)) {
for (const name of config.excludeChunks) {
// See https://github.com/GoogleChrome/workbox/issues/2717
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(
compilation,
name,
);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
deniedAssetNames.add(assetName);
}
} // Don't warn if the chunk group isn't found.
}
}
for (const asset of assets) {
// chunk based filtering is funky because:
// - Each asset might belong to one or more chunks.
// - If *any* of those chunk names match our config.excludeChunks,
// then we skip that asset.
// - If the config.chunks is defined *and* there's no match
// between at least one of the chunkNames and one entry, then
// we skip that assets as well.
if (deniedAssetNames.has(asset.name)) {
continue;
}
if (Array.isArray(config.chunks) && !allowedAssetNames.has(asset.name)) {
continue;
}
// Next, check asset-level checks via includes/excludes:
const isExcluded = checkConditions(asset, compilation, config.exclude);
if (isExcluded) {
continue;
}
// Treat an empty config.includes as an implicit inclusion.
const isIncluded =
!Array.isArray(config.include) ||
checkConditions(asset, compilation, config.include);
if (!isIncluded) {
continue;
}
// If we've gotten this far, then add the asset.
filteredAssets.add(asset);
}
return filteredAssets;
}
export async function getManifestEntriesFromCompilation(
compilation: Compilation,
config: WebpackGenerateSWOptions | WebpackInjectManifestOptions,
): Promise<{size: number; sortedEntries: ManifestEntry[]}> {
const filteredAssets = filterAssets(compilation, config);
const {publicPath} = compilation.options.output;
const fileDetails = Array.from(filteredAssets).map((asset) => {
return {
file: resolveWebpackURL(publicPath as string, asset.name),
hash: getAssetHash(asset),
size: asset.source.size() || 0,
} as FileDetails;
});
const {manifestEntries, size, warnings} = await transformManifest({
fileDetails,
additionalManifestEntries: config.additionalManifestEntries,
dontCacheBustURLsMatching: config.dontCacheBustURLsMatching,
manifestTransforms: config.manifestTransforms,
maximumFileSizeToCacheInBytes: config.maximumFileSizeToCacheInBytes,
modifyURLPrefix: config.modifyURLPrefix,
transformParam: compilation,
});
// See https://github.com/GoogleChrome/workbox/issues/2790
for (const warning of warnings) {
compilation.warnings.push(new Error(warning) as WebpackError);
}
// Ensure that the entries are properly sorted by URL.
const sortedEntries = manifestEntries.sort((a, b) =>
a.url === b.url ? 0 : a.url > b.url ? 1 : -1,
);
return {size, sortedEntries};
}

View File

@@ -0,0 +1,51 @@
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import upath from 'upath';
import {Compilation, WebpackError} from 'webpack';
import {resolveWebpackURL} from './resolve-webpack-url';
export function getScriptFilesForChunks(
compilation: Compilation,
chunkNames: Array<string>,
): Array<string> {
const {chunks} = compilation.getStats().toJson({chunks: true});
const {publicPath} = compilation.options.output;
const scriptFiles = new Set<string>();
for (const chunkName of chunkNames) {
const chunk = chunks!.find((chunk) => chunk.names?.includes(chunkName));
if (chunk) {
for (const file of chunk?.files ?? []) {
// See https://github.com/GoogleChrome/workbox/issues/2161
if (upath.extname(file) === '.js') {
scriptFiles.add(resolveWebpackURL(publicPath as string, file));
}
}
} else {
compilation.warnings.push(
new Error(
`${chunkName} was provided to ` +
`importScriptsViaChunks, but didn't match any named chunks.`,
) as WebpackError,
);
}
}
if (scriptFiles.size === 0) {
compilation.warnings.push(
new Error(
`There were no assets matching ` +
`importScriptsViaChunks: [${chunkNames.join(' ')}].`,
) as WebpackError,
);
}
return Array.from(scriptFiles);
}

View File

@@ -0,0 +1,54 @@
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {getSourceMapURL} from 'workbox-build/build/lib/get-source-map-url';
import upath from 'upath';
import type {Compilation} from 'webpack';
/**
* If our bundled swDest file contains a sourcemap, we would invalidate that
* mapping if we just replaced injectionPoint with the stringified manifest.
* Instead, we need to update the swDest contents as well as the sourcemap
* at the same time.
*
* See https://github.com/GoogleChrome/workbox/issues/2235
*
* @param {Object} compilation The current webpack compilation.
* @param {string} swContents The contents of the swSrc file, which may or
* may not include a valid sourcemap comment.
* @param {string} swDest The configured swDest value.
* @return {string|undefined} If the swContents contains a valid sourcemap
* comment pointing to an asset present in the compilation, this will return the
* name of that asset. Otherwise, it will return undefined.
*
* @private
*/
export function getSourcemapAssetName(
compilation: Compilation,
swContents: string,
swDest: string,
): string | undefined {
const url = getSourceMapURL(swContents);
if (url) {
// Translate the relative URL to what the presumed name for the webpack
// asset should be.
// This *might* not be a valid asset if the sourcemap URL that was found
// was added by another module incidentally.
// See https://github.com/GoogleChrome/workbox/issues/2250
const swAssetDirname = upath.dirname(swDest);
const sourcemapURLAssetName = upath.normalize(
upath.join(swAssetDirname, url),
);
// Not sure if there's a better way to check for asset existence?
if (compilation.getAsset(sourcemapURLAssetName)) {
return sourcemapURLAssetName;
}
}
return undefined;
}

View File

@@ -0,0 +1,29 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import upath from 'upath';
import type {Compilation} from 'webpack';
/**
* @param {Object} compilation The webpack compilation.
* @param {string} swDest The original swDest value.
*
* @return {string} If swDest was not absolute, the returns swDest as-is.
* Otherwise, returns swDest relative to the compilation's output path.
*
* @private
*/
export function relativeToOutputPath(compilation: Compilation, swDest: string): string {
// See https://github.com/jantimon/html-webpack-plugin/pull/266/files#diff-168726dbe96b3ce427e7fedce31bb0bcR38
if (upath.resolve(swDest) === upath.normalize(swDest)) {
return upath.relative(compilation.options.output.path!, swDest);
}
// Otherwise, return swDest as-is.
return swDest;
}

View File

@@ -0,0 +1,30 @@
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
/**
* Resolves a url in the way that webpack would (with string concatenation)
*
* Use publicPath + filePath instead of url.resolve(publicPath, filePath) see:
* https://webpack.js.org/configuration/output/#output-publicpath
*
* @function resolveWebpackURL
* @param {string} publicPath The publicPath value from webpack's compilation.
* @param {Array<string>} paths File paths to join
* @return {string} Joined file path
*
* @private
*/
export function resolveWebpackURL(publicPath: string, ...paths: Array<string>): string {
// This is a change in webpack v5.
// See https://github.com/jantimon/html-webpack-plugin/pull/1516
if (publicPath === 'auto') {
return paths.join('');
} else {
return [publicPath, ...paths].join('');
}
}

View File

@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"esModuleInterop": true,
"module": "CommonJS",
"outDir": "./build",
"resolveJsonModule": true,
"rootDir": "./src",
"target": "ES2018",
"tsBuildInfoFile": "./tsconfig.tsbuildinfo"
},
"include": ["src/**/*.ts"],
"references": [{"path": "../workbox-build/"}]
}

File diff suppressed because one or more lines are too long