@serwist/build 8.4.4 → 9.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/chunks/getManifest.js +6 -0
  2. package/dist/chunks/glob.js +58 -0
  3. package/dist/chunks/injectManifest.js +23 -0
  4. package/dist/chunks/serwist-config-error.js +54 -0
  5. package/dist/chunks/vite.js +7 -0
  6. package/dist/chunks/webpack.js +34 -0
  7. package/dist/get-manifest.d.ts +2 -1
  8. package/dist/get-manifest.d.ts.map +1 -0
  9. package/dist/index.d.ts +2 -1
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +54 -1014
  12. package/dist/index.next.d.ts +3 -0
  13. package/dist/index.next.d.ts.map +1 -0
  14. package/dist/index.next.js +38 -0
  15. package/dist/inject-manifest.d.ts +2 -1
  16. package/dist/inject-manifest.d.ts.map +1 -0
  17. package/dist/lib/additional-precache-entries-transform.d.ts +6 -5
  18. package/dist/lib/additional-precache-entries-transform.d.ts.map +1 -0
  19. package/dist/lib/errors.d.ts +1 -2
  20. package/dist/lib/errors.d.ts.map +1 -0
  21. package/dist/lib/escape-regexp.d.ts +2 -1
  22. package/dist/lib/escape-regexp.d.ts.map +1 -0
  23. package/dist/lib/get-composite-details.d.ts +2 -1
  24. package/dist/lib/get-composite-details.d.ts.map +1 -0
  25. package/dist/lib/get-file-details.d.ts +2 -1
  26. package/dist/lib/get-file-details.d.ts.map +1 -0
  27. package/dist/lib/get-file-hash.d.ts +1 -0
  28. package/dist/lib/get-file-hash.d.ts.map +1 -0
  29. package/dist/lib/get-file-manifest-entries.d.ts +1 -0
  30. package/dist/lib/get-file-manifest-entries.d.ts.map +1 -0
  31. package/dist/lib/get-file-size.d.ts +1 -0
  32. package/dist/lib/get-file-size.d.ts.map +1 -0
  33. package/dist/lib/get-source-map-url.d.ts +1 -0
  34. package/dist/lib/get-source-map-url.d.ts.map +1 -0
  35. package/dist/lib/get-string-details.d.ts +1 -0
  36. package/dist/lib/get-string-details.d.ts.map +1 -0
  37. package/dist/lib/get-string-hash.d.ts +1 -0
  38. package/dist/lib/get-string-hash.d.ts.map +1 -0
  39. package/dist/lib/maximum-size-transform.d.ts +1 -0
  40. package/dist/lib/maximum-size-transform.d.ts.map +1 -0
  41. package/dist/lib/modify-url-prefix-transform.d.ts +1 -0
  42. package/dist/lib/modify-url-prefix-transform.d.ts.map +1 -0
  43. package/dist/lib/no-revision-for-urls-matching-transform.d.ts +1 -0
  44. package/dist/lib/no-revision-for-urls-matching-transform.d.ts.map +1 -0
  45. package/dist/lib/rebase-path.d.ts +1 -0
  46. package/dist/lib/rebase-path.d.ts.map +1 -0
  47. package/dist/lib/replace-and-update-source-map.d.ts +1 -0
  48. package/dist/lib/replace-and-update-source-map.d.ts.map +1 -0
  49. package/dist/lib/serwist-config-error.d.ts +7 -0
  50. package/dist/lib/serwist-config-error.d.ts.map +1 -0
  51. package/dist/lib/transform-manifest.d.ts +2 -1
  52. package/dist/lib/transform-manifest.d.ts.map +1 -0
  53. package/dist/lib/translate-url-to-sourcemap-paths.d.ts +1 -0
  54. package/dist/lib/translate-url-to-sourcemap-paths.d.ts.map +1 -0
  55. package/dist/lib/validate-next-options.d.ts +3 -0
  56. package/dist/lib/validate-next-options.d.ts.map +1 -0
  57. package/dist/lib/validate-options.d.ts +6 -8
  58. package/dist/lib/validate-options.d.ts.map +1 -0
  59. package/dist/schema/assertType.d.ts +3 -0
  60. package/dist/schema/assertType.d.ts.map +1 -0
  61. package/dist/schema/base.d.ts +169 -0
  62. package/dist/schema/base.d.ts.map +1 -0
  63. package/dist/schema/getManifest.d.ts +187 -0
  64. package/dist/schema/getManifest.d.ts.map +1 -0
  65. package/dist/schema/glob.d.ts +35 -0
  66. package/dist/schema/glob.d.ts.map +1 -0
  67. package/dist/schema/injectManifest.d.ts +206 -0
  68. package/dist/schema/injectManifest.d.ts.map +1 -0
  69. package/dist/schema/manifestEntry.d.ts +15 -0
  70. package/dist/schema/manifestEntry.d.ts.map +1 -0
  71. package/dist/schema/manifestTransform.d.ts +121 -0
  72. package/dist/schema/manifestTransform.d.ts.map +1 -0
  73. package/dist/schema/next.d.ts +243 -0
  74. package/dist/schema/next.d.ts.map +1 -0
  75. package/dist/schema/swDest.d.ts +16 -0
  76. package/dist/schema/swDest.d.ts.map +1 -0
  77. package/dist/schema/validationErrorMap.d.ts +3 -0
  78. package/dist/schema/validationErrorMap.d.ts.map +1 -0
  79. package/dist/schema/vite.d.ts +196 -0
  80. package/dist/schema/vite.d.ts.map +1 -0
  81. package/dist/schema/webpack.d.ts +231 -0
  82. package/dist/schema/webpack.d.ts.map +1 -0
  83. package/dist/types.d.ts +147 -175
  84. package/dist/types.d.ts.map +1 -0
  85. package/package.json +43 -29
  86. package/src/_types.js +112 -0
  87. package/src/get-manifest.ts +33 -0
  88. package/src/index.next.ts +3 -0
  89. package/{dist/index.d.cts → src/index.ts} +27 -2
  90. package/src/inject-manifest.ts +140 -0
  91. package/src/lib/additional-precache-entries-transform.ts +58 -0
  92. package/src/lib/errors.ts +99 -0
  93. package/src/lib/escape-regexp.ts +12 -0
  94. package/src/lib/get-composite-details.ts +31 -0
  95. package/src/lib/get-file-details.ts +68 -0
  96. package/src/lib/get-file-hash.ts +21 -0
  97. package/src/lib/get-file-manifest-entries.ts +126 -0
  98. package/src/lib/get-file-size.ts +23 -0
  99. package/src/lib/get-source-map-url.ts +17 -0
  100. package/src/lib/get-string-details.ts +18 -0
  101. package/src/lib/get-string-hash.ts +15 -0
  102. package/src/lib/maximum-size-transform.ts +29 -0
  103. package/src/lib/modify-url-prefix-transform.ts +55 -0
  104. package/src/lib/no-revision-for-urls-matching-transform.ts +32 -0
  105. package/src/lib/rebase-path.ts +22 -0
  106. package/src/lib/replace-and-update-source-map.ts +122 -0
  107. package/src/lib/serwist-config-error.ts +6 -0
  108. package/src/lib/transform-manifest.ts +158 -0
  109. package/src/lib/translate-url-to-sourcemap-paths.ts +38 -0
  110. package/src/lib/validate-next-options.ts +14 -0
  111. package/src/lib/validate-options.ts +47 -0
  112. package/src/schema/assertType.ts +5 -0
  113. package/src/schema/base.ts +20 -0
  114. package/src/schema/getManifest.ts +13 -0
  115. package/src/schema/glob.ts +41 -0
  116. package/src/schema/injectManifest.ts +25 -0
  117. package/src/schema/manifestEntry.ts +9 -0
  118. package/src/schema/manifestTransform.ts +15 -0
  119. package/src/schema/next.ts +33 -0
  120. package/src/schema/swDest.ts +20 -0
  121. package/src/schema/validationErrorMap.ts +36 -0
  122. package/src/schema/vite.ts +18 -0
  123. package/src/schema/webpack.ts +47 -0
  124. package/src/types.ts +407 -0
  125. package/dist/index.cjs +0 -1632
  126. package/dist/lib/cdn-utils.d.ts +0 -1
  127. package/dist/lib/copy-serwist-libraries.d.ts +0 -16
  128. package/dist/schema/index.d.ts +0 -605
