@vuepress/plugin-replace-assets 2.0.0-rc.131 → 2.0.0-rc.134

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.
@@ -1,6 +1,5 @@
1
1
  import { VitePlugin, WebpackPluginInstance } from "unplugin";
2
2
  import { Plugin } from "vuepress/core";
3
-
4
3
  //#region src/node/types.d.ts
5
4
  /**
6
5
  * Assets Replacement Target Path
@@ -134,17 +133,17 @@ type ReplaceAssetsPluginOptions = ReplaceAssetsOptions | Replacement | Replaceme
134
133
  * plugins: [replaceAssetsPlugin('https://cnd.example.com')],
135
134
  * })
136
135
  */
137
- declare const replaceAssetsPlugin: (options?: ReplaceAssetsPluginOptions) => Plugin;
136
+ export declare const replaceAssetsPlugin: (options?: ReplaceAssetsPluginOptions) => Plugin;
138
137
  //#endregion
139
138
  //#region src/node/normalizeRules.d.ts
140
- declare const createFindPattern: (dir: string, extensions: string[]) => RegExp;
139
+ export declare const createFindPattern: (dir: string, extensions: string[]) => RegExp;
141
140
  /**
142
141
  * Normalize replacement rules
143
142
  *
144
143
  * @param options - The plugin options to normalize
145
144
  * @returns Normalized replacement rules
146
145
  */
147
- declare const normalizeRules: (options?: ReplaceAssetsPluginOptions) => ReplacementRule[];
146
+ export declare const normalizeRules: (options?: ReplaceAssetsPluginOptions) => ReplacementRule[];
148
147
  //#endregion
149
148
  //#region src/node/transformAssets.d.ts
150
149
  /**
@@ -156,7 +155,7 @@ declare const normalizeRules: (options?: ReplaceAssetsPluginOptions) => Replacem
156
155
  * @returns True if the URL matches the find pattern, false otherwise / 如果 URL
157
156
  * 匹配查找模式则返回 true,否则返回 false
158
157
  */
159
- declare const isMatchUrl: (find: RegExp | string, url: string) => boolean;
158
+ export declare const isMatchUrl: (find: RegExp | string, url: string) => boolean;
160
159
  /**
161
160
  * Replace asset with rules
162
161
  *
@@ -172,12 +171,19 @@ declare const isMatchUrl: (find: RegExp | string, url: string) => boolean;
172
171
  * @returns The replaced asset URL if matched, otherwise return undefined /
173
172
  * 如果匹配则返回替换后的资源 URL,否则返回 undefined
174
173
  */
175
- declare const replacementAssetWithRules: (rules: ReplacementRule[], url: string) => string | void;
176
- declare const transformAssets: (code: string, pattern: RegExp, rules: ReplacementRule[]) => string;
174
+ export declare const replacementAssetWithRules: (rules: ReplacementRule[], url: string) => string | void;
175
+ export declare const transformAssets: (code: string, pattern: RegExp, { rules, base }: {
176
+ rules: ReplacementRule[];
177
+ base: string;
178
+ }) => string;
177
179
  //#endregion
178
180
  //#region src/node/unplugin.d.ts
179
- declare const createVitePluginReplaceAssets: () => (options: ReplacementRule[]) => VitePlugin | VitePlugin[];
180
- declare const createWebpackPluginReplaceAssets: () => (options: ReplacementRule[]) => WebpackPluginInstance;
181
+ interface ReplaceAssetsFactoryOptions {
182
+ rules: ReplacementRule[];
183
+ base: string;
184
+ }
185
+ export declare const createVitePluginReplaceAssets: () => (options: ReplaceAssetsFactoryOptions) => VitePlugin | VitePlugin[];
186
+ export declare const createWebpackPluginReplaceAssets: () => (options: ReplaceAssetsFactoryOptions) => WebpackPluginInstance;
181
187
  //#endregion
