This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

19
frontend/node_modules/workbox-build/.ncurc.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
/*
Copyright 2020 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.
*/
// We use `npx npm-check-updates` to find updates to dependencies.
// Some dependencies have breaking changes that we can't resolve.
// This config file excludes those dependencies from the checks
// until we're able to remediate our code to deal with them.
module.exports = {
reject: [
// joi v16 is the last release to support Node v10:
// https://github.com/sideway/joi/issues/2262
'@hapi/joi',
],
};

19
frontend/node_modules/workbox-build/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.

1
frontend/node_modules/workbox-build/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
This module's documentation can be found at https://developers.google.com/web/tools/workbox/modules/workbox-build

View File

@@ -0,0 +1,6 @@
{
"origin": "https://storage.googleapis.com",
"bucketName": "workbox-cdn",
"releasesDir": "releases",
"latestVersion": "6.6.0"
}

View File

@@ -0,0 +1,47 @@
import { BuildResult, GenerateSWOptions } from './types';
/**
* This method creates a list of URLs to precache, referred to as a "precache
* manifest", based on the options you provide.
*
* It also takes in additional options that configures the service worker's
* behavior, like any `runtimeCaching` rules it should use.
*
* Based on the precache manifest and the additional configuration, it writes
* a ready-to-use service worker file to disk at `swDest`.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* const {count, size, warnings} = await generateSW({
* dontCacheBustURLsMatching: [new RegExp('...')],
* globDirectory: '...',
* globPatterns: ['...', '...'],
* 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: ...,
* swDest: '...',
* });
* ```
*
* @memberof workbox-build
*/
export declare function generateSW(config: GenerateSWOptions): Promise<BuildResult>;

View File

@@ -0,0 +1,105 @@
"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 upath_1 = __importDefault(require("upath"));
const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries");
const rebase_path_1 = require("./lib/rebase-path");
const validate_options_1 = require("./lib/validate-options");
const write_sw_using_default_template_1 = require("./lib/write-sw-using-default-template");
/**
* This method creates a list of URLs to precache, referred to as a "precache
* manifest", based on the options you provide.
*
* It also takes in additional options that configures the service worker's
* behavior, like any `runtimeCaching` rules it should use.
*
* Based on the precache manifest and the additional configuration, it writes
* a ready-to-use service worker file to disk at `swDest`.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* const {count, size, warnings} = await generateSW({
* dontCacheBustURLsMatching: [new RegExp('...')],
* globDirectory: '...',
* globPatterns: ['...', '...'],
* 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: ...,
* swDest: '...',
* });
* ```
*
* @memberof workbox-build
*/
async function generateSW(config) {
const options = (0, validate_options_1.validateGenerateSWOptions)(config);
let entriesResult;
if (options.globDirectory) {
// Make sure we leave swDest out of the precache manifest.
options.globIgnores.push((0, rebase_path_1.rebasePath)({
baseDirectory: options.globDirectory,
file: options.swDest,
}));
// If we create an extra external runtime file, ignore that, too.
// See https://rollupjs.org/guide/en/#outputchunkfilenames for naming.
if (!options.inlineWorkboxRuntime) {
const swDestDir = upath_1.default.dirname(options.swDest);
const workboxRuntimeFile = upath_1.default.join(swDestDir, 'workbox-*.js');
options.globIgnores.push((0, rebase_path_1.rebasePath)({
baseDirectory: options.globDirectory,
file: workboxRuntimeFile,
}));
}
// We've previously asserted that options.globDirectory is set, so this
// should be a safe cast.
entriesResult = await (0, get_file_manifest_entries_1.getFileManifestEntries)(options);
}
else {
entriesResult = {
count: 0,
manifestEntries: [],
size: 0,
warnings: [],
};
}
const filePaths = await (0, write_sw_using_default_template_1.writeSWUsingDefaultTemplate)(Object.assign({
manifestEntries: entriesResult.manifestEntries,
}, options));
return {
filePaths,
count: entriesResult.count,
size: entriesResult.size,
warnings: entriesResult.warnings,
};
}
exports.generateSW = generateSW;

View File

@@ -0,0 +1,20 @@
import { GetManifestOptions, GetManifestResult } from './types';
/**
* This method returns a list of URLs to precache, referred to as a "precache
* manifest", along with details about the number of entries and their size,
* based on the options you provide.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* const {count, manifestEntries, size, warnings} = await getManifest({
* dontCacheBustURLsMatching: [new RegExp('...')],
* globDirectory: '...',
* globPatterns: ['...', '...'],
* maximumFileSizeToCacheInBytes: ...,
* });
* ```
*
* @memberof workbox-build
*/
export declare function getManifest(config: GetManifestOptions): Promise<GetManifestResult>;

View File

@@ -0,0 +1,35 @@
"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.getManifest = void 0;
const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries");
const validate_options_1 = require("./lib/validate-options");
/**
* This method returns a list of URLs to precache, referred to as a "precache
* manifest", along with details about the number of entries and their size,
* based on the options you provide.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* const {count, manifestEntries, size, warnings} = await getManifest({
* dontCacheBustURLsMatching: [new RegExp('...')],
* globDirectory: '...',
* globPatterns: ['...', '...'],
* maximumFileSizeToCacheInBytes: ...,
* });
* ```
*
* @memberof workbox-build
*/
async function getManifest(config) {
const options = (0, validate_options_1.validateGetManifestOptions)(config);
return await (0, get_file_manifest_entries_1.getFileManifestEntries)(options);
}
exports.getManifest = getManifest;

10
frontend/node_modules/workbox-build/build/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { copyWorkboxLibraries } from './lib/copy-workbox-libraries';
import { getModuleURL } from './lib/cdn-utils';
import { generateSW } from './generate-sw';
import { getManifest } from './get-manifest';
import { injectManifest } from './inject-manifest';
/**
* @module workbox-build
*/
export { copyWorkboxLibraries, generateSW, getManifest, getModuleURL, injectManifest, };
export * from './types';

35
frontend/node_modules/workbox-build/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,35 @@
"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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.injectManifest = exports.getModuleURL = exports.getManifest = exports.generateSW = exports.copyWorkboxLibraries = void 0;
const copy_workbox_libraries_1 = require("./lib/copy-workbox-libraries");
Object.defineProperty(exports, "copyWorkboxLibraries", { enumerable: true, get: function () { return copy_workbox_libraries_1.copyWorkboxLibraries; } });
const cdn_utils_1 = require("./lib/cdn-utils");
Object.defineProperty(exports, "getModuleURL", { enumerable: true, get: function () { return cdn_utils_1.getModuleURL; } });
const generate_sw_1 = require("./generate-sw");
Object.defineProperty(exports, "generateSW", { enumerable: true, get: function () { return generate_sw_1.generateSW; } });
const get_manifest_1 = require("./get-manifest");
Object.defineProperty(exports, "getManifest", { enumerable: true, get: function () { return get_manifest_1.getManifest; } });
const inject_manifest_1 = require("./inject-manifest");
Object.defineProperty(exports, "injectManifest", { enumerable: true, get: function () { return inject_manifest_1.injectManifest; } });
__exportStar(require("./types"), exports);

View File

@@ -0,0 +1,30 @@
import { BuildResult, InjectManifestOptions } from './types';
/**
* This method creates a list of URLs to precache, referred to as a "precache
* manifest", based on the options you provide.
*
* The manifest is injected into the `swSrc` file, and the placeholder string
* `injectionPoint` determines where in the file the manifest should go.
*
* The final service worker file, with the manifest injected, is written to
* disk at `swDest`.
*
* This method will not compile or bundle your `swSrc` file; it just handles
* injecting the manifest.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* const {count, size, warnings} = await injectManifest({
* dontCacheBustURLsMatching: [new RegExp('...')],
* globDirectory: '...',
* globPatterns: ['...', '...'],
* maximumFileSizeToCacheInBytes: ...,
* swDest: '...',
* swSrc: '...',
* });
* ```
*
* @memberof workbox-build
*/
export declare function injectManifest(config: InjectManifestOptions): Promise<BuildResult>;

View File

@@ -0,0 +1,133 @@
"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 assert_1 = __importDefault(require("assert"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./lib/errors");
const escape_regexp_1 = require("./lib/escape-regexp");
const get_file_manifest_entries_1 = require("./lib/get-file-manifest-entries");
const get_source_map_url_1 = require("./lib/get-source-map-url");
const rebase_path_1 = require("./lib/rebase-path");
const replace_and_update_source_map_1 = require("./lib/replace-and-update-source-map");
const translate_url_to_sourcemap_paths_1 = require("./lib/translate-url-to-sourcemap-paths");
const validate_options_1 = require("./lib/validate-options");
/**
* This method creates a list of URLs to precache, referred to as a "precache
* manifest", based on the options you provide.
*
* The manifest is injected into the `swSrc` file, and the placeholder string
* `injectionPoint` determines where in the file the manifest should go.
*
* The final service worker file, with the manifest injected, is written to
* disk at `swDest`.
*
* This method will not compile or bundle your `swSrc` file; it just handles
* injecting the manifest.
*
* ```
* // The following lists some common options; see the rest of the documentation
* // for the full set of options and defaults.
* const {count, size, warnings} = await injectManifest({
* dontCacheBustURLsMatching: [new RegExp('...')],
* globDirectory: '...',
* globPatterns: ['...', '...'],
* maximumFileSizeToCacheInBytes: ...,
* swDest: '...',
* swSrc: '...',
* });
* ```
*
* @memberof workbox-build
*/
async function injectManifest(config) {
const options = (0, validate_options_1.validateInjectManifestOptions)(config);
// Make sure we leave swSrc and swDest out of the precache manifest.
for (const file of [options.swSrc, options.swDest]) {
options.globIgnores.push((0, rebase_path_1.rebasePath)({
file,
baseDirectory: options.globDirectory,
}));
}
const globalRegexp = new RegExp((0, escape_regexp_1.escapeRegExp)(options.injectionPoint), 'g');
const { count, size, manifestEntries, warnings } = await (0, get_file_manifest_entries_1.getFileManifestEntries)(options);
let swFileContents;
try {
swFileContents = await fs_extra_1.default.readFile(options.swSrc, 'utf8');
}
catch (error) {
throw new Error(`${errors_1.errors['invalid-sw-src']} ${error instanceof Error && error.message ? error.message : ''}`);
}
const injectionResults = swFileContents.match(globalRegexp);
// See https://github.com/GoogleChrome/workbox/issues/2230
const injectionPoint = options.injectionPoint ? options.injectionPoint : '';
if (!injectionResults) {
if (upath_1.default.resolve(options.swSrc) === upath_1.default.resolve(options.swDest)) {
throw new Error(`${errors_1.errors['same-src-and-dest']} ${injectionPoint}`);
}
throw new Error(`${errors_1.errors['injection-point-not-found']} ${injectionPoint}`);
}
(0, assert_1.default)(injectionResults.length === 1, `${errors_1.errors['multiple-injection-points']} ${injectionPoint}`);
const manifestString = (0, fast_json_stable_stringify_1.default)(manifestEntries);
const filesToWrite = {};
const url = (0, get_source_map_url_1.getSourceMapURL)(swFileContents);
// See https://github.com/GoogleChrome/workbox/issues/2957
const { destPath, srcPath, warning } = (0, translate_url_to_sourcemap_paths_1.translateURLToSourcemapPaths)(url, options.swSrc, options.swDest);
if (warning) {
warnings.push(warning);
}
// If our swSrc 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
// (assuming it's a real file, not a data: URL) at the same time.
// See https://github.com/GoogleChrome/workbox/issues/2235
// and https://github.com/GoogleChrome/workbox/issues/2648
if (srcPath && destPath) {
const originalMap = (await fs_extra_1.default.readJSON(srcPath, {
encoding: 'utf8',
}));
const { map, source } = await (0, replace_and_update_source_map_1.replaceAndUpdateSourceMap)({
originalMap,
jsFilename: upath_1.default.basename(options.swDest),
originalSource: swFileContents,
replaceString: manifestString,
searchString: options.injectionPoint,
});
filesToWrite[options.swDest] = source;
filesToWrite[destPath] = map;
}
else {
// If there's no sourcemap associated with swSrc, a simple string
// replacement will suffice.
filesToWrite[options.swDest] = swFileContents.replace(globalRegexp, manifestString);
}
for (const [file, contents] of Object.entries(filesToWrite)) {
try {
await fs_extra_1.default.mkdirp(upath_1.default.dirname(file));
}
catch (error) {
throw new Error(errors_1.errors['unable-to-make-sw-directory'] +
` '${error instanceof Error && error.message ? error.message : ''}'`);
}
await fs_extra_1.default.writeFile(file, contents);
}
return {
count,
size,
warnings,
// Use upath.resolve() to make all the paths absolute.
filePaths: Object.keys(filesToWrite).map((f) => upath_1.default.resolve(f)),
};
}
exports.injectManifest = injectManifest;

View File

@@ -0,0 +1,13 @@
import { ManifestEntry } from '../types';
type AdditionalManifestEntriesTransform = {
(manifest: Array<ManifestEntry & {
size: number;
}>): {
manifest: Array<ManifestEntry & {
size: number;
}>;
warnings: string[];
};
};
export declare function additionalManifestEntriesTransform(additionalManifestEntries: Array<ManifestEntry | string>): AdditionalManifestEntriesTransform;
export {};

View File

@@ -0,0 +1,47 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.additionalManifestEntriesTransform = void 0;
const errors_1 = require("./errors");
function additionalManifestEntriesTransform(additionalManifestEntries) {
return (manifest) => {
const warnings = [];
const stringEntries = new Set();
for (const additionalEntry of additionalManifestEntries) {
// Warn about either a string or an object that lacks a revision property.
// (An object with a revision property set to null is okay.)
if (typeof additionalEntry === 'string') {
stringEntries.add(additionalEntry);
manifest.push({
revision: null,
size: 0,
url: additionalEntry,
});
}
else {
if (additionalEntry && additionalEntry.revision === undefined) {
stringEntries.add(additionalEntry.url);
}
manifest.push(Object.assign({ size: 0 }, additionalEntry));
}
}
if (stringEntries.size > 0) {
let urls = '\n';
for (const stringEntry of stringEntries) {
urls += ` - ${stringEntry}\n`;
}
warnings.push(errors_1.errors['string-entry-warning'] + urls);
}
return {
manifest,
warnings,
};
};
}
exports.additionalManifestEntriesTransform = additionalManifestEntriesTransform;

View File

@@ -0,0 +1,9 @@
import { GeneratePartial, RequiredSWDestPartial } from '../types';
interface NameAndContents {
contents: string | Uint8Array;
name: string;
}
export declare function bundle({ babelPresetEnvTargets, inlineWorkboxRuntime, mode, sourcemap, swDest, unbundledCode, }: Omit<GeneratePartial, 'runtimeCaching'> & RequiredSWDestPartial & {
unbundledCode: string;
}): Promise<Array<NameAndContents>>;
export {};

123
frontend/node_modules/workbox-build/build/lib/bundle.js generated vendored Normal file
View File

@@ -0,0 +1,123 @@
"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.bundle = void 0;
const plugin_babel_1 = require("@rollup/plugin-babel");
const plugin_node_resolve_1 = require("@rollup/plugin-node-resolve");
const rollup_1 = require("rollup");
const rollup_plugin_terser_1 = require("rollup-plugin-terser");
const fs_extra_1 = require("fs-extra");
const rollup_plugin_off_main_thread_1 = __importDefault(require("@surma/rollup-plugin-off-main-thread"));
const preset_env_1 = __importDefault(require("@babel/preset-env"));
const plugin_replace_1 = __importDefault(require("@rollup/plugin-replace"));
const tempy_1 = __importDefault(require("tempy"));
const upath_1 = __importDefault(require("upath"));
async function bundle({ babelPresetEnvTargets, inlineWorkboxRuntime, mode, sourcemap, swDest, unbundledCode, }) {
// We need to write this to the "real" file system, as Rollup won't read from
// a custom file system.
const { dir, base } = upath_1.default.parse(swDest);
const temporaryFile = tempy_1.default.file({ name: base });
await (0, fs_extra_1.writeFile)(temporaryFile, unbundledCode);
const plugins = [
(0, plugin_node_resolve_1.nodeResolve)(),
(0, plugin_replace_1.default)({
// See https://github.com/GoogleChrome/workbox/issues/2769
'preventAssignment': true,
'process.env.NODE_ENV': JSON.stringify(mode),
}),
(0, plugin_babel_1.babel)({
babelHelpers: 'bundled',
// Disable the logic that checks for local Babel config files:
// https://github.com/GoogleChrome/workbox/issues/2111
babelrc: false,
configFile: false,
presets: [
[
preset_env_1.default,
{
targets: {
browsers: babelPresetEnvTargets,
},
loose: true,
},
],
],
}),
];
if (mode === 'production') {
plugins.push((0, rollup_plugin_terser_1.terser)({
mangle: {
toplevel: true,
properties: {
regex: /(^_|_$)/,
},
},
}));
}
const rollupConfig = {
plugins,
input: temporaryFile,
};
// Rollup will inline the runtime by default. If we don't want that, we need
// to add in some additional config.
if (!inlineWorkboxRuntime) {
// No lint for omt(), library has no types.
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
rollupConfig.plugins.unshift((0, rollup_plugin_off_main_thread_1.default)());
rollupConfig.manualChunks = (id) => {
return id.includes('workbox') ? 'workbox' : undefined;
};
}
const bundle = await (0, rollup_1.rollup)(rollupConfig);
const { output } = await bundle.generate({
sourcemap,
// Using an external Workbox runtime requires 'amd'.
format: inlineWorkboxRuntime ? 'es' : 'amd',
});
const files = [];
for (const chunkOrAsset of output) {
if (chunkOrAsset.type === 'asset') {
files.push({
name: chunkOrAsset.fileName,
contents: chunkOrAsset.source,
});
}
else {
let code = chunkOrAsset.code;
if (chunkOrAsset.map) {
const sourceMapFile = chunkOrAsset.fileName + '.map';
code += `//# sourceMappingURL=${sourceMapFile}\n`;
files.push({
name: sourceMapFile,
contents: chunkOrAsset.map.toString(),
});
}
files.push({
name: chunkOrAsset.fileName,
contents: code,
});
}
}
// Make sure that if there was a directory portion included in swDest, it's
// preprended to all of the generated files.
return files.map((file) => {
file.name = upath_1.default.format({
dir,
base: file.name,
ext: '',
name: '',
root: '',
});
return file;
});
}
exports.bundle = bundle;

View File

@@ -0,0 +1,2 @@
import { BuildType } from '../types';
export declare function getModuleURL(moduleName: string, buildType: BuildType): string;

View File

@@ -0,0 +1,57 @@
"use strict";
/*
Copyright 2021 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getModuleURL = void 0;
const assert_1 = require("assert");
const errors_1 = require("./errors");
const cdn = __importStar(require("../cdn-details.json"));
function getVersionedURL() {
return `${getCDNPrefix()}/${cdn.latestVersion}`;
}
function getCDNPrefix() {
return `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}`;
}
function getModuleURL(moduleName, buildType) {
(0, assert_1.ok)(moduleName, errors_1.errors['no-module-name']);
if (buildType) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pkgJson = require(`${moduleName}/package.json`);
if (buildType === 'dev' && pkgJson.workbox && pkgJson.workbox.prodOnly) {
// This is not due to a public-facing exception, so just throw an Error(),
// without creating an entry in errors.js.
throw Error(`The 'dev' build of ${moduleName} is not available.`);
}
return `${getVersionedURL()}/${moduleName}.${buildType.slice(0, 4)}.js`;
}
return `${getVersionedURL()}/${moduleName}.js`;
}
exports.getModuleURL = getModuleURL;

View File

@@ -0,0 +1,20 @@
/**
* This copies over a set of runtime libraries used by Workbox into a
* local directory, which should be deployed alongside your service worker file.
*
* As an alternative to deploying these local copies, you could instead use
* Workbox from its official CDN URL.
*
* This method is exposed for the benefit of developers using
* {@link workbox-build.injectManifest} who would
* prefer not to use the CDN copies of Workbox. Developers using
* {@link workbox-build.generateSW} don't need to
* explicitly call this method.
*
* @param {string} destDirectory The path to the parent directory under which
* the new directory of libraries will be created.
* @return {Promise<string>} The name of the newly created directory.
*
* @alias workbox-build.copyWorkboxLibraries
*/
export declare function copyWorkboxLibraries(destDirectory: string): Promise<string>;

View File

@@ -0,0 +1,69 @@
"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.copyWorkboxLibraries = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./errors");
// Used to filter the libraries to copy based on our package.json dependencies.
const WORKBOX_PREFIX = 'workbox-';
// The directory within each package containing the final bundles.
const BUILD_DIR = 'build';
/**
* This copies over a set of runtime libraries used by Workbox into a
* local directory, which should be deployed alongside your service worker file.
*
* As an alternative to deploying these local copies, you could instead use
* Workbox from its official CDN URL.
*
* This method is exposed for the benefit of developers using
* {@link workbox-build.injectManifest} who would
* prefer not to use the CDN copies of Workbox. Developers using
* {@link workbox-build.generateSW} don't need to
* explicitly call this method.
*
* @param {string} destDirectory The path to the parent directory under which
* the new directory of libraries will be created.
* @return {Promise<string>} The name of the newly created directory.
*
* @alias workbox-build.copyWorkboxLibraries
*/
async function copyWorkboxLibraries(destDirectory) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const thisPkg = require('../../package.json');
// Use the version string from workbox-build in the name of the parent
// directory. This should be safe, because lerna will bump workbox-build's
// pkg.version whenever one of the dependent libraries gets bumped, and we
// care about versioning the dependent libraries.
const workboxDirectoryName = `workbox-v${thisPkg.version ? thisPkg.version : ''}`;
const workboxDirectoryPath = upath_1.default.join(destDirectory, workboxDirectoryName);
await fs_extra_1.default.ensureDir(workboxDirectoryPath);
const copyPromises = [];
const librariesToCopy = Object.keys(thisPkg.dependencies || {}).filter((dependency) => dependency.startsWith(WORKBOX_PREFIX));
for (const library of librariesToCopy) {
// Get the path to the package on the user's filesystem by require-ing
// the package's `package.json` file via the node resolution algorithm.
const libraryPath = upath_1.default.dirname(require.resolve(`${library}/package.json`));
const buildPath = upath_1.default.join(libraryPath, BUILD_DIR);
// fse.copy() copies all the files in a directory, not the directory itself.
// See https://github.com/jprichardson/node-fs-extra/blob/master/docs/copy.md#copysrc-dest-options-callback
copyPromises.push(fs_extra_1.default.copy(buildPath, workboxDirectoryPath));
}
try {
await Promise.all(copyPromises);
return workboxDirectoryName;
}
catch (error) {
throw Error(`${errors_1.errors['unable-to-copy-workbox-libraries']} ${error instanceof Error ? error.toString() : ''}`);
}
}
exports.copyWorkboxLibraries = copyWorkboxLibraries;

