### Install unifont with npm Source: https://unifont.dev/docs/getting-started Install the unifont package. unifont is ESM-only and has no peer dependencies. ```bash npm i unifont ``` -------------------------------- ### GET / Source: https://unifont.dev/docs/proxy Returns the list of available endpoints as JSON. ```APIDOC ## GET / ### Description Returns the endpoint list as JSON. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (JSON) - The list of available endpoints. #### Response Example ```json { "endpoints": [ "/adobe/v1/kit/:id", "/adobe/v1/kit-css/:id", "/bunny/v1/list", "/bunny/v1/css", "/fontshare/v1/fonts", "/fontshare/v1/css", "/fontsource/v1/fonts", "/fontsource/v1/fonts/:id", "/fontsource/v1/variable/:id", "/google/v1/fonts", "/google/v1/css", "/google/v1/icons", "/google/v1/icon" ] } ``` ``` -------------------------------- ### GET /bunny/v1/css Source: https://unifont.dev/docs/proxy Retrieves CSS for fonts from Bunny Fonts. ```APIDOC ## GET /bunny/v1/css ### Description Retrieves CSS for fonts from Bunny Fonts. ### Method GET ### Endpoint /bunny/v1/css ### Parameters #### Query Parameters - **family** (string) - Required - The font family name. ### Response #### Success Response (200) - **body** (CSS) - The CSS content for the requested font family. #### Response Example ```css @font-face { font-family: 'Example'; src: url('...'); } ``` ``` -------------------------------- ### Import unifont exports and types Source: https://unifont.dev/docs/reference Import the three runtime exports and the type exports from the 'unifont' package. This is the starting point for using the API. ```ts import { createUnifont, defineFontProvider, providers } from 'unifont' import type { FontFaceData, FontProperties, ResolveFontOptions, ResolveFontResult, Unifont } from 'unifont' ``` -------------------------------- ### GET /google/v1/css Source: https://unifont.dev/docs/proxy Retrieves CSS for fonts from Google Fonts. ```APIDOC ## GET /google/v1/css ### Description Retrieves CSS for fonts from Google Fonts. ### Method GET ### Endpoint /google/v1/css ### Parameters #### Query Parameters - **family** (string) - Required - The font family name. - **text** (string) - Optional - The text to render. - **icon_names** (string) - Optional - The icon names. - **format** (string) - Optional - The font format. One of `woff2` (default), `woff`, `ttf`, or `eot`. ### Response #### Success Response (200) - **body** (CSS) - The CSS content for the requested font family. #### Response Example ```css @font-face { font-family: 'Example'; src: url('...'); } ``` ``` -------------------------------- ### GET /fontshare/v1/css Source: https://unifont.dev/docs/proxy Retrieves CSS for fonts from Fontshare. ```APIDOC ## GET /fontshare/v1/css ### Description Retrieves CSS for fonts from Fontshare. ### Method GET ### Endpoint /fontshare/v1/css ### Parameters #### Query Parameters - **f[]** (array) - Required - The font family names. ### Response #### Success Response (200) - **body** (CSS) - The CSS content for the requested font families. #### Response Example ```css @font-face { font-family: 'Example'; src: url('...'); } ``` ``` -------------------------------- ### resolveFont() with weights, styles, subsets, formats Source: https://unifont.dev/docs/resolving Basic usage of resolveFont() with options for weights, styles, subsets, and formats. Every option is a hint, not a guarantee; for example, requesting otf from a provider that only serves woff2 returns woff2. ```ts const { fonts, fallbacks, provider } = await unifont.resolveFont('Poppins', { weights: ['400', '700'], styles: ['normal', 'italic'], subsets: ['latin', 'latin-ext'], formats: ['woff2'], }) ``` -------------------------------- ### Pass provider options to unifont.resolveFont() Source: https://unifont.dev/docs/resolving Use to pass per-family provider options. The options object is grouped by provider name (here 'google') and is typed from the providers passed to createUnifont(). This example passes experimental glyphs to the Google provider. ```ts const { fonts } = await unifont.resolveFont('Poppins', { options: { google: { experimental: { glyphs: ['Hello', 'World'] }, }, }, }) ``` -------------------------------- ### Create unifont with providers and resolve a family Source: https://unifont.dev/docs Sets up a unifont instance with Google and Fontshare providers proportional, then resolves a font family. Use this to get consistent font metadata across different CDNs. ```ts import { createUnifont, providers } from 'unifont' const unifont = await createUnifont([ providers.google(), providers.fontshare(), ]) const { fonts, fallbacks } = await unifont.resolveFont('Switzer') ``` -------------------------------- ### GET /google/v1/icon Source: https://unifont.dev/docs/proxy Retrieves an icon from Google Fonts. ```APIDOC ## GET /google/v1/icon ### Description Retrieves an icon from Google Fonts. ### Method GET ### Endpoint /google/v1/icon ### Parameters #### Query Parameters - **family** (string) - Required - The icon family name. - **format** (string) - Optional - The font format. One of `woff2` (default), `woff`, `ttf`, or `eot`. ### Response #### Success Response (200) - **body** (CSS) - The CSS content for the requested icon. #### Response Example ```css @font-face { font-family: 'Example'; src: url('...'); } ``` ``` -------------------------------- ### GET /bunny/v1/list Source: https://unifont.dev/docs/proxy Retrieves the list of fonts from Bunny Fonts. ```APIDOC ## GET /bunny/v1/list ### Description Retrieves the list of fonts from Bunny Fonts. ### Method GET ### Endpoint /bunny/v1/list ### Response #### Success Response (200) - **body** (JSON) - The list of fonts. #### Response Example ```json { "fonts": [] } ``` ``` -------------------------------- ### GET /fontsource/v1/fonts Source: https://unifont.dev/docs/proxy Retrieves the list of fonts from Fontsource. ```APIDOC ## GET /fontsource/v1/fonts ### Description Retrieves the list of fonts from Fontsource. ### Method GET ### Endpoint /fontsource/v1/fonts ### Response #### Success Response (200) - **body** (JSON) - The list of fonts. #### Response Example ```json { "fonts": [] } ``` ``` -------------------------------- ### GET /adobe/v1/kit-css/:id Source: https://unifont.dev/docs/proxy Retrieves the CSS for an Adobe kit from the upstream Typekit CSS endpoint. ```APIDOC ## GET /adobe/v1/kit-css/:id ### Description Retrieves the CSS for an Adobe kit from the upstream Typekit CSS endpoint. ### Method GET ### Endpoint /adobe/v1/kit-css/:id ### Parameters #### Path Parameters - **id** (string) - Required - The kit identifier. ### Response #### Success Response (200) - **body** (CSS) - The CSS content for the kit. #### Response Example ```css @font-face { font-family: 'Example'; src: url('...'); } ``` ``` -------------------------------- ### GET /adobe/v1/kit/:id Source: https://unifont.dev/docs/proxy Retrieves Adobe kit information from the upstream Typekit API. ```APIDOC ## GET /adobe/v1/kit/:id ### Description Retrieves Adobe kit information from the upstream Typekit API. ### Method GET ### Endpoint /adobe/v1/kit/:id ### Parameters #### Path Parameters - **id** (string) - Required - The kit identifier. ### Response #### Success Response (200) - **body** (JSON) - The kit data from the upstream API. #### Response Example ```json { "id": "abc123", "families": [] } ``` ``` -------------------------------- ### GET /google/v1/icons Source: https://unifont.dev/docs/proxy Retrieves the list of icons from Google Fonts. ```APIDOC ## GET /google/v1/icons ### Description Retrieves the list of icons from Google Fonts. ### Method GET ### Endpoint /google/v1/icons ### Response #### Success Response (200) - **body** (JSON) - The list of icons. #### Response Example ```json { "icons": [] } ``` ``` -------------------------------- ### GET /google/v1/fonts Source: https://unifont.dev/docs/proxy Retrieves the list of fonts from Google Fonts. ```APIDOC ## GET /google/v1/fonts ### Description Retrieves the list of fonts from Google Fonts. ### Method GET ### Endpoint /google/v1/fonts ### Response #### Success Response (200) - **body** (JSON) - The list of fonts. #### Response Example ```json { "fonts": [] } ``` ``` -------------------------------- ### resolveFont() with explicit weight list Source: https://unifont.dev/docs/resolving Lists individual weights to get the ones in between when a variable range is not expanded. Use this when you need specific intermediate weights. ```ts await unifont.resolveFont('Poppins', { weights: ['500', '600', '700', '800', '900'] }) ``` -------------------------------- ### Create a unifont instance with providers Source: https://unifont.dev/docs/getting-started Create a unifont instance with an array of providers. Providers are tried in order, and the first one that knows the family wins. ```ts import { createUnifont, providers } from 'unifont' const unifont = await createUnifont([ providers.google(), providers.fontshare(), providers.fontsource(), ]) ``` -------------------------------- ### Basic npm provider usage Source: https://unifont.dev/docs/providers Creates an npm provider with default settings, resolving fonts from node_modules or a CDN. ```ts providers.npm() ``` -------------------------------- ### Configure unifont with unstorage filesystem cache Source: https://unifont.dev/docs/caching Configure unifont to use a filesystem-backed cache via unstorage's fs-lite driver. The storage option accepts anything with getItem and setItem, so any unstorage driver works. Entries expire after a week and are keyed by unifont version, so upgrading invalidates the cache. ```ts import { createUnifont, providers } from 'unifont' import { createStorage } from 'unstorage' import fsDriver from 'unstorage/drivers/fs-lite' const storage = createStorage({ driver: fsDriver({ base: 'node_modules/.cache/unifont' }), }) const unifont = await createUnifont([providers.google()], { storage }) ``` -------------------------------- ### GET /fontshare/v1/fonts Source: https://unifont.dev/docs/proxy Retrieves the list of fonts from Fontshare. ```APIDOC ## GET /fontshare/v1/fonts ### Description Retrieves the list of fonts from Fontshare. ### Method GET ### Endpoint /fontshare/v1/fonts ### Parameters #### Query Parameters - **offset** (number) - Optional - The offset for pagination. - **limit** (number) - Optional - The maximum number of results to return. ### Response #### Success Response (200) - **body** (JSON) - The list of fonts. #### Response Example ```json { "fonts": [] } ``` ``` -------------------------------- ### Asking only some providers with provider list Source: https://unifont.dev/docs/reference Shows how to restrict all three methods to a subset of providers by passing a provider name list as the last argument. The default is every provider the instance was built with. Here the instance is built with Google and Bunny providers, and the calls only query the 'bunny' provider. ```ts const unifont = await createUnifont([providers.google(), providers.bunny()]) await unifont.resolveFont('Poppins', {}, ['bunny']) await unifont.getFontProperties('Poppins', ['bunny']) await unifont.listFonts(['bunny']) ``` -------------------------------- ### Run Leturgerð CLI Source: https://unifont.dev/docs/layout-shift Command to run the Leturgerð CLI, which downloads font files and writes @font-face rules and fallbacks into the project. ```Bash npx @leturgero/cli@latest ``` -------------------------------- ### createUnifont() Source: https://unifont.dev/docs/reference Documentation for the createUnifont() function, including its signature, options, and error handling behavior. ```APIDOC ## createUnifont() ### Description Creates a Unifont instance with the given providers. Providers are tried in order, and the first one that knows a family answers. Providers start lazily on first request and may fetch a whole family index, so it is recommended to keep the instance rather than creating one per request. ### Signature ```ts function createUnifont( providers: T, options?: UnifontOptions, ): Promise> ``` ### Parameters - **providers** (Provider tuple) - Required - An array of providers to use, tried in order. - **options** (UnifontOptions) - Optional - Configuration options. ### Options | Option | Type | Default | Description | | --- | --- | --- | --- | | `storage` | `{ getItem, setItem }` | in memory | Storage for caching. | | `throwOnError` | `boolean` | `false` | If true, errors from providers are thrown instead of logged and skipped. | | `apiBase` | `string \| false` | hosted proxy in browser, otherwise unset | Base URL for API requests. | ### Returns - **Promise>** - A promise that resolves to a Unifont instance. ### Error Handling By default, a provider that fails to start or throws from any of its methods is logged and skipped, and the next provider is tried. If `throwOnError` is set, errors are thrown for `resolveFont()` and `getFontProperties()` only when no provider could serve the request; failures recovered by later providers are warnings. `listFonts()` merges every provider, so any failure there results in an incomplete list and is thrown. Multiple failures are raised as an `AggregateError`. ``` -------------------------------- ### Get font properties with getFontProperties Source: https://unifont.dev/docs/getting-started Get font properties for a family. Returns undefined if no provider recognizes the name. A missing field means the provider doesn't publish that information. Variable families report a range as one ' ' string. ```ts const properties = await unifont.getFontProperties('Newsreader') properties?.weights // ['200 800'], a variable range properties?.styles // ['normal', 'italic'] properties?.subsets // ['cyrillic', 'greek', 'latin', 'latin-ext', 'vietnamese'] properties?.axes // [{ tag: 'opsz', min: 6, max: 72, defaultValue: 14 }, …] properties?.provider // 'google' ``` -------------------------------- ### Use unifont with Nitro/Nuxt storage adapter Source: https://unifont.dev/docs/caching Create a unifont instance in Nitro or Nuxt using the existing storage system. The adapter wraps useStorage('unifont') with getItem and setItem, and the instance is cached so the provider's family index is fetched only once per process. ```ts // server/utils/unifont.ts import { createUnifont, providers } from 'unifont' let instance: ReturnType | undefined export function useUnifont() { const cache = useStorage('unifont') instance ??= createUnifont([providers.google()], { storage: { getItem: key => cache.getItem(key), setItem: (key, value) => cache.setItem(key, value), }, }) return instance } ``` -------------------------------- ### GET /fontsource/v1/variable/:id Source: https://unifont.dev/docs/proxy Retrieves a variable font from Fontsource. ```APIDOC ## GET /fontsource/v1/variable/:id ### Description Retrieves a variable font from Fontsource. ### Method GET ### Endpoint /fontsource/v1/variable/:id ### Parameters #### Path Parameters - **id** (string) - Required - The font identifier. ### Response #### Success Response (200) - **body** (JSON) - The variable font data. #### Response Example ```json { "id": "example", "family": "Example", "axes": {} } ``` ``` -------------------------------- ### Use a custom provider with createUnifont Source: https://unifont.dev/docs/custom-providers Uses the custom provider alongside a built-in provider in `createUnifont`. The provider is instantiated with its options, here reading the token from an environment variable. ```ts const unifont = await createUnifont([ foundry({ token: process.env.FOUNDRY_TOKEN }), providers.google(), ]) ``` -------------------------------- ### GET /fontsource/v1/fonts/:id Source: https://unifont.dev/docs/proxy Retrieves a specific font from Fontsource. ```APIDOC ## GET /fontsource/v1/fonts/:id ### Description Retrieves a specific font from Fontsource. ### Method GET ### Endpoint /fontsource/v1/fonts/:id ### Parameters #### Path Parameters - **id** (string) - Required - The font identifier. ### Response #### Success Response (200) - **body** (JSON) - The font data. #### Response Example ```json { "id": "example", "family": "Example" } ``` ``` -------------------------------- ### Create unifont with throwOnError Source: https://unifont.dev/docs/getting-started Create a unifont instance with throwOnError to stop on provider failures. Errors are only raised if no provider could serve the family; otherwise failures are warnings. Multiple failures result in an AggregateError. ```ts const unifont = await createUnifont([providers.google()], { throwOnError: true }) ``` -------------------------------- ### Configure Adobe provider with TYPEKIT_ID Source: https://unifont.dev/docs/providers Requires the TYPEKIT_ID environment variable and throws an error if missing. The id is required and can be a string or string array; read it from the environment. ```ts if (!process.env.TYPEKIT_ID) { throw new Error('TYPEKIT_ID is required to resolve Adobe fonts.') } providers.adobe({ id: process.env.TYPEKIT_ID }) ``` -------------------------------- ### Define provider family options and pass them at the call site Source: https://unifont.dev/docs/custom-providers Declare a family options type and it is inferred at the call site under the provider's name. The first block defines the provider with typed options; the second shows how a caller passes those options to unifont.resolveFont. ```ts export interface FoundryFamilyOptions { optical?: 'display' | 'text' } import type { ProviderResolveFontOptions } from 'unifont' export const foundry = defineFontProvider('foundry', async (options: FoundryOptions, ctx) => ({ async resolveFont(family, options: ProviderResolveFontOptions) { options.options?.optical // typed // … }, })) ``` ```ts await unifont.resolveFont('Foundry Sans', { options: { foundry: { optical: 'display' }, }, }) ``` -------------------------------- ### Get font properties to check available axes Source: https://unifont.dev/docs/resolving Use getFontProperties() to check which axes a family publishes before requesting them. The returned properties object includes an axes array with tag, min, max, and defaultValue. ```TypeScript const properties = await unifont.getFontProperties('Recursive') properties?.axes // [{ tag: 'CASL', min: 0, max: 1, defaultValue: 0 }, …] ``` -------------------------------- ### Define a custom provider with defineFontProvider Source: https://unifont.dev/docs/custom-providers Defines a custom font provider with `defineFontProvider`, specifying the provider name and typed options. The returned object must include `listFonts`, `getFontProperties`, and `resolveFont` methods. The function runs once when the instance is created. ```ts import { defineFontProvider } from 'unifont' export interface FoundryOptions { token: string } export const foundry = defineFontProvider('foundry', async (options: FoundryOptions, ctx) => { // Runs once, when the instance is created. return { listFonts() { /* … */ }, getFontProperties(family) { /* … */ }, resolveFont(family, options) { /* … */ }, } }) ``` -------------------------------- ### Local-only npm provider with custom file system access Source: https://unifont.dev/docs/providers Configures the npm provider to resolve fonts locally without CDN fallback, using custom readFile and exists functions to read from node_modules. Returns file:// URLs for copying or hashing. ```ts import { access, readFile } from 'node:fs/promises' providers.npm({ readFile: path => readFile(path, 'utf-8').catch(() => null), exists: path => access(path).then(() => true).catch(() => false), remote: false, }) ``` -------------------------------- ### getFontProperties() - Return font properties or undefined Source: https://unifont.dev/docs/custom-providers Optional method for a custom provider. Return undefined for a family you don't know, and unifont will move on to the next provider. ```ts getFontProperties(family) { const match = families.find(item => item.name === family) if (!match) { return undefined } return { weights: match.weights, styles: match.styles, subsets: match.subsets, formats: ['woff2'], } } ``` -------------------------------- ### Create Unifont in a browser with automatic proxy Source: https://unifont.dev/docs/browser Creates a Unifont instance in a browser or web container, automatically routing provider requests through the hosted proxy because provider APIs lack CORS headers. ```ts import { createUnifont, providers } from 'unifont' // In a browser or a StackBlitz web container, this goes via the proxy. const unifont = await createUnifont([providers.google()]) ``` -------------------------------- ### listFonts(providers?) Source: https://unifont.dev/docs/reference Returns a list of all family names that the specified providers can serve, or undefined if none of the providers can list fonts. ```APIDOC ## `listFonts()` ### Description Returns every family name that the providers will list, or `undefined` if none of them can. `npm` and `adobe` providers never list fonts. ### Signature ```ts listFonts(providers?: string[]): Promise ``` ### Parameters - **providers** (string[]) - Optional - List of providers to query. ### Return Value Promise that resolves to an array of family names, or `undefined` if no provider can list fonts. ``` -------------------------------- ### createUnifont() signature Source: https://unifont.dev/docs/reference Signature of the createUnifont function. It takes an array of providers and optional options, returning a promise of a Unifont instance. Providers are tried in order, and the first that knows a family answers. ```ts function createUnifont( providers: T, options?: UnifontOptions, ): Promise> ``` -------------------------------- ### resolveFont() - Required method for custom providers Source: https://unifont.dev/docs/custom-providers The only required method for every provider. Return undefined for families you don't know, otherwise return fonts and fallbacks. Key the cache on the options because the same family may resolve differently from one request to the next. ```ts import { hash } from 'ohash' async resolveFont(family, options) { const match = families.find(item => item.name === family) if (!match) { return } return { fonts: await ctx.storage.getItem(`foundry:${family}-${hash(options)}.json`, async () => { const css = await ctx.fetch(match.cssUrl).then(res => res.text()) return parseIntoFontFaceData(css) }), fallbacks: ['sans-serif'], } } ``` -------------------------------- ### Cache provider data with ctx.storage.getItem Source: https://unifont.dev/docs/custom-providers Uses `ctx.storage.getItem` to cache the result of a fetch. The function passed as the second argument runs once, then subsequent calls read from the configured storage. `ctx.fetch` retries failures and rewrites built-in provider URLs to `apiBase`, but custom endpoints are not rewritten. ```ts export const foundry = defineFontProvider('foundry', async (options: FoundryOptions, ctx) => { const families = await ctx.storage.getItem('foundry:index.json', () => ctx.fetch('https://api.foundry.example/families').then(res => res.json()), ) // … }) ``` -------------------------------- ### Limit a single unifont call to specific providers Source: https://unifont.dev/docs/providers Shows how to pass an array of provider names to resolveFont and getFontProperties to limit the call to those providers. ```ts const { fonts } = await unifont.resolveFont('Poppins', {}, ['bunny']) const properties = await unifont.getFontProperties('Poppins', ['bunny']) ``` -------------------------------- ### Resolving a specific font family with npm options Source: https://unifont.dev/docs/providers Shows how to pass family-specific npm options to unifont.resolveFont, specifying the package and file for the Roboto font. ```ts const { fonts } = await unifont.resolveFont('Roboto', { options: { npm: { package: '@fontsource/roboto', file: 'latin.css' }, }, }) ``` -------------------------------- ### Google Icons provider Source: https://unifont.dev/docs/providers Use `providers.googleicons()` to access Material Symbols as variable icon fonts. The full file is huge, so specifying glyphs is important. ```TypeScript providers.googleicons() ``` -------------------------------- ### getFontProperties(family, providers?) Source: https://unifont.dev/docs/reference Retrieves font properties for a given family from the first provider that knows it. ```APIDOC ## getFontProperties(family, providers?) ### Description Returns the font properties published by the first provider that knows the family, or `undefined` if none do. The result includes `axes`, `weights`, and `formats` as published by the provider. ### Method Function call ### Endpoint `getFontProperties(family: string, providers?: string[]): Promise<(FontProperties & { provider?: string }) | undefined>` ### Parameters - **family** (string) - Required - The font family name. - **providers** (string[]) - Optional - List of provider names to query. Defaults to all providers the instance was built with. ### Response Returns a Promise resolving to `FontProperties` with an additional `provider` field, or `undefined` if no provider knows the family. ### Response Example ```json { "provider": "google", "axes": [ { "tag": "wght", "min": 100, "max": 900, "defaultValue": 400 } ], "weights": ["400", "100 900"], "formats": ["woff2"] } ``` ``` -------------------------------- ### Resolve font with formats option Source: https://unifont.dev/docs/resolving Use the formats option to request specific font formats. Default is ['woff2']. Only request more formats if you know you need them. ```TypeScript await unifont.resolveFont('Poppins', { formats: ['woff2', 'woff'] }) ``` -------------------------------- ### Vite config with fontless plugin Source: https://unifont.dev/docs/layout-shift Adds the fontless plugin to a Vite config to automatically generate metric-matched fallbacks for fonts resolved via unifont. ```TypeScript // vite.config.ts import react from '@vitejs/plugin-react' import { fontless } from 'fontless' import { defineConfig } from 'vite' export default defineConfig({ plugins: [react(), fontless()], }) ``` -------------------------------- ### FontFaceData interface returned by resolveFont() Source: https://unifont.dev/docs/resolving Shows the shape of the resolved font data. A `src` entry with `name` is a local font; with `url` it's remote. `meta.subset` is the provider's own name for the range. `meta.init` carries a RequestInit for providers that need headers; pass it through when downloading the font. ```ts interface FontFaceData { src: Array<{ name: string } | { url: string, format?: string, tech?: string }> display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional' weight?: string | number | [number, number] stretch?: string style?: string unicodeRange?: string[] featureSettings?: string variationSettings?: string meta?: { priority?: number, subset?: string, init?: RequestInit } } ``` -------------------------------- ### Bunny provider Source: https://unifont.dev/docs/providers Use `providers.bunny()` to access the Google Fonts library mirrored on fonts.bunny.net without analytics. Family names match Google, so it can be swapped in where privacy is a concern. ```TypeScript providers.bunny() ``` -------------------------------- ### listFonts() - Return resolvable family names Source: https://unifont.dev/docs/custom-providers Optional method for a custom provider. Return the family names you can resolve, or undefined if listing doesn't make sense for your source. ```ts listFonts() { return families.map(family => family.name) } ``` -------------------------------- ### resolveFont() with variable weight range Source: https://unifont.dev/docs/resolving Shows discrete weights as strings and a variable range as a single string with a space. If no variable font covers the range, unifont picks a few weights: the ends plus whichever is nearest 400. If no published weight falls inside the range, it returns the nearest weight. ```ts await unifont.resolveFont('Poppins', { weights: ['300', '500 900'] }) ``` -------------------------------- ### defineFontProvider() Source: https://unifont.dev/docs/reference Function to define a custom font provider. It takes a name and a provider function that returns an object with resolveFont, getFontProperties, and listFonts methods. ```APIDOC ## defineFontProvider() ### Description Defines a custom font provider. The provider function receives options and a context, and returns an object with methods to resolve fonts, get font properties, and list fonts. ### Function Signature ```ts function defineFontProvider( name: Name, provider: (options: Options, ctx: ProviderContext) => Awaitable<{ resolveFont: (family: string, options: ProviderResolveFontOptions) => Awaitable getFontProperties?: (family: string) => Awaitable listFonts?: () => Awaitable } | undefined> ): (options?: Options) => Provider ``` ### Parameters - **name** (Name) - Required - The name of the provider. - **provider** (function) - Required - A function that receives options and a ProviderContext, and returns an object with the following methods: - **resolveFont** (function) - Required - Resolves a font family to a ResolveFontResult or undefined. - **getFontProperties** (function) - Optional - Gets font properties for a family. - **listFonts** (function) - Optional - Lists available font families. ### Returns A function that accepts optional options and returns a Provider instance. ``` -------------------------------- ### npm provider with custom resolve for non-standard layouts Source: https://unifont.dev/docs/providers Uses a custom resolve function to handle pnpm, monorepo hoisting, Yarn PnP, or bundler aliases where packages are not under /node_modules. ```ts import { fileURLToPath } from 'node:url' providers.npm({ readFile: path => readFile(path, 'utf-8').catch(() => null), resolve: id => fileURLToPath(import.meta.resolve(id)), }) ``` -------------------------------- ### resolveFont() with styles: ['normal'] Source: https://unifont.dev/docs/resolving Narrows the styles option to only normal. The default is ['normal', 'italic'], which doubles the number of files for a page that may never use italic. ```ts await unifont.resolveFont('Poppins', { styles: ['normal'] }) ``` -------------------------------- ### Fontsource provider Source: https://unifont.dev/docs/providers Use `providers.fontsource()` to access open fonts packaged for npm and served from jsDelivr. Useful for using the Google library without Google's servers or for pinning exact files via a lockfile. ```TypeScript providers.fontsource() ``` -------------------------------- ### Set a custom apiBase for the proxy Source: https://unifont.dev/docs/browser Configures a custom proxy endpoint via the apiBase option, overriding the default hosted proxy for provider API requests. ```ts const unifont = await createUnifont([providers.google()], { apiBase: 'https://fonts.example.com', }) ``` -------------------------------- ### defineFontProvider() function signature Source: https://unifont.dev/docs/reference Signature for defining a custom font provider. Only resolveFont() is required; getFontProperties() and listFonts() are optional. Returns a function that accepts provider options and returns a Provider instance. ```ts function defineFontProvider( name: Name, provider: (options: Options, ctx: ProviderContext) => Awaitable<{ resolveFont: (family: string, options: ProviderResolveFontOptions) => Awaitable getFontProperties?: (family: string) => Awaitable listFonts?: () => Awaitable } | undefined> ): (options?: Options) => Provider ``` -------------------------------- ### resolveFont Source: https://unifont.dev/docs/resolving Documentation for the resolveFont method, including per-family provider options and the FontFaceData return type. ```APIDOC ## resolveFont ### Description Resolves a font family with optional per-family provider options. Returns font face data for the resolved font. ### Method resolveFont ### Endpoint unifont.resolveFont(fontFamily, options) ### Parameters #### Path Parameters - **fontFamily** (string) - Required - The font family name to resolve. #### Request Body - **options** (object) - Optional - Options for resolution. - **options** (object) - Optional - Per-family provider options, grouped by provider name. - **google** (object) - Optional - Options for the Google provider. - **experimental** (object) - Optional - Experimental options. - **glyphs** (string[]) - Optional - Array of glyph strings. ### Request Example ```ts const { fonts } = await unifont.resolveFont('Poppins', { options: { google: { experimental: { glyphs: ['Hello', 'World'] }, }, }, }) ``` ### Response #### Success Response - **fonts** (FontFaceData[]) - Array of font face data. #### Response Example ```ts interface FontFaceData { src: Array<{ name: string } | { url: string, format?: string, tech?: string }> display?: 'auto' | 'block' | 'swap' | 'fallback' | 'optional' weight?: string | number | [number, number] stretch?: string style?: string unicodeRange?: string[] featureSettings?: string variationSettings?: string meta?: { priority?: number, subset?: string, init?: RequestInit } } ``` ``` -------------------------------- ### Generate fallback font face with unifont and fontaine Source: https://unifont.dev/docs/layout-shift Resolves a font family with unifont, reads its metrics, and generates a fallback @font-face rule with fontaine. The fallback is scaled to match the real font's metrics. ```TypeScript import { generateFontFace, readMetrics } from 'fontaine' import { createUnifont, providers } from 'unifont' const unifont = await createUnifont([providers.google()]) const { fonts, fallbacks } = await unifont.resolveFont('Poppins') const url = fonts .flatMap(font => font.src) .find(source => 'url' in source)?.url const metrics = url ? await readMetrics(url) : null const css = metrics ? generateFontFace(metrics, { name: 'Poppins fallback', font: fallbacks[0] ?? 'sans-serif' }) : '' ``` -------------------------------- ### Resolve font with subset option Source: https://unifont.dev/docs/resolving Use the subsets option to limit the font files to specific character subsets. Default is ['cyrillic-ext', 'cyrillic', 'greek-ext', 'greek', 'vietnamese', 'latin-ext', 'latin']. Providers that don't split by subset ignore this option. ```TypeScript await unifont.resolveFont('Poppins', { subsets: ['latin'] }) ``` -------------------------------- ### Add @nuxt/fonts to Nuxt Source: https://unifont.dev/docs/layout-shift Command to add the @nuxt/fonts module to a Nuxt project, which automatically generates metric-matched fallbacks. ```Bash npx nuxt add fonts ```