Initial commit: Developer Tools MVP with visual editor

- Complete React app with 7 developer tools
- JSON Tool with visual structured editor
- Serialize Tool with visual structured editor
- URL, Base64, CSV/JSON, Beautifier, Diff tools
- Responsive navigation with dropdown menu
- Dark/light mode toggle
- Mobile-responsive design with sticky header
- All tools working with copy/paste functionality
This commit is contained in:
dwindown
2025-08-02 09:31:26 +07:00
commit 7f2dd5260f
45657 changed files with 4730486 additions and 0 deletions

243
node_modules/workbox-webpack-plugin/src/generate-sw.ts generated vendored Normal file
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};

19
node_modules/workbox-webpack-plugin/src/index.ts generated vendored Normal file
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('');
}
}