View File

@@ -0,0 +1,61 @@
export declare const errors: {
'unable-to-get-rootdir': string;
'no-extension': string;
'invalid-file-manifest-name': string;
'unable-to-get-file-manifest-name': string;
'invalid-sw-dest': string;
'unable-to-get-sw-name': string;
'unable-to-get-save-config': string;
'unable-to-get-file-hash': string;
'unable-to-get-file-size': string;
'unable-to-glob-files': string;
'unable-to-make-manifest-directory': string;
'read-manifest-template-failure': string;
'populating-manifest-tmpl-failed': string;
'manifest-file-write-failure': string;
'unable-to-make-sw-directory': string;
'read-sw-template-failure': string;
'sw-write-failure': string;
'sw-write-failure-directory': string;
'unable-to-copy-workbox-libraries': string;
'invalid-generate-sw-input': string;
'invalid-glob-directory': string;
'invalid-dont-cache-bust': string;
'invalid-exclude-files': string;
'invalid-get-manifest-entries-input': string;
'invalid-manifest-path': string;
'invalid-manifest-entries': string;
'invalid-manifest-format': string;
'invalid-static-file-globs': string;
'invalid-templated-urls': string;
'templated-url-matches-glob': string;
'invalid-glob-ignores': string;
'manifest-entry-bad-url': string;
'modify-url-prefix-bad-prefixes': string;
'invalid-inject-manifest-arg': string;
'injection-point-not-found': string;
'multiple-injection-points': string;
'populating-sw-tmpl-failed': string;
'useless-glob-pattern': string;
'bad-template-urls-asset': string;
'invalid-runtime-caching': string;
'static-file-globs-deprecated': string;
'dynamic-url-deprecated': string;
'urlPattern-is-required': string;
'handler-is-required': string;
'invalid-generate-file-manifest-arg': string;
'invalid-sw-src': string;
'same-src-and-dest': string;
'only-regexp-routes-supported': string;
'bad-runtime-caching-config': string;
'invalid-network-timeout-seconds': string;
'no-module-name': string;
'bad-manifest-transforms-return-value': string;
'string-entry-warning': string;
'no-manifest-entries-or-runtime-caching': string;
'cant-find-sourcemap': string;
'nav-preload-runtime-caching': string;
'cache-name-required': string;
'manifest-transforms': string;
'invalid-handler-string': string;
};

125
frontend/node_modules/workbox-build/build/lib/errors.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
"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.errors = void 0;
const common_tags_1 = require("common-tags");
exports.errors = {
'unable-to-get-rootdir': `Unable to get the root directory of your web app.`,
'no-extension': (0, common_tags_1.oneLine) `Unable to detect a usable extension for a file in your web
app directory.`,
'invalid-file-manifest-name': (0, common_tags_1.oneLine) `The File Manifest Name must have at least one
character.`,
'unable-to-get-file-manifest-name': 'Unable to get a file manifest name.',
'invalid-sw-dest': `The 'swDest' value must be a valid path.`,
'unable-to-get-sw-name': 'Unable to get a service worker file name.',
'unable-to-get-save-config': (0, common_tags_1.oneLine) `An error occurred when asking to save details
in a config file.`,
'unable-to-get-file-hash': (0, common_tags_1.oneLine) `An error occurred when attempting to create a
file hash.`,
'unable-to-get-file-size': (0, common_tags_1.oneLine) `An error occurred when attempting to get a file
size.`,
'unable-to-glob-files': 'An error occurred when globbing for files.',
'unable-to-make-manifest-directory': (0, common_tags_1.oneLine) `Unable to make output directory for
file manifest.`,
'read-manifest-template-failure': 'Unable to read template for file manifest',
'populating-manifest-tmpl-failed': (0, common_tags_1.oneLine) `An error occurred when populating the
file manifest template.`,
'manifest-file-write-failure': 'Unable to write the file manifest.',
'unable-to-make-sw-directory': (0, common_tags_1.oneLine) `Unable to make the directories to output
the service worker path.`,
'read-sw-template-failure': (0, common_tags_1.oneLine) `Unable to read the service worker template
file.`,
'sw-write-failure': 'Unable to write the service worker file.',
'sw-write-failure-directory': (0, common_tags_1.oneLine) `Unable to write the service worker file;
'swDest' should be a full path to the file, not a path to a directory.`,
'unable-to-copy-workbox-libraries': (0, common_tags_1.oneLine) `One or more of the Workbox libraries
could not be copied over to the destination directory: `,
'invalid-generate-sw-input': (0, common_tags_1.oneLine) `The input to generateSW() must be an object.`,
'invalid-glob-directory': (0, common_tags_1.oneLine) `The supplied globDirectory must be a path as a
string.`,
'invalid-dont-cache-bust': (0, common_tags_1.oneLine) `The supplied 'dontCacheBustURLsMatching'
parameter must be a RegExp.`,
'invalid-exclude-files': 'The excluded files should be an array of strings.',
'invalid-get-manifest-entries-input': (0, common_tags_1.oneLine) `The input to
'getFileManifestEntries()' must be an object.`,
'invalid-manifest-path': (0, common_tags_1.oneLine) `The supplied manifest path is not a string with
at least one character.`,
'invalid-manifest-entries': (0, common_tags_1.oneLine) `The manifest entries must be an array of
strings or JavaScript objects containing a url parameter.`,
'invalid-manifest-format': (0, common_tags_1.oneLine) `The value of the 'format' option passed to
generateFileManifest() must be either 'iife' (the default) or 'es'.`,
'invalid-static-file-globs': (0, common_tags_1.oneLine) `The 'globPatterns' value must be an array
of strings.`,
'invalid-templated-urls': (0, common_tags_1.oneLine) `The 'templatedURLs' value should be an object
that maps URLs to either a string, or to an array of glob patterns.`,
'templated-url-matches-glob': (0, common_tags_1.oneLine) `One of the 'templatedURLs' URLs is already
being tracked via 'globPatterns': `,
'invalid-glob-ignores': (0, common_tags_1.oneLine) `The 'globIgnores' parameter must be an array of
glob pattern strings.`,
'manifest-entry-bad-url': (0, common_tags_1.oneLine) `The generated manifest contains an entry without
a URL string. This is likely an error with workbox-build.`,
'modify-url-prefix-bad-prefixes': (0, common_tags_1.oneLine) `The 'modifyURLPrefix' parameter must be
an object with string key value pairs.`,
'invalid-inject-manifest-arg': (0, common_tags_1.oneLine) `The input to 'injectManifest()' must be an
object.`,
'injection-point-not-found': (0, common_tags_1.oneLine) `Unable to find a place to inject the manifest.
Please ensure that your service worker file contains the following: `,
'multiple-injection-points': (0, common_tags_1.oneLine) `Please ensure that your 'swSrc' file contains
only one match for the following: `,
'populating-sw-tmpl-failed': (0, common_tags_1.oneLine) `Unable to generate service worker from
template.`,
'useless-glob-pattern': (0, common_tags_1.oneLine) `One of the glob patterns doesn't match any files.
Please remove or fix the following: `,
'bad-template-urls-asset': (0, common_tags_1.oneLine) `There was an issue using one of the provided
'templatedURLs'.`,
'invalid-runtime-caching': (0, common_tags_1.oneLine) `The 'runtimeCaching' parameter must an an
array of objects with at least a 'urlPattern' and 'handler'.`,
'static-file-globs-deprecated': (0, common_tags_1.oneLine) `'staticFileGlobs' is deprecated.
Please use 'globPatterns' instead.`,
'dynamic-url-deprecated': (0, common_tags_1.oneLine) `'dynamicURLToDependencies' is deprecated.
Please use 'templatedURLs' instead.`,
'urlPattern-is-required': (0, common_tags_1.oneLine) `The 'urlPattern' option is required when using
'runtimeCaching'.`,
'handler-is-required': (0, common_tags_1.oneLine) `The 'handler' option is required when using
runtimeCaching.`,
'invalid-generate-file-manifest-arg': (0, common_tags_1.oneLine) `The input to generateFileManifest()
must be an Object.`,
'invalid-sw-src': `The 'swSrc' file can't be read.`,
'same-src-and-dest': (0, common_tags_1.oneLine) `Unable to find a place to inject the manifest. This is
likely because swSrc and swDest are configured to the same file.
Please ensure that your swSrc file contains the following:`,
'only-regexp-routes-supported': (0, common_tags_1.oneLine) `Please use a regular expression object as
the urlPattern parameter. (Express-style routes are not currently
supported.)`,
'bad-runtime-caching-config': (0, common_tags_1.oneLine) `An unknown configuration option was used
with runtimeCaching: `,
'invalid-network-timeout-seconds': (0, common_tags_1.oneLine) `When using networkTimeoutSeconds, you
must set the handler to 'NetworkFirst'.`,
'no-module-name': (0, common_tags_1.oneLine) `You must provide a moduleName parameter when calling
getModuleURL().`,
'bad-manifest-transforms-return-value': (0, common_tags_1.oneLine) `The return value from a
manifestTransform should be an object with 'manifest' and optionally
'warnings' properties.`,
'string-entry-warning': (0, common_tags_1.oneLine) `Some items were passed to additionalManifestEntries
without revisioning info. This is generally NOT safe. Learn more at
https://bit.ly/wb-precache.`,
'no-manifest-entries-or-runtime-caching': (0, common_tags_1.oneLine) `Couldn't find configuration for
either precaching or runtime caching. Please ensure that the various glob
options are set to match one or more files, and/or configure the
runtimeCaching option.`,
'cant-find-sourcemap': (0, common_tags_1.oneLine) `The swSrc file refers to a sourcemap that can't be
opened:`,
'nav-preload-runtime-caching': (0, common_tags_1.oneLine) `When using navigationPreload, you must also
configure a runtimeCaching route that will use the preloaded response.`,
'cache-name-required': (0, common_tags_1.oneLine) `When using cache expiration, you must also
configure a custom cacheName.`,
'manifest-transforms': (0, common_tags_1.oneLine) `When using manifestTransforms, you must provide
an array of functions.`,
'invalid-handler-string': (0, common_tags_1.oneLine) `The handler name provided is not valid: `,
};

View File

@@ -0,0 +1 @@
export declare function escapeRegExp(str: string): string;

View File

@@ -0,0 +1,15 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.escapeRegExp = void 0;
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
exports.escapeRegExp = escapeRegExp;

View File

@@ -0,0 +1,2 @@
import { FileDetails } from '../types';
export declare function getCompositeDetails(compositeURL: string, dependencyDetails: Array<FileDetails>): FileDetails;

View File

@@ -0,0 +1,31 @@
"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.getCompositeDetails = void 0;
const crypto_1 = __importDefault(require("crypto"));
function getCompositeDetails(compositeURL, dependencyDetails) {
let totalSize = 0;
let compositeHash = '';
for (const fileDetails of dependencyDetails) {
totalSize += fileDetails.size;
compositeHash += fileDetails.hash;
}
const md5 = crypto_1.default.createHash('md5');
md5.update(compositeHash);
const hashOfHashes = md5.digest('hex');
return {
file: compositeURL,
hash: hashOfHashes,
size: totalSize,
};
}
exports.getCompositeDetails = getCompositeDetails;

View File

@@ -0,0 +1,14 @@
import { GlobPartial } from '../types';
interface FileDetails {
file: string;
hash: string;
size: number;
}
export declare function getFileDetails({ globDirectory, globFollow, globIgnores, globPattern, globStrict, }: Omit<GlobPartial, 'globDirectory' | 'globPatterns' | 'templatedURLs'> & {
globDirectory: string;
globPattern: string;
}): {
globbedFileDetails: Array<FileDetails>;
warning: string;
};
export {};

View File

@@ -0,0 +1,55 @@
"use strict";
/*
Copyright 2021 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.getFileDetails = void 0;
const glob_1 = __importDefault(require("glob"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./errors");
const get_file_size_1 = require("./get-file-size");
const get_file_hash_1 = require("./get-file-hash");
function getFileDetails({ globDirectory, globFollow, globIgnores, globPattern, globStrict, }) {
let globbedFiles;
let warning = '';
try {
globbedFiles = glob_1.default.sync(globPattern, {
cwd: globDirectory,
follow: globFollow,
ignore: globIgnores,
strict: globStrict,
});
}
catch (err) {
throw new Error(errors_1.errors['unable-to-glob-files'] +
` '${err instanceof Error && err.message ? err.message : ''}'`);
}
if (globbedFiles.length === 0) {
warning =
errors_1.errors['useless-glob-pattern'] +
' ' +
JSON.stringify({ globDirectory, globPattern, globIgnores }, null, 2);
}
const globbedFileDetails = [];
for (const file of globbedFiles) {
const fullPath = upath_1.default.join(globDirectory, file);
const fileSize = (0, get_file_size_1.getFileSize)(fullPath);
if (fileSize !== null) {
const fileHash = (0, get_file_hash_1.getFileHash)(fullPath);
globbedFileDetails.push({
file: `${upath_1.default.relative(globDirectory, fullPath)}`,
hash: fileHash,
size: fileSize,
});
}
}
return { globbedFileDetails, warning };
}
exports.getFileDetails = getFileDetails;

View File

@@ -0,0 +1 @@
export declare function getFileHash(file: string): string;

View File

@@ -0,0 +1,27 @@
"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.getFileHash = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const get_string_hash_1 = require("./get-string-hash");
const errors_1 = require("./errors");
function getFileHash(file) {
try {
const buffer = fs_extra_1.default.readFileSync(file);
return (0, get_string_hash_1.getStringHash)(buffer);
}
catch (err) {
throw new Error(errors_1.errors['unable-to-get-file-hash'] +
` '${err instanceof Error && err.message ? err.message : ''}'`);
}
}
exports.getFileHash = getFileHash;

View File

@@ -0,0 +1,2 @@
import { GetManifestResult, GetManifestOptions } from '../types';
export declare function getFileManifestEntries({ additionalManifestEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns, globStrict, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, }: GetManifestOptions): Promise<GetManifestResult>;

View File

@@ -0,0 +1,98 @@
"use strict";
/*
Copyright 2021 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.getFileManifestEntries = void 0;
const assert_1 = __importDefault(require("assert"));
const errors_1 = require("./errors");
const get_composite_details_1 = require("./get-composite-details");
const get_file_details_1 = require("./get-file-details");
const get_string_details_1 = require("./get-string-details");
const transform_manifest_1 = require("./transform-manifest");
async function getFileManifestEntries({ additionalManifestEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns = [], globStrict, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, }) {
const warnings = [];
const allFileDetails = new Map();
try {
for (const globPattern of globPatterns) {
const { globbedFileDetails, warning } = (0, get_file_details_1.getFileDetails)({
globDirectory,
globFollow,
globIgnores,
globPattern,
globStrict,
});
if (warning) {
warnings.push(warning);
}
for (const details of globbedFileDetails) {
if (details && !allFileDetails.has(details.file)) {
allFileDetails.set(details.file, details);
}
}
}
}
catch (error) {
// If there's an exception thrown while globbing, then report
// it back as a warning, and don't consider it fatal.
if (error instanceof Error && error.message) {
warnings.push(error.message);
}
}
if (templatedURLs) {
for (const url of Object.keys(templatedURLs)) {
(0, assert_1.default)(!allFileDetails.has(url), errors_1.errors['templated-url-matches-glob']);
const dependencies = templatedURLs[url];
if (Array.isArray(dependencies)) {
const details = dependencies.reduce((previous, globPattern) => {
try {
const { globbedFileDetails, warning } = (0, get_file_details_1.getFileDetails)({
globDirectory,
globFollow,
globIgnores,
globPattern,
globStrict,
});
if (warning) {
warnings.push(warning);
}
return previous.concat(globbedFileDetails);
}
catch (error) {
const debugObj = {};
debugObj[url] = dependencies;
throw new Error(`${errors_1.errors['bad-template-urls-asset']} ` +
`'${globPattern}' from '${JSON.stringify(debugObj)}':\n` +
`${error instanceof Error ? error.toString() : ''}`);
}
}, []);
if (details.length === 0) {
throw new Error(`${errors_1.errors['bad-template-urls-asset']} The glob ` +
`pattern '${dependencies.toString()}' did not match anything.`);
}
allFileDetails.set(url, (0, get_composite_details_1.getCompositeDetails)(url, details));
}
else if (typeof dependencies === 'string') {
allFileDetails.set(url, (0, get_string_details_1.getStringDetails)(url, dependencies));
}
}
}
const transformedManifest = await (0, transform_manifest_1.transformManifest)({
additionalManifestEntries,
dontCacheBustURLsMatching,
manifestTransforms,
maximumFileSizeToCacheInBytes,
modifyURLPrefix,
fileDetails: Array.from(allFileDetails.values()),
});
transformedManifest.warnings.push(...warnings);
return transformedManifest;
}
exports.getFileManifestEntries = getFileManifestEntries;

View File

@@ -0,0 +1 @@
export declare function getFileSize(file: string): number | null;

View File

@@ -0,0 +1,29 @@
"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.getFileSize = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const errors_1 = require("./errors");
function getFileSize(file) {
try {
const stat = fs_extra_1.default.statSync(file);
if (!stat.isFile()) {
return null;
}
return stat.size;
}
catch (err) {
throw new Error(errors_1.errors['unable-to-get-file-size'] +
` '${err instanceof Error && err.message ? err.message : ''}'`);
}
}
exports.getFileSize = getFileSize;

View File

@@ -0,0 +1 @@
export declare function getSourceMapURL(srcContents: string): string | null;

View File

@@ -0,0 +1,32 @@
"use strict";
/*
Copyright 2022 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.getSourceMapURL = void 0;
// Adapted from https://github.com/lydell/source-map-url/blob/master/source-map-url.js
// See https://github.com/GoogleChrome/workbox/issues/3019
const innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/;
const regex = RegExp('(?:' +
'/\\*' +
'(?:\\s*\r?\n(?://)?)?' +
'(?:' +
innerRegex.source +
')' +
'\\s*' +
'\\*/' +
'|' +
'//(?:' +
innerRegex.source +
')' +
')' +
'\\s*');
function getSourceMapURL(srcContents) {
const match = srcContents.match(regex);
return match ? match[1] || match[2] || '' : null;
}
exports.getSourceMapURL = getSourceMapURL;

View File

@@ -0,0 +1,2 @@
import { FileDetails } from '../types';
export declare function getStringDetails(url: string, str: string): FileDetails;

View File

@@ -0,0 +1,19 @@
"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.getStringDetails = void 0;
const get_string_hash_1 = require("./get-string-hash");
function getStringDetails(url, str) {
return {
file: url,
hash: (0, get_string_hash_1.getStringHash)(str),
size: str.length,
};
}
exports.getStringDetails = getStringDetails;

View File

@@ -0,0 +1,3 @@
/// <reference types="node" />
import crypto from 'crypto';
export declare function getStringHash(input: crypto.BinaryLike): string;

View File

@@ -0,0 +1,20 @@
"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.getStringHash = void 0;
const crypto_1 = __importDefault(require("crypto"));
function getStringHash(input) {
const md5 = crypto_1.default.createHash('md5');
md5.update(input);
return md5.digest('hex');
}
exports.getStringHash = getStringHash;

View File

@@ -0,0 +1,2 @@
import { ManifestTransform } from '../types';
export declare function maximumSizeTransform(maximumFileSizeToCacheInBytes: number): ManifestTransform;

View File

@@ -0,0 +1,30 @@
"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.maximumSizeTransform = void 0;
const pretty_bytes_1 = __importDefault(require("pretty-bytes"));
function maximumSizeTransform(maximumFileSizeToCacheInBytes) {
return (originalManifest) => {
const warnings = [];
const manifest = originalManifest.filter((entry) => {
if (entry.size <= maximumFileSizeToCacheInBytes) {
return true;
}
warnings.push(`${entry.url} is ${(0, pretty_bytes_1.default)(entry.size)}, and won't ` +
`be precached. Configure maximumFileSizeToCacheInBytes to change ` +
`this limit.`);
return false;
});
return { manifest, warnings };
};
}
exports.maximumSizeTransform = maximumSizeTransform;

View File

@@ -0,0 +1,4 @@
import { ManifestTransform } from '../types';
export declare function modifyURLPrefixTransform(modifyURLPrefix: {
[key: string]: string;
}): ManifestTransform;

View File

