"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("crypto");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("path"),require("fs");var r=t(e);class s extends Error{constructor(e){super(e.message),this.errMsg=e.message||"",this.code=this.errCode=e.code,this.errSubject=e.subject,this.forceReturn=e.forceReturn||!1,this.cause=e.cause,Object.defineProperties(this,{message:{get(){return this.errMsg},set(e){this.errMsg=e}}})}toJSON(e=0){if(!(e>=10))return e++,{errCode:this.errCode,errMsg:this.errMsg,errSubject:this.errSubject,cause:this.cause&&this.cause.toJSON?this.cause.toJSON(e):this.cause}}}const n=Object.prototype.toString,o=Object.prototype.hasOwnProperty;function c(e){return n.call(e).slice(8,-1).toLowerCase()}function a(e,t){return new Error(e.replace("%err%",t))}function i(e){const{param:t,rule:r,errTpl:s="%err%",paramPath:n=""}=e||{};Object.keys(r).forEach((e=>{if(!function(e,t){return o.call(e,t)}(t,e))throw a(s,`缺少参数${n}${e}`);if(!t[e]&&!1!==t[e]&&0!==t[e])throw a(s,`参数${n}${e}值不可为空`);if("object"===c(r[e]))i({param:t[e],rule:r[e],errTpl:s,paramPath:`${e}.`});else{const o=c(t[e]);if(-1===r[e].indexOf(o))throw a(s,`参数${n}${e}类型不正确，期望传入类型${r[e].join("、")}，实际传入${o}`)}}))}function u(){return JSON.parse(process.env.UNICLOUD_SERVICE_SECRET||"{}")}async function d(e,t){let r;try{r=await uniCloud.httpclient.request(e,{method:"POST",data:t,contentType:"json",dataType:"text",followRedirect:!0,timeout:6e4})}catch(e){if("ResponseTimeoutError"===e.name)return{code:999,message:"service timeout"};throw e.message=e.message.replace(/https?:\/\/(.*).dcloud.net.cn/,(function(e,t){return`service[${t}]`})),e}if(r.status>=400)return{code:r.status,message:r.data||"service error"};const s=JSON.parse(r.data);return s.ret?{code:s.ret,message:s.desc}:(delete s.ret,delete s.desc,s)}const p=Object.create(null);function l(e,t,r){throw new s({subject:"uni-cloud-sms",code:e,message:t,cause:r})}function f(e){"string"==typeof e&&/^(0|17951|86|\+86)?(1\d{10})$/.test(e)||l(h.INVALID_PARAM,"手机号格式不正确，仅支持中国大陆手机号")}["string","boolean","number","null"].forEach((e=>{p[e]=function(t){return c(t)===e}}));const h={INVALID_PARAM:1001};async function m(e){const t={templateId:["string"],data:["object"]};try{i({param:e,rule:t,errTpl:"sendSms%err%"})}catch(e){l(h.INVALID_PARAM,e.message)}const n=uniCloud.getCloudInfos()[0],o=e.appid||global.__ctx__.APPID||void 0,c=function(e){const{provider:t,spaceId:r,useOldSpaceId:s}=e||{};return"aliyun"!==t||!0!==s||r.startsWith("mp-")?r:"mp-"+r}(n),a=function(e){switch(e){case"tcb":case"tencent":return"tcb";default:return e}}(n.provider),p=Date.now(),{smsKey:m,smsSecret:g,templateId:y,data:b,phone:I,phoneList:O}=e;if(I)f(I);else if(O)for(let e=0;e<O.length;e++)f(O[e]);else l(h.INVALID_PARAM,"手机号格式不正确，请传入phone或phoneList参数");const j=Object.keys(b).reduce(((e,t)=>e+b[t]),"");/【|】/.test(j)&&l(h.INVALID_PARAM,"为避免与签名混淆，短信内容不可包含“【】”符号"),/(测试|test)/i.test(j)&&console.warn("短信内容包含“测试”、“test”字样时，系统可能会被判定为测试用途，不会真正把短信下发到对应手机（此行为由运营商控制，可能真实发送，也可能不发送）");const S={appid:o,templateId:y,timestamp:p,spaceId:c,provider:a,params:JSON.stringify(b)};let w;if(m||g)S.apiKey=m,w=g;else{const{secretKeyId:e,secretKey:t}=u()||{};S.keyId=e,w=t}I?S.phone=I:O&&(S.phoneList=O.filter(((e,t)=>O.indexOf(e)===t)).join(","));const A=function(e,t){const s=Object.keys(e).sort().filter((function(t){return void 0!==e[t]})).map((t=>`${t}=${""+e[t]}`));s.push(`apiSecret=${t}`);const n=r.default.createHash("md5");return n.update(s.join("&")),n.digest("hex").toLowerCase()}(S,w);let $;$=I?"/http/unisms/api/sendSms":"/http/unisms/api/batchSendSms";const P=["ucoasmsbk.dcloud.net.cn"].map((e=>`https://${e}${$}`)),v=await async function(e,t){let r=null;const s=e.length,n=Math.floor(Math.random()*s);let o=0;for(;!r;){const c=e[(n+o)%s];r=await d(c,t),r.code<600&&r.code>=400&&o<e.length-1&&(r=null),o++}return r}(P,{...S,sign:A});if(!v.code)return{code:0,errCode:0,success:!0};v.code>=400&&v.code<1e3&&l(6e4,"service error",new s(v)),l(v.code,v.message)}function g(){Object.getPrototypeOf(uniCloud).sendSms=m}g(),exports.init=g;