@unocss/preset-web-fonts 0.61.0 → 0.61.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,59 +1,6 @@
1
1
  import * as _unocss_core from '@unocss/core';
2
-
3
- type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
- interface WebFontMeta {
5
- name: string;
6
- weights?: (string | number)[];
7
- italic?: boolean;
8
- /**
9
- * Override the provider
10
- * @default <matches root config>
11
- */
12
- provider?: WebFontsProviders;
13
- }
14
- interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
15
- provider: Provider;
16
- }
17
- interface WebFontsOptions {
18
- /**
19
- * Provider service of the web fonts
20
- * @default 'google'
21
- */
22
- provider?: WebFontsProviders;
23
- /**
24
- * The fonts
25
- */
26
- fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
27
- /**
28
- * Extend fonts to the theme object
29
- * @default true
30
- */
31
- extendTheme?: boolean;
32
- /**
33
- * Key for the theme object
34
- *
35
- * @default 'fontFamily'
36
- */
37
- themeKey?: string;
38
- /**
39
- * Inline CSS @import()
40
- *
41
- * @default true
42
- */
43
- inlineImports?: boolean;
44
- /**
45
- * Custom fetch function
46
- *
47
- * @default undefined
48
- */
49
- customFetch?: (url: string) => Promise<any>;
50
- }
51
- interface Provider {
52
- name: WebFontsProviders;
53
- getPreflight?: (fonts: WebFontMeta[]) => string;
54
- getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
55
- getFontName?: (font: WebFontMeta) => string;
56
- }
2
+ import { W as WebFontMeta, a as WebFontsProviders, R as ResolvedWebFontMeta, P as Provider, b as WebFontsOptions } from './shared/preset-web-fonts.DSrOMtoz.mjs';
3
+ export { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.mjs';
57
4
 
58
5
  declare function normalizedFontMeta(meta: WebFontMeta | string, defaultProvider: WebFontsProviders): ResolvedWebFontMeta;
59
6
 
@@ -66,4 +13,4 @@ declare function createGoogleCompatibleProvider(name: WebFontsProviders, host: s
66
13
  */
67
14
  declare const presetWebFonts: _unocss_core.PresetFactory<any, WebFontsOptions>;
68
15
 
69
- export { type Provider, type ResolvedWebFontMeta, type WebFontMeta, type WebFontsOptions, type WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
16
+ export { Provider, ResolvedWebFontMeta, WebFontMeta, WebFontsOptions, WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
package/dist/index.d.ts CHANGED
@@ -1,59 +1,6 @@
1
1
  import * as _unocss_core from '@unocss/core';
2
-
3
- type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
- interface WebFontMeta {
5
- name: string;
6
- weights?: (string | number)[];
7
- italic?: boolean;
8
- /**
9
- * Override the provider
10
- * @default <matches root config>
11
- */
12
- provider?: WebFontsProviders;
13
- }
14
- interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
15
- provider: Provider;
16
- }
17
- interface WebFontsOptions {
18
- /**
19
- * Provider service of the web fonts
20
- * @default 'google'
21
- */
22
- provider?: WebFontsProviders;
23
- /**
24
- * The fonts
25
- */
26
- fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
27
- /**
28
- * Extend fonts to the theme object
29
- * @default true
30
- */
31
- extendTheme?: boolean;
32
- /**
33
- * Key for the theme object
34
- *
35
- * @default 'fontFamily'
36
- */
37
- themeKey?: string;
38
- /**
39
- * Inline CSS @import()
40
- *
41
- * @default true
42
- */
43
- inlineImports?: boolean;
44
- /**
45
- * Custom fetch function
46
- *
47
- * @default undefined
48
- */
49
- customFetch?: (url: string) => Promise<any>;
50
- }
51
- interface Provider {
52
- name: WebFontsProviders;
53
- getPreflight?: (fonts: WebFontMeta[]) => string;
54
- getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
55
- getFontName?: (font: WebFontMeta) => string;
56
- }
2
+ import { W as WebFontMeta, a as WebFontsProviders, R as ResolvedWebFontMeta, P as Provider, b as WebFontsOptions } from './shared/preset-web-fonts.DSrOMtoz.js';
3
+ export { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.js';
57
4
 
58
5
  declare function normalizedFontMeta(meta: WebFontMeta | string, defaultProvider: WebFontsProviders): ResolvedWebFontMeta;
59
6
 
@@ -66,4 +13,4 @@ declare function createGoogleCompatibleProvider(name: WebFontsProviders, host: s
66
13
  */
67
14
  declare const presetWebFonts: _unocss_core.PresetFactory<any, WebFontsOptions>;
68
15
 
69
- export { type Provider, type ResolvedWebFontMeta, type WebFontMeta, type WebFontsOptions, type WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
16
+ export { Provider, ResolvedWebFontMeta, WebFontMeta, WebFontsOptions, WebFontsProviders, createGoogleCompatibleProvider as createGoogleProvider, presetWebFonts as default, normalizedFontMeta };
package/dist/index.mjs CHANGED
@@ -108,18 +108,43 @@ function createWebFontPreset(fetcher) {
108
108
  extendTheme = true,
109
109
  inlineImports = true,
110
110
  themeKey = "fontFamily",
111
- customFetch = fetcher
111
+ customFetch = fetcher,
112
+ timeouts = {}
112
113
  } = options;
114
+ const processors = toArray(options.processors || []);
113
115
  const fontObject = Object.fromEntries(
114
116
  Object.entries(options.fonts || {}).map(([name, meta]) => [name, toArray(meta).map((m) => normalizedFontMeta(m, defaultProvider))])
115
117
  );
116
118
  const fonts = Object.values(fontObject).flatMap((i) => i);
117
119
  const importCache = {};
120
+ async function fetchWithTimeout(url) {
121
+ if (timeouts === false)
122
+ return customFetch(url);
123
+ const {
124
+ warning = 1e3,
125
+ failure = 2e3
126
+ } = timeouts;
127
+ let warned = false;
128
+ const timer = setTimeout(() => {
129
+ console.warn(`[unocss] Fetching web fonts: ${url}`);
130
+ warned = true;
131
+ }, warning);
132
+ return await Promise.race([
133
+ customFetch(url),
134
+ new Promise((_, reject) => {
135
+ setTimeout(() => reject(new Error(`[unocss] Fetch web fonts timeout.`)), failure);
136
+ })
137
+ ]).then((res) => {
138
+ if (warned)
139
+ console.info(`[unocss] Web fonts fetched.`);
140
+ return res;
141
+ }).finally(() => clearTimeout(timer));
142
+ }
118
143
  async function importUrl(url) {
119
144
  if (inlineImports) {
120
145
  if (!importCache[url]) {
121
- importCache[url] = customFetch(url).catch((e) => {
122
- console.error("Failed to fetch web fonts");
146
+ importCache[url] = fetchWithTimeout(url).catch((e) => {
147
+ console.error(`[unocss] Failed to fetch web fonts: ${url}`);
123
148
  console.error(e);
124
149
  if (typeof process !== "undefined" && process.env.CI)
125
150
  throw e;
@@ -130,23 +155,43 @@ function createWebFontPreset(fetcher) {
130
155
  return `@import url('${url}');`;
131
156
  }
132
157
  }
133
- const enabledProviders = new Set(fonts.map((i) => i.provider));
158
+ const enabledProviders = Array.from(new Set(fonts.map((i) => i.provider)));
159
+ async function getCSSDefault(fonts2, providers) {
160
+ const preflights = [];
161
+ for (const provider of providers) {
162
+ const fontsForProvider = fonts2.filter((i) => i.provider.name === provider.name);
163
+ if (provider.getImportUrl) {
164
+ const url = provider.getImportUrl(fontsForProvider);
165
+ if (url)
166
+ preflights.push(await importUrl(url));
167
+ }
168
+ preflights.push(provider.getPreflight?.(fontsForProvider));
169
+ }
170
+ const css = preflights.filter(Boolean).join("\n");
171
+ return css;
172
+ }
134
173
  const preset = {
135
174
  name: "@unocss/preset-web-fonts",
136
175
  preflights: [
137
176
  {
138
177
  async getCSS() {
139
- const preflights = [];
140
- for (const provider of enabledProviders) {
141
- const fontsForProvider = fonts.filter((i) => i.provider.name === provider.name);
142
- if (provider.getImportUrl) {
143
- const url = provider.getImportUrl(fontsForProvider);
144
- if (url)
145
- preflights.push(await importUrl(url));
178
+ let css;
179
+ for (const processor of processors) {
180
+ const result = await processor.getCSS?.(fonts, enabledProviders, getCSSDefault);
181
+ if (result) {
182
+ css = result;
183
+ break;
146
184
  }
147
- preflights.push(provider.getPreflight?.(fontsForProvider));
148
185
  }
149
- return preflights.filter(Boolean).join("\n");
186
+ if (!css) {
187
+ css = await getCSSDefault(
188
+ fonts,
189
+ enabledProviders
190
+ );
191
+ }
192
+ for (const processor of processors)
193
+ css = await processor.transformCSS?.(css) || css;
194
+ return css;
150
195
  },
151
196
  layer: inlineImports ? void 0 : LAYER_IMPORTS
152
197
  }
@@ -0,0 +1,32 @@
1
+ import { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.mjs';
2
+ import '@unocss/core';
3
+
4
+ interface LocalFontProcessorOptions {
5
+ /**
6
+ * Current working directory
7
+ *
8
+ * @default process.cwd()
9
+ */
10
+ cwd?: string;
11
+ /**
12
+ * Directory to cache the fonts
13
+ *
14
+ * @default 'node_modules/.cache/unocss/fonts'
15
+ */
16
+ cacheDir?: string;
17
+ /**
18
+ * Directory to save the fonts assets
19
+ *
20
+ * @default 'public/assets/fonts'
21
+ */
22
+ fontAssetsDir?: string;
23
+ /**
24
+ * Base URL to serve the fonts from the client
25
+ *
26
+ * @default '/assets/fonts'
27
+ */
28
+ fontServeBaseUrl?: string;
29
+ }
30
+ declare function createLocalFontProcessor(options?: LocalFontProcessorOptions): WebFontProcessor;
31
+
32
+ export { type LocalFontProcessorOptions, createLocalFontProcessor };
@@ -0,0 +1,32 @@
1
+ import { c as WebFontProcessor } from './shared/preset-web-fonts.DSrOMtoz.js';
2
+ import '@unocss/core';
3
+
4
+ interface LocalFontProcessorOptions {
5
+ /**
6
+ * Current working directory
7
+ *
8
+ * @default process.cwd()
9
+ */
10
+ cwd?: string;
11
+ /**
12
+ * Directory to cache the fonts
13
+ *
14
+ * @default 'node_modules/.cache/unocss/fonts'
15
+ */
16
+ cacheDir?: string;
17
+ /**
18
+ * Directory to save the fonts assets
19
+ *
20
+ * @default 'public/assets/fonts'
21
+ */
22
+ fontAssetsDir?: string;
23
+ /**
24
+ * Base URL to serve the fonts from the client
25
+ *
26
+ * @default '/assets/fonts'
27
+ */
28
+ fontServeBaseUrl?: string;
29
+ }
30
+ declare function createLocalFontProcessor(options?: LocalFontProcessorOptions): WebFontProcessor;
31
+
32
+ export { type LocalFontProcessorOptions, createLocalFontProcessor };
package/dist/local.mjs ADDED
@@ -0,0 +1,83 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import process from 'node:process';
5
+ import { resolve, join } from 'node:path';
6
+ import { Buffer } from 'node:buffer';
7
+ import { fetch } from 'ofetch';
8
+
9
+ function replaceAsync(string, searchValue, replacer) {
10
+ try {
11
+ if (typeof replacer === "function") {
12
+ const values = [];
13
+ String.prototype.replace.call(string, searchValue, (...args) => {
14
+ values.push(replacer(...args));
15
+ return "";
16
+ });
17
+ return Promise.all(values).then((resolvedValues) => {
18
+ return String.prototype.replace.call(string, searchValue, () => {
19
+ return resolvedValues.shift() || "";
20
+ });
21
+ });
22
+ } else {
23
+ return Promise.resolve(
24
+ String.prototype.replace.call(string, searchValue, replacer)
25
+ );
26
+ }
27
+ } catch (error) {
28
+ return Promise.reject(error);
29
+ }
30
+ }
31
+
32
+ const fontUrlRegex = /[-\w@:%+.~#?&/=]+\.(?:woff2?|eot|ttf|otf|svg)/gi;
33
+ function createLocalFontProcessor(options) {
34
+ const cwd = options?.cwd || process.cwd();
35
+ const cacheDir = resolve(cwd, options?.cacheDir || "node_modules/.cache/unocss/fonts");
36
+ const fontAssetsDir = resolve(cwd, options?.fontAssetsDir || "public/assets/fonts");
37
+ const fontServeBaseUrl = options?.fontServeBaseUrl || "/assets/fonts";
38
+ async function _downloadFont(url, assetPath) {
39
+ const response = await fetch(url).then((r) => r.arrayBuffer());
40
+ await fsp.mkdir(fontAssetsDir, { recursive: true });
41
+ await fsp.writeFile(assetPath, Buffer.from(response));
42
+ }
43
+ const cache = /* @__PURE__ */ new Map();
44
+ function downloadFont(url, assetPath) {
45
+ if (!cache.has(url))
46
+ cache.set(url, _downloadFont(url, assetPath));
47
+ return cache.get(url);
48
+ }
49
+ return {
50
+ async getCSS(fonts, providers, getCSSDefault) {
51
+ const hash = getHash(JSON.stringify(fonts));
52
+ const cachePath = join(cacheDir, `${hash}.css`);
53
+ if (fs.existsSync(cachePath)) {
54
+ return fsp.readFile(cachePath, "utf-8");
55
+ }
56
+ const css = await getCSSDefault(fonts, providers);
57
+ await fsp.mkdir(cacheDir, { recursive: true });
58
+ await fsp.writeFile(cachePath, css, "utf-8");
59
+ return css;
60
+ },
61
+ async transformCSS(css) {
62
+ return await replaceAsync(css, fontUrlRegex, async (url) => {
63
+ const hash = getHash(url);
64
+ const ext = url.split(".").pop();
65
+ let name = "";
66
+ const match1 = url.match(/\/s\/([^/]+)\//);
67
+ if (match1)
68
+ name = match1[1].replace(/\W/g, " ").trim().replace(/\s+/, "-").toLowerCase();
69
+ const filename = `${[name, hash].filter(Boolean).join("-")}.${ext}`;
70
+ const assetPath = join(fontAssetsDir, filename);
71
+ if (!fs.existsSync(assetPath)) {
72
+ await downloadFont(url, assetPath);
73
+ }
74
+ return `${fontServeBaseUrl}/${filename}`;
75
+ });
76
+ }
77
+ };
78
+ }
79
+ function getHash(input, length = 8) {
80
+ return createHash("sha256").update(input).digest("hex").slice(0, length);
81
+ }
82
+
83
+ export { createLocalFontProcessor };
@@ -0,0 +1,83 @@
1
+ import { Awaitable, Arrayable } from '@unocss/core';
2
+
3
+ type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
+ interface WebFontMeta {
5
+ name: string;
6
+ weights?: (string | number)[];
7
+ italic?: boolean;
8
+ /**
9
+ * Override the provider
10
+ * @default <matches root config>
11
+ */
12
+ provider?: WebFontsProviders;
13
+ }
14
+ interface WebFontProcessor {
15
+ getCSS?: (fonts: ResolvedWebFontMeta[], providers: Provider[], getCSSDefault: (fonts: ResolvedWebFontMeta[], providers: Provider[]) => Awaitable<string>) => Awaitable<string | undefined>;
16
+ transformCSS?: (css: string) => Promise<string | undefined>;
17
+ }
18
+ interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
19
+ provider: Provider;
20
+ }
21
+ interface WebFontsOptions {
22
+ /**
23
+ * Provider service of the web fonts
24
+ * @default 'google'
25
+ */
26
+ provider?: WebFontsProviders;
27
+ /**
28
+ * The fonts
29
+ */
30
+ fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
31
+ /**
32
+ * Extend fonts to the theme object
33
+ * @default true
34
+ */
35
+ extendTheme?: boolean;
36
+ /**
37
+ * Key for the theme object
38
+ *
39
+ * @default 'fontFamily'
40
+ */
41
+ themeKey?: string;
42
+ /**
43
+ * Inline CSS @import()
44
+ *
45
+ * @default true
46
+ */
47
+ inlineImports?: boolean;
48
+ /**
49
+ * Custom fetch function
50
+ *
51
+ * @default undefined
52
+ */
53
+ customFetch?: (url: string) => Promise<any>;
54
+ /**
55
+ * Custom processor for the font CSS
56
+ */
57
+ processors?: Arrayable<WebFontProcessor>;
58
+ /**
59
+ * Timeouts for fetching web fonts
60
+ */
61
+ timeouts?: false | {
62
+ /**
63
+ * Timeout for printing warning message
64
+ *
65
+ * @default 500
66
+ */
67
+ warning?: number;
68
+ /**
69
+ * Timeout for failing the fetch
70
+ *
71
+ * @default 2000
72
+ */
73
+ failure?: number;
74
+ };
75
+ }
76
+ interface Provider {
77
+ name: WebFontsProviders;
78
+ getPreflight?: (fonts: WebFontMeta[]) => string;
79
+ getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
80
+ getFontName?: (font: WebFontMeta) => string;
81
+ }
82
+
83
+ export type { Provider as P, ResolvedWebFontMeta as R, WebFontMeta as W, WebFontsProviders as a, WebFontsOptions as b, WebFontProcessor as c };
@@ -0,0 +1,83 @@
1
+ import { Awaitable, Arrayable } from '@unocss/core';
2
+
3
+ type WebFontsProviders = 'google' | 'bunny' | 'fontshare' | 'none' | Provider;
4
+ interface WebFontMeta {
5
+ name: string;
6
+ weights?: (string | number)[];
7
+ italic?: boolean;
8
+ /**
9
+ * Override the provider
10
+ * @default <matches root config>
11
+ */
12
+ provider?: WebFontsProviders;
13
+ }
14
+ interface WebFontProcessor {
15
+ getCSS?: (fonts: ResolvedWebFontMeta[], providers: Provider[], getCSSDefault: (fonts: ResolvedWebFontMeta[], providers: Provider[]) => Awaitable<string>) => Awaitable<string | undefined>;
16
+ transformCSS?: (css: string) => Promise<string | undefined>;
17
+ }
18
+ interface ResolvedWebFontMeta extends Omit<WebFontMeta, 'provider'> {
19
+ provider: Provider;
20
+ }
21
+ interface WebFontsOptions {
22
+ /**
23
+ * Provider service of the web fonts
24
+ * @default 'google'
25
+ */
26
+ provider?: WebFontsProviders;
27
+ /**
28
+ * The fonts
29
+ */
30
+ fonts?: Record<string, WebFontMeta | string | (WebFontMeta | string)[]>;
31
+ /**
32
+ * Extend fonts to the theme object
33
+ * @default true
34
+ */
35
+ extendTheme?: boolean;
36
+ /**
37
+ * Key for the theme object
38
+ *
39
+ * @default 'fontFamily'
40
+ */
41
+ themeKey?: string;
42
+ /**
43
+ * Inline CSS @import()
44
+ *
45
+ * @default true
46
+ */
47
+ inlineImports?: boolean;
48
+ /**
49
+ * Custom fetch function
50
+ *
51
+ * @default undefined
52
+ */
53
+ customFetch?: (url: string) => Promise<any>;
54
+ /**
55
+ * Custom processor for the font CSS
56
+ */
57
+ processors?: Arrayable<WebFontProcessor>;
58
+ /**
59
+ * Timeouts for fetching web fonts
60
+ */
61
+ timeouts?: false | {
62
+ /**
63
+ * Timeout for printing warning message
64
+ *
65
+ * @default 500
66
+ */
67
+ warning?: number;
68
+ /**
69
+ * Timeout for failing the fetch
70
+ *
71
+ * @default 2000
72
+ */
73
+ failure?: number;
74
+ };
75
+ }
76
+ interface Provider {
77
+ name: WebFontsProviders;
78
+ getPreflight?: (fonts: WebFontMeta[]) => string;
79
+ getImportUrl?: (fonts: WebFontMeta[]) => string | undefined;
80
+ getFontName?: (font: WebFontMeta) => string;
81
+ }
82
+
83
+ export type { Provider as P, ResolvedWebFontMeta as R, WebFontMeta as W, WebFontsProviders as a, WebFontsOptions as b, WebFontProcessor as c };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unocss/preset-web-fonts",
3
3
  "type": "module",
4
- "version": "0.61.0",
4
+ "version": "0.61.3",
5
5
  "description": "Web Fonts support for Uno CSS",
6
6
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
7
7
  "license": "MIT",
@@ -27,6 +27,10 @@
27
27
  ".": {
28
28
  "types": "./dist/index.d.mts",
29
29
  "default": "./dist/index.mjs"
30
+ },
31
+ "./local": {
32
+ "types": "./dist/local.d.mts",
33
+ "default": "./dist/local.mjs"
30
34
  }
31
35
  },
32
36
  "main": "dist/index.mjs",
@@ -38,7 +42,7 @@
38
42
  ],
39
43
  "dependencies": {
40
44
  "ofetch": "^1.3.4",
41
- "@unocss/core": "0.61.0"
45
+ "@unocss/core": "0.61.3"
42
46
  },
43
47
  "scripts": {
44
48
  "build": "unbuild",