|
| 1 | +/** |
| 2 | + * Admin locale allowlist helpers. |
| 3 | + * |
| 4 | + * Build-time utilities for validating a user-supplied list of admin UI |
| 5 | + * locales and rewiring locale catalog imports so only the listed locales |
| 6 | + * are bundled. Unlisted locales fall back to the source (English) catalog. |
| 7 | + */ |
| 8 | + |
| 9 | +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; |
| 10 | +import { createRequire } from "node:module"; |
| 11 | +import { dirname, isAbsolute, relative, resolve } from "node:path"; |
| 12 | + |
| 13 | +import type { Plugin } from "vite"; |
| 14 | + |
| 15 | +const DEFAULT_LOCALE = "en"; |
| 16 | +const SOURCE_MESSAGES_RE = /^\.\/([a-zA-Z0-9-]+)\/messages\.mjs$/; |
| 17 | +const DIST_CHUNK_RE = /^\.\/messages-([A-Za-z0-9_-]+)\.js$/; |
| 18 | +const LOCALE_LOADERS_ENTRY_RE = |
| 19 | + /"\.\/([a-zA-Z0-9-]+)\/messages\.mjs":\s*\(\)\s*=>\s*import\("\.\/messages-([A-Za-z0-9_-]+)\.js"\)/g; |
| 20 | + |
| 21 | +/** |
| 22 | + * Resolve path to the admin package dist directory. |
| 23 | + * Used for Vite alias to ensure the package is found in pnpm's isolated node_modules. |
| 24 | + */ |
| 25 | +export function resolveAdminDist(): string { |
| 26 | + const require = createRequire(import.meta.url); |
| 27 | + const adminPath = require.resolve("@emdash-cms/admin"); |
| 28 | + return dirname(adminPath); |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Resolve path to the admin package source directory. |
| 33 | + * In dev mode inside this repo, we alias @emdash-cms/admin to the source so |
| 34 | + * Vite processes it directly — giving instant HMR instead of requiring a |
| 35 | + * rebuild + restart. External apps should use the built package surface. |
| 36 | + */ |
| 37 | +export function resolveAdminSource(projectRoot: string): string | undefined { |
| 38 | + const require = createRequire(import.meta.url); |
| 39 | + const adminPath = require.resolve("@emdash-cms/admin"); |
| 40 | + const packageRoot = resolve(dirname(adminPath), ".."); |
| 41 | + const repoRoot = resolve(packageRoot, "..", ".."); |
| 42 | + const srcEntry = resolve(packageRoot, "src", "index.ts"); |
| 43 | + |
| 44 | + try { |
| 45 | + if (existsSync(srcEntry) && isInside(repoRoot, projectRoot)) { |
| 46 | + return resolve(packageRoot, "src"); |
| 47 | + } |
| 48 | + } catch { |
| 49 | + // Not in local repo — fall back to dist |
| 50 | + } |
| 51 | + return undefined; |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Check whether child is inside parent without relying on simple prefix checks. |
| 56 | + */ |
| 57 | +function isInside(parent: string, child: string): boolean { |
| 58 | + const relativePath = relative(parent, child); |
| 59 | + return relativePath === "" || (!relativePath.startsWith("..") && !isAbsolute(relativePath)); |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Read the locale codes that actually have compiled catalogs in the admin |
| 64 | + * package. The returned set drives config-time validation and runtime |
| 65 | + * filtering; keeping it filesystem-based means the allowlist automatically |
| 66 | + * matches whatever locales the installed admin version ships. |
| 67 | + */ |
| 68 | +export function getAdminLocaleCodes(adminDistPath: string): Set<string> { |
| 69 | + const codes = new Set<string>(); |
| 70 | + const localesDir = resolve(adminDistPath, "locales"); |
| 71 | + |
| 72 | + try { |
| 73 | + for (const entry of readdirSync(localesDir)) { |
| 74 | + const entryPath = resolve(localesDir, entry); |
| 75 | + if (statSync(entryPath).isDirectory() && existsSync(resolve(entryPath, "messages.mjs"))) { |
| 76 | + codes.add(entry); |
| 77 | + } |
| 78 | + } |
| 79 | + } catch { |
| 80 | + // If the admin package has no compiled locales (shouldn't happen in a |
| 81 | + // real install), fall through to an empty set and let validation fail |
| 82 | + // clearly if the user supplied an allowlist. |
| 83 | + } |
| 84 | + |
| 85 | + return codes; |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Validate and canonicalize a user-supplied admin locale allowlist. |
| 90 | + * |
| 91 | + * - Each entry must be a non-empty BCP 47 tag that names a locale the admin |
| 92 | + * actually ships. |
| 93 | + * - The source locale (English) must be present so the fallback catalog is |
| 94 | + * always available. |
| 95 | + * - Entries are de-duplicated and canonicalized via Intl.Locale. |
| 96 | + */ |
| 97 | +export function validateAdminLocales( |
| 98 | + input: unknown, |
| 99 | + knownCodes: Iterable<string>, |
| 100 | + sourceLocale = DEFAULT_LOCALE, |
| 101 | +): string[] | undefined { |
| 102 | + if (input === undefined) return undefined; |
| 103 | + |
| 104 | + if (!Array.isArray(input)) { |
| 105 | + throw new Error("`admin.locales` must be an array of locale codes."); |
| 106 | + } |
| 107 | + if (input.length === 0) { |
| 108 | + throw new Error("`admin.locales` cannot be empty."); |
| 109 | + } |
| 110 | + |
| 111 | + const known = new Set(knownCodes); |
| 112 | + const result: string[] = []; |
| 113 | + const seen = new Set<string>(); |
| 114 | + |
| 115 | + for (const raw of input) { |
| 116 | + if (typeof raw !== "string" || raw.trim() === "") { |
| 117 | + throw new Error("`admin.locales` entries must be non-empty locale codes."); |
| 118 | + } |
| 119 | + |
| 120 | + let canonical: string; |
| 121 | + try { |
| 122 | + canonical = new Intl.Locale(raw.trim()).baseName; |
| 123 | + } catch { |
| 124 | + throw new Error(`Invalid locale code in \`admin.locales\`: "${raw}".`); |
| 125 | + } |
| 126 | + |
| 127 | + if (!known.has(canonical)) { |
| 128 | + throw new Error( |
| 129 | + `Unknown admin locale: "${canonical}". ` + |
| 130 | + `Supported locales are: ${[...known].join(", ")}.`, |
| 131 | + ); |
| 132 | + } |
| 133 | + |
| 134 | + if (!seen.has(canonical)) { |
| 135 | + seen.add(canonical); |
| 136 | + result.push(canonical); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + if (!seen.has(sourceLocale)) { |
| 141 | + throw new Error( |
| 142 | + `\`admin.locales\` must include the source locale "${sourceLocale}" ` + |
| 143 | + `so the admin has a fallback catalog.`, |
| 144 | + ); |
| 145 | + } |
| 146 | + |
| 147 | + return result; |
| 148 | +} |
| 149 | + |
| 150 | +interface LocaleChunkInfo { |
| 151 | + /** Map from chunk filename hash (e.g. "gTCuzb6s") to locale code. */ |
| 152 | + hashToLocale: Map<string, string>; |
| 153 | + /** Filename of the source (English) chunk, e.g. "messages-gTCuzb6s.js". */ |
| 154 | + defaultChunk: string | undefined; |
| 155 | +} |
| 156 | + |
| 157 | +/** |
| 158 | + * Parse the admin dist chunk containing `LOCALE_LOADERS` so we know which |
| 159 | + * hashed chunk belongs to which locale. This is the only reliable way to map |
| 160 | + * the pre-hashed filenames in the built admin back to locale codes. |
| 161 | + */ |
| 162 | +function buildLocaleChunkMap(adminDistPath: string, defaultLocale: string): LocaleChunkInfo { |
| 163 | + const hashToLocale = new Map<string, string>(); |
| 164 | + let defaultChunk: string | undefined; |
| 165 | + |
| 166 | + try { |
| 167 | + for (const file of readdirSync(adminDistPath)) { |
| 168 | + if (!file.endsWith(".js") || file.endsWith(".map")) continue; |
| 169 | + |
| 170 | + const content = readFileSync(resolve(adminDistPath, file), "utf8"); |
| 171 | + if (!content.includes("LOCALE_LOADERS")) continue; |
| 172 | + |
| 173 | + for (const match of content.matchAll(LOCALE_LOADERS_ENTRY_RE)) { |
| 174 | + const locale = match[1]!; |
| 175 | + const hash = match[2]!; |
| 176 | + hashToLocale.set(hash, locale); |
| 177 | + if (locale === defaultLocale) { |
| 178 | + defaultChunk = `messages-${hash}.js`; |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + // Only one chunk contains the loader map. |
| 183 | + break; |
| 184 | + } |
| 185 | + } catch { |
| 186 | + // Leave the map empty; resolution will fall back to Rollup defaults. |
| 187 | + } |
| 188 | + |
| 189 | + return { hashToLocale, defaultChunk }; |
| 190 | +} |
| 191 | + |
| 192 | +interface AdminLocaleResolverOptions { |
| 193 | + adminDistPath: string; |
| 194 | + adminSourcePath?: string; |
| 195 | + locales: string[]; |
| 196 | + defaultLocale?: string; |
| 197 | +} |
| 198 | + |
| 199 | +/** |
| 200 | + * Vite plugin that redirects admin locale imports and hashed locale chunks |
| 201 | + * for locales outside the allowlist back to the source (default) locale. |
| 202 | + * |
| 203 | + * In dev mode with the admin package aliased to source, imports look like |
| 204 | + * `./de/messages.mjs`. In production builds that consume the pre-built admin |
| 205 | + * dist, imports look like `./messages-<hash>.js`. Both forms are handled. |
| 206 | + */ |
| 207 | +export function createAdminLocaleResolverPlugin(options: AdminLocaleResolverOptions): Plugin { |
| 208 | + const { adminDistPath, adminSourcePath, locales, defaultLocale = DEFAULT_LOCALE } = options; |
| 209 | + const allowed = new Set(locales); |
| 210 | + const { hashToLocale, defaultChunk } = buildLocaleChunkMap(adminDistPath, defaultLocale); |
| 211 | + |
| 212 | + const defaultMessagesPath = resolve(adminDistPath, "locales", defaultLocale, "messages.mjs"); |
| 213 | + |
| 214 | + return { |
| 215 | + name: "emdash-admin-locales", |
| 216 | + enforce: "pre", |
| 217 | + resolveId(source, importer) { |
| 218 | + if (!importer) return; |
| 219 | + |
| 220 | + const isSourceImporter = |
| 221 | + adminSourcePath !== undefined && importer.startsWith(adminSourcePath); |
| 222 | + const isDistImporter = importer.startsWith(adminDistPath); |
| 223 | + if (!isSourceImporter && !isDistImporter) return; |
| 224 | + |
| 225 | + // Dev-mode import from admin source: ./de/messages.mjs |
| 226 | + const sourceMatch = SOURCE_MESSAGES_RE.exec(source); |
| 227 | + if (sourceMatch) { |
| 228 | + const locale = sourceMatch[1]!; |
| 229 | + if (locale === defaultLocale || allowed.has(locale)) { |
| 230 | + // Let the Lingui macro plugin (dev source mode) or Rollup handle allowed locales. |
| 231 | + return; |
| 232 | + } |
| 233 | + return defaultMessagesPath; |
| 234 | + } |
| 235 | + |
| 236 | + // Production import from admin dist: ./messages-<hash>.js |
| 237 | + const chunkMatch = DIST_CHUNK_RE.exec(source); |
| 238 | + if (chunkMatch && defaultChunk) { |
| 239 | + const hash = chunkMatch[1]!; |
| 240 | + const locale = hashToLocale.get(hash); |
| 241 | + if (!locale) return; |
| 242 | + if (locale === defaultLocale || allowed.has(locale)) return; |
| 243 | + return resolve(adminDistPath, defaultChunk); |
| 244 | + } |
| 245 | + }, |
| 246 | + }; |
| 247 | +} |
0 commit comments