vite-add-cdn-script 0.0.7 → 0.0.8

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.js CHANGED
@@ -1,22 +1,22 @@
1
1
  var D = Object.defineProperty;
2
2
  var F = (n, t, e) => t in n ? D(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
- var y = (n, t, e) => (F(n, typeof t != "symbol" ? t + "" : t, e), e);
4
- import U from "node:path";
5
- import w from "node:fs";
3
+ var S = (n, t, e) => (F(n, typeof t != "symbol" ? t + "" : t, e), e);
4
+ import O from "node:path";
5
+ import y from "node:fs";
6
6
  import b from "node:https";
7
7
  class E {
8
8
  constructor() {
9
- y(this, "cdnCache", {});
10
- y(this, "cdnCachePath", "");
11
- this.cdnCachePath = U.resolve(process.cwd(), "./.cdn-cache.json");
9
+ S(this, "cdnCache", {});
10
+ S(this, "cdnCachePath", "");
11
+ this.cdnCachePath = O.resolve(process.cwd(), "./.cdn-cache.json");
12
12
  }
13
13
  // 初始化cdn缓存
14
14
  async init() {
15
15
  try {
16
- const t = await w.readFileSync(this.cdnCachePath, "utf-8");
16
+ const t = await y.readFileSync(this.cdnCachePath, "utf-8");
17
17
  this.cdnCache = JSON.parse(t);
18
18
  } catch {
19
- console.log("cdn缓存文件不存在,创建缓存文件"), this.cdnCache = {}, await w.writeFileSync(this.cdnCachePath, "", "utf-8");
19
+ console.log("cdn缓存文件不存在,创建缓存文件"), this.cdnCache = {}, await y.writeFileSync(this.cdnCachePath, "", "utf-8");
20
20
  }
21
21
  }
22
22
  /**
@@ -43,48 +43,48 @@ class E {
43
43
  * 更新cdn缓存
44
44
  */
45
45
  async save() {
46
- await w.writeFileSync(this.cdnCachePath, JSON.stringify(this.cdnCache), "utf-8");
46
+ await y.writeFileSync(this.cdnCachePath, JSON.stringify(this.cdnCache), "utf-8");
47
47
  }
48
48
  }
49
- let $;
50
- const L = async () => ($ || ($ = new E(), await $.init()), $), f = {
49
+ let C;
50
+ const L = async () => (C || (C = new E(), await C.init()), C), $ = {
51
51
  //get请求封装
52
52
  get: (n, t, e) => new Promise((r, s) => {
53
53
  try {
54
- b.get(n, (i) => {
54
+ b.get(n, (c) => {
55
55
  let o = "";
56
- i.on("data", (c) => {
57
- o += c;
58
- }), i.on("end", () => {
56
+ c.on("data", (i) => {
57
+ o += i;
58
+ }), c.on("end", () => {
59
59
  t == null || t(o), r(o);
60
60
  });
61
61
  });
62
- } catch (i) {
63
- e == null || e(i), s(i);
62
+ } catch (c) {
63
+ e == null || e(c), s(c);
64
64
  }
65
65
  })
66
66
  }, N = async (n) => {
67
67
  const t = /^(https:\/\/.*\d+\.\d+\.\d+\/).+?\.js$/;
68
68
  if (t.test(n)) {
69
69
  const e = n.replace(t, (r, s) => `${s}package.json`);
70
- return JSON.parse(await f.get(e));
70
+ return JSON.parse(await $.get(e));
71
71
  } else
72
72
  throw new Error(`${n} 不是正确的url`);
73
73
  }, I = (n, t) => {
74
74
  var e, r;
75
75
  return ((e = n.dependencies) == null ? void 0 : e[t]) || ((r = n.devDependencies) == null ? void 0 : r[t]);
76
- }, k = (n) => n.reduce((t, e) => (e.type === "file" ? t.push({ name: e.path }) : e.files && t.push(...k(e.files)), t), []), x = {
76
+ }, J = (n) => n.reduce((t, e) => (e.type === "file" ? t.push({ name: e.path }) : e.files && t.push(...J(e.files)), t), []), k = {
77
77
  jsdelivr: {
78
78
  getFileList: (n, t) => new Promise((e, r) => {
79
- f.get(
79
+ $.get(
80
80
  `https://data.jsdelivr.com/v1/stats/packages/npm/${n}@${t}/files`,
81
81
  (s) => {
82
- const i = JSON.parse(s);
83
- if (i.length === 0) {
82
+ const c = JSON.parse(s);
83
+ if (c.length === 0) {
84
84
  r(new Error(`${n}@${t} not found`));
85
85
  return;
86
86
  }
87
- e({ fileList: i });
87
+ e({ fileList: c });
88
88
  },
89
89
  (s) => {
90
90
  r(s);
@@ -96,11 +96,11 @@ const L = async () => ($ || ($ = new E(), await $.init()), $), f = {
96
96
  },
97
97
  unpkg: {
98
98
  getFileList: (n, t) => new Promise((e, r) => {
99
- f.get(
99
+ $.get(
100
100
  `https://unpkg.com/${n}@${t}/?meta`,
101
101
  (s) => {
102
- const i = JSON.parse(s);
103
- e({ fileList: k(i.files || []) });
102
+ const c = JSON.parse(s);
103
+ e({ fileList: J(c.files || []) });
104
104
  },
105
105
  (s) => {
106
106
  r(s);
@@ -111,15 +111,15 @@ const L = async () => ($ || ($ = new E(), await $.init()), $), f = {
111
111
  },
112
112
  bootcdn: {
113
113
  getFileList: (n, t) => new Promise((e, r) => {
114
- f.get(
114
+ $.get(
115
115
  `https://api.bootcdn.cn/libraries/${n}`,
116
116
  (s) => {
117
- const i = JSON.parse(s);
118
- if (i.length === 0) {
117
+ const c = JSON.parse(s);
118
+ if (c.length === 0) {
119
119
  r(new Error(`${n} not found in bootcdn`));
120
120
  return;
121
121
  }
122
- const o = i[0], a = o.assets.find((d) => d.version === t);
122
+ const o = c[0], a = o.assets.find((d) => d.version === t);
123
123
  if (!a) {
124
124
  r(new Error(`${n}@${t} not found in ${o.name}`));
125
125
  return;
@@ -138,16 +138,16 @@ const L = async () => ($ || ($ = new E(), await $.init()), $), f = {
138
138
  },
139
139
  cdnjs: {
140
140
  getFileList: (n, t) => new Promise((e, r) => {
141
- f.get(
141
+ $.get(
142
142
  `https://api.cdnjs.com/libraries/${n}/${t}`,
143
143
  (s) => {
144
- const i = JSON.parse(s);
145
- if (i.error) {
144
+ const c = JSON.parse(s);
145
+ if (c.error) {
146
146
  r(new Error(`cdnjs: ${n}@${t} not found`));
147
147
  return;
148
148
  }
149
149
  e({
150
- fileList: i.rawFiles.map((o) => ({
150
+ fileList: c.rawFiles.map((o) => ({
151
151
  name: "/" + o
152
152
  }))
153
153
  });
@@ -164,14 +164,14 @@ const L = async () => ($ || ($ = new E(), await $.init()), $), f = {
164
164
  const r = (o = t.match(/\d+(.\d+)?(.\d+)?/)) == null ? void 0 : o[0];
165
165
  if (!r)
166
166
  throw new Error(`${n} version ${t} is not valid`);
167
- const s = await x[e].getFileList(n, r).catch((c) => {
168
- throw c;
169
- }), i = A(s, n);
170
- if (!i)
167
+ const s = await k[e].getFileList(n, r).catch((i) => {
168
+ throw i;
169
+ }), c = A(s, n);
170
+ if (!c)
171
171
  throw new Error(`在 ${e} 中找不到 ${n}@${r} 文件,请检查包名或版本号`);
172
- return x[e].getUrl(n, r, i);
172
+ return k[e].getUrl(n, r, c);
173
173
  }, A = ({ fileList: n }, t) => {
174
- var i, o;
174
+ var c, o;
175
175
  let e = [
176
176
  `umd/${t}.production.min.js`,
177
177
  /umd\/.+?\.production\.min\.js$/,
@@ -189,10 +189,10 @@ const L = async () => ($ || ($ = new E(), await $.init()), $), f = {
189
189
  /\.min\.js$/,
190
190
  /\.js$/
191
191
  ];
192
- const r = ["runtime", "compiler", ".esm", ".cjs", "development"].filter((c) => !t.includes(c));
192
+ const r = ["runtime", "compiler", ".esm", ".cjs", "development"].filter((i) => !t.includes(i));
193
193
  let s = "";
194
- for (let c of e)
195
- if (c instanceof RegExp ? s = ((i = n.find((a) => c.test(a.name) && !r.some((l) => a.name.includes(l)))) == null ? void 0 : i.name) || "" : s = ((o = n.find((a) => a.name.includes(c) && !r.some((l) => a.name.includes(l)))) == null ? void 0 : o.name) || "", s)
194
+ for (let i of e)
195
+ if (i instanceof RegExp ? s = ((c = n.find((a) => i.test(a.name) && !r.some((l) => a.name.includes(l)))) == null ? void 0 : c.name) || "" : s = ((o = n.find((a) => a.name.includes(i) && !r.some((l) => a.name.includes(l)))) == null ? void 0 : o.name) || "", s)
196
196
  break;
197
197
  return s;
198
198
  };
@@ -202,11 +202,11 @@ function M(n, t) {
202
202
  e.push("0");
203
203
  for (; r.length < s; )
204
204
  r.push("0");
205
- for (let i = 0; i < s; i++) {
206
- const o = parseInt(e[i], 10), c = parseInt(r[i], 10);
207
- if (o > c)
205
+ for (let c = 0; c < s; c++) {
206
+ const o = parseInt(e[c], 10), i = parseInt(r[c], 10);
207
+ if (o > i)
208
208
  return 1;
209
- if (o < c)
209
+ if (o < i)
210
210
  return -1;
211
211
  }
212
212
  return 0;
@@ -216,40 +216,41 @@ function V(n, t) {
216
216
  Object.prototype.hasOwnProperty.call(t, e) && (n[e] ? M(n[e], t[e]) === -1 && (n[e] = t[e]) : n[e] = t[e]);
217
217
  return n;
218
218
  }
219
- async function S({ external: n, packageData: t, customScript: e, defaultCdns: r }) {
220
- let s = [], i = !1;
219
+ async function v({ external: n, packageData: t, customScript: e, defaultCdns: r }) {
220
+ let s = [], c = !1;
221
221
  const o = await L();
222
222
  return await Promise.all(
223
- n.map(async (c) => {
224
- const a = I(t, c);
225
- if (e[c])
223
+ n.map(async (i) => {
224
+ const a = I(t, i);
225
+ if (e[i])
226
226
  return {
227
227
  urls: [],
228
- key: c
228
+ key: i
229
229
  };
230
- if (!a) {
231
- s.push(c);
232
- return;
233
- }
234
- const l = o.getCdnCache(c, a);
230
+ if (!a)
231
+ return s.push(i), {
232
+ urls: [],
233
+ key: i
234
+ };
235
+ const l = o.getCdnCache(i, a);
235
236
  if (l)
236
237
  return {
237
238
  urls: l,
238
- key: c
239
+ key: i
239
240
  };
240
241
  {
241
- i = !0;
242
+ c = !0, console.log(`从网络获取${i}${a}的cdn地址`);
242
243
  const d = {
243
244
  urls: await Promise.all(
244
- r.map(async (h) => await R(c, a, h))
245
+ r.map(async (h) => await R(i, a, h))
245
246
  ),
246
- key: c
247
+ key: i
247
248
  };
248
- return o.setCdnCache(c, a, d.urls), d;
249
+ return o.setCdnCache(i, a, d.urls), d;
249
250
  }
250
251
  })
251
- ).then((c) => (i && o.save(), {
252
- urls: c,
252
+ ).then((i) => (c && o.save(), {
253
+ urls: i,
253
254
  noVersionPackages: s
254
255
  }));
255
256
  }
@@ -260,54 +261,60 @@ function q(n) {
260
261
  name: "vite-add-cdn-script",
261
262
  enforce: "pre",
262
263
  apply: "build",
263
- config(i) {
264
- s = i;
264
+ config(c) {
265
+ s = c;
265
266
  },
266
- async transformIndexHtml(i) {
267
+ async transformIndexHtml(c) {
267
268
  if (!r || r.length === 0)
268
269
  throw new Error("defaultCdns不能为空");
269
- const o = U.resolve(process.cwd(), "package.json");
270
+ const o = O.resolve(process.cwd(), "package.json");
270
271
  try {
271
- const c = w.readFileSync(o, "utf-8"), a = JSON.parse(c), l = s.build.rollupOptions.external, d = {};
272
+ const i = y.readFileSync(o, "utf-8"), a = JSON.parse(i), l = s.build.rollupOptions.external, d = {};
272
273
  let h = "";
273
- const { urls: C, noVersionPackages: P } = await S({
274
+ const { urls: P, noVersionPackages: U } = await v({
274
275
  external: l,
275
276
  packageData: a,
276
277
  customScript: t,
277
278
  defaultCdns: r
278
279
  });
279
- if (P.length > 0) {
280
- const p = { dependencies: {} };
280
+ if (U.length > 0) {
281
+ const f = { dependencies: {} };
281
282
  await Promise.all(
282
- C.map(async (g) => {
283
- if (!g)
283
+ P.map(async (p) => {
284
+ if (!p)
284
285
  return;
285
- const { key: v, urls: O } = g, j = t[v] || O[0];
286
- if (!j)
286
+ const { key: j, urls: x } = p, m = t[j] || x[0];
287
+ if (!m)
287
288
  return;
288
- const J = await N(j);
289
- V(p.dependencies, J.dependencies);
289
+ const g = await N(m);
290
+ V(f.dependencies, g.dependencies);
290
291
  })
291
292
  );
292
- const { urls: m, noVersionPackages: u } = await S({
293
- external: P,
294
- packageData: p,
293
+ const { urls: w, noVersionPackages: u } = await v({
294
+ external: U,
295
+ packageData: f,
295
296
  customScript: t,
296
297
  defaultCdns: r
297
298
  });
298
- if (C.push(...m), u.length > 0)
299
+ if (w.map((p) => {
300
+ var m;
301
+ if (!p)
302
+ return;
303
+ const { urls: j, key: x } = p;
304
+ (m = P.find((g) => (g == null ? void 0 : g.key) === x)) == null || m.urls.push(...j);
305
+ }), u.length > 0)
299
306
  throw console.error(`找不到${u.join(",")}的版本`), new Error(`找不到${u.join(",")}的版本`);
300
307
  }
301
- return C.forEach((p) => {
302
- if (!p)
308
+ return P.forEach((f) => {
309
+ if (!f)
303
310
  return;
304
- const { urls: m, key: u } = p;
311
+ const { urls: w, key: u } = f;
305
312
  if (t[u])
306
313
  h += t[u];
307
314
  else {
308
- d[u] = m;
309
- const g = m[0];
310
- h += `<script src="${g}" type="text/javascript" crossorigin="anonymous" onerror="errorCDN(this)" data-cur="0" data-key="${u}"><\/script>
315
+ d[u] = w;
316
+ const p = w[0];
317
+ h += `<script src="${p}" type="text/javascript" crossorigin="anonymous" onerror="errorCDN(this)" data-cur="0" data-key="${u}"><\/script>
311
318
  `;
312
319
  }
313
320
  }), h = `<script>
@@ -332,9 +339,9 @@ function q(n) {
332
339
  document.head.appendChild(cdnDOM);
333
340
  e.remove();
334
341
  }
335
- <\/script>` + h, i = i.replace("</head>", `${h}</head>`), i;
336
- } catch (c) {
337
- console.error("获取dependencies出错:", c);
342
+ <\/script>` + h, c = c.replace("</head>", `${h}</head>`), c;
343
+ } catch (i) {
344
+ console.error("获取dependencies出错:", i);
338
345
  }
339
346
  }
340
347
  };
@@ -1,4 +1,4 @@
1
- (function(d,a){typeof exports=="object"&&typeof module<"u"?module.exports=a(require("node:path"),require("node:fs"),require("node:https")):typeof define=="function"&&define.amd?define(["node:path","node:fs","node:https"],a):(d=typeof globalThis<"u"?globalThis:d||self,d.index=a(d.path,d.fs,d.https))})(this,function(d,a,f){"use strict";var V=Object.defineProperty;var T=(d,a,f)=>a in d?V(d,a,{enumerable:!0,configurable:!0,writable:!0,value:f}):d[a]=f;var P=(d,a,f)=>(T(d,typeof a!="symbol"?a+"":a,f),f);class O{constructor(){P(this,"cdnCache",{});P(this,"cdnCachePath","");this.cdnCachePath=d.resolve(process.cwd(),"./.cdn-cache.json")}async init(){try{const e=await a.readFileSync(this.cdnCachePath,"utf-8");this.cdnCache=JSON.parse(e)}catch{console.log("cdn缓存文件不存在,创建缓存文件"),this.cdnCache={},await a.writeFileSync(this.cdnCachePath,"","utf-8")}}getCdnCache(e,t){var r;return(r=this.cdnCache[e])==null?void 0:r[t]}setCdnCache(e,t,r){this.cdnCache[e]?this.cdnCache[e][t]=r:this.cdnCache[e]={[t]:r}}async save(){await a.writeFileSync(this.cdnCachePath,JSON.stringify(this.cdnCache),"utf-8")}}let w;const J=async()=>(w||(w=new O,await w.init()),w),g={get:(n,e,t)=>new Promise((r,s)=>{try{f.get(n,i=>{let o="";i.on("data",c=>{o+=c}),i.on("end",()=>{e==null||e(o),r(o)})})}catch(i){t==null||t(i),s(i)}})},D=async n=>{const e=/^(https:\/\/.*\d+\.\d+\.\d+\/).+?\.js$/;if(e.test(n)){const t=n.replace(e,(r,s)=>`${s}package.json`);return JSON.parse(await g.get(t))}else throw new Error(`${n} 不是正确的url`)},F=(n,e)=>{var t,r;return((t=n.dependencies)==null?void 0:t[e])||((r=n.devDependencies)==null?void 0:r[e])},x=n=>n.reduce((e,t)=>(t.type==="file"?e.push({name:t.path}):t.files&&e.push(...x(t.files)),e),[]),S={jsdelivr:{getFileList:(n,e)=>new Promise((t,r)=>{g.get(`https://data.jsdelivr.com/v1/stats/packages/npm/${n}@${e}/files`,s=>{const i=JSON.parse(s);if(i.length===0){r(new Error(`${n}@${e} not found`));return}t({fileList:i})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://cdn.jsdelivr.net/npm/${n}@${e}${t}`},unpkg:{getFileList:(n,e)=>new Promise((t,r)=>{g.get(`https://unpkg.com/${n}@${e}/?meta`,s=>{const i=JSON.parse(s);t({fileList:x(i.files||[])})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://unpkg.com/${n}@${e}${t}`},bootcdn:{getFileList:(n,e)=>new Promise((t,r)=>{g.get(`https://api.bootcdn.cn/libraries/${n}`,s=>{const i=JSON.parse(s);if(i.length===0){r(new Error(`${n} not found in bootcdn`));return}const o=i[0],u=o.assets.find(h=>h.version===e);if(!u){r(new Error(`${n}@${e} not found in ${o.name}`));return}const l=u.files.map(h=>({name:"/"+h}));t({fileList:l,recommendFileName:o.filename})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://cdn.bootcdn.net/ajax/libs/${n}/${e}${t}`},cdnjs:{getFileList:(n,e)=>new Promise((t,r)=>{g.get(`https://api.cdnjs.com/libraries/${n}/${e}`,s=>{const i=JSON.parse(s);if(i.error){r(new Error(`cdnjs: ${n}@${e} not found`));return}t({fileList:i.rawFiles.map(o=>({name:"/"+o}))})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://cdnjs.cloudflare.com/ajax/libs/${n}/${e}${t}`}},E=async(n,e,t)=>{var o;const r=(o=e.match(/\d+(.\d+)?(.\d+)?/))==null?void 0:o[0];if(!r)throw new Error(`${n} version ${e} is not valid`);const s=await S[t].getFileList(n,r).catch(c=>{throw c}),i=L(s,n);if(!i)throw new Error(`在 ${t} 中找不到 ${n}@${r} 文件,请检查包名或版本号`);return S[t].getUrl(n,r,i)},L=({fileList:n},e)=>{var i,o;let t=[`umd/${e}.production.min.js`,/umd\/.+?\.production\.min\.js$/,/dist\/.+?\.production\.min\.js$/,/dist\/.+?\.umd\.min\.js$/,`dist/${e}.prod.min.js`,/dist\/.+?\.global.prod.min.js/,`dist/${e}.min.js`,/.+?\.global.prod.min.js/,/.+?.global.prod.js/,/lib\/.+?\.min\.js$/,/dist\/.+?\.min\.js$/,/index\.min\.js$/,/index\.js$/,/\.min\.js$/,/\.js$/];const r=["runtime","compiler",".esm",".cjs","development"].filter(c=>!e.includes(c));let s="";for(let c of t)if(c instanceof RegExp?s=((i=n.find(u=>c.test(u.name)&&!r.some(l=>u.name.includes(l))))==null?void 0:i.name)||"":s=((o=n.find(u=>u.name.includes(c)&&!r.some(l=>u.name.includes(l))))==null?void 0:o.name)||"",s)break;return s};function b(n,e){const t=n.replace(/^\D/,"").split("."),r=e.replace(/^\D/,"").split("."),s=Math.max(t.length,r.length);for(;t.length<s;)t.push("0");for(;r.length<s;)r.push("0");for(let i=0;i<s;i++){const o=parseInt(t[i],10),c=parseInt(r[i],10);if(o>c)return 1;if(o<c)return-1}return 0}function N(n,e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]?b(n[t],e[t])===-1&&(n[t]=e[t]):n[t]=e[t]);return n}async function U({external:n,packageData:e,customScript:t,defaultCdns:r}){let s=[],i=!1;const o=await J();return await Promise.all(n.map(async c=>{const u=F(e,c);if(t[c])return{urls:[],key:c};if(!u){s.push(c);return}const l=o.getCdnCache(c,u);if(l)return{urls:l,key:c};{i=!0;const h={urls:await Promise.all(r.map(async m=>await E(c,u,m))),key:c};return o.setCdnCache(c,u,h.urls),h}})).then(c=>(i&&o.save(),{urls:c,noVersionPackages:s}))}function I(n){const{customScript:e={},retryTimes:t=1,defaultCdns:r=["jsdelivr","unpkg"]}=n;let s;return{name:"vite-add-cdn-script",enforce:"pre",apply:"build",config(i){s=i},async transformIndexHtml(i){if(!r||r.length===0)throw new Error("defaultCdns不能为空");const o=d.resolve(process.cwd(),"package.json");try{const c=a.readFileSync(o,"utf-8"),u=JSON.parse(c),l=s.build.rollupOptions.external,h={};let m="";const{urls:j,noVersionPackages:k}=await U({external:l,packageData:u,customScript:e,defaultCdns:r});if(k.length>0){const $={dependencies:{}};await Promise.all(j.map(async y=>{if(!y)return;const{key:R,urls:A}=y,v=e[R]||A[0];if(!v)return;const M=await D(v);N($.dependencies,M.dependencies)}));const{urls:C,noVersionPackages:p}=await U({external:k,packageData:$,customScript:e,defaultCdns:r});if(j.push(...C),p.length>0)throw console.error(`找不到${p.join(",")}的版本`),new Error(`找不到${p.join(",")}的版本`)}return j.forEach($=>{if(!$)return;const{urls:C,key:p}=$;if(e[p])m+=e[p];else{h[p]=C;const y=C[0];m+=`<script src="${y}" type="text/javascript" crossorigin="anonymous" onerror="errorCDN(this)" data-cur="0" data-key="${p}"><\/script>
1
+ (function(u,a){typeof exports=="object"&&typeof module<"u"?module.exports=a(require("node:path"),require("node:fs"),require("node:https")):typeof define=="function"&&define.amd?define(["node:path","node:fs","node:https"],a):(u=typeof globalThis<"u"?globalThis:u||self,u.index=a(u.path,u.fs,u.https))})(this,function(u,a,f){"use strict";var V=Object.defineProperty;var T=(u,a,f)=>a in u?V(u,a,{enumerable:!0,configurable:!0,writable:!0,value:f}):u[a]=f;var k=(u,a,f)=>(T(u,typeof a!="symbol"?a+"":a,f),f);class F{constructor(){k(this,"cdnCache",{});k(this,"cdnCachePath","");this.cdnCachePath=u.resolve(process.cwd(),"./.cdn-cache.json")}async init(){try{const e=await a.readFileSync(this.cdnCachePath,"utf-8");this.cdnCache=JSON.parse(e)}catch{console.log("cdn缓存文件不存在,创建缓存文件"),this.cdnCache={},await a.writeFileSync(this.cdnCachePath,"","utf-8")}}getCdnCache(e,t){var r;return(r=this.cdnCache[e])==null?void 0:r[t]}setCdnCache(e,t,r){this.cdnCache[e]?this.cdnCache[e][t]=r:this.cdnCache[e]={[t]:r}}async save(){await a.writeFileSync(this.cdnCachePath,JSON.stringify(this.cdnCache),"utf-8")}}let j;const E=async()=>(j||(j=new F,await j.init()),j),$={get:(n,e,t)=>new Promise((r,s)=>{try{f.get(n,i=>{let o="";i.on("data",c=>{o+=c}),i.on("end",()=>{e==null||e(o),r(o)})})}catch(i){t==null||t(i),s(i)}})},L=async n=>{const e=/^(https:\/\/.*\d+\.\d+\.\d+\/).+?\.js$/;if(e.test(n)){const t=n.replace(e,(r,s)=>`${s}package.json`);return JSON.parse(await $.get(t))}else throw new Error(`${n} 不是正确的url`)},b=(n,e)=>{var t,r;return((t=n.dependencies)==null?void 0:t[e])||((r=n.devDependencies)==null?void 0:r[e])},v=n=>n.reduce((e,t)=>(t.type==="file"?e.push({name:t.path}):t.files&&e.push(...v(t.files)),e),[]),O={jsdelivr:{getFileList:(n,e)=>new Promise((t,r)=>{$.get(`https://data.jsdelivr.com/v1/stats/packages/npm/${n}@${e}/files`,s=>{const i=JSON.parse(s);if(i.length===0){r(new Error(`${n}@${e} not found`));return}t({fileList:i})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://cdn.jsdelivr.net/npm/${n}@${e}${t}`},unpkg:{getFileList:(n,e)=>new Promise((t,r)=>{$.get(`https://unpkg.com/${n}@${e}/?meta`,s=>{const i=JSON.parse(s);t({fileList:v(i.files||[])})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://unpkg.com/${n}@${e}${t}`},bootcdn:{getFileList:(n,e)=>new Promise((t,r)=>{$.get(`https://api.bootcdn.cn/libraries/${n}`,s=>{const i=JSON.parse(s);if(i.length===0){r(new Error(`${n} not found in bootcdn`));return}const o=i[0],d=o.assets.find(h=>h.version===e);if(!d){r(new Error(`${n}@${e} not found in ${o.name}`));return}const l=d.files.map(h=>({name:"/"+h}));t({fileList:l,recommendFileName:o.filename})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://cdn.bootcdn.net/ajax/libs/${n}/${e}${t}`},cdnjs:{getFileList:(n,e)=>new Promise((t,r)=>{$.get(`https://api.cdnjs.com/libraries/${n}/${e}`,s=>{const i=JSON.parse(s);if(i.error){r(new Error(`cdnjs: ${n}@${e} not found`));return}t({fileList:i.rawFiles.map(o=>({name:"/"+o}))})},s=>{r(s)})}),getUrl:(n,e,t)=>`https://cdnjs.cloudflare.com/ajax/libs/${n}/${e}${t}`}},N=async(n,e,t)=>{var o;const r=(o=e.match(/\d+(.\d+)?(.\d+)?/))==null?void 0:o[0];if(!r)throw new Error(`${n} version ${e} is not valid`);const s=await O[t].getFileList(n,r).catch(c=>{throw c}),i=I(s,n);if(!i)throw new Error(`在 ${t} 中找不到 ${n}@${r} 文件,请检查包名或版本号`);return O[t].getUrl(n,r,i)},I=({fileList:n},e)=>{var i,o;let t=[`umd/${e}.production.min.js`,/umd\/.+?\.production\.min\.js$/,/dist\/.+?\.production\.min\.js$/,/dist\/.+?\.umd\.min\.js$/,`dist/${e}.prod.min.js`,/dist\/.+?\.global.prod.min.js/,`dist/${e}.min.js`,/.+?\.global.prod.min.js/,/.+?.global.prod.js/,/lib\/.+?\.min\.js$/,/dist\/.+?\.min\.js$/,/index\.min\.js$/,/index\.js$/,/\.min\.js$/,/\.js$/];const r=["runtime","compiler",".esm",".cjs","development"].filter(c=>!e.includes(c));let s="";for(let c of t)if(c instanceof RegExp?s=((i=n.find(d=>c.test(d.name)&&!r.some(l=>d.name.includes(l))))==null?void 0:i.name)||"":s=((o=n.find(d=>d.name.includes(c)&&!r.some(l=>d.name.includes(l))))==null?void 0:o.name)||"",s)break;return s};function R(n,e){const t=n.replace(/^\D/,"").split("."),r=e.replace(/^\D/,"").split("."),s=Math.max(t.length,r.length);for(;t.length<s;)t.push("0");for(;r.length<s;)r.push("0");for(let i=0;i<s;i++){const o=parseInt(t[i],10),c=parseInt(r[i],10);if(o>c)return 1;if(o<c)return-1}return 0}function A(n,e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(n[t]?R(n[t],e[t])===-1&&(n[t]=e[t]):n[t]=e[t]);return n}async function J({external:n,packageData:e,customScript:t,defaultCdns:r}){let s=[],i=!1;const o=await E();return await Promise.all(n.map(async c=>{const d=b(e,c);if(t[c])return{urls:[],key:c};if(!d)return s.push(c),{urls:[],key:c};const l=o.getCdnCache(c,d);if(l)return{urls:l,key:c};{i=!0,console.log(`从网络获取${c}${d}的cdn地址`);const h={urls:await Promise.all(r.map(async m=>await N(c,d,m))),key:c};return o.setCdnCache(c,d,h.urls),h}})).then(c=>(i&&o.save(),{urls:c,noVersionPackages:s}))}function M(n){const{customScript:e={},retryTimes:t=1,defaultCdns:r=["jsdelivr","unpkg"]}=n;let s;return{name:"vite-add-cdn-script",enforce:"pre",apply:"build",config(i){s=i},async transformIndexHtml(i){if(!r||r.length===0)throw new Error("defaultCdns不能为空");const o=u.resolve(process.cwd(),"package.json");try{const c=a.readFileSync(o,"utf-8"),d=JSON.parse(c),l=s.build.rollupOptions.external,h={};let m="";const{urls:x,noVersionPackages:D}=await J({external:l,packageData:d,customScript:e,defaultCdns:r});if(D.length>0){const w={dependencies:{}};await Promise.all(x.map(async g=>{if(!g)return;const{key:S,urls:U}=g,C=e[S]||U[0];if(!C)return;const y=await L(C);A(w.dependencies,y.dependencies)}));const{urls:P,noVersionPackages:p}=await J({external:D,packageData:w,customScript:e,defaultCdns:r});if(P.map(g=>{var C;if(!g)return;const{urls:S,key:U}=g;(C=x.find(y=>(y==null?void 0:y.key)===U))==null||C.urls.push(...S)}),p.length>0)throw console.error(`找不到${p.join(",")}的版本`),new Error(`找不到${p.join(",")}的版本`)}return x.forEach(w=>{if(!w)return;const{urls:P,key:p}=w;if(e[p])m+=e[p];else{h[p]=P;const g=P[0];m+=`<script src="${g}" type="text/javascript" crossorigin="anonymous" onerror="errorCDN(this)" data-cur="0" data-key="${p}"><\/script>
2
2
  `}}),m=`<script>
3
3
  function errorCDN(e) {
4
4
  const packNameUrl = JSON.parse('${JSON.stringify(h)}');
@@ -21,4 +21,4 @@
21
21
  document.head.appendChild(cdnDOM);
22
22
  e.remove();
23
23
  }
24
- <\/script>`+m,i=i.replace("</head>",`${m}</head>`),i}catch(c){console.error("获取dependencies出错:",c)}}}}return I});
24
+ <\/script>`+m,i=i.replace("</head>",`${m}</head>`),i}catch(c){console.error("获取dependencies出错:",c)}}}}return M});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-add-cdn-script",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "keywords": [
5
5
  "vite",
6
6
  "cdn",