cdn-script-core 1.0.1 → 1.0.2
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.ts +1 -2
- package/dist/index.js +1 -1
- package/dist/index.umd.cjs +3 -3
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -78,7 +78,7 @@ export declare function generateScript(urlListRes: {
|
|
|
78
78
|
key: string;
|
|
79
79
|
}[]): string;
|
|
80
80
|
|
|
81
|
-
declare function getExternalScript({ libName, customScript, external: inputExternal, defaultCdns, }: {
|
|
81
|
+
export declare function getExternalScript({ libName, customScript, external: inputExternal, defaultCdns, }: {
|
|
82
82
|
libName: string;
|
|
83
83
|
external: ExternalOption;
|
|
84
84
|
customScript: {
|
|
@@ -86,7 +86,6 @@ declare function getExternalScript({ libName, customScript, external: inputExter
|
|
|
86
86
|
};
|
|
87
87
|
defaultCdns: PropertyCdn[];
|
|
88
88
|
}): Promise<string>;
|
|
89
|
-
export default getExternalScript;
|
|
90
89
|
|
|
91
90
|
/**
|
|
92
91
|
* 文件获取失败错误
|
package/dist/index.js
CHANGED
package/dist/index.umd.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(a,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("node-fetch"),require("semver"),require("node:path"),require("node:fs")):typeof define=="function"&&define.amd?define(["exports","node-fetch","semver","node:path","node:fs"],f):(a=typeof globalThis<"u"?globalThis:a||self,f(a.index={},a.fetch,a.semver,a.path,a.fs))})(this,function(a,f,j,F,
|
|
1
|
+
(function(a,f){typeof exports=="object"&&typeof module<"u"?f(exports,require("node-fetch"),require("semver"),require("node:path"),require("node:fs")):typeof define=="function"&&define.amd?define(["exports","node-fetch","semver","node:path","node:fs"],f):(a=typeof globalThis<"u"?globalThis:a||self,f(a.index={},a.fetch,a.semver,a.path,a.fs))})(this,function(a,f,j,F,U){"use strict";var me=Object.defineProperty;var ye=(a,f,j)=>f in a?me(a,f,{enumerable:!0,configurable:!0,writable:!0,value:j}):a[f]=j;var g=(a,f,j)=>(ye(a,typeof f!="symbol"?f+"":f,j),j);var b=(r=>(r.log="log",r.warn="warn",r.error="error",r.info="info",r))(b||{});class x{constructor(e){g(this,"logList",[]);g(this,"prefixString","cdn-script");e&&(this.prefixString=e)}log(e){this.logList.push({type:"log",message:e})}warn(e){this.logList.push({type:"warn",message:e})}error(e){this.logList.push({type:"error",message:e})}info(e){this.logList.push({type:"info",message:e})}consoleAll(){console.log(""),this.logList.forEach(e=>{console[e.type](`${this.prefixString} ${e.message}`)})}addMessageList(e,t){t.forEach(s=>{this.logList.push({type:e,message:s.toString()})})}clear(){this.logList=[]}}class p extends Error{constructor(e){super(e),this.name="NetworkError"}}class m extends p{constructor({packageName:t,version:s,cdn:n}){super(`${n} ${t}@${s} 网络请求失败`);g(this,"cdn");g(this,"packageName");g(this,"version");this.name="PackageNetworkError",this.cdn=n,this.packageName=t,this.version=s}getErrorInfo(){return{cdn:this.cdn,packageName:this.packageName,version:this.version}}}class y extends Error{constructor({packageName:t,version:s,cdn:n}){super(`${n}上没有${t}@${s}的版本`);g(this,"cdn");g(this,"packageName");g(this,"version");this.name="NoVersionError",this.cdn=n,this.packageName=t,this.version=s}getErrorInfo(){return{cdn:this.cdn,packageName:this.packageName,version:this.version}}}class _ extends Error{constructor({packageName:e,version:t,cdn:s}){super(`在 ${s} 中找不到 ${e}@${t} 文件,请检查包名或版本号`),this.name="GetFileListError"}}function K(r,e){const t=r.replace(/^\D/,"").split("."),s=e.replace(/^\D/,"").split("."),n=Math.max(t.length,s.length);for(;t.length<n;)t.push("0");for(;s.length<n;)s.push("0");for(let c=0;c<n;c++){const d=parseInt(t[c],10),i=parseInt(s[c],10);if(d>i)return 1;if(d<i)return-1}return 0}function M(r,e){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&(r[t]?K(r[t],e[t])===-1&&(r[t]=e[t]):r[t]=e[t]);return r}class W{constructor(e){g(this,"_max");g(this,"_count");g(this,"_taskQueue");this._max=e||5,this._count=0,this._taskQueue=[]}call(e,...t){return new Promise((s,n)=>{const c=this._createTask(e,t,s,n);this._count>=this._max?this._taskQueue.push(c):c()})}_createTask(e,t,s,n){return()=>{e(...t).then(s).catch(n).finally(()=>{this._count--,this._taskQueue.length&&this._taskQueue.shift()()}),this._count++}}}const O=new W(5),R=async r=>{try{const e=await f(r,{method:"HEAD",redirect:"manual"});return e.status>=300&&e.status<400?await R(e.headers.get("location")||""):r}catch(e){throw new p(e.message)}},X={get:async r=>{try{const e=await f(r);if(e.ok){const t=e.headers.get("content-type"),s=await e.text();return t&&t.includes("application/json")?JSON.parse(s):s}else throw new p(`请求失败,状态码:${e.status}`)}catch(e){throw new p(e.message)}}},P={get:O.call.bind(O,X.get)},Y={getFileList:async(r,e)=>{try{const t=await P.get(`https://api.bootcdn.cn/libraries/${r}`);if(t.length===0)throw new y({packageName:r,version:e,cdn:"bootcdn"});const s=t[0],c=s.assets.reverse().find(i=>{if(j.satisfies(i.version,e))return!0});if(!c)throw new y({packageName:r,version:e,cdn:"bootcdn"});return{fileList:c.files.map(i=>({name:"/"+i})),recommendFileName:s.filename,version:c.version}}catch(t){throw t instanceof p?new m({packageName:r,version:e,cdn:"bootcdn"}):t}},getUrl:(r,e,t)=>`https://cdn.bootcdn.net/ajax/libs/${r}/${e}${t}`};async function V(r,e,t=!1){try{if(!t&&e.match(/^\D/)){const n=await ee(r,e);for(let c of n)if(j.satisfies(c,e))return V(r,c,!0);throw new y({packageName:r,version:e,cdn:"cdnjs"})}const s=await P.get(`https://api.cdnjs.com/libraries/${r}/${e}`);if(s.error)throw new y({packageName:r,version:e,cdn:"cdnjs"});return{fileList:s.rawFiles.map(n=>({name:"/"+n})),version:e}}catch(s){throw s instanceof p?new m({packageName:r,version:e,cdn:"cdnjs"}):s}}const Z=(r,e,t)=>`https://cdnjs.cloudflare.com/ajax/libs/${r}/${e}${t}`,ee=async(r,e)=>{try{return(await P.get(`https://api.cdnjs.com/libraries/${r}?fields=versions`)).versions}catch(t){throw t instanceof p?new m({packageName:r,version:e,cdn:"cdnjs"}):t}},te={getFileList:V,getUrl:Z},J=(r,e="")=>r.reduce((t,s)=>(s.type==="file"?t.push({name:`${e}/${s.name}`}):s.files&&t.push(...J(s.files,`${e}/${s.name}`)),t),[]);async function A(r,e,t=!1){try{if(!t&&e.match(/^\D/)){const n=await se(r,e);if(typeof n=="string")return A(r,n,!0);throw new y({packageName:r,version:e,cdn:"jsdelivr"})}const s=await P.get(`https://data.jsdelivr.com/v1/packages/npm/${r}@${e}`);if(s.status)throw new y({packageName:r,version:e,cdn:"jsdelivr"});return{fileList:J(s.files),version:e}}catch(s){throw s instanceof p?new m({packageName:r,version:e,cdn:"jsdelivr"}):s}}const re=(r,e,t)=>`https://cdn.jsdelivr.net/npm/${r}@${e}${t}`,se=async(r,e)=>{try{return(await P.get(`https://data.jsdelivr.com/v1/packages/npm/${r}/resolved?specifier=${e}`)).version}catch(t){throw t instanceof p?new m({packageName:r,version:e,cdn:"jsdelivr"}):t}},ne={getFileList:A,getUrl:re},N=r=>r.reduce((e,t)=>(t.type==="file"?e.push({name:t.path}):t.files&&e.push(...N(t.files)),e),[]);async function ce(r,e){var t;try{const n=(t=(await R(`https://unpkg.com/${r}@${e}/?meta`)).match(new RegExp("(?<=@)\\d+\\.\\d+\\.\\d+(?=\\/\\?meta)")))==null?void 0:t[0];if(n){const c=await P.get(`https://unpkg.com/${r}@${n}/?meta`);return{fileList:N(c.files||[]),version:n}}else throw new y({packageName:r,version:e,cdn:"unpkg"})}catch(s){throw s instanceof p?new m({packageName:r,version:e,cdn:"unpkg"}):s}}function ie(r,e,t){return`https://unpkg.com/${r}@${e}${t}`}const oe={getFileList:ce,getUrl:ie},ae=async r=>{try{const e=/^(https?:\/\/.*\d+\.\d+\.\d+\/).+?\.js$/;if(e.test(r)){const t=r.replace(e,(s,n)=>`${n}package.json`);return await P.get(t)}else throw new Error(`${r} 不是正确的url`)}catch(e){throw e}},le=(r,e)=>{var t,s;return((t=r.dependencies)==null?void 0:t[e])||((s=r.devDependencies)==null?void 0:s[e])},I=async(r,e,t)=>{if(!e.match(/\d+(.\d+)?(.\d+)?/))throw new Error(`${r} version ${e} is not valid`);const n=await q[t].getFileList(r,e),c=de(n,r);if(!c)throw new _({packageName:r,version:e,cdn:t});return q[t].getUrl(r,n.version,c)},de=({fileList:r},e)=>{var c,d;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 s=["runtime","compiler",".esm",".cjs","development"].filter(i=>!e.includes(i));let n="";for(let i of t)if(i instanceof RegExp?n=((c=r.find(o=>i.test(o.name)&&!s.some(h=>o.name.includes(h))))==null?void 0:c.name)||"":n=((d=r.find(o=>o.name.includes(i)&&!s.some(h=>o.name.includes(h))))==null?void 0:d.name)||"",n)break;return n},q={jsdelivr:ne,bootcdn:Y,cdnjs:te,unpkg:oe};var v=(r=>(r.noFound="noFound",r.NetworkError="networkError",r))(v||{});class ue{constructor(){g(this,"cdnCache",{packageDependencies:{},cdnsUrl:{}});g(this,"cdnCachePath","");this.cdnCachePath=F.resolve(process.cwd(),"./.cdn-cache.json")}async init(){try{const e=await U.readFileSync(this.cdnCachePath,"utf-8");this.cdnCache=JSON.parse(e)}catch{console.log("cdn缓存文件不存在,创建缓存文件"),this.cdnCache={packageDependencies:{},cdnsUrl:{}},await U.writeFileSync(this.cdnCachePath,"","utf-8")}}getCdnCache(e,t){var s;return(s=this.cdnCache.cdnsUrl[e])==null?void 0:s[t]}setCdnCache(e,t,s){this.cdnCache.cdnsUrl[e]?this.cdnCache.cdnsUrl[e][t]=s:this.cdnCache.cdnsUrl[e]={[t]:s}}async save(){await U.writeFileSync(this.cdnCachePath,JSON.stringify(this.cdnCache),"utf-8")}getPackageDependencies(e,t){var s;return(s=this.cdnCache.packageDependencies[e])==null?void 0:s[t]}setPackageDependencies(e,t,s){this.cdnCache.packageDependencies[e]?this.cdnCache.packageDependencies[e][t]=s:this.cdnCache.packageDependencies[e]={[t]:s}}}let D;const Q=async()=>(D||(D=new ue,await D.init()),D);async function S({external:r,packageData:e,customScript:t,defaultCdns:s}){let n=[],c=!1,d=[];const i=await Q();return await Promise.all(r.map(async o=>{const h=le(e,o);if(t[o])return{urls:[t[o]],key:o};if(!h)return n.push(o),{urls:[],key:o};const w=i.getCdnCache(o,h);if(w){const $=new Set(s),C=new Map,L=w.filter((l,u)=>{if($.has(l.cdnName)&&l.success)return $.delete(l.cdnName),!0;!l.success&&l.error===v.noFound?$.delete(l.cdnName):C.set(l.cdnName,u)}).map(l=>l.url);if($.size>0){const l=await Promise.allSettled([...$].map(async u=>({cdnName:u,success:!0,url:await I(o,h,u)}))).then(u=>u.filter(k=>{if(k.status==="fulfilled")return L.push(k.value.url),!0;d.push(k.reason)}));l.length>0&&(l.forEach(u=>{const k=C.get(u.value.cdnName);k!==void 0?w[k]=u.value:w.push(u.value)}),i.setCdnCache(o,h,w),c=!0)}return{urls:L,version:h,key:o}}else{c=!0,console.log(`从网络获取${o}${h}的cdn地址`);const $=await Promise.allSettled(s.map(async l=>({cdnName:l,success:!0,url:await I(o,h,l)}))).then(l=>l.map(u=>{if(u.status==="fulfilled")return u.value;if(d.push(u.reason),u.reason instanceof m||u.reason instanceof y)return{cdnName:u.reason.cdn,success:!1,error:u.reason instanceof m?v.NetworkError:v.noFound}}).filter(u=>!!u)),C=$.filter(l=>l.success).map(l=>l.url);if(C.length===0)throw new Error(`
|
|
2
2
|
${d.map(l=>l.message).join(`
|
|
3
|
-
`)}获取${o} ${h}的cdn地址失败`);const L={urls:C,version:h,key:o};return i.setCdnCache(o,h,$),L}})).then(o=>(c&&i.save(),{urls:o,noVersionPackages:n,errorList:d}))}const T=async({packageVersionInfo:r})=>{const e={dependencies:{}};let t=!1;const s=await Q(),n=[];return await Promise.allSettled(r.map(async c=>{if(!c)return;const{urls:d}=c,i=d[0];if(!i)return;const o=c.version||i,h=s.getPackageDependencies(c.key,o);if(h)return
|
|
3
|
+
`)}获取${o} ${h}的cdn地址失败`);const L={urls:C,version:h,key:o};return i.setCdnCache(o,h,$),L}})).then(o=>(c&&i.save(),{urls:o,noVersionPackages:n,errorList:d}))}const T=async({packageVersionInfo:r})=>{const e={dependencies:{}};let t=!1;const s=await Q(),n=[];return await Promise.allSettled(r.map(async c=>{if(!c)return;const{urls:d}=c,i=d[0];if(!i)return;const o=c.version||i,h=s.getPackageDependencies(c.key,o);if(h)return M(e.dependencies,h.dependencies);const w=await ae(i);s.setPackageDependencies(c.key,o,{dependencies:w.dependencies}),t=!0,M(e.dependencies,w.dependencies)})).then(c=>(t&&s.save(),c.forEach(d=>{d.status==="rejected"&&n.push(d.reason)}),{urlPackageJsonRes:e,errorList:n}))};function G(r){let e="";const t={};return r.forEach(n=>{if(!n)return;const{urls:c,key:d}=n;t[d]=c;const i=c[0];e+=`<script src="${i}" type="text/javascript" crossorigin="anonymous" onerror="errorCDN(this)" data-cur="0" data-key="${d}"><\/script>
|
|
4
4
|
`}),e=`<script>
|
|
5
5
|
function errorCDN(e) {
|
|
6
6
|
const packNameUrl = JSON.parse('${JSON.stringify(t)}');
|
|
@@ -22,4 +22,4 @@
|
|
|
22
22
|
document.head.appendChild(cdnDOM);
|
|
23
23
|
e.remove();
|
|
24
24
|
}
|
|
25
|
-
<\/script>`.replace(/^\s*\/\/.*?$/gm,"")+e,e}function H(r){return Object.prototype.toString.call(r)}function he(r){return H(r)==="[object String]"}function fe(r){return H(r)==="[object Object]"}async function ge({libName:r,customScript:e,external:t,defaultCdns:s}){let n=new
|
|
25
|
+
<\/script>`.replace(/^\s*\/\/.*?$/gm,"")+e,e}function H(r){return Object.prototype.toString.call(r)}function he(r){return H(r)==="[object String]"}function fe(r){return H(r)==="[object Object]"}async function ge({libName:r,customScript:e,external:t,defaultCdns:s}){let n=new x(r);const c=F.resolve(process.cwd(),"package.json");if(!t)return"";let d=[];if(he(t))d=[t];else if(Array.isArray(t))d=t.filter(i=>typeof i=="string");else if(fe(t))d=Object.keys(t);else return"";try{const i=U.readFileSync(c,"utf-8"),o=JSON.parse(i),{urls:h,noVersionPackages:w,errorList:$}=await S({external:d,packageData:o,customScript:e,defaultCdns:s});if(n.addMessageList("warn",$),w.length>0){const{urlPackageJsonRes:L,errorList:l}=await T({packageVersionInfo:h});n.addMessageList("warn",l);const{urls:u,noVersionPackages:k,errorList:pe}=await S({external:w,packageData:L,customScript:e,defaultCdns:s});if(n.addMessageList("warn",pe),u.map(z=>{var B;if(!z)return;const{urls:we,key:$e}=z;(B=h.find(E=>(E==null?void 0:E.key)===$e))==null||B.urls.push(...we)}),k.length>0)throw new Error(`找不到${k.join(",")}的版本`)}return n.consoleAll(),G(h)}catch(i){throw n.consoleAll(),i}}a.ConsoleManage=x,a.ConsoleType=b,a.GetFileListError=_,a.NetworkError=p,a.NoVersionError=y,a.PackageNetworkError=m,a.findUrls=S,a.generateScript=G,a.getExternalScript=ge,a.getPackageDependencies=T,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
|