package/src/_types.js ADDED
@@ -0,0 +1,112 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ /**
10
+ * @typedef {Object} ManifestEntry
11
+ * @property {string} url The URL to the asset in the manifest.
12
+ * @property {string} revision The revision details for the file. This should be
13
+ * either a hash generated based on the file contents, or `null` if there is
14
+ * versioning already included in the URL.
15
+ * @property {string} [integrity] Integrity metadata that will be used when
16
+ * making the network request for the URL.
17
+ */
18
+
19
+ /**
20
+ * @typedef {Object} ManifestTransformResult
21
+ * @property {Array<module:workbox-build.ManifestEntry>} manifest
22
+ * @property {Array<string>|undefined} warnings
23
+ */
24
+
25
+ /**
26
+ * @typedef {Object} RuntimeCachingEntry
27
+ *
28
+ * @property {string|module:workbox-routing~handlerCallback} handler
29
+ * Either the name of one of the [built-in strategy classes]{@link module:workbox-strategies},
30
+ * or custom handler callback to use when the generated route matches.
31
+ *
32
+ * @property {string|RegExp|module:workbox-routing~matchCallback} urlPattern
33
+ * The value that will be passed to [`registerRoute()`]{@link module:workbox-routing.registerRoute},
34
+ * used to determine whether the generated route will match a given request.
35
+ *
36
+ * @property {string} [method='GET'] The
37
+ * [HTTP method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) that
38
+ * will match the generated route.
39
+ *
40
+ * @property {Object} [options]
41
+ *
42
+ * @property {Object} [options.backgroundSync]
43
+ *
44
+ * @property {string} [options.backgroundSync.name] The `name` property to use
45
+ * when creating the
46
+ * [`BackgroundSyncPlugin`]{@link module:workbox-background-sync.BackgroundSyncPlugin}.
47
+ *
48
+ * @property {Object} [options.backgroundSync.options] The `options` property
49
+ * to use when creating the
50
+ * [`BackgroundSyncPlugin`]{@link module:workbox-background-sync.BackgroundSyncPlugin}.
51
+ *
52
+ * @property {Object} [options.broadcastUpdate]
53
+ *
54
+ * @property {string} [options.broadcastUpdate.channelName] The `channelName`
55
+ * property to use when creating the
56
+ * [`BroadcastCacheUpdatePlugin`]{@link module:workbox-broadcast-update.BroadcastUpdatePlugin}.
57
+ *
58
+ * @property {Object} [options.broadcastUpdate.options] The `options` property
59
+ * to use when creating the
60
+ * [`BroadcastCacheUpdatePlugin`]{@link module:workbox-broadcast-update.BroadcastUpdatePlugin}.
61
+ *
62
+ * @property {Object} [options.cacheableResponse]
63
+ *
64
+ * @property {Object} [options.cacheableResponse.headers] The `headers` property
65
+ * to use when creating the
66
+ * [`CacheableResponsePlugin`]{@link module:workbox-cacheable-response.CacheableResponsePlugin}.
67
+ *
68
+ * @property {Array<number>} [options.cacheableResponse.statuses] `statuses`
69
+ * property to use when creating the
70
+ * [`CacheableResponsePlugin`]{@link module:workbox-cacheable-response.CacheableResponsePlugin}.
71
+ *
72
+ * @property {string} [options.cacheName] The `cacheName` to use when
73
+ * constructing one of the
74
+ * [Workbox strategy classes]{@link module:workbox-strategies}.
75
+ *
76
+ * @property {Object} [options.fetchOptions] The `fetchOptions` property value
77
+ * to use when constructing one of the
78
+ * [Workbox strategy classes]{@link module:workbox-strategies}.
79
+ *
80
+ * @property {Object} [options.expiration]
81
+ *
82
+ * @property {number} [options.expiration.maxAgeSeconds] The `maxAgeSeconds`
83
+ * property to use when creating the
84
+ * [`ExpirationPlugin`]{@link module:workbox-expiration.ExpirationPlugin}.
85
+ *
86
+ * @property {number} [options.expiration.maxEntries] The `maxEntries`
87
+ * property to use when creating the
88
+ * [`ExpirationPlugin`]{@link module:workbox-expiration.ExpirationPlugin}.
89
+ *
90
+ * @property {Object} [options.precacheFallback]
91
+ *
92
+ * @property {string} [options.precacheFallback.fallbackURL] The `fallbackURL`
93
+ * property to use when creating the
94
+ * [`PrecacheFallbackPlugin`]{@link module:workbox-precaching.PrecacheFallbackPlugin}.
95
+ *
96
+ * @property {boolean} [options.rangeRequests] Set to `true` to add the
97
+ * [`RangeRequestsPlugin`]{@link module:workbox-range-requests.RangeRequestsPlugin}
98
+ * for the strategy being configured.
99
+ *
100
+ * @property {Object} [options.matchOptions] The `matchOptions` property value
101
+ * to use when constructing one of the
102
+ * [Workbox strategy classes]{@link module:workbox-strategies}.
103
+ *
104
+ * @property {number} [options.networkTimeoutSeconds] The
105
+ * `networkTimeoutSeconds` property value to use when creating a
106
+ * [`NetworkFirst`]{@link module:workbox-strategies.NetworkFirst} strategy.
107
+ *
108
+ * @property {Array<Object>} [options.plugins]
109
+ * One or more [additional plugins](https://developers.google.com/web/tools/workbox/guides/using-plugins#custom_plugins)
110
+ * to apply to the handler. Useful when you want a plugin that doesn't have a
111
+ * "shortcut" configuration.
112
+ */
@@ -0,0 +1,33 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { getFileManifestEntries } from "./lib/get-file-manifest-entries.js";
10
+ import { validateGetManifestOptions } from "./lib/validate-options.js";
11
+ import type { GetManifestOptions, GetManifestResult } from "./types.js";
12
+
13
+ /**
14
+ * This method returns a list of URLs to precache, referred to as a "precache
15
+ * manifest", along with details about the number of entries and their size,
16
+ * based on the options you provide.
17
+ *
18
+ * ```
19
+ * // The following lists some common options; see the rest of the documentation
20
+ * // for the full set of options and defaults.
21
+ * const {count, manifestEntries, size, warnings} = await getManifest({
22
+ * dontCacheBustURLsMatching: [new RegExp('...')],
23
+ * globDirectory: '...',
24
+ * globPatterns: ['...', '...'],
25
+ * maximumFileSizeToCacheInBytes: ...,
26
+ * });
27
+ * ```
28
+ */
29
+ export const getManifest = async (config: GetManifestOptions): Promise<GetManifestResult> => {
30
+ const options = await validateGetManifestOptions(config);
31
+
32
+ return await getFileManifestEntries(options);
33
+ };
@@ -0,0 +1,3 @@
1
+ import { validateNextInjectManifestOptions } from "./lib/validate-next-options.js";
2
+
3
+ export { validateNextInjectManifestOptions };
@@ -1,4 +1,12 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
1
8
  import stringify from "fast-json-stable-stringify";