@@ -0,0 +1,51 @@
"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.modifyURLPrefixTransform = void 0;
const errors_1 = require("./errors");
const escape_regexp_1 = require("./escape-regexp");
function modifyURLPrefixTransform(modifyURLPrefix) {
if (!modifyURLPrefix ||
typeof modifyURLPrefix !== 'object' ||
Array.isArray(modifyURLPrefix)) {
throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']);
}
// If there are no entries in modifyURLPrefix, just return an identity
// function as a shortcut.
if (Object.keys(modifyURLPrefix).length === 0) {
return (manifest) => {
return { manifest };
};
}
for (const key of Object.keys(modifyURLPrefix)) {
if (typeof modifyURLPrefix[key] !== 'string') {
throw new Error(errors_1.errors['modify-url-prefix-bad-prefixes']);
}
}
// Escape the user input so it's safe to use in a regex.
const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escape_regexp_1.escapeRegExp);
// Join all the `modifyURLPrefix` keys so a single regex can be used.
const prefixMatchesStrings = safeModifyURLPrefixes.join('|');
// Add `^` to the front the prefix matches so it only matches the start of
// a string.
const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`);
return (originalManifest) => {
const manifest = originalManifest.map((entry) => {
if (typeof entry.url !== 'string') {
throw new Error(errors_1.errors['manifest-entry-bad-url']);
}
entry.url = entry.url.replace(modifyRegex, (match) => {
return modifyURLPrefix[match];
});
return entry;
});
return { manifest };
};
}
exports.modifyURLPrefixTransform = modifyURLPrefixTransform;

View File

@@ -0,0 +1,33 @@
/**
* Class for keeping track of which Workbox modules are used by the generated
* service worker script.
*
* @private
*/
export declare class ModuleRegistry {
private readonly _modulesUsed;
/**
* @private
*/
constructor();
/**
* @return {Array<string>} A list of all of the import statements that are
* needed for the modules being used.
* @private
*/
getImportStatements(): Array<string>;
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
getLocalName(pkg: string, moduleName: string): string;
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
use(pkg: string, moduleName: string): string;
}

View File

@@ -0,0 +1,70 @@
"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.ModuleRegistry = void 0;
const common_tags_1 = require("common-tags");
const upath_1 = __importDefault(require("upath"));
/**
* Class for keeping track of which Workbox modules are used by the generated
* service worker script.
*
* @private
*/
class ModuleRegistry {
/**
* @private
*/
constructor() {
this._modulesUsed = new Map();
}
/**
* @return {Array<string>} A list of all of the import statements that are
* needed for the modules being used.
* @private
*/
getImportStatements() {
const workboxModuleImports = [];
for (const [localName, { moduleName, pkg }] of this._modulesUsed) {
// By default require.resolve returns the resolved path of the 'main'
// field, which might be deeper than the package root. To work around
// this, we can find the package's root by resolving its package.json and
// strip the '/package.json' from the resolved path.
const pkgJsonPath = require.resolve(`${pkg}/package.json`);
const pkgRoot = upath_1.default.dirname(pkgJsonPath);
const importStatement = (0, common_tags_1.oneLine) `import {${moduleName} as ${localName}} from
'${pkgRoot}/${moduleName}.mjs';`;
workboxModuleImports.push(importStatement);
}
return workboxModuleImports;
}
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
getLocalName(pkg, moduleName) {
return `${pkg.replace(/-/g, '_')}_${moduleName}`;
}
/**
* @param {string} pkg The workbox package that the module belongs to.
* @param {string} moduleName The name of the module to import.
* @return {string} The local variable name that corresponds to that module.
* @private
*/
use(pkg, moduleName) {
const localName = this.getLocalName(pkg, moduleName);
this._modulesUsed.set(localName, { moduleName, pkg });
return localName;
}
}
exports.ModuleRegistry = ModuleRegistry;

View File

@@ -0,0 +1,2 @@
import { ManifestTransform } from '../types';
export declare function noRevisionForURLsMatchingTransform(regexp: RegExp): ManifestTransform;

View File

@@ -0,0 +1,29 @@
"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.noRevisionForURLsMatchingTransform = void 0;
const errors_1 = require("./errors");
function noRevisionForURLsMatchingTransform(regexp) {
if (!(regexp instanceof RegExp)) {
throw new Error(errors_1.errors['invalid-dont-cache-bust']);
}
return (originalManifest) => {
const manifest = originalManifest.map((entry) => {
if (typeof entry.url !== 'string') {
throw new Error(errors_1.errors['manifest-entry-bad-url']);
}
if (entry.url.match(regexp)) {
entry.revision = null;
}
return entry;
});
return { manifest };
};
}
exports.noRevisionForURLsMatchingTransform = noRevisionForURLsMatchingTransform;

View File

@@ -0,0 +1,4 @@
import { GeneratePartial, ManifestEntry } from '../types';
export declare function populateSWTemplate({ cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, }: GeneratePartial & {
manifestEntries?: Array<ManifestEntry>;
}): string;

View File

@@ -0,0 +1,79 @@
"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.populateSWTemplate = void 0;
const template_1 = __importDefault(require("lodash/template"));
const errors_1 = require("./errors");
const module_registry_1 = require("./module-registry");
const runtime_caching_converter_1 = require("./runtime-caching-converter");
const stringify_without_comments_1 = require("./stringify-without-comments");
const sw_template_1 = require("../templates/sw-template");
function populateSWTemplate({ cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, manifestEntries = [], navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching = [], skipWaiting, }) {
// There needs to be at least something to precache, or else runtime caching.
if (!((manifestEntries === null || manifestEntries === void 0 ? void 0 : manifestEntries.length) > 0 || runtimeCaching.length > 0)) {
throw new Error(errors_1.errors['no-manifest-entries-or-runtime-caching']);
}
// These are all options that can be passed to the precacheAndRoute() method.
const precacheOptions = {
directoryIndex,
// An array of RegExp objects can't be serialized by JSON.stringify()'s
// default behavior, so if it's given, convert it manually.
ignoreURLParametersMatching: ignoreURLParametersMatching
? []
: undefined,
};
let precacheOptionsString = JSON.stringify(precacheOptions, null, 2);
if (ignoreURLParametersMatching) {
precacheOptionsString = precacheOptionsString.replace(`"ignoreURLParametersMatching": []`, `"ignoreURLParametersMatching": [` +
`${ignoreURLParametersMatching.join(', ')}]`);
}
let offlineAnalyticsConfigString = undefined;
if (offlineGoogleAnalytics) {
// If offlineGoogleAnalytics is a truthy value, we need to convert it to the
// format expected by the template.
offlineAnalyticsConfigString =
offlineGoogleAnalytics === true
? // If it's the literal value true, then use an empty config string.
'{}'
: // Otherwise, convert the config object into a more complex string, taking
// into account the fact that functions might need to be stringified.
(0, stringify_without_comments_1.stringifyWithoutComments)(offlineGoogleAnalytics);
}
const moduleRegistry = new module_registry_1.ModuleRegistry();
try {
const populatedTemplate = (0, template_1.default)(sw_template_1.swTemplate)({
cacheId,
cleanupOutdatedCaches,
clientsClaim,
disableDevLogs,
importScripts,
manifestEntries,
navigateFallback,
navigateFallbackDenylist,
navigateFallbackAllowlist,
navigationPreload,
offlineAnalyticsConfigString,
precacheOptionsString,
runtimeCaching: (0, runtime_caching_converter_1.runtimeCachingConverter)(moduleRegistry, runtimeCaching),
skipWaiting,
use: moduleRegistry.use.bind(moduleRegistry),
});
const workboxImportStatements = moduleRegistry.getImportStatements();
// We need the import statements for all of the Workbox runtime modules
// prepended, so that the correct bundle can be created.
return workboxImportStatements.join('\n') + populatedTemplate;
}
catch (error) {
throw new Error(`${errors_1.errors['populating-sw-tmpl-failed']} '${error instanceof Error && error.message ? error.message : ''}'`);
}
}
exports.populateSWTemplate = populateSWTemplate;

View File

@@ -0,0 +1,4 @@
export declare function rebasePath({ baseDirectory, file, }: {
baseDirectory: string;
file: string;
}): string;

View File

@@ -0,0 +1,24 @@
"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.rebasePath = void 0;
const upath_1 = __importDefault(require("upath"));
function rebasePath({ baseDirectory, file, }) {
// The initial path is relative to the current directory, so make it absolute.
const absolutePath = upath_1.default.resolve(file);
// Convert the absolute path so that it's relative to the baseDirectory.
const relativePath = upath_1.default.relative(baseDirectory, absolutePath);
// Remove any leading ./ as it won't work in a glob pattern.
const normalizedPath = upath_1.default.normalize(relativePath);
return normalizedPath;
}
exports.rebasePath = rebasePath;

View File

@@ -0,0 +1,30 @@
import { RawSourceMap } from 'source-map';
/**
* Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern
* JavaScript updates, along with additional properties copied from originalMap.
*
* @param {Object} options
* @param {string} options.jsFilename The name for the file whose contents
* correspond to originalSource.
* @param {Object} options.originalMap The sourcemap for originalSource,
* prior to any replacements.
* @param {string} options.originalSource The source code, prior to any
* replacements.
* @param {string} options.replaceString A string to swap in for searchString.
* @param {string} options.searchString A string in originalSource to replace.
* Only the first occurrence will be replaced.
* @return {{source: string, map: string}} An object containing both
* originalSource with the replacement applied, and the modified originalMap.
*
* @private
*/
export declare function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString, }: {
jsFilename: string;
originalMap: RawSourceMap;
originalSource: string;
replaceString: string;
searchString: string;
}): Promise<{
map: string;
source: string;
}>;

View File

@@ -0,0 +1,98 @@
"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.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.replaceAndUpdateSourceMap = void 0;
const source_map_1 = require("source-map");
/**
* Adapted from https://github.com/nsams/sourcemap-aware-replace, with modern
* JavaScript updates, along with additional properties copied from originalMap.
*
* @param {Object} options
* @param {string} options.jsFilename The name for the file whose contents
* correspond to originalSource.
* @param {Object} options.originalMap The sourcemap for originalSource,
* prior to any replacements.
* @param {string} options.originalSource The source code, prior to any
* replacements.
* @param {string} options.replaceString A string to swap in for searchString.
* @param {string} options.searchString A string in originalSource to replace.
* Only the first occurrence will be replaced.
* @return {{source: string, map: string}} An object containing both
* originalSource with the replacement applied, and the modified originalMap.
*
* @private
*/
async function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString, }) {
const generator = new source_map_1.SourceMapGenerator({
file: jsFilename,
});
const consumer = await new source_map_1.SourceMapConsumer(originalMap);
let pos;
let src = originalSource;
const replacements = [];
let lineNum = 0;
let filePos = 0;
const lines = src.split('\n');
for (let line of lines) {
lineNum++;
let searchPos = 0;
while ((pos = line.indexOf(searchString, searchPos)) !== -1) {
src =
src.substring(0, filePos + pos) +
replaceString +
src.substring(filePos + pos + searchString.length);
line =
line.substring(0, pos) +
replaceString +
line.substring(pos + searchString.length);
replacements.push({ line: lineNum, column: pos });
searchPos = pos + replaceString.length;
}
filePos += line.length + 1;
}
replacements.reverse();
consumer.eachMapping((mapping) => {
for (const replacement of replacements) {
if (replacement.line === mapping.generatedLine &&
mapping.generatedColumn > replacement.column) {
const offset = searchString.length - replaceString.length;
mapping.generatedColumn -= offset;
}
}
if (mapping.source) {
const newMapping = {
generated: {
line: mapping.generatedLine,
column: mapping.generatedColumn,
},
original: {
line: mapping.originalLine,
column: mapping.originalColumn,
},
source: mapping.source,
};
return generator.addMapping(newMapping);
}
return mapping;
});
consumer.destroy();
// JSON.parse returns any.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const updatedSourceMap = Object.assign(JSON.parse(generator.toString()), {
names: originalMap.names,
sourceRoot: originalMap.sourceRoot,
sources: originalMap.sources,
sourcesContent: originalMap.sourcesContent,
});
return {
map: JSON.stringify(updatedSourceMap),
source: src,
};
}
exports.replaceAndUpdateSourceMap = replaceAndUpdateSourceMap;

View File

@@ -0,0 +1,3 @@
import { ModuleRegistry } from './module-registry';
import { RuntimeCaching } from '../types';
export declare function runtimeCachingConverter(moduleRegistry: ModuleRegistry, runtimeCaching: Array<RuntimeCaching>): Array<string>;

View File

@@ -0,0 +1,142 @@
"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.runtimeCachingConverter = void 0;
const common_tags_1 = require("common-tags");
const errors_1 = require("./errors");
const stringify_without_comments_1 = require("./stringify-without-comments");
/**
* Given a set of options that configures runtime caching behavior, convert it
* to the equivalent Workbox method calls.
*
* @param {ModuleRegistry} moduleRegistry
* @param {Object} options See
* https://developers.google.com/web/tools/workbox/modules/workbox-build#generateSW-runtimeCaching
* @return {string} A JSON string representing the equivalent options.
*
* @private
*/
function getOptionsString(moduleRegistry, options = {}) {
const plugins = [];
const handlerOptions = {};
for (const optionName of Object.keys(options)) {
if (options[optionName] === undefined) {
continue;
}
switch (optionName) {
// Using a library here because JSON.stringify won't handle functions.
case 'plugins': {
plugins.push(...options.plugins.map(stringify_without_comments_1.stringifyWithoutComments));
break;
}
// These are the option properties that we want to pull out, so that
// they're passed to the handler constructor.
case 'cacheName':
case 'networkTimeoutSeconds':
case 'fetchOptions':
case 'matchOptions': {
handlerOptions[optionName] = options[optionName];
break;
}
// The following cases are all shorthands for creating a plugin with a
// given configuration.
case 'backgroundSync': {
const name = options.backgroundSync.name;
const plugin = moduleRegistry.use('workbox-background-sync', 'BackgroundSyncPlugin');
let pluginCode = `new ${plugin}(${JSON.stringify(name)}`;
if (options.backgroundSync.options) {
pluginCode += `, ${(0, stringify_without_comments_1.stringifyWithoutComments)(options.backgroundSync.options)}`;
}
pluginCode += `)`;
plugins.push(pluginCode);
break;
}
case 'broadcastUpdate': {
const channelName = options.broadcastUpdate.channelName;
const opts = Object.assign({ channelName }, options.broadcastUpdate.options);
const plugin = moduleRegistry.use('workbox-broadcast-update', 'BroadcastUpdatePlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(opts)})`);
break;
}
case 'cacheableResponse': {
const plugin = moduleRegistry.use('workbox-cacheable-response', 'CacheableResponsePlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.cacheableResponse)})`);
break;
}
case 'expiration': {
const plugin = moduleRegistry.use('workbox-expiration', 'ExpirationPlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.expiration)})`);
break;
}
case 'precacheFallback': {
const plugin = moduleRegistry.use('workbox-precaching', 'PrecacheFallbackPlugin');
plugins.push(`new ${plugin}(${(0, stringify_without_comments_1.stringifyWithoutComments)(options.precacheFallback)})`);
break;
}
case 'rangeRequests': {
const plugin = moduleRegistry.use('workbox-range-requests', 'RangeRequestsPlugin');
// There are no configuration options for the constructor.
plugins.push(`new ${plugin}()`);
break;
}
default: {
throw new Error(
// In the default case optionName is typed as 'never'.
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
`${errors_1.errors['bad-runtime-caching-config']} ${optionName}`);
}
}
}
if (Object.keys(handlerOptions).length > 0 || plugins.length > 0) {
const optionsString = JSON.stringify(handlerOptions).slice(1, -1);
return (0, common_tags_1.oneLine) `{
${optionsString ? optionsString + ',' : ''}
plugins: [${plugins.join(', ')}]
}`;
}
else {
return '';
}
}
function runtimeCachingConverter(moduleRegistry, runtimeCaching) {
return runtimeCaching
.map((entry) => {
const method = entry.method || 'GET';
if (!entry.urlPattern) {
throw new Error(errors_1.errors['urlPattern-is-required']);
}
if (!entry.handler) {
throw new Error(errors_1.errors['handler-is-required']);
}
if (entry.options &&
entry.options.networkTimeoutSeconds &&
entry.handler !== 'NetworkFirst') {
throw new Error(errors_1.errors['invalid-network-timeout-seconds']);
}
// urlPattern might be a string, a RegExp object, or a function.
// If it's a string, it needs to be quoted.
const matcher = typeof entry.urlPattern === 'string'
? JSON.stringify(entry.urlPattern)
: entry.urlPattern;
const registerRoute = moduleRegistry.use('workbox-routing', 'registerRoute');
if (typeof entry.handler === 'string') {
const optionsString = getOptionsString(moduleRegistry, entry.options);
const handler = moduleRegistry.use('workbox-strategies', entry.handler);
const strategyString = `new ${handler}(${optionsString})`;
return `${registerRoute}(${matcher.toString()}, ${strategyString}, '${method}');\n`;
}
else if (typeof entry.handler === 'function') {
return `${registerRoute}(${matcher.toString()}, ${entry.handler.toString()}, '${method}');\n`;
}
// '' will be filtered out.
return '';
})
.filter((entry) => Boolean(entry));
}
exports.runtimeCachingConverter = runtimeCachingConverter;

View File

@@ -0,0 +1,3 @@
export declare function stringifyWithoutComments(obj: {
[key: string]: any;
}): string;

View File

@@ -0,0 +1,28 @@
"use strict";
/*
Copyright 2021 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.stringifyWithoutComments = void 0;
const stringify_object_1 = __importDefault(require("stringify-object"));
const strip_comments_1 = __importDefault(require("strip-comments"));
function stringifyWithoutComments(obj) {
return (0, stringify_object_1.default)(obj, {
// See https://github.com/yeoman/stringify-object#transformobject-property-originalresult
transform: (_obj, _prop, str) => {
if (typeof _prop !== 'symbol' && typeof _obj[_prop] === 'function') {
// Can't typify correctly stripComments
return (0, strip_comments_1.default)(str); // eslint-disable-line
}
return str;
},
});
}
exports.stringifyWithoutComments = stringifyWithoutComments;

View File

@@ -0,0 +1,63 @@
import { BasePartial, FileDetails, ManifestEntry } from '../types';
/**
* A `ManifestTransform` function can be used to modify the modify the `url` or
* `revision` properties of some or all of the
* {@link workbox-build.ManifestEntry} in the manifest.
*
* Deleting the `revision` property of an entry will cause
* the corresponding `url` to be precached without cache-busting parameters
* applied, which is to say, it implies that the URL itself contains
* proper versioning info. If the `revision` property is present, it must be
* set to a string.
*
* @example A transformation that prepended the origin of a CDN for any
* URL starting with '/assets/' could be implemented as:
*
* const cdnTransform = async (manifestEntries) => {
* const manifest = manifestEntries.map(entry => {
* const cdnOrigin = 'https://example.com';
* if (entry.url.startsWith('/assets/')) {
* entry.url = cdnOrigin + entry.url;
* }
* return entry;
* });
* return {manifest, warnings: []};
* };
*
* @example A transformation that nulls the revision field when the
* URL contains an 8-character hash surrounded by '.', indicating that it
* already contains revision information:
*
* const removeRevisionTransform = async (manifestEntries) => {
* const manifest = manifestEntries.map(entry => {
* const hashRegExp = /\.\w{8}\./;
* if (entry.url.match(hashRegExp)) {
* entry.revision = null;
* }
* return entry;
* });
* return {manifest, warnings: []};
* };
*
* @callback ManifestTransform
* @param {Array<workbox-build.ManifestEntry>} manifestEntries The full
* array of entries, prior to the current transformation.
* @param {Object} [compilation] When used in the webpack plugins, this param
* will be set to the current `compilation`.
* @return {Promise<workbox-build.ManifestTransformResult>}
* The array of entries with the transformation applied, and optionally, any
* warnings that should be reported back to the build tool.
*
* @memberof workbox-build
*/
interface ManifestTransformResultWithWarnings {
count: number;
size: number;
manifestEntries: ManifestEntry[];
warnings: string[];
}
export declare function transformManifest({ additionalManifestEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, }: BasePartial & {
fileDetails: Array<FileDetails>;
transformParam?: unknown;
}): Promise<ManifestTransformResultWithWarnings>;
export {};

View File

@@ -0,0 +1,69 @@
"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.transformManifest = void 0;
const additional_manifest_entries_transform_1 = require("./additional-manifest-entries-transform");
const errors_1 = require("./errors");
const maximum_size_transform_1 = require("./maximum-size-transform");
const modify_url_prefix_transform_1 = require("./modify-url-prefix-transform");
const no_revision_for_urls_matching_transform_1 = require("./no-revision-for-urls-matching-transform");
async function transformManifest({ additionalManifestEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, }) {
const allWarnings = [];
// Take the array of fileDetail objects and convert it into an array of
// {url, revision, size} objects, with \ replaced with /.
const normalizedManifest = fileDetails.map((fileDetails) => {
return {
url: fileDetails.file.replace(/\\/g, '/'),
revision: fileDetails.hash,
size: fileDetails.size,
};
});
const transformsToApply = [];
if (maximumFileSizeToCacheInBytes) {
transformsToApply.push((0, maximum_size_transform_1.maximumSizeTransform)(maximumFileSizeToCacheInBytes));
}
if (modifyURLPrefix) {
transformsToApply.push((0, modify_url_prefix_transform_1.modifyURLPrefixTransform)(modifyURLPrefix));
}
if (dontCacheBustURLsMatching) {
transformsToApply.push((0, no_revision_for_urls_matching_transform_1.noRevisionForURLsMatchingTransform)(dontCacheBustURLsMatching));
}
// Run any manifestTransforms functions second-to-last.
if (manifestTransforms) {
transformsToApply.push(...manifestTransforms);
}
// Run additionalManifestEntriesTransform last.
if (additionalManifestEntries) {
transformsToApply.push((0, additional_manifest_entries_transform_1.additionalManifestEntriesTransform)(additionalManifestEntries));
}
let transformedManifest = normalizedManifest;
for (const transform of transformsToApply) {
const result = await transform(transformedManifest, transformParam);
if (!('manifest' in result)) {
throw new Error(errors_1.errors['bad-manifest-transforms-return-value']);
}
transformedManifest = result.manifest;
allWarnings.push(...(result.warnings || []));
}
// Generate some metadata about the manifest before we clear out the size
// properties from each entry.
const count = transformedManifest.length;
let size = 0;
for (const manifestEntry of transformedManifest) {
size += manifestEntry.size || 0;
delete manifestEntry.size;
}
return {
count,
size,
manifestEntries: transformedManifest,
warnings: allWarnings,
};
}
exports.transformManifest = transformManifest;

View File

