xhs-mp-shared 2.0.4-beta.3 → 2.0.4

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.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("chalk"),t=require("cos-nodejs-sdk-v5"),o=require("path"),r=require("fs"),s=require("uuid"),i=require("node-fetch"),n=require("child_process"),a=require("os"),c=require("crypto");function l(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(o){if("default"!==o){var r=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,r.get?r:{enumerable:!0,get:function(){return e[o]}})}})),t.default=e,Object.freeze(t)}var u=l(t);class p{constructor(e){this.prefix=e||"[@xhs-toolkit]",this.verbose=global.verbose}setVerbose(e){this.verbose=e}info(...t){console.info(e.blue(this.prefix),...t)}log(...t){console.log(e.blue(this.prefix),...t)}debug(...t){this.verbose&&console.debug(e.yellow(this.prefix),...t)}warn(...t){this.verbose&&console.warn(e.yellow(this.prefix),...t)}error(...t){console.error(e.red(this.prefix),...t)}}class d{static getLogger(){return window.eaglet.sendApm&&window.eaglet||global.eaglet}constructor({success:e=!0,code:t=0,info:o}){this.success=e,this.code=t,this.info=o}setCode(e){return this.code=e,this}setMsg(e){return this.msg=e,this}setData(e){return this.data=e,this}setInfo(e){return this.info=e,this}fail(){return this.success=!1,this.code=-1,this}log(e,t){var o;try{const r={bizName:e.bizName,scene:e.scene,customerHost:window.location.host,routePath:window.location.pathname,uploadSuccess:this.success,code:this.code,errorMsg:this.msg,successData:JSON.stringify(this.data),fileType:this.info.fileType,fileSize:this.info.fileSize,startTime:d.formatDate(this.info.startTime),endTime:d.formatDate(Date.now()),tokenStartTime:d.formatDate(this.info.startTime),tokenEndTime:d.formatDate(this.info.tokenEndTime||Date.now()),tokenTimestamp:(this.info.tokenEndTime||Date.now())-this.info.startTime,uploadTimestamp:Date.now()-this.info.startTime,...t};r.uploadSuccess&&0!==r.uploadTimestamp&&(r.uploadSpeed=r.fileSize/r.uploadTimestamp);const s=d.getLogger();if(s)s.push({type:"InfraUploader",value:r},"ApmJSONTracker");else{console.warn.bind(console)("[APM Warning]: eaglet is undefined, web app please install @xhs/launcher-plugin-eaglet, react-native app use eaglet plugin from asgard!")}const i=(null===(o=null===window||void 0===window?void 0:window.insight)||void 0===o?void 0:o.sendCustomPoint.bind(null===window||void 0===window?void 0:window.insight))||(null==s?void 0:s.flushApm);i&&(Object.keys(r).forEach((e=>{"boolean"==typeof r[e]&&(r[e]=Number(r[e]))})),i({measurement_name:"infraUploader",measurement_data:r},"ApmXrayTracker"))}finally{return this}}static formatDate(e){return new Date(e).toISOString().replace(/T/," ").replace(/\..+/,"")}}var h;!function(e){e.SECRET_ID="AKIDopc9PQM41h6VeVhqKRIsnRoy77sOe18z",e.SECRET_KEY="kEUTCdR0IOMuBONjlkUO4VgZiaCappql",e.BUCKET_NAME="fe-static",e.APP_ID="1251524319",e.REGION="ap-shanghai",e.HOST="eva-1251524319.cos.ap-shanghai.myqcloud.com",e.FILE_KEY="mp/red/map"}(h||(h={}));const m=new t({SecretId:h.SECRET_ID,SecretKey:h.SECRET_KEY}),f=`${h.BUCKET_NAME}-${h.APP_ID}`,g=(e,t)=>{const r=o.basename(e),s=o.extname(r);if(!s||"."===s)throw new Error(`fileName: '${e}' is not validata, please check extname`);const i=`${`${h.FILE_KEY}`}/${t}/${r}`;return{Bucket:f,Region:h.REGION,Key:i,FilePath:e}},v=async e=>{const t=e.map((({Key:e})=>({Key:e})));try{await m.deleteMultipleObject({Bucket:f,Region:h.REGION,Objects:t})}catch(e){console.log("===== 腾讯云中已存在同名文件,且删除时报错: =====",e)}};var w=Object.freeze({__proto__:null,Bucket:f,deleteExistingFiles:v,qcloudClient:m,upload2Qcloud:async(e,t)=>{if(!e||!e.length)throw new Error("上传地址不能为空!");const o=Array.isArray(e)?e.map((e=>g(e,t))):[g(e,t)];if(!o.every((e=>r.existsSync(e.FilePath))))throw new Error(`上传地址不合法: ${JSON.stringify(o,null,2)}`);return await v(o),await((e,t)=>new Promise(((t,o)=>{m.uploadFiles({files:e,SliceSize:1024,onProgress:e=>{Number(e.speed/1024/1024*100)}},((e,r)=>{e?o(e):t(r)}))})))(o)}});const y={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:"%windir%\\System32\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :"};function b(e){return c.createHash("sha256").update(e).digest("hex")}function S(){var e,t;try{return"darwin"===process.platform?null===(e=n.execSync("sw_vers -productVersion",{encoding:"utf-8"}))||void 0===e?void 0:e.trim():null===(t=a.release())||void 0===t?void 0:t.trim()}catch(e){}return""}function x(){var e,t,o;const r=a.cpus(),s=null==r?void 0:r[0];return{os_platform:(null===(t=null===(e=process.platform)||void 0===e?void 0:e[0])||void 0===t?void 0:t.toUpperCase())+process.platform.slice(1),os_arch:process.arch,cpu_speed:Number(null===(o=1e3*(null==s?void 0:s.speed))||void 0===o?void 0:o.toFixed(0)),cpu_model:null==s?void 0:s.model,machine_memory:Math.round(a.totalmem()/1024/1024),os_version:S()}}const _=x(),T={context_nameTracker:"nodeT",context_platform:_.os_platform,context_appVersion:"",context_osVersion:_.os_version,context_deviceModel:"",context_deviceId:function(){try{return function(e){switch(process.platform){case"darwin":return e.split("IOPlatformUUID")[1].split("\n")[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return e.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return e.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error(`Unsupported platform: ${process.platform}`)}}(n.execSync(y[process.platform]).toString())}catch(e){}return JSON.stringify({...x(),login_user:b(a.userInfo().username||process.env.username),node_version:process.version})}(),context_package:"",context_networkType:"unknow",context_matchedPath:"cli",context_route:"xhsmp://cli",context_userAgent:[`Node/${process.version}`,`${_.os_platform}/${_.os_version} (${_.cpu_model}; ${_.cpu_speed}mhz; ${_.machine_memory}mb)`].join(" "),context_artifactName:"miniprogram",context_networkQuality:"UNKNOWN",context_artifactVersion:"UNKNOWN",context_userId:""},E="https://apm-fe.xiaohongshu.com/api/data";var I,k,N,O,C,D,z;exports.FeatureReporter=void 0,I=exports.FeatureReporter||(exports.FeatureReporter={}),(k=I.MODULE||(I.MODULE={})).appJSON="json-app",k.extJSON="json-ext",k.componentJSON="json-component",k.ml="ml",k.thirdFramework="third-framework",k.developMode="develop-mode",(N=I.AppExtJSON||(I.AppExtJSON={})).pages="pages",N.subpackages="subpackages",N.subPackages="subPackages",N.lazyCodeLoading="lazyCodeLoading",N.tabBar="tabBar",N.preloadRule="preloadRule",N.usingComponents="usingComponents",N.extPages="extPages",(O=I.JSONComponent||(I.JSONComponent={})).styleIsolation="styleIsolation",O.componentPlaceholder="componentPlaceholder",(C=I.ML||(I.ML={})).WebComponent="web-component",C.animation="animation",C.template="template",C.sjs="sjs",(D=I.ThirdFramework||(I.ThirdFramework={})).taroReact="taro-react",D.taroVue="taro-vue",D.taro="taro",D.uniapp3="uniapp3",D.uniapp2="uniapp2",D.weimeng="weimeng",(z=I.DevelopMode||(I.DevelopMode={})).customDevelopment="custom-development",z.templateDevelopment="template-development",exports.COS=u,exports.APM=class{constructor(e){this.reportQueue=[],this.allowReport=!1,this.eventSeq=1,this.context={...T},this.baseData={},this.logger=new p("[apm]: "),this.timer=null,this.context.context_appVersion=e}setContext(e,t={}){this.context={...this.context,context_userId:e},this.baseData=t,this.startReport()}startReport(){this.allowReport=!0,this.bactchReport()}getSequence(){return{context_sdkSeqId:this.eventSeq++,context_sdkSessionId:s.v4(),context_pageSessionId:s.v4(),clientTime:Date.now()}}_request(e,t=!0){var o;const r=(Array.isArray(e)?e:[e]).map((e=>({...this.context,...e.suquence,measurement_name:e.measurement_name,measurement_data:{...this.baseData,...e.measurement_data}})));return null===(o=this.logger)||void 0===o||o.debug("apm before send",`${JSON.stringify(r)}`,"warning"),i(E,{method:"post",body:JSON.stringify(r),headers:{accept:"*/*","accept-language":"zh-CN,zh;q=0.9",batch:"true","biz-type":"apm_fe","cache-control":"no-cache","content-type":"application/json",pragma:"no-cache"}}).then((e=>e.json())).then((e=>{var t;if(!(null==e?void 0:e.success))throw new Error(null==e?void 0:e.msg);null===(t=this.logger)||void 0===t||t.debug("apm send success","")})).catch((e=>{var o;t&&setTimeout((()=>this._request(r,!1)),1e3),null===(o=this.logger)||void 0===o||o.log("apm send failed",`${(null==e?void 0:e.message)||null}`,"error")}))}bactchReport(){const e=[...this.reportQueue];for(this.reportQueue=[];e.length;)this._request(e.splice(0,5))}report(e,t={}){const o={suquence:this.getSequence(),measurement_name:e,measurement_data:t};this.reportQueue.push(o),clearTimeout(this.timer),this.allowReport&&(this.reportQueue.length>=10?this.bactchReport():this.timer=setTimeout((()=>{this.bactchReport()}),500))}},exports.Logger=p,exports.Uploader=class{constructor(e){this.useCache=!1,this.bizName=e.bizName,this.scene=e.scene,this.getToken=e.getToken,this.enableResume=e.enableResume}get cacheKey(){return`uploader-permit-${this.scene}-${this.bizName}`}getCachePermit(e,t){try{const o=`${t.name}-${t.size}`,r=localStorage.getItem(this.cacheKey);if(!r)return null;const s=JSON.parse(r)[o];return s?s.expireTime-12e4<Date.now()?(this.setCachePermit(e,t,null),null):s:null}catch(e){return localStorage.setItem(this.cacheKey,""),null}}setCachePermit(e,t,o){try{const e=`${t.name}-${t.size}`,r=localStorage.getItem(this.cacheKey),s=r?JSON.parse(r):{};s[e]=o,localStorage.setItem(this.cacheKey,JSON.stringify(s))}catch(e){}}getPermit(e,t,o,r,s){if(this.enableResume){const o=this.getCachePermit(e,t);if(o)return this.useCache=!0,Promise.resolve(o)}return this.useCache=!1,this.getToken({bizName:this.bizName,scene:this.scene,fileCount:1,fileFormat:o,persistentOps:r,persistentNotifyUrl:s}).then((({uploadTempPermits:o,uploadLimitPolicy:r})=>{const s=t.type,i=t.size;if(r){const{fileTypes:e,maxSize:t}=r;if((null==e?void 0:e.length)&&!e.reduce(((e,t)=>[...e,...t.split("/")]),[]).some((e=>s.endsWith(e))))throw new Error(`文件类型 ${s} 不在可上传的文件类型 ${e.join(", ")} 中。`);if(void 0!==t&&i>t)throw new Error(`文件尺寸(${i/1048576} mb)超过最大尺寸(${t/1048576} mb)。`)}if(!(null==o?void 0:o.length))throw new Error("token 获取失败。");const[n]=o.sort(((e,t)=>t.qos-e.qos));return this.enableResume&&this.setCachePermit(e,t,n),n}))}post(e){const o=Date.now(),{fileFormat:r,onInstanceCreated:s,...i}=e,n=new d({info:{fileType:e.fileInfo.type,fileSize:e.fileInfo.size,startTime:o}});return this.getPermit(e.Body,e.fileInfo,r).then((r=>{n.setInfo({...n.info,tokenEndTime:Date.now()});const[a]=r.fileIds,c={Domain:r.uploadAddr,getAuthorization(e,t){t({TmpSecretId:r.secretId||"null",TmpSecretKey:r.secretKey||"null",SecurityToken:r.token,StartTime:Math.floor(o/1e3),ExpiredTime:Math.floor(r.expireTime/1e3)})}};"unknown"===r.bucket&&(c.AppId="1251524319");const l=new t(c);return s&&s(l),l.uploadFile({Bucket:r.bucket,Region:r.region,Key:a,...i}).then((t=>{var o,s;const c={...t,bizName:this.bizName,scene:this.scene,cloudType:r.cloudType,fileId:a,useCache:this.useCache};if(r.cdnDomain){const e=`${r.cdnDomain}/${a}`;c.cdnDomain=r.cdnDomain,c.url=e,c.previewUrl=e,c.staticUrl=e}(null==t?void 0:t.headers)&&Object.keys(t.headers).forEach((e=>{var o;if(e.startsWith("x-ros-")){const r=e.split("x-ros-")[1].replace(/\-(\w)/g,(e=>e[1].toUpperCase()));c[r]=null===(o=t.headers)||void 0===o?void 0:o[e]}}));const l={fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:i.SliceSize||1048576,isSlice:e.fileInfo.size>(i.SliceSize||1048576),tokenFail:!1};return(null===(o=null==t?void 0:t.headers)||void 0===o?void 0:o["x-tracer"])&&(l.tracerId=null===(s=t.headers)||void 0===s?void 0:s["x-tracer"]),this.setCachePermit(e.Body,e.fileInfo,null),n.setData(c).log(this,l)})).catch((t=>{var o;return this.enableResume&&!(null===(o=null==t?void 0:t.message)||void 0===o?void 0:o.includes("network error"))&&this.setCachePermit(e.Body,e.fileInfo,null),n.fail().setCode(Number((null==t?void 0:t.code)||-1)).setMsg(null==t?void 0:t.message).log(this,{fileId:a,cloudType:r.cloudType,uploaderAddr:r.uploadAddr,sliceSize:i.SliceSize||1048576,isSlice:e.fileInfo.size>(i.SliceSize||1048576),tokenFail:!1,serverFail:!0})}))})).catch((e=>n.fail().setInfo({...n.info,tokenEndTime:Date.now()}).setMsg(e.message).log(this,{tokenFail:!0})))}},exports.publicCos=w;
1
+ "use strict";var e=require("chalk"),t=require("cos-nodejs-sdk-v5"),o=require("path"),s=require("fs"),r=require("uuid"),i=require("node-fetch"),n=require("child_process"),a=require("os"),c=require("crypto");function l(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(o){if("default"!==o){var s=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(t,o,s.get?s:{enumerable:!0,get:function(){return e[o]}})}})),t.default=e,Object.freeze(t)}var u=l(t);class p{constructor(e){this.prefix=e||"[@xhs-toolkit]",this.verbose=global.verbose}setVerbose(e){this.verbose=e}info(...t){console.info(e.blue(this.prefix),...t)}log(...t){console.log(e.blue(this.prefix),...t)}debug(...t){this.verbose&&console.debug(e.yellow(this.prefix),...t)}warn(...t){this.verbose&&console.warn(e.yellow(this.prefix),...t)}error(...t){console.error(e.red(this.prefix),...t)}}class d{static getLogger(){return window.eaglet.sendApm&&window.eaglet||global.eaglet}constructor({success:e=!0,code:t=0,info:o}){this.success=e,this.code=t,this.info=o}setCode(e){return this.code=e,this}setMsg(e){return this.msg=e,this}setData(e){return this.data=e,this}setInfo(e){return this.info=e,this}fail(){return this.success=!1,this.code=-1,this}log(e,t){var o;try{const s={bizName:e.bizName,scene:e.scene,customerHost:window.location.host,routePath:window.location.pathname,uploadSuccess:this.success,code:this.code,errorMsg:this.msg,successData:JSON.stringify(this.data),fileType:this.info.fileType,fileSize:this.info.fileSize,startTime:d.formatDate(this.info.startTime),endTime:d.formatDate(Date.now()),tokenStartTime:d.formatDate(this.info.startTime),tokenEndTime:d.formatDate(this.info.tokenEndTime||Date.now()),tokenTimestamp:(this.info.tokenEndTime||Date.now())-this.info.startTime,uploadTimestamp:Date.now()-this.info.startTime,...t};s.uploadSuccess&&0!==s.uploadTimestamp&&(s.uploadSpeed=s.fileSize/s.uploadTimestamp);const r=d.getLogger();if(r)r.push({type:"InfraUploader",value:s},"ApmJSONTracker");else{console.warn.bind(console)("[APM Warning]: eaglet is undefined, web app please install @xhs/launcher-plugin-eaglet, react-native app use eaglet plugin from asgard!")}const i=(null===(o=null===window||void 0===window?void 0:window.insight)||void 0===o?void 0:o.sendCustomPoint.bind(null===window||void 0===window?void 0:window.insight))||(null==r?void 0:r.flushApm);i&&(Object.keys(s).forEach((e=>{"boolean"==typeof s[e]&&(s[e]=Number(s[e]))})),i({measurement_name:"infraUploader",measurement_data:s},"ApmXrayTracker"))}finally{return this}}static formatDate(e){return new Date(e).toISOString().replace(/T/," ").replace(/\..+/,"")}}var h;!function(e){e.SECRET_ID="AKIDopc9PQM41h6VeVhqKRIsnRoy77sOe18z",e.SECRET_KEY="kEUTCdR0IOMuBONjlkUO4VgZiaCappql",e.BUCKET_NAME="fe-static",e.APP_ID="1251524319",e.REGION="ap-shanghai",e.HOST="eva-1251524319.cos.ap-shanghai.myqcloud.com",e.FILE_KEY="mp/red/map"}(h||(h={}));const m=new t({SecretId:h.SECRET_ID,SecretKey:h.SECRET_KEY}),f=`${h.BUCKET_NAME}-${h.APP_ID}`,g=(e,t)=>{const s=o.basename(e),r=o.extname(s);if(!r||"."===r)throw new Error(`fileName: '${e}' is not validata, please check extname`);const i=`${`${h.FILE_KEY}`}/${t}/${s}`;return{Bucket:f,Region:h.REGION,Key:i,FilePath:e}},v=async e=>{const t=e.map((({Key:e})=>({Key:e})));try{await m.deleteMultipleObject({Bucket:f,Region:h.REGION,Objects:t})}catch(e){console.log("===== 腾讯云中已存在同名文件,且删除时报错: =====",e)}};var w=Object.freeze({__proto__:null,Bucket:f,deleteExistingFiles:v,qcloudClient:m,upload2Qcloud:async(e,t)=>{if(!e||!e.length)throw new Error("上传地址不能为空!");const o=Array.isArray(e)?e.map((e=>g(e,t))):[g(e,t)];if(!o.every((e=>s.existsSync(e.FilePath))))throw new Error(`上传地址不合法: ${JSON.stringify(o,null,2)}`);return await v(o),await((e,t)=>new Promise(((t,o)=>{m.uploadFiles({files:e,SliceSize:1024,onProgress:e=>{Number(e.speed/1024/1024*100)}},((e,s)=>{e?o(e):t(s)}))})))(o)}});const y={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:"%windir%\\System32\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :"};function S(e){return c.createHash("sha256").update(e).digest("hex")}function b(){var e,t;try{return"darwin"===process.platform?null===(e=n.execSync("sw_vers -productVersion",{encoding:"utf-8"}))||void 0===e?void 0:e.trim():null===(t=a.release())||void 0===t?void 0:t.trim()}catch(e){}return""}function x(){var e,t,o;const s=a.cpus(),r=null==s?void 0:s[0];return{os_platform:(null===(t=null===(e=process.platform)||void 0===e?void 0:e[0])||void 0===t?void 0:t.toUpperCase())+process.platform.slice(1),os_arch:process.arch,cpu_speed:Number(null===(o=1e3*(null==r?void 0:r.speed))||void 0===o?void 0:o.toFixed(0)),cpu_model:null==r?void 0:r.model,machine_memory:Math.round(a.totalmem()/1024/1024),os_version:b()}}const _=x(),T={context_nameTracker:"nodeT",context_platform:_.os_platform,context_appVersion:"",context_osVersion:_.os_version,context_deviceModel:"",context_deviceId:function(){try{return function(e){switch(process.platform){case"darwin":return e.split("IOPlatformUUID")[1].split("\n")[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return e.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return e.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error(`Unsupported platform: ${process.platform}`)}}(n.execSync(y[process.platform]).toString())}catch(e){}return JSON.stringify({...x(),login_user:S(a.userInfo().username||process.env.username),node_version:process.version})}(),context_package:"",context_networkType:"unknow",context_matchedPath:"cli",context_route:"xhsmp://cli",context_userAgent:[`Node/${process.version}`,`${_.os_platform}/${_.os_version} (${_.cpu_model}; ${_.cpu_speed}mhz; ${_.machine_memory}mb)`].join(" "),context_artifactName:"miniprogram",context_networkQuality:"UNKNOWN",context_artifactVersion:"UNKNOWN",context_userId:""},k="https://apm-fe.xiaohongshu.com/api/data";var E,I,N,O,C,D,P;exports.FeatureReporter=void 0,E=exports.FeatureReporter||(exports.FeatureReporter={}),(I=E.MODULE||(E.MODULE={})).appJSON="json-app",I.extJSON="json-ext",I.componentJSON="json-component",I.pageJSON="json-page",I.ml="ml",I.thirdFramework="third-framework",I.developMode="develop-mode",(N=E.AppExtJSON||(E.AppExtJSON={})).pages="pages",N.subpackages="subpackages",N.subPackages="subPackages",N.lazyCodeLoading="lazyCodeLoading",N.tabBar="tabBar",N.preloadRule="preloadRule",N.usingComponents="usingComponents",N.extPages="extPages",(O=E.ComponentJSON||(E.ComponentJSON={})).styleIsolation="styleIsolation",O.componentPlaceholder="componentPlaceholder",(E.PageJSON||(E.PageJSON={})).skeleton="skeleton",(C=E.ML||(E.ML={})).WebComponent="web-component",C.animation="animation",C.template="template",C.sjs="sjs",(D=E.ThirdFramework||(E.ThirdFramework={})).taroReact="taro-react",D.taroVue="taro-vue",D.taro="taro",D.uniapp3="uniapp3",D.uniapp2="uniapp2",D.weimeng="weimeng",(P=E.DevelopMode||(E.DevelopMode={})).customDevelopment="custom-development",P.templateDevelopment="template-development",exports.COS=u,exports.APM=class{constructor(e){this.reportQueue=[],this.allowReport=!1,this.eventSeq=1,this.context={...T},this.baseData={},this.logger=new p("[apm]: "),this.timer=null,this.context.context_appVersion=e}setContext(e,t={}){this.context={...this.context,context_userId:e},this.baseData=t,this.startReport()}startReport(){this.allowReport=!0,this.bactchReport()}getSequence(){return{context_sdkSeqId:this.eventSeq++,context_sdkSessionId:r.v4(),context_pageSessionId:r.v4(),clientTime:Date.now()}}_request(e,t=!0){var o;const s=(Array.isArray(e)?e:[e]).map((e=>({...this.context,...e.suquence,measurement_name:e.measurement_name,measurement_data:{...this.baseData,...e.measurement_data}})));return null===(o=this.logger)||void 0===o||o.debug("apm before send",`${JSON.stringify(s)}`,"warning"),i(k,{method:"post",body:JSON.stringify(s),headers:{accept:"*/*","accept-language":"zh-CN,zh;q=0.9",batch:"true","biz-type":"apm_fe","cache-control":"no-cache","content-type":"application/json",pragma:"no-cache"}}).then((e=>e.json())).then((e=>{var t;if(!(null==e?void 0:e.success))throw new Error(null==e?void 0:e.msg);null===(t=this.logger)||void 0===t||t.debug("apm send success","")})).catch((e=>{var o;t&&setTimeout((()=>this._request(s,!1)),1e3),null===(o=this.logger)||void 0===o||o.log("apm send failed",`${(null==e?void 0:e.message)||null}`,"error")}))}bactchReport(){const e=[...this.reportQueue];for(this.reportQueue=[];e.length;)this._request(e.splice(0,5))}report(e,t={}){const o={suquence:this.getSequence(),measurement_name:e,measurement_data:t};this.reportQueue.push(o),clearTimeout(this.timer),this.allowReport&&(this.reportQueue.length>=10?this.bactchReport():this.timer=setTimeout((()=>{this.bactchReport()}),500))}},exports.Logger=p,exports.Uploader=class{constructor(e){this.useCache=!1,this.bizName=e.bizName,this.scene=e.scene,this.getToken=e.getToken,this.enableResume=e.enableResume}get cacheKey(){return`uploader-permit-${this.scene}-${this.bizName}`}getCachePermit(e,t){try{const o=`${t.name}-${t.size}`,s=localStorage.getItem(this.cacheKey);if(!s)return null;const r=JSON.parse(s)[o];return r?r.expireTime-12e4<Date.now()?(this.setCachePermit(e,t,null),null):r:null}catch(e){return localStorage.setItem(this.cacheKey,""),null}}setCachePermit(e,t,o){try{const e=`${t.name}-${t.size}`,s=localStorage.getItem(this.cacheKey),r=s?JSON.parse(s):{};r[e]=o,localStorage.setItem(this.cacheKey,JSON.stringify(r))}catch(e){}}getPermit(e,t,o,s,r){if(this.enableResume){const o=this.getCachePermit(e,t);if(o)return this.useCache=!0,Promise.resolve(o)}return this.useCache=!1,this.getToken({bizName:this.bizName,scene:this.scene,fileCount:1,fileFormat:o,persistentOps:s,persistentNotifyUrl:r}).then((({uploadTempPermits:o,uploadLimitPolicy:s})=>{const r=t.type,i=t.size;if(s){const{fileTypes:e,maxSize:t}=s;if((null==e?void 0:e.length)&&!e.reduce(((e,t)=>[...e,...t.split("/")]),[]).some((e=>r.endsWith(e))))throw new Error(`文件类型 ${r} 不在可上传的文件类型 ${e.join(", ")} 中。`);if(void 0!==t&&i>t)throw new Error(`文件尺寸(${i/1048576} mb)超过最大尺寸(${t/1048576} mb)。`)}if(!(null==o?void 0:o.length))throw new Error("token 获取失败。");const[n]=o.sort(((e,t)=>t.qos-e.qos));return this.enableResume&&this.setCachePermit(e,t,n),n}))}post(e){const o=Date.now(),{fileFormat:s,onInstanceCreated:r,...i}=e,n=new d({info:{fileType:e.fileInfo.type,fileSize:e.fileInfo.size,startTime:o}});return this.getPermit(e.Body,e.fileInfo,s).then((s=>{n.setInfo({...n.info,tokenEndTime:Date.now()});const[a]=s.fileIds,c={Domain:s.uploadAddr,getAuthorization(e,t){t({TmpSecretId:s.secretId||"null",TmpSecretKey:s.secretKey||"null",SecurityToken:s.token,StartTime:Math.floor(o/1e3),ExpiredTime:Math.floor(s.expireTime/1e3)})}};"unknown"===s.bucket&&(c.AppId="1251524319");const l=new t(c);return r&&r(l),l.uploadFile({Bucket:s.bucket,Region:s.region,Key:a,...i}).then((t=>{var o,r;const c={...t,bizName:this.bizName,scene:this.scene,cloudType:s.cloudType,fileId:a,useCache:this.useCache};if(s.cdnDomain){const e=`${s.cdnDomain}/${a}`;c.cdnDomain=s.cdnDomain,c.url=e,c.previewUrl=e,c.staticUrl=e}(null==t?void 0:t.headers)&&Object.keys(t.headers).forEach((e=>{var o;if(e.startsWith("x-ros-")){const s=e.split("x-ros-")[1].replace(/\-(\w)/g,(e=>e[1].toUpperCase()));c[s]=null===(o=t.headers)||void 0===o?void 0:o[e]}}));const l={fileId:a,cloudType:s.cloudType,uploaderAddr:s.uploadAddr,sliceSize:i.SliceSize||1048576,isSlice:e.fileInfo.size>(i.SliceSize||1048576),tokenFail:!1};return(null===(o=null==t?void 0:t.headers)||void 0===o?void 0:o["x-tracer"])&&(l.tracerId=null===(r=t.headers)||void 0===r?void 0:r["x-tracer"]),this.setCachePermit(e.Body,e.fileInfo,null),n.setData(c).log(this,l)})).catch((t=>{var o;return this.enableResume&&!(null===(o=null==t?void 0:t.message)||void 0===o?void 0:o.includes("network error"))&&this.setCachePermit(e.Body,e.fileInfo,null),n.fail().setCode(Number((null==t?void 0:t.code)||-1)).setMsg(null==t?void 0:t.message).log(this,{fileId:a,cloudType:s.cloudType,uploaderAddr:s.uploadAddr,sliceSize:i.SliceSize||1048576,isSlice:e.fileInfo.size>(i.SliceSize||1048576),tokenFail:!1,serverFail:!0})}))})).catch((e=>n.fail().setInfo({...n.info,tokenEndTime:Date.now()}).setMsg(e.message).log(this,{tokenFail:!0})))}},exports.publicCos=w;
@@ -3,6 +3,7 @@ export declare namespace FeatureReporter {
3
3
  appJSON = "json-app",
4
4
  extJSON = "json-ext",
5
5
  componentJSON = "json-component",
6
+ pageJSON = "json-page",
6
7
  ml = "ml",
7
8
  thirdFramework = "third-framework",
8
9
  developMode = "develop-mode"
@@ -17,10 +18,13 @@ export declare namespace FeatureReporter {
17
18
  usingComponents = "usingComponents",
18
19
  extPages = "extPages"
19
20
  }
20
- enum JSONComponent {
21
+ enum ComponentJSON {
21
22
  styleIsolation = "styleIsolation",
22
23
  componentPlaceholder = "componentPlaceholder"
23
24
  }
25
+ enum PageJSON {
26
+ skeleton = "skeleton"
27
+ }
24
28
  enum ML {
25
29
  WebComponent = "web-component",
26
30
  animation = "animation",
@@ -41,12 +45,12 @@ export declare namespace FeatureReporter {
41
45
  }
42
46
  interface IReporter {
43
47
  reportThirdFramework: (a: ThirdFramework) => void;
48
+ reportDevelopMode: (a: DevelopMode) => void;
44
49
  reportMlFeature: (a: ML) => void;
45
50
  reportMlWebComponent: (a: string) => void;
46
- reportJSONComponent: (a: JSONComponent) => void;
47
- reportStyleIsolation: (a: string) => void;
48
- reportAppJSON: (a: AppExtJSON) => void;
49
- reportExtJSON: (a: AppExtJSON) => void;
50
- reportDevelopMode: (a: DevelopMode) => void;
51
+ reportComponentJSON: (a: ComponentJSON, value?: unknown) => void;
52
+ reportPageJSON: (a: PageJSON, value?: unknown) => void;
53
+ reportAppJSON: (a: AppExtJSON, value?: unknown) => void;
54
+ reportExtJSON: (a: AppExtJSON, value?: unknown) => void;
51
55
  }
52
56
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "xhs-mp-shared",
3
- "version": "2.0.4-beta.3",
3
+ "version": "2.0.4",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",