@unplugin-pwa/core 0.0.1 → 0.0.2

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 (65) hide show
  1. package/dist/additional-manifest-entries.d.mts +10 -0
  2. package/dist/additional-manifest-entries.mjs +60 -0
  3. package/dist/build-pwa-asset.d.mts +18 -0
  4. package/dist/build-pwa-asset.mjs +87 -0
  5. package/dist/config.d.mts +75 -0
  6. package/dist/config.mjs +293 -0
  7. package/dist/constants.d.mts +31 -0
  8. package/dist/constants.mjs +41 -0
  9. package/dist/context-types.d.mts +155 -0
  10. package/dist/context.d.mts +15 -0
  11. package/dist/context.mjs +58 -0
  12. package/dist/create-generate-register-sw-script.d.mts +15 -0
  13. package/dist/create-generate-register-sw-script.mjs +27 -0
  14. package/dist/create-web-manifest-html-link.d.mts +13 -0
  15. package/dist/create-web-manifest-html-link.mjs +21 -0
  16. package/dist/dev/prepare-sw-names-and-glob-directory.d.mts +18 -0
  17. package/dist/dev/prepare-sw-names-and-glob-directory.mjs +75 -0
  18. package/dist/dev/prepare-temp-folder.d.mts +9 -0
  19. package/dist/dev/prepare-temp-folder.mjs +44 -0
  20. package/dist/dual-sw-utilities.d.mts +9 -0
  21. package/dist/dual-sw-utilities.mjs +16 -0
  22. package/dist/generate-register-sw.d.mts +14 -0
  23. package/dist/generate-register-sw.mjs +22 -0
  24. package/dist/generate-web-manifest.d.mts +9 -0
  25. package/dist/generate-web-manifest.mjs +12 -0
  26. package/dist/helpers.d.mts +33 -0
  27. package/dist/helpers.mjs +132 -0
  28. package/dist/html.d.mts +8 -0
  29. package/dist/html.mjs +28 -0
  30. package/dist/index.d.mts +9 -0
  31. package/dist/inject-generate-register-sw.d.mts +16 -0
  32. package/dist/inject-generate-register-sw.mjs +22 -0
  33. package/dist/inject-web-manifest-html-link.d.mts +14 -0
  34. package/dist/inject-web-manifest-html-link.mjs +20 -0
  35. package/dist/inspector-utils.d.mts +26 -0
  36. package/dist/inspector-utils.mjs +47 -0
  37. package/dist/logs.d.mts +8 -0
  38. package/dist/logs.mjs +19 -0
  39. package/dist/package-DpKc2x3j.mjs +10 -0
  40. package/dist/prepare-pwa-context.d.mts +11 -0
  41. package/dist/prepare-pwa-context.mjs +135 -0
  42. package/dist/prepare-sw-names.d.mts +11 -0
  43. package/dist/prepare-sw-names.mjs +45 -0
  44. package/dist/pwa-assets/build.d.mts +9 -0
  45. package/dist/pwa-assets/build.mjs +15 -0
  46. package/dist/pwa-assets/config.d.mts +10 -0
  47. package/dist/pwa-assets/config.mjs +136 -0
  48. package/dist/pwa-assets/dev.d.mts +11 -0
  49. package/dist/pwa-assets/dev.mjs +35 -0
  50. package/dist/pwa-assets/generator.d.mts +20 -0
  51. package/dist/pwa-assets/generator.mjs +31 -0
  52. package/dist/pwa-assets/html.d.mts +11 -0
  53. package/dist/pwa-assets/html.mjs +47 -0
  54. package/dist/pwa-assets/manifest.d.mts +10 -0
  55. package/dist/pwa-assets/manifest.mjs +15 -0
  56. package/dist/pwa-assets/options.d.mts +9 -0
  57. package/dist/pwa-assets/options.mjs +34 -0
  58. package/dist/pwa-assets/types.d.mts +9 -0
  59. package/dist/pwa-assets/utils.d.mts +11 -0
  60. package/dist/pwa-assets/utils.mjs +48 -0
  61. package/dist/resolve-inspector-dist.d.mts +11 -0
  62. package/dist/resolve-inspector-dist.mjs +25 -0
  63. package/dist/types-B60e7Nq4.d.mts +67 -0
  64. package/dist/types-BhwjnGLn.d.mts +703 -0
  65. package/package.json +1 -1