@@ -0,0 +1,5 @@
export declare function translateURLToSourcemapPaths(url: string | null, swSrc: string, swDest: string): {
destPath: string | undefined;
srcPath: string | undefined;
warning: string | undefined;
};

View File

@@ -0,0 +1,33 @@
"use strict";
/*
Copyright 2021 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.translateURLToSourcemapPaths = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const upath_1 = __importDefault(require("upath"));
const errors_1 = require("./errors");
function translateURLToSourcemapPaths(url, swSrc, swDest) {
let destPath = undefined;
let srcPath = undefined;
let warning = undefined;
if (url && !url.startsWith('data:')) {
const possibleSrcPath = upath_1.default.resolve(upath_1.default.dirname(swSrc), url);
if (fs_extra_1.default.existsSync(possibleSrcPath)) {
srcPath = possibleSrcPath;
destPath = upath_1.default.resolve(upath_1.default.dirname(swDest), url);
}
else {
warning = `${errors_1.errors['cant-find-sourcemap']} ${possibleSrcPath}`;
}
}
return { destPath, srcPath, warning };
}
exports.translateURLToSourcemapPaths = translateURLToSourcemapPaths;

View File

@@ -0,0 +1,9 @@
import { GenerateSWOptions, GetManifestOptions, InjectManifestOptions, WebpackGenerateSWOptions, WebpackInjectManifestOptions } from '../types';
export declare class WorkboxConfigError extends Error {
constructor(message?: string);
}
export declare function validateGenerateSWOptions(input: unknown): GenerateSWOptions;
export declare function validateGetManifestOptions(input: unknown): GetManifestOptions;
export declare function validateInjectManifestOptions(input: unknown): InjectManifestOptions;
export declare function validateWebpackGenerateSWOptions(input: unknown): WebpackGenerateSWOptions;
export declare function validateWebpackInjectManifestOptions(input: unknown): WebpackInjectManifestOptions;

View File

@@ -0,0 +1,147 @@
"use strict";
/*
Copyright 2021 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.validateWebpackInjectManifestOptions = exports.validateWebpackGenerateSWOptions = exports.validateInjectManifestOptions = exports.validateGetManifestOptions = exports.validateGenerateSWOptions = exports.WorkboxConfigError = void 0;
const better_ajv_errors_1 = require("@apideck/better-ajv-errors");
const common_tags_1 = require("common-tags");
const ajv_1 = __importDefault(require("ajv"));
const errors_1 = require("./errors");
const ajv = new ajv_1.default({
useDefaults: true,
});
const DEFAULT_EXCLUDE_VALUE = [/\.map$/, /^manifest.*\.js$/];
class WorkboxConfigError extends Error {
constructor(message) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
}
}
exports.WorkboxConfigError = WorkboxConfigError;
// Some methods need to do follow-up validation using the JSON schema,
// so return both the validated options and then schema.
function validate(input, methodName) {
// Don't mutate input: https://github.com/GoogleChrome/workbox/issues/2158
const inputCopy = Object.assign({}, input);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const jsonSchema = require(`../schema/${methodName}Options.json`);
const validate = ajv.compile(jsonSchema);
if (validate(inputCopy)) {
// All methods support manifestTransforms, so validate it here.
ensureValidManifestTransforms(inputCopy);
return [inputCopy, jsonSchema];
}
const betterErrors = (0, better_ajv_errors_1.betterAjvErrors)({
basePath: methodName,
data: input,
errors: validate.errors,
// This is needed as JSONSchema6 is expected, but JSONSchemaType works.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
schema: jsonSchema,
});
const messages = betterErrors.map((err) => (0, common_tags_1.oneLine) `[${err.path}] ${err.message}.
${err.suggestion ? err.suggestion : ''}`);
throw new WorkboxConfigError(messages.join('\n\n'));
}
function ensureValidManifestTransforms(options) {
if ('manifestTransforms' in options &&
!(Array.isArray(options.manifestTransforms) &&
options.manifestTransforms.every((item) => typeof item === 'function'))) {
throw new WorkboxConfigError(errors_1.errors['manifest-transforms']);
}
}
function ensureValidNavigationPreloadConfig(options) {
if (options.navigationPreload &&
(!Array.isArray(options.runtimeCaching) ||
options.runtimeCaching.length === 0)) {
throw new WorkboxConfigError(errors_1.errors['nav-preload-runtime-caching']);
}
}
function ensureValidCacheExpiration(options) {
var _a, _b;
for (const runtimeCaching of options.runtimeCaching || []) {
if (((_a = runtimeCaching.options) === null || _a === void 0 ? void 0 : _a.expiration) &&
!((_b = runtimeCaching.options) === null || _b === void 0 ? void 0 : _b.cacheName)) {
throw new WorkboxConfigError(errors_1.errors['cache-name-required']);
}
}
}
function ensureValidRuntimeCachingOrGlobDirectory(options) {
if (!options.globDirectory &&
(!Array.isArray(options.runtimeCaching) ||
options.runtimeCaching.length === 0)) {
throw new WorkboxConfigError(errors_1.errors['no-manifest-entries-or-runtime-caching']);
}
}
// This is... messy, because we can't rely on the built-in ajv validation for
// runtimeCaching.handler, as it needs to accept {} (i.e. any) due to
// https://github.com/GoogleChrome/workbox/pull/2899
// So we need to perform validation when a string (not a function) is used.
function ensureValidStringHandler(options, jsonSchema) {
var _a, _b, _c, _d;
let validHandlers = [];
/* eslint-disable */
for (const handler of ((_d = (_c = (_b = (_a = jsonSchema.definitions) === null || _a === void 0 ? void 0 : _a.RuntimeCaching) === null || _b === void 0 ? void 0 : _b.properties) === null || _c === void 0 ? void 0 : _c.handler) === null || _d === void 0 ? void 0 : _d.anyOf) || []) {
if ('enum' in handler) {
validHandlers = handler.enum;
break;
}
}
/* eslint-enable */
for (const runtimeCaching of options.runtimeCaching || []) {
if (typeof runtimeCaching.handler === 'string' &&
!validHandlers.includes(runtimeCaching.handler)) {
throw new WorkboxConfigError(errors_1.errors['invalid-handler-string'] + runtimeCaching.handler);
}
}
}
function validateGenerateSWOptions(input) {
const [validatedOptions, jsonSchema] = validate(input, 'GenerateSW');
ensureValidNavigationPreloadConfig(validatedOptions);
ensureValidCacheExpiration(validatedOptions);
ensureValidRuntimeCachingOrGlobDirectory(validatedOptions);
ensureValidStringHandler(validatedOptions, jsonSchema);
return validatedOptions;
}
exports.validateGenerateSWOptions = validateGenerateSWOptions;
function validateGetManifestOptions(input) {
const [validatedOptions] = validate(input, 'GetManifest');
return validatedOptions;
}
exports.validateGetManifestOptions = validateGetManifestOptions;
function validateInjectManifestOptions(input) {
const [validatedOptions] = validate(input, 'InjectManifest');
return validatedOptions;
}
exports.validateInjectManifestOptions = validateInjectManifestOptions;
// The default `exclude: [/\.map$/, /^manifest.*\.js$/]` value can't be
// represented in the JSON schema, so manually set it for the webpack options.
function validateWebpackGenerateSWOptions(input) {
const inputWithExcludeDefault = Object.assign({
// Make a copy, as exclude can be mutated when used.
exclude: Array.from(DEFAULT_EXCLUDE_VALUE),
}, input);
const [validatedOptions, jsonSchema] = validate(inputWithExcludeDefault, 'WebpackGenerateSW');
ensureValidNavigationPreloadConfig(validatedOptions);
ensureValidCacheExpiration(validatedOptions);
ensureValidStringHandler(validatedOptions, jsonSchema);
return validatedOptions;
}
exports.validateWebpackGenerateSWOptions = validateWebpackGenerateSWOptions;
function validateWebpackInjectManifestOptions(input) {
const inputWithExcludeDefault = Object.assign({
// Make a copy, as exclude can be mutated when used.
exclude: Array.from(DEFAULT_EXCLUDE_VALUE),
}, input);
const [validatedOptions] = validate(inputWithExcludeDefault, 'WebpackInjectManifest');
return validatedOptions;
}
exports.validateWebpackInjectManifestOptions = validateWebpackInjectManifestOptions;

View File

@@ -0,0 +1,4 @@
import { GenerateSWOptions, ManifestEntry } from '../types';
export declare function writeSWUsingDefaultTemplate({ babelPresetEnvTargets, cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, inlineWorkboxRuntime, manifestEntries, mode, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, sourcemap, swDest, }: GenerateSWOptions & {
manifestEntries: Array<ManifestEntry>;
}): Promise<Array<string>>;

View File

@@ -0,0 +1,71 @@
"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.writeSWUsingDefaultTemplate = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const upath_1 = __importDefault(require("upath"));
const bundle_1 = require("./bundle");
const errors_1 = require("./errors");
const populate_sw_template_1 = require("./populate-sw-template");
async function writeSWUsingDefaultTemplate({ babelPresetEnvTargets, cacheId, cleanupOutdatedCaches, clientsClaim, directoryIndex, disableDevLogs, ignoreURLParametersMatching, importScripts, inlineWorkboxRuntime, manifestEntries, mode, navigateFallback, navigateFallbackDenylist, navigateFallbackAllowlist, navigationPreload, offlineGoogleAnalytics, runtimeCaching, skipWaiting, sourcemap, swDest, }) {
const outputDir = upath_1.default.dirname(swDest);
try {
await fs_extra_1.default.mkdirp(outputDir);
}
catch (error) {
throw new Error(`${errors_1.errors['unable-to-make-sw-directory']}. ` +
`'${error instanceof Error && error.message ? error.message : ''}'`);
}
const unbundledCode = (0, populate_sw_template_1.populateSWTemplate)({
cacheId,
cleanupOutdatedCaches,
clientsClaim,
directoryIndex,
disableDevLogs,
ignoreURLParametersMatching,
importScripts,
manifestEntries,
navigateFallback,
navigateFallbackDenylist,
navigateFallbackAllowlist,
navigationPreload,
offlineGoogleAnalytics,
runtimeCaching,
skipWaiting,
});
try {
const files = await (0, bundle_1.bundle)({
babelPresetEnvTargets,
inlineWorkboxRuntime,
mode,
sourcemap,
swDest,
unbundledCode,
});
const filePaths = [];
for (const file of files) {
const filePath = upath_1.default.resolve(file.name);
filePaths.push(filePath);
await fs_extra_1.default.writeFile(filePath, file.contents);
}
return filePaths;
}
catch (error) {
const err = error;
if (err.code === 'EISDIR') {
// See https://github.com/GoogleChrome/workbox/issues/612
throw new Error(errors_1.errors['sw-write-failure-directory']);
}
throw new Error(`${errors_1.errors['sw-write-failure']} '${err.message}'`);
}
}
exports.writeSWUsingDefaultTemplate = writeSWUsingDefaultTemplate;

View File