182
- export { type ReplaceAssetsOptions, type ReplaceAssetsPluginOptions, type Replacement, type ReplacementRule, createFindPattern, createVitePluginReplaceAssets, createWebpackPluginReplaceAssets, isMatchUrl, normalizeRules, replaceAssetsPlugin, replacementAssetWithRules, transformAssets };
188
+ export type { ReplaceAssetsOptions, ReplaceAssetsPluginOptions, Replacement, ReplacementRule };
183
189
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- import{addViteConfig as e,configWebpack as t,getBundlerName as n,isArray as r,isFunction as i,removeEndingSlash as a,removeLeadingSlash as o}from"@vuepress/helper";import{createVitePlugin as s,createWebpackPlugin as c}from"unplugin";import l from"magic-string";const u=[`apng`,`bmp`,`png`,`jpe?g`,`jfif`,`pjpeg`,`pjp`,`gif`,`svg`,`ico`,`webp`,`avif`,`cur`,`jxl`],d=[`mp4`,`webm`,`ogg`,`mp3`,`wav`,`flac`,`aac`,`opus`,`mov`,`m4a`,`vtt`,`pdf`],f=(e,t)=>RegExp(`^/${e}/.*\\.(?:${t.join(`|`)})(\\?.*)?$`,`u`),p=e=>{let t=[];return e?((typeof e==`string`||i(e))&&(e={all:e}),r(e)?(t.push(...e),t):`find`in e?(e.find&&e.replacement&&t.push(e),t):(e.rules&&t.push(...r(e.rules)?e.rules:[e.rules]),(e.image||e.all)&&t.push({find:f(`images`,u),replacement:e.image||e.all}),(e.media||e.all)&&t.push({find:f(`medias`,d),replacement:e.media||e.all}),t)):[]},m=e=>{let t=`(${e}.*?)`;return new RegExp([`(?:"${t}")`,`(?:'${t}')`,`(?:\\(${t}\\))`,`(?:\\('${t}'\\))`,`(?:\\("${t}"\\))`,`(?:\\\\"${t}\\\\")`].join(`|`),`gu`)},h=(e,t)=>e?t?`${a(t)}/${o(e)}`:e:``,g=new Map,_=(e,t)=>{if(typeof e==`string`){if(e.startsWith(`^`)||e.endsWith(`$`)){let n=g.get(e);return n||(n=new RegExp(e,`u`),g.set(e,n)),n.test(t)}return t.endsWith(e)||t.startsWith(e)}return e.test(t)},v=new Map,y=(e,t)=>{if(v.has(t))return v.get(t);for(let{find:n,replacement:r}of e)if(n&&_(n,t)){let e=typeof r==`function`?h(r(t)):h(t,r);if(e)return v.set(t,e),e}},b=String.raw`\"`,x=(e,t,n)=>{let r=new l(e),i,a=!1;for(;i=t.exec(e);){let e=i[6]||i[5]||i[4]||i[3]||i[2]||i[1],[t,o]=i[0].startsWith(`(`)?[`("`,`")`]:i[0].startsWith(b)?[b,b]:[`"`,`"`],s=i.index,c=s+i[0].length,l=y(n,e);l&&(a=!0,r.update(s,c,`${t}${l}${o}`))}return a?r.toString():e},S=(e,t)=>{let n=m(`/[^/]`);return{name:`vuepress:replace-assets`,enforce:t?.framework===`vite`?`pre`:void 0,transform:{filter:{id:{exclude:[/\.json(?:$|\?)/u,/\.html?$/u]}},handler(t){return x(t,n,e)}}}},C=()=>s(S),w=()=>c(S),T=r=>{let i={name:`@vuepress/plugin-replace-assets`},a=p(r);return a.length===0?i:{...i,extendsBundlerOptions(r,i){let o=n(i);o===`vite`&&e(r,i,{plugins:[C()(a)]}),o===`webpack`&&t(r,i,e=>{e.plugins??=[];let t=w();e.plugins.push(t(a))})}}};export{f as createFindPattern,C as createVitePluginReplaceAssets,w as createWebpackPluginReplaceAssets,_ as isMatchUrl,p as normalizeRules,T as replaceAssetsPlugin,y as replacementAssetWithRules,x as transformAssets};
1
+ import{addViteConfig as e,configWebpack as t,getBundlerName as n,isArray as r,isFunction as i,removeEndingSlash as a,removeLeadingSlash as o}from"@vuepress/helper";import{createVitePlugin as s,createWebpackPlugin as c}from"unplugin";import{MagicString as l}from"magic-string";const u=[`apng`,`bmp`,`png`,`jpe?g`,`jfif`,`pjpeg`,`pjp`,`gif`,`svg`,`ico`,`webp`,`avif`,`cur`,`jxl`],d=[`mp4`,`webm`,`ogg`,`mp3`,`wav`,`flac`,`aac`,`opus`,`mov`,`m4a`,`vtt`,`pdf`],f=(e,t)=>RegExp(`^/${e}/.*\\.(?:${t.join(`|`)})(\\?.*)?$`,`u`),p=e=>{let t=[];return e?((typeof e==`string`||i(e))&&(e={all:e}),r(e)?(t.push(...e),t):`find`in e?(e.find&&e.replacement&&t.push(e),t):(e.rules&&t.push(...r(e.rules)?e.rules:[e.rules]),(e.image||e.all)&&t.push({find:f(`images`,u),replacement:e.image||e.all}),(e.media||e.all)&&t.push({find:f(`medias`,d),replacement:e.media||e.all}),t)):[]},m=e=>{let t=`(${e}.*?)`;return new RegExp([`(?:"${t}")`,`(?:'${t}')`,`(?:\\(${t}\\))`,`(?:\\('${t}'\\))`,`(?:\\("${t}"\\))`,`(?:\\\\"${t}\\\\")`].join(`|`),`gu`)},h=(e,t)=>e?t?`${a(t)}/${o(e)}`:e:``,g=new Map,_=(e,t)=>{if(typeof e==`string`){if(e.startsWith(`^`)||e.endsWith(`$`)){let n=g.get(e);return n||(n=new RegExp(e,`u`),g.set(e,n)),n.test(t)}return t.endsWith(e)||t.startsWith(e)}return e.test(t)},v=new Map,y=(e,t)=>{if(v.has(t))return v.get(t);for(let{find:n,replacement:r}of e)if(n&&_(n,t)){let e=typeof r==`function`?h(r(t)):h(t,r);if(e)return v.set(t,e),e}},b=String.raw`\"`,x=(e,t,{rules:n,base:r})=>{let i=new l(e),a,o=!1,s=RegExp(`^${r}`,`u`);for(;a=t.exec(e);){let e=a[6]||a[5]||a[4]||a[3]||a[2]||a[1],[t,r]=a[0].startsWith(`(`)?[`("`,`")`]:a[0].startsWith(b)?[b,b]:[`"`,`"`],c=a.index,l=c+a[0].length,u=y(n,e.replace(s,`/`));u&&(o=!0,i.update(c,l,`${t}${u}${r}`))}return o?i.toString():e},S=(e,t)=>{let n=m(`/[^/]`);return{name:`vuepress:replace-assets`,enforce:t?.framework===`vite`?`pre`:void 0,transform:{filter:{id:{exclude:[/\.json(?:$|\?)/u,/\.html?$/u]}},handler(t){return x(t,n,e)}}}},C=()=>s(S),w=()=>c(S),T=r=>{let i={name:`@vuepress/plugin-replace-assets`},a=p(r);return a.length===0?i:{...i,extendsBundlerOptions(r,i){let o=n(i);if(o===`vite`){let t=C();e(r,i,{plugins:[t({rules:a,base:i.options.base})]})}o===`webpack`&&t(r,i,e=>{e.plugins??=[];let t=w();e.plugins.push(t({rules:a,base:i.options.base}))})}}};export{f as createFindPattern,C as createVitePluginReplaceAssets,w as createWebpackPluginReplaceAssets,_ as isMatchUrl,p as normalizeRules,T as replaceAssetsPlugin,y as replacementAssetWithRules,x as transformAssets};
2
2
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/node/constants.ts","../../src/node/normalizeRules.ts","../../src/node/utils.ts","../../src/node/transformAssets.ts","../../src/node/unplugin.ts","../../src/node/replaceAssetsPlugin.ts"],"sourcesContent":["export const PLUGIN_NAME = '@vuepress/plugin-replace-assets'\n\n/** Images extensions */\nexport const KNOWN_IMAGE_EXTENSIONS: string[] = [\n 'apng',\n 'bmp',\n 'png',\n 'jpe?g',\n 'jfif',\n 'pjpeg',\n 'pjp',\n 'gif',\n 'svg',\n 'ico',\n 'webp',\n 'avif',\n 'cur',\n 'jxl',\n]\n\n/** Media extensions */\nexport const KNOWN_MEDIA_EXTENSIONS: string[] = [\n 'mp4',\n 'webm',\n 'ogg',\n 'mp3',\n 'wav',\n 'flac',\n 'aac',\n 'opus',\n 'mov',\n 'm4a',\n 'vtt',\n\n 'pdf',\n]\n","import { isArray, isFunction } from '@vuepress/helper'\n\nimport { KNOWN_IMAGE_EXTENSIONS, KNOWN_MEDIA_EXTENSIONS } from './constants.js'\nimport type { ReplaceAssetsPluginOptions, ReplacementRule } from './types.js'\n\nexport const createFindPattern = (dir: string, extensions: string[]): RegExp =>\n new RegExp(`^/${dir}/.*\\\\.(?:${extensions.join('|')})(\\\\?.*)?$`, 'u')\n\n/**\n * Normalize replacement rules\n *\n * @param options - The plugin options to normalize\n * @returns Normalized replacement rules\n */\nexport const normalizeRules = (\n options?: ReplaceAssetsPluginOptions,\n): ReplacementRule[] => {\n const normalized: ReplacementRule[] = []\n\n if (!options) return []\n\n if (typeof options === 'string' || isFunction(options)) {\n // oxlint-disable-next-line no-param-reassign\n options = {\n all: options,\n }\n }\n\n if (isArray(options)) {\n normalized.push(...options)\n return normalized\n }\n\n if ('find' in options) {\n if (options.find && options.replacement) normalized.push(options)\n return normalized\n }\n\n if (options.rules) {\n normalized.push(\n ...(isArray(options.rules) ? options.rules : [options.rules]),\n )\n }\n\n if (options.image || options.all) {\n normalized.push({\n find: createFindPattern('images', KNOWN_IMAGE_EXTENSIONS),\n replacement: options.image || options.all!,\n })\n }\n\n if (options.media || options.all) {\n normalized.push({\n find: createFindPattern('medias', KNOWN_MEDIA_EXTENSIONS),\n replacement: options.media || options.all!,\n })\n }\n\n return normalized\n}\n","import { removeEndingSlash, removeLeadingSlash } from '@vuepress/helper'\n\nexport const createAssetPattern = (prefix: string): RegExp => {\n // oxlint-disable-next-line id-length\n const s = `(${prefix}.*?)`\n return new RegExp(\n [\n `(?:\"${s}\")`, // \"prefix\"\n `(?:'${s}')`, // 'prefix'\n `(?:\\\\(${s}\\\\))`, // (prefix)\n `(?:\\\\('${s}'\\\\))`, // ('prefix')\n `(?:\\\\(\"${s}\"\\\\))`, // (\"prefix\")\n `(?:\\\\\\\\\"${s}\\\\\\\\\")`, // \\\"prefix\\\"\n ].join('|'),\n 'gu',\n )\n}\n\n/**\n * Normalize url\n *\n * @example\n * normalizeUrl('/bar', '/foo/') // -> /foo/bar\n *\n * @param url - The url to normalize\n * @param base - The base url to prepend to the url\n * @returns Normalized url\n */\nexport const normalizeUrl = (url: string, base?: string): string => {\n if (!url) return ''\n\n if (base) return `${removeEndingSlash(base)}/${removeLeadingSlash(url)}`\n\n return url\n}\n","import MagicString from 'magic-string'\n\nimport type { ReplacementRule } from './types.js'\nimport { normalizeUrl } from './utils.js'\n\nconst regexpCache = new Map<string, RegExp>()\n\n/**\n * Check if url matches find\n *\n * @param find - The find pattern, can be a string or a RegExp /\n * 查找模式,可以是字符串或正则表达式\n * @param url - The URL to check / 要检查的 URL\n * @returns True if the URL matches the find pattern, false otherwise / 如果 URL\n * 匹配查找模式则返回 true,否则返回 false\n */\nexport const isMatchUrl = (find: RegExp | string, url: string): boolean => {\n if (typeof find === 'string') {\n // like regexp string, start with `^` or end with `$`\n if (find.startsWith('^') || find.endsWith('$')) {\n let re = regexpCache.get(find)\n if (!re) {\n re = new RegExp(find, 'u')\n regexpCache.set(find, re)\n }\n return re.test(url)\n }\n\n return url.endsWith(find) || url.startsWith(find)\n }\n\n return find.test(url)\n}\n\nconst cache = new Map<string, string>()\n\n/**\n * Replace asset with rules\n *\n * @example\n * replacementAssetWithRules(\n * [{ find: '/foo/', replacement: 'https://example.com' }],\n * '/foo/a.jpg',\n * )\n * // -> 'https://example.com/foo/a.jpg'\n *\n * @param rules - Replacement rules / 替换规则\n * @param url - The original asset URL / 原始资源 URL\n * @returns The replaced asset URL if matched, otherwise return undefined /\n * 如果匹配则返回替换后的资源 URL,否则返回 undefined\n */\nexport const replacementAssetWithRules = (\n rules: ReplacementRule[],\n url: string,\n): string | void => {\n if (cache.has(url)) return cache.get(url)\n\n for (const { find, replacement } of rules) {\n if (find && isMatchUrl(find, url)) {\n const replaced =\n typeof replacement === 'function'\n ? normalizeUrl(replacement(url))\n : normalizeUrl(url, replacement)\n\n /* istanbul ignore if -- @preserve */\n if (replaced) {\n cache.set(url, replaced)\n return replaced\n }\n }\n }\n}\n\nconst ESCAPED_DOUBLE_QUOTE = String.raw`\\\"`\n\nexport const transformAssets = (\n code: string,\n pattern: RegExp,\n rules: ReplacementRule[],\n): string => {\n const str = new MagicString(code)\n let matched: RegExpExecArray | null\n let hasMatched = false\n\n while ((matched = pattern.exec(code))) {\n const assetUrl =\n matched[6] ||\n matched[5] ||\n matched[4] ||\n matched[3] ||\n matched[2] ||\n matched[1]\n const [left, right] = matched[0].startsWith('(')\n ? ['(\"', '\")']\n : matched[0].startsWith(ESCAPED_DOUBLE_QUOTE)\n ? [ESCAPED_DOUBLE_QUOTE, ESCAPED_DOUBLE_QUOTE]\n : ['\"', '\"']\n\n const start = matched.index\n const end = start + matched[0].length\n const resolved = replacementAssetWithRules(rules, assetUrl)\n if (resolved) {\n hasMatched = true\n str.update(start, end, `${left}${resolved}${right}`)\n }\n }\n\n if (!hasMatched) return code\n\n return str.toString()\n}\n","import type {\n UnpluginFactory,\n VitePlugin,\n WebpackPluginInstance,\n} from 'unplugin'\nimport { createVitePlugin, createWebpackPlugin } from 'unplugin'\n\nimport { transformAssets } from './transformAssets.js'\nimport type { ReplacementRule } from './types.js'\nimport { createAssetPattern } from './utils.js'\n\nconst replaceAssetsFactory: UnpluginFactory<ReplacementRule[]> = (\n rules,\n meta,\n) => {\n const pattern = createAssetPattern('/[^/]')\n return {\n name: 'vuepress:replace-assets',\n enforce: meta?.framework === 'vite' ? 'pre' : undefined,\n transform: {\n filter: { id: { exclude: [/\\.json(?:$|\\?)/u, /\\.html?$/u] } },\n handler(code) {\n return transformAssets(code, pattern, rules)\n },\n },\n }\n}\n\nexport const createVitePluginReplaceAssets: () => (\n options: ReplacementRule[],\n) => VitePlugin | VitePlugin[] = () => createVitePlugin(replaceAssetsFactory)\n\nexport const createWebpackPluginReplaceAssets: () => (\n options: ReplacementRule[],\n) => WebpackPluginInstance = () => createWebpackPlugin(replaceAssetsFactory)\n","import { addViteConfig, configWebpack, getBundlerName } from '@vuepress/helper'\nimport type { Plugin } from 'vuepress/core'\n\nimport { PLUGIN_NAME } from './constants.js'\nimport { normalizeRules } from './normalizeRules.js'\nimport type { ReplaceAssetsPluginOptions } from './types.js'\nimport {\n createVitePluginReplaceAssets,\n createWebpackPluginReplaceAssets,\n} from './unplugin.js'\n\n/**\n * Plugin for replacing assets path\n *\n * 资源路径替换插件\n *\n * @example\n * export default defineUserConfig({\n * plugins: [replaceAssetsPlugin('https://cnd.example.com')],\n * })\n */\nexport const replaceAssetsPlugin = (\n options?: ReplaceAssetsPluginOptions,\n): Plugin => {\n const EMPTY_PLUGIN = { name: PLUGIN_NAME }\n\n const rules = normalizeRules(options)\n\n if (rules.length === 0) return EMPTY_PLUGIN\n\n return {\n ...EMPTY_PLUGIN,\n\n extendsBundlerOptions(bundlerOptions, app) {\n const bundle = getBundlerName(app)\n\n if (bundle === 'vite') {\n const replaceAssets = createVitePluginReplaceAssets()\n addViteConfig(bundlerOptions, app, {\n plugins: [replaceAssets(rules)],\n })\n }\n\n if (bundle === 'webpack') {\n configWebpack(bundlerOptions, app, (config) => {\n config.plugins ??= []\n const replaceAssets = createWebpackPluginReplaceAssets()\n config.plugins.push(replaceAssets(rules))\n })\n }\n },\n }\n}\n"],"mappings":"qQAAA,MAGa,EAAmC,CAC9C,OACA,MACA,MACA,QACA,OACA,QACA,MACA,MACA,MACA,MACA,OACA,OACA,MACA,KACF,EAGa,EAAmC,CAC9C,MACA,OACA,MACA,MACA,MACA,OACA,MACA,OACA,MACA,MAC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AM,YAAc,OAAS,MAAQ,IAAA,GAC9C,UAAW,CACT,OAAQ,CAAE,GAAI,CAAE,QAAS,CAAC,kBAAmB,WAAW,CAAE,CAAE,EAC5D,QAAQ,EAAM,CACZ,OAAO,EAAgB,EAAM,EAAS,CAAK,CAC7C,CACF,CACF,CACF,EAEa,MAE0B,EAAiB,CAAoB,EAE/D,MAEsB,EAAoB,CAAoB,ECb9D,EACX,GACW,CACX,IAAM,EAAe,CAAE,KAAM,iCAAY,EAEnC,EAAQ,EAAe,CAAO,EAIpC,OAFI,EAAM,SAAW,EAAU,EAExB,CACL,GAAG,EAEH,sBAAsB,EAAgB,EAAK,CACzC,IAAM,EAAS,EAAe,CAAG,EAE7B,IAAW,QAEb,EAAc,EAAgB,EAAK,CACjC,QAAS,CAFW,EAEE,CAAC,CAAC,CAAK,CAAC,CAChC,CAAC,EAGC,IAAW,WACb,EAAc,EAAgB,EAAM,GAAW,CAC7C,EAAO,UAAY,CAAC,EACpB,IAAM,EAAgB,EAAiC,EACvD,EAAO,QAAQ,KAAK,EAAc,CAAK,CAAC,CAC1C,CAAC,CAEL,CACF,CACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/node/constants.ts","../../src/node/normalizeRules.ts","../../src/node/utils.ts","../../src/node/transformAssets.ts","../../src/node/unplugin.ts","../../src/node/replaceAssetsPlugin.ts"],"sourcesContent":["export const PLUGIN_NAME = '@vuepress/plugin-replace-assets'\n\n/** Images extensions */\nexport const KNOWN_IMAGE_EXTENSIONS: string[] = [\n 'apng',\n 'bmp',\n 'png',\n 'jpe?g',\n 'jfif',\n 'pjpeg',\n 'pjp',\n 'gif',\n 'svg',\n 'ico',\n 'webp',\n 'avif',\n 'cur',\n 'jxl',\n]\n\n/** Media extensions */\nexport const KNOWN_MEDIA_EXTENSIONS: string[] = [\n 'mp4',\n 'webm',\n 'ogg',\n 'mp3',\n 'wav',\n 'flac',\n 'aac',\n 'opus',\n 'mov',\n 'm4a',\n 'vtt',\n\n 'pdf',\n]\n","import { isArray, isFunction } from '@vuepress/helper'\n\nimport { KNOWN_IMAGE_EXTENSIONS, KNOWN_MEDIA_EXTENSIONS } from './constants.js'\nimport type { ReplaceAssetsPluginOptions, ReplacementRule } from './types.js'\n\nexport const createFindPattern = (dir: string, extensions: string[]): RegExp =>\n new RegExp(`^/${dir}/.*\\\\.(?:${extensions.join('|')})(\\\\?.*)?$`, 'u')\n\n/**\n * Normalize replacement rules\n *\n * @param options - The plugin options to normalize\n * @returns Normalized replacement rules\n */\nexport const normalizeRules = (\n options?: ReplaceAssetsPluginOptions,\n): ReplacementRule[] => {\n const normalized: ReplacementRule[] = []\n\n if (!options) return []\n\n if (typeof options === 'string' || isFunction(options)) {\n // oxlint-disable-next-line no-param-reassign\n options = {\n all: options,\n }\n }\n\n if (isArray(options)) {\n normalized.push(...options)\n return normalized\n }\n\n if ('find' in options) {\n if (options.find && options.replacement) normalized.push(options)\n return normalized\n }\n\n if (options.rules) {\n normalized.push(\n ...(isArray(options.rules) ? options.rules : [options.rules]),\n )\n }\n\n if (options.image || options.all) {\n normalized.push({\n find: createFindPattern('images', KNOWN_IMAGE_EXTENSIONS),\n replacement: options.image || options.all!,\n })\n }\n\n if (options.media || options.all) {\n normalized.push({\n find: createFindPattern('medias', KNOWN_MEDIA_EXTENSIONS),\n replacement: options.media || options.all!,\n })\n }\n\n return normalized\n}\n","import { removeEndingSlash, removeLeadingSlash } from '@vuepress/helper'\n\nexport const createAssetPattern = (prefix: string): RegExp => {\n // oxlint-disable-next-line id-length\n const s = `(${prefix}.*?)`\n return new RegExp(\n [\n `(?:\"${s}\")`, // \"prefix\"\n `(?:'${s}')`, // 'prefix'\n `(?:\\\\(${s}\\\\))`, // (prefix)\n `(?:\\\\('${s}'\\\\))`, // ('prefix')\n `(?:\\\\(\"${s}\"\\\\))`, // (\"prefix\")\n `(?:\\\\\\\\\"${s}\\\\\\\\\")`, // \\\"prefix\\\"\n ].join('|'),\n 'gu',\n )\n}\n\n/**\n * Normalize url\n *\n * @example\n * normalizeUrl('/bar', '/foo/') // -> /foo/bar\n *\n * @param url - The url to normalize\n * @param base - The base url to prepend to the url\n * @returns Normalized url\n */\nexport const normalizeUrl = (url: string, base?: string): string => {\n if (!url) return ''\n\n if (base) return `${removeEndingSlash(base)}/${removeLeadingSlash(url)}`\n\n return url\n}\n","import { MagicString } from 'magic-string'\n\nimport type { ReplacementRule } from './types.js'\nimport { normalizeUrl } from './utils.js'\n\nconst regexpCache = new Map<string, RegExp>()\n\n/**\n * Check if url matches find\n *\n * @param find - The find pattern, can be a string or a RegExp /\n * 查找模式,可以是字符串或正则表达式\n * @param url - The URL to check / 要检查的 URL\n * @returns True if the URL matches the find pattern, false otherwise / 如果 URL\n * 匹配查找模式则返回 true,否则返回 false\n */\nexport const isMatchUrl = (find: RegExp | string, url: string): boolean => {\n if (typeof find === 'string') {\n // like regexp string, start with `^` or end with `$`\n if (find.startsWith('^') || find.endsWith('$')) {\n let re = regexpCache.get(find)\n if (!re) {\n re = new RegExp(find, 'u')\n regexpCache.set(find, re)\n }\n return re.test(url)\n }\n\n return url.endsWith(find) || url.startsWith(find)\n }\n\n return find.test(url)\n}\n\nconst cache = new Map<string, string>()\n\n/**\n * Replace asset with rules\n *\n * @example\n * replacementAssetWithRules(\n * [{ find: '/foo/', replacement: 'https://example.com' }],\n * '/foo/a.jpg',\n * )\n * // -> 'https://example.com/foo/a.jpg'\n *\n * @param rules - Replacement rules / 替换规则\n * @param url - The original asset URL / 原始资源 URL\n * @returns The replaced asset URL if matched, otherwise return undefined /\n * 如果匹配则返回替换后的资源 URL,否则返回 undefined\n */\nexport const replacementAssetWithRules = (\n rules: ReplacementRule[],\n url: string,\n): string | void => {\n if (cache.has(url)) return cache.get(url)\n\n for (const { find, replacement } of rules) {\n if (find && isMatchUrl(find, url)) {\n const replaced =\n typeof replacement === 'function'\n ? normalizeUrl(replacement(url))\n : normalizeUrl(url, replacement)\n\n /* istanbul ignore if -- @preserve */\n if (replaced) {\n cache.set(url, replaced)\n return replaced\n }\n }\n }\n}\n\nconst ESCAPED_DOUBLE_QUOTE = String.raw`\\\"`\n\nexport const transformAssets = (\n code: string,\n pattern: RegExp,\n { rules, base }: { rules: ReplacementRule[]; base: string },\n): string => {\n const str = new MagicString(code)\n let matched: RegExpExecArray | null\n let hasMatched = false\n const basePattern = new RegExp(`^${base}`, 'u')\n\n while ((matched = pattern.exec(code))) {\n const assetUrl =\n matched[6] ||\n matched[5] ||\n matched[4] ||\n matched[3] ||\n matched[2] ||\n matched[1]\n const [left, right] = matched[0].startsWith('(')\n ? ['(\"', '\")']\n : matched[0].startsWith(ESCAPED_DOUBLE_QUOTE)\n ? [ESCAPED_DOUBLE_QUOTE, ESCAPED_DOUBLE_QUOTE]\n : ['\"', '\"']\n\n const start = matched.index\n const end = start + matched[0].length\n const resolved = replacementAssetWithRules(\n rules,\n assetUrl.replace(basePattern, '/'),\n )\n if (resolved) {\n hasMatched = true\n str.update(start, end, `${left}${resolved}${right}`)\n }\n }\n\n if (!hasMatched) return code\n\n return str.toString()\n}\n","import type {\n UnpluginFactory,\n VitePlugin,\n WebpackPluginInstance,\n} from 'unplugin'\nimport { createVitePlugin, createWebpackPlugin } from 'unplugin'\n\nimport { transformAssets } from './transformAssets.js'\nimport type { ReplacementRule } from './types.js'\nimport { createAssetPattern } from './utils.js'\n\ninterface ReplaceAssetsFactoryOptions {\n rules: ReplacementRule[]\n base: string\n}\n\nconst replaceAssetsFactory: UnpluginFactory<ReplaceAssetsFactoryOptions> = (\n options,\n meta,\n) => {\n const pattern = createAssetPattern('/[^/]')\n return {\n name: 'vuepress:replace-assets',\n enforce: meta?.framework === 'vite' ? 'pre' : undefined,\n transform: {\n filter: { id: { exclude: [/\\.json(?:$|\\?)/u, /\\.html?$/u] } },\n handler(code) {\n return transformAssets(code, pattern, options)\n },\n },\n }\n}\n\nexport const createVitePluginReplaceAssets: () => (\n options: ReplaceAssetsFactoryOptions,\n) => VitePlugin | VitePlugin[] = () => createVitePlugin(replaceAssetsFactory)\n\nexport const createWebpackPluginReplaceAssets: () => (\n options: ReplaceAssetsFactoryOptions,\n) => WebpackPluginInstance = () => createWebpackPlugin(replaceAssetsFactory)\n","import { addViteConfig, configWebpack, getBundlerName } from '@vuepress/helper'\nimport type { Plugin } from 'vuepress/core'\n\nimport { PLUGIN_NAME } from './constants.js'\nimport { normalizeRules } from './normalizeRules.js'\nimport type { ReplaceAssetsPluginOptions } from './types.js'\nimport {\n createVitePluginReplaceAssets,\n createWebpackPluginReplaceAssets,\n} from './unplugin.js'\n\n/**\n * Plugin for replacing assets path\n *\n * 资源路径替换插件\n *\n * @example\n * export default defineUserConfig({\n * plugins: [replaceAssetsPlugin('https://cnd.example.com')],\n * })\n */\nexport const replaceAssetsPlugin = (\n options?: ReplaceAssetsPluginOptions,\n): Plugin => {\n const EMPTY_PLUGIN = { name: PLUGIN_NAME }\n\n const rules = normalizeRules(options)\n\n if (rules.length === 0) return EMPTY_PLUGIN\n\n return {\n ...EMPTY_PLUGIN,\n\n extendsBundlerOptions(bundlerOptions, app) {\n const bundle = getBundlerName(app)\n\n if (bundle === 'vite') {\n const replaceAssets = createVitePluginReplaceAssets()\n addViteConfig(bundlerOptions, app, {\n plugins: [replaceAssets({ rules, base: app.options.base })],\n })\n }\n\n if (bundle === 'webpack') {\n configWebpack(bundlerOptions, app, (config) => {\n config.plugins ??= []\n const replaceAssets = createWebpackPluginReplaceAssets()\n config.plugins.push(replaceAssets({ rules, base: app.options.base }))\n })\n }\n },\n }\n}\n"],"mappings":"oRAAA,MAGa,EAAmC,CAC9C,OACA,MACA,MACA,QACA,OACA,QACA,MACA,MACA,MACA,MACA,OACA,OACA,MACA,KACF,EAGa,EAAmC,CAC9C,MACA,OACA,MACA,MACA,MACA,OACA,MACA,OACA,MACA,MACA,MAEA,KACF,EC9Ba,GAAqB,EAAa,IACzC,OAAO,KAAK,EAAI,WAAW,EAAW,KAAK,GAAG,EAAE,YAAa,GAAG,EAQzD,EACX,GACsB,CACtB,IA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GAAI,CAAE,QAAS,CAAC,kBAAmB,WAAW,CAAE,CAAE,EAC5D,QAAQ,EAAM,CACZ,OAAO,EAAgB,EAAM,EAAS,CAAO,CAC/C,CACF,CACF,CACF,EAEa,MAE0B,EAAiB,CAAoB,EAE/D,MAEsB,EAAoB,CAAoB,EClB9D,EACX,GACW,CACX,IAAM,EAAe,CAAE,KAAM,iCAAY,EAEnC,EAAQ,EAAe,CAAO,EAIpC,OAFI,EAAM,SAAW,EAAU,EAExB,CACL,GAAG,EAEH,sBAAsB,EAAgB,EAAK,CACzC,IAAM,EAAS,EAAe,CAAG,EAEjC,GAAI,IAAW,OAAQ,CACrB,IAAM,EAAgB,EAA8B,EACpD,EAAc,EAAgB,EAAK,CACjC,QAAS,CAAC,EAAc,CAAE,QAAO,KAAM,EAAI,QAAQ,IAAK,CAAC,CAAC,CAC5D,CAAC,CACH,CAEI,IAAW,WACb,EAAc,EAAgB,EAAM,GAAW,CAC7C,EAAO,UAAY,CAAC,EACpB,IAAM,EAAgB,EAAiC,EACvD,EAAO,QAAQ,KAAK,EAAc,CAAE,QAAO,KAAM,EAAI,QAAQ,IAAK,CAAC,CAAC,CACtE,CAAC,CAEL,CACF,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vuepress/plugin-replace-assets",
3
- "version": "2.0.0-rc.131",
3
+ "version": "2.0.0-rc.134",
4
4
  "description": "VuePress plugin - replace assets",
5
5
  "keywords": [
6
6
  "plugin",
@@ -41,15 +41,15 @@
41
41
  "access": "public"
42
42
  },
43
43
  "dependencies": {
44
- "@vuepress/helper": "2.0.0-rc.131",
45
- "magic-string": "^0.30.21",
44
+ "@vuepress/helper": "2.0.0-rc.134",
45
+ "magic-string": "^1.2.3",
46
46
  "unplugin": "^3.3.0"
47
47
  },
48
48
  "devDependencies": {
49
- "webpack": "^5.108.3"
49
+ "webpack": "^5.110.3"
50
50
  },
51
51
  "peerDependencies": {
52
- "vuepress": "2.0.0-rc.30"
52
+ "vuepress": "2.0.0-rc.31"
53
53
  },
54
- "gitHead": "57a09d0808e424fe729d29ef8352d8cff9f30b16"
54
+ "gitHead": "938b80193c26fb617270f6d86729e52ee298da03"
55
55
  }