@mednours/fronton 0.1.0

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 ADDED
@@ -0,0 +1,122 @@
1
+ # @mednours/fronton
2
+
3
+ Vite plugins and runtime helpers for a fronton-scaffolded project — installed automatically by [`create-fronton`](../create-fronton), or add by hand to an existing Vite project.
4
+
5
+ ```
6
+ bun add @mednours/fronton
7
+ ```
8
+
9
+ Two separate entry points, deliberately not one:
10
+
11
+ - **`@mednours/fronton`** (the root import) — Node-side, meant for `vite.config.ts` only: `obfuscateTailwind()`, `frontonCompression()`, `backonProxy()`.
12
+ - **`@mednours/fronton/client`** — browser-safe, meant for application code: `resolveApiBaseUrl()`.
13
+
14
+ Mixing these into one entry point was the first version's actual design, and it broke in a specific, findable way: importing `resolveApiBaseUrl` from a component pulled the *entire* bundle — including `postcss`, `magic-string`, and `vite-plugin-compression2` — into the client dependency graph, since esbuild had already flattened everything into a single file before Vite's bundler ever got a chance to tree-shake it. Vite's dependency scanner then warned about externalizing `node:crypto`, `node:fs`, and `zlib` for the browser, and the shipped JS bundle was measurably bigger for it (in one test project, 338 KB vs. 191 KB after the split — that's not a rounding error). Splitting the entry point at the source fixes it structurally instead of relying on a bundler to clean it up.
15
+
16
+ ## `obfuscateTailwind(options?)`
17
+
18
+ A build-only Vite plugin (`apply: "build"` — `bun run dev` stays fully readable). After Tailwind's CSS and the JS bundle are both fully generated, it collects every real class selector Tailwind actually emitted, hashes each one to a short opaque name, and rewrites both the stylesheet and known-safe class-bearing text in the built JS/HTML to match:
19
+
20
+ ```ts
21
+ import { obfuscateTailwind } from "@mednours/fronton";
22
+
23
+ export default defineConfig({
24
+ plugins: [react(), tailwindcss(), obfuscateTailwind()],
25
+ });
26
+ ```
27
+
28
+ It runs in `generateBundle`, strictly after Tailwind and Rollup/Rolldown have both finished — so there's no ordering dependency on how `@tailwindcss/vite` scans source for content, and no dependency on a class-merging helper's *name* surviving minification (it usually doesn't: `clsx(...)` routinely comes out the other side as `u(...)`, with no trace of the string "clsx" left anywhere). Class-bearing values are found by **position** — the value of a `className`/`class` property, however it got there — not by naming known helpers, which is what makes it keep working after minification renames everything around it.
29
+
30
+ What it rewrites:
31
+
32
+ - `className="..."` / `class="..."` (a plain string or template literal, in either compiled `className:"..."`/`className:\`...\`` object-property form or raw HTML attribute form)
33
+ - string-literal arguments inside *any* expression used as a `className`/`class` value — a `clsx()`/`cn()` call, a ternary, a logical expression — regardless of what produced it or what it's been renamed to
34
+
35
+ What it leaves alone, on purpose:
36
+
37
+ - a class list built at runtime from an array or object with no literal strings in scope
38
+ - a template literal with real `${}` interpolation
39
+
40
+ Every rewrite is checked against the real set of classes Tailwind's own generated CSS defines — a token only ever gets renamed if it's provably a real class, never a guess based on pattern-matching arbitrary text. That's what makes the failure mode "under-obfuscates a dynamic string" rather than "corrupts unrelated text somewhere in the bundle."
41
+
42
+ Options:
43
+
44
+ - `enabled` (default `true`) — turn the whole plugin off for a one-off debug build without editing `vite.config.ts`.
45
+ - `safelist` (default `[]`) — specific class names to never rename, for classes an external stylesheet, an end-to-end test selector, or a third-party script depends on by their real Tailwind name.
46
+ - `salt` (default `""`) — mixed into every class's hash. Two fronton projects with an identical class set otherwise produce identical hashes; set this if that's not what you want.
47
+
48
+ ## `frontonCompression(options?)`
49
+
50
+ Gzip + Brotli, every production build, on by default:
51
+
52
+ ```ts
53
+ import { frontonCompression } from "@mednours/fronton";
54
+
55
+ export default defineConfig({
56
+ plugins: [react(), tailwindcss(), obfuscateTailwind(), frontonCompression()],
57
+ });
58
+ ```
59
+
60
+ Order matters — list it after `obfuscateTailwind()` (as above) so the compressed files reflect the already-obfuscated output, not the pre-rename one. Options: `threshold` (default 1024 bytes — skip files too small for compression to pay for itself), `deleteOriginalAssets` (default `false` — keep the uncompressed copy alongside `.gz`/`.br` so a host that doesn't serve precompressed files still works), `overrides` (passed straight through to the underlying [`vite-plugin-compression2`](https://github.com/tomjs/vite-plugin-compression) for anything not covered above).
61
+
62
+ ## `backonProxy(target, options?)`
63
+
64
+ Builds a Vite dev-server `server.proxy` entry pointed at a [backon](https://github.com/mednours/backon) backend:
65
+
66
+ ```ts
67
+ import { backonProxy } from "@mednours/fronton";
68
+
69
+ export default defineConfig({
70
+ server: { proxy: backonProxy("http://localhost:3000") },
71
+ });
72
+ ```
73
+
74
+ `fetch("/api/users")` during `bun run dev` reaches the real backend with no CORS round-trip or hardcoded port baked into application code. `target` is a full origin; `create-fronton` fills this in automatically when it detects a sibling backon backend at scaffold time. Options: `prefix` (default `"/api"`), `stripPrefix` (default `true` — a request to `/api/users` reaches the backend as `/users`, matching how backon mounts routes at their real path rather than under an `/api` namespace of their own).
75
+
76
+ ## `resolveApiBaseUrl()` (from `@mednours/fronton/client`)
77
+
78
+ ```ts
79
+ import { resolveApiBaseUrl } from "@mednours/fronton/client";
80
+
81
+ fetch(`${resolveApiBaseUrl()}/api/users`);
82
+ ```
83
+
84
+ Reads `import.meta.env.VITE_API_BASE_URL`, returning `""` (relative requests) when it's unset — correct for same-origin deployment or the dev-server proxy above. This exists because the obvious alternative, a `process.env` check (the pattern backon's own generated `generate-client` script uses, correctly, since that script runs under Node/Bun), does nothing useful in a browser bundle: `process` isn't defined there, so the check just silently falls through. Only `VITE_`-prefixed variables are ever exposed to client code — Vite drops everything else on purpose, so a backend secret sitting in the same `.env` file never leaks into the browser bundle.
85
+
86
+ ## `compressImages(options?)` and `compressVideos(options?)`
87
+
88
+ Opt-in — not wired into `create-fronton`'s generated `vite.config.ts` by default, and not installed by default either (see "Peer dependencies" below). Both re-encode media files in the finished output directory in place, keeping the result only if it's smaller than the original — same "never make it worse" contract `frontonCompression`'s `skipIfLargerOrEqual` uses:
89
+
90
+ ```ts
91
+ import { compressImages, compressVideos, frontonCompression, obfuscateTailwind } from "@mednours/fronton";
92
+
93
+ export default defineConfig({
94
+ plugins: [react(), tailwindcss(), obfuscateTailwind(), frontonCompression(), compressImages(), compressVideos()],
95
+ });
96
+ ```
97
+
98
+ Both run in `closeBundle` — the last hook Vite/Rollup fire — and walk the real `outDir` on disk, not Rollup's in-memory bundle. That's a deliberate difference from `obfuscateTailwind`'s `generateBundle` approach, and it isn't cosmetic: `public/` is copied to `outDir` by Vite as a step outside Rollup's bundle machinery entirely, so a `generateBundle` hook never sees those files — and a hero video or photo living in `public/` (the common case; nobody `import`s a multi-megabyte video from a component) would silently never get touched by a generateBundle-based version of this. This was caught by actually running a real Vite build against the first version of these two plugins, not by reasoning about it — the first version compressed nothing on a real project and logged no error, because iterating over an empty match set doesn't look like a bug from the inside. Walking `outDir` after everything — Rollup's own output and the `public/` copy — is actually on disk is the only way to reach both.
99
+
100
+ **`compressImages`** re-encodes `.jpg`/`.jpeg`/`.png`/`.webp` through [`sharp`](https://sharp.pixelplumbing.com/) — `quality` (default `75`) for jpeg/webp, and lossy palette quantization (sharp's pngquant-equivalent) for png, which is where most of a PNG's real size win comes from, not a lossless recompress. This is a fixed-dimension, same-format squeeze — it doesn't generate multiple sizes, `srcset`, or `<picture>` markup with format fallbacks; reach for [`@responsive-image/vite-plugin`](https://www.npmjs.com/package/@responsive-image/vite-plugin) or `vite-imagetools` if you need that. It also can't reach a file small enough to fall under Vite's own `build.assetsInlineLimit` (4 KiB by default) — those get base64-inlined into JS/CSS text before this plugin ever runs, so there's no standalone file left to touch; that's rarely a real photo in practice. Options: `enabled`, `quality`, `extensions` (default `[".jpg", ".jpeg", ".png", ".webp"]`), `cacheDir`.
101
+
102
+ **`compressVideos`** re-encodes `.mp4` through ffmpeg (H.264/AAC, `+faststart`) via [`fluent-ffmpeg`](https://www.npmjs.com/package/fluent-ffmpeg) + [`ffmpeg-static`](https://www.npmjs.com/package/ffmpeg-static) — a prebuilt ffmpeg binary shipped as the npm package itself, so nothing needs to be separately installed or on `PATH`. Only `.mp4` by default: a `.webm` source is almost always already VP9/AV1, and re-encoding it through libx264 would silently change codec rather than just compress it — add other extensions via `extensions` only once you've confirmed libx264 is the right target. Options: `enabled`, `crf` (default `28` — noticeably smaller than libx264's own default of `23`), `preset` (default `"slow"` — worth spending more encode time than ffmpeg's own `"medium"` default, since the cost is paid once per unique input and cached), `extensions` (default `[".mp4"]`), `cacheDir`.
103
+
104
+ Both cache their output across builds (default `node_modules/.cache/fronton-media`, keyed by a hash of the file's own bytes plus the active options — same idea as `obfuscateTailwind`'s `salt`, so changing `quality`/`crf`/`preset` correctly busts the cache instead of serving a stale result). Re-encoding — video especially — is real CPU work; without this, every build (including every CI run) would pay that cost again for a file that hasn't changed since last time. Verified against real sharp/ffmpeg output, not mocked: a solid-color PNG shrinks ~92% via palette quantization, and a deliberately high-quality (low-crf) synthetic test clip shrinks measurably through the plugin's default crf 28 — both checked directly, and separately confirmed end-to-end in a real `vite build` against files placed in `public/`.
105
+
106
+ Neither plugin fails a build if its dependencies are missing — each logs a warning and does nothing, so leaving `sharp` or `fluent-ffmpeg`/`ffmpeg-static` uninstalled is a safe way to keep them present in `vite.config.ts` but effectively off.
107
+
108
+ ## Peer dependencies
109
+
110
+ `vite` is required. `sharp`, `fluent-ffmpeg`, and `ffmpeg-static` are optional peer dependencies — only needed if you actually use `compressImages`/`compressVideos`:
111
+
112
+ ```
113
+ bun add sharp # for compressImages
114
+ bun add fluent-ffmpeg ffmpeg-static # for compressVideos
115
+ bun add -D @types/fluent-ffmpeg # optional, for types
116
+ ```
117
+
118
+ They're kept out of `dependencies` on purpose: `sharp` and `ffmpeg-static` are large native binaries, and most projects using `obfuscateTailwind`/`frontonCompression`/`backonProxy` have no media to compress at all — there's no reason for `bun install` to pay for either one unless you're actually calling the function that needs it.
119
+
120
+ ## Requirements
121
+
122
+ Bun >= 1.3, Vite >= 8 (peer dependency — not bundled, so your project's own Vite is what actually runs).
@@ -0,0 +1,24 @@
1
+ import type { ProxyOptions } from "vite";
2
+ export interface BackonProxyOptions {
3
+ /** Path prefix on the dev server that gets forwarded to the backend. Default "/api". */
4
+ prefix?: string;
5
+ /**
6
+ * Strip `prefix` before forwarding, so a request to `/api/users` reaches
7
+ * the backend as `/users` — matching how backon mounts routes at their
8
+ * real path (`endpoints.route("/users", ...)`), not under an `/api`
9
+ * namespace of their own. Default true.
10
+ */
11
+ stripPrefix?: boolean;
12
+ }
13
+ /**
14
+ * Builds a Vite dev-server `server.proxy` entry pointed at a backon
15
+ * backend, so `fetch("/api/users")` from the frontend during `bun run dev`
16
+ * reaches the real backend without a CORS round-trip or hardcoded port —
17
+ * only the production build needs `VITE_API_BASE_URL` (or same-origin
18
+ * deployment) at all. `target` is a full origin, e.g.
19
+ * `http://localhost:3000` — create-fronton fills this in automatically
20
+ * when it detects a sibling backon backend at scaffold time; set it by
21
+ * hand otherwise.
22
+ */
23
+ export declare function backonProxy(target: string, options?: BackonProxyOptions): Record<string, ProxyOptions>;
24
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/backon/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,CAAC;AASzC,MAAM,WAAW,kBAAkB;IACjC,wFAAwF;IACxF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;;OAKG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,kBAAuB,GAAG,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAU1G"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Reads the API base URL a fronton project's own components should call
3
+ * against, at runtime, in the browser.
4
+ *
5
+ * This exists to fix a real gap: a plain `process.env.API_BASE_URL` check
6
+ * (the pattern backon's own generated `generate-client` script uses,
7
+ * correctly, since that script runs under Node/Bun) does nothing useful in
8
+ * a Vite-built browser bundle — `process` isn't defined there, so the
9
+ * check just silently falls through. Vite's own env mechanism is
10
+ * `import.meta.env`, statically replaced at build time, and only
11
+ * `VITE_`-prefixed variables are ever exposed to client code (Vite drops
12
+ * everything else on purpose, so a backend secret sitting in the same
13
+ * .env file never leaks into the browser bundle).
14
+ *
15
+ * Returns "" (relative requests) when unset — correct for same-origin
16
+ * deployment or a dev-server proxy (see backonProxy in the root entry
17
+ * point); set VITE_API_BASE_URL explicitly when the frontend and backend
18
+ * are on different origins.
19
+ */
20
+ export declare function resolveApiBaseUrl(): string;
21
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAG1C"}
package/dist/client.js ADDED
@@ -0,0 +1,8 @@
1
+ // src/client.ts
2
+ function resolveApiBaseUrl() {
3
+ const value = import.meta.env?.VITE_API_BASE_URL;
4
+ return typeof value === "string" && value.length > 0 ? value : "";
5
+ }
6
+ export {
7
+ resolveApiBaseUrl
8
+ };
@@ -0,0 +1,30 @@
1
+ import type { Plugin } from "vite";
2
+ import type { ViteCompressionPluginOption } from "vite-plugin-compression2";
3
+ export interface FrontonCompressionOptions {
4
+ /**
5
+ * Minimum file size (bytes) before a compressed copy is even attempted.
6
+ * Compressing a 200-byte chunk just adds build time and a slightly
7
+ * bigger deploy for no real win. Default 1024 (1 KiB).
8
+ */
9
+ threshold?: number;
10
+ /**
11
+ * Keep both the original and compressed assets in the build output
12
+ * (default) so a host that doesn't serve precompressed files still
13
+ * works — set to true only if you know your host always serves the
14
+ * compressed variant when the client accepts it (e.g. it rewrites
15
+ * Accept-Encoding: br to *.br transparently) and you want the smaller
16
+ * deploy.
17
+ */
18
+ deleteOriginalAssets?: boolean;
19
+ /** Passed straight through to vite-plugin-compression2 for anything not covered above. */
20
+ overrides?: Partial<ViteCompressionPluginOption>;
21
+ }
22
+ /**
23
+ * Gzip + Brotli compression for the production build, on by default in
24
+ * every fronton-scaffolded project. One plugin, both algorithms — most
25
+ * static hosts (Vercel included) will serve whichever the browser's
26
+ * Accept-Encoding actually asks for, so there's no real reason to ship
27
+ * only one.
28
+ */
29
+ export declare function frontonCompression(options?: FrontonCompressionOptions): Plugin;
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/compression/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAE5E,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;;;;OAOG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,0FAA0F;IAC1F,SAAS,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAC;CAClD;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,MAAM,CAUlF"}
@@ -0,0 +1,11 @@
1
+ export { obfuscateTailwind } from "./obfuscate/plugin";
2
+ export type { ObfuscateTailwindOptions } from "./obfuscate/plugin";
3
+ export { frontonCompression } from "./compression/index";
4
+ export type { FrontonCompressionOptions } from "./compression/index";
5
+ export { backonProxy } from "./backon/index";
6
+ export type { BackonProxyOptions } from "./backon/index";
7
+ export { compressImages } from "./media/images";
8
+ export type { CompressImagesOptions } from "./media/images";
9
+ export { compressVideos } from "./media/videos";
10
+ export type { CompressVideosOptions } from "./media/videos";
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,YAAY,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,YAAY,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAOzD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,YAAY,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,458 @@
1
+ // src/obfuscate/hash.ts
2
+ import { createHash } from "node:crypto";
3
+ function hashHex(input) {
4
+ return createHash("sha256").update(input).digest("hex");
5
+ }
6
+ function buildClassMap(classes, salt = "") {
7
+ const map = /* @__PURE__ */ new Map();
8
+ const used = /* @__PURE__ */ new Set();
9
+ for (const className of Array.from(classes).sort()) {
10
+ const digest = hashHex(`${salt}:${className}`);
11
+ let length = 6;
12
+ let candidate = `f${digest.slice(0, length)}`;
13
+ while (used.has(candidate) && length < digest.length) {
14
+ length += 2;
15
+ candidate = `f${digest.slice(0, length)}`;
16
+ }
17
+ used.add(candidate);
18
+ map.set(className, candidate);
19
+ }
20
+ return map;
21
+ }
22
+
23
+ // src/obfuscate/rewrite-css.ts
24
+ import postcss from "postcss";
25
+ import selectorParser from "postcss-selector-parser";
26
+ function collectClassesFromCss(css) {
27
+ const root = postcss.parse(css);
28
+ const classes = /* @__PURE__ */ new Set();
29
+ root.walkRules((rule) => {
30
+ selectorParser((selectors) => {
31
+ selectors.walkClasses((classNode) => {
32
+ classes.add(classNode.value);
33
+ });
34
+ }).processSync(rule.selector);
35
+ });
36
+ return classes;
37
+ }
38
+ function rewriteCssClasses(css, map) {
39
+ const root = postcss.parse(css);
40
+ root.walkRules((rule) => {
41
+ rule.selector = selectorParser((selectors) => {
42
+ selectors.walkClasses((classNode) => {
43
+ const replacement = map.get(classNode.value);
44
+ if (replacement) classNode.value = replacement;
45
+ });
46
+ }).processSync(rule.selector);
47
+ });
48
+ return root.toString();
49
+ }
50
+
51
+ // src/obfuscate/rewrite-text.ts
52
+ import MagicString from "magic-string";
53
+ var PROP_START = /\b(?:className|class)\s*(?::|=)\s*/g;
54
+ function rewriteClassList(list, map) {
55
+ let changed = false;
56
+ const text = list.split(/(\s+)/).map((token) => {
57
+ const replacement = map.get(token);
58
+ if (replacement) {
59
+ changed = true;
60
+ return replacement;
61
+ }
62
+ return token;
63
+ }).join("");
64
+ return { text, changed };
65
+ }
66
+ function scanExpressionEnd(code, start) {
67
+ let depth = 0;
68
+ let inString = null;
69
+ for (let i = start; i < code.length; i++) {
70
+ const ch = code[i];
71
+ if (inString) {
72
+ if (ch === "\\") {
73
+ i++;
74
+ continue;
75
+ }
76
+ if (ch === inString) inString = null;
77
+ continue;
78
+ }
79
+ if (ch === '"' || ch === "'" || ch === "`") {
80
+ inString = ch;
81
+ continue;
82
+ }
83
+ if (ch === "(" || ch === "[" || ch === "{") {
84
+ depth++;
85
+ continue;
86
+ }
87
+ if (ch === ")" || ch === "]" || ch === "}") {
88
+ if (depth === 0) return i;
89
+ depth--;
90
+ continue;
91
+ }
92
+ if (ch === "," && depth === 0) return i;
93
+ }
94
+ return code.length;
95
+ }
96
+ var QUOTE_CHARS = /* @__PURE__ */ new Set(['"', "'", "`"]);
97
+ var STRING_LITERAL_PATTERN = /(["'`])(?<lit>(?:\\.|(?!\1).)*)\1/gd;
98
+ function rewriteTextOutput(code, map) {
99
+ const s = new MagicString(code);
100
+ let count = 0;
101
+ for (const match of code.matchAll(PROP_START)) {
102
+ let i = match.index + match[0].length;
103
+ while (i < code.length && /\s/.test(code[i])) i++;
104
+ if (code[i] === "{") {
105
+ i++;
106
+ while (i < code.length && /\s/.test(code[i])) i++;
107
+ }
108
+ const ch = code[i];
109
+ if (ch !== void 0 && QUOTE_CHARS.has(ch)) {
110
+ const quote = ch;
111
+ let j = i + 1;
112
+ while (j < code.length && code[j] !== quote) {
113
+ if (code[j] === "\\") j++;
114
+ j++;
115
+ }
116
+ const start = i + 1;
117
+ const end = j;
118
+ const list = code.slice(start, end);
119
+ const { text, changed } = rewriteClassList(list, map);
120
+ if (changed) {
121
+ s.overwrite(start, end, text);
122
+ count++;
123
+ }
124
+ continue;
125
+ }
126
+ if (ch === void 0) continue;
127
+ const exprEnd = scanExpressionEnd(code, i);
128
+ const exprText = code.slice(i, exprEnd);
129
+ for (const litMatch of exprText.matchAll(STRING_LITERAL_PATTERN)) {
130
+ const range = litMatch.indices.groups.lit;
131
+ if (!range) continue;
132
+ const [relStart, relEnd] = range;
133
+ const start = i + relStart;
134
+ const end = i + relEnd;
135
+ const list = code.slice(start, end);
136
+ const { text, changed } = rewriteClassList(list, map);
137
+ if (changed) {
138
+ s.overwrite(start, end, text);
139
+ count++;
140
+ }
141
+ }
142
+ }
143
+ return { code: s.toString(), count };
144
+ }
145
+
146
+ // src/obfuscate/plugin.ts
147
+ var CSS_EXT = /\.css$/;
148
+ var JS_HTML_EXT = /\.(?:m?js|html)$/;
149
+ function obfuscateTailwind(options = {}) {
150
+ const { enabled = true, safelist = [], salt = "" } = options;
151
+ return {
152
+ name: "fronton:obfuscate-tailwind",
153
+ apply: "build",
154
+ enforce: "post",
155
+ generateBundle(_outputOptions, bundle) {
156
+ if (!enabled) return;
157
+ const cssAssets = Object.values(bundle).filter(
158
+ (item) => item.type === "asset" && CSS_EXT.test(item.fileName)
159
+ );
160
+ if (cssAssets.length === 0) return;
161
+ const allClasses = /* @__PURE__ */ new Set();
162
+ for (const asset of cssAssets) {
163
+ const source = typeof asset.source === "string" ? asset.source : Buffer.from(asset.source).toString("utf-8");
164
+ for (const className of collectClassesFromCss(source)) allClasses.add(className);
165
+ }
166
+ for (const skip of safelist) allClasses.delete(skip);
167
+ if (allClasses.size === 0) return;
168
+ const map = buildClassMap(allClasses, salt);
169
+ for (const asset of cssAssets) {
170
+ const source = typeof asset.source === "string" ? asset.source : Buffer.from(asset.source).toString("utf-8");
171
+ asset.source = rewriteCssClasses(source, map);
172
+ }
173
+ let renamedTokens = 0;
174
+ for (const item of Object.values(bundle)) {
175
+ if (!JS_HTML_EXT.test(item.fileName)) continue;
176
+ if (item.type === "chunk") {
177
+ const chunk = item;
178
+ const { code, count } = rewriteTextOutput(chunk.code, map);
179
+ chunk.code = code;
180
+ renamedTokens += count;
181
+ } else {
182
+ const source = typeof item.source === "string" ? item.source : Buffer.from(item.source).toString("utf-8");
183
+ const { code, count } = rewriteTextOutput(source, map);
184
+ item.source = code;
185
+ renamedTokens += count;
186
+ }
187
+ }
188
+ this.info(
189
+ `[fronton] obfuscated ${map.size} Tailwind class name(s) across ${cssAssets.length} stylesheet(s) (${renamedTokens} usage site(s) rewritten in built JS/HTML)`
190
+ );
191
+ }
192
+ };
193
+ }
194
+
195
+ // src/compression/index.ts
196
+ import { compression } from "vite-plugin-compression2";
197
+ function frontonCompression(options = {}) {
198
+ const { threshold = 1024, deleteOriginalAssets = false, overrides = {} } = options;
199
+ return compression({
200
+ algorithms: ["gzip", "brotliCompress"],
201
+ threshold,
202
+ deleteOriginalAssets,
203
+ skipIfLargerOrEqual: true,
204
+ ...overrides
205
+ });
206
+ }
207
+
208
+ // src/backon/index.ts
209
+ function backonProxy(target, options = {}) {
210
+ const { prefix = "/api", stripPrefix = true } = options;
211
+ return {
212
+ [prefix]: {
213
+ target,
214
+ changeOrigin: true,
215
+ ...stripPrefix ? { rewrite: (path) => path.replace(new RegExp(`^${prefix}`), "") } : {}
216
+ }
217
+ };
218
+ }
219
+
220
+ // src/media/images.ts
221
+ import { readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
222
+ import { resolve } from "node:path";
223
+
224
+ // src/media/cache.ts
225
+ import { createHash as createHash2 } from "node:crypto";
226
+ import { existsSync } from "node:fs";
227
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
228
+ import { join } from "node:path";
229
+ function hashKey(content, salt) {
230
+ return createHash2("sha256").update(salt).update(content).digest("hex");
231
+ }
232
+ function createMediaCache(cacheDir) {
233
+ return {
234
+ async get(content, salt) {
235
+ const path = join(cacheDir, hashKey(content, salt));
236
+ if (!existsSync(path)) return void 0;
237
+ try {
238
+ return await readFile(path);
239
+ } catch {
240
+ return void 0;
241
+ }
242
+ },
243
+ async set(content, salt, result) {
244
+ await mkdir(cacheDir, { recursive: true });
245
+ await writeFile(join(cacheDir, hashKey(content, salt)), result);
246
+ }
247
+ };
248
+ }
249
+ var DEFAULT_CACHE_DIR = "node_modules/.cache/fronton-media";
250
+
251
+ // src/media/format-bytes.ts
252
+ function formatBytes(n) {
253
+ if (n < 1024) return `${n} B`;
254
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
255
+ return `${(n / 1024 / 1024).toFixed(2)} MB`;
256
+ }
257
+ function extname(fileName) {
258
+ const i = fileName.lastIndexOf(".");
259
+ return i === -1 ? "" : fileName.slice(i).toLowerCase();
260
+ }
261
+
262
+ // src/media/walk-files.ts
263
+ import { readdir } from "node:fs/promises";
264
+ import { join as join2 } from "node:path";
265
+ async function walkFiles(dir, extSet) {
266
+ let entries;
267
+ try {
268
+ entries = await readdir(dir, { withFileTypes: true });
269
+ } catch {
270
+ return [];
271
+ }
272
+ const files = [];
273
+ for (const entry of entries) {
274
+ const full = join2(dir, entry.name);
275
+ if (entry.isDirectory()) {
276
+ files.push(...await walkFiles(full, extSet));
277
+ } else if (entry.isFile() && extSet.has(extname(entry.name))) {
278
+ files.push(full);
279
+ }
280
+ }
281
+ return files;
282
+ }
283
+
284
+ // src/media/images.ts
285
+ var DEFAULT_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp"];
286
+ async function loadSharp() {
287
+ try {
288
+ return (await import("sharp")).default;
289
+ } catch {
290
+ return void 0;
291
+ }
292
+ }
293
+ async function reencode(sharp, source, ext, quality) {
294
+ const image = sharp(source);
295
+ switch (ext) {
296
+ case ".jpg":
297
+ case ".jpeg":
298
+ return image.jpeg({ quality, mozjpeg: true }).toBuffer();
299
+ case ".webp":
300
+ return image.webp({ quality }).toBuffer();
301
+ case ".png":
302
+ return image.png({ quality, palette: true, compressionLevel: 9 }).toBuffer();
303
+ default:
304
+ throw new Error(`unsupported extension "${ext}"`);
305
+ }
306
+ }
307
+ function compressImages(options = {}) {
308
+ const { enabled = true, quality = 75, extensions = DEFAULT_EXTENSIONS, cacheDir = DEFAULT_CACHE_DIR } = options;
309
+ const cache = createMediaCache(cacheDir);
310
+ const extSet = new Set(extensions.map((e) => e.toLowerCase()));
311
+ let outDir = "";
312
+ return {
313
+ name: "fronton:compress-images",
314
+ apply: "build",
315
+ configResolved(config) {
316
+ outDir = resolve(config.root, config.build.outDir);
317
+ },
318
+ async closeBundle() {
319
+ if (!enabled) return;
320
+ const sharp = await loadSharp();
321
+ if (!sharp) {
322
+ this.warn(
323
+ '[fronton] compressImages is enabled but "sharp" isn\'t installed \u2014 skipping image compression. Run `bun add sharp` to use it.'
324
+ );
325
+ return;
326
+ }
327
+ const files = await walkFiles(outDir, extSet);
328
+ let originalBytes = 0;
329
+ let compressedBytes = 0;
330
+ let touched = 0;
331
+ for (const filePath of files) {
332
+ const ext = extname(filePath);
333
+ const source = await readFile2(filePath);
334
+ const salt = `${ext}:q${quality}`;
335
+ let result = await cache.get(source, salt);
336
+ if (!result) {
337
+ try {
338
+ result = await reencode(sharp, source, ext, quality);
339
+ } catch (err) {
340
+ this.warn(`[fronton] failed to compress ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
341
+ continue;
342
+ }
343
+ await cache.set(source, salt, result);
344
+ }
345
+ if (result.length < source.length) {
346
+ await writeFile2(filePath, result);
347
+ originalBytes += source.length;
348
+ compressedBytes += result.length;
349
+ touched++;
350
+ }
351
+ }
352
+ if (touched > 0) {
353
+ const pct = Math.round((1 - compressedBytes / originalBytes) * 100);
354
+ this.info(`[fronton] compressed ${touched} image(s): ${formatBytes(originalBytes)} -> ${formatBytes(compressedBytes)} (-${pct}%)`);
355
+ }
356
+ }
357
+ };
358
+ }
359
+
360
+ // src/media/videos.ts
361
+ import { mkdtemp, readFile as readFile3, rm, writeFile as writeFile3 } from "node:fs/promises";
362
+ import { tmpdir } from "node:os";
363
+ import { join as join3, resolve as resolve2 } from "node:path";
364
+ var DEFAULT_EXTENSIONS2 = [".mp4"];
365
+ async function loadFfmpeg() {
366
+ try {
367
+ const [{ default: ffmpeg }, { default: ffmpegPath }] = await Promise.all([import("fluent-ffmpeg"), import("ffmpeg-static")]);
368
+ return { ffmpeg, ffmpegPath };
369
+ } catch {
370
+ return void 0;
371
+ }
372
+ }
373
+ async function transcode(ffmpeg, source, ext, crf, preset) {
374
+ const dir = await mkdtemp(join3(tmpdir(), "fronton-video-"));
375
+ const inputPath = join3(dir, `input${ext}`);
376
+ const outputPath = join3(dir, `output${ext}`);
377
+ try {
378
+ await writeFile3(inputPath, source);
379
+ await new Promise((resolve3, reject) => {
380
+ ffmpeg(inputPath).videoCodec("libx264").outputOptions([
381
+ `-crf ${crf}`,
382
+ `-preset ${preset}`,
383
+ "-pix_fmt yuv420p",
384
+ // widest-compatibility pixel format — some source footage decodes to one Safari/older devices won't play back
385
+ "-movflags +faststart"
386
+ // moves the moov atom to the front so playback can start before the whole file has downloaded
387
+ ]).audioCodec("aac").audioBitrate("128k").on("error", (err) => reject(err)).on("end", () => resolve3()).save(outputPath);
388
+ });
389
+ return await readFile3(outputPath);
390
+ } finally {
391
+ await rm(dir, { recursive: true, force: true });
392
+ }
393
+ }
394
+ function compressVideos(options = {}) {
395
+ const { enabled = true, crf = 28, preset = "slow", extensions = DEFAULT_EXTENSIONS2, cacheDir = DEFAULT_CACHE_DIR } = options;
396
+ const cache = createMediaCache(cacheDir);
397
+ const extSet = new Set(extensions.map((e) => e.toLowerCase()));
398
+ let outDir = "";
399
+ return {
400
+ name: "fronton:compress-videos",
401
+ apply: "build",
402
+ configResolved(config) {
403
+ outDir = resolve2(config.root, config.build.outDir);
404
+ },
405
+ async closeBundle() {
406
+ if (!enabled) return;
407
+ const loaded = await loadFfmpeg();
408
+ if (!loaded) {
409
+ this.warn(
410
+ '[fronton] compressVideos is enabled but "fluent-ffmpeg"/"ffmpeg-static" aren\'t installed \u2014 skipping video compression. Run `bun add fluent-ffmpeg ffmpeg-static` to use it.'
411
+ );
412
+ return;
413
+ }
414
+ const { ffmpeg, ffmpegPath } = loaded;
415
+ if (!ffmpegPath) {
416
+ this.warn("[fronton] ffmpeg-static didn't resolve a binary for this platform \u2014 skipping video compression.");
417
+ return;
418
+ }
419
+ ffmpeg.setFfmpegPath(ffmpegPath);
420
+ const files = await walkFiles(outDir, extSet);
421
+ let originalBytes = 0;
422
+ let compressedBytes = 0;
423
+ let touched = 0;
424
+ for (const filePath of files) {
425
+ const ext = extname(filePath);
426
+ const source = await readFile3(filePath);
427
+ const salt = `${ext}:crf${crf}:${preset}`;
428
+ let result = await cache.get(source, salt);
429
+ if (!result) {
430
+ try {
431
+ result = await transcode(ffmpeg, source, ext, crf, preset);
432
+ } catch (err) {
433
+ this.warn(`[fronton] failed to compress ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
434
+ continue;
435
+ }
436
+ await cache.set(source, salt, result);
437
+ }
438
+ if (result.length < source.length) {
439
+ await writeFile3(filePath, result);
440
+ originalBytes += source.length;
441
+ compressedBytes += result.length;
442
+ touched++;
443
+ }
444
+ }
445
+ if (touched > 0) {
446
+ const pct = Math.round((1 - compressedBytes / originalBytes) * 100);
447
+ this.info(`[fronton] compressed ${touched} video(s): ${formatBytes(originalBytes)} -> ${formatBytes(compressedBytes)} (-${pct}%)`);
448
+ }
449
+ }
450
+ };
451
+ }
452
+ export {
453
+ backonProxy,
454
+ compressImages,
455
+ compressVideos,
456
+ frontonCompression,
457
+ obfuscateTailwind
458
+ };
@@ -0,0 +1,7 @@
1
+ export interface MediaCache {
2
+ get(content: Buffer, salt: string): Promise<Buffer | undefined>;
3
+ set(content: Buffer, salt: string, result: Buffer): Promise<void>;
4
+ }
5
+ export declare function createMediaCache(cacheDir: string): MediaCache;
6
+ export declare const DEFAULT_CACHE_DIR = "node_modules/.cache/fronton-media";
7
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/media/cache.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAChE,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnE;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,UAAU,CAgB7D;AAKD,eAAO,MAAM,iBAAiB,sCAAsC,CAAC"}
@@ -0,0 +1,4 @@
1
+ /** Shared by compressImages and compressVideos for their build-summary log line. */
2
+ export declare function formatBytes(n: number): string;
3
+ export declare function extname(fileName: string): string;
4
+ //# sourceMappingURL=format-bytes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"format-bytes.d.ts","sourceRoot":"","sources":["../../src/media/format-bytes.ts"],"names":[],"mappings":"AAAA,oFAAoF;AACpF,wBAAgB,WAAW,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAI7C;AAED,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAGhD"}
@@ -0,0 +1,49 @@
1
+ import type { Plugin } from "vite";
2
+ export interface CompressImagesOptions {
3
+ /** Default true — set false to disable without removing the plugin from vite.config.ts. */
4
+ enabled?: boolean;
5
+ /**
6
+ * 0-100, passed to sharp's own jpeg/webp/png encoders. Default 75 — sharp's
7
+ * own reasonable middle ground, not a fronton-specific tuning.
8
+ */
9
+ quality?: number;
10
+ /** Which output-directory file extensions to touch. Default [".jpg", ".jpeg", ".png", ".webp"]. */
11
+ extensions?: string[];
12
+ /** Where re-encoded output is cached across builds, keyed by content hash + these options. */
13
+ cacheDir?: string;
14
+ }
15
+ /**
16
+ * Build-only Vite plugin (`apply: "build"`) that re-encodes raster images in
17
+ * the finished output directory through sharp, in place, overwriting each
18
+ * file only if the result comes out smaller — same "never make it worse"
19
+ * contract frontonCompression's skipIfLargerOrEqual uses. No markup changes
20
+ * needed: this rewrites the same file at the same path, so both
21
+ * `<img src="/photo.jpg">` (a public/ file, copied verbatim by Vite) and a
22
+ * `import photo from "./photo.jpg"` reference (processed by Rollup, unless
23
+ * it's small enough to get base64-inlined — see the note on
24
+ * `build.assetsInlineLimit` below) keep working exactly as written.
25
+ *
26
+ * Runs in `closeBundle`, the last hook Vite/Rollup fire — by then `outDir`
27
+ * has everything: Rollup's own emitted assets *and* the verbatim `public/`
28
+ * copy, which happens as a separate step outside Rollup's bundle entirely
29
+ * and would never show up in a `generateBundle` hook. Walking the real
30
+ * output directory on disk is the only way to reach both.
31
+ *
32
+ * This is a fixed-dimension, same-format squeeze, not a responsive-image
33
+ * pipeline — it doesn't generate multiple sizes, `srcset`, or `<picture>`
34
+ * markup with format fallbacks. If you need that, reach for
35
+ * `@responsive-image/vite-plugin` or `vite-imagetools` instead; this plugin
36
+ * is for the common case of "the image is already the right dimensions,
37
+ * just ship fewer bytes for it." It also can't reach an image small enough
38
+ * to fall under Vite's own `build.assetsInlineLimit` (4 KiB by default) —
39
+ * those get base64-inlined directly into JS/CSS text before this plugin
40
+ * ever runs, so there's no standalone file left to compress. That's rarely
41
+ * a real photo or hero image in practice; lower `assetsInlineLimit` if it
42
+ * matters for your project.
43
+ *
44
+ * `sharp` is a peer dependency, not bundled — install it yourself
45
+ * (`bun add sharp`) to use this plugin. Left uninstalled, this plugin logs a
46
+ * warning and does nothing, rather than failing the build.
47
+ */
48
+ export declare function compressImages(options?: CompressImagesOptions): Plugin;
49
+ //# sourceMappingURL=images.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.d.ts","sourceRoot":"","sources":["../../src/media/images.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAC;AAKnD,MAAM,WAAW,qBAAqB;IACpC,2FAA2F;IAC3F,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mGAAmG;IACnG,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,8FAA8F;IAC9F,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAoCD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,CA2D1E"}
@@ -0,0 +1,5 @@
1
+ export { compressImages } from "./images";
2
+ export type { CompressImagesOptions } from "./images";
3
+ export { compressVideos } from "./videos";
4
+ export type { CompressVideosOptions } from "./videos";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/media/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,YAAY,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAC1C,YAAY,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC"}
@@ -0,0 +1,60 @@
1
+ import type { Plugin } from "vite";
2
+ export interface CompressVideosOptions {
3
+ /** Default true — set false to disable without removing the plugin from vite.config.ts. */
4
+ enabled?: boolean;
5
+ /**
6
+ * libx264's own quality knob — lower is higher quality and a bigger file.
7
+ * Default 28: noticeably smaller than x264's own default of 23, with a
8
+ * quality loss that's a fair trade for a web-delivered background/hero
9
+ * video (not archival footage).
10
+ */
11
+ crf?: number;
12
+ /**
13
+ * libx264 preset — trades encode time for compression efficiency at a
14
+ * given crf. Default "slow": this cost is paid once per unique input (see
15
+ * the cache in cache.ts), so it's worth spending more of it than ffmpeg's
16
+ * own "medium" default to land a meaningfully smaller file.
17
+ */
18
+ preset?: string;
19
+ /** Which output-directory file extensions to touch. Default [".mp4"] — see the plugin doc comment for why other containers aren't included by default. */
20
+ extensions?: string[];
21
+ /** Where re-encoded output is cached across builds, keyed by content hash + these options. */
22
+ cacheDir?: string;
23
+ }
24
+ /**
25
+ * Build-only Vite plugin (`apply: "build"`) that re-encodes `.mp4` video
26
+ * files in the finished output directory through ffmpeg (H.264/AAC,
27
+ * faststart), in place, overwriting each file only if the result comes out
28
+ * smaller — same contract compressImages and frontonCompression use. No
29
+ * markup changes needed: `<video src="/hero.mp4">` keeps pointing at the
30
+ * same path.
31
+ *
32
+ * Runs in `closeBundle`, same as compressImages and for the same reason: a
33
+ * video dropped in `public/` (by far the common case for a hero/background
34
+ * video — nobody `import`s a multi-megabyte video from a component) is
35
+ * copied to `outDir` by Vite as a step outside Rollup's own bundle
36
+ * entirely, and a `generateBundle` hook never sees it. Walking the real
37
+ * output directory once everything is actually on disk is the only way to
38
+ * reach it.
39
+ *
40
+ * Only `.mp4`/H.264 by default, deliberately: a `.webm` source is almost
41
+ * always already VP9/AV1, and re-encoding it through libx264 would silently
42
+ * change codec and often container semantics rather than just compress it.
43
+ * Add other extensions via `extensions` only if you've confirmed libx264 is
44
+ * the right target codec for them.
45
+ *
46
+ * `fluent-ffmpeg` and `ffmpeg-static` are peer dependencies, not bundled —
47
+ * install them yourself (`bun add fluent-ffmpeg ffmpeg-static`, plus
48
+ * `bun add -D @types/fluent-ffmpeg` for types) to use this plugin. Left
49
+ * uninstalled, this plugin logs a warning and does nothing, rather than
50
+ * failing the build. `ffmpeg-static` ships a prebuilt ffmpeg binary as the
51
+ * npm package itself, so nothing needs to be separately installed or on
52
+ * `PATH` — that's the point of using it over shelling out to a system
53
+ * `ffmpeg`.
54
+ *
55
+ * Re-encoding is genuinely slow — this is the reason cache.ts exists at
56
+ * all. A build with unchanged video assets should cost close to nothing
57
+ * after the first one.
58
+ */
59
+ export declare function compressVideos(options?: CompressVideosOptions): Plugin;
60
+ //# sourceMappingURL=videos.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"videos.d.ts","sourceRoot":"","sources":["../../src/media/videos.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAC;AAKnD,MAAM,WAAW,qBAAqB;IACpC,2FAA2F;IAC3F,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;;OAKG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,0JAA0J;IAC1J,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,8FAA8F;IAC9F,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AA0CD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,qBAA0B,GAAG,MAAM,CAiE1E"}
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Recursively lists every file under `dir` whose extension is in `extSet`.
3
+ *
4
+ * Why this walks the real output directory instead of Rollup's in-memory
5
+ * bundle (what obfuscateTailwind's generateBundle hook does): Vite copies
6
+ * `public/` straight to `outDir` as a separate step outside Rollup's own
7
+ * bundle machinery entirely — those files never appear in a `generateBundle`
8
+ * hook's bundle object at all. A hero video or photo dropped in `public/`
9
+ * (the common case — that's exactly how lestudioevents' own Hero_Video.mp4
10
+ * is set up) would silently never get touched by a generateBundle-based
11
+ * version of this plugin. Walking `outDir` after everything (Rollup's own
12
+ * output *and* the public/ copy) has actually been written to disk is the
13
+ * only way to reach both.
14
+ */
15
+ export declare function walkFiles(dir: string, extSet: Set<string>): Promise<string[]>;
16
+ //# sourceMappingURL=walk-files.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"walk-files.d.ts","sourceRoot":"","sources":["../../src/media/walk-files.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;;;;GAaG;AACH,wBAAsB,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAkBnF"}
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Builds a stable className -> short-hash map for a whole build. Each
3
+ * class is hashed independently off its own name (not an incrementing
4
+ * counter), so adding or removing an unrelated class elsewhere in the
5
+ * project never shifts an existing class's hash — output stays as stable
6
+ * as the input class set itself, not the order classes happened to be
7
+ * discovered in.
8
+ *
9
+ * Collisions on the default 6-hex-char prefix are vanishingly unlikely for
10
+ * a normal project's utility count, but handled anyway: on a clash the
11
+ * losing class gets a longer slice of the same digest instead of a
12
+ * different algorithm, so the mapping stays deterministic.
13
+ */
14
+ export declare function buildClassMap(classes: Iterable<string>, salt?: string): Map<string, string>;
15
+ //# sourceMappingURL=hash.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hash.d.ts","sourceRoot":"","sources":["../../src/obfuscate/hash.ts"],"names":[],"mappings":"AAMA;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,SAAK,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAqBvF"}
@@ -0,0 +1,6 @@
1
+ export { obfuscateTailwind } from "./plugin";
2
+ export type { ObfuscateTailwindOptions } from "./plugin";
3
+ export { buildClassMap } from "./hash";
4
+ export { collectClassesFromCss, rewriteCssClasses } from "./rewrite-css";
5
+ export { rewriteTextOutput } from "./rewrite-text";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/obfuscate/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,YAAY,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { Plugin } from "vite";
2
+ export interface ObfuscateTailwindOptions {
3
+ /** Turn the whole plugin off without removing it from vite.config.ts — useful for a one-off debug build. Default true. */
4
+ enabled?: boolean;
5
+ /**
6
+ * Specific class names to never rename — for classes an external
7
+ * stylesheet, an end-to-end test selector, or a third-party script
8
+ * depends on by their real Tailwind name.
9
+ */
10
+ safelist?: string[];
11
+ /**
12
+ * Mixed into every class's hash. Two fronton projects with an identical
13
+ * safelist and class set otherwise produce identical hashes; set this
14
+ * (e.g. to the project name) if that's not what you want.
15
+ */
16
+ salt?: string;
17
+ }
18
+ /**
19
+ * Build-only Vite plugin: after Tailwind's CSS and the JS bundle are both
20
+ * fully generated, hashes every real Tailwind utility class Tailwind
21
+ * actually emitted and rewrites both the stylesheet and known-safe
22
+ * class-bearing text in the JS/HTML output to match. Deliberately does
23
+ * nothing in dev (`apply: "build"`) — hashing classes on every HMR update
24
+ * would make dev tools useless without buying anything, since dev output
25
+ * never ships.
26
+ *
27
+ * Runs in `generateBundle`, strictly after Tailwind's own plugin has
28
+ * finished generating CSS and Rollup/Rolldown has finished bundling and
29
+ * minifying JS — so there's no ordering dependency on how @tailwindcss/vite
30
+ * scans source files for content, and no dependency on any particular
31
+ * class-merging helper's name surviving minification (it usually doesn't —
32
+ * `clsx(...)` routinely comes out the other side as `u(...)`). This plugin
33
+ * never looks at source at all; it only ever rewrites finished output,
34
+ * matched against the real generated CSS.
35
+ */
36
+ export declare function obfuscateTailwind(options?: ObfuscateTailwindOptions): Plugin;
37
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/obfuscate/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAU,MAAM,MAAM,CAAC;AAK3C,MAAM,WAAW,wBAAwB;IACvC,0HAA0H;IAC1H,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAKD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,MAAM,CAmDhF"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Parses emitted CSS and returns the definitive set of class selectors it
3
+ * actually defines. This is the whitelist everything else in the plugin
4
+ * works from — a token in the built JS/HTML only ever gets renamed if
5
+ * it's provably a real class Tailwind generated, never a guess based on
6
+ * pattern-matching arbitrary text.
7
+ */
8
+ export declare function collectClassesFromCss(css: string): Set<string>;
9
+ /** Rewrites every class selector in `css` using `map`; anything not in the map is left exactly as it was. */
10
+ export declare function rewriteCssClasses(css: string, map: Map<string, string>): string;
11
+ //# sourceMappingURL=rewrite-css.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rewrite-css.d.ts","sourceRoot":"","sources":["../../src/obfuscate/rewrite-css.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC,CAa9D;AAED,6GAA6G;AAC7G,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAa/E"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Rewrites known-safe class-bearing text in already-built JS/HTML output.
3
+ * For each `className`/`class` property found:
4
+ *
5
+ * - if its value is a single plain string/template literal (no
6
+ * interpolation), rewrite class tokens in it directly;
7
+ * - otherwise (a function call, ternary, logical expression — however a
8
+ * merge helper compiled down), scan the whole value expression for
9
+ * string literals and rewrite class tokens inside each one, without
10
+ * needing to know what produced the expression.
11
+ *
12
+ * Anything not shaped like one of those — a class list built from an
13
+ * array/object at runtime and joined without any literal strings present
14
+ * in this scope, a template literal with real `${}` interpolation — is
15
+ * left exactly as it was. Only tokens present in `map` (i.e. provably
16
+ * real classes Tailwind actually generated, per rewrite-css.ts's
17
+ * collectClassesFromCss) are ever touched, so a miss here just means
18
+ * "not obfuscated", never a broken build.
19
+ */
20
+ export declare function rewriteTextOutput(code: string, map: Map<string, string>): {
21
+ code: string;
22
+ count: number;
23
+ };
24
+ //# sourceMappingURL=rewrite-text.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rewrite-text.d.ts","sourceRoot":"","sources":["../../src/obfuscate/rewrite-text.ts"],"names":[],"mappings":"AA2FA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CA+DzG"}
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@mednours/fronton",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Opinionated runtime pieces for fronton-scaffolded Vite projects — Tailwind class obfuscation, gzip/brotli compression, and backon API wiring.",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/mednours/fronton/tree/main/packages/fronton#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/mednours/fronton.git",
11
+ "directory": "packages/fronton"
12
+ },
13
+ "bugs": "https://github.com/mednours/fronton/issues",
14
+ "engines": {
15
+ "bun": ">=1.3.0",
16
+ "node": ">=18.0.0"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "files": ["dist"],
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js"
26
+ },
27
+ "./client": {
28
+ "types": "./dist/client.d.ts",
29
+ "import": "./dist/client.js"
30
+ }
31
+ },
32
+ "scripts": {
33
+ "test": "bun test",
34
+ "typecheck": "tsc --noEmit",
35
+ "build": "rm -rf dist && tsc -p tsconfig.json --emitDeclarationOnly && esbuild src/index.ts src/client.ts --bundle --platform=node --format=esm --target=node18 --packages=external --outdir=dist",
36
+ "prepublishOnly": "bun run typecheck && bun run test && bun run build"
37
+ },
38
+ "peerDependencies": {
39
+ "vite": "^8.0.0",
40
+ "sharp": "^0.35.0",
41
+ "fluent-ffmpeg": "^2.1.3",
42
+ "ffmpeg-static": "^5.3.0"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "sharp": { "optional": true },
46
+ "fluent-ffmpeg": { "optional": true },
47
+ "ffmpeg-static": { "optional": true }
48
+ },
49
+ "dependencies": {
50
+ "magic-string": "^1.2.0",
51
+ "postcss": "^8.5.26",
52
+ "postcss-selector-parser": "^7.1.5",
53
+ "vite-plugin-compression2": "^2.5.3"
54
+ },
55
+ "devDependencies": {
56
+ "@types/bun": "latest",
57
+ "@types/fluent-ffmpeg": "^2.1.28",
58
+ "esbuild": "^0.28.2",
59
+ "ffmpeg-static": "^5.3.0",
60
+ "fluent-ffmpeg": "^2.1.3",
61
+ "sharp": "^0.35.3",
62
+ "typescript": "^7.0.2",
63
+ "vite": "^8.2.1"
64
+ }
65
+ }