@@ -0,0 +1,872 @@
{
"additionalProperties": false,
"type": "object",
"properties": {
"additionalManifestEntries": {
"description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.",
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/ManifestEntry"
},
{
"type": "string"
}
]
}
},
"dontCacheBustURLsMatching": {
"description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.",
"$ref": "#/definitions/RegExp"
},
"manifestTransforms": {
"description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.",
"type": "array",
"items": {}
},
"maximumFileSizeToCacheInBytes": {
"description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.",
"default": 2097152,
"type": "number"
},
"modifyURLPrefix": {
"description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"globFollow": {
"description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).",
"default": true,
"type": "boolean"
},
"globIgnores": {
"description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).",
"default": [
"**/node_modules/**/*"
],
"type": "array",
"items": {
"type": "string"
}
},
"globPatterns": {
"description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).",
"default": [
"**/*.{js,css,html}"
],
"type": "array",
"items": {
"type": "string"
}
},
"globStrict": {
"description": "If true, an error reading a directory when generating a precache manifest\nwill cause the build to fail. If false, the problematic directory will be\nskipped. For more information, see the definition of `strict` in the `glob`\n[documentation](https://github.com/isaacs/node-glob#options).",
"default": true,
"type": "boolean"
},
"templatedURLs": {
"description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.",
"type": "object",
"additionalProperties": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
}
},
{
"type": "string"
}
]
}
},
"babelPresetEnvTargets": {
"description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.",
"default": [
"chrome >= 56"
],
"type": "array",
"items": {
"type": "string"
}
},
"cacheId": {
"description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.",
"type": [
"null",
"string"
]
},
"cleanupOutdatedCaches": {
"description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.",
"default": false,
"type": "boolean"
},
"clientsClaim": {
"description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.",
"default": false,
"type": "boolean"
},
"directoryIndex": {
"description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.",
"type": [
"null",
"string"
]
},
"disableDevLogs": {
"default": false,
"type": "boolean"
},
"ignoreURLParametersMatching": {
"description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.",
"type": "array",
"items": {
"$ref": "#/definitions/RegExp"
}
},
"importScripts": {
"description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.",
"type": "array",
"items": {
"type": "string"
}
},
"inlineWorkboxRuntime": {
"description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.",
"default": false,
"type": "boolean"
},
"mode": {
"description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.",
"default": "production",
"type": [
"null",
"string"
]
},
"navigateFallback": {
"description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).",
"default": null,
"type": [
"null",
"string"
]
},
"navigateFallbackAllowlist": {
"description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.",
"type": "array",
"items": {
"$ref": "#/definitions/RegExp"
}
},
"navigateFallbackDenylist": {
"description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.",
"type": "array",
"items": {
"$ref": "#/definitions/RegExp"
}
},
"navigationPreload": {
"description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.",
"default": false,
"type": "boolean"
},
"offlineGoogleAnalytics": {
"description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.",
"default": false,
"anyOf": [
{
"$ref": "#/definitions/GoogleAnalyticsInitializeOptions"
},
{
"type": "boolean"
}
]
},
"runtimeCaching": {
"description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:",
"type": "array",
"items": {
"$ref": "#/definitions/RuntimeCaching"
}
},
"skipWaiting": {
"description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.",
"default": false,
"type": "boolean"
},
"sourcemap": {
"description": "Whether to create a sourcemap for the generated service worker files.",
"default": true,
"type": "boolean"
},
"swDest": {
"description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.",
"type": "string"
},
"globDirectory": {
"description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.",
"type": "string"
}
},
"required": [
"swDest"
],
"definitions": {
"ManifestEntry": {
"type": "object",
"properties": {
"integrity": {
"type": "string"
},
"revision": {
"type": [
"null",
"string"
]
},
"url": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"revision",
"url"
]
},
"RegExp": {
"type": "object",
"properties": {
"source": {
"type": "string"
},
"global": {
"type": "boolean"
},
"ignoreCase": {
"type": "boolean"
},
"multiline": {
"type": "boolean"
},
"lastIndex": {
"type": "number"
},
"flags": {
"type": "string"
},
"sticky": {
"type": "boolean"
},
"unicode": {
"type": "boolean"
},
"dotAll": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"dotAll",
"flags",
"global",
"ignoreCase",
"lastIndex",
"multiline",
"source",
"sticky",
"unicode"
]
},
"GoogleAnalyticsInitializeOptions": {
"type": "object",
"properties": {
"cacheName": {
"type": "string"
},
"parameterOverrides": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"hitFilter": {
"type": "object",
"additionalProperties": false
}
},
"additionalProperties": false
},
"RuntimeCaching": {
"type": "object",
"properties": {
"handler": {
"description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.",
"anyOf": [
{
"$ref": "#/definitions/RouteHandlerCallback"
},
{
"$ref": "#/definitions/RouteHandlerObject"
},
{
"enum": [
"CacheFirst",
"CacheOnly",
"NetworkFirst",
"NetworkOnly",
"StaleWhileRevalidate"
],
"type": "string"
}
]
},
"method": {
"description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.",
"default": "GET",
"enum": [
"DELETE",
"GET",
"HEAD",
"PATCH",
"POST",
"PUT"
],
"type": "string"
},
"options": {
"type": "object",
"properties": {
"backgroundSync": {
"description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"options": {
"$ref": "#/definitions/QueueOptions"
}
},
"additionalProperties": false,
"required": [
"name"
]
},
"broadcastUpdate": {
"description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.",
"type": "object",
"properties": {
"channelName": {
"type": "string"
},
"options": {
"$ref": "#/definitions/BroadcastCacheUpdateOptions"
}
},
"additionalProperties": false,
"required": [
"options"
]
},
"cacheableResponse": {
"description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/CacheableResponseOptions"
},
"cacheName": {
"description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.",
"type": [
"null",
"string"
]
},
"expiration": {
"description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/ExpirationPluginOptions"
},
"networkTimeoutSeconds": {
"description": "If provided, this will set the `networkTimeoutSeconds` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.",
"type": "number"
},
"plugins": {
"description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.",
"type": "array",
"items": {
"$ref": "#/definitions/WorkboxPlugin"
}
},
"precacheFallback": {
"description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"type": "object",
"properties": {
"fallbackURL": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"fallbackURL"
]
},
"rangeRequests": {
"description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"type": "boolean"
},
"fetchOptions": {
"description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/RequestInit"
},
"matchOptions": {
"description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/CacheQueryOptions"
}
},
"additionalProperties": false
},
"urlPattern": {
"description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.",
"anyOf": [
{
"$ref": "#/definitions/RegExp"
},
{
"$ref": "#/definitions/RouteMatchCallback"
},
{
"type": "string"
}
]
}
},
"additionalProperties": false,
"required": [
"handler",
"urlPattern"
]
},
"RouteHandlerCallback": {},
"RouteHandlerObject": {
"description": "An object with a `handle` method of type `RouteHandlerCallback`.\n\nA `Route` object can be created with either an `RouteHandlerCallback`\nfunction or this `RouteHandler` object. The benefit of the `RouteHandler`\nis it can be extended (as is done by the `workbox-strategies` package).",
"type": "object",
"properties": {
"handle": {
"$ref": "#/definitions/RouteHandlerCallback"
}
},
"additionalProperties": false,
"required": [
"handle"
]
},
"QueueOptions": {
"type": "object",
"properties": {
"forceSyncFallback": {
"type": "boolean"
},
"maxRetentionTime": {
"type": "number"
},
"onSync": {
"$ref": "#/definitions/OnSyncCallback"
}
},
"additionalProperties": false
},
"OnSyncCallback": {},
"BroadcastCacheUpdateOptions": {
"type": "object",
"properties": {
"headersToCheck": {
"type": "array",
"items": {
"type": "string"
}
},
"generatePayload": {
"type": "object",
"additionalProperties": false
},
"notifyAllClients": {
"type": "boolean"
}
},
"additionalProperties": false
},
"CacheableResponseOptions": {
"type": "object",
"properties": {
"statuses": {
"type": "array",
"items": {
"type": "number"
}
},
"headers": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"additionalProperties": false
},
"ExpirationPluginOptions": {
"type": "object",
"properties": {
"maxEntries": {
"type": "number"
},
"maxAgeSeconds": {
"type": "number"
},
"matchOptions": {
"$ref": "#/definitions/CacheQueryOptions"
},
"purgeOnQuotaError": {
"type": "boolean"
}
},
"additionalProperties": false
},
"CacheQueryOptions": {
"type": "object",
"properties": {
"ignoreMethod": {
"type": "boolean"
},
"ignoreSearch": {
"type": "boolean"
},
"ignoreVary": {
"type": "boolean"
}
},
"additionalProperties": false
},
"WorkboxPlugin": {
"description": "An object with optional lifecycle callback properties for the fetch and\ncache operations.",
"type": "object",
"properties": {
"cacheDidUpdate": {},
"cachedResponseWillBeUsed": {},
"cacheKeyWillBeUsed": {},
"cacheWillUpdate": {},
"fetchDidFail": {},
"fetchDidSucceed": {},
"handlerDidComplete": {},
"handlerDidError": {},
"handlerDidRespond": {},
"handlerWillRespond": {},
"handlerWillStart": {},
"requestWillFetch": {}
},
"additionalProperties": false
},
"CacheDidUpdateCallback": {
"type": "object",
"additionalProperties": false
},
"CachedResponseWillBeUsedCallback": {
"type": "object",
"additionalProperties": false
},
"CacheKeyWillBeUsedCallback": {
"type": "object",
"additionalProperties": false
},
"CacheWillUpdateCallback": {
"type": "object",
"additionalProperties": false
},
"FetchDidFailCallback": {
"type": "object",
"additionalProperties": false
},
"FetchDidSucceedCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerDidCompleteCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerDidErrorCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerDidRespondCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerWillRespondCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerWillStartCallback": {
"type": "object",
"additionalProperties": false
},
"RequestWillFetchCallback": {
"type": "object",
"additionalProperties": false
},
"RequestInit": {
"type": "object",
"properties": {
"body": {
"anyOf": [
{
"$ref": "#/definitions/ArrayBuffer"
},
{
"$ref": "#/definitions/ArrayBufferView"
},
{
"$ref": "#/definitions/ReadableStream<any>"
},
{
"$ref": "#/definitions/Blob"
},
{
"$ref": "#/definitions/FormData"
},
{
"$ref": "#/definitions/URLSearchParams"
},
{
"type": [
"null",
"string"
]
}
]
},
"cache": {
"enum": [
"default",
"force-cache",
"no-cache",
"no-store",
"only-if-cached",
"reload"
],
"type": "string"
},
"credentials": {
"enum": [
"include",
"omit",
"same-origin"
],
"type": "string"
},
"headers": {
"anyOf": [
{
"$ref": "#/definitions/Record<string,string>"
},
{
"type": "array",
"items": {
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "string"
}
],
"minItems": 2,
"maxItems": 2
}
},
{
"$ref": "#/definitions/Headers"
}
]
},
"integrity": {
"type": "string"
},
"keepalive": {
"type": "boolean"
},
"method": {
"type": "string"
},
"mode": {
"enum": [
"cors",
"navigate",
"no-cors",
"same-origin"
],
"type": "string"
},
"redirect": {
"enum": [
"error",
"follow",
"manual"
],
"type": "string"
},
"referrer": {
"type": "string"
},
"referrerPolicy": {
"enum": [
"",
"no-referrer",
"no-referrer-when-downgrade",
"origin",
"origin-when-cross-origin",
"same-origin",
"strict-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
],
"type": "string"
},
"signal": {
"anyOf": [
{
"$ref": "#/definitions/AbortSignal"
},
{
"type": "null"
}
]
},
"window": {
"type": "null"
}
},
"additionalProperties": false
},
"ArrayBuffer": {
"type": "object",
"properties": {
"byteLength": {
"type": "number"
},
"__@toStringTag@25": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"__@toStringTag@25",
"byteLength"
]
},
"ArrayBufferView": {
"type": "object",
"properties": {
"buffer": {
"$ref": "#/definitions/ArrayBufferLike"
},
"byteLength": {
"type": "number"
},
"byteOffset": {
"type": "number"
}
},
"additionalProperties": false,
"required": [
"buffer",
"byteLength",
"byteOffset"
]
},
"ArrayBufferLike": {
"anyOf": [
{
"$ref": "#/definitions/ArrayBuffer"
},
{
"$ref": "#/definitions/SharedArrayBuffer"
}
]
},
"SharedArrayBuffer": {
"type": "object",
"properties": {
"byteLength": {
"type": "number"
},
"__@species@598": {
"$ref": "#/definitions/SharedArrayBuffer"
},
"__@toStringTag@25": {
"type": "string",
"enum": [
"SharedArrayBuffer"
]
}
},
"additionalProperties": false,
"required": [
"__@species@598",
"__@toStringTag@25",
"byteLength"
]
},
"ReadableStream<any>": {
"type": "object",
"properties": {
"locked": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"locked"
]
},
"Blob": {
"type": "object",
"properties": {
"size": {
"type": "number"
},
"type": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"size",
"type"
]
},
"FormData": {
"type": "object",
"additionalProperties": false
},
"URLSearchParams": {
"type": "object",
"additionalProperties": false
},
"Record<string,string>": {
"type": "object",
"additionalProperties": false
},
"Headers": {
"type": "object",
"additionalProperties": false
},
"AbortSignal": {},
"RouteMatchCallback": {}
},
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -0,0 +1,164 @@
{
"additionalProperties": false,
"type": "object",
"properties": {
"additionalManifestEntries": {
"description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.",
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/ManifestEntry"
},
{
"type": "string"
}
]
}
},
"dontCacheBustURLsMatching": {
"description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.",
"$ref": "#/definitions/RegExp"
},
"manifestTransforms": {
"description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.",
"type": "array",
"items": {}
},
"maximumFileSizeToCacheInBytes": {
"description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.",
"default": 2097152,
"type": "number"
},
"modifyURLPrefix": {
"description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"globFollow": {
"description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).",
"default": true,
"type": "boolean"
},
"globIgnores": {
"description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).",
"default": [
"**/node_modules/**/*"
],
"type": "array",
"items": {
"type": "string"
}
},
"globPatterns": {
"description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).",
"default": [
"**/*.{js,css,html}"
],
"type": "array",
"items": {
"type": "string"
}
},
"globStrict": {
"description": "If true, an error reading a directory when generating a precache manifest\nwill cause the build to fail. If false, the problematic directory will be\nskipped. For more information, see the definition of `strict` in the `glob`\n[documentation](https://github.com/isaacs/node-glob#options).",
"default": true,
"type": "boolean"
},
"templatedURLs": {
"description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.",
"type": "object",
"additionalProperties": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
}
},
{
"type": "string"
}
]
}
},
"globDirectory": {
"description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.",
"type": "string"
}
},
"required": [
"globDirectory"
],
"definitions": {
"ManifestEntry": {
"type": "object",
"properties": {
"integrity": {
"type": "string"
},
"revision": {
"type": [
"null",
"string"
]
},
"url": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"revision",
"url"
]
},
"RegExp": {
"type": "object",
"properties": {
"source": {
"type": "string"
},
"global": {
"type": "boolean"
},
"ignoreCase": {
"type": "boolean"
},
"multiline": {
"type": "boolean"
},
"lastIndex": {
"type": "number"
},
"flags": {
"type": "string"
},
"sticky": {
"type": "boolean"
},
"unicode": {
"type": "boolean"
},
"dotAll": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"dotAll",
"flags",
"global",
"ignoreCase",
"lastIndex",
"multiline",
"source",
"sticky",
"unicode"
]
}
},
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -0,0 +1,179 @@
{
"additionalProperties": false,
"type": "object",
"properties": {
"additionalManifestEntries": {
"description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.",
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/ManifestEntry"
},
{
"type": "string"
}
]
}
},
"dontCacheBustURLsMatching": {
"description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.",
"$ref": "#/definitions/RegExp"
},
"manifestTransforms": {
"description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.",
"type": "array",
"items": {}
},
"maximumFileSizeToCacheInBytes": {
"description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.",
"default": 2097152,
"type": "number"
},
"modifyURLPrefix": {
"description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"globFollow": {
"description": "Determines whether or not symlinks are followed when generating the\nprecache manifest. For more information, see the definition of `follow` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).",
"default": true,
"type": "boolean"
},
"globIgnores": {
"description": "A set of patterns matching files to always exclude when generating the\nprecache manifest. For more information, see the definition of `ignore` in\nthe `glob` [documentation](https://github.com/isaacs/node-glob#options).",
"default": [
"**/node_modules/**/*"
],
"type": "array",
"items": {
"type": "string"
}
},
"globPatterns": {
"description": "Files matching any of these patterns will be included in the precache\nmanifest. For more information, see the\n[`glob` primer](https://github.com/isaacs/node-glob#glob-primer).",
"default": [
"**/*.{js,css,html}"
],
"type": "array",
"items": {
"type": "string"
}
},
"globStrict": {
"description": "If true, an error reading a directory when generating a precache manifest\nwill cause the build to fail. If false, the problematic directory will be\nskipped. For more information, see the definition of `strict` in the `glob`\n[documentation](https://github.com/isaacs/node-glob#options).",
"default": true,
"type": "boolean"
},
"templatedURLs": {
"description": "If a URL is rendered based on some server-side logic, its contents may\ndepend on multiple files or on some other unique string value. The keys in\nthis object are server-rendered URLs. If the values are an array of\nstrings, they will be interpreted as `glob` patterns, and the contents of\nany files matching the patterns will be used to uniquely version the URL.\nIf used with a single string, it will be interpreted as unique versioning\ninformation that you've generated for a given URL.",
"type": "object",
"additionalProperties": {
"anyOf": [
{
"type": "array",
"items": {
"type": "string"
}
},
{
"type": "string"
}
]
}
},
"injectionPoint": {
"description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.",
"default": "self.__WB_MANIFEST",
"type": "string"
},
"swSrc": {
"description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.",
"type": "string"
},
"swDest": {
"description": "The path and filename of the service worker file that will be created by\nthe build process, relative to the current working directory. It must end\nin '.js'.",
"type": "string"
},
"globDirectory": {
"description": "The local directory you wish to match `globPatterns` against. The path is\nrelative to the current directory.",
"type": "string"
}
},
"required": [
"globDirectory",
"swDest",
"swSrc"
],
"definitions": {
"ManifestEntry": {
"type": "object",
"properties": {
"integrity": {
"type": "string"
},
"revision": {
"type": [
"null",
"string"
]
},
"url": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"revision",
"url"
]
},
"RegExp": {
"type": "object",
"properties": {
"source": {
"type": "string"
},
"global": {
"type": "boolean"
},
"ignoreCase": {
"type": "boolean"
},
"multiline": {
"type": "boolean"
},
"lastIndex": {
"type": "number"
},
"flags": {
"type": "string"
},
"sticky": {
"type": "boolean"
},
"unicode": {
"type": "boolean"
},
"dotAll": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"dotAll",
"flags",
"global",
"ignoreCase",
"lastIndex",
"multiline",
"source",
"sticky",
"unicode"
]
}
},
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -0,0 +1,850 @@
{
"additionalProperties": false,
"type": "object",
"properties": {
"additionalManifestEntries": {
"description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.",
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/ManifestEntry"
},
{
"type": "string"
}
]
}
},
"dontCacheBustURLsMatching": {
"description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.",
"$ref": "#/definitions/RegExp"
},
"manifestTransforms": {
"description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.",
"type": "array",
"items": {}
},
"maximumFileSizeToCacheInBytes": {
"description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.",
"default": 2097152,
"type": "number"
},
"modifyURLPrefix": {
"description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"chunks": {
"description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.",
"type": "array",
"items": {
"type": "string"
}
},
"exclude": {
"description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.",
"type": "array",
"items": {}
},
"excludeChunks": {
"description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.",
"type": "array",
"items": {
"type": "string"
}
},
"include": {
"description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.",
"type": "array",
"items": {}
},
"mode": {
"description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `process.env.NODE_ENV` value will be used, and failing that, it\nwill fall back to `'production'`.",
"default": "production",
"type": [
"null",
"string"
]
},
"babelPresetEnvTargets": {
"description": "The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass\nto `babel-preset-env` when transpiling the service worker bundle.",
"default": [
"chrome >= 56"
],
"type": "array",
"items": {
"type": "string"
}
},
"cacheId": {
"description": "An optional ID to be prepended to cache names. This is primarily useful for\nlocal development where multiple sites may be served from the same\n`http://localhost:port` origin.",
"type": [
"null",
"string"
]
},
"cleanupOutdatedCaches": {
"description": "Whether or not Workbox should attempt to identify and delete any precaches\ncreated by older, incompatible versions.",
"default": false,
"type": "boolean"
},
"clientsClaim": {
"description": "Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)\nany existing clients as soon as it activates.",
"default": false,
"type": "boolean"
},
"directoryIndex": {
"description": "If a navigation request for a URL ending in `/` fails to match a precached\nURL, this value will be appended to the URL and that will be checked for a\nprecache match. This should be set to what your web server is using for its\ndirectory index.",
"type": [
"null",
"string"
]
},
"disableDevLogs": {
"default": false,
"type": "boolean"
},
"ignoreURLParametersMatching": {
"description": "Any search parameter names that match against one of the RegExp in this\narray will be removed before looking for a precache match. This is useful\nif your users might request URLs that contain, for example, URL parameters\nused to track the source of the traffic. If not provided, the default value\nis `[/^utm_/, /^fbclid$/]`.",
"type": "array",
"items": {
"$ref": "#/definitions/RegExp"
}
},
"importScripts": {
"description": "A list of JavaScript files that should be passed to\n[`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)\ninside the generated service worker file. This is useful when you want to\nlet Workbox create your top-level service worker file, but want to include\nsome additional code, such as a push event listener.",
"type": "array",
"items": {
"type": "string"
}
},
"inlineWorkboxRuntime": {
"description": "Whether the runtime code for the Workbox library should be included in the\ntop-level service worker, or split into a separate file that needs to be\ndeployed alongside the service worker. Keeping the runtime separate means\nthat users will not have to re-download the Workbox code each time your\ntop-level service worker changes.",
"default": false,
"type": "boolean"
},
"navigateFallback": {
"description": "If specified, all\n[navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)\nfor URLs that aren't precached will be fulfilled with the HTML at the URL\nprovided. You must pass in the URL of an HTML document that is listed in\nyour precache manifest. This is meant to be used in a Single Page App\nscenario, in which you want all navigations to use common\n[App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).",
"default": null,
"type": [
"null",
"string"
]
},
"navigateFallbackAllowlist": {
"description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedent.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.",
"type": "array",
"items": {
"$ref": "#/definitions/RegExp"
}
},
"navigateFallbackDenylist": {
"description": "An optional array of regular expressions that restricts which URLs the\nconfigured `navigateFallback` behavior applies to. This is useful if only a\nsubset of your site's URLs should be treated as being part of a\n[Single Page App](https://en.wikipedia.org/wiki/Single-page_application).\nIf both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are\nconfigured, the denylist takes precedence.\n\n*Note*: These RegExps may be evaluated against every destination URL during\na navigation. Avoid using\n[complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),\nor else your users may see delays when navigating your site.",
"type": "array",
"items": {
"$ref": "#/definitions/RegExp"
}
},
"navigationPreload": {
"description": "Whether or not to enable\n[navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)\nin the generated service worker. When set to true, you must also use\n`runtimeCaching` to set up an appropriate response strategy that will match\nnavigation requests, and make use of the preloaded response.",
"default": false,
"type": "boolean"
},
"offlineGoogleAnalytics": {
"description": "Controls whether or not to include support for\n[offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).\nWhen `true`, the call to `workbox-google-analytics`'s `initialize()` will\nbe added to your generated service worker. When set to an `Object`, that\nobject will be passed in to the `initialize()` call, allowing you to\ncustomize the behavior.",
"default": false,
"anyOf": [
{
"$ref": "#/definitions/GoogleAnalyticsInitializeOptions"
},
{
"type": "boolean"
}
]
},
"runtimeCaching": {
"description": "When using Workbox's build tools to generate your service worker, you can\nspecify one or more runtime caching configurations. These are then\ntranslated to {@link workbox-routing.registerRoute} calls using the match\nand handler configuration you define.\n\nFor all of the options, see the {@link workbox-build.RuntimeCaching}\ndocumentation. The example below shows a typical configuration, with two\nruntime routes defined:",
"type": "array",
"items": {
"$ref": "#/definitions/RuntimeCaching"
}
},
"skipWaiting": {
"description": "Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)\nto the generated service worker. If `false`, then a `message` listener will\nbe added instead, allowing client pages to trigger `skipWaiting()` by\ncalling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.",
"default": false,
"type": "boolean"
},
"sourcemap": {
"description": "Whether to create a sourcemap for the generated service worker files.",
"default": true,
"type": "boolean"
},
"importScriptsViaChunks": {
"description": "One or more names of webpack chunks. The content of those chunks will be\nincluded in the generated service worker, via a call to `importScripts()`.",
"type": "array",
"items": {
"type": "string"
}
},
"swDest": {
"description": "The asset name of the service worker file created by this plugin.",
"default": "service-worker.js",
"type": "string"
}
},
"definitions": {
"ManifestEntry": {
"type": "object",
"properties": {
"integrity": {
"type": "string"
},
"revision": {
"type": [
"null",
"string"
]
},
"url": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"revision",
"url"
]
},
"RegExp": {
"type": "object",
"properties": {
"source": {
"type": "string"
},
"global": {
"type": "boolean"
},
"ignoreCase": {
"type": "boolean"
},
"multiline": {
"type": "boolean"
},
"lastIndex": {
"type": "number"
},
"flags": {
"type": "string"
},
"sticky": {
"type": "boolean"
},
"unicode": {
"type": "boolean"
},
"dotAll": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"dotAll",
"flags",
"global",
"ignoreCase",
"lastIndex",
"multiline",
"source",
"sticky",
"unicode"
]
},
"GoogleAnalyticsInitializeOptions": {
"type": "object",
"properties": {
"cacheName": {
"type": "string"
},
"parameterOverrides": {
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"hitFilter": {
"type": "object",
"additionalProperties": false
}
},
"additionalProperties": false
},
"RuntimeCaching": {
"type": "object",
"properties": {
"handler": {
"description": "This determines how the runtime route will generate a response.\nTo use one of the built-in {@link workbox-strategies}, provide its name,\nlike `'NetworkFirst'`.\nAlternatively, this can be a {@link workbox-core.RouteHandler} callback\nfunction with custom response logic.",
"anyOf": [
{
"$ref": "#/definitions/RouteHandlerCallback"
},
{
"$ref": "#/definitions/RouteHandlerObject"
},
{
"enum": [
"CacheFirst",
"CacheOnly",
"NetworkFirst",
"NetworkOnly",
"StaleWhileRevalidate"
],
"type": "string"
}
]
},
"method": {
"description": "The HTTP method to match against. The default value of `'GET'` is normally\nsufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or\nanother type of request.",
"default": "GET",
"enum": [
"DELETE",
"GET",
"HEAD",
"PATCH",
"POST",
"PUT"
],
"type": "string"
},
"options": {
"type": "object",
"properties": {
"backgroundSync": {
"description": "Configuring this will add a\n{@link workbox-background-sync.BackgroundSyncPlugin} instance to the\n{@link workbox-strategies} configured in `handler`.",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"options": {
"$ref": "#/definitions/QueueOptions"
}
},
"additionalProperties": false,
"required": [
"name"
]
},
"broadcastUpdate": {
"description": "Configuring this will add a\n{@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the\n{@link workbox-strategies} configured in `handler`.",
"type": "object",
"properties": {
"channelName": {
"type": "string"
},
"options": {
"$ref": "#/definitions/BroadcastCacheUpdateOptions"
}
},
"additionalProperties": false,
"required": [
"options"
]
},
"cacheableResponse": {
"description": "Configuring this will add a\n{@link workbox-cacheable-response.CacheableResponsePlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/CacheableResponseOptions"
},
"cacheName": {
"description": "If provided, this will set the `cacheName` property of the\n{@link workbox-strategies} configured in `handler`.",
"type": [
"null",
"string"
]
},
"expiration": {
"description": "Configuring this will add a\n{@link workbox-expiration.ExpirationPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/ExpirationPluginOptions"
},
"networkTimeoutSeconds": {
"description": "If provided, this will set the `networkTimeoutSeconds` property of the\n{@link workbox-strategies} configured in `handler`. Note that only\n`'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.",
"type": "number"
},
"plugins": {
"description": "Configuring this allows the use of one or more Workbox plugins that\ndon't have \"shortcut\" options (like `expiration` for\n{@link workbox-expiration.ExpirationPlugin}). The plugins provided here\nwill be added to the {@link workbox-strategies} configured in `handler`.",
"type": "array",
"items": {
"$ref": "#/definitions/WorkboxPlugin"
}
},
"precacheFallback": {
"description": "Configuring this will add a\n{@link workbox-precaching.PrecacheFallbackPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"type": "object",
"properties": {
"fallbackURL": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"fallbackURL"
]
},
"rangeRequests": {
"description": "Enabling this will add a\n{@link workbox-range-requests.RangeRequestsPlugin} instance to\nthe {@link workbox-strategies} configured in `handler`.",
"type": "boolean"
},
"fetchOptions": {
"description": "Configuring this will pass along the `fetchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/RequestInit"
},
"matchOptions": {
"description": "Configuring this will pass along the `matchOptions` value to\nthe {@link workbox-strategies} configured in `handler`.",
"$ref": "#/definitions/CacheQueryOptions"
}
},
"additionalProperties": false
},
"urlPattern": {
"description": "This match criteria determines whether the configured handler will\ngenerate a response for any requests that don't match one of the precached\nURLs. If multiple `RuntimeCaching` routes are defined, then the first one\nwhose `urlPattern` matches will be the one that responds.\n\nThis value directly maps to the first parameter passed to\n{@link workbox-routing.registerRoute}. It's recommended to use a\n{@link workbox-core.RouteMatchCallback} function for greatest flexibility.",
"anyOf": [
{
"$ref": "#/definitions/RegExp"
},
{
"$ref": "#/definitions/RouteMatchCallback"
},
{
"type": "string"
}
]
}
},
"additionalProperties": false,
"required": [
"handler",
"urlPattern"
]
},
"RouteHandlerCallback": {},
"RouteHandlerObject": {
"description": "An object with a `handle` method of type `RouteHandlerCallback`.\n\nA `Route` object can be created with either an `RouteHandlerCallback`\nfunction or this `RouteHandler` object. The benefit of the `RouteHandler`\nis it can be extended (as is done by the `workbox-strategies` package).",
"type": "object",
"properties": {
"handle": {
"$ref": "#/definitions/RouteHandlerCallback"
}
},
"additionalProperties": false,
"required": [
"handle"
]
},
"QueueOptions": {
"type": "object",
"properties": {
"forceSyncFallback": {
"type": "boolean"
},
"maxRetentionTime": {
"type": "number"
},
"onSync": {
"$ref": "#/definitions/OnSyncCallback"
}
},
"additionalProperties": false
},
"OnSyncCallback": {},
"BroadcastCacheUpdateOptions": {
"type": "object",
"properties": {
"headersToCheck": {
"type": "array",
"items": {
"type": "string"
}
},
"generatePayload": {
"type": "object",
"additionalProperties": false
},
"notifyAllClients": {
"type": "boolean"
}
},
"additionalProperties": false
},
"CacheableResponseOptions": {
"type": "object",
"properties": {
"statuses": {
"type": "array",
"items": {
"type": "number"
}
},
"headers": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"additionalProperties": false
},
"ExpirationPluginOptions": {
"type": "object",
"properties": {
"maxEntries": {
"type": "number"
},
"maxAgeSeconds": {
"type": "number"
},
"matchOptions": {
"$ref": "#/definitions/CacheQueryOptions"
},
"purgeOnQuotaError": {
"type": "boolean"
}
},
"additionalProperties": false
},
"CacheQueryOptions": {
"type": "object",
"properties": {
"ignoreMethod": {
"type": "boolean"
},
"ignoreSearch": {
"type": "boolean"
},
"ignoreVary": {
"type": "boolean"
}
},
"additionalProperties": false
},
"WorkboxPlugin": {
"description": "An object with optional lifecycle callback properties for the fetch and\ncache operations.",
"type": "object",
"properties": {
"cacheDidUpdate": {},
"cachedResponseWillBeUsed": {},
"cacheKeyWillBeUsed": {},
"cacheWillUpdate": {},
"fetchDidFail": {},
"fetchDidSucceed": {},
"handlerDidComplete": {},
"handlerDidError": {},
"handlerDidRespond": {},
"handlerWillRespond": {},
"handlerWillStart": {},
"requestWillFetch": {}
},
"additionalProperties": false
},
"CacheDidUpdateCallback": {
"type": "object",
"additionalProperties": false
},
"CachedResponseWillBeUsedCallback": {
"type": "object",
"additionalProperties": false
},
"CacheKeyWillBeUsedCallback": {
"type": "object",
"additionalProperties": false
},
"CacheWillUpdateCallback": {
"type": "object",
"additionalProperties": false
},
"FetchDidFailCallback": {
"type": "object",
"additionalProperties": false
},
"FetchDidSucceedCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerDidCompleteCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerDidErrorCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerDidRespondCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerWillRespondCallback": {
"type": "object",
"additionalProperties": false
},
"HandlerWillStartCallback": {
"type": "object",
"additionalProperties": false
},
"RequestWillFetchCallback": {
"type": "object",
"additionalProperties": false
},
"RequestInit": {
"type": "object",
"properties": {
"body": {
"anyOf": [
{
"$ref": "#/definitions/ArrayBuffer"
},
{
"$ref": "#/definitions/ArrayBufferView"
},
{
"$ref": "#/definitions/ReadableStream<any>"
},
{
"$ref": "#/definitions/Blob"
},
{
"$ref": "#/definitions/FormData"
},
{
"$ref": "#/definitions/URLSearchParams"
},
{
"type": [
"null",
"string"
]
}
]
},
"cache": {
"enum": [
"default",
"force-cache",
"no-cache",
"no-store",
"only-if-cached",
"reload"
],
"type": "string"
},
"credentials": {
"enum": [
"include",
"omit",
"same-origin"
],
"type": "string"
},
"headers": {
"anyOf": [
{
"$ref": "#/definitions/Record<string,string>"
},
{
"type": "array",
"items": {
"type": "array",
"items": [
{
"type": "string"
},
{
"type": "string"
}
],
"minItems": 2,
"maxItems": 2
}
},
{
"$ref": "#/definitions/Headers"
}
]
},
"integrity": {
"type": "string"
},
"keepalive": {
"type": "boolean"
},
"method": {
"type": "string"
},
"mode": {
"enum": [
"cors",
"navigate",
"no-cors",
"same-origin"
],
"type": "string"
},
"redirect": {
"enum": [
"error",
"follow",
"manual"
],
"type": "string"
},
"referrer": {
"type": "string"
},
"referrerPolicy": {
"enum": [
"",
"no-referrer",
"no-referrer-when-downgrade",
"origin",
"origin-when-cross-origin",
"same-origin",
"strict-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
],
"type": "string"
},
"signal": {
"anyOf": [
{
"$ref": "#/definitions/AbortSignal"
},
{
"type": "null"
}
]
},
"window": {
"type": "null"
}
},
"additionalProperties": false
},
"ArrayBuffer": {
"type": "object",
"properties": {
"byteLength": {
"type": "number"
},
"__@toStringTag@25": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"__@toStringTag@25",
"byteLength"
]
},
"ArrayBufferView": {
"type": "object",
"properties": {
"buffer": {
"$ref": "#/definitions/ArrayBufferLike"
},
"byteLength": {
"type": "number"
},
"byteOffset": {
"type": "number"
}
},
"additionalProperties": false,
"required": [
"buffer",
"byteLength",
"byteOffset"
]
},
"ArrayBufferLike": {
"anyOf": [
{
"$ref": "#/definitions/ArrayBuffer"
},
{
"$ref": "#/definitions/SharedArrayBuffer"
}
]
},
"SharedArrayBuffer": {
"type": "object",
"properties": {
"byteLength": {
"type": "number"
},
"__@species@598": {
"$ref": "#/definitions/SharedArrayBuffer"
},
"__@toStringTag@25": {
"type": "string",
"enum": [
"SharedArrayBuffer"
]
}
},
"additionalProperties": false,
"required": [
"__@species@598",
"__@toStringTag@25",
"byteLength"
]
},
"ReadableStream<any>": {
"type": "object",
"properties": {
"locked": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"locked"
]
},
"Blob": {
"type": "object",
"properties": {
"size": {
"type": "number"
},
"type": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"size",
"type"
]
},
"FormData": {
"type": "object",
"additionalProperties": false
},
"URLSearchParams": {
"type": "object",
"additionalProperties": false
},
"Record<string,string>": {
"type": "object",
"additionalProperties": false
},
"Headers": {
"type": "object",
"additionalProperties": false
},
"AbortSignal": {},
"RouteMatchCallback": {}
},
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -0,0 +1,167 @@
{
"additionalProperties": false,
"type": "object",
"properties": {
"additionalManifestEntries": {
"description": "A list of entries to be precached, in addition to any entries that are\ngenerated as part of the build configuration.",
"type": "array",
"items": {
"anyOf": [
{
"$ref": "#/definitions/ManifestEntry"
},
{
"type": "string"
}
]
}
},
"dontCacheBustURLsMatching": {
"description": "Assets that match this will be assumed to be uniquely versioned via their\nURL, and exempted from the normal HTTP cache-busting that's done when\npopulating the precache. While not required, it's recommended that if your\nexisting build process already inserts a `[hash]` value into each filename,\nyou provide a RegExp that will detect that, as it will reduce the bandwidth\nconsumed when precaching.",
"$ref": "#/definitions/RegExp"
},
"manifestTransforms": {
"description": "One or more functions which will be applied sequentially against the\ngenerated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are\nalso specified, their corresponding transformations will be applied first.",
"type": "array",
"items": {}
},
"maximumFileSizeToCacheInBytes": {
"description": "This value can be used to determine the maximum size of files that will be\nprecached. This prevents you from inadvertently precaching very large files\nthat might have accidentally matched one of your patterns.",
"default": 2097152,
"type": "number"
},
"modifyURLPrefix": {
"description": "An object mapping string prefixes to replacement string values. This can be\nused to, e.g., remove or add a path prefix from a manifest entry if your\nweb hosting setup doesn't match your local filesystem setup. As an\nalternative with more flexibility, you can use the `manifestTransforms`\noption and provide a function that modifies the entries in the manifest\nusing whatever logic you provide.\n\nExample usage:\n\n```\n// Replace a '/dist/' prefix with '/', and also prepend\n// '/static' to every URL.\nmodifyURLPrefix: {\n '/dist/': '/',\n '': '/static',\n}\n```",
"type": "object",
"additionalProperties": {
"type": "string"
}
},
"chunks": {
"description": "One or more chunk names whose corresponding output files should be included\nin the precache manifest.",
"type": "array",
"items": {
"type": "string"
}
},
"exclude": {
"description": "One or more specifiers used to exclude assets from the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `exclude` option.\nIf not provided, the default value is `[/\\.map$/, /^manifest.*\\.js$]`.",
"type": "array",
"items": {}
},
"excludeChunks": {
"description": "One or more chunk names whose corresponding output files should be excluded\nfrom the precache manifest.",
"type": "array",
"items": {
"type": "string"
}
},
"include": {
"description": "One or more specifiers used to include assets in the precache manifest.\nThis is interpreted following\n[the same rules](https://webpack.js.org/configuration/module/#condition)\nas `webpack`'s standard `include` option.",
"type": "array",
"items": {}
},
"mode": {
"description": "If set to 'production', then an optimized service worker bundle that\nexcludes debugging info will be produced. If not explicitly configured\nhere, the `mode` value configured in the current `webpack` compilation\nwill be used.",
"type": [
"null",
"string"
]
},
"injectionPoint": {
"description": "The string to find inside of the `swSrc` file. Once found, it will be\nreplaced by the generated precache manifest.",
"default": "self.__WB_MANIFEST",
"type": "string"
},
"swSrc": {
"description": "The path and filename of the service worker file that will be read during\nthe build process, relative to the current working directory.",
"type": "string"
},
"compileSrc": {
"description": "When `true` (the default), the `swSrc` file will be compiled by webpack.\nWhen `false`, compilation will not occur (and `webpackCompilationPlugins`\ncan't be used.) Set to `false` if you want to inject the manifest into,\ne.g., a JSON file.",
"default": true,
"type": "boolean"
},
"swDest": {
"description": "The asset name of the service worker file that will be created by this\nplugin. If omitted, the name will be based on the `swSrc` name.",
"type": "string"
},
"webpackCompilationPlugins": {
"description": "Optional `webpack` plugins that will be used when compiling the `swSrc`\ninput file. Only valid if `compileSrc` is `true`.",
"type": "array",
"items": {}
}
},
"required": [
"swSrc"
],
"definitions": {
"ManifestEntry": {
"type": "object",
"properties": {
"integrity": {
"type": "string"
},
"revision": {
"type": [
"null",
"string"
]
},
"url": {
"type": "string"
}
},
"additionalProperties": false,
"required": [
"revision",
"url"
]
},
"RegExp": {
"type": "object",
"properties": {
"source": {
"type": "string"
},
"global": {
"type": "boolean"
},
"ignoreCase": {
"type": "boolean"
},
"multiline": {
"type": "boolean"
},
"lastIndex": {
"type": "number"
},
"flags": {
"type": "string"
},
"sticky": {
"type": "boolean"
},
"unicode": {
"type": "boolean"
},
"dotAll": {
"type": "boolean"
}
},
"additionalProperties": false,
"required": [
"dotAll",
"flags",
"global",
"ignoreCase",
"lastIndex",
"multiline",
"source",
"sticky",
"unicode"
]
}
},
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -0,0 +1 @@
export declare const swTemplate = "/**\n * Welcome to your Workbox-powered service worker!\n *\n * You'll need to register this file in your web app.\n * See https://goo.gl/nhQhGp\n *\n * The rest of the code is auto-generated. Please don't update this file\n * directly; instead, make changes to your Workbox build configuration\n * and re-run your build process.\n * See https://goo.gl/2aRDsh\n */\n\n<% if (importScripts) { %>\nimportScripts(\n <%= importScripts.map(JSON.stringify).join(',\\n ') %>\n);\n<% } %>\n\n<% if (navigationPreload) { %><%= use('workbox-navigation-preload', 'enable') %>();<% } %>\n\n<% if (cacheId) { %><%= use('workbox-core', 'setCacheNameDetails') %>({prefix: <%= JSON.stringify(cacheId) %>});<% } %>\n\n<% if (skipWaiting) { %>\nself.skipWaiting();\n<% } else { %>\nself.addEventListener('message', (event) => {\n if (event.data && event.data.type === 'SKIP_WAITING') {\n self.skipWaiting();\n }\n});\n<% } %>\n<% if (clientsClaim) { %><%= use('workbox-core', 'clientsClaim') %>();<% } %>\n\n<% if (Array.isArray(manifestEntries) && manifestEntries.length > 0) {%>\n/**\n * The precacheAndRoute() method efficiently caches and responds to\n * requests for URLs in the manifest.\n * See https://goo.gl/S9QRab\n */\n<%= use('workbox-precaching', 'precacheAndRoute') %>(<%= JSON.stringify(manifestEntries, null, 2) %>, <%= precacheOptionsString %>);\n<% if (cleanupOutdatedCaches) { %><%= use('workbox-precaching', 'cleanupOutdatedCaches') %>();<% } %>\n<% if (navigateFallback) { %><%= use('workbox-routing', 'registerRoute') %>(new <%= use('workbox-routing', 'NavigationRoute') %>(<%= use('workbox-precaching', 'createHandlerBoundToURL') %>(<%= JSON.stringify(navigateFallback) %>)<% if (navigateFallbackAllowlist || navigateFallbackDenylist) { %>, {\n <% if (navigateFallbackAllowlist) { %>allowlist: [<%= navigateFallbackAllowlist %>],<% } %>\n <% if (navigateFallbackDenylist) { %>denylist: [<%= navigateFallbackDenylist %>],<% } %>\n}<% } %>));<% } %>\n<% } %>\n\n<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>\n\n<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %>\n\n<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>";

View File

@@ -0,0 +1,62 @@
"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.swTemplate = void 0;
exports.swTemplate = `/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/
<% if (importScripts) { %>
importScripts(
<%= importScripts.map(JSON.stringify).join(',\\n ') %>
);
<% } %>
<% if (navigationPreload) { %><%= use('workbox-navigation-preload', 'enable') %>();<% } %>
<% if (cacheId) { %><%= use('workbox-core', 'setCacheNameDetails') %>({prefix: <%= JSON.stringify(cacheId) %>});<% } %>
<% if (skipWaiting) { %>
self.skipWaiting();
<% } else { %>
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
self.skipWaiting();
}
});
<% } %>
<% if (clientsClaim) { %><%= use('workbox-core', 'clientsClaim') %>();<% } %>
<% if (Array.isArray(manifestEntries) && manifestEntries.length > 0) {%>
/**
* The precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
<%= use('workbox-precaching', 'precacheAndRoute') %>(<%= JSON.stringify(manifestEntries, null, 2) %>, <%= precacheOptionsString %>);
<% if (cleanupOutdatedCaches) { %><%= use('workbox-precaching', 'cleanupOutdatedCaches') %>();<% } %>
<% if (navigateFallback) { %><%= use('workbox-routing', 'registerRoute') %>(new <%= use('workbox-routing', 'NavigationRoute') %>(<%= use('workbox-precaching', 'createHandlerBoundToURL') %>(<%= JSON.stringify(navigateFallback) %>)<% if (navigateFallbackAllowlist || navigateFallbackDenylist) { %>, {
<% if (navigateFallbackAllowlist) { %>allowlist: [<%= navigateFallbackAllowlist %>],<% } %>
<% if (navigateFallbackDenylist) { %>denylist: [<%= navigateFallbackDenylist %>],<% } %>
}<% } %>));<% } %>
<% } %>
<% if (runtimeCaching) { runtimeCaching.forEach(runtimeCachingString => {%><%= runtimeCachingString %><% });} %>
<% if (offlineAnalyticsConfigString) { %><%= use('workbox-google-analytics', 'initialize') %>(<%= offlineAnalyticsConfigString %>);<% } %>
<% if (disableDevLogs) { %>self.__WB_DISABLE_DEV_LOGS = true;<% } %>`;

528
frontend/node_modules/workbox-build/build/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,528 @@
import { PackageJson } from 'type-fest';
import { BroadcastCacheUpdateOptions } from 'workbox-broadcast-update/BroadcastCacheUpdate';
import { GoogleAnalyticsInitializeOptions } from 'workbox-google-analytics/initialize';
import { HTTPMethod } from 'workbox-routing/utils/constants';
import { QueueOptions } from 'workbox-background-sync/Queue';
import { RouteHandler, RouteMatchCallback } from 'workbox-core/types';
import { CacheableResponseOptions } from 'workbox-cacheable-response/CacheableResponse';
import { ExpirationPluginOptions } from 'workbox-expiration/ExpirationPlugin';
import { WorkboxPlugin } from 'workbox-core/types';
export interface ManifestEntry {
integrity?: string;
revision: string | null;
url: string;
}
export type StrategyName = 'CacheFirst' | 'CacheOnly' | 'NetworkFirst' | 'NetworkOnly' | 'StaleWhileRevalidate';
export interface RuntimeCaching {
/**
* This determines how the runtime route will generate a response.
* To use one of the built-in {@link workbox-strategies}, provide its name,
* like `'NetworkFirst'`.
* Alternatively, this can be a {@link workbox-core.RouteHandler} callback
* function with custom response logic.
*/
handler: RouteHandler | StrategyName;
/**
* The HTTP method to match against. The default value of `'GET'` is normally
* sufficient, unless you explicitly need to match `'POST'`, `'PUT'`, or
* another type of request.
* @default "GET"
*/
method?: HTTPMethod;
options?: {
/**
* Configuring this will add a
* {@link workbox-background-sync.BackgroundSyncPlugin} instance to the
* {@link workbox-strategies} configured in `handler`.
*/
backgroundSync?: {
name: string;
options?: QueueOptions;
};
/**
* Configuring this will add a
* {@link workbox-broadcast-update.BroadcastUpdatePlugin} instance to the
* {@link workbox-strategies} configured in `handler`.
*/
broadcastUpdate?: {
channelName?: string;
options: BroadcastCacheUpdateOptions;
};
/**
* Configuring this will add a
* {@link workbox-cacheable-response.CacheableResponsePlugin} instance to
* the {@link workbox-strategies} configured in `handler`.
*/
cacheableResponse?: CacheableResponseOptions;
/**
* If provided, this will set the `cacheName` property of the
* {@link workbox-strategies} configured in `handler`.
*/
cacheName?: string | null;
/**
* Configuring this will add a
* {@link workbox-expiration.ExpirationPlugin} instance to
* the {@link workbox-strategies} configured in `handler`.
*/
expiration?: ExpirationPluginOptions;
/**
* If provided, this will set the `networkTimeoutSeconds` property of the
* {@link workbox-strategies} configured in `handler`. Note that only
* `'NetworkFirst'` and `'NetworkOnly'` support `networkTimeoutSeconds`.
*/
networkTimeoutSeconds?: number;
/**
* Configuring this allows the use of one or more Workbox plugins that
* don't have "shortcut" options (like `expiration` for
* {@link workbox-expiration.ExpirationPlugin}). The plugins provided here
* will be added to the {@link workbox-strategies} configured in `handler`.
*/
plugins?: Array<WorkboxPlugin>;
/**
* Configuring this will add a
* {@link workbox-precaching.PrecacheFallbackPlugin} instance to
* the {@link workbox-strategies} configured in `handler`.
*/
precacheFallback?: {
fallbackURL: string;
};
/**
* Enabling this will add a
* {@link workbox-range-requests.RangeRequestsPlugin} instance to
* the {@link workbox-strategies} configured in `handler`.
*/
rangeRequests?: boolean;
/**
* Configuring this will pass along the `fetchOptions` value to
* the {@link workbox-strategies} configured in `handler`.
*/
fetchOptions?: RequestInit;
/**
* Configuring this will pass along the `matchOptions` value to
* the {@link workbox-strategies} configured in `handler`.
*/
matchOptions?: CacheQueryOptions;
};
/**
* This match criteria determines whether the configured handler will
* generate a response for any requests that don't match one of the precached
* URLs. If multiple `RuntimeCaching` routes are defined, then the first one
* whose `urlPattern` matches will be the one that responds.
*
* This value directly maps to the first parameter passed to
* {@link workbox-routing.registerRoute}. It's recommended to use a
* {@link workbox-core.RouteMatchCallback} function for greatest flexibility.
*/
urlPattern: RegExp | string | RouteMatchCallback;
}
export interface ManifestTransformResult {
manifest: Array<ManifestEntry & {
size: number;
}>;
warnings?: Array<string>;
}
export type ManifestTransform = (manifestEntries: Array<ManifestEntry & {
size: number;
}>, compilation?: unknown) => Promise<ManifestTransformResult> | ManifestTransformResult;
export interface BasePartial {
/**
* A list of entries to be precached, in addition to any entries that are
* generated as part of the build configuration.
*/
additionalManifestEntries?: Array<string | ManifestEntry>;
/**
* Assets that match this will be assumed to be uniquely versioned via their
* URL, and exempted from the normal HTTP cache-busting that's done when
* populating the precache. While not required, it's recommended that if your
* existing build process already inserts a `[hash]` value into each filename,
* you provide a RegExp that will detect that, as it will reduce the bandwidth
* consumed when precaching.
*/
dontCacheBustURLsMatching?: RegExp;
/**
* One or more functions which will be applied sequentially against the
* generated manifest. If `modifyURLPrefix` or `dontCacheBustURLsMatching` are
* also specified, their corresponding transformations will be applied first.
*/
manifestTransforms?: Array<ManifestTransform>;
/**
* This value can be used to determine the maximum size of files that will be
* precached. This prevents you from inadvertently precaching very large files
* that might have accidentally matched one of your patterns.
* @default 2097152
*/
maximumFileSizeToCacheInBytes?: number;
/**
* An object mapping string prefixes to replacement string values. This can be
* used to, e.g., remove or add a path prefix from a manifest entry if your
* web hosting setup doesn't match your local filesystem setup. As an
* alternative with more flexibility, you can use the `manifestTransforms`
* option and provide a function that modifies the entries in the manifest
* using whatever logic you provide.
*
* Example usage:
*
* ```
* // Replace a '/dist/' prefix with '/', and also prepend
* // '/static' to every URL.
* modifyURLPrefix: {
* '/dist/': '/',
* '': '/static',
* }
* ```
*/
modifyURLPrefix?: {
[key: string]: string;
};
}
export interface GeneratePartial {
/**
* The [targets](https://babeljs.io/docs/en/babel-preset-env#targets) to pass
* to `babel-preset-env` when transpiling the service worker bundle.
* @default ["chrome >= 56"]
*/
babelPresetEnvTargets?: Array<string>;
/**
* An optional ID to be prepended to cache names. This is primarily useful for
* local development where multiple sites may be served from the same
* `http://localhost:port` origin.
*/
cacheId?: string | null;
/**
* Whether or not Workbox should attempt to identify and delete any precaches
* created by older, incompatible versions.
* @default false
*/
cleanupOutdatedCaches?: boolean;
/**
* Whether or not the service worker should [start controlling](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#clientsclaim)
* any existing clients as soon as it activates.
* @default false
*/
clientsClaim?: boolean;
/**
* If a navigation request for a URL ending in `/` fails to match a precached
* URL, this value will be appended to the URL and that will be checked for a
* precache match. This should be set to what your web server is using for its
* directory index.
*/
directoryIndex?: string | null;
/**
* @default false
*/
disableDevLogs?: boolean;
/**
* Any search parameter names that match against one of the RegExp in this
* array will be removed before looking for a precache match. This is useful
* if your users might request URLs that contain, for example, URL parameters
* used to track the source of the traffic. If not provided, the default value
* is `[/^utm_/, /^fbclid$/]`.
*
*/
ignoreURLParametersMatching?: Array<RegExp>;
/**
* A list of JavaScript files that should be passed to
* [`importScripts()`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)
* inside the generated service worker file. This is useful when you want to
* let Workbox create your top-level service worker file, but want to include
* some additional code, such as a push event listener.
*/
importScripts?: Array<string>;
/**
* Whether the runtime code for the Workbox library should be included in the
* top-level service worker, or split into a separate file that needs to be
* deployed alongside the service worker. Keeping the runtime separate means
* that users will not have to re-download the Workbox code each time your
* top-level service worker changes.
* @default false
*/
inlineWorkboxRuntime?: boolean;
/**
* If set to 'production', then an optimized service worker bundle that
* excludes debugging info will be produced. If not explicitly configured
* here, the `process.env.NODE_ENV` value will be used, and failing that, it
* will fall back to `'production'`.
* @default "production"
*/
mode?: string | null;
/**
* If specified, all
* [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests)
* for URLs that aren't precached will be fulfilled with the HTML at the URL
* provided. You must pass in the URL of an HTML document that is listed in
* your precache manifest. This is meant to be used in a Single Page App
* scenario, in which you want all navigations to use common
* [App Shell HTML](https://developers.google.com/web/fundamentals/architecture/app-shell).
* @default null
*/
navigateFallback?: string | null;
/**
* An optional array of regular expressions that restricts which URLs the
* configured `navigateFallback` behavior applies to. This is useful if only a
* subset of your site's URLs should be treated as being part of a
* [Single Page App](https://en.wikipedia.org/wiki/Single-page_application).
* If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
* configured, the denylist takes precedent.
*
* *Note*: These RegExps may be evaluated against every destination URL during
* a navigation. Avoid using
* [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
* or else your users may see delays when navigating your site.
*/
navigateFallbackAllowlist?: Array<RegExp>;
/**
* An optional array of regular expressions that restricts which URLs the
* configured `navigateFallback` behavior applies to. This is useful if only a
* subset of your site's URLs should be treated as being part of a
* [Single Page App](https://en.wikipedia.org/wiki/Single-page_application).
* If both `navigateFallbackDenylist` and `navigateFallbackAllowlist` are
* configured, the denylist takes precedence.
*
* *Note*: These RegExps may be evaluated against every destination URL during
* a navigation. Avoid using
* [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
* or else your users may see delays when navigating your site.
*/
navigateFallbackDenylist?: Array<RegExp>;
/**
* Whether or not to enable
* [navigation preload](https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload)
* in the generated service worker. When set to true, you must also use
* `runtimeCaching` to set up an appropriate response strategy that will match
* navigation requests, and make use of the preloaded response.
* @default false
*/
navigationPreload?: boolean;
/**
* Controls whether or not to include support for
* [offline Google Analytics](https://developers.google.com/web/tools/workbox/guides/enable-offline-analytics).
* When `true`, the call to `workbox-google-analytics`'s `initialize()` will
* be added to your generated service worker. When set to an `Object`, that
* object will be passed in to the `initialize()` call, allowing you to
* customize the behavior.
* @default false
*/
offlineGoogleAnalytics?: boolean | GoogleAnalyticsInitializeOptions;
/**
* When using Workbox's build tools to generate your service worker, you can
* specify one or more runtime caching configurations. These are then
* translated to {@link workbox-routing.registerRoute} calls using the match
* and handler configuration you define.
*
* For all of the options, see the {@link workbox-build.RuntimeCaching}
* documentation. The example below shows a typical configuration, with two
* runtime routes defined:
*
* @example
* runtimeCaching: [{
* urlPattern: ({url}) => url.origin === 'https://api.example.com',
* handler: 'NetworkFirst',
* options: {
* cacheName: 'api-cache',
* },
* }, {
* urlPattern: ({request}) => request.destination === 'image',
* handler: 'StaleWhileRevalidate',
* options: {
* cacheName: 'images-cache',
* expiration: {
* maxEntries: 10,
* },
* },
* }]
*/
runtimeCaching?: Array<RuntimeCaching>;
/**
* Whether to add an unconditional call to [`skipWaiting()`](https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#skip_the_waiting_phase)
* to the generated service worker. If `false`, then a `message` listener will
* be added instead, allowing client pages to trigger `skipWaiting()` by
* calling `postMessage({type: 'SKIP_WAITING'})` on a waiting service worker.
* @default false
*/
skipWaiting?: boolean;
/**
* Whether to create a sourcemap for the generated service worker files.
* @default true
*/
sourcemap?: boolean;
}
export interface RequiredGlobDirectoryPartial {
/**
* The local directory you wish to match `globPatterns` against. The path is
* relative to the current directory.
*/
globDirectory: string;
}
export interface OptionalGlobDirectoryPartial {
/**
* The local directory you wish to match `globPatterns` against. The path is
* relative to the current directory.
*/
globDirectory?: string;
}
export interface GlobPartial {
/**
* Determines whether or not symlinks are followed when generating the
* precache manifest. For more information, see the definition of `follow` in
* the `glob` [documentation](https://github.com/isaacs/node-glob#options).
* @default true
*/
globFollow?: boolean;
/**
* A set of patterns matching files to always exclude when generating the
* precache manifest. For more information, see the definition of `ignore` in
* the `glob` [documentation](https://github.com/isaacs/node-glob#options).
* @default ["**\/node_modules\/**\/*"]
*/
globIgnores?: Array<string>;
/**
* Files matching any of these patterns will be included in the precache
* manifest. For more information, see the
* [`glob` primer](https://github.com/isaacs/node-glob#glob-primer).
* @default ["**\/*.{js,css,html}"]
*/
globPatterns?: Array<string>;
/**
* If true, an error reading a directory when generating a precache manifest
* will cause the build to fail. If false, the problematic directory will be
* skipped. For more information, see the definition of `strict` in the `glob`
* [documentation](https://github.com/isaacs/node-glob#options).
* @default true
*/
globStrict?: boolean;
/**
* If a URL is rendered based on some server-side logic, its contents may
* depend on multiple files or on some other unique string value. The keys in
* this object are server-rendered URLs. If the values are an array of
* strings, they will be interpreted as `glob` patterns, and the contents of
* any files matching the patterns will be used to uniquely version the URL.
* If used with a single string, it will be interpreted as unique versioning
* information that you've generated for a given URL.
*/
templatedURLs?: {
[key: string]: string | Array<string>;
};
}
export interface InjectPartial {
/**
* The string to find inside of the `swSrc` file. Once found, it will be
* replaced by the generated precache manifest.
* @default "self.__WB_MANIFEST"
*/
injectionPoint?: string;
/**
* The path and filename of the service worker file that will be read during
* the build process, relative to the current working directory.
*/
swSrc: string;
}
export interface WebpackPartial {
/**
* One or more chunk names whose corresponding output files should be included
* in the precache manifest.
*/
chunks?: Array<string>;
/**
* One or more specifiers used to exclude assets from the precache manifest.
* This is interpreted following
* [the same rules](https://webpack.js.org/configuration/module/#condition)
* as `webpack`'s standard `exclude` option.
* If not provided, the default value is `[/\.map$/, /^manifest.*\.js$]`.
*/
exclude?: Array<string | RegExp | ((arg0: any) => boolean)>;
/**
* One or more chunk names whose corresponding output files should be excluded
* from the precache manifest.
*/
excludeChunks?: Array<string>;
/**
* One or more specifiers used to include assets in the precache manifest.
* This is interpreted following
* [the same rules](https://webpack.js.org/configuration/module/#condition)
* as `webpack`'s standard `include` option.
*/
include?: Array<string | RegExp | ((arg0: any) => boolean)>;
/**
* If set to 'production', then an optimized service worker bundle that
* excludes debugging info will be produced. If not explicitly configured
* here, the `mode` value configured in the current `webpack` compilation
* will be used.
*/
mode?: string | null;
}
export interface RequiredSWDestPartial {
/**
* The path and filename of the service worker file that will be created by
* the build process, relative to the current working directory. It must end
* in '.js'.
*/
swDest: string;
}
export interface WebpackGenerateSWPartial {
/**
* One or more names of webpack chunks. The content of those chunks will be
* included in the generated service worker, via a call to `importScripts()`.
*/
importScriptsViaChunks?: Array<string>;
/**
* The asset name of the service worker file created by this plugin.
* @default "service-worker.js"
*/
swDest?: string;
}
export interface WebpackInjectManifestPartial {
/**
* When `true` (the default), the `swSrc` file will be compiled by webpack.
* When `false`, compilation will not occur (and `webpackCompilationPlugins`
* can't be used.) Set to `false` if you want to inject the manifest into,
* e.g., a JSON file.
* @default true
*/
compileSrc?: boolean;
/**
* The asset name of the service worker file that will be created by this
* plugin. If omitted, the name will be based on the `swSrc` name.
*/
swDest?: string;
/**
* Optional `webpack` plugins that will be used when compiling the `swSrc`
* input file. Only valid if `compileSrc` is `true`.
*/
webpackCompilationPlugins?: Array<any>;
}
export type GenerateSWOptions = BasePartial & GlobPartial & GeneratePartial & RequiredSWDestPartial & OptionalGlobDirectoryPartial;
export type GetManifestOptions = BasePartial & GlobPartial & RequiredGlobDirectoryPartial;
export type InjectManifestOptions = BasePartial & GlobPartial & InjectPartial & RequiredSWDestPartial & RequiredGlobDirectoryPartial;
export type WebpackGenerateSWOptions = BasePartial & WebpackPartial & GeneratePartial & WebpackGenerateSWPartial;
export type WebpackInjectManifestOptions = BasePartial & WebpackPartial & InjectPartial & WebpackInjectManifestPartial;
export interface GetManifestResult {
count: number;
manifestEntries: Array<ManifestEntry>;
size: number;
warnings: Array<string>;
}
export type BuildResult = Omit<GetManifestResult, 'manifestEntries'> & {
filePaths: Array<string>;
};
/**
* @private
*/
export interface FileDetails {
file: string;
hash: string;
size: number;
}
/**
* @private
*/
export type BuildType = 'dev' | 'prod';
/**
* @private
*/
export interface WorkboxPackageJSON extends PackageJson {
workbox?: {
browserNamespace?: string;
packageType?: string;
prodOnly?: boolean;
};
}

2
frontend/node_modules/workbox-build/build/types.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Apideck
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,71 @@
[![npm (scoped)](https://img.shields.io/npm/v/@apideck/better-ajv-errors?color=brightgreen)](https://npmjs.com/@apideck/better-ajv-errors) [![npm](https://img.shields.io/npm/dm/@apideck/better-ajv-errors)](https://npmjs.com/@apideck/better-ajv-errors) [![GitHub Workflow Status](https://img.shields.io/github/workflow/status/apideck-libraries/better-ajv-errors/CI)](https://github.com/apideck-libraries/better-ajv-errors/actions/workflows/main.yml?query=branch%3Amain++)
# @apideck/better-ajv-errors 👮‍♀️
> Human-friendly JSON Schema validation for APIs
- Readable and helpful [ajv](https://github.com/ajv-validator/ajv) errors
- API-friendly format
- Suggestions for spelling mistakes
- Minimal footprint: 1.56 kB (gzip + minified)
![better-ajv-errors output Example](https://user-images.githubusercontent.com/8850410/118274790-e0529e80-b4c5-11eb-8188-9097c8064c61.png)
## Install
```bash
$ yarn add @apideck/better-ajv-errors
```
or
```bash
$ npm i @apideck/better-ajv-errors
```
Also make sure that you've installed [ajv](https://www.npmjs.com/package/ajv) at version 8 or higher.
## Usage
After validating some data with ajv, pass the errors to `betterAjvErrors`
```ts
import Ajv from 'ajv';
import { betterAjvErrors } from '@apideck/better-ajv-errors';
// Without allErrors: true, ajv will only return the first error
const ajv = new Ajv({ allErrors: true });
const valid = ajv.validate(schema, data);
if (!valid) {
const betterErrors = betterAjvErrors({ schema, data, errors: ajv.errors });
}
```
## API
### betterAjvErrors
Function that formats ajv validation errors in a human-friendly format.
#### Parameters
- `options: BetterAjvErrorsOptions`
- `errors: ErrorObject[] | null | undefined` Your ajv errors, you will find these in the `errors` property of your ajv instance (`ErrorObject` is a type from the ajv package).
- `data: Object` The data you passed to ajv to be validated.
- `schema: JSONSchema` The schema you passed to ajv to validate against.
- `basePath?: string` An optional base path to prefix paths returned by `betterAjvErrors`. For example, in APIs, it could be useful to use `'{requestBody}'` or `'{queryParemeters}'` as a basePath. This will make it clear to users where exactly the error occurred.
#### Return Value
- `ValidationError[]` Array of formatted errors (properties of `ValidationError` below)
- `message: string` Formatted error message
- `suggestion?: string` Optional suggestion based on provided data and schema
- `path: string` Object path where the error occurred (example: `.foo.bar.0.quz`)
- `context: { errorType: DefinedError['keyword']; [additionalContext: string]: unknown }` `errorType` is `error.keyword` proxied from `ajv`. `errorType` can be used as a key for i18n if needed. There might be additional properties on context, based on the type of error.
## Related
- [atlassian/better-ajv-errors](https://github.com/atlassian/better-ajv-errors) was the inspiration for this library. Atlassian's library is more focused on CLI errors, this library is focused on developer-friendly API error messages.

View File

@@ -0,0 +1,246 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var leven = _interopDefault(require('leven'));
var pointer = _interopDefault(require('jsonpointer'));
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
var AJV_ERROR_KEYWORD_WEIGHT_MAP = {
"enum": 1,
type: 0
};
var QUOTES_REGEX = /"/g;
var NOT_REGEX = /NOT/g;
var SLASH_REGEX = /\//g;
var filterSingleErrorPerProperty = function filterSingleErrorPerProperty(errors) {
var errorsPerProperty = errors.reduce(function (acc, error) {
var _ref, _error$params$additio, _error$params, _error$params2, _AJV_ERROR_KEYWORD_WE, _AJV_ERROR_KEYWORD_WE2;
var prop = error.instancePath + ((_ref = (_error$params$additio = (_error$params = error.params) == null ? void 0 : _error$params.additionalProperty) != null ? _error$params$additio : (_error$params2 = error.params) == null ? void 0 : _error$params2.missingProperty) != null ? _ref : '');
var existingError = acc[prop];
if (!existingError) {
acc[prop] = error;
return acc;
}
var weight = (_AJV_ERROR_KEYWORD_WE = AJV_ERROR_KEYWORD_WEIGHT_MAP[error.keyword]) != null ? _AJV_ERROR_KEYWORD_WE : 0;
var existingWeight = (_AJV_ERROR_KEYWORD_WE2 = AJV_ERROR_KEYWORD_WEIGHT_MAP[existingError.keyword]) != null ? _AJV_ERROR_KEYWORD_WE2 : 0;
if (weight > existingWeight) {
acc[prop] = error;
}
return acc;
}, {});
return Object.values(errorsPerProperty);
};
var getSuggestion = function getSuggestion(_ref) {
var value = _ref.value,
suggestions = _ref.suggestions,
_ref$format = _ref.format,
format = _ref$format === void 0 ? function (suggestion) {
return "Did you mean '" + suggestion + "'?";
} : _ref$format;
if (!value) return '';
var bestSuggestion = suggestions.reduce(function (best, current) {
var distance = leven(value, current);
if (best.distance > distance) {
return {
value: current,
distance: distance
};
}
return best;
}, {
distance: Infinity,
value: ''
});
return bestSuggestion.distance < value.length ? format(bestSuggestion.value) : '';
};
var pointerToDotNotation = function pointerToDotNotation(pointer) {
return pointer.replace(SLASH_REGEX, '.');
};
var cleanAjvMessage = function cleanAjvMessage(message) {
return message.replace(QUOTES_REGEX, "'").replace(NOT_REGEX, 'not');
};
var getLastSegment = function getLastSegment(path) {
var segments = path.split('/');
return segments.pop();
};
var safeJsonPointer = function safeJsonPointer(_ref) {
var object = _ref.object,
pnter = _ref.pnter,
fallback = _ref.fallback;
try {
return pointer.get(object, pnter);
} catch (err) {
return fallback;
}
};
var betterAjvErrors = function betterAjvErrors(_ref) {
var errors = _ref.errors,
data = _ref.data,
schema = _ref.schema,
_ref$basePath = _ref.basePath,
basePath = _ref$basePath === void 0 ? '{base}' : _ref$basePath;
if (!Array.isArray(errors) || errors.length === 0) {
return [];
}
var definedErrors = filterSingleErrorPerProperty(errors);
return definedErrors.map(function (error) {
var path = pointerToDotNotation(basePath + error.instancePath);
var prop = getLastSegment(error.instancePath);
var defaultContext = {
errorType: error.keyword
};
var defaultMessage = (prop ? "property '" + prop + "'" : path) + " " + cleanAjvMessage(error.message);
var validationError;
switch (error.keyword) {
case 'additionalProperties':
{
var additionalProp = error.params.additionalProperty;
var suggestionPointer = error.schemaPath.replace('#', '').replace('/additionalProperties', '');
var _safeJsonPointer = safeJsonPointer({
object: schema,
pnter: suggestionPointer,
fallback: {
properties: {}
}
}),
properties = _safeJsonPointer.properties;
validationError = {
message: "'" + additionalProp + "' property is not expected to be here",
suggestion: getSuggestion({
value: additionalProp,
suggestions: Object.keys(properties != null ? properties : {}),
format: function format(suggestion) {
return "Did you mean property '" + suggestion + "'?";
}
}),
path: path,
context: defaultContext
};
break;
}
case 'enum':
{
var suggestions = error.params.allowedValues.map(function (value) {
return value.toString();
});
var _prop = getLastSegment(error.instancePath);
var value = safeJsonPointer({
object: data,
pnter: error.instancePath,
fallback: ''
});
validationError = {
message: "'" + _prop + "' property must be equal to one of the allowed values",
suggestion: getSuggestion({
value: value,
suggestions: suggestions
}),
path: path,
context: _extends({}, defaultContext, {
allowedValues: error.params.allowedValues
})
};
break;
}
case 'type':
{
var _prop2 = getLastSegment(error.instancePath);
var type = error.params.type;
validationError = {
message: "'" + _prop2 + "' property type must be " + type,
path: path,
context: defaultContext
};
break;
}
case 'required':
{
validationError = {
message: path + " must have required property '" + error.params.missingProperty + "'",
path: path,
context: defaultContext
};
break;
}
case 'const':
{
return {
message: "'" + prop + "' property must be equal to the allowed value",
path: path,
context: _extends({}, defaultContext, {
allowedValue: error.params.allowedValue
})
};
}
default:
return {
message: defaultMessage,
path: path,
context: defaultContext
};
} // Remove empty properties
var errorEntries = Object.entries(validationError);
for (var _i = 0, _errorEntries = errorEntries; _i < _errorEntries.length; _i++) {
var _errorEntries$_i = _errorEntries[_i],
key = _errorEntries$_i[0],
_value = _errorEntries$_i[1];
if (_value === null || _value === undefined || _value === '') {
delete validationError[key];
}
}
return validationError;
});
};
exports.betterAjvErrors = betterAjvErrors;
//# sourceMappingURL=better-ajv-errors.cjs.development.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var t=e(require("leven")),r=e(require("jsonpointer"));function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(e[a]=r[a])}return e}).apply(this,arguments)}var n={enum:1,type:0},o=/"/g,s=/NOT/g,u=/\//g,l=function(e){var r=e.value,a=e.format,n=void 0===a?function(e){return"Did you mean '"+e+"'?"}:a;if(!r)return"";var o=e.suggestions.reduce((function(e,a){var n=t(r,a);return e.distance>n?{value:a,distance:n}:e}),{distance:Infinity,value:""});return o.distance<r.length?n(o.value):""},i=function(e){return e.split("/").pop()},p=function(e){var t=e.object,a=e.pnter,n=e.fallback;try{return r.get(t,a)}catch(e){return n}};exports.betterAjvErrors=function(e){var t=e.errors,r=e.data,c=e.schema,d=e.basePath,v=void 0===d?"{base}":d;return Array.isArray(t)&&0!==t.length?function(e){var t=e.reduce((function(e,t){var r,a,o,s,u,l,i=t.instancePath+(null!=(r=null!=(a=null==(o=t.params)?void 0:o.additionalProperty)?a:null==(s=t.params)?void 0:s.missingProperty)?r:""),p=e[i];return p?((null!=(u=n[t.keyword])?u:0)>(null!=(l=n[p.keyword])?l:0)&&(e[i]=t),e):(e[i]=t,e)}),{});return Object.values(t)}(t).map((function(e){var t,n=function(e){return e.replace(u,".")}(v+e.instancePath),d=i(e.instancePath),y={errorType:e.keyword},f=(d?"property '"+d+"'":n)+" "+e.message.replace(o,"'").replace(s,"not");switch(e.keyword){case"additionalProperties":var m=e.params.additionalProperty,g=e.schemaPath.replace("#","").replace("/additionalProperties",""),h=p({object:c,pnter:g,fallback:{properties:{}}}).properties;t={message:"'"+m+"' property is not expected to be here",suggestion:l({value:m,suggestions:Object.keys(null!=h?h:{}),format:function(e){return"Did you mean property '"+e+"'?"}}),path:n,context:y};break;case"enum":var b=e.params.allowedValues.map((function(e){return e.toString()})),P=i(e.instancePath),w=p({object:r,pnter:e.instancePath,fallback:""});t={message:"'"+P+"' property must be equal to one of the allowed values",suggestion:l({value:w,suggestions:b}),path:n,context:a({},y,{allowedValues:e.params.allowedValues})};break;case"type":t={message:"'"+i(e.instancePath)+"' property type must be "+e.params.type,path:n,context:y};break;case"required":t={message:n+" must have required property '"+e.params.missingProperty+"'",path:n,context:y};break;case"const":return{message:"'"+d+"' property must be equal to the allowed value",path:n,context:a({},y,{allowedValue:e.params.allowedValue})};default:return{message:f,path:n,context:y}}for(var j=0,k=Object.entries(t);j<k.length;j++){var x=k[j],O=x[1];null!=O&&""!==O||delete t[x[0]]}return t})):[]};
//# sourceMappingURL=better-ajv-errors.cjs.production.min.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,240 @@
import leven from 'leven';
import pointer from 'jsonpointer';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
var AJV_ERROR_KEYWORD_WEIGHT_MAP = {
"enum": 1,
type: 0
};
var QUOTES_REGEX = /"/g;
var NOT_REGEX = /NOT/g;
var SLASH_REGEX = /\//g;
var filterSingleErrorPerProperty = function filterSingleErrorPerProperty(errors) {
var errorsPerProperty = errors.reduce(function (acc, error) {
var _ref, _error$params$additio, _error$params, _error$params2, _AJV_ERROR_KEYWORD_WE, _AJV_ERROR_KEYWORD_WE2;
var prop = error.instancePath + ((_ref = (_error$params$additio = (_error$params = error.params) == null ? void 0 : _error$params.additionalProperty) != null ? _error$params$additio : (_error$params2 = error.params) == null ? void 0 : _error$params2.missingProperty) != null ? _ref : '');
var existingError = acc[prop];
if (!existingError) {
acc[prop] = error;
return acc;
}
var weight = (_AJV_ERROR_KEYWORD_WE = AJV_ERROR_KEYWORD_WEIGHT_MAP[error.keyword]) != null ? _AJV_ERROR_KEYWORD_WE : 0;
var existingWeight = (_AJV_ERROR_KEYWORD_WE2 = AJV_ERROR_KEYWORD_WEIGHT_MAP[existingError.keyword]) != null ? _AJV_ERROR_KEYWORD_WE2 : 0;
if (weight > existingWeight) {
acc[prop] = error;
}
return acc;
}, {});
return Object.values(errorsPerProperty);
};
var getSuggestion = function getSuggestion(_ref) {
var value = _ref.value,
suggestions = _ref.suggestions,
_ref$format = _ref.format,
format = _ref$format === void 0 ? function (suggestion) {
return "Did you mean '" + suggestion + "'?";
} : _ref$format;
if (!value) return '';
var bestSuggestion = suggestions.reduce(function (best, current) {
var distance = leven(value, current);
if (best.distance > distance) {
return {
value: current,
distance: distance
};
}
return best;
}, {
distance: Infinity,
value: ''
});
return bestSuggestion.distance < value.length ? format(bestSuggestion.value) : '';
};
var pointerToDotNotation = function pointerToDotNotation(pointer) {
return pointer.replace(SLASH_REGEX, '.');
};
var cleanAjvMessage = function cleanAjvMessage(message) {
return message.replace(QUOTES_REGEX, "'").replace(NOT_REGEX, 'not');
};
var getLastSegment = function getLastSegment(path) {
var segments = path.split('/');
return segments.pop();
};
var safeJsonPointer = function safeJsonPointer(_ref) {
var object = _ref.object,
pnter = _ref.pnter,
fallback = _ref.fallback;
try {
return pointer.get(object, pnter);
} catch (err) {
return fallback;
}
};
var betterAjvErrors = function betterAjvErrors(_ref) {
var errors = _ref.errors,
data = _ref.data,
schema = _ref.schema,
_ref$basePath = _ref.basePath,
basePath = _ref$basePath === void 0 ? '{base}' : _ref$basePath;
if (!Array.isArray(errors) || errors.length === 0) {
return [];
}
var definedErrors = filterSingleErrorPerProperty(errors);
return definedErrors.map(function (error) {
var path = pointerToDotNotation(basePath + error.instancePath);
var prop = getLastSegment(error.instancePath);
var defaultContext = {
errorType: error.keyword
};
var defaultMessage = (prop ? "property '" + prop + "'" : path) + " " + cleanAjvMessage(error.message);
var validationError;
switch (error.keyword) {
case 'additionalProperties':
{
var additionalProp = error.params.additionalProperty;
var suggestionPointer = error.schemaPath.replace('#', '').replace('/additionalProperties', '');
var _safeJsonPointer = safeJsonPointer({
object: schema,
pnter: suggestionPointer,
fallback: {
properties: {}
}
}),
properties = _safeJsonPointer.properties;
validationError = {
message: "'" + additionalProp + "' property is not expected to be here",
suggestion: getSuggestion({
value: additionalProp,
suggestions: Object.keys(properties != null ? properties : {}),
format: function format(suggestion) {
return "Did you mean property '" + suggestion + "'?";
}
}),
path: path,
context: defaultContext
};
break;
}
case 'enum':
{
var suggestions = error.params.allowedValues.map(function (value) {
return value.toString();
});
var _prop = getLastSegment(error.instancePath);
var value = safeJsonPointer({
object: data,
pnter: error.instancePath,
fallback: ''
});
validationError = {
message: "'" + _prop + "' property must be equal to one of the allowed values",
suggestion: getSuggestion({
value: value,
suggestions: suggestions
}),
path: path,
context: _extends({}, defaultContext, {
allowedValues: error.params.allowedValues
})
};
break;
}
case 'type':
{
var _prop2 = getLastSegment(error.instancePath);
var type = error.params.type;
validationError = {
message: "'" + _prop2 + "' property type must be " + type,
path: path,
context: defaultContext
};
break;
}
case 'required':
{
validationError = {
message: path + " must have required property '" + error.params.missingProperty + "'",
path: path,
context: defaultContext
};
break;
}
case 'const':
{
return {
message: "'" + prop + "' property must be equal to the allowed value",
path: path,
context: _extends({}, defaultContext, {
allowedValue: error.params.allowedValue
})
};
}
default:
return {
message: defaultMessage,
path: path,
context: defaultContext
};
} // Remove empty properties
var errorEntries = Object.entries(validationError);
for (var _i = 0, _errorEntries = errorEntries; _i < _errorEntries.length; _i++) {
var _errorEntries$_i = _errorEntries[_i],
key = _errorEntries$_i[0],
_value = _errorEntries$_i[1];
if (_value === null || _value === undefined || _value === '') {
delete validationError[key];
}
}
return validationError;
});
};
export { betterAjvErrors };
//# sourceMappingURL=better-ajv-errors.esm.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,5 @@
import { DefinedError } from 'ajv';
export declare const AJV_ERROR_KEYWORD_WEIGHT_MAP: Partial<Record<DefinedError['keyword'], number>>;
export declare const QUOTES_REGEX: RegExp;
export declare const NOT_REGEX: RegExp;
export declare const SLASH_REGEX: RegExp;

View File

@@ -0,0 +1,11 @@
import { ErrorObject } from 'ajv';
import type { JSONSchema6 } from 'json-schema';
import { ValidationError } from './types/ValidationError';
export interface BetterAjvErrorsOptions {
errors: ErrorObject[] | null | undefined;
data: any;
schema: JSONSchema6;
basePath?: string;
}
export declare const betterAjvErrors: ({ errors, data, schema, basePath, }: BetterAjvErrorsOptions) => ValidationError[];
export { ValidationError };

View File

@@ -0,0 +1,8 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./better-ajv-errors.cjs.production.min.js')
} else {
module.exports = require('./better-ajv-errors.cjs.development.js')
}

View File

@@ -0,0 +1,2 @@
import { DefinedError } from 'ajv';
export declare const filterSingleErrorPerProperty: (errors: DefinedError[]) => DefinedError[];

View File

@@ -0,0 +1,5 @@
export declare const getSuggestion: ({ value, suggestions, format, }: {
value: string | null;
suggestions: string[];
format?: ((suggestion: string) => string) | undefined;
}) => string;

View File

@@ -0,0 +1,8 @@
export declare const pointerToDotNotation: (pointer: string) => string;
export declare const cleanAjvMessage: (message: string) => string;
export declare const getLastSegment: (path: string) => string;
export declare const safeJsonPointer: <T>({ object, pnter, fallback }: {
object: any;
pnter: string;
fallback: T;
}) => T;

View File

@@ -0,0 +1,10 @@
import { DefinedError } from 'ajv';
export interface ValidationError {
message: string;
path: string;
suggestion?: string;
context: {
errorType: DefinedError['keyword'];
[additionalContext: string]: unknown;
};
}

View File

@@ -0,0 +1,88 @@
{
"name": "@apideck/better-ajv-errors",
"description": "Human-friendly JSON Schema validation for APIs",
"version": "0.3.6",
"author": "Apideck <support@apideck.com> (https://apideck.com/)",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/apideck-libraries/better-ajv-errors"
},
"bugs": {
"url": "https://github.com/apideck-libraries/better-ajv-errors/issues"
},
"contributors": [
"Elias Meire <elias@apideck.com>"
],
"main": "dist/index.js",
"module": "dist/better-ajv-errors.esm.js",
"typings": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"scripts": {
"start": "tsdx watch",
"build": "tsdx build",
"test": "tsdx test",
"lint": "tsdx lint",
"prepare": "tsdx build",
"size": "size-limit",
"release": "np --no-publish && npm publish --access public --registry https://registry.npmjs.org",
"analyze": "size-limit --why"
},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 120,
"singleQuote": true,
"trailingComma": "es5"
},
"size-limit": [
{
"path": "dist/better-ajv-errors.cjs.production.min.js",
"limit": "2 KB"
},
{
"path": "dist/better-ajv-errors.esm.js",
"limit": "2.5 KB"
}
],
"devDependencies": {
"@size-limit/preset-small-lib": "^7.0.8",
"ajv": "^8.11.0",
"eslint-plugin-prettier": "^4.0.0",
"husky": "^8.0.1",
"np": "^7.6.1",
"size-limit": "^7.0.8",
"tsdx": "^0.14.1",
"tslib": "^2.4.0",
"typescript": "^4.7.2"
},
"peerDependencies": {
"ajv": ">=8"
},
"dependencies": {
"json-schema": "^0.4.0",
"jsonpointer": "^5.0.0",
"leven": "^3.1.0"
},
"resolutions": {
"prettier": "^2.3.0"
},
"keywords": [
"apideck",
"ajv",
"json",
"schema",
"json-schema",
"errors",
"human"
]
}

View File

@@ -0,0 +1,10 @@
import { DefinedError } from 'ajv';
export const AJV_ERROR_KEYWORD_WEIGHT_MAP: Partial<Record<DefinedError['keyword'], number>> = {
enum: 1,
type: 0,
};
export const QUOTES_REGEX = /"/g;
export const NOT_REGEX = /NOT/g;
export const SLASH_REGEX = /\//g;

View File

@@ -0,0 +1,434 @@
import Ajv from 'ajv';
import { JSONSchema6 } from 'json-schema';
import { betterAjvErrors } from './index';
describe('betterAjvErrors', () => {
let ajv: Ajv;
let schema: JSONSchema6;
let data: Record<string, unknown>;
beforeEach(() => {
ajv = new Ajv({ allErrors: true });
schema = {
type: 'object',
required: ['str'],
properties: {
str: {
type: 'string',
},
enum: {
type: 'string',
enum: ['one', 'two'],
},
bounds: {
type: 'number',
minimum: 2,
maximum: 4,
},
nested: {
type: 'object',
required: ['deepReq'],
properties: {
deepReq: {
type: 'boolean',
},
deep: {
type: 'string',
},
},
additionalProperties: false,
},
},
additionalProperties: false,
};
});
describe('additionalProperties', () => {
it('should handle additionalProperties=false', () => {
data = {
str: 'str',
foo: 'bar',
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'additionalProperties',
},
message: "'foo' property is not expected to be here",
path: '{base}',
},
]);
});
it('should handle additionalProperties=true', () => {
data = {
str: 'str',
foo: 'bar',
};
schema.additionalProperties = true;
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([]);
});
it('should give suggestions when relevant', () => {
data = {
str: 'str',
bonds: 'bar',
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'additionalProperties',
},
message: "'bonds' property is not expected to be here",
path: '{base}',
suggestion: "Did you mean property 'bounds'?",
},
]);
});
it('should handle object schemas without properties', () => {
data = {
empty: { foo: 1 },
};
schema = {
type: 'object',
properties: {
empty: {
type: 'object',
additionalProperties: false,
},
},
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'additionalProperties',
},
message: "'foo' property is not expected to be here",
path: '{base}.empty',
},
]);
});
});
describe('required', () => {
it('should handle required properties', () => {
data = {
nested: {},
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'required',
},
message: "{base} must have required property 'str'",
path: '{base}',
},
{
context: {
errorType: 'required',
},
message: "{base}.nested must have required property 'deepReq'",
path: '{base}.nested',
},
]);
});
it('should handle multiple required properties', () => {
schema = {
type: 'object',
required: ['req1', 'req2'],
properties: {
req1: {
type: 'string',
},
req2: {
type: 'string',
},
},
};
data = {};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'required',
},
message: "{base} must have required property 'req1'",
path: '{base}',
},
{
context: {
errorType: 'required',
},
message: "{base} must have required property 'req2'",
path: '{base}',
},
]);
});
});
describe('type', () => {
it('should handle type errors', () => {
data = {
str: 123,
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'type',
},
message: "'str' property type must be string",
path: '{base}.str',
},
]);
});
});
describe('minimum/maximum', () => {
it('should handle minimum/maximum errors', () => {
data = {
str: 'str',
bounds: 123,
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'maximum',
},
message: "property 'bounds' must be <= 4",
path: '{base}.bounds',
},
]);
});
});
describe('enum', () => {
it('should handle enum errors', () => {
data = {
str: 'str',
enum: 'zzzz',
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'enum',
allowedValues: ['one', 'two'],
},
message: "'enum' property must be equal to one of the allowed values",
path: '{base}.enum',
},
]);
});
it('should provide suggestions when relevant', () => {
data = {
str: 'str',
enum: 'pne',
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'enum',
allowedValues: ['one', 'two'],
},
message: "'enum' property must be equal to one of the allowed values",
path: '{base}.enum',
suggestion: "Did you mean 'one'?",
},
]);
});
it('should not crash on null value', () => {
data = {
type: null,
};
schema = {
type: 'object',
properties: {
type: {
type: 'string',
enum: ['primary', 'secondary'],
},
},
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
allowedValues: ['primary', 'secondary'],
errorType: 'enum',
},
message: "'type' property must be equal to one of the allowed values",
path: '{base}.type',
},
]);
});
});
it('should handle array paths', () => {
data = {
custom: [{ foo: 'bar' }, { aaa: 'zzz' }],
};
schema = {
type: 'object',
properties: {
custom: {
type: 'array',
items: {
type: 'object',
additionalProperties: false,
properties: {
id: {
type: 'string',
},
title: {
type: 'string',
},
},
},
},
},
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'additionalProperties',
},
message: "'foo' property is not expected to be here",
path: '{base}.custom.0',
},
{
context: {
errorType: 'additionalProperties',
},
message: "'aaa' property is not expected to be here",
path: '{base}.custom.1',
},
]);
});
it('should handle file $refs', () => {
data = {
child: [{ foo: 'bar' }, { aaa: 'zzz' }],
};
schema = {
$id: 'http://example.com/schemas/Main.json',
type: 'object',
properties: {
child: {
type: 'array',
items: {
$ref: './Child.json',
},
},
},
};
ajv.addSchema({
$id: 'http://example.com/schemas/Child.json',
additionalProperties: false,
type: 'object',
properties: {
id: {
type: 'string',
},
},
});
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
errorType: 'additionalProperties',
},
message: "'foo' property is not expected to be here",
path: '{base}.child.0',
},
{
context: {
errorType: 'additionalProperties',
},
message: "'aaa' property is not expected to be here",
path: '{base}.child.1',
},
]);
});
it('should handle number enums', () => {
data = {
isLive: 2,
};
schema = {
type: 'object',
properties: {
isLive: {
type: 'integer',
enum: [0, 1],
},
},
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
allowedValues: [0, 1],
errorType: 'enum',
},
message: "'isLive' property must be equal to one of the allowed values",
path: '{base}.isLive',
},
]);
});
describe('const', () => {
it('should handle const errors', () => {
data = {
const: 2,
};
schema = {
type: 'object',
properties: {
const: {
type: 'integer',
const: 42,
},
},
};
ajv.validate(schema, data);
const errors = betterAjvErrors({ data, schema, errors: ajv.errors });
expect(errors).toEqual([
{
context: {
allowedValue: 42,
errorType: 'const',
},
message: "'const' property must be equal to the allowed value",
path: '{base}.const',
},
]);
});
});
});