9
+
2
10
  import { getManifest } from "./get-manifest.js";
3
11
  import { injectManifest } from "./inject-manifest.js";
4
12
  import { errors } from "./lib/errors.js";
@@ -10,5 +18,22 @@ import { replaceAndUpdateSourceMap } from "./lib/replace-and-update-source-map.j
10
18
  import { transformManifest } from "./lib/transform-manifest.js";
11
19
  import { translateURLToSourcemapPaths } from "./lib/translate-url-to-sourcemap-paths.js";
12
20
  import { validateInjectManifestOptions, validateViteInjectManifestOptions, validateWebpackInjectManifestOptions } from "./lib/validate-options.js";
13
- export { errors, escapeRegExp, getFileManifestEntries, getManifest, getSourceMapURL, injectManifest, rebasePath, replaceAndUpdateSourceMap, stringify, transformManifest, translateURLToSourcemapPaths, validateInjectManifestOptions, validateViteInjectManifestOptions, validateWebpackInjectManifestOptions, };
14
- export * from "./types.js";
21
+
22
+ export {
23
+ errors,
24
+ escapeRegExp,
25
+ getFileManifestEntries,
26
+ getManifest,
27
+ getSourceMapURL,
28
+ injectManifest,
29
+ rebasePath,
30
+ replaceAndUpdateSourceMap,
31
+ stringify,
32
+ transformManifest,
33
+ translateURLToSourcemapPaths,
34
+ validateInjectManifestOptions,
35
+ validateViteInjectManifestOptions,
36
+ validateWebpackInjectManifestOptions,
37
+ };
38
+
39
+ export type * from "./types.js";
@@ -0,0 +1,140 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import assert from "assert";
10
+ import stringify from "fast-json-stable-stringify";
11
+ import fse from "fs-extra";
12
+ import type { RawSourceMap } from "source-map";
13
+ import upath from "upath";
14
+
15
+ import { errors } from "./lib/errors.js";
16
+ import { escapeRegExp } from "./lib/escape-regexp.js";
17
+ import { getFileManifestEntries } from "./lib/get-file-manifest-entries.js";
18
+ import { getSourceMapURL } from "./lib/get-source-map-url.js";
19
+ import { rebasePath } from "./lib/rebase-path.js";
20
+ import { replaceAndUpdateSourceMap } from "./lib/replace-and-update-source-map.js";
21
+ import { translateURLToSourcemapPaths } from "./lib/translate-url-to-sourcemap-paths.js";
22
+ import { validateInjectManifestOptions } from "./lib/validate-options.js";
23
+ import type { BuildResult, InjectManifestOptions } from "./types.js";
24
+
25
+ /**
26
+ * This method creates a list of URLs to precache, referred to as a "precache
27
+ * manifest", based on the options you provide.
28
+ *
29
+ * The manifest is injected into the `swSrc` file, and the placeholder string
30
+ * `injectionPoint` determines where in the file the manifest should go.
31
+ *
32
+ * The final service worker file, with the manifest injected, is written to
33
+ * disk at `swDest`.
34
+ *
35
+ * This method will not compile or bundle your `swSrc` file; it just handles
36
+ * injecting the manifest.
37
+ *
38
+ * ```
39
+ * // The following lists some common options; see the rest of the documentation
40
+ * // for the full set of options and defaults.
41
+ * const {count, size, warnings} = await injectManifest({
42
+ * dontCacheBustURLsMatching: [new RegExp('...')],
43
+ * globDirectory: '...',
44
+ * globPatterns: ['...', '...'],
45
+ * maximumFileSizeToCacheInBytes: ...,
46
+ * swDest: '...',
47
+ * swSrc: '...',
48
+ * });
49
+ * ```
50
+ */
51
+ export const injectManifest = async (config: InjectManifestOptions): Promise<BuildResult> => {
52
+ const options = await validateInjectManifestOptions(config);
53
+
54
+ // Make sure we leave swSrc and swDest out of the precache manifest.
55
+ for (const file of [options.swSrc, options.swDest]) {
56
+ options.globIgnores!.push(
57
+ rebasePath({
58
+ file,
59
+ baseDirectory: options.globDirectory,
60
+ }),
61
+ );
62
+ }
63
+
64
+ const globalRegexp = new RegExp(escapeRegExp(options.injectionPoint!), "g");
65
+
66
+ const { count, size, manifestEntries, warnings } = await getFileManifestEntries(options);
67
+ let swFileContents: string;
68
+ try {
69
+ swFileContents = await fse.readFile(options.swSrc, "utf8");
70
+ } catch (error) {
71
+ throw new Error(`${errors["invalid-sw-src"]} ${error instanceof Error && error.message ? error.message : ""}`);
72
+ }
73
+
74
+ const injectionResults = swFileContents.match(globalRegexp);
75
+ // See https://github.com/GoogleChrome/workbox/issues/2230
76
+ const injectionPoint = options.injectionPoint ? options.injectionPoint : "";
77
+ if (!injectionResults) {
78
+ if (upath.resolve(options.swSrc) === upath.resolve(options.swDest)) {
79
+ throw new Error(`${errors["same-src-and-dest"]} ${injectionPoint}`);
80
+ }
81
+ throw new Error(`${errors["injection-point-not-found"]} ${injectionPoint}`);
82
+ }
83
+
84
+ assert(injectionResults.length === 1, `${errors["multiple-injection-points"]} ${injectionPoint}`);
85
+
86
+ const manifestString = manifestEntries === undefined ? "undefined" : stringify(manifestEntries);
87
+ const filesToWrite: { [key: string]: string } = {};
88
+
89
+ const url = getSourceMapURL(swFileContents);
90
+ // See https://github.com/GoogleChrome/workbox/issues/2957
91
+ const { destPath, srcPath, warning } = translateURLToSourcemapPaths(url, options.swSrc, options.swDest);
92
+ if (warning) {
93
+ warnings.push(warning);
94
+ }
95
+
96
+ // If our swSrc file contains a sourcemap, we would invalidate that
97
+ // mapping if we just replaced injectionPoint with the stringified manifest.
98
+ // Instead, we need to update the swDest contents as well as the sourcemap
99
+ // (assuming it's a real file, not a data: URL) at the same time.
100
+ // See https://github.com/GoogleChrome/workbox/issues/2235
101
+ // and https://github.com/GoogleChrome/workbox/issues/2648
102
+ if (srcPath && destPath) {
103
+ const originalMap = (await fse.readJSON(srcPath, {
104
+ encoding: "utf8",
105
+ })) as RawSourceMap;
106
+
107
+ const { map, source } = await replaceAndUpdateSourceMap({
108
+ originalMap,
109
+ jsFilename: upath.basename(options.swDest),
110
+ originalSource: swFileContents,
111
+ replaceString: manifestString,
112
+ searchString: options.injectionPoint!,
113
+ });
114
+
115
+ filesToWrite[options.swDest] = source;
116
+ filesToWrite[destPath] = map;
117
+ } else {
118
+ // If there's no sourcemap associated with swSrc, a simple string
119
+ // replacement will suffice.
120
+ filesToWrite[options.swDest] = swFileContents.replace(globalRegexp, manifestString);
121
+ }
122
+
123
+ for (const [file, contents] of Object.entries(filesToWrite)) {
124
+ try {
125
+ await fse.mkdirp(upath.dirname(file));
126
+ } catch (error: unknown) {
127
+ throw new Error(`${errors["unable-to-make-sw-directory"]} '${error instanceof Error && error.message ? error.message : ""}'`);
128
+ }
129
+
130
+ await fse.writeFile(file, contents);
131
+ }
132
+
133
+ return {
134
+ count,
135
+ size,
136
+ warnings,
137
+ // Use upath.resolve() to make all the paths absolute.
138
+ filePaths: Object.keys(filesToWrite).map((f) => upath.resolve(f)),
139
+ };
140
+ };
@@ -0,0 +1,58 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import type { ManifestEntry } from "../types.js";
10
+ import { errors } from "./errors.js";
11
+
12
+ type AdditionalManifestEntriesTransform = {
13
+ (
14
+ manifest: (ManifestEntry & { size: number })[],
15
+ ): {
16
+ manifest: (ManifestEntry & { size: number })[];
17
+ warnings: string[];
18
+ };
19
+ };
20
+
21
+ export const additionalPrecacheEntriesTransform = (additionalPrecacheEntries: (ManifestEntry | string)[]): AdditionalManifestEntriesTransform => {
22
+ return (manifest: (ManifestEntry & { size: number })[]) => {
23
+ const warnings: string[] = [];
24
+ const stringEntries = new Set<string>();
25
+
26
+ for (const additionalEntry of additionalPrecacheEntries) {
27
+ // Warn about either a string or an object that lacks a revision property.
28
+ // (An object with a revision property set to null is okay.)
29
+ if (typeof additionalEntry === "string") {
30
+ stringEntries.add(additionalEntry);
31
+ manifest.push({
32
+ revision: null,
33
+ size: 0,
34
+ url: additionalEntry,
35
+ });
36
+ } else {
37
+ if (additionalEntry && additionalEntry.revision === undefined) {
38
+ stringEntries.add(additionalEntry.url);
39
+ }
40
+ manifest.push(Object.assign({ size: 0 }, additionalEntry));
41
+ }
42
+ }
43
+
44
+ if (stringEntries.size > 0) {
45
+ let urls = "\n";
46
+ for (const stringEntry of stringEntries) {
47
+ urls += ` - ${stringEntry}\n`;
48
+ }
49
+
50
+ warnings.push(errors["string-entry-warning"] + urls);
51
+ }
52
+
53
+ return {
54
+ manifest,
55
+ warnings,
56
+ };
57
+ };
58
+ };
@@ -0,0 +1,99 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { oneLine as ol } from "common-tags";
10
+
11
+ export const errors = {
12
+ "unable-to-get-rootdir": "Unable to get the root directory of your web app.",
13
+ "no-extension": ol`Unable to detect a usable extension for a file in your web
14
+ app directory.`,
15
+ "invalid-file-manifest-name": ol`The File Manifest Name must have at least one
16
+ character.`,
17
+ "unable-to-get-file-manifest-name": "Unable to get a file manifest name.",
18
+ "invalid-sw-dest": `The 'swDest' value must be a valid path.`,
19
+ "unable-to-get-sw-name": "Unable to get a service worker file name.",
20
+ "unable-to-get-save-config": ol`An error occurred when asking to save details
21
+ in a config file.`,
22
+ "unable-to-get-file-hash": ol`An error occurred when attempting to create a
23
+ file hash.`,
24
+ "unable-to-get-file-size": ol`An error occurred when attempting to get a file
25
+ size.`,
26
+ "unable-to-glob-files": "An error occurred when globbing for files.",
27
+ "unable-to-make-manifest-directory": ol`Unable to make output directory for
28
+ file manifest.`,
29
+ "read-manifest-template-failure": "Unable to read template for file manifest",
30
+ "populating-manifest-tmpl-failed": ol`An error occurred when populating the
31
+ file manifest template.`,
32
+ "manifest-file-write-failure": "Unable to write the file manifest.",
33
+ "unable-to-make-sw-directory": ol`Unable to make the directories to output
34
+ the service worker path.`,
35
+ "sw-write-failure": "Unable to write the service worker file.",
36
+ "sw-write-failure-directory": ol`Unable to write the service worker file;
37
+ 'swDest' should be a full path to the file, not a path to a directory.`,
38
+ "unable-to-copy-serwist-libraries": ol`One or more of the Serwist libraries
39
+ could not be copied over to the destination directory: `,
40
+ "invalid-glob-directory": ol`The supplied globDirectory must be a path as a
41
+ string.`,
42
+ "invalid-dont-cache-bust": ol`The supplied 'dontCacheBustURLsMatching'
43
+ parameter must be a RegExp.`,
44
+ "invalid-exclude-files": "The excluded files should be an array of strings.",
45
+ "invalid-get-manifest-entries-input": ol`The input to
46
+ 'getFileManifestEntries()' must be an object.`,
47
+ "invalid-manifest-path": ol`The supplied manifest path is not a string with
48
+ at least one character.`,
49
+ "invalid-manifest-entries": ol`The manifest entries must be an array of
50
+ strings or JavaScript objects containing a url parameter.`,
51
+ "invalid-manifest-format": ol`The value of the 'format' option passed to
52
+ generateFileManifest() must be either 'iife' (the default) or 'es'.`,
53
+ "invalid-static-file-globs": ol`The 'globPatterns' value must be an array
54
+ of strings.`,
55
+ "invalid-templated-urls": ol`The 'templatedURLs' value should be an object
56
+ that maps URLs to either a string, or to an array of glob patterns.`,
57
+ "templated-url-matches-glob": ol`One of the 'templatedURLs' URLs is already
58
+ being tracked via 'globPatterns': `,
59
+ "invalid-glob-ignores": ol`The 'globIgnores' parameter must be an array of
60
+ glob pattern strings.`,
61
+ "manifest-entry-bad-url": ol`The generated manifest contains an entry without
62
+ a URL string. This is likely an error with @serwist/build.`,
63
+ "modify-url-prefix-bad-prefixes": ol`The 'modifyURLPrefix' parameter must be
64
+ an object with string key value pairs.`,
65
+ "invalid-inject-manifest-arg": ol`The input to 'injectManifest()' must be an
66
+ object.`,
67
+ "injection-point-not-found": ol`Unable to find a place to inject the manifest.
68
+ Please ensure that your service worker file contains the following: `,
69
+ "multiple-injection-points": ol`Please ensure that your 'swSrc' file contains
70
+ only one match for the following: `,
71
+ "useless-glob-pattern": ol`One of the glob patterns doesn't match any files.
72
+ Please remove or fix the following: `,
73
+ "bad-template-urls-asset": ol`There was an issue using one of the provided
74
+ 'templatedURLs'.`,
75
+ "invalid-runtime-caching": ol`The 'runtimeCaching' parameter must an an
76
+ array of objects with at least a 'urlPattern' and 'handler'.`,
77
+ "urlPattern-is-required": ol`The 'urlPattern' option is required when using
78
+ 'runtimeCaching'.`,
79
+ "handler-is-required": ol`The 'handler' option is required when using
80
+ runtimeCaching.`,
81
+ "invalid-generate-file-manifest-arg": ol`The input to generateFileManifest()
82
+ must be an Object.`,
83
+ "invalid-sw-src": `The 'swSrc' file can't be read.`,
84
+ "same-src-and-dest": ol`Unable to find a place to inject the manifest. This is
85
+ likely because swSrc and swDest are configured to the same file.
86
+ Please ensure that your swSrc file contains the following:`,
87
+ "no-module-name": ol`You must provide a moduleName parameter when calling
88
+ getModuleURL().`,
89
+ "bad-manifest-transforms-return-value": ol`The return value from a
90
+ manifestTransform should be an object with 'manifest' and optionally
91
+ 'warnings' properties.`,
92
+ "string-entry-warning": ol`Some items were passed to additionalPrecacheEntries
93
+ without revisioning info. This is generally NOT safe. Learn more at
94
+ https://bit.ly/wb-precache.`,
95
+ "cant-find-sourcemap": ol`The swSrc file refers to a sourcemap that can't be
96
+ opened:`,
97
+ "manifest-transforms": ol`When using manifestTransforms, you must provide
98
+ an array of functions.`,
99
+ };
@@ -0,0 +1,12 @@
1
+ /*
2
+ Copyright 2019 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
10
+ export const escapeRegExp = (str: string): string => {
11
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
12
+ };
@@ -0,0 +1,31 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import crypto from "crypto";
10
+
11
+ import type { FileDetails } from "../types.js";
12
+
13
+ export const getCompositeDetails = (compositeURL: string, dependencyDetails: FileDetails[]): FileDetails => {
14
+ let totalSize = 0;
15
+ let compositeHash = "";
16
+
17
+ for (const fileDetails of dependencyDetails) {
18
+ totalSize += fileDetails.size;
19
+ compositeHash += fileDetails.hash;
20
+ }
21
+
22
+ const md5 = crypto.createHash("md5");
23
+ md5.update(compositeHash);
24
+ const hashOfHashes = md5.digest("hex");
25
+
26
+ return {
27
+ file: compositeURL,
28
+ hash: hashOfHashes,
29
+ size: totalSize,
30
+ };
31
+ };
@@ -0,0 +1,68 @@
1
+ /*
2
+ Copyright 2021 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import { glob } from "glob";
10
+ import upath from "upath";
11
+
12
+ import type { GlobPartial } from "../types.js";
13
+ import { errors } from "./errors.js";
14
+ import { getFileHash } from "./get-file-hash.js";
15
+ import { getFileSize } from "./get-file-size.js";
16
+
17
+ interface FileDetails {
18
+ file: string;
19
+ hash: string;
20
+ size: number;
21
+ }
22
+
23
+ export function getFileDetails({
24
+ globDirectory,
25
+ globFollow,
26
+ globIgnores,
27
+ globPattern,
28
+ }: Omit<GlobPartial, "globDirectory" | "globPatterns" | "templatedURLs"> & {
29
+ // This will only be called when globDirectory is not undefined.
30
+ globDirectory: string;
31
+ globPattern: string;
32
+ }): {
33
+ globbedFileDetails: FileDetails[];
34
+ warning: string;
35
+ } {
36
+ let globbedFiles: string[];
37
+ let warning = "";
38
+
39
+ try {
40
+ globbedFiles = glob.sync(globPattern, {
41
+ cwd: globDirectory,
42
+ follow: globFollow,
43
+ ignore: globIgnores,
44
+ });
45
+ } catch (err) {
46
+ throw new Error(`${errors["unable-to-glob-files"]} '${err instanceof Error && err.message ? err.message : ""}'`);
47
+ }
48
+
49
+ if (globbedFiles.length === 0) {
50
+ warning = `${errors["useless-glob-pattern"]} ${JSON.stringify({ globDirectory, globPattern, globIgnores }, null, 2)}`;
51
+ }
52
+
53
+ const globbedFileDetails: FileDetails[] = [];
54
+ for (const file of globbedFiles) {
55
+ const fullPath = upath.join(globDirectory, file);
56
+ const fileSize = getFileSize(fullPath);
57
+ if (fileSize !== null) {
58
+ const fileHash = getFileHash(fullPath);
59
+ globbedFileDetails.push({
60
+ file: `${upath.relative(globDirectory, fullPath)}`,
61
+ hash: fileHash,
62
+ size: fileSize,
63
+ });
64
+ }
65
+ }
66
+
67
+ return { globbedFileDetails, warning };
68
+ }
@@ -0,0 +1,21 @@
1
+ /*
2
+ Copyright 2018 Google LLC
3
+
4
+ Use of this source code is governed by an MIT-style
5
+ license that can be found in the LICENSE file or at
6
+ https://opensource.org/licenses/MIT.
7
+ */
8
+
9
+ import fse from "fs-extra";
10
+
11
+ import { errors } from "./errors.js";
12
+ import { getStringHash } from "./get-string-hash.js";
13
+
14
+ export function getFileHash(file: string): string {
15
+ try {
16
+ const buffer = fse.readFileSync(file);
17
+ return getStringHash(buffer);
18
+ } catch (err) {
19
+ throw new Error(`${errors["unable-to-get-file-hash"]} '${err instanceof Error && err.message ? err.message : ""}'`);
20
+ }
21
+ }