@staticworks/sitekit 0.0.0-stage → 1.0.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
@@ -1,3 +1,193 @@
1
- # Temporary Holding Version
1
+ # @staticworks/sitekit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One shared build for small static sites. You write plain HTML, CSS and JS, add a few npm
4
+ packages (a font, a carousel), and sitekit turns it into a fast, production-ready site:
5
+
6
+ - every `.html` file is a page, with nice URLs (`site/en/index.html` → `/en/`)
7
+ - npm packages imported from CSS or JS, bundled and tree-shaken
8
+ - hashed file names for long-term caching
9
+ - minified HTML, CSS and JS
10
+ - compressed images, and responsive `<picture>` images from a single `?responsive` flag
11
+
12
+ It is [Vite](https://vite.dev) with one fixed setup, so there is no config to copy between sites.
13
+ Improve sitekit once and every site gets it on its next build.
14
+
15
+ ## Quick start
16
+
17
+ A site looks like this:
18
+
19
+ ```
20
+ my-site/
21
+ ├── site/
22
+ │ ├── index.html
23
+ │ ├── en/index.html
24
+ │ ├── main.css
25
+ │ ├── images/
26
+ │ └── public/ copied as-is: favicons, web manifest, _headers, robots.txt
27
+ └── package.json
28
+ ```
29
+
30
+ ```json
31
+ {
32
+ "private": true,
33
+ "scripts": {
34
+ "dev": "npx --yes @staticworks/sitekit@1 dev",
35
+ "build": "npx --yes @staticworks/sitekit@1 build",
36
+ "preview": "npx --yes @staticworks/sitekit@1 preview"
37
+ },
38
+ "dependencies": {
39
+ "@fontsource/inter": "^5.2.0"
40
+ }
41
+ }
42
+ ```
43
+
44
+ ```bash
45
+ npm run dev # dev server with live reload, http://localhost:5173
46
+ npm run build # site/ -> dist/
47
+ npm run preview # serve dist/ to check the build, http://localhost:4173
48
+ ```
49
+
50
+ sitekit is not installed in the site. `npx` fetches the newest 1.x, so every site stays on the
51
+ same build without a version bump in each repo. Run the commands from the site's root folder.
52
+
53
+ Add to the site's `.gitignore`: `node_modules/`, `dist/`, `.sitekit-cache/`.
54
+
55
+ ## Pages, CSS and JS
56
+
57
+ Write normal HTML. Links to local files are rewritten to the built, hashed files.
58
+
59
+ ```html
60
+ <link rel="stylesheet" href="/main.css">
61
+ <script type="module" src="/main.js"></script>
62
+ ```
63
+
64
+ npm packages are imported by name from CSS or a module script:
65
+
66
+ ```css
67
+ /* main.css */
68
+ @import "@fontsource/inter/400.css";
69
+ @import "swiper/css";
70
+ ```
71
+
72
+ ```html
73
+ <script type="module">
74
+ import Swiper from 'swiper';
75
+ new Swiper('.swiper', { loop: true });
76
+ </script>
77
+ ```
78
+
79
+ - Only `<script type="module">` is bundled. A classic `<script src>` is not processed or copied
80
+ (the build warns): add `type="module"`, or put the file in `site/public/`.
81
+ - Files in `site/public/` keep their names and are not processed. Link to them from the root
82
+ (`/favicon.ico`). Use it for files whose URL must not change, or that are only referenced from
83
+ places sitekit doesn't read, such as the icons inside a web manifest.
84
+
85
+ ## Images
86
+
87
+ Images linked from HTML and CSS are compressed at build time. If the compressed file comes out
88
+ larger, the original is kept.
89
+
90
+ ### Responsive images
91
+
92
+ Add `?responsive` to an `<img>` and say how wide it is shown with `sizes`:
93
+
94
+ ```html
95
+ <img src="/images/daiquiri.jpg?responsive" sizes="(min-width: 1024px) 420px, 100vw" alt="Daiquiri">
96
+ ```
97
+
98
+ sitekit replaces it with a full `<picture>`:
99
+
100
+ ```html
101
+ <picture>
102
+ <source type="image/avif" srcset="/assets/daiquiri-480w….avif 480w, …-800w….avif 800w, …" sizes="…">
103
+ <source type="image/webp" srcset="/assets/daiquiri-480w….webp 480w, …" sizes="…">
104
+ <img src="/assets/daiquiri-1363w….jpg" srcset="…" sizes="…" alt="Daiquiri"
105
+ width="1363" height="1280" loading="lazy" decoding="async">
106
+ </picture>
107
+ ```
108
+
109
+ - Widths: the site defaults (480, 800, 1200, 1600). Widths larger than the original are
110
+ dropped, and the original's own width is used as the top size instead.
111
+ - `width` and `height` are filled in from the image (prevents layout shift), unless you set them.
112
+ - `loading="lazy"` and `decoding="async"` are added unless you set them. Use
113
+ `loading="eager"` for the main image at the top of a page.
114
+ - Every other attribute (`alt`, `class`, …) is kept.
115
+ - Don't wrap it in your own `<picture>`; the build stops with an error if you do.
116
+
117
+ Options in the URL:
118
+
119
+ | Option | Example | Effect |
120
+ | --- | --- | --- |
121
+ | `widths` | `?responsive&widths=320,640` | other widths for this image |
122
+ | `quality` | `?responsive&quality=60` | other quality (1–100) for this image |
123
+
124
+ `sizes` tells the browser how wide the image is shown, so it can pick the smallest file that's
125
+ sharp enough. Only you know the layout, so set it on each `<img>`. Without it, the site default
126
+ applies (`100vw`: as wide as the screen).
127
+
128
+ ### Single variants
129
+
130
+ For one specific file, add options to any image URL in `src`, `srcset`, `href` or `content`:
131
+
132
+ ```html
133
+ <meta property="og:image" content="/images/hero.jpg?as=jpeg&width=1200">
134
+ <link rel="preload" as="image" href="/images/hero.jpg?as=avif&width=800">
135
+ ```
136
+
137
+ | Option | Short | Values |
138
+ | --- | --- | --- |
139
+ | `as` | `format` | `avif`, `webp`, `jpeg`, `png` |
140
+ | `width` | `w` | pixels; never wider than the original |
141
+ | `height` | `h` | pixels |
142
+ | `quality` | `q` | 1–100 |
143
+
144
+ Variants are made with [sharp](https://sharp.pixelplumbing.com) and cached in `.sitekit-cache/`,
145
+ so only new or changed images are processed. Responsive images and variants work in HTML only,
146
+ not in CSS `url()` or JS imports.
147
+
148
+ ## Settings
149
+
150
+ Everything has a default. To change something for one site, add a `"sitekit"` key to its
151
+ `package.json`:
152
+
153
+ ```json
154
+ {
155
+ "sitekit": {
156
+ "port": 3000,
157
+ "responsive": {
158
+ "widths": [400, 800, 1200],
159
+ "formats": ["avif", "webp"],
160
+ "sizes": "(min-width: 1024px) 50vw, 100vw"
161
+ },
162
+ "quality": { "jpeg": 75, "png": 80, "webp": 75, "avif": 55 }
163
+ }
164
+ }
165
+ ```
166
+
167
+ | Setting | Default | Meaning |
168
+ | --- | --- | --- |
169
+ | `port` | `5173` (dev), `4173` (preview) | local server port |
170
+ | `responsive.widths` | `[480, 800, 1200, 1600]` | widths made for `?responsive` images |
171
+ | `responsive.formats` | `["avif", "webp"]` | modern formats offered before the JPEG/PNG fallback |
172
+ | `responsive.sizes` | `"100vw"` | `sizes` for `?responsive` images that don't set their own |
173
+ | `quality.jpeg` / `png` / `webp` / `avif` | `80` / `80` / `80` / `60` | quality (1–100) for compression and variants |
174
+
175
+ Unknown keys and wrong values stop the build with a message, so typos don't go unnoticed.
176
+
177
+ ## Deploying
178
+
179
+ The build output is `dist/`, a plain folder of static files that any static host can serve.
180
+ The staticworks sites build and deploy it to Bunny Sites with the shared GitLab CI job in
181
+ [static-kit](https://gitlab.com/staticworks/static-kit) (`ci/build-deploy.yml`).
182
+
183
+ ## Releases
184
+
185
+ Sites use `@1`, so every 1.x release reaches them on their next build. Changes that could break
186
+ a site go to 2.0.0, and each site moves when it is ready.
187
+
188
+ To release, in static-kit: bump `version` in `bundler/package.json`, commit, and push the tag
189
+ `sitekit-v<version>`. CI publishes it to npm.
190
+
191
+ ## Requirements
192
+
193
+ Node.js 22.12 or newer.
package/bin/sitekit.js ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ import { build, createServer, preview } from 'vite';
3
+ import { createConfig } from '../lib/config.js';
4
+
5
+ const USAGE = `Usage: sitekit <command>
6
+
7
+ Run from the site's root folder (the one with site/).
8
+
9
+ Commands:
10
+ dev Start the dev server on site/
11
+ build Build site/ into dist/
12
+ preview Serve dist/ to check a build`;
13
+
14
+ const [command] = process.argv.slice(2);
15
+ const cwd = process.cwd();
16
+
17
+ try {
18
+ switch (command) {
19
+ case 'dev': {
20
+ const server = await createServer(await createConfig(cwd));
21
+ await server.listen();
22
+ server.printUrls();
23
+ server.bindCLIShortcuts({ print: true });
24
+ break;
25
+ }
26
+ case 'build':
27
+ await build(await createConfig(cwd));
28
+ break;
29
+ case 'preview': {
30
+ const server = await preview(await createConfig(cwd));
31
+ server.printUrls();
32
+ break;
33
+ }
34
+ case undefined:
35
+ case '-h':
36
+ case '--help':
37
+ console.log(USAGE);
38
+ break;
39
+ default:
40
+ console.error(`Unknown command: ${command}\n\n${USAGE}`);
41
+ process.exit(1);
42
+ }
43
+ } catch (error) {
44
+ console.error(error.message ?? error);
45
+ process.exit(1);
46
+ }
package/lib/config.js ADDED
@@ -0,0 +1,113 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join, relative, resolve } from 'node:path';
3
+ import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
4
+ import { imageVariants, RESPONSIVE_DEFAULTS, VARIANT_MARK } from './image-variants.js';
5
+ import { minifyHtml } from './minify-html.js';
6
+
7
+ const SKIP_DIRS = new Set(['public', 'node_modules']);
8
+
9
+ // Every .html file under site/ (except site/public/) is a page.
10
+ function findPages(siteDir) {
11
+ const pages = {};
12
+ const walk = (dir) => {
13
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
14
+ if (entry.name.startsWith('.')) continue;
15
+ const path = join(dir, entry.name);
16
+ if (entry.isDirectory()) {
17
+ if (dir === siteDir && SKIP_DIRS.has(entry.name)) continue;
18
+ walk(path);
19
+ } else if (entry.name.endsWith('.html')) {
20
+ const name = relative(siteDir, path).replace(/\.html$/, '');
21
+ pages[name] = path;
22
+ }
23
+ }
24
+ };
25
+ walk(siteDir);
26
+ return pages;
27
+ }
28
+
29
+ export const QUALITY_DEFAULTS = { jpeg: 80, png: 80, webp: 80, avif: 60 };
30
+ export const RESPONSIVE_KEYS = ['widths', 'formats', 'sizes'];
31
+ const SETTINGS_KEYS = ['port', 'responsive', 'quality'];
32
+
33
+ function fail(message) {
34
+ throw new Error(`package.json "sitekit": ${message}`);
35
+ }
36
+
37
+ // Site settings live under the "sitekit" key of the site's package.json.
38
+ export function readSettings(cwd) {
39
+ const file = resolve(cwd, 'package.json');
40
+ if (!existsSync(file)) return {};
41
+ const settings = JSON.parse(readFileSync(file, 'utf8')).sitekit ?? {};
42
+ for (const key of Object.keys(settings)) {
43
+ if (!SETTINGS_KEYS.includes(key)) fail(`unknown key "${key}" (expected ${SETTINGS_KEYS.join(', ')})`);
44
+ }
45
+ for (const key of Object.keys(settings.responsive ?? {})) {
46
+ if (!RESPONSIVE_KEYS.includes(key)) fail(`unknown key "responsive.${key}" (expected ${RESPONSIVE_KEYS.join(', ')})`);
47
+ }
48
+ for (const [format, value] of Object.entries(settings.quality ?? {})) {
49
+ if (!(format in QUALITY_DEFAULTS)) fail(`unknown format "quality.${format}" (expected ${Object.keys(QUALITY_DEFAULTS).join(', ')})`);
50
+ if (!(value >= 1 && value <= 100)) fail(`"quality.${format}" must be 1-100`);
51
+ }
52
+ const widths = settings.responsive?.widths;
53
+ if (widths && !(Array.isArray(widths) && widths.length && widths.every((w) => Number.isInteger(w) && w > 0))) {
54
+ fail('"responsive.widths" must be a list of positive whole numbers');
55
+ }
56
+ const formats = settings.responsive?.formats;
57
+ if (formats && !(Array.isArray(formats) && formats.every((f) => ['avif', 'webp'].includes(f)))) {
58
+ fail('"responsive.formats" must be a list of "avif" and/or "webp"');
59
+ }
60
+ return settings;
61
+ }
62
+
63
+ /**
64
+ * Builds the Vite config for the site in `cwd`.
65
+ * Layout: site/ (pages and assets), site/public/ (copied as-is), dist/ (output).
66
+ * Settings come from the "sitekit" key of the site's package.json (see readSettings).
67
+ */
68
+ export async function createConfig(cwd) {
69
+ const siteDir = resolve(cwd, 'site');
70
+ if (!existsSync(siteDir)) {
71
+ throw new Error(`No site/ folder in ${cwd}. Run sitekit from the site's root.`);
72
+ }
73
+
74
+ const settings = readSettings(cwd);
75
+ const quality = { ...QUALITY_DEFAULTS, ...settings.quality };
76
+ const compress = (format) => ({ quality: quality[format], ...(format === 'jpeg' && { mozjpeg: true }) });
77
+
78
+ return {
79
+ configFile: false,
80
+ root: siteDir,
81
+ publicDir: resolve(siteDir, 'public'),
82
+ cacheDir: resolve(cwd, 'node_modules/.vite'),
83
+ envDir: cwd,
84
+ appType: 'mpa',
85
+ server: { port: settings.port ?? 5173, fs: { allow: [cwd] } },
86
+ preview: { port: settings.port ?? 4173 },
87
+ build: {
88
+ outDir: resolve(cwd, 'dist'),
89
+ emptyOutDir: true,
90
+ // Never inline image variants as data: URLs; they belong in srcset as files.
91
+ assetsInlineLimit: (file) => (VARIANT_MARK.test(file) ? false : undefined),
92
+ rolldownOptions: { input: findPages(siteDir) },
93
+ },
94
+ plugins: [
95
+ imageVariants({
96
+ siteDir,
97
+ cacheDir: resolve(cwd, '.sitekit-cache/images'),
98
+ responsive: { ...RESPONSIVE_DEFAULTS, ...settings.responsive },
99
+ quality,
100
+ }),
101
+ ViteImageOptimizer({
102
+ exclude: VARIANT_MARK,
103
+ logStats: false,
104
+ jpeg: compress('jpeg'),
105
+ jpg: compress('jpeg'),
106
+ png: compress('png'),
107
+ webp: compress('webp'),
108
+ avif: compress('avif'),
109
+ }),
110
+ minifyHtml(),
111
+ ],
112
+ };
113
+ }
@@ -0,0 +1,186 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs';
3
+ import { basename, dirname, extname, join, relative, resolve } from 'node:path';
4
+ import sharp from 'sharp';
5
+
6
+ // Image variants written straight in the HTML.
7
+ //
8
+ // 1. Single variants, in src/srcset/href/content:
9
+ // <img srcset="/images/a.jpg?as=webp&width=640 640w, /images/a.jpg?as=webp&width=1080 1080w">
10
+ // Query keys: as|format (avif, webp, jpeg, png), width|w, height|h, quality|q.
11
+ // 2. Whole responsive images:
12
+ // <img src="/images/a.jpg?responsive" sizes="(min-width: 1024px) 420px, 100vw" alt="...">
13
+ // becomes a <picture> with AVIF and WebP sources plus a fallback <img>, at the site's
14
+ // default widths (or ?responsive&widths=640,1080), never wider than the original.
15
+ // sizes comes from the <img> (else the site default, else 100vw). It also fills in
16
+ // width/height, loading="lazy" and decoding="async" unless given.
17
+ //
18
+ // Each variant is made once with sharp into .sitekit-cache/images and then
19
+ // handed back to Vite as a normal file, so it gets hashed and emitted like any asset.
20
+
21
+ const ATTRS = /\b(src|srcset|href|content)="([^"]*\?[^"]*)"/g;
22
+ const URL_IN_ATTR = /([^\s,]+\?[^\s,]+)/g;
23
+ const IMAGE_EXT = /\.(jpe?g|png|webp|avif|gif|tiff?)$/i;
24
+ const FORMATS = { jpg: 'jpeg', jpeg: 'jpeg', png: 'png', webp: 'webp', avif: 'avif' };
25
+ const IMG_TAG = /<img\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
26
+ const TAG_ATTR = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
27
+
28
+ export const RESPONSIVE_DEFAULTS = { widths: [480, 800, 1200, 1600], formats: ['avif', 'webp'], sizes: '100vw' };
29
+
30
+ // Variants are already compressed; the optimizer skips files with this mark.
31
+ export const VARIANT_MARK = /\.v-[0-9a-f]{10}/;
32
+
33
+ const searchParams = (search) => new URLSearchParams(search.replace(/&amp;/g, '&'));
34
+
35
+ function parseQuery(search) {
36
+ const params = searchParams(search);
37
+ const get = (...keys) => keys.map((k) => params.get(k)).find((v) => v != null);
38
+ const format = get('as', 'format');
39
+ const width = get('width', 'w');
40
+ const height = get('height', 'h');
41
+ const quality = get('quality', 'q');
42
+ if (!format && !width && !height && !quality) return null;
43
+ return {
44
+ format: format && (FORMATS[format.toLowerCase()] ?? null),
45
+ width: width ? Number(width) : undefined,
46
+ height: height ? Number(height) : undefined,
47
+ quality: quality ? Number(quality) : undefined,
48
+ };
49
+ }
50
+
51
+ function parseTag(tag) {
52
+ const attrs = new Map();
53
+ const inner = tag.replace(/^<img\b/i, '').replace(/\/?>$/, '');
54
+ for (const m of inner.matchAll(TAG_ATTR)) attrs.set(m[1].toLowerCase(), m[2] ?? m[3] ?? m[4] ?? null);
55
+ return attrs;
56
+ }
57
+
58
+ const writeAttrs = (attrs) =>
59
+ [...attrs].map(([k, v]) => (v == null ? ` ${k}` : ` ${k}="${v}"`)).join('');
60
+
61
+ export function imageVariants({ siteDir, cacheDir, responsive, quality }) {
62
+ let command = 'build';
63
+ const made = new Map();
64
+
65
+ function sourceFile(path, url, htmlFile) {
66
+ const source = path.startsWith('/') ? join(siteDir, path) : resolve(dirname(htmlFile), path);
67
+ if (!existsSync(source)) throw new Error(`Image not found: ${url} (in ${relative(siteDir, htmlFile)})`);
68
+ return source;
69
+ }
70
+
71
+ // <img src="a.jpg?responsive"> -> <picture> with one srcset per format.
72
+ async function expandResponsive(tag, html, offset, htmlFile) {
73
+ const attrs = parseTag(tag);
74
+ const src = attrs.get('src') ?? '';
75
+ const q = src.indexOf('?');
76
+ if (q < 0) return tag;
77
+ const params = searchParams(src.slice(q + 1));
78
+ if (!params.has('responsive')) return tag;
79
+ if (html.lastIndexOf('<picture', offset) > html.lastIndexOf('</picture>', offset)) {
80
+ throw new Error(`?responsive makes its own <picture>; remove the one around ${src} (in ${relative(siteDir, htmlFile)})`);
81
+ }
82
+
83
+ const path = src.slice(0, q);
84
+ const meta = await sharp(sourceFile(path, src, htmlFile)).metadata();
85
+ const rotated = (meta.orientation ?? 1) >= 5;
86
+ const fullWidth = rotated ? meta.height : meta.width;
87
+ const fullHeight = rotated ? meta.width : meta.height;
88
+
89
+ const listed = params.get('widths')?.split(',').map(Number).filter((n) => n > 0);
90
+ const widths = [...new Set((listed?.length ? listed : responsive.widths).map((w) => Math.min(w, fullWidth)))]
91
+ .sort((a, b) => a - b);
92
+ const largest = widths.at(-1);
93
+ const quality = params.get('quality') ?? params.get('q');
94
+ const extra = quality ? `&quality=${quality}` : '';
95
+ const fallback = FORMATS[extname(path).slice(1).toLowerCase()] ?? 'jpeg';
96
+ const srcset = (format) => widths.map((w) => `${path}?as=${format}&width=${w}${extra} ${w}w`).join(', ');
97
+ const sizes = attrs.get('sizes') ?? responsive.sizes;
98
+
99
+ for (const name of ['src', 'srcset', 'sizes']) attrs.delete(name);
100
+ if (!attrs.has('width') && !attrs.has('height')) {
101
+ attrs.set('width', String(largest));
102
+ attrs.set('height', String(Math.round((fullHeight * largest) / fullWidth)));
103
+ }
104
+ if (!attrs.has('loading')) attrs.set('loading', 'lazy');
105
+ if (!attrs.has('decoding')) attrs.set('decoding', 'async');
106
+
107
+ const sources = responsive.formats
108
+ .filter((format) => FORMATS[format] !== fallback)
109
+ .map((format) => `<source type="image/${format}" srcset="${srcset(format)}" sizes="${sizes}">`);
110
+ const img = `<img src="${path}?as=${fallback}&width=${largest}${extra}" srcset="${srcset(fallback)}" sizes="${sizes}"${writeAttrs(attrs)}>`;
111
+ return `<picture>${sources.join('')}${img}</picture>`;
112
+ }
113
+
114
+ async function variantFor(sourcePath, opts) {
115
+ const stat = statSync(sourcePath);
116
+ const format = opts.format ?? FORMATS[extname(sourcePath).slice(1).toLowerCase()] ?? 'jpeg';
117
+ const q = opts.quality ?? quality[format];
118
+ const key = createHash('sha1')
119
+ .update(JSON.stringify([sourcePath, stat.size, stat.mtimeMs, opts.width, opts.height, format, q]))
120
+ .digest('hex')
121
+ .slice(0, 10);
122
+ const ext = format === 'jpeg' ? 'jpg' : format;
123
+ const name = basename(sourcePath, extname(sourcePath));
124
+ const label = opts.width ? `-${opts.width}w` : opts.height ? `-${opts.height}h` : '';
125
+ const out = join(cacheDir, `${name}${label}.v-${key}.${ext}`);
126
+ if (made.has(out)) return made.get(out);
127
+
128
+ const job = (async () => {
129
+ if (!existsSync(out)) {
130
+ mkdirSync(cacheDir, { recursive: true });
131
+ await sharp(readFileSync(sourcePath))
132
+ .rotate()
133
+ .resize({ width: opts.width, height: opts.height, withoutEnlargement: true })
134
+ .toFormat(format, { quality: q, mozjpeg: format === 'jpeg' })
135
+ .toFile(out);
136
+ }
137
+ return out;
138
+ })();
139
+ made.set(out, job);
140
+ return job;
141
+ }
142
+
143
+ async function rewriteUrl(url, htmlFile) {
144
+ const q = url.indexOf('?');
145
+ const path = url.slice(0, q);
146
+ if (!IMAGE_EXT.test(path) || /^[a-z]+:/i.test(path)) return url;
147
+ const opts = parseQuery(url.slice(q + 1));
148
+ if (!opts) return url;
149
+ const file = await variantFor(sourceFile(path, url, htmlFile), opts);
150
+ // Dev serves it from the filesystem; the build resolves it relative to the page.
151
+ return command === 'serve' ? `/@fs${file}` : relative(dirname(htmlFile), file);
152
+ }
153
+
154
+ return {
155
+ name: 'sitekit:image-variants',
156
+ configResolved(config) {
157
+ command = config.command;
158
+ },
159
+ transformIndexHtml: {
160
+ order: 'pre',
161
+ async handler(html, ctx) {
162
+ const htmlFile = ctx.filename;
163
+ const tags = [...html.matchAll(IMG_TAG)].filter((m) => /\?(?:[^"']*&(?:amp;)?)?responsive\b/.test(m[0]));
164
+ if (tags.length) {
165
+ const expanded = await Promise.all(tags.map((m) => expandResponsive(m[0], html, m.index, htmlFile)));
166
+ for (let i = tags.length - 1; i >= 0; i--) {
167
+ const { index } = tags[i];
168
+ html = html.slice(0, index) + expanded[i] + html.slice(index + tags[i][0].length);
169
+ }
170
+ }
171
+
172
+ const jobs = [];
173
+ html.replace(ATTRS, (_m, _attr, value) => {
174
+ for (const [url] of value.matchAll(URL_IN_ATTR)) jobs.push(url);
175
+ return _m;
176
+ });
177
+ if (!jobs.length) return html;
178
+ const urls = [...new Set(jobs)];
179
+ const map = new Map(await Promise.all(urls.map(async (u) => [u, await rewriteUrl(u, htmlFile)])));
180
+ return html.replace(ATTRS, (_m, attr, value) =>
181
+ `${attr}="${value.replace(URL_IN_ATTR, (u) => map.get(u) ?? u)}"`,
182
+ );
183
+ },
184
+ },
185
+ };
186
+ }
@@ -0,0 +1,24 @@
1
+ import { minify } from 'html-minifier-terser';
2
+
3
+ // Vite leaves HTML as written; minify the emitted pages at the end of the build.
4
+ export function minifyHtml() {
5
+ return {
6
+ name: 'sitekit:minify-html',
7
+ apply: 'build',
8
+ enforce: 'post',
9
+ async generateBundle(_options, bundle) {
10
+ for (const file of Object.values(bundle)) {
11
+ if (file.type !== 'asset' || !file.fileName.endsWith('.html')) continue;
12
+ file.source = await minify(String(file.source), {
13
+ collapseWhitespace: true,
14
+ conservativeCollapse: true,
15
+ removeComments: true,
16
+ minifyCSS: true,
17
+ minifyJS: true,
18
+ sortAttributes: true,
19
+ sortClassName: true,
20
+ });
21
+ }
22
+ },
23
+ };
24
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@staticworks/sitekit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Shared build for the staticworks static sites: Vite with multi-page HTML, hashed assets, minified HTML and compressed images.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "sitekit": "bin/sitekit.js"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "lib"
13
+ ],
14
+ "engines": {
15
+ "node": ">=22.12"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://gitlab.com/staticworks/static-kit.git",
20
+ "directory": "bundler"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "html-minifier-terser": "^7.2.0",
27
+ "sharp": "^0.35.6",
28
+ "svgo": "^4.1.0",
29
+ "vite": "^8.4.1",
30
+ "vite-plugin-image-optimizer": "^2.0.3"
31
+ }
32
+ }