View File

@@ -0,0 +1,121 @@
import { DefinedError, ErrorObject } from 'ajv';
import type { JSONSchema6 } from 'json-schema';
import { ValidationError } from './types/ValidationError';
import { filterSingleErrorPerProperty } from './lib/filter';
import { getSuggestion } from './lib/suggestions';
import { cleanAjvMessage, getLastSegment, pointerToDotNotation, safeJsonPointer } from './lib/utils';
export interface BetterAjvErrorsOptions {
errors: ErrorObject[] | null | undefined;
data: any;
schema: JSONSchema6;
basePath?: string;
}
export const betterAjvErrors = ({
errors,
data,
schema,
basePath = '{base}',
}: BetterAjvErrorsOptions): ValidationError[] => {
if (!Array.isArray(errors) || errors.length === 0) {
return [];
}
const definedErrors = filterSingleErrorPerProperty(errors as DefinedError[]);
return definedErrors.map((error) => {
const path = pointerToDotNotation(basePath + error.instancePath);
const prop = getLastSegment(error.instancePath);
const defaultContext = {
errorType: error.keyword,
};
const defaultMessage = `${prop ? `property '${prop}'` : path} ${cleanAjvMessage(error.message as string)}`;
let validationError: ValidationError;
switch (error.keyword) {
case 'additionalProperties': {
const additionalProp = error.params.additionalProperty;
const suggestionPointer = error.schemaPath.replace('#', '').replace('/additionalProperties', '');
const { properties } = safeJsonPointer({
object: schema,
pnter: suggestionPointer,
fallback: { properties: {} },
});
validationError = {
message: `'${additionalProp}' property is not expected to be here`,
suggestion: getSuggestion({
value: additionalProp,
suggestions: Object.keys(properties ?? {}),
format: (suggestion) => `Did you mean property '${suggestion}'?`,
}),
path,
context: defaultContext,
};
break;
}
case 'enum': {
const suggestions = error.params.allowedValues.map((value) => value.toString());
const prop = getLastSegment(error.instancePath);
const value = safeJsonPointer({ object: data, pnter: error.instancePath, fallback: '' });
validationError = {
message: `'${prop}' property must be equal to one of the allowed values`,
suggestion: getSuggestion({
value,
suggestions,
}),
path,
context: {
...defaultContext,
allowedValues: error.params.allowedValues,
},
};
break;
}
case 'type': {
const prop = getLastSegment(error.instancePath);
const type = error.params.type;
validationError = {
message: `'${prop}' property type must be ${type}`,
path,
context: defaultContext,
};
break;
}
case 'required': {
validationError = {
message: `${path} must have required property '${error.params.missingProperty}'`,
path,
context: defaultContext,
};
break;
}
case 'const': {
return {
message: `'${prop}' property must be equal to the allowed value`,
path,
context: {
...defaultContext,
allowedValue: error.params.allowedValue,
},
};
}
default:
return { message: defaultMessage, path, context: defaultContext };
}
// Remove empty properties
const errorEntries = Object.entries(validationError);
for (const [key, value] of errorEntries as [keyof ValidationError, unknown][]) {
if (value === null || value === undefined || value === '') {
delete validationError[key];
}
}
return validationError;
});
};
export { ValidationError };

