diff --git a/.gitignore b/.gitignore index 57e1855..b0bba18 100644 --- a/.gitignore +++ b/.gitignore @@ -26,7 +26,7 @@ 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) +# Fonts and icon sprite, written by island's font-copy and icon-sprite plugins on next dev and next build (0012) apps/*/public/icons/ apps/*/public/fonts/ diff --git a/apps/bear/.env.example b/apps/bear/.env.example index 0e569f9..604e5a5 100644 --- a/apps/bear/.env.example +++ b/apps/bear/.env.example @@ -6,10 +6,6 @@ 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 42263ff..6038442 100644 --- a/apps/bear/next.config.ts +++ b/apps/bear/next.config.ts @@ -1,6 +1,13 @@ -import { withIslandAssets } from '@lumina/island/tools/asset-plugin'; +import { withFontCopy } from '@lumina/island/tools/font-copy-plugin'; +import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin'; import type { NextConfig } from 'next'; +// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new +// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again. +const immutable = [ + { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }, +]; + const nextConfig: NextConfig = { // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ @@ -21,6 +28,12 @@ const nextConfig: NextConfig = { }, ]; }, + async headers() { + return [ + { source: '/fonts/:path*', headers: immutable }, + { source: '/icons/:path*', headers: immutable }, + ]; + }, // One canonical URL per channel: send direct `/channels/…` hits to `/@…`. async redirects() { return [ @@ -33,5 +46,6 @@ const nextConfig: NextConfig = { }, }; -// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008). -export default withIslandAssets(nextConfig); +// On next dev and next build, island's plugins write the fonts and icon sprite into public/ +// under their fixed names, with no hash (0012). +export default withIconSprite(withFontCopy(nextConfig)); diff --git a/apps/bear/src/app/global-error.tsx b/apps/bear/src/app/global-error.tsx index b33a685..19d8792 100644 --- a/apps/bear/src/app/global-error.tsx +++ b/apps/bear/src/app/global-error.tsx @@ -8,7 +8,6 @@ import { Element } from '@lumina/island/primitives/element'; import { ErrorFallback } from '@lumina/market/app/error-boundaries'; import { i18n } from '../i18n/i18n.client'; -import { yekanBakh } from '../styles'; type GlobalErrorProps = { error: Error & { digest?: string }; @@ -17,12 +16,7 @@ type GlobalErrorProps = { /** The app boundary (EB-W): the last resort when nothing below caught the error. */ export default function GlobalError({ error }: GlobalErrorProps) { return ( - + + {children} diff --git a/apps/bear/src/bootstrap/bootstrap.client.ts b/apps/bear/src/bootstrap/bootstrap.client.ts index c50069a..b11fa21 100644 --- a/apps/bear/src/bootstrap/bootstrap.client.ts +++ b/apps/bear/src/bootstrap/bootstrap.client.ts @@ -1,6 +1,5 @@ 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'; @@ -9,7 +8,6 @@ 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. @@ -19,7 +17,6 @@ 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 8539bb8..1e1c316 100644 --- a/apps/bear/src/bootstrap/bootstrap.server.ts +++ b/apps/bear/src/bootstrap/bootstrap.server.ts @@ -1,6 +1,5 @@ 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'; @@ -12,7 +11,6 @@ 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({ @@ -21,7 +19,6 @@ 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 deleted file mode 100644 index 0c101d5..0000000 --- a/apps/bear/src/bootstrap/island-env.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 c7d6d49..67ec37c 100644 --- a/apps/bear/src/env/env.client.ts +++ b/apps/bear/src/env/env.client.ts @@ -3,7 +3,6 @@ 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({ @@ -14,11 +13,6 @@ 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, @@ -26,12 +20,5 @@ 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/bear/src/styles/fonts.ts b/apps/bear/src/styles/fonts.ts deleted file mode 100644 index c6f1b75..0000000 --- a/apps/bear/src/styles/fonts.ts +++ /dev/null @@ -1,23 +0,0 @@ -import localFont from 'next/font/local'; - -// Variable fonts from island. next/font self-hosts them, preloads the critical face, -// and adds a size-adjusted fallback so the swap doesn't shift the layout. - -/** Yekan Bakh with Persian digit shapes: every UI text. */ -export const yekanBakh = localFont({ - src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2', - variable: '--font-yekan-bakh', - weight: '100 1000', - display: 'swap', - adjustFontFallback: 'Arial', -}); - -/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */ -export const yekanBakhLatin = localFont({ - src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2', - variable: '--font-yekan-bakh-latin', - weight: '100 1000', - display: 'swap', - preload: false, - adjustFontFallback: 'Arial', -}); diff --git a/apps/bear/src/styles/index.ts b/apps/bear/src/styles/index.ts deleted file mode 100644 index b0a9521..0000000 --- a/apps/bear/src/styles/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { yekanBakh, yekanBakhLatin } from './fonts'; diff --git a/apps/bull/.env.example b/apps/bull/.env.example index d8f1b99..2c80a51 100644 --- a/apps/bull/.env.example +++ b/apps/bull/.env.example @@ -6,10 +6,6 @@ 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 42263ff..6038442 100644 --- a/apps/bull/next.config.ts +++ b/apps/bull/next.config.ts @@ -1,6 +1,13 @@ -import { withIslandAssets } from '@lumina/island/tools/asset-plugin'; +import { withFontCopy } from '@lumina/island/tools/font-copy-plugin'; +import { withIconSprite } from '@lumina/island/tools/icon-sprite-plugin'; import type { NextConfig } from 'next'; +// Fonts and the icon sprite keep fixed names; a changed font gets a new name, and the sprite a new +// ?v= (0011, 0012). Next serves public/ with max-age=0, so without this every visit asks for them again. +const immutable = [ + { key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }, +]; + const nextConfig: NextConfig = { // Workspace packages export TypeScript source, so Next.js compiles them. transpilePackages: [ @@ -21,6 +28,12 @@ const nextConfig: NextConfig = { }, ]; }, + async headers() { + return [ + { source: '/fonts/:path*', headers: immutable }, + { source: '/icons/:path*', headers: immutable }, + ]; + }, // One canonical URL per channel: send direct `/channels/…` hits to `/@…`. async redirects() { return [ @@ -33,5 +46,6 @@ const nextConfig: NextConfig = { }, }; -// On next dev and next build, writes island's hashed fonts and icon sprite into public/ (0008). -export default withIslandAssets(nextConfig); +// On next dev and next build, island's plugins write the fonts and icon sprite into public/ +// under their fixed names, with no hash (0012). +export default withIconSprite(withFontCopy(nextConfig)); diff --git a/apps/bull/src/app/global-error.tsx b/apps/bull/src/app/global-error.tsx index b33a685..19d8792 100644 --- a/apps/bull/src/app/global-error.tsx +++ b/apps/bull/src/app/global-error.tsx @@ -8,7 +8,6 @@ import { Element } from '@lumina/island/primitives/element'; import { ErrorFallback } from '@lumina/market/app/error-boundaries'; import { i18n } from '../i18n/i18n.client'; -import { yekanBakh } from '../styles'; type GlobalErrorProps = { error: Error & { digest?: string }; @@ -17,12 +16,7 @@ type GlobalErrorProps = { /** The app boundary (EB-W): the last resort when nothing below caught the error. */ export default function GlobalError({ error }: GlobalErrorProps) { return ( - + + {children} diff --git a/apps/bull/src/bootstrap/bootstrap.client.ts b/apps/bull/src/bootstrap/bootstrap.client.ts index c50069a..b11fa21 100644 --- a/apps/bull/src/bootstrap/bootstrap.client.ts +++ b/apps/bull/src/bootstrap/bootstrap.client.ts @@ -1,6 +1,5 @@ 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'; @@ -9,7 +8,6 @@ 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. @@ -19,7 +17,6 @@ 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 8539bb8..1e1c316 100644 --- a/apps/bull/src/bootstrap/bootstrap.server.ts +++ b/apps/bull/src/bootstrap/bootstrap.server.ts @@ -1,6 +1,5 @@ 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'; @@ -12,7 +11,6 @@ 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({ @@ -21,7 +19,6 @@ 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 deleted file mode 100644 index 0c101d5..0000000 --- a/apps/bull/src/bootstrap/island-env.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 c7d6d49..67ec37c 100644 --- a/apps/bull/src/env/env.client.ts +++ b/apps/bull/src/env/env.client.ts @@ -3,7 +3,6 @@ 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({ @@ -14,11 +13,6 @@ 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, @@ -26,12 +20,5 @@ 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/src/styles/fonts.ts b/apps/bull/src/styles/fonts.ts deleted file mode 100644 index c6f1b75..0000000 --- a/apps/bull/src/styles/fonts.ts +++ /dev/null @@ -1,23 +0,0 @@ -import localFont from 'next/font/local'; - -// Variable fonts from island. next/font self-hosts them, preloads the critical face, -// and adds a size-adjusted fallback so the swap doesn't shift the layout. - -/** Yekan Bakh with Persian digit shapes: every UI text. */ -export const yekanBakh = localFont({ - src: '../../../../packages/island/src/fonts/yekan-bakh-fa-num-vf.woff2', - variable: '--font-yekan-bakh', - weight: '100 1000', - display: 'swap', - adjustFontFallback: 'Arial', -}); - -/** Yekan Bakh with Latin digits: شبا and other bank codes. Loaded only where used. */ -export const yekanBakhLatin = localFont({ - src: '../../../../packages/island/src/fonts/yekan-bakh-vf.woff2', - variable: '--font-yekan-bakh-latin', - weight: '100 1000', - display: 'swap', - preload: false, - adjustFontFallback: 'Arial', -}); diff --git a/apps/bull/src/styles/index.ts b/apps/bull/src/styles/index.ts deleted file mode 100644 index b0a9521..0000000 --- a/apps/bull/src/styles/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { yekanBakh, yekanBakhLatin } from './fonts'; diff --git a/packages/island/package.json b/packages/island/package.json index 3aff7dc..2a4b59f 100644 --- a/packages/island/package.json +++ b/packages/island/package.json @@ -16,7 +16,7 @@ "./primitives/*": "./src/primitives/*/index.ts", "./hooks/*": "./src/hooks/*/index.ts", "./tools/*": "./src/tools/*/index.ts", - "./env": "./src/env/index.ts", + "./constants": "./src/constants.ts", "./styles/*": "./src/styles/*", "./icons/*": "./src/icons/*", "./fonts/*": "./src/fonts/*", diff --git a/packages/island/src/atoms/icon/Icon.tsx b/packages/island/src/atoms/icon/Icon.tsx index 9bab90b..a89eb19 100644 --- a/packages/island/src/atoms/icon/Icon.tsx +++ b/packages/island/src/atoms/icon/Icon.tsx @@ -1,4 +1,4 @@ -import { getEnv } from '../../env'; +import { ICON_SPRITE_URL } from '../../constants'; import { Element } from '../../primitives/element'; import { cn } from '../../tools/cn'; import type { IconProps } from './types'; @@ -30,8 +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. */} - + {/* One sprite under a fixed name, linked with its version, that the browser caches across deploys; each icon is a `` into it, so icons add no JavaScript. */} + ); } diff --git a/packages/island/src/constants.ts b/packages/island/src/constants.ts new file mode 100644 index 0000000..e3b685c --- /dev/null +++ b/packages/island/src/constants.ts @@ -0,0 +1,24 @@ +// Fonts and the icon sprite keep fixed names that no build step hashes or renames, so a file that +// didn't change stays in every visitor's cache across deploys (0011, 0012). Fonts have no version: a +// changed font ships as a new file with a new name. The sprite's version lives only in its link. + +/** + * Raise it with every change to `icons/*.svg` or to the svgo step in `icon-sprite-plugin`, in the + * same commit. Never reuse or lower it. + */ +export const ICON_SPRITE_VERSION = 1; + +/** Where `icon-sprite-plugin` writes the sprite, under each app's `public/`. Its name never changes. */ +export const ICON_SPRITE_PATH = '/icons/symbol-defs.svg'; + +/** + * Root-relative and same-origin: `` never loads across origins, and CORS can't change + * that. The version is a query string, so a CDN must keep the query in its cache key. + */ +export const ICON_SPRITE_URL = `${ICON_SPRITE_PATH}?v=${ICON_SPRITE_VERSION}`; + +/** + * The face every page renders first, Yekan Bakh FaNum. Each root layout preloads it. A font file + * is named only here and in `styles/fonts.css`. + */ +export const CRITICAL_FONT_URL = '/fonts/yekan-bakh-fa-num-vf.woff2'; diff --git a/packages/island/src/env/env.ts b/packages/island/src/env/env.ts deleted file mode 100644 index 9739e83..0000000 --- a/packages/island/src/env/env.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 3393c00..0000000 --- a/packages/island/src/env/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -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 deleted file mode 100644 index ef094df..0000000 --- a/packages/island/src/env/types.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** 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 6ba6da8..3765bb1 100644 --- a/packages/island/src/index.ts +++ b/packages/island/src/index.ts @@ -204,5 +204,9 @@ export type { ValidTags, } from './primitives/element'; export { cn } from './tools/cn'; -export { getEnv, setEnv } from './env'; -export type { IslandEnv } from './env'; +export { + CRITICAL_FONT_URL, + ICON_SPRITE_PATH, + ICON_SPRITE_URL, + ICON_SPRITE_VERSION, +} from './constants'; diff --git a/packages/island/src/styles/fonts.css b/packages/island/src/styles/fonts.css new file mode 100644 index 0000000..3ec6978 --- /dev/null +++ b/packages/island/src/styles/fonts.css @@ -0,0 +1,41 @@ +/* + * Yekan Bakh, served from each app's public/fonts/ by font-copy-plugin (0011, 0012). + * Every `src` is a root path to a file under its fixed name. Next.js leaves root paths alone; a + * relative url('../fonts/…') would go through the bundler and get a hash. + * A font file is named only here and in CRITICAL_FONT_URL (constants.ts). A changed font ships + * under a new name, never under its old one. + * + * Both faces are variable: wght 100–950 and wdth 62.5–150%. The ranges must be declared: + * without font-stretch the browser leaves wdth at its default, 62.5%, and text renders condensed. + */ + +/* Persian digit shapes for Latin digits: every UI text (`font-sans`). Preloaded. */ +@font-face { + font-family: 'Yekan Bakh FaNum'; + src: url('/fonts/yekan-bakh-fa-num-vf.woff2') format('woff2'); + font-weight: 100 950; + font-stretch: 62.5% 150%; + font-display: swap; +} + +/* Latin digits: only شبا and other codes banks print that way (`font-latin`). Not preloaded. */ +@font-face { + font-family: 'Yekan Bakh'; + src: url('/fonts/yekan-bakh-vf.woff2') format('woff2'); + font-weight: 100 950; + font-stretch: 62.5% 150%; + font-display: swap; +} + +/* + * Shown until Yekan Bakh loads. Its vertical metrics are the web font's own (hhea: ascent 1000, + * descent 550, line gap 0, per 1000 units), so lines keep their height when the font swaps in. + * size-adjust isn't measured yet; it needs Persian text set in Tahoma against Yekan Bakh. + */ +@font-face { + font-family: 'Yekan Bakh Fallback'; + src: local('Tahoma'), local('Arial'); + ascent-override: 100%; + descent-override: 55%; + line-gap-override: 0%; +} diff --git a/packages/island/src/styles/island.css b/packages/island/src/styles/island.css index f7d4259..a1c2f95 100644 --- a/packages/island/src/styles/island.css +++ b/packages/island/src/styles/island.css @@ -1,4 +1,5 @@ -/* Entry that apps import after `tailwindcss`. Fonts are loaded by each app with next/font. */ +/* Entry that apps import after `tailwindcss`. Never load fonts with next/font: it hashes them (0011). */ +@import './fonts.css'; @import './theme.css'; @import './utilities.css'; @source '../'; diff --git a/packages/island/src/styles/theme.css b/packages/island/src/styles/theme.css index 0d0c3fe..9451371 100644 --- a/packages/island/src/styles/theme.css +++ b/packages/island/src/styles/theme.css @@ -13,9 +13,10 @@ --breakpoint-*: initial; --container-*: initial; - --font-sans: var(--font-yekan-bakh), Tahoma, sans-serif; + /* Faces and their fallback are declared in fonts.css. */ + --font-sans: 'Yekan Bakh FaNum', 'Yekan Bakh Fallback', Tahoma, sans-serif; /* Latin digits, for شبا and other codes banks print in Latin digits. */ - --font-latin: var(--font-yekan-bakh-latin), Tahoma, sans-serif; + --font-latin: 'Yekan Bakh', 'Yekan Bakh Fallback', Tahoma, sans-serif; /* Sizes are the design system's px values ÷ 16, in rem, so text and spacing follow the reader's browser font size. */ diff --git a/packages/island/src/tools/asset-plugin/asset-plugin.ts b/packages/island/src/tools/asset-plugin/asset-plugin.ts deleted file mode 100644 index 696d011..0000000 --- a/packages/island/src/tools/asset-plugin/asset-plugin.ts +++ /dev/null @@ -1,135 +0,0 @@ -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 deleted file mode 100644 index a1c8509..0000000 --- a/packages/island/src/tools/asset-plugin/constants.ts +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index 57d795f..0000000 --- a/packages/island/src/tools/asset-plugin/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index affe5a6..0000000 --- a/packages/island/src/tools/asset-plugin/types.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** 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/font-copy-plugin/constants.ts b/packages/island/src/tools/font-copy-plugin/constants.ts new file mode 100644 index 0000000..61090e9 --- /dev/null +++ b/packages/island/src/tools/font-copy-plugin/constants.ts @@ -0,0 +1,6 @@ +import { fileURLToPath } from 'node:url'; + +/** island's fonts, resolved from this file, so the plugin works from every app. */ +export const FONTS_DIR = fileURLToPath( + new URL('../../fonts/', import.meta.url), +); diff --git a/packages/island/src/tools/font-copy-plugin/font-copy-plugin.ts b/packages/island/src/tools/font-copy-plugin/font-copy-plugin.ts new file mode 100644 index 0000000..b5a653e --- /dev/null +++ b/packages/island/src/tools/font-copy-plugin/font-copy-plugin.ts @@ -0,0 +1,63 @@ +import { + copyFileSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, +} from 'node:fs'; +import { join } from 'node:path'; + +import type { NextConfig } from 'next'; + +import { FONTS_DIR } from './constants'; + +/** + * Wraps an app's `next.config`. On `next dev` and `next build` it copies island's `fonts/` byte + * for byte into `public/fonts/`, keeping their fixed names with no hash (0011, 0012). + * Build-time only: import it from `next.config.ts`, never from app code. + */ +export function withFontCopy(config: NextConfig): NextConfig { + return { + ...config, + // Only Next calls `headers()`, and only on `next dev` and `next build`; `next start` reads the + // build's routes manifest. Others that evaluate the config, such as Nx's project graph, never + // call it, so the files are copied here and nowhere else. + async headers() { + copyFonts(); + return (await config.headers?.()) ?? []; + }, + }; +} + +/** + * Next can call `headers()` more than once per command, in more than one process. An unchanged + * file is left alone, and a new one is copied to a temp file, then renamed, so no request ever + * sees half a font. + */ +function copyFonts(): 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( + `font-copy-plugin: ${publicDir} doesn't exist. Run next from the app's folder.`, + ); + } + const targetDir = join(publicDir, 'fonts'); + mkdirSync(targetDir, { recursive: true }); + for (const file of readdirSync(FONTS_DIR)) { + if (!file.endsWith('.woff2')) continue; + const source = join(FONTS_DIR, file); + const target = join(targetDir, file); + if (existsSync(target)) { + if (readFileSync(target).equals(readFileSync(source))) continue; + // Visitors who cached this name keep its old bytes for a year. + console.warn( + `font-copy-plugin: ${file} changed under the same name. Ship the changed font under a new name in fonts/, fonts.css and CRITICAL_FONT_URL before this ships.`, + ); + } + const temp = `${target}.${process.pid}.tmp`; + copyFileSync(source, temp); + renameSync(temp, target); + } +} diff --git a/packages/island/src/tools/font-copy-plugin/index.ts b/packages/island/src/tools/font-copy-plugin/index.ts new file mode 100644 index 0000000..a3fa7a5 --- /dev/null +++ b/packages/island/src/tools/font-copy-plugin/index.ts @@ -0,0 +1,2 @@ +// Build-time only, so island's root index.ts leaves it out (0012). +export { withFontCopy } from './font-copy-plugin'; 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 index e0708de..b2b1222 100644 --- a/packages/island/src/tools/icon-name-extraction/icon-name-extraction.ts +++ b/packages/island/src/tools/icon-name-extraction/icon-name-extraction.ts @@ -5,7 +5,7 @@ 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`. + * the sprite has. The sprite itself is built by `tools/icon-sprite-plugin` on `next dev` and `next build`. */ export function extractIconNames({ iconsDir, diff --git a/packages/island/src/tools/icon-sprite-plugin/constants.ts b/packages/island/src/tools/icon-sprite-plugin/constants.ts new file mode 100644 index 0000000..a8e6dba --- /dev/null +++ b/packages/island/src/tools/icon-sprite-plugin/constants.ts @@ -0,0 +1,6 @@ +import { fileURLToPath } from 'node:url'; + +/** island's icons, resolved from this file, so the plugin works from every app. */ +export const ICONS_DIR = fileURLToPath( + new URL('../../icons/', import.meta.url), +); 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 new file mode 100644 index 0000000..a075501 --- /dev/null +++ b/packages/island/src/tools/icon-sprite-plugin/icon-sprite-plugin.ts @@ -0,0 +1,94 @@ +import { + existsSync, + mkdirSync, + readdirSync, + readFileSync, + renameSync, + writeFileSync, +} from 'node:fs'; +import { basename, dirname, join } from 'node:path'; + +import type { NextConfig } from 'next'; + +import { ICON_SPRITE_PATH, ICON_SPRITE_VERSION } from '../../constants'; +import { ICONS_DIR } from './constants'; + +const ROOT_SVG = /^]*)>([\s\S]*)<\/svg>$/; +const VIEW_BOX = /viewBox="([^"]+)"/; +/** The sprite's first line, so the next run knows which version the file in `public/` was built for. */ +const VERSION_STAMP = ``; + +/** + * Wraps an app's `next.config`. On `next dev` and `next build` it builds island's icon sprite + * with svgo and writes it to `public/` at `ICON_SPRITE_PATH`, a fixed name with no hash (0012). The + * version lives only in `ICON_SPRITE_URL`'s query string. + * Build-time only: import it from `next.config.ts`, never from app code. + */ +export function withIconSprite(config: NextConfig): NextConfig { + return { + ...config, + // Only Next calls `headers()`, and only on `next dev` and `next build`; `next start` reads the + // build's routes manifest. Others that evaluate the config, such as Nx's project graph, never + // call it, so the file is written here and nowhere else. + async headers() { + writeSprite(await buildSprite()); + return (await config.headers?.()) ?? []; + }, + }; +} + +/** + * 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. + */ +async function buildSprite(): Promise { + // Loaded here, so `next start` never needs svgo. + const { optimize } = await import('svgo'); + 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 `${VERSION_STAMP}\n${symbols.join('')}\n`; +} + +/** + * Next can call `headers()` more than once per command, in more than one process. An unchanged + * file is left alone, and a new one is written to a temp file, then renamed, so no request ever + * sees half a file. + */ +function writeSprite(sprite: string): 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( + `icon-sprite-plugin: ${publicDir} doesn't exist. Run next from the app's folder.`, + ); + } + const target = join(publicDir, ICON_SPRITE_PATH); + if (existsSync(target)) { + const current = readFileSync(target, 'utf8'); + if (current === sprite) return; + // Same version, new icons: visitors who cached this version keep the old icons for a year. + if (current.startsWith(VERSION_STAMP)) { + console.warn( + `icon-sprite-plugin: the sprite changed, but ICON_SPRITE_VERSION is still ${ICON_SPRITE_VERSION}. Raise it in island's constants.ts before this ships.`, + ); + } + } + mkdirSync(dirname(target), { recursive: true }); + const temp = `${target}.${process.pid}.tmp`; + writeFileSync(temp, sprite); + renameSync(temp, target); +} diff --git a/packages/island/src/tools/icon-sprite-plugin/index.ts b/packages/island/src/tools/icon-sprite-plugin/index.ts new file mode 100644 index 0000000..2a7d7bb --- /dev/null +++ b/packages/island/src/tools/icon-sprite-plugin/index.ts @@ -0,0 +1,2 @@ +// Build-time only, so island's root index.ts leaves it out (0012). +export { withIconSprite } from './icon-sprite-plugin';