diff --git a/.gitignore b/.gitignore index 298ee76..57e1855 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,9 @@ build .next next-env.d.ts .vercel +# Hashed fonts and icon sprite, written by island's asset plugin on next dev and next build (0008) +apps/*/public/icons/ +apps/*/public/fonts/ # Testing coverage diff --git a/apps/bear/.env.example b/apps/bear/.env.example index 604e5a5..0e569f9 100644 --- a/apps/bear/.env.example +++ b/apps/bear/.env.example @@ -6,6 +6,10 @@ NEXT_PUBLIC_BALE_HANDLE=lumina_support NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ +# Optional: the CDN origin, without a trailing slash, that serves public/fonts/ under the same paths. +# It must send Access-Control-Allow-Origin. The icon sprite always loads from the app's own origin. +NEXT_PUBLIC_CDN_ORIGIN= + # Server only: the API origin from inside the deployment network. API_INTERNAL_ORIGIN=http://localhost:3000 diff --git a/apps/bear/next.config.ts b/apps/bear/next.config.ts index 9009d5c..42263ff 100644 --- a/apps/bear/next.config.ts +++ b/apps/bear/next.config.ts @@ -1,3 +1,4 @@ +import { withIslandAssets } from '@lumina/island/tools/asset-plugin'; import type { NextConfig } from 'next'; const nextConfig: NextConfig = { @@ -32,4 +33,5 @@ const nextConfig: NextConfig = { }, }; -export default nextConfig; +// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008). +export default withIslandAssets(nextConfig); diff --git a/apps/bear/package.json b/apps/bear/package.json index 9d69b82..dd231b4 100644 --- a/apps/bear/package.json +++ b/apps/bear/package.json @@ -10,6 +10,14 @@ "scope:market" ], "targets": { + "build": { + "outputs": [ + "{projectRoot}/.next/!(cache)/**/*", + "{projectRoot}/.next/!(cache)", + "{projectRoot}/public/icons", + "{projectRoot}/public/fonts" + ] + }, "dev": { "options": { "command": "next dev --port 3002" diff --git a/apps/bear/src/bootstrap/bootstrap.client.ts b/apps/bear/src/bootstrap/bootstrap.client.ts index b11fa21..c50069a 100644 --- a/apps/bear/src/bootstrap/bootstrap.client.ts +++ b/apps/bear/src/bootstrap/bootstrap.client.ts @@ -1,5 +1,6 @@ import { configureErrorHandler } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; +import { setEnv as setIslandEnv } from '@lumina/island/env'; import { http } from '@lumina/libs/http'; import { mapApiErrorBody } from '@lumina/market/app/http'; import { setEnv as setMarketEnv } from '@lumina/market/env'; @@ -8,6 +9,7 @@ import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth'; import { API_VERSION_PATH } from '../constants'; import { clientEnv } from '../env'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; +import { ISLAND_ENV } from './island-env'; // Fills the client module graph with public values only, before client components render (during // SSR and in the browser). Idempotent: safe to run again. @@ -17,6 +19,7 @@ setMarketEnv({ telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); +setIslandEnv(ISLAND_ENV); // The session lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the // whole app; when that fails the session is over and the shell signs the user out. http.configure({ diff --git a/apps/bear/src/bootstrap/bootstrap.server.ts b/apps/bear/src/bootstrap/bootstrap.server.ts index 1e1c316..8539bb8 100644 --- a/apps/bear/src/bootstrap/bootstrap.server.ts +++ b/apps/bear/src/bootstrap/bootstrap.server.ts @@ -1,5 +1,6 @@ import 'server-only'; +import { setEnv as setIslandEnv } from '@lumina/island/env'; import { configureErrorHandler } from '@lumina/libs/error-handler'; import { http } from '@lumina/libs/http'; import { configureServerHttp } from '@lumina/libs/server'; @@ -11,6 +12,7 @@ import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants'; import { clientEnv } from '../env'; import { serverEnv } from '../env/server'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; +import { ISLAND_ENV } from './island-env'; // Fills the server module graph once, before rendering. Idempotent: safe to run again. setMarketEnv({ @@ -19,6 +21,7 @@ setMarketEnv({ telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); +setIslandEnv(ISLAND_ENV); // Server requests forward only the allowlisted cookies, never the session: the server render is // the same for every visitor, and the browser loads whatever depends on the viewer. Read on each // request; nothing per visitor is kept in module state. diff --git a/apps/bear/src/bootstrap/island-env.ts b/apps/bear/src/bootstrap/island-env.ts new file mode 100644 index 0000000..0c101d5 --- /dev/null +++ b/apps/bear/src/bootstrap/island-env.ts @@ -0,0 +1,18 @@ +import type { IslandEnv } from '@lumina/island/env'; + +import { clientEnv } from '../env'; + +const cdnOrigin = clientEnv.NEXT_PUBLIC_CDN_ORIGIN ?? ''; + +/** + * island's settings for both sides, from the hashed paths its asset plugin wrote into `public/`. + * Fonts may load from the CDN under the same paths; the sprite never does, because `` + * only loads same-origin. + */ +export const ISLAND_ENV: IslandEnv = { + iconSpritePath: clientEnv.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH, + fontUrls: { + sans: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH}`, + latin: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH}`, + }, +}; diff --git a/apps/bear/src/env/env.client.ts b/apps/bear/src/env/env.client.ts index 67ec37c..c7d6d49 100644 --- a/apps/bear/src/env/env.client.ts +++ b/apps/bear/src/env/env.client.ts @@ -3,6 +3,7 @@ import * as v from 'valibot'; const required = v.pipe(v.string(), v.nonEmpty()); const url = v.pipe(v.string(), v.url()); +const rootPath = v.pipe(v.string(), v.startsWith('/')); /** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */ export const clientEnv = createClientEnv({ @@ -13,6 +14,11 @@ export const clientEnv = createClientEnv({ NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_SUPPORT_HOURS: required, + NEXT_PUBLIC_CDN_ORIGIN: v.optional(url), + // Written by island's asset plugin in next.config, never set in .env. + NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH: rootPath, + NEXT_PUBLIC_ISLAND_FONT_SANS_PATH: rootPath, + NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH: rootPath, }, runtimeEnv: { NEXT_PUBLIC_API_ORIGIN: process.env.NEXT_PUBLIC_API_ORIGIN, @@ -20,5 +26,12 @@ export const clientEnv = createClientEnv({ NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE, NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE, NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS, + NEXT_PUBLIC_CDN_ORIGIN: process.env.NEXT_PUBLIC_CDN_ORIGIN, + NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH: + process.env.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH, + NEXT_PUBLIC_ISLAND_FONT_SANS_PATH: + process.env.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH, + NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH: + process.env.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH, }, }); diff --git a/apps/bull/.env.example b/apps/bull/.env.example index 2c80a51..d8f1b99 100644 --- a/apps/bull/.env.example +++ b/apps/bull/.env.example @@ -6,6 +6,10 @@ NEXT_PUBLIC_BALE_HANDLE=lumina_support NEXT_PUBLIC_TELEGRAM_HANDLE=lumina_support NEXT_PUBLIC_SUPPORT_HOURS=شنبه تا پنجشنبه، ۹ تا ۱۸ +# Optional: the CDN origin, without a trailing slash, that serves public/fonts/ under the same paths. +# It must send Access-Control-Allow-Origin. The icon sprite always loads from the app's own origin. +NEXT_PUBLIC_CDN_ORIGIN= + # Server only: the API origin from inside the deployment network. API_INTERNAL_ORIGIN=http://localhost:3000 diff --git a/apps/bull/next.config.ts b/apps/bull/next.config.ts index 9009d5c..42263ff 100644 --- a/apps/bull/next.config.ts +++ b/apps/bull/next.config.ts @@ -1,3 +1,4 @@ +import { withIslandAssets } from '@lumina/island/tools/asset-plugin'; import type { NextConfig } from 'next'; const nextConfig: NextConfig = { @@ -32,4 +33,5 @@ const nextConfig: NextConfig = { }, }; -export default nextConfig; +// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008). +export default withIslandAssets(nextConfig); diff --git a/apps/bull/package.json b/apps/bull/package.json index 66bc685..19e09f8 100644 --- a/apps/bull/package.json +++ b/apps/bull/package.json @@ -10,6 +10,14 @@ "scope:market" ], "targets": { + "build": { + "outputs": [ + "{projectRoot}/.next/!(cache)/**/*", + "{projectRoot}/.next/!(cache)", + "{projectRoot}/public/icons", + "{projectRoot}/public/fonts" + ] + }, "dev": { "options": { "command": "next dev --port 3001" diff --git a/apps/bull/src/bootstrap/bootstrap.client.ts b/apps/bull/src/bootstrap/bootstrap.client.ts index b11fa21..c50069a 100644 --- a/apps/bull/src/bootstrap/bootstrap.client.ts +++ b/apps/bull/src/bootstrap/bootstrap.client.ts @@ -1,5 +1,6 @@ import { configureErrorHandler } from '@lumina/libs/error-handler'; import { eventEmitter } from '@lumina/libs/event-emitter'; +import { setEnv as setIslandEnv } from '@lumina/island/env'; import { http } from '@lumina/libs/http'; import { mapApiErrorBody } from '@lumina/market/app/http'; import { setEnv as setMarketEnv } from '@lumina/market/env'; @@ -8,6 +9,7 @@ import { AUTH_ENDPOINTS, AUTH_EVENTS } from '@lumina/market/features/auth'; import { API_VERSION_PATH } from '../constants'; import { clientEnv } from '../env'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; +import { ISLAND_ENV } from './island-env'; // Fills the client module graph with public values only, before client components render (during // SSR and in the browser). Idempotent: safe to run again. @@ -17,6 +19,7 @@ setMarketEnv({ telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); +setIslandEnv(ISLAND_ENV); // The session lives in HttpOnly cookies the browser sends itself. A 401 runs one refresh for the // whole app; when that fails the session is over and the shell signs the user out. http.configure({ diff --git a/apps/bull/src/bootstrap/bootstrap.server.ts b/apps/bull/src/bootstrap/bootstrap.server.ts index 1e1c316..8539bb8 100644 --- a/apps/bull/src/bootstrap/bootstrap.server.ts +++ b/apps/bull/src/bootstrap/bootstrap.server.ts @@ -1,5 +1,6 @@ import 'server-only'; +import { setEnv as setIslandEnv } from '@lumina/island/env'; import { configureErrorHandler } from '@lumina/libs/error-handler'; import { http } from '@lumina/libs/http'; import { configureServerHttp } from '@lumina/libs/server'; @@ -11,6 +12,7 @@ import { API_VERSION_PATH, FORWARDED_COOKIES } from '../constants'; import { clientEnv } from '../env'; import { serverEnv } from '../env/server'; import { ERROR_HANDLER_CONFIG } from './error-reporting'; +import { ISLAND_ENV } from './island-env'; // Fills the server module graph once, before rendering. Idempotent: safe to run again. setMarketEnv({ @@ -19,6 +21,7 @@ setMarketEnv({ telegramHandle: clientEnv.NEXT_PUBLIC_TELEGRAM_HANDLE, supportHours: clientEnv.NEXT_PUBLIC_SUPPORT_HOURS, }); +setIslandEnv(ISLAND_ENV); // Server requests forward only the allowlisted cookies, never the session: the server render is // the same for every visitor, and the browser loads whatever depends on the viewer. Read on each // request; nothing per visitor is kept in module state. diff --git a/apps/bull/src/bootstrap/island-env.ts b/apps/bull/src/bootstrap/island-env.ts new file mode 100644 index 0000000..0c101d5 --- /dev/null +++ b/apps/bull/src/bootstrap/island-env.ts @@ -0,0 +1,18 @@ +import type { IslandEnv } from '@lumina/island/env'; + +import { clientEnv } from '../env'; + +const cdnOrigin = clientEnv.NEXT_PUBLIC_CDN_ORIGIN ?? ''; + +/** + * island's settings for both sides, from the hashed paths its asset plugin wrote into `public/`. + * Fonts may load from the CDN under the same paths; the sprite never does, because `` + * only loads same-origin. + */ +export const ISLAND_ENV: IslandEnv = { + iconSpritePath: clientEnv.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH, + fontUrls: { + sans: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH}`, + latin: `${cdnOrigin}${clientEnv.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH}`, + }, +}; diff --git a/apps/bull/src/env/env.client.ts b/apps/bull/src/env/env.client.ts index 67ec37c..c7d6d49 100644 --- a/apps/bull/src/env/env.client.ts +++ b/apps/bull/src/env/env.client.ts @@ -3,6 +3,7 @@ import * as v from 'valibot'; const required = v.pipe(v.string(), v.nonEmpty()); const url = v.pipe(v.string(), v.url()); +const rootPath = v.pipe(v.string(), v.startsWith('/')); /** Public variables, inlined into the browser bundle. Next.js inlines only literal reads. */ export const clientEnv = createClientEnv({ @@ -13,6 +14,11 @@ export const clientEnv = createClientEnv({ NEXT_PUBLIC_BALE_HANDLE: required, NEXT_PUBLIC_TELEGRAM_HANDLE: required, NEXT_PUBLIC_SUPPORT_HOURS: required, + NEXT_PUBLIC_CDN_ORIGIN: v.optional(url), + // Written by island's asset plugin in next.config, never set in .env. + NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH: rootPath, + NEXT_PUBLIC_ISLAND_FONT_SANS_PATH: rootPath, + NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH: rootPath, }, runtimeEnv: { NEXT_PUBLIC_API_ORIGIN: process.env.NEXT_PUBLIC_API_ORIGIN, @@ -20,5 +26,12 @@ export const clientEnv = createClientEnv({ NEXT_PUBLIC_BALE_HANDLE: process.env.NEXT_PUBLIC_BALE_HANDLE, NEXT_PUBLIC_TELEGRAM_HANDLE: process.env.NEXT_PUBLIC_TELEGRAM_HANDLE, NEXT_PUBLIC_SUPPORT_HOURS: process.env.NEXT_PUBLIC_SUPPORT_HOURS, + NEXT_PUBLIC_CDN_ORIGIN: process.env.NEXT_PUBLIC_CDN_ORIGIN, + NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH: + process.env.NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH, + NEXT_PUBLIC_ISLAND_FONT_SANS_PATH: + process.env.NEXT_PUBLIC_ISLAND_FONT_SANS_PATH, + NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH: + process.env.NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH, }, }); diff --git a/docs/decisions/0007-yekan-bakh-from-public-or-cdn.md b/docs/decisions/0007-yekan-bakh-from-public-or-cdn.md index f3a53ff..ce5e314 100644 --- a/docs/decisions/0007-yekan-bakh-from-public-or-cdn.md +++ b/docs/decisions/0007-yekan-bakh-from-public-or-cdn.md @@ -19,4 +19,4 @@ Lumina uses two variable faces from `packages/island/src/fonts/`: Yekan Bakh FaN ## Consequences - We now own what `next/font` did: hashed names and immutable `Cache-Control` (the asset plugin), the preload (`FontFaces`), and the fallback metrics (`FONT_FALLBACK` in island `constants.ts`, measured on Persian text). - The font is licensed. "Never a public CDN" means only the company's own CDN. Confirm the licence covers web embedding from that CDN. -- Debt: both apps still load the faces with `next/font/local` in `src/styles/fonts.ts`, and `island.css` says so. `FontFaces`, island env, `FONT_FALLBACK`, and the asset plugin don't exist yet. +- Debt: both apps still load the faces with `next/font/local` in `src/styles/fonts.ts`, and `island.css` says so. `FontFaces` and `FONT_FALLBACK` don't exist yet; island env and the asset plugin do, and already write and pass the hashed font URLs. diff --git a/docs/decisions/0008-island-asset-plugin.md b/docs/decisions/0008-island-asset-plugin.md index 0005e67..5f48c92 100644 --- a/docs/decisions/0008-island-asset-plugin.md +++ b/docs/decisions/0008-island-asset-plugin.md @@ -25,3 +25,4 @@ Fonts (0007) and the icon sprite live in island, but browsers load them from eac - In dev, edits to island assets need a dev-server restart (Next watches only next.config), unless the plugin adds a watcher. - Other phases, `next start` included, get the config back unchanged: the build already inlined `env` and wrote the headers into its routes manifest, so production needs neither island's sources nor svgo. `next typegen` and other build-phase commands still run it. - Standalone and Docker builds must copy `public/`. +- Nx's `@nx/next` plugin also calls the config with `PHASE_PRODUCTION_BUILD`, from the workspace root, to read `distDir`. So the plugin hashes when the config is evaluated but writes only in `headers()`, which only Next calls. Each app's Nx `build` outputs include `public/icons` and `public/fonts`. diff --git a/packages/island/package.json b/packages/island/package.json index 71af01c..3aff7dc 100644 --- a/packages/island/package.json +++ b/packages/island/package.json @@ -30,16 +30,15 @@ ], "targets": { "icons": { - "command": "jiti src/tools/icon-sprite-plugin/run.ts", + "command": "jiti src/tools/icon-name-extraction/run.ts", "options": { "cwd": "{projectRoot}" }, "inputs": [ "{projectRoot}/src/icons/*.svg", - "{projectRoot}/src/tools/icon-sprite-plugin/**/*" + "{projectRoot}/src/tools/icon-name-extraction/**/*" ], "outputs": [ - "{projectRoot}/src/atoms/icon/sprite.svg", "{projectRoot}/src/atoms/icon/icon-names.ts" ], "cache": true diff --git a/packages/island/src/atoms/icon/Icon.tsx b/packages/island/src/atoms/icon/Icon.tsx index 1c76f52..9bab90b 100644 --- a/packages/island/src/atoms/icon/Icon.tsx +++ b/packages/island/src/atoms/icon/Icon.tsx @@ -1,6 +1,6 @@ +import { getEnv } from '../../env'; import { Element } from '../../primitives/element'; import { cn } from '../../tools/cn'; -import { SPRITE_URL } from './constants'; import type { IconProps } from './types'; /** A line icon from the sprite, drawn in `currentColor` on a 24px grid. */ @@ -30,7 +30,8 @@ export function Icon({ className={cn('inline-block flex-none align-middle', className)} {...props} > - + {/* One hashed sprite the browser caches; each icon is a `` into it, so icons add no JavaScript. */} + ); } diff --git a/packages/island/src/atoms/icon/constants.ts b/packages/island/src/atoms/icon/constants.ts deleted file mode 100644 index 6d97bed..0000000 --- a/packages/island/src/atoms/icon/constants.ts +++ /dev/null @@ -1,7 +0,0 @@ -import sprite from './sprite.svg'; - -/** Next.js imports a static file as `{ src }`, other bundlers as a URL string. */ -const asset = sprite as unknown as string | { src: string }; - -/** One hashed file the browser caches; each icon is a `` into it, so icons add no JavaScript. */ -export const SPRITE_URL = typeof asset === 'string' ? asset : asset.src; diff --git a/packages/island/src/atoms/icon/icon-names.ts b/packages/island/src/atoms/icon/icon-names.ts index 53daf4d..3320355 100644 --- a/packages/island/src/atoms/icon/icon-names.ts +++ b/packages/island/src/atoms/icon/icon-names.ts @@ -1,4 +1,4 @@ -// Generated by tools/icon-sprite-plugin from src/icons/*.svg. Run `pnpm nx run island:icons`. +// Generated by tools/icon-name-extraction from src/icons/*.svg. Run `pnpm nx run island:icons`. export const ICON_NAMES = [ 'alert', diff --git a/packages/island/src/atoms/icon/sprite.svg b/packages/island/src/atoms/icon/sprite.svg deleted file mode 100644 index 6476de0..0000000 --- a/packages/island/src/atoms/icon/sprite.svg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/packages/island/src/env/.gitkeep b/packages/island/src/env/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/env/env.ts b/packages/island/src/env/env.ts new file mode 100644 index 0000000..9739e83 --- /dev/null +++ b/packages/island/src/env/env.ts @@ -0,0 +1,18 @@ +import type { IslandEnv } from './types'; + +let islandEnv: IslandEnv | undefined; + +/** Called by each app bootstrap, on the server and in the browser. Idempotent. */ +export function setEnv(env: IslandEnv): void { + islandEnv = env; +} + +/** Read inside functions, never at module top level: bootstrap may not have run yet. */ +export function getEnv(): Readonly { + if (!islandEnv) { + throw new Error( + 'island env is not set. The app bootstrap must call setEnv from @lumina/island/env first.', + ); + } + return islandEnv; +} diff --git a/packages/island/src/env/index.ts b/packages/island/src/env/index.ts new file mode 100644 index 0000000..3393c00 --- /dev/null +++ b/packages/island/src/env/index.ts @@ -0,0 +1,2 @@ +export { getEnv, setEnv } from './env'; +export type { IslandEnv } from './types'; diff --git a/packages/island/src/env/types.ts b/packages/island/src/env/types.ts new file mode 100644 index 0000000..ef094df --- /dev/null +++ b/packages/island/src/env/types.ts @@ -0,0 +1,15 @@ +/** island's settings: the hashed asset URLs that the asset plugin wrote into the app's `public/`. */ +export type IslandEnv = { + /** + * Root-relative URL of the icon sprite (`/icons/symbol-defs..svg`). Always same-origin: + * `` never loads across origins, and CORS can't change that. + */ + iconSpritePath: string; + /** Font URL per font token, from the app's `public/fonts/` or the CDN under the same paths. */ + fontUrls: { + /** Yekan Bakh FaNum: every UI text. */ + sans: string; + /** Yekan Bakh: only text that must show Latin digits, such as شبا. */ + latin: string; + }; +}; diff --git a/packages/island/src/index.ts b/packages/island/src/index.ts index b65f143..0a2ee57 100644 --- a/packages/island/src/index.ts +++ b/packages/island/src/index.ts @@ -204,3 +204,5 @@ export type { ValidTags, } from './primitives/element'; export { cn } from './tools/cn'; +export { getEnv, setEnv } from './env'; +export type { IslandEnv } from './env'; diff --git a/packages/island/src/tools/asset-plugin/asset-plugin.ts b/packages/island/src/tools/asset-plugin/asset-plugin.ts new file mode 100644 index 0000000..696d011 --- /dev/null +++ b/packages/island/src/tools/asset-plugin/asset-plugin.ts @@ -0,0 +1,135 @@ +import { createHash } from 'node:crypto'; +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + writeFileSync, +} from 'node:fs'; +import { basename, dirname, extname, join } from 'node:path'; + +import type { NextConfig } from 'next'; +import { optimize } from 'svgo'; + +import { + ASSET_PHASES, + FONTS, + FONTS_DIR, + HASH_LENGTH, + ICONS_DIR, + IMMUTABLE_CACHE_CONTROL, + SPRITE, +} from './constants'; +import type { HashedAsset } from './types'; + +const ROOT_SVG = /^]*)>([\s\S]*)<\/svg>$/; +const VIEW_BOX = /viewBox="([^"]+)"/; + +/** + * Wraps an app's `next.config`. On `next dev` and `next build` it writes island's fonts and icon + * sprite into the app's `public/` under content-hashed names, puts their paths in `env` + * (`NEXT_PUBLIC_ISLAND_*`), and serves each file with an immutable `Cache-Control`. + * Build-time only: import it from `next.config.ts`, never from app code. + */ +export function withIslandAssets( + config: NextConfig, +): (phase: string) => NextConfig { + return (phase) => + ASSET_PHASES.has(phase) ? addIslandAssets(config) : config; +} + +function addIslandAssets(config: NextConfig): NextConfig { + const assets: HashedAsset[] = [ + { ...SPRITE, content: buildSprite() }, + ...FONTS.map((font) => ({ + ...font, + content: readFileSync(join(FONTS_DIR, font.file)), + })), + ].map(({ dir, file, envKey, content }) => ({ + envKey, + content, + // Header sources match without basePath; Next adds it. + route: `/${dir}/${hashedName(file, content)}`, + })); + const basePath = config.basePath ?? ''; + + return { + ...config, + env: { + ...config.env, + ...Object.fromEntries( + assets.map(({ envKey, route }) => [envKey, `${basePath}${route}`]), + ), + }, + // Only Next loads the headers, on `next dev` and `next build`, so the files are written here. + // Others that evaluate the config, such as Nx's project graph, read it without side effects. + async headers() { + writeAssets(assets); + return [ + ...((await config.headers?.()) ?? []), + ...assets.map(({ route }) => ({ + source: route, + headers: [{ key: 'Cache-Control', value: IMMUTABLE_CACHE_CONTROL }], + })), + ]; + }, + }; +} + +/** + * Optimizes every icon with svgo and joins them into one sprite. Stroke and fill are dropped + * from each root, so the `` that references a symbol sets them and a caller can change them. + */ +function buildSprite(): string { + const symbols = readdirSync(ICONS_DIR) + .filter((file) => file.endsWith('.svg')) + .sort() + .map((file) => { + const { data } = optimize(readFileSync(join(ICONS_DIR, file), 'utf8'), { + multipass: true, + // svgo 4 keeps the viewBox by default. + plugins: ['preset-default'], + }); + const [, attributes, body] = ROOT_SVG.exec(data) ?? []; + const viewBox = VIEW_BOX.exec(attributes ?? '')?.[1]; + if (body === undefined || !viewBox) { + throw new Error(`${file}: expected one root with a viewBox`); + } + return `${body}`; + }); + return `${symbols.join('')}\n`; +} + +/** `symbol-defs.svg` → `symbol-defs..svg`. */ +function hashedName(file: string, content: string | Buffer): string { + const hash = createHash('sha256') + .update(content) + .digest('hex') + .slice(0, HASH_LENGTH); + const extension = extname(file); + return `${basename(file, extension)}.${hash}${extension}`; +} + +/** + * Next can load the headers more than once per command, in more than one process. A hashed name + * always holds the same bytes, so an existing file is kept, and a new one is written to a temp + * file, then renamed, so no request ever sees half a file. + */ +function writeAssets(assets: readonly HashedAsset[]): void { + // Next runs from the app's folder, as every Nx target does. + const publicDir = join(process.cwd(), 'public'); + if (!existsSync(publicDir)) { + throw new Error( + `island asset plugin: ${publicDir} doesn't exist. Run next from the app's folder.`, + ); + } + for (const { route, content } of assets) { + const target = join(publicDir, route); + if (existsSync(target)) continue; + mkdirSync(dirname(target), { recursive: true }); + const temp = `${target}.${process.pid}.tmp`; + writeFileSync(temp, content); + renameSync(temp, target); + } +} diff --git a/packages/island/src/tools/asset-plugin/constants.ts b/packages/island/src/tools/asset-plugin/constants.ts new file mode 100644 index 0000000..a1c8509 --- /dev/null +++ b/packages/island/src/tools/asset-plugin/constants.ts @@ -0,0 +1,52 @@ +import { fileURLToPath } from 'node:url'; + +import { + PHASE_DEVELOPMENT_SERVER, + PHASE_PRODUCTION_BUILD, +} from 'next/constants'; + +import type { IslandAsset } from './types'; + +/** island's sources, resolved from this file, so the plugin works from every app. */ +export const ICONS_DIR = fileURLToPath( + new URL('../../icons/', import.meta.url), +); +export const FONTS_DIR = fileURLToPath( + new URL('../../fonts/', import.meta.url), +); + +/** Built with svgo from every `icons/*.svg`, one `` per icon. */ +export const SPRITE: IslandAsset = { + dir: 'icons', + file: 'symbol-defs.svg', + envKey: 'NEXT_PUBLIC_ISLAND_ICON_SPRITE_PATH', +}; + +/** Copied as they are from `fonts/`, one per font token. */ +export const FONTS: readonly IslandAsset[] = [ + { + dir: 'fonts', + file: 'yekan-bakh-fa-num-vf.woff2', + envKey: 'NEXT_PUBLIC_ISLAND_FONT_SANS_PATH', + }, + { + dir: 'fonts', + file: 'yekan-bakh-vf.woff2', + envKey: 'NEXT_PUBLIC_ISLAND_FONT_LATIN_PATH', + }, +]; + +/** + * `next dev` and `next build`. Every other phase, `next start` included, gets the config unchanged: + * the build already inlined `env` and wrote the headers into its routes manifest. + */ +export const ASSET_PHASES: ReadonlySet = new Set([ + PHASE_DEVELOPMENT_SERVER, + PHASE_PRODUCTION_BUILD, +]); + +/** A hashed name never gets new content, so browsers and CDNs keep the file without asking again. */ +export const IMMUTABLE_CACHE_CONTROL = 'public, max-age=31536000, immutable'; + +/** Hex characters of the SHA-256 content hash in each file name. */ +export const HASH_LENGTH = 8; diff --git a/packages/island/src/tools/asset-plugin/index.ts b/packages/island/src/tools/asset-plugin/index.ts new file mode 100644 index 0000000..57d795f --- /dev/null +++ b/packages/island/src/tools/asset-plugin/index.ts @@ -0,0 +1,2 @@ +// Build-time only, so island's root index.ts leaves it out (0008). +export { withIslandAssets } from './asset-plugin'; diff --git a/packages/island/src/tools/asset-plugin/types.ts b/packages/island/src/tools/asset-plugin/types.ts new file mode 100644 index 0000000..affe5a6 --- /dev/null +++ b/packages/island/src/tools/asset-plugin/types.ts @@ -0,0 +1,16 @@ +/** One island file the plugin copies into the app's `public/`. */ +export type IslandAsset = { + /** Folder under `public/`, which is also the URL path. */ + dir: 'icons' | 'fonts'; + /** Source file name; the written copy gets its content hash before the extension. */ + file: string; + /** The variable that carries the hashed path to the app's `env/`. */ + envKey: `NEXT_PUBLIC_ISLAND_${string}`; +}; + +/** An asset ready to write: its bytes and its hashed path under `public/`. */ +export type HashedAsset = Pick & { + content: string | Buffer; + /** `//..`, without basePath. */ + route: string; +}; diff --git a/packages/island/src/tools/icon-name-extraction/.gitkeep b/packages/island/src/tools/icon-name-extraction/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/packages/island/src/tools/icon-name-extraction/icon-name-extraction.ts b/packages/island/src/tools/icon-name-extraction/icon-name-extraction.ts new file mode 100644 index 0000000..e0708de --- /dev/null +++ b/packages/island/src/tools/icon-name-extraction/icon-name-extraction.ts @@ -0,0 +1,33 @@ +import { readdirSync, writeFileSync } from 'node:fs'; +import { basename } from 'node:path'; + +import type { IconNameExtractionOptions } from './types'; + +/** + * Writes the `IconName` union from the icon file names, so `` only accepts an icon + * the sprite has. The sprite itself is built by `tools/asset-plugin` on `next dev` and `next build`. + */ +export function extractIconNames({ + iconsDir, + namesFile, +}: IconNameExtractionOptions): string[] { + const names = readdirSync(iconsDir) + .filter((file) => file.endsWith('.svg')) + .sort() + .map((file) => basename(file, '.svg')); + + writeFileSync( + namesFile, + [ + '// Generated by tools/icon-name-extraction from src/icons/*.svg. Run `pnpm nx run island:icons`.', + '', + 'export const ICON_NAMES = [', + ...names.map((name) => ` '${name}',`), + '] as const;', + '', + 'export type IconName = (typeof ICON_NAMES)[number];', + '', + ].join('\n'), + ); + return names; +} diff --git a/packages/island/src/tools/icon-name-extraction/index.ts b/packages/island/src/tools/icon-name-extraction/index.ts new file mode 100644 index 0000000..e401752 --- /dev/null +++ b/packages/island/src/tools/icon-name-extraction/index.ts @@ -0,0 +1,2 @@ +export { extractIconNames } from './icon-name-extraction'; +export type { IconNameExtractionOptions } from './types'; diff --git a/packages/island/src/tools/icon-sprite-plugin/run.ts b/packages/island/src/tools/icon-name-extraction/run.ts similarity index 53% rename from packages/island/src/tools/icon-sprite-plugin/run.ts rename to packages/island/src/tools/icon-name-extraction/run.ts index bdb0792..4dc84ea 100644 --- a/packages/island/src/tools/icon-sprite-plugin/run.ts +++ b/packages/island/src/tools/icon-name-extraction/run.ts @@ -1,14 +1,13 @@ import { fileURLToPath } from 'node:url'; -import { buildIconSprite } from './icon-sprite-plugin'; +import { extractIconNames } from './icon-name-extraction'; const src = (path: string) => fileURLToPath(new URL(`../../${path}`, import.meta.url)); -const names = buildIconSprite({ +const names = extractIconNames({ iconsDir: src('icons'), - spriteFile: src('atoms/icon/sprite.svg'), namesFile: src('atoms/icon/icon-names.ts'), }); -console.log(`Icon sprite: ${names.length} icons`); +console.log(`Icon names: ${names.length} icons`); diff --git a/packages/island/src/tools/icon-sprite-plugin/types.ts b/packages/island/src/tools/icon-name-extraction/types.ts similarity index 62% rename from packages/island/src/tools/icon-sprite-plugin/types.ts rename to packages/island/src/tools/icon-name-extraction/types.ts index cec969b..05ad608 100644 --- a/packages/island/src/tools/icon-sprite-plugin/types.ts +++ b/packages/island/src/tools/icon-name-extraction/types.ts @@ -1,8 +1,6 @@ -export type IconSpriteOptions = { +export type IconNameExtractionOptions = { /** Folder of source icons, one `.svg` each, drawn on a 24px grid in `currentColor`. */ iconsDir: string; - /** The sprite to write: one `` per icon. */ - spriteFile: string; /** The TypeScript file to write with the `IconName` union. */ namesFile: string; }; diff --git a/packages/island/src/tools/icon-sprite-plugin/icon-sprite-plugin.ts b/packages/island/src/tools/icon-sprite-plugin/icon-sprite-plugin.ts deleted file mode 100644 index a4d48f6..0000000 --- a/packages/island/src/tools/icon-sprite-plugin/icon-sprite-plugin.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { readdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { basename, join } from 'node:path'; -import { optimize } from 'svgo'; - -import type { IconSpriteOptions } from './types'; - -const ROOT_SVG = /^]*)>([\s\S]*)<\/svg>$/; -const VIEW_BOX = /viewBox="([^"]+)"/; - -/** - * Optimizes every icon with svgo and joins them into one sprite. Stroke and fill are dropped - * from each root, so the `` that references a symbol sets them and a caller can change them. - */ -export function buildIconSprite({ - iconsDir, - spriteFile, - namesFile, -}: IconSpriteOptions): string[] { - const files = readdirSync(iconsDir) - .filter((file) => file.endsWith('.svg')) - .sort(); - const names = files.map((file) => basename(file, '.svg')); - - const symbols = files.map((file, index) => { - const { data } = optimize(readFileSync(join(iconsDir, file), 'utf8'), { - multipass: true, - // svgo 4 keeps the viewBox by default. - plugins: ['preset-default'], - }); - const [, attributes, body] = ROOT_SVG.exec(data) ?? []; - const viewBox = VIEW_BOX.exec(attributes ?? '')?.[1]; - if (body === undefined || !viewBox) { - throw new Error(`${file}: expected one root with a viewBox`); - } - return `${body}`; - }); - - // Next.js reads a static SVG's size on import, so the root carries one; `` ignores it. - writeFileSync( - spriteFile, - `${symbols.join('')}\n`, - ); - writeFileSync( - namesFile, - [ - '// Generated by tools/icon-sprite-plugin from src/icons/*.svg. Run `pnpm nx run island:icons`.', - '', - 'export const ICON_NAMES = [', - ...names.map((name) => ` '${name}',`), - '] as const;', - '', - 'export type IconName = (typeof ICON_NAMES)[number];', - '', - ].join('\n'), - ); - return names; -} diff --git a/packages/island/src/tools/icon-sprite-plugin/index.ts b/packages/island/src/tools/icon-sprite-plugin/index.ts deleted file mode 100644 index 26e69f6..0000000 --- a/packages/island/src/tools/icon-sprite-plugin/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { buildIconSprite } from './icon-sprite-plugin'; -export type { IconSpriteOptions } from './types';