@genesislcap/vite-builder 15.79.2-alpha-e9d30db797.0 → 15.80.0-FUI-2666.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.
package/README.md CHANGED
@@ -2,21 +2,7 @@
2
2
 
3
3
  Builder wrapping [Vite](https://vitejs.dev/) bundler.
4
4
 
5
- ## PWA and Service Worker
6
5
 
7
- The `pwa` and `serviceWorker` options in `genx.config.ts` are supported by the Vite builder, matching the Webpack builder:
8
-
9
- - `pwa`: emits `manifest.json` and injects `<link rel="manifest">`, `theme-color` and, when `ios` is set, the Apple meta and touch-icon tags into `index.html`. Icon and manifest URLs use `pwa.publicPath`, falling back to `PUBLIC_PATH`.
10
- - Icons under `public/` are served from there. Other icon paths are resolved from the app root and emitted to `destination` (default `icons/`).
11
- - Icons are not resized, so a raster icon needs one entry per size. A warning is logged when one file is declared at several sizes.
12
- - `serviceWorker`: compiles `serviceWorker.worker` into a classic script at `assetName` (default: the worker's file name with a `.js` extension).
13
- - `registration` is added to `index.html`. Without it, genx adds a script that registers the worker once the page has loaded.
14
- - Workbox `injectManifest` fills `self.__WB_MANIFEST` with every emitted file except those matched by `exclude`. As in the Webpack builder, strings match as prefixes, functions receive `{ asset }`, and the default is `[/\.map$/, /^manifest.*\.js$/]`.
15
- - Files over `maximumFileSizeToCache` are left out of the precache with a warning.
16
- - `precache: false` builds a worker that doesn't precache, so it needn't reference `self.__WB_MANIFEST`.
17
- - Under `genx dev` the worker is bundled on request and served at `assetName`, with an empty precache manifest.
18
-
19
- When neither option is configured, output remains unchanged.
20
6
 
21
7
  ## Installation
22
8
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;yBA6CrC,KAAK,YAAY;AAAvC,wBAgSE"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;yBA4CrC,KAAK,YAAY;AAAvC,wBA6RE"}
package/dist/index.js CHANGED
@@ -5,7 +5,6 @@ const node_fs_1 = require("node:fs");
5
5
  const node_path_1 = require("node:path");
6
6
  const build_kit_1 = require("@genesislcap/build-kit");
7
7
  const consola_1 = tslib_1.__importDefault(require("consola"));
8
- const pwa_js_1 = require("./pwa.js");
9
8
  const vite_js_1 = require("./vite.js");
10
9
  /**
11
10
  * There seems to be various documented issues using Vite in a monorepo setup that are impacted by various factors.
@@ -155,7 +154,6 @@ exports.default = (ctx) => tslib_1.__awaiter(void 0, void 0, void 0, function* (
155
154
  typescript: { tsconfigPath, buildMode },
156
155
  })
157
156
  : null;
158
- const pwaPlugins = yield (0, pwa_js_1.resolvePwaPlugins)(ctx);
159
157
  const baseHrefPlugin = {
160
158
  name: 'genesis-base-href',
161
159
  transformIndexHtml(html) {
@@ -181,7 +179,6 @@ exports.default = (ctx) => tslib_1.__awaiter(void 0, void 0, void 0, function* (
181
179
  insertEntryPoint: true,
182
180
  },
183
181
  }),
184
- ...pwaPlugins,
185
182
  ],
186
183
  resolve: {
187
184
  alias: Object.assign(Object.assign({}, alias), { 'foundationRapid/RapidDesignSystem': '@genesislcap/rapid-design-system' }),
package/dist/vite.d.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  import { Plugin } from 'vite';
2
- import type { VitePWAOptions } from 'vite-plugin-pwa';
3
2
  export declare const getHandlebarsModule: () => Promise<(...args: any) => Promise<Plugin>>;
4
3
  export declare const getCheckerModule: () => Promise<(...args: any) => Plugin>;
5
4
  export declare const getViteModule: () => Promise<{
6
5
  build: any;
7
6
  createServer: any;
8
7
  }>;
9
- export declare const getPwaModule: () => Promise<(options: Partial<VitePWAOptions>) => Plugin[]>;
10
8
  //# sourceMappingURL=vite.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAC9B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAWtD,eAAO,MAAM,mBAAmB,0BACuC,GAAG,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA,CAAC;AAE/F,eAAO,MAAM,gBAAgB,0BACuC,GAAG,KAAK,MAAM,CAAA,CAAC;AAEnF,eAAO,MAAM,aAAa;;;EAMzB,CAAC;AAEF,eAAO,MAAM,YAAY,0BAEZ,OAAO,CAAC,cAAc,CAAC,KAC7B,MAAM,EAAE,CAAA,CAAC"}
1
+ {"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAW9B,eAAO,MAAM,mBAAmB,0BACuC,GAAG,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA,CAAC;AAE/F,eAAO,MAAM,gBAAgB,0BACuC,GAAG,KAAK,MAAM,CAAA,CAAC;AAEnF,eAAO,MAAM,aAAa;;;EAMzB,CAAC"}
package/dist/vite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getPwaModule = exports.getViteModule = exports.getCheckerModule = exports.getHandlebarsModule = void 0;
3
+ exports.getViteModule = exports.getCheckerModule = exports.getHandlebarsModule = void 0;
4
4
  const tslib_1 = require("tslib");
5
5
  /**
6
6
  * This is a glue layer to import the ESM modules into the commonjs plugin.
@@ -22,7 +22,3 @@ const getViteModule = () => tslib_1.__awaiter(void 0, void 0, void 0, function*
22
22
  };
23
23
  });
24
24
  exports.getViteModule = getViteModule;
25
- const getPwaModule = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
26
- return (yield dynamicImport('vite-plugin-pwa')).VitePWA;
27
- });
28
- exports.getPwaModule = getPwaModule;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@genesislcap/vite-builder",
3
3
  "description": "Vite builder",
4
- "version": "15.79.2-alpha-e9d30db797.0",
4
+ "version": "15.80.0-FUI-2666.1",
5
5
  "license": "SEE LICENSE IN license.txt",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -12,22 +12,16 @@
12
12
  "build": "npm run clean && tsc -b ./tsconfig.json",
13
13
  "clean": "rimraf dist temp tsconfig.tsbuildinfo",
14
14
  "dev": "tsc -b ./tsconfig.json -w",
15
- "test": "uvu -r tsx/cjs test 'test.ts'",
16
15
  "lint": "genx lint -l ox",
17
16
  "lint:fix": "genx lint -l ox --fix"
18
17
  },
19
- "devDependencies": {
20
- "tsx": "^4.7.0",
21
- "uvu": "0.5.6"
22
- },
23
18
  "dependencies": {
24
- "@genesislcap/build-kit": "15.79.2-alpha-e9d30db797.0",
19
+ "@genesislcap/build-kit": "15.80.0-FUI-2666.1",
25
20
  "consola": "^3.0.2",
26
21
  "copyfiles": "^2.4.1",
27
22
  "vite": "^7.2.2",
28
23
  "vite-plugin-checker": "^0.11.0",
29
- "vite-plugin-handlebars": "^2.0.3",
30
- "vite-plugin-pwa": "^2.0.0"
24
+ "vite-plugin-handlebars": "^2.0.3"
31
25
  },
32
26
  "repository": {
33
27
  "type": "git",
package/dist/pwa.d.ts DELETED
@@ -1,40 +0,0 @@
1
- import type { BuildContext, PWAIcon, PWAManifest } from '@genesislcap/build-kit';
2
- import type { HtmlTagDescriptor, Plugin, ResolvedConfig } from 'vite';
3
- import type { VitePWAOptions } from 'vite-plugin-pwa';
4
- type ServiceWorkerConfig = BuildContext['config']['serviceWorker'];
5
- type ExcludePattern = ServiceWorkerConfig['exclude'][number];
6
- export interface ManifestIcon {
7
- src: string;
8
- sizes: string;
9
- type: string;
10
- purpose?: string;
11
- }
12
- export interface ResolvedManifestIcons {
13
- icons: ManifestIcon[];
14
- appleTags: HtmlTagDescriptor[];
15
- /** Output file name to source path, for icons that are not served from `public/` */
16
- files: Map<string, string>;
17
- }
18
- export declare const iconMimeType: (src: string) => string;
19
- export declare const resolveManifestIcons: (icons: PWAIcon | PWAIcon[] | undefined, base: string, cwd: string) => ResolvedManifestIcons;
20
- export declare const appleHeadTags: (pwa: PWAManifest) => HtmlTagDescriptor[];
21
- export declare const resolveManifest: (pwa: PWAManifest, base: string, cwd: string) => {
22
- manifest: Record<string, unknown>;
23
- appleTags: HtmlTagDescriptor[];
24
- iconFiles: Map<string, string>;
25
- };
26
- export declare const createManifestPlugin: (pwa: PWAManifest, cwd: string) => Plugin;
27
- export declare const createExcludeTransform: (patterns: ExcludePattern[]) => <T extends {
28
- url: string;
29
- }>(entries: T[]) => Promise<{
30
- manifest: T[];
31
- warnings: string[];
32
- }>;
33
- export declare const createServiceWorkerOptions: (serviceWorker: ServiceWorkerConfig) => Partial<VitePWAOptions>;
34
- export declare const bundleServiceWorker: (swSrc: string, config: ResolvedConfig) => Promise<{
35
- code: string;
36
- moduleIds: Set<string>;
37
- }>;
38
- export declare const resolvePwaPlugins: (ctx: BuildContext) => Promise<Plugin[]>;
39
- export {};
40
- //# sourceMappingURL=pwa.d.ts.map
package/dist/pwa.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"pwa.d.ts","sourceRoot":"","sources":["../src/pwa.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EACZ,OAAO,EAGP,WAAW,EACZ,MAAM,wBAAwB,CAAC;AAOhC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,EAAE,cAAc,EAAU,MAAM,MAAM,CAAC;AAC9E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAGtD,KAAK,mBAAmB,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC,eAAe,CAAC,CAAC;AACnE,KAAK,cAAc,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC;AAE7D,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,YAAY,EAAE,CAAC;IACtB,SAAS,EAAE,iBAAiB,EAAE,CAAC;IAC/B,oFAAoF;IACpF,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC5B;AA8CD,eAAO,MAAM,YAAY,GAAI,KAAK,MAAM,KAAG,MAK1C,CAAC;AAoBF,eAAO,MAAM,oBAAoB,GAC/B,OAAO,OAAO,GAAG,OAAO,EAAE,GAAG,SAAS,EACtC,MAAM,MAAM,EACZ,KAAK,MAAM,KACV,qBA6BF,CAAC;AAWF,eAAO,MAAM,aAAa,GAAI,KAAK,WAAW,KAAG,iBAAiB,EAqBjE,CAAC;AAEF,eAAO,MAAM,eAAe,GAAI,KAAK,WAAW,EAAE,MAAM,MAAM,EAAE,KAAK,MAAM;;;;CAc1E,CAAC;AAEF,eAAO,MAAM,oBAAoB,GAAI,KAAK,WAAW,EAAE,KAAK,MAAM,KAAG,MAwDpE,CAAC;AAiDF,eAAO,MAAM,sBAAsB,GAChC,UAAU,cAAc,EAAE,MACpB,CAAC,SAAS;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,SAAS,CAAC,EAAE;;cAI5B,MAAM,EAAE;EACxB,CAAC;AAUL,eAAO,MAAM,0BAA0B,GACrC,eAAe,mBAAmB,KACjC,OAAO,CAAC,cAAc,CAwBxB,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAU,OAAO,MAAM,EAAE,QAAQ,cAAc;;;EAwB9E,CAAC;AA2CF,eAAO,MAAM,iBAAiB,GAAU,KAAK,YAAY,KAAG,OAAO,CAAC,MAAM,EAAE,CAsB3E,CAAC"}
package/dist/pwa.js DELETED
@@ -1,347 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolvePwaPlugins = exports.bundleServiceWorker = exports.createServiceWorkerOptions = exports.createExcludeTransform = exports.createManifestPlugin = exports.resolveManifest = exports.appleHeadTags = exports.resolveManifestIcons = exports.iconMimeType = void 0;
4
- const tslib_1 = require("tslib");
5
- const node_fs_1 = require("node:fs");
6
- const node_path_1 = require("node:path");
7
- const build_kit_1 = require("@genesislcap/build-kit");
8
- const consola_1 = tslib_1.__importDefault(require("consola"));
9
- const vite_js_1 = require("./vite.js");
10
- const MANIFEST_FILE_NAME = 'manifest.json';
11
- // workbox-webpack-plugin's default `exclude`
12
- const DEFAULT_SW_EXCLUDE = [/\.map$/, /^manifest.*\.js$/];
13
- // webpack-pwa-manifest options (snake_cased) that are not Web App Manifest members
14
- const NON_MANIFEST_KEYS = [
15
- 'crossorigin',
16
- 'filename',
17
- 'fingerprints',
18
- 'icon',
19
- 'include_directory',
20
- 'inject',
21
- 'ios',
22
- 'public_path',
23
- 'use_webpack_public_path',
24
- ];
25
- const APPLE_META_TAGS = [
26
- 'apple-mobile-web-app-title',
27
- 'apple-mobile-web-app-capable',
28
- 'apple-mobile-web-app-status-bar-style',
29
- ];
30
- const ICON_MIME_TYPES = {
31
- svg: 'image/svg+xml',
32
- png: 'image/png',
33
- ico: 'image/x-icon',
34
- webp: 'image/webp',
35
- jpg: 'image/jpeg',
36
- jpeg: 'image/jpeg',
37
- };
38
- const PUBLIC_DIR_PREFIX = /^(\.\/)?public\//;
39
- const REMOTE_SRC = /^(https?:|data:)/;
40
- const withTrailingSlash = (path) => (path.endsWith('/') ? path : `${path}/`);
41
- const stripSrcDir = (path) => path.replace(/^\.?\/?src\//, '');
42
- const formatSize = (size) => /^\d+$/.test(String(size)) ? `${size}x${size}` : String(size);
43
- const headTag = (tag, attrs) => ({
44
- tag,
45
- attrs,
46
- injectTo: 'head',
47
- });
48
- const iconMimeType = (src) => {
49
- var _a, _b;
50
- const dataUriType = (_a = /^data:([^;,]+)/.exec(src)) === null || _a === void 0 ? void 0 : _a[1];
51
- if (dataUriType)
52
- return dataUriType;
53
- const ext = (0, node_path_1.extname)(src.split(/[?#]/)[0]).slice(1).toLowerCase();
54
- return (_b = ICON_MIME_TYPES[ext]) !== null && _b !== void 0 ? _b : 'image/png';
55
- };
56
- exports.iconMimeType = iconMimeType;
57
- const locateIcon = (icon, base, cwd) => {
58
- var _a;
59
- const { src } = icon;
60
- const publicUrl = `${base}${src.replace(PUBLIC_DIR_PREFIX, '').replace(/^\//, '')}`;
61
- if (REMOTE_SRC.test(src))
62
- return { url: src };
63
- if (PUBLIC_DIR_PREFIX.test(src) || src.startsWith('/'))
64
- return { url: publicUrl };
65
- const file = (0, node_path_1.resolve)(cwd, src);
66
- if ((0, node_fs_1.existsSync)(file)) {
67
- const destination = withTrailingSlash(((_a = icon.destination) !== null && _a !== void 0 ? _a : 'icons').replace(/^\.?\//, ''));
68
- const fileName = `${destination}${(0, node_path_1.basename)(src)}`;
69
- return { url: `${base}${fileName}`, file, fileName };
70
- }
71
- if (!(0, node_fs_1.existsSync)((0, node_path_1.resolve)(cwd, 'public', src))) {
72
- consola_1.default.warn(`PWA icon ${src} not found in ${cwd} or its public directory.`);
73
- }
74
- return { url: publicUrl };
75
- };
76
- const resolveManifestIcons = (icons, base, cwd) => {
77
- var _a;
78
- const resolved = { icons: [], appleTags: [], files: new Map() };
79
- for (const icon of icons ? [icons].flat() : []) {
80
- const { url, file, fileName } = locateIcon(icon, base, cwd);
81
- const type = icon.type || (0, exports.iconMimeType)(icon.src);
82
- const declaredSizes = [(_a = icon.sizes) !== null && _a !== void 0 ? _a : icon.size].flat().filter(Boolean);
83
- const sizes = declaredSizes.length ? declaredSizes.map(formatSize) : ['any'];
84
- if (file)
85
- resolved.files.set(fileName, file);
86
- if (sizes.length > 1 && type !== 'image/svg+xml') {
87
- consola_1.default.warn(`PWA icon ${icon.src} is declared at ${sizes.join(', ')}, but the Vite builder does not resize icons. Add one icon entry per size.`);
88
- }
89
- for (const size of sizes) {
90
- resolved.icons.push(Object.assign({ src: url, sizes: size, type }, (icon.purpose ? { purpose: icon.purpose } : {})));
91
- if (icon.ios) {
92
- const rel = icon.ios === 'startup' ? 'apple-touch-startup-image' : 'apple-touch-icon';
93
- resolved.appleTags.push(headTag('link', { rel, sizes: size, href: url }));
94
- }
95
- }
96
- }
97
- return resolved;
98
- };
99
- exports.resolveManifestIcons = resolveManifestIcons;
100
- const appleTouchIconTag = (value) => {
101
- const { href, sizes } = typeof value === 'string' ? { href: value, sizes: undefined } : value;
102
- return headTag('link', Object.assign({ rel: 'apple-touch-icon', href }, (sizes ? { sizes: String(sizes) } : {})));
103
- };
104
- const appleHeadTags = (pwa) => {
105
- if (!pwa.ios)
106
- return [];
107
- const apple = Object.assign({ 'apple-mobile-web-app-title': pwa.name, 'apple-mobile-web-app-capable': 'yes', 'apple-mobile-web-app-status-bar-style': 'default' }, (typeof pwa.ios === 'object' ? pwa.ios : {}));
108
- return Object.entries(apple).flatMap(([name, value]) => {
109
- if (APPLE_META_TAGS.includes(name)) {
110
- const content = typeof value === 'boolean' ? (value ? 'yes' : 'no') : String(value);
111
- return [headTag('meta', { name, content })];
112
- }
113
- if (name === 'apple-touch-icon') {
114
- return [appleTouchIconTag(value)];
115
- }
116
- if (name === 'apple-touch-startup-image') {
117
- return [headTag('link', { rel: name, href: String(value) })];
118
- }
119
- return [];
120
- });
121
- };
122
- exports.appleHeadTags = appleHeadTags;
123
- const resolveManifest = (pwa, base, cwd) => {
124
- var _a, _b, _c, _d;
125
- const fields = Object.fromEntries(Object.entries((0, build_kit_1.objToSnakeCase)(pwa)).filter(([key]) => !NON_MANIFEST_KEYS.includes(key)));
126
- const { icons, appleTags, files } = (0, exports.resolveManifestIcons)(pwa.icons, base, cwd);
127
- const manifest = Object.assign(Object.assign(Object.assign({}, fields), { short_name: (_a = fields.short_name) !== null && _a !== void 0 ? _a : pwa.name, start_url: (_b = fields.start_url) !== null && _b !== void 0 ? _b : '.', scope: (_c = fields.scope) !== null && _c !== void 0 ? _c : base, display: (_d = fields.display) !== null && _d !== void 0 ? _d : 'standalone' }), (pwa.icons ? { icons } : {}));
128
- return { manifest, appleTags, iconFiles: files };
129
- };
130
- exports.resolveManifest = resolveManifest;
131
- const createManifestPlugin = (pwa, cwd) => {
132
- let base;
133
- let resolved;
134
- const manifestJson = () => JSON.stringify(resolved.manifest, null, 2);
135
- return {
136
- name: 'genesis-pwa-manifest',
137
- configResolved(config) {
138
- // Resolved per config so a dev restart picks up a changed PUBLIC_PATH
139
- base = withTrailingSlash(typeof pwa.publicPath === 'string' ? pwa.publicPath : config.base);
140
- resolved = (0, exports.resolveManifest)(pwa, base, cwd);
141
- },
142
- transformIndexHtml(html) {
143
- const themeColor = resolved.manifest.theme_color;
144
- const tags = [
145
- ...(html.includes('rel="manifest"')
146
- ? []
147
- : [
148
- headTag('link', Object.assign({ rel: 'manifest', href: `${base}${MANIFEST_FILE_NAME}` }, (pwa.crossorigin ? { crossorigin: pwa.crossorigin } : {}))),
149
- ]),
150
- ...(typeof themeColor === 'string' && !html.includes('name="theme-color"')
151
- ? [headTag('meta', { name: 'theme-color', content: themeColor })]
152
- : []),
153
- ...(0, exports.appleHeadTags)(pwa),
154
- ...resolved.appleTags,
155
- ];
156
- return { html, tags };
157
- },
158
- configureServer(server) {
159
- server.middlewares.use((req, res, next) => {
160
- var _a, _b;
161
- const path = (_b = (_a = req.url) === null || _a === void 0 ? void 0 : _a.split('?')[0]) !== null && _b !== void 0 ? _b : '';
162
- if (path === `${base}${MANIFEST_FILE_NAME}`) {
163
- res.setHeader('Content-Type', 'application/manifest+json');
164
- res.end(manifestJson());
165
- return;
166
- }
167
- const iconFile = path.startsWith(base) && resolved.iconFiles.get(path.slice(base.length));
168
- if (iconFile) {
169
- res.setHeader('Content-Type', (0, exports.iconMimeType)(iconFile));
170
- res.end((0, node_fs_1.readFileSync)(iconFile));
171
- return;
172
- }
173
- next();
174
- });
175
- },
176
- generateBundle() {
177
- this.emitFile({ type: 'asset', fileName: MANIFEST_FILE_NAME, source: manifestJson() });
178
- for (const [fileName, file] of resolved.iconFiles) {
179
- this.emitFile({ type: 'asset', fileName, source: (0, node_fs_1.readFileSync)(file) });
180
- }
181
- },
182
- };
183
- };
184
- exports.createManifestPlugin = createManifestPlugin;
185
- const createRegistrationPlugin = (registration) => ({
186
- name: 'genesis-sw-registration',
187
- transformIndexHtml: {
188
- order: 'pre',
189
- handler(html) {
190
- const regPath = stripSrcDir(registration);
191
- const scriptTag = `<script type="module" src="/src/${regPath}"></script>`;
192
- if (html.includes(scriptTag) || html.includes(regPath))
193
- return html;
194
- if (html.includes('</head>')) {
195
- return html.replace('</head>', ` ${scriptTag}\n </head>`);
196
- }
197
- return html.replace('</body>', ` ${scriptTag}\n </body>`);
198
- },
199
- },
200
- });
201
- const createDefaultRegistrationPlugin = (assetName) => {
202
- let base;
203
- return {
204
- name: 'genesis-sw-registration',
205
- configResolved(config) {
206
- base = withTrailingSlash(config.base);
207
- },
208
- transformIndexHtml: {
209
- order: 'pre',
210
- handler: (html) => ({
211
- html,
212
- tags: [
213
- {
214
- tag: 'script',
215
- attrs: { type: 'module' },
216
- children: (0, build_kit_1.createServiceWorkerRegistration)(`${base}${assetName}`),
217
- injectTo: 'head',
218
- },
219
- ],
220
- }),
221
- },
222
- };
223
- };
224
- // Matches workbox-webpack-plugin: strings are prefixes and functions receive `{ asset }`
225
- const excludeMatches = (url, pattern) => {
226
- if (typeof pattern === 'string')
227
- return url.startsWith(pattern);
228
- if (pattern instanceof RegExp)
229
- return pattern.test(url);
230
- return pattern({ asset: { name: url } });
231
- };
232
- const createExcludeTransform = (patterns) => (entries) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
233
- return ({
234
- manifest: entries.filter(({ url }) => !patterns.some((pattern) => excludeMatches(url, pattern))),
235
- warnings: [],
236
- });
237
- });
238
- exports.createExcludeTransform = createExcludeTransform;
239
- const precacheOptions = (serviceWorker) => {
240
- var _a;
241
- return (Object.assign({ globPatterns: ['**/*'], manifestTransforms: [(0, exports.createExcludeTransform)((_a = serviceWorker.exclude) !== null && _a !== void 0 ? _a : DEFAULT_SW_EXCLUDE)] }, (serviceWorker.maximumFileSizeToCache
242
- ? { maximumFileSizeToCacheInBytes: serviceWorker.maximumFileSizeToCache }
243
- : {})));
244
- };
245
- const createServiceWorkerOptions = (serviceWorker) => {
246
- const assetName = (0, build_kit_1.getServiceWorkerAssetName)(serviceWorker);
247
- return {
248
- strategies: 'injectManifest',
249
- srcDir: 'src',
250
- filename: stripSrcDir(serviceWorker.worker),
251
- manifest: false,
252
- injectRegister: false,
253
- showMaximumFileSizeToCacheInBytesWarning: true,
254
- injectManifest: Object.assign({ rollupFormat: 'iife' }, (serviceWorker.precache === false
255
- ? { injectionPoint: undefined }
256
- : precacheOptions(serviceWorker))),
257
- integration: {
258
- beforeBuildServiceWorker(options) {
259
- const swDest = (0, node_path_1.resolve)(options.injectManifest.globDirectory, assetName);
260
- options.swDest = swDest;
261
- options.injectManifest.swDest = swDest;
262
- },
263
- },
264
- };
265
- };
266
- exports.createServiceWorkerOptions = createServiceWorkerOptions;
267
- const bundleServiceWorker = (swSrc, config) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
268
- const { build } = yield (0, vite_js_1.getViteModule)();
269
- const result = yield build({
270
- configFile: false,
271
- root: config.root,
272
- mode: config.mode,
273
- logLevel: 'warn',
274
- publicDir: false,
275
- resolve: { alias: config.resolve.alias, dedupe: config.resolve.dedupe },
276
- define: Object.assign(Object.assign({}, config.define), { 'process.env.NODE_ENV': JSON.stringify('development'), 'self.__WB_MANIFEST': '[]' }),
277
- build: {
278
- write: false,
279
- minify: false,
280
- emptyOutDir: false,
281
- lib: { entry: swSrc, name: 'serviceWorker', formats: ['iife'], fileName: 'service-worker' },
282
- },
283
- });
284
- const [{ output }] = [result].flat();
285
- const [chunk] = output;
286
- return { code: chunk.code, moduleIds: new Set(chunk.moduleIds) };
287
- });
288
- exports.bundleServiceWorker = bundleServiceWorker;
289
- // Rollup reports module ids as real paths, while the dev watcher reports them as configured
290
- const toRealPath = (file) => {
291
- try {
292
- return (0, node_fs_1.realpathSync)(file);
293
- }
294
- catch (_a) {
295
- return file;
296
- }
297
- };
298
- // Serves the worker at its built URL so the app's own registration script works under `genx dev`
299
- const createDevServiceWorkerPlugin = (serviceWorker, cwd) => {
300
- const assetName = (0, build_kit_1.getServiceWorkerAssetName)(serviceWorker);
301
- const swSrc = (0, node_path_1.resolve)(cwd, 'src', stripSrcDir(serviceWorker.worker));
302
- return {
303
- name: 'genesis-sw-dev',
304
- apply: 'serve',
305
- configureServer(server) {
306
- const urls = new Set([`${server.config.base}${assetName}`, `/${assetName}`]);
307
- let worker;
308
- let moduleIds = new Set();
309
- server.watcher.on('change', (file) => {
310
- if (moduleIds.has(toRealPath(file)))
311
- worker = undefined;
312
- });
313
- server.middlewares.use((req, res, next) => tslib_1.__awaiter(this, void 0, void 0, function* () {
314
- var _a;
315
- if (!urls.has((_a = req.url) === null || _a === void 0 ? void 0 : _a.split('?')[0]))
316
- return next();
317
- try {
318
- worker !== null && worker !== void 0 ? worker : (worker = (0, exports.bundleServiceWorker)(swSrc, server.config));
319
- const bundled = yield worker;
320
- moduleIds = bundled.moduleIds;
321
- res.setHeader('Content-Type', 'text/javascript');
322
- res.end(bundled.code);
323
- }
324
- catch (error) {
325
- worker = undefined;
326
- next(error);
327
- }
328
- }));
329
- },
330
- };
331
- };
332
- const resolvePwaPlugins = (ctx) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
333
- const { config: { pwa, serviceWorker }, dirs: { cwd }, cli: { isDev }, } = ctx;
334
- const plugins = [];
335
- if (pwa) {
336
- plugins.push((0, exports.createManifestPlugin)(pwa, cwd));
337
- }
338
- if (serviceWorker) {
339
- plugins.push(serviceWorker.registration
340
- ? createRegistrationPlugin(serviceWorker.registration)
341
- : createDefaultRegistrationPlugin((0, build_kit_1.getServiceWorkerAssetName)(serviceWorker)), ...(isDev
342
- ? [createDevServiceWorkerPlugin(serviceWorker, cwd)]
343
- : (yield (0, vite_js_1.getPwaModule)())((0, exports.createServiceWorkerOptions)(serviceWorker))));
344
- }
345
- return plugins;
346
- });
347
- exports.resolvePwaPlugins = resolvePwaPlugins;