View File

@@ -0,0 +1,23 @@
import { DefinedError } from 'ajv';
import { AJV_ERROR_KEYWORD_WEIGHT_MAP } from '../constants';
export const filterSingleErrorPerProperty = (errors: DefinedError[]): DefinedError[] => {
const errorsPerProperty = errors.reduce<Record<string, DefinedError>>((acc, error) => {
const prop =
error.instancePath + ((error.params as any)?.additionalProperty ?? (error.params as any)?.missingProperty ?? '');
const existingError = acc[prop];
if (!existingError) {
acc[prop] = error;
return acc;
}
const weight = AJV_ERROR_KEYWORD_WEIGHT_MAP[error.keyword] ?? 0;
const existingWeight = AJV_ERROR_KEYWORD_WEIGHT_MAP[existingError.keyword] ?? 0;
if (weight > existingWeight) {
acc[prop] = error;
}
return acc;
}, {});
return Object.values(errorsPerProperty);
};

View File

@@ -0,0 +1,29 @@
import leven from 'leven';
export const getSuggestion = ({
value,
suggestions,
format = (suggestion) => `Did you mean '${suggestion}'?`,
}: {
value: string | null;
suggestions: string[];
format?: (suggestion: string) => string;
}): string => {
if (!value) return '';
const bestSuggestion = suggestions.reduce(
(best, current) => {
const distance = leven(value, current);
if (best.distance > distance) {
return { value: current, distance };
}
return best;
},
{
distance: Infinity,
value: '',
}
);
return bestSuggestion.distance < value.length ? format(bestSuggestion.value) : '';
};