@@ -0,0 +1,10 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ import { PWAPluginContext } from "./context-types.mjs";
9
+ import { ManifestEntry } from "@vite-pwa/workbox-build/types";
10
+ export declare function additionalManifestEntriesFactory(ctx: PWAPluginContext<any, any, any>, mapFile: (url: string) => string): () => AsyncGenerator<string | ManifestEntry, undefined, void>;
@@ -0,0 +1,60 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ import { generateWebManifest } from "./generate-web-manifest.mjs";
9
+ // src/additional-manifest-entries.ts
10
+ function additionalManifestEntriesFactory(ctx, mapFile) {
11
+ return async function* additionalManifestEntries() {
12
+ const { includeManifest, includeManifestIcons, includeAssets, includeManifestShortcutIcons, includeManifestScreenshots } = ctx.resolvedOptions;
13
+ if (includeManifest || includeManifestIcons || includeAssets || includeManifestScreenshots || includeManifestShortcutIcons) {
14
+ const manifest = ctx.resolvedOptions.manifest;
15
+ const [{ hash }, { readFile }] = await Promise.all([import("node:crypto"), import("node:fs/promises")]);
16
+ if (manifest) {
17
+ if (includeManifest) yield {
18
+ url: ctx.resolvedOptions.manifestFilename,
19
+ revision: hash("md5", generateWebManifest(ctx), "hex")
20
+ };
21
+ if (includeManifestIcons && manifest.icons) {
22
+ const consumerIcons = /* @__PURE__ */ new Set();
23
+ if (ctx.consumerOptions.manifest && ctx.consumerOptions.manifest.icons) {
24
+ for (const icon of ctx.consumerOptions.manifest.icons) if (icon.src) consumerIcons.add(mapFile(icon.src));
25
+ }
26
+ for (const icon of manifest.icons) if (icon.src) {
27
+ const path = mapFile(icon.src);
28
+ if (!consumerIcons.has(path)) continue;
29
+ yield {
30
+ url: icon.src,
31
+ revision: hash("md5", await readFile(path, "utf-8"), "hex")
32
+ };
33
+ }
34
+ }
35
+ if (includeManifestShortcutIcons && manifest.shortcuts) {
36
+ for (const shortcut of manifest.shortcuts) if (shortcut.icons) {
37
+ for (const icons of shortcut.icons) if (icons.src) yield {
38
+ url: icons.src,
39
+ revision: hash("md5", await readFile(mapFile(icons.src), "utf-8"), "hex")
40
+ };
41
+ }
42
+ }
43
+ if (includeManifestScreenshots && manifest.screenshots) for (const screenshot of manifest.screenshots) yield {
44
+ url: screenshot.src,
45
+ revision: hash("md5", await readFile(mapFile(screenshot.src), "utf-8"), "hex")
46
+ };
47
+ if (includeAssets) {
48
+ const assets = typeof includeAssets === "string" ? [includeAssets] : includeAssets;
49
+ for (const asset of assets) yield {
50
+ url: asset,
51
+ revision: hash("md5", await readFile(mapFile(asset), "utf-8"), "hex")
52
+ };
53
+ }
54
+ }
55
+ }
56
+ const consumerGenerator = ctx.consumerOptions.additionalManifestEntriesGenerator;
57
+ if (consumerGenerator) yield* consumerGenerator();
58
+ };
59
+ }
60
+ export { additionalManifestEntriesFactory };
@@ -0,0 +1,18 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ import { w as VitePWAStrategy } from "./types-BhwjnGLn.mjs";
9
+ import { Bundler, PWAPluginContext } from "./context-types.mjs";
10
+ import { SWType } from "@vite-pwa/workbox-build/types";
11
+ export type DependenciesResolved = NonNullable<Pick<import('rolldown').Plugin, 'resolveId' | 'load'>>;
12
+ /**
13
+ * This module will build `registerSW` or any virtual module.
14
+ * @param code The code to build.
15
+ * @param ctx The context of the PWA bundler.
16
+ * @param resolver Rolldown hooks to resolve dependencies.
17
+ */
18
+ export declare function buildPwaAsset<B extends Bundler, UserStrategy extends VitePWAStrategy, T extends SWType>(code: string, ctx: PWAPluginContext<B, UserStrategy, T>, resolver?: DependenciesResolved): Promise<string>;
@@ -0,0 +1,87 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ import { resolveSWNames } from "@vite-pwa/workbox-build/utils/resolve-sw-names";
9
+ // src/build-pwa-asset.ts
10
+ /**
11
+ * This module will build `registerSW` or any virtual module.
12
+ * @param code The code to build.
13
+ * @param ctx The context of the PWA bundler.
14
+ * @param resolver Rolldown hooks to resolve dependencies.
15
+ */
16
+ async function buildPwaAsset(code, ctx, resolver) {
17
+ const { filename = "sw.js" } = ctx.consumerOptions;
18
+ const { strategy, scope, buildBase, base: useBase, buildSW, injectManifest, updateViaCache } = ctx.resolvedOptions;
19
+ const useGenerateSW = strategy === "generate-sw";
20
+ const { swDestPath, classicSWDestPath, moduleSWDestPath } = resolveSWNames(filename, strategy === "generate-sw" ? "" : strategy === "build-sw" ? buildSW.swSrc : injectManifest.swSrc, useGenerateSW);
21
+ let swType = "classic";
22
+ if (ctx.devEnvironment) {
23
+ if (ctx.resolvedOptions.devOptions?.type === "module") swType = "module";
24
+ } else if (ctx.resolvedOptions.swType === "module") swType = "module";
25
+ const devEnabled = ctx.resolvedOptions.devOptions?.enabled === true;
26
+ const base = ctx.devEnvironment ? useBase : buildBase;
27
+ return await buildPwaAssetWithRolldown(code, {
28
+ "import.meta.PWA_ESM_FALLBACK_SW": JSON.stringify(ctx.resolvedOptions.swType === "classic-and-module"),
29
+ "import.meta.PWA_SELF_DESTROYING_SW": JSON.stringify(ctx.strategy === "self-destroy-sw"),
30
+ "import.meta.PWA_SW_URL": JSON.stringify(`${base}${swDestPath}`),
31
+ "import.meta.PWA_SW_CLASSIC_URL": JSON.stringify(`${base}${classicSWDestPath}`),
32
+ "import.meta.PWA_SW_MODULE_URL": JSON.stringify(`${base}${moduleSWDestPath}`),
33
+ "import.meta.PWA_SW_SCOPE": JSON.stringify(scope),
34
+ "import.meta.PWA_SW_TYPE": JSON.stringify(swType),
35
+ "import.meta.PWA_SW_UPDATE_VIA_CACHE": JSON.stringify(updateViaCache),
36
+ "import.meta.PWA_DEV_SERVER": JSON.stringify(ctx.devEnvironment),
37
+ "import.meta.PWA_SW_AUTO_UPDATE": JSON.stringify(ctx.resolvedOptions.registerType === "autoUpdate"),
38
+ "import.meta.PWA_DEV_ENABLED": JSON.stringify(devEnabled),
39
+ "import.meta.PWA_DEV_UI_ENABLED": JSON.stringify(devEnabled && ctx.resolvedOptions.devOptions?.enableUISwitcher === true),
40
+ "import.meta.PWA_DEV_CURRENT_SW_TYPE": JSON.stringify(ctx.dev.options.swType)
41
+ }, ctx.devEnvironment, ctx.resolvedOptions.minify, resolver);
42
+ }
43
+ async function writeAsset(instance, options) {
44
+ try {
45
+ return await instance.generate(options);
46
+ } finally {
47
+ await instance.close();
48
+ }
49
+ }
50
+ async function buildPwaAssetWithRolldown(code, define, isDev, minify, resolver) {
51
+ const { rolldown } = await import("rolldown");
52
+ const input = "asset.js";
53
+ const plugins = [{
54
+ name: "pwa-asset-resolver",
55
+ resolveId(id) {
56
+ return id === input ? input : void 0;
57
+ },
58
+ load(id) {
59
+ return id === input ? code : void 0;
60
+ }
61
+ }];
62
+ if (resolver) plugins.push({
63
+ name: "pwa-asset-custom-resolver",
64
+ resolveId: resolver.resolveId,
65
+ load: resolver.load
66
+ });
67
+ return (await writeAsset(await rolldown({
68
+ input,
69
+ platform: "browser",
70
+ treeshake: true,
71
+ logLevel: "warn",
72
+ plugins,
73
+ transform: { define }
74
+ }), {
75
+ format: "esm",
76
+ topLevelVar: true,
77
+ cleanDir: false,
78
+ comments: {
79
+ legal: !isDev && !minify,
80
+ jsdoc: false,
81
+ annotation: false
82
+ },
83
+ minify: isDev ? false : minify,
84
+ codeSplitting: false
85
+ })).output.find((e) => e.fileName === input && e.type === "chunk").code;
86
+ }
87
+ export { buildPwaAsset };
@@ -0,0 +1,75 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ import { C as VitePWAOptions, w as VitePWAStrategy, y as ResolvedVitePWAOptions } from "./types-BhwjnGLn.mjs";
9
+ import { ExtractStrategy } from "./context-types.mjs";
10
+ import { SWType } from "@vite-pwa/workbox-build/types";
11
+ export declare const DEFAULT_CONFIG_FILES: readonly ["pwa.config.js", "pwa.config.ts", "pwa.config.mjs", "pwa.config.mts"];
12
+ export type LoaderType<S extends VitePWAStrategy, T extends SWType> = VitePWAOptions<S, T> | (() => VitePWAOptions<S, T>) | (() => Promise<VitePWAOptions<S, T>>);
13
+ /**
14
+ * Loads the PWA configuration from a specified path.
15
+ *
16
+ * If the `path` options is not provided, it will return the provided options as is.
17
+ *
18
+ * Otherwise, it will attempt to load the configuration from the specified path
19
+ * and merge it with the provided options if `mergeOptions` is set to true.
20
+ *
21
+ * @param options The partial PWA options to load.
22
+ * @returns The resolved PWA options, merged with the provided options if `mergeOptions` is set to true.
23
+ */
24
+ export declare function loadConfiguration<S extends VitePWAStrategy, T extends SWType>(options: Partial<VitePWAOptions<S, T>>): Promise<Partial<VitePWAOptions<S, T>>>;
25
+ /**
26
+ * Loads the first existing default configuration file from the current working directory.
27
+ *
28
+ * The default configuration files are searched in the following order:
29
+ * - `pwa.config.js`
30
+ * - `pwa.config.ts`
31
+ * - `pwa.config.mjs`
32
+ * - `pwa.config.mts`
33
+ *
34
+ * @param cwd The current working directory to search for the default configuration files. Defaults to `process.cwd()`.
35
+ * @returns The path to the first existing default configuration file, or `undefined` if none are found.
36
+ */
37
+ export declare function resolveDefaultConfig(cwd?: string): string | undefined;
38
+ /**
39
+ * Loads the default manifest using the `package.json` file.
40
+ *
41
+ * @param options The resolved PWA options.
42
+ */
43
+ export declare function prepareManifest(options: ResolvedVitePWAOptions<any, any>): void;
44
+ /**
45
+ * The resolver options containing environment information and callbacks for `resolvePwaConfiguration`.
46
+ */
47
+ export interface ResolverOptions {
48
+ /**
49
+ * Whether the current environment is a development environment.
50
+ */
51
+ isDev: boolean;
52
+ /**
53
+ * When using `inject-manifest`, this callback must resolve if the strategy is wrong, the implementation should be:
54
+ * - if the service worker with `.ts` or `.mts` extension, then, it is `build-sw` and not `inject-manifest` strategy: must return true
55
+ * - if the service worker outside public dir, then, it is `build-sw` and not `inject-manifest` strategy: must return true
56
+ * - otherwise must return false
57
+ */
58
+ isWrongInjectManifest: (swSrc: string) => boolean | Promise<boolean>;
59
+ }
60
+ /**
61
+ * Resolves the PWA configuration based on the provided options and resolver options.
62
+ *
63
+ * This function will search for the PWA configuration file if the `path` option is not provided,
64
+ * and will merge the loaded configuration with the provided options.
65
+ *
66
+ * When using `inject-manifest`, the `resolverOptions.isWrongInjectManifest` callback must resolve if the strategy is wrong, the implementation should be:
67
+ * - if the service worker with `.ts` or `.mts` extension, then, it is `build-sw` and not `inject-manifest` strategy: must return true
68
+ * - if the service worker outside public dir, then, it is `build-sw` and not `inject-manifest` strategy: must return true
69
+ * - otherwise must return false
70
+ *
71
+ * @param pwaOptions The PWA options to resolve.
72
+ * @param resolverOptions The resolver options containing environment information and callbacks.
73
+ * @returns The resolved PWA options.
74
+ */
75
+ export declare function resolvePwaConfiguration<UserStrategy extends VitePWAStrategy, T extends SWType>(pwaOptions: Partial<VitePWAOptions<UserStrategy, T>>, resolverOptions: ResolverOptions): Promise<ResolvedVitePWAOptions<ExtractStrategy<UserStrategy>, T>>;
@@ -0,0 +1,293 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ import { resolvePWAAssetsOptions } from "./pwa-assets/options.mjs";
9
+ import { normalizePath } from "@vite-pwa/workbox-build/utils/resolve-sw-names";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import process from "node:process";
13
+ import { pathToFileURL } from "node:url";
14
+ import { errStyle } from "@vite-pwa/workbox-build/utils/colors";
15
+ // src/config.ts
16
+ function deepMergeObject(magicast, object) {
17
+ if (typeof object === "object" && object !== null) for (const key in object) {
18
+ const magicastValue = magicast[key];
19
+ const objectValue = object[key];
20
+ if (magicastValue === objectValue) continue;
21
+ if (typeof magicastValue === "object" && magicastValue !== null && typeof objectValue === "object" && objectValue !== null) deepMergeObject(magicastValue, objectValue);
22
+ else magicast[key] = objectValue;
23
+ }
24
+ }
25
+ const DEFAULT_CONFIG_FILES = [
26
+ "pwa.config.js",
27
+ "pwa.config.ts",
28
+ "pwa.config.mjs",
29
+ "pwa.config.mts"
30
+ ];
31
+ /**
32
+ * Loads the PWA configuration from a specified path.
33
+ *
34
+ * If the `path` options is not provided, it will return the provided options as is.
35
+ *
36
+ * Otherwise, it will attempt to load the configuration from the specified path
37
+ * and merge it with the provided options if `mergeOptions` is set to true.
38
+ *
39
+ * @param options The partial PWA options to load.
40
+ * @returns The resolved PWA options, merged with the provided options if `mergeOptions` is set to true.
41
+ */
42
+ async function loadConfiguration(options) {
43
+ if (!options.path) return options;
44
+ const cwd = path.resolve(process.cwd(), options.cwd || ".");
45
+ const configPath = path.isAbsolute(options.path) ? options.path : path.resolve(cwd, options.path);
46
+ const configModule = await import(pathToFileURL(configPath).href).then((m) => m.default ?? m.options ?? m.config ?? m);
47
+ const external = typeof configModule === "function" ? await configModule() : configModule;
48
+ if (options.mergeOptions) deepMergeObject(external, options);
49
+ external.path = normalizePath(configPath);
50
+ return external;
51
+ }
52
+ /**
53
+ * Loads the first existing default configuration file from the current working directory.
54
+ *
55
+ * The default configuration files are searched in the following order:
56
+ * - `pwa.config.js`
57
+ * - `pwa.config.ts`
58
+ * - `pwa.config.mjs`
59
+ * - `pwa.config.mts`
60
+ *
61
+ * @param cwd The current working directory to search for the default configuration files. Defaults to `process.cwd()`.
62
+ * @returns The path to the first existing default configuration file, or `undefined` if none are found.
63
+ */
64
+ function resolveDefaultConfig(cwd = process.cwd()) {
65
+ for (const name of DEFAULT_CONFIG_FILES) {
66
+ const candidate = path.resolve(cwd, name);
67
+ if (fs.existsSync(candidate)) return candidate;
68
+ }
69
+ }
70
+ /**
71
+ * Loads the default manifest using the `package.json` file.
72
+ *
73
+ * @param options The resolved PWA options.
74
+ */
75
+ function prepareManifest(options) {
76
+ if (options.manifest === false) return;
77
+ const pkg = fs.existsSync("package.json") ? JSON.parse(fs.readFileSync("package.json", "utf-8")) : {};
78
+ options.manifest = Object.assign({}, {
79
+ name: pkg.name,
80
+ short_name: pkg.name,
81
+ description: pkg.description,
82
+ start_url: options.base,
83
+ display: "standalone",
84
+ background_color: "#ffffff",
85
+ theme_color: "#42b883",
86
+ lang: "en",
87
+ scope: options.scope
88
+ }, options.manifest ?? {});
89
+ }
90
+ function checkInjectRegister(strategy, injectRegister, swType, color, buildWarning) {
91
+ return swType === "classic-and-module" && injectRegister === "inline" ? [
92
+ `\n${errStyle([color, "bold"], "[Vite PWA]")} ${errStyle(color, "WRONG CONFIGURATION")}:`,
93
+ `You are using ${errStyle("cyan", "inline")} for inject register with dual service worker registration.`,
94
+ `Specify other value at ${errStyle("cyan", "injectRegister")} option${buildWarning}.\n`
95
+ ].join("\n") : void 0;
96
+ }
97
+ function checkOptions(isDev, consumerOptions, resolvedOptions) {
98
+ const isDevEnabled = consumerOptions.devOptions?.enabled === true;
99
+ const isWarning = isDev && !isDevEnabled;
100
+ const color = isWarning ? "yellow" : "red";
101
+ const warning = isWarning ? `, ${errStyle("yellow", "running build command will fail")}` : "";
102
+ let message;
103
+ switch (resolvedOptions.strategy) {
104
+ case "inject-manifest": {
105
+ const { swType } = resolvedOptions.injectManifest;
106
+ if (swType === "classic-and-module") message = [
107
+ `\n${errStyle([color, "bold"], "[Vite PWA]")} ${errStyle(color, "WRONG CONFIGURATION")}:`,
108
+ `You are using ${errStyle("cyan", String(consumerOptions.strategies))} with ${errStyle("cyan", swType)} service worker type.`,
109
+ `Specify ${errStyle("green", "classic")} or ${errStyle("green", "module")} at ${errStyle("cyan", "swType")} option${warning}.\n`
110
+ ].join("\n");
111
+ break;
112
+ }
113
+ case "generate-sw":
114
+ message = checkInjectRegister("generate-sw", resolvedOptions.injectRegister, resolvedOptions.generateSW.swType, color, warning);
115
+ break;
116
+ case "build-sw": message = checkInjectRegister("build-sw", consumerOptions.injectRegister, resolvedOptions.buildSW.swType, color, warning);
117
+ }
118
+ if (message) {
119
+ if (isWarning) console.warn(message);
120
+ else throw new Error(message);
121
+ }
122
+ return resolvedOptions;
123
+ }
124
+ /**
125
+ * Resolves the PWA configuration based on the provided options and resolver options.
126
+ *
127
+ * This function will search for the PWA configuration file if the `path` option is not provided,
128
+ * and will merge the loaded configuration with the provided options.
129
+ *
130
+ * When using `inject-manifest`, the `resolverOptions.isWrongInjectManifest` callback must resolve if the strategy is wrong, the implementation should be:
131
+ * - if the service worker with `.ts` or `.mts` extension, then, it is `build-sw` and not `inject-manifest` strategy: must return true
132
+ * - if the service worker outside public dir, then, it is `build-sw` and not `inject-manifest` strategy: must return true
133
+ * - otherwise must return false
134
+ *
135
+ * @param pwaOptions The PWA options to resolve.
136
+ * @param resolverOptions The resolver options containing environment information and callbacks.
137
+ * @returns The resolved PWA options.
138
+ */
139
+ async function resolvePwaConfiguration(pwaOptions, resolverOptions) {
140
+ const resolvedPath = pwaOptions.path ?? resolveDefaultConfig(pwaOptions.cwd);
141
+ const { pwaAssets, filename = "sw.js", strategies = "generateSW", swType = "classic", includeManifest = true, includeManifestIcons = true, includeManifestShortcutIcons = true, includeManifestScreenshots = false, disable = false, injectRegister = "auto", registerType = "prompt", useCredentials = false, manifestFilename = "manifest.webmanifest", minify, maximumFileSizeToCacheInBytes, throwMaximumFileSizeToCacheInBytes, additionalManifestEntries, additionalManifestEntriesGenerator, manifest, updateViaCache = "imports", ...rest } = await loadConfiguration(Object.assign({}, pwaOptions, { path: resolvedPath }));
142
+ const resolvedPwaAssets = resolvePWAAssetsOptions(pwaAssets);
143
+ switch (strategies) {
144
+ case "generateSW":
145
+ case "generate-sw": {
146
+ const { workbox, generateSW, ...strategyOptions } = rest;
147
+ if (workbox && !generateSW) console.warn([
148
+ `\n${errStyle(["yellow", "bold"], "[Vite PWA]")} ${errStyle("yellow", "DEPRECATION WARNING")}:`,
149
+ `You are using ${errStyle("cyan", "workbox")} option, which is now deprecated.`,
150
+ `Please replace ${errStyle("cyan", "workbox")} with ${errStyle("green", "generateSW")} option.`,
151
+ `${errStyle("cyan", "workbox")} option will be removed in the next major version.\n`
152
+ ].join("\n"));
153
+ const { inlineWorkboxRuntime = false, workboxRuntimeCompatible = true, ...generateSWOptions } = generateSW ?? workbox ?? {};
154
+ return checkOptions(resolverOptions.isDev, pwaOptions, Object.assign({}, strategyOptions, {
155
+ strategy: "generate-sw",
156
+ swType,
157
+ includeManifest,
158
+ includeManifestIcons,
159
+ includeManifestShortcutIcons,
160
+ includeManifestScreenshots,
161
+ disable,
162
+ injectRegister,
163
+ registerType,
164
+ useCredentials,
165
+ manifest,
166
+ manifestFilename,
167
+ minify,
168
+ updateViaCache,
169
+ pwaAssets: resolvedPwaAssets
170
+ }, { generateSW: Object.assign(generateSWOptions, {
171
+ inlineWorkboxRuntime,
172
+ workboxRuntimeCompatible,
173
+ swDest: filename,
174
+ swType,
175
+ minify,
176
+ maximumFileSizeToCacheInBytes,
177
+ throwMaximumFileSizeToCacheInBytes,
178
+ additionalManifestEntries,
179
+ additionalManifestEntriesGenerator
180
+ }) }));
181
+ }
182
+ case "injectManifest":
183
+ case "inject-manifest": {
184
+ const swSrcName = pwaOptions.injectManifest?.swSrc;
185
+ if (!swSrcName) throw new Error([`\n${errStyle(["red", "bold"], "[Vite PWA]")} ${errStyle("red", "WRONG CONFIGURATION")}:`, `You are using ${errStyle("cyan", strategies)} option without ${errStyle("cyan", "swSrc")} option.\n`].join("\n"));
186
+ const isTS = swSrcName.endsWith(".ts") || swSrcName.endsWith(".mts");
187
+ if (isTS || await resolverOptions.isWrongInjectManifest(normalizePath(path.resolve(process.cwd(), swSrcName)))) {
188
+ const isWarning = resolverOptions.isDev && !(pwaOptions?.devOptions?.enabled === true);
189
+ const warning = isWarning ? `, ${errStyle("yellow", "running build command will fail")}` : "";
190
+ const color = isWarning ? "yellow" : "red";
191
+ const message = [
192
+ `\n${errStyle([color, "bold"], "[Vite PWA]")} ${errStyle(color, "WRONG CONFIGURATION")}:`,
193
+ `You are using ${errStyle("cyan", strategies)} option with a service worker ${isTS ? "using TypeScript" : "as static asset"}.`,
194
+ `Please migrate to ${errStyle("green", "buildSW")} option${warning}.`,
195
+ `${errStyle("cyan", strategies)} option should be only used when you need to inject a manifest into an existing service worker.\n`
196
+ ].join("\n");
197
+ if (isWarning) console.warn(message);
198
+ else throw new Error(message);
199
+ return checkOptions(resolverOptions.isDev, pwaOptions, Object.assign({}, rest, {
200
+ strategy: "build-sw",
201
+ swType,
202
+ includeManifest,
203
+ includeManifestIcons,
204
+ includeManifestShortcutIcons,
205
+ includeManifestScreenshots,
206
+ disable,
207
+ injectRegister,
208
+ registerType,
209
+ useCredentials,
210
+ manifest,
211
+ manifestFilename,
212
+ minify,
213
+ updateViaCache,
214
+ pwaAssets: resolvedPwaAssets
215
+ }, { buildSW: Object.assign(rest.injectManifest ?? {}, {
216
+ swDest: filename,
217
+ swType,
218
+ minify,
219
+ maximumFileSizeToCacheInBytes,
220
+ throwMaximumFileSizeToCacheInBytes,
221
+ additionalManifestEntries,
222
+ additionalManifestEntriesGenerator
223
+ }) }));
224
+ }
225
+ return checkOptions(resolverOptions.isDev, pwaOptions, Object.assign({}, rest, {
226
+ strategy: "inject-manifest",
227
+ swType,
228
+ includeManifest,
229
+ includeManifestIcons,
230
+ includeManifestShortcutIcons,
231
+ includeManifestScreenshots,
232
+ disable,
233
+ injectRegister,
234
+ registerType,
235
+ useCredentials,
236
+ manifest,
237
+ manifestFilename,
238
+ minify,
239
+ updateViaCache,
240
+ pwaAssets: resolvedPwaAssets
241
+ }, { injectManifest: Object.assign(rest.injectManifest ?? {}, {
242
+ swDest: filename,
243
+ maximumFileSizeToCacheInBytes,
244
+ throwMaximumFileSizeToCacheInBytes,
245
+ additionalManifestEntries,
246
+ additionalManifestEntriesGenerator
247
+ }) }));
248
+ }
249
+ case "build-sw":
250
+ case "buildSW": {
251
+ const { inlineWorkboxRuntime = true, workboxRuntimeCompatible = true, ...buildSWOptions } = rest.buildSW ?? {};
252
+ return checkOptions(resolverOptions.isDev, pwaOptions, Object.assign({}, rest, {
253
+ strategy: "build-sw",
254
+ swType,
255
+ includeManifest,
256
+ includeManifestIcons,
257
+ includeManifestShortcutIcons,
258
+ includeManifestScreenshots,
259
+ disable,
260
+ injectRegister,
261
+ registerType,
262
+ useCredentials,
263
+ manifest,
264
+ manifestFilename,
265
+ minify,
266
+ updateViaCache,
267
+ pwaAssets: resolvedPwaAssets
268
+ }, { buildSW: Object.assign(buildSWOptions, {
269
+ inlineWorkboxRuntime,
270
+ workboxRuntimeCompatible,
271
+ swDest: filename,
272
+ swType,
273
+ minify,
274
+ maximumFileSizeToCacheInBytes,
275
+ throwMaximumFileSizeToCacheInBytes,
276
+ additionalManifestEntries,
277
+ additionalManifestEntriesGenerator
278
+ }) }));
279
+ }
280
+ case "self-destroy-sw":
281
+ case "selfDestroySW": throw new Error([
282
+ `\n${errStyle(["red", "bold"], "[Vite PWA] self-destroying")} ${errStyle("red", "strategy is no longer supported directly in the build process.")}`,
283
+ " It has been replaced by an interactive Self Destroying SW CLI. This tool will safely generate",
284
+ " the necessary auto-destroying Service Workers for your specific setup (including dual classic/ESM builds)",
285
+ " and update your config automatically.",
286
+ " The Self Destroying SW CLI is not yet available, in the meantime check:",
287
+ " https://github.com/vite-pwa/unplugin-pwa/blob/main/packages/vite/BREAKING-CHANGES.md#1-do-i-need-to-change-my-service-worker-setup-read-this-first",
288
+ "\n"
289
+ ].join("\n"));
290
+ }
291
+ throw new Error("Unknown strategy, please use one of the following: \"generateSW\", \"injectManifest\", \"buildSW\"");
292
+ }
293
+ export { DEFAULT_CONFIG_FILES, loadConfiguration, prepareManifest, resolveDefaultConfig, resolvePwaConfiguration };
@@ -0,0 +1,31 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ export declare const FILE_SW_REGISTER = "registerSW.js";
9
+ export declare const VIRTUAL_MODULES_MAP: Record<string, string>;
10
+ export declare const VIRTUAL_MODULES_RESOLVED_PREFIX = "/@unplugin-pwa/";
11
+ export declare const VIRTUAL_MODULES: string[];
12
+ export declare const PWA_INFO_VIRTUAL = "virtual:pwa-info";
13
+ export declare const RESOLVED_PWA_INFO_VIRTUAL = "\0virtual:pwa-info";
14
+ export declare const PWA_ASSETS_HEAD_VIRTUAL = "virtual:pwa-assets/head";
15
+ export declare const RESOLVED_PWA_ASSETS_HEAD_VIRTUAL = "\0virtual:pwa-assets/head";
16
+ export declare const PWA_ASSETS_ICONS_VIRTUAL = "virtual:pwa-assets/icons";
17
+ export declare const RESOLVED_PWA_ASSETS_ICONS_VIRTUAL = "\0virtual:pwa-assets/icons";
18
+ export declare const DEV_SW_NAME = "dev-sw.js?dev-sw";
19
+ export declare const DEV_SW_VIRTUAL = "/@unplugin-pwa/pwa-entry-point-loaded";
20
+ export declare const DEV_SW_VIRTUAL_VIRTUAL = "virtual:pwa-entry-point-loaded";
21
+ export declare const RESOLVED_DEV_SW_VIRTUAL_VIRTUAL = "\0virtual:pwa-entry-point-loaded";
22
+ export declare const RESOLVED_DEV_SW_VIRTUAL = "\0/@unplugin-pwa/pwa-entry-point-loaded";
23
+ export declare const DEV_READY_NAME = "unplugin-pwa:dev-ready";
24
+ export declare const DEV_REGISTER_SW_NAME = "unplugin-pwa:register-sw";
25
+ export declare const DEV_PWA_ASSETS_NAME = "unplugin-pwa:pwa-assets";
26
+ export declare const DEV_SWITCHER_NAME = "unplugin-pwa:pwa-switcher";
27
+ export declare const DEV_PWA_DUAL_SW_SWITCHER_NAME = "./switcher.js";
28
+ export declare const DEV_PWA_REGISTER_NAME = "./register.js";
29
+ export declare const INSPECTOR_BASE_PATH = "/__unplugin_pwa_inspector";
30
+ export declare const INSPECTOR_BASE_PATH_URL = "/__unplugin_pwa_inspector/";
31
+ export declare const INSPECTOR_BASE_PATH_API = "/__unplugin_pwa_inspector_api";
@@ -0,0 +1,41 @@
1
+ /*!
2
+ MIT License
3
+
4
+ Copyright (c) 2020-PRESENT Anthony Fu <https://github.com/antfu>
5
+
6
+ https://github.com/userquin/quini-pwa-monorepo/blob/main/LICENSE.
7
+ */
8
+ // src/constants.ts
9
+ const FILE_SW_REGISTER = "registerSW.js";
10
+ const VIRTUAL_MODULES_MAP = {
11
+ "virtual:pwa-register": "register",
12
+ "virtual:pwa-register/vue": "vue",
13
+ "virtual:pwa-register/svelte": "svelte",
14
+ "virtual:pwa-register/react": "react",
15
+ "virtual:pwa-register/react-legacy": "react-legacy",
16
+ "virtual:pwa-register/preact": "preact",
17
+ "virtual:pwa-register/solid": "solid"
18
+ };
19
+ const VIRTUAL_MODULES_RESOLVED_PREFIX = "/@unplugin-pwa/";
20
+ const VIRTUAL_MODULES = /* @__PURE__ */ Object.keys(VIRTUAL_MODULES_MAP);
21
+ const PWA_INFO_VIRTUAL = "virtual:pwa-info";
22
+ const RESOLVED_PWA_INFO_VIRTUAL = `\0${PWA_INFO_VIRTUAL}`;
23
+ const PWA_ASSETS_HEAD_VIRTUAL = "virtual:pwa-assets/head";
24
+ const RESOLVED_PWA_ASSETS_HEAD_VIRTUAL = `\0${PWA_ASSETS_HEAD_VIRTUAL}`;
25
+ const PWA_ASSETS_ICONS_VIRTUAL = "virtual:pwa-assets/icons";
26
+ const RESOLVED_PWA_ASSETS_ICONS_VIRTUAL = `\0${PWA_ASSETS_ICONS_VIRTUAL}`;
27
+ const DEV_SW_NAME = "dev-sw.js?dev-sw";
28
+ const DEV_SW_VIRTUAL = `${VIRTUAL_MODULES_RESOLVED_PREFIX}pwa-entry-point-loaded`;
29
+ const DEV_SW_VIRTUAL_VIRTUAL = "virtual:pwa-entry-point-loaded";
30
+ const RESOLVED_DEV_SW_VIRTUAL_VIRTUAL = `\0${DEV_SW_VIRTUAL_VIRTUAL}`;
31
+ const RESOLVED_DEV_SW_VIRTUAL = `\0${DEV_SW_VIRTUAL}`;
32
+ const DEV_READY_NAME = "unplugin-pwa:dev-ready";
33
+ const DEV_REGISTER_SW_NAME = "unplugin-pwa:register-sw";
34
+ const DEV_PWA_ASSETS_NAME = "unplugin-pwa:pwa-assets";
35
+ const DEV_SWITCHER_NAME = "unplugin-pwa:pwa-switcher";
36
+ const DEV_PWA_DUAL_SW_SWITCHER_NAME = "./switcher.js";
37
+ const DEV_PWA_REGISTER_NAME = "./register.js";
38
+ const INSPECTOR_BASE_PATH = "/__unplugin_pwa_inspector";
39
+ const INSPECTOR_BASE_PATH_URL = `${INSPECTOR_BASE_PATH}/`;
40
+ const INSPECTOR_BASE_PATH_API = `${INSPECTOR_BASE_PATH}_api`;
41
+ export { DEV_PWA_ASSETS_NAME, DEV_PWA_DUAL_SW_SWITCHER_NAME, DEV_PWA_REGISTER_NAME, DEV_READY_NAME, DEV_REGISTER_SW_NAME, DEV_SWITCHER_NAME, DEV_SW_NAME, DEV_SW_VIRTUAL, DEV_SW_VIRTUAL_VIRTUAL, FILE_SW_REGISTER, INSPECTOR_BASE_PATH, INSPECTOR_BASE_PATH_API, INSPECTOR_BASE_PATH_URL, PWA_ASSETS_HEAD_VIRTUAL, PWA_ASSETS_ICONS_VIRTUAL, PWA_INFO_VIRTUAL, RESOLVED_DEV_SW_VIRTUAL, RESOLVED_DEV_SW_VIRTUAL_VIRTUAL, RESOLVED_PWA_ASSETS_HEAD_VIRTUAL, RESOLVED_PWA_ASSETS_ICONS_VIRTUAL, RESOLVED_PWA_INFO_VIRTUAL, VIRTUAL_MODULES, VIRTUAL_MODULES_MAP, VIRTUAL_MODULES_RESOLVED_PREFIX };