View File

@@ -0,0 +1,23 @@
import { NOT_REGEX, QUOTES_REGEX, SLASH_REGEX } from '../constants';
import pointer from 'jsonpointer';
export const pointerToDotNotation = (pointer: string): string => {
return pointer.replace(SLASH_REGEX, '.');
};
export const cleanAjvMessage = (message: string): string => {
return message.replace(QUOTES_REGEX, "'").replace(NOT_REGEX, 'not');
};
export const getLastSegment = (path: string): string => {
const segments = path.split('/');
return segments.pop() as string;
};
export const safeJsonPointer = <T>({ object, pnter, fallback }: { object: any; pnter: string; fallback: T }): T => {
try {
return pointer.get(object, pnter);
} catch (err) {
return fallback;
}
};

View File

@@ -0,0 +1,11 @@
import { DefinedError } from 'ajv';
export interface ValidationError {
message: string;
path: string;
suggestion?: string;
context: {
errorType: DefinedError['keyword'];
[additionalContext: string]: unknown;
};
}

View File

@@ -0,0 +1,23 @@
const Ajv = require("ajv")
const ajv = new Ajv({allErrors: true})
const schema = {
type: "object",
properties: {
foo: {type: "string"},
bar: {type: "number", maximum: 3},
},
required: ["foo", "bar"],
additionalProperties: false,
}
const validate = ajv.compile(schema)
test({foo: "abc", bar: 2})
test({foo: 2, bar: 4})
function test(data) {
const valid = validate(data)
if (valid) console.log("Valid!")
else console.log("Invalid: " + ajv.errorsText(validate.errors))
}

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015-2021 Evgeny Poberezkin
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.

Some files were not shown because too many files have changed in this diff Show More