@neuctra/authix 3.0.0 → 3.0.1
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.
|
@@ -1787,14 +1787,14 @@ class an {
|
|
|
1787
1787
|
*/
|
|
1788
1788
|
async request(e, r, n, s = {}, i = !1) {
|
|
1789
1789
|
try {
|
|
1790
|
-
const o = {
|
|
1790
|
+
const o = e.toUpperCase(), c = o === "GET" || o === "HEAD" ? void 0 : {
|
|
1791
1791
|
...this.appId ? { appId: this.appId } : {},
|
|
1792
1792
|
...n || {}
|
|
1793
1793
|
};
|
|
1794
1794
|
return (await this.client.request({
|
|
1795
1795
|
url: r,
|
|
1796
1796
|
method: e,
|
|
1797
|
-
data:
|
|
1797
|
+
data: c,
|
|
1798
1798
|
headers: s,
|
|
1799
1799
|
withCredentials: i
|
|
1800
1800
|
// 👈 override axios default
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){const n=new this(e);return r.forEach(s=>n.set(s)),n}static accessor(e){const n=(this[Me]=this[Me]={accessors:{}}).accessors,s=this.prototype;function i(o){const c=G(o);n[c]||(mr(s,o),n[c]=!0)}return a.isArray(e)?e.forEach(i):i(e),this}};T.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),a.reduceDescriptors(T.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}}),a.freezeMethods(T);function ye(t,e){const r=this||W,n=e||r,s=T.from(n.headers);let i=n.data;return a.forEach(t,function(c){i=c.call(r,i,s.normalize(),e?e.status:void 0)}),s.normalize(),i}function He(t){return!!(t&&t.__CANCEL__)}function v(t,e,r){w.call(this,t??"canceled",w.ERR_CANCELED,e,r),this.name="CanceledError"}a.inherits(v,w,{__CANCEL__:!0});function ve(t,e,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new w("Request failed with status code "+r.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function wr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function yr(t,e){t=t||10;const r=new Array(t),n=new Array(t);let s=0,i=0,o;return e=e!==void 0?e:1e3,function(l){const u=Date.now(),d=n[i];o||(o=u),r[s]=l,n[s]=u;let h=i,y=0;for(;h!==s;)y+=r[h++],h=h%t;if(s=(s+1)%t,s===i&&(i=(i+1)%t),u-o<e)return;const R=d&&u-d;return R?Math.round(y*1e3/R):void 0}}function Er(t,e){let r=0,n=1e3/e,s,i;const o=(u,d=Date.now())=>{r=d,s=null,i&&(clearTimeout(i),i=null),t(...u)};return[(...u)=>{const d=Date.now(),h=d-r;h>=n?o(u,d):(s=u,i||(i=setTimeout(()=>{i=null,o(s)},n-h)))},()=>s&&o(s)]}const ne=(t,e,r=3)=>{let n=0;const s=yr(50,250);return Er(i=>{const o=i.loaded,c=i.lengthComputable?i.total:void 0,l=o-n,u=s(l),d=o<=c;n=o;const h={loaded:o,total:c,progress:c?o/c:void 0,bytes:l,rate:u||void 0,estimated:u&&c&&d?(c-o)/u:void 0,event:i,lengthComputable:c!=null,[e?"download":"upload"]:!0};t(h)},r)},ze=(t,e)=>{const r=t!=null;return[n=>e[0]({lengthComputable:r,total:t,loaded:n}),e[1]]},Ve=t=>(...e)=>a.asap(()=>t(...e)),gr=S.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,S.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(S.origin),S.navigator&&/(msie|trident)/i.test(S.navigator.userAgent)):()=>!0,br=S.hasStandardBrowserEnv?{write(t,e,r,n,s,i){const o=[t+"="+encodeURIComponent(e)];a.isNumber(r)&&o.push("expires="+new Date(r).toGMTString()),a.isString(n)&&o.push("path="+n),a.isString(s)&&o.push("domain="+s),i===!0&&o.push("secure"),document.cookie=o.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sr(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Rr(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Je(t,e,r){let n=!Sr(e);return t&&(n||r==!1)?Rr(t,e):e}const Ke=t=>t instanceof T?{...t}:t;function _(t,e){e=e||{};const r={};function n(u,d,h,y){return a.isPlainObject(u)&&a.isPlainObject(d)?a.merge.call({caseless:y},u,d):a.isPlainObject(d)?a.merge({},d):a.isArray(d)?d.slice():d}function s(u,d,h,y){if(a.isUndefined(d)){if(!a.isUndefined(u))return n(void 0,u,h,y)}else return n(u,d,h,y)}function i(u,d){if(!a.isUndefined(d))return n(void 0,d)}function o(u,d){if(a.isUndefined(d)){if(!a.isUndefined(u))return n(void 0,u)}else return n(void 0,d)}function c(u,d,h){if(h in e)return n(u,d);if(h in t)return n(void 0,u)}const l={url:i,method:i,data:i,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(u,d,h)=>s(Ke(u),Ke(d),h,!0)};return a.forEach(Object.keys({...t,...e}),function(d){const h=l[d]||s,y=h(t[d],e[d],d);a.isUndefined(y)&&h!==c||(r[d]=y)}),r}const We=t=>{const e=_({},t);let{data:r,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:i,headers:o,auth:c}=e;if(e.headers=o=T.from(o),e.url=Le(Je(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),a.isFormData(r)){if(S.hasStandardBrowserEnv||S.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if(a.isFunction(r.getHeaders)){const l=r.getHeaders(),u=["content-type","content-length"];Object.entries(l).forEach(([d,h])=>{u.includes(d.toLowerCase())&&o.set(d,h)})}}if(S.hasStandardBrowserEnv&&(n&&a.isFunction(n)&&(n=n(e)),n||n!==!1&&gr(e.url))){const l=s&&i&&br.read(i);l&&o.set(s,l)}return e},Ar=typeof XMLHttpRequest<"u"&&function(t){return new Promise(function(r,n){const s=We(t);let i=s.data;const o=T.from(s.headers).normalize();let{responseType:c,onUploadProgress:l,onDownloadProgress:u}=s,d,h,y,R,f;function m(){R&&R(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(d),s.signal&&s.signal.removeEventListener("abort",d)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function g(){if(!p)return;const b=T.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),q={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:b,config:t,request:p};ve(function(U){r(U),m()},function(U){n(U),m()},q),p=null}"onloadend"in p?p.onloadend=g:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(g)},p.onabort=function(){p&&(n(new w("Request aborted",w.ECONNABORTED,t,p)),p=null)},p.onerror=function(O){const q=O&&O.message?O.message:"Network Error",L=new w(q,w.ERR_NETWORK,t,p);L.event=O||null,n(L),p=null},p.ontimeout=function(){let O=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const q=s.transitional||Be;s.timeoutErrorMessage&&(O=s.timeoutErrorMessage),n(new w(O,q.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,p)),p=null},i===void 0&&o.setContentType(null),"setRequestHeader"in p&&a.forEach(o.toJSON(),function(O,q){p.setRequestHeader(q,O)}),a.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),c&&c!=="json"&&(p.responseType=s.responseType),u&&([y,f]=ne(u,!0),p.addEventListener("progress",y)),l&&p.upload&&([h,R]=ne(l),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",R)),(s.cancelToken||s.signal)&&(d=b=>{p&&(n(!b||b.type?new v(null,t,p):b),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(d),s.signal&&(s.signal.aborted?d():s.signal.addEventListener("abort",d)));const I=wr(s.url);if(I&&S.protocols.indexOf(I)===-1){n(new w("Unsupported protocol "+I+":",w.ERR_BAD_REQUEST,t));return}p.send(i||null)})},Tr=(t,e)=>{const{length:r}=t=t?t.filter(Boolean):[];if(e||r){let n=new AbortController,s;const i=function(u){if(!s){s=!0,c();const d=u instanceof Error?u:this.reason;n.abort(d instanceof w?d:new v(d instanceof Error?d.message:d))}};let o=e&&setTimeout(()=>{o=null,i(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const c=()=>{t&&(o&&clearTimeout(o),o=null,t.forEach(u=>{u.unsubscribe?u.unsubscribe(i):u.removeEventListener("abort",i)}),t=null)};t.forEach(u=>u.addEventListener("abort",i));const{signal:l}=n;return l.unsubscribe=()=>a.asap(c),l}},Or=function*(t,e){let r=t.byteLength;if(r<e){yield t;return}let n=0,s;for(;n<r;)s=n+e,yield t.slice(n,s),n=s},Ir=async function*(t,e){for await(const r of Ur(t))yield*Or(r,e)},Ur=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:r,value:n}=await e.read();if(r)break;yield n}}finally{await e.cancel()}},Ge=(t,e,r,n)=>{const s=Ir(t,e);let i=0,o,c=l=>{o||(o=!0,n&&n(l))};return new ReadableStream({async pull(l){try{const{done:u,value:d}=await s.next();if(u){c(),l.close();return}let h=d.byteLength;if(r){let y=i+=h;r(y)}l.enqueue(new Uint8Array(d))}catch(u){throw c(u),u}},cancel(l){return c(l),s.return()}},{highWaterMark:2})},Xe=64*1024,{isFunction:se}=a,Cr=(({Request:t,Response:e})=>({Request:t,Response:e}))(a.global),{ReadableStream:Qe,TextEncoder:Ze}=a.global,Ye=(t,...e)=>{try{return!!t(...e)}catch{return!1}},qr=t=>{t=a.merge.call({skipUndefined:!0},Cr,t);const{fetch:e,Request:r,Response:n}=t,s=e?se(e):typeof fetch=="function",i=se(r),o=se(n);if(!s)return!1;const c=s&&se(Qe),l=s&&(typeof Ze=="function"?(f=>m=>f.encode(m))(new Ze):async f=>new Uint8Array(await new r(f).arrayBuffer())),u=i&&c&&Ye(()=>{let f=!1;const m=new r(S.origin,{body:new Qe,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),d=o&&c&&Ye(()=>a.isReadableStream(new n("").body)),h={stream:d&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let g=m&&m[f];if(g)return g.call(m);throw new w(`Response type '${f}' is not supported`,w.ERR_NOT_SUPPORT,p)})});const y=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new r(S.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await l(f)).byteLength},R=async(f,m)=>{const p=a.toFiniteNumber(f.getContentLength());return p??y(m)};return async f=>{let{url:m,method:p,data:g,signal:I,cancelToken:b,timeout:O,onDownloadProgress:q,onUploadProgress:L,responseType:U,headers:Se,withCredentials:ae="same-origin",fetchOptions:at}=We(f),ct=e||fetch;U=U?(U+"").toLowerCase():"text";let ce=Tr([I,b&&b.toAbortSignal()],O),X=null;const $=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let ut;try{if(L&&u&&p!=="get"&&p!=="head"&&(ut=await R(Se,g))!==0){let N=new r(m,{method:"POST",body:g,duplex:"half"}),z;if(a.isFormData(g)&&(z=N.headers.get("content-type"))&&Se.setContentType(z),N.body){const[Re,ue]=ze(ut,ne(Ve(L)));g=Ge(N.body,Xe,Re,ue)}}a.isString(ae)||(ae=ae?"include":"omit");const x=i&&"credentials"in r.prototype,lt={...at,signal:ce,method:p.toUpperCase(),headers:Se.normalize().toJSON(),body:g,duplex:"half",credentials:x?ae:void 0};X=i&&new r(m,lt);let D=await(i?ct(X,at):ct(m,lt));const dt=d&&(U==="stream"||U==="response");if(d&&(q||dt&&$)){const N={};["status","statusText","headers"].forEach(ft=>{N[ft]=D[ft]});const z=a.toFiniteNumber(D.headers.get("content-length")),[Re,ue]=q&&ze(z,ne(Ve(q),!0))||[];D=new n(Ge(D.body,Xe,Re,()=>{ue&&ue(),$&&$()}),N)}U=U||"text";let Lr=await h[a.findKey(h,U)||"text"](D,f);return!dt&&$&&$(),await new Promise((N,z)=>{ve(N,z,{data:Lr,headers:T.from(D.headers),status:D.status,statusText:D.statusText,config:f,request:X})})}catch(x){throw $&&$(),x&&x.name==="TypeError"&&/Load failed|fetch/i.test(x.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,f,X),{cause:x.cause||x}):w.from(x,x&&x.code,f,X)}}},Pr=new Map,et=t=>{let e=t?t.env:{};const{fetch:r,Request:n,Response:s}=e,i=[n,s,r];let o=i.length,c=o,l,u,d=Pr;for(;c--;)l=i[c],u=d.get(l),u===void 0&&d.set(l,u=c?new Map:qr(e)),d=u;return u};et();const Ee={http:Zt,xhr:Ar,fetch:{get:et}};a.forEach(Ee,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const tt=t=>`- ${t}`,xr=t=>a.isFunction(t)||t===null||t===!1,rt={getAdapter:(t,e)=>{t=a.isArray(t)?t:[t];const{length:r}=t;let n,s;const i={};for(let o=0;o<r;o++){n=t[o];let c;if(s=n,!xr(n)&&(s=Ee[(c=String(n)).toLowerCase()],s===void 0))throw new w(`Unknown adapter '${c}'`);if(s&&(a.isFunction(s)||(s=s.get(e))))break;i[c||"#"+o]=s}if(!s){const o=Object.entries(i).map(([l,u])=>`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let c=r?o.length>1?`since :
|
|
4
4
|
`+o.map(tt).join(`
|
|
5
5
|
`):" "+tt(o[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s},adapters:Ee};function ge(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new v(null,t)}function nt(t){return ge(t),t.headers=T.from(t.headers),t.data=ye.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),rt.getAdapter(t.adapter||W.adapter,t)(t).then(function(n){return ge(t),n.data=ye.call(t,t.transformResponse,n),n.headers=T.from(n.headers),n},function(n){return He(n)||(ge(t),n&&n.response&&(n.response.data=ye.call(t,t.transformResponse,n.response),n.response.headers=T.from(n.response.headers))),Promise.reject(n)})}const st="1.12.2",oe={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{oe[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const ot={};oe.transitional=function(e,r,n){function s(i,o){return"[Axios v"+st+"] Transitional option '"+i+"'"+o+(n?". "+n:"")}return(i,o,c)=>{if(e===!1)throw new w(s(o," has been removed"+(r?" in "+r:"")),w.ERR_DEPRECATED);return r&&!ot[o]&&(ot[o]=!0,console.warn(s(o," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(i,o,c):!0}},oe.spelling=function(e){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Dr(t,e,r){if(typeof t!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let s=n.length;for(;s-- >0;){const i=n[s],o=e[i];if(o){const c=t[i],l=c===void 0||o(c,i,t);if(l!==!0)throw new w("option "+i+" must be "+l,w.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new w("Unknown option "+i,w.ERR_BAD_OPTION)}}const ie={assertOptions:Dr,validators:oe},P=ie.validators;let k=class{constructor(e){this.defaults=e||{},this.interceptors={request:new $e,response:new $e}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const i=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?i&&!String(n.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(n.stack+=`
|
|
6
|
-
`+i):n.stack=i}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=_(this.defaults,r);const{transitional:n,paramsSerializer:s,headers:i}=r;n!==void 0&&ie.assertOptions(n,{silentJSONParsing:P.transitional(P.boolean),forcedJSONParsing:P.transitional(P.boolean),clarifyTimeoutError:P.transitional(P.boolean)},!1),s!=null&&(a.isFunction(s)?r.paramsSerializer={serialize:s}:ie.assertOptions(s,{encode:P.function,serialize:P.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ie.assertOptions(r,{baseUrl:P.spelling("baseURL"),withXsrfToken:P.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=i&&a.merge(i.common,i[r.method]);i&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),r.headers=T.concat(o,i);const c=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(r)===!1||(l=l&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let d,h=0,y;if(!l){const f=[nt.bind(this),void 0];for(f.unshift(...c),f.push(...u),y=f.length,d=Promise.resolve(r);h<y;)d=d.then(f[h++],f[h++]);return d}y=c.length;let R=r;for(;h<y;){const f=c[h++],m=c[h++];try{R=f(R)}catch(p){m.call(this,p);break}}try{d=nt.call(this,R)}catch(f){return Promise.reject(f)}for(h=0,y=u.length;h<y;)d=d.then(u[h++],u[h++]);return d}getUri(e){e=_(this.defaults,e);const r=Je(e.baseURL,e.url,e.allowAbsoluteUrls);return Le(r,e.params,e.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(e){k.prototype[e]=function(r,n){return this.request(_(n||{},{method:e,url:r,data:(n||{}).data}))}}),a.forEach(["post","put","patch"],function(e){function r(n){return function(i,o,c){return this.request(_(c||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}k.prototype[e]=r(),k.prototype[e+"Form"]=r(!0)});let Nr=class pt{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(i){r=i});const n=this;this.promise.then(s=>{if(!n._listeners)return;let i=n._listeners.length;for(;i-- >0;)n._listeners[i](s);n._listeners=null}),this.promise.then=s=>{let i;const o=new Promise(c=>{n.subscribe(c),i=c}).then(s);return o.cancel=function(){n.unsubscribe(i)},o},e(function(i,o,c){n.reason||(n.reason=new v(i,o,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new pt(function(s){e=s}),cancel:e}}};function Fr(t){return function(r){return t.apply(null,r)}}function _r(t){return a.isObject(t)&&t.isAxiosError===!0}const be={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(be).forEach(([t,e])=>{be[e]=t});function it(t){const e=new k(t),r=j(k.prototype.request,e);return a.extend(r,k.prototype,e,{allOwnKeys:!0}),a.extend(r,e,null,{allOwnKeys:!0}),r.create=function(s){return it(_(t,s))},r}const E=it(W);E.Axios=k,E.CanceledError=v,E.CancelToken=Nr,E.isCancel=He,E.VERSION=st,E.toFormData=te,E.AxiosError=w,E.Cancel=E.CanceledError,E.all=function(e){return Promise.all(e)},E.spread=Fr,E.isAxiosError=_r,E.mergeConfig=_,E.AxiosHeaders=T,E.formToJSON=t=>je(a.isHTMLForm(t)?new FormData(t):t),E.getAdapter=rt.getAdapter,E.HttpStatusCode=be,E.default=E;const{Axios:zr,AxiosError:Vr,CanceledError:Jr,isCancel:Kr,CancelToken:Wr,VERSION:Gr,all:Xr,Cancel:Qr,isAxiosError:Zr,spread:Yr,toFormData:en,AxiosHeaders:tn,HttpStatusCode:rn,formToJSON:nn,getAdapter:sn,mergeConfig:on}=E;class kr{appName;baseUrl;apiKey;appId;client;constructor(e){if(!e||!e.baseUrl)throw new Error("NeuctraAuthix: 'baseUrl' is required in config");const r=e.apiKey;if(!r)throw new Error("NeuctraAuthix: 'apiKey' is required in config");this.appName=e.appName,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=r,this.appId=e.appId||null,this.client=E.create({baseURL:this.baseUrl,headers:{"Content-Type":"application/json","x-api-key":r},timeout:3e4,withCredentials:!0})}async request(e,r,n,s={},i=!1){try{const o={...this.appId?{appId:this.appId}:{},...n||{}};return(await this.client.request({url:r,method:e,data:o,headers:s,withCredentials:i})).data}catch(o){if(E.isAxiosError(o)){const c=o.response?.status??0,l=o.response?.data;let u=l?.message||o.message||"Request failed";throw c===403&&l?.code==="INSUFFICIENT_SCOPE"&&(u=`${u} (called "${r}" with an API key). This endpoint needs an API key — call it from your server, not from client code.`),c===401&&l?.code==="NO_USER_SESSION"&&(u=`${u} Sign the user in with loginUser() first — this endpoint acts on the signed-in user's own data.`),c===409&&l?.code==="VERSION_CONFLICT"?{message:`${u} Re-read the record to get its current version, then retry the update.`,status:c,code:"VERSION_CONFLICT",isConflict:!0,currentVersion:l?.currentVersion,expectedVersion:l?.expectedVersion}:c===429?{message:u,status:c,code:l?.code||"RATE_LIMITED",isRateLimited:!0,resetDate:l?.resetDate}:{message:u,status:c,code:l?.code}}throw{message:o.message||"Unexpected error occurred"}}}async signupUser(e){const{name:r,email:n,password:s}=e;if(!r||!n||!s)throw new Error("signup: 'name', 'email', and 'password' are required");return await this.request("POST","/users/signup",e,{},!0)}async loginUser(e){const{email:r,password:n}=e;if(!r||!n)throw new Error("login: 'email' and 'password' are required");try{return await this.request("POST","/users/login",{email:r,password:n},{},!0)}catch(s){throw new Error(s.message||"Login failed due to an unknown error")}}async logoutUser(){try{return(await this.request("POST","/users/logout",{},{},!0))?.success?(typeof window<"u"&&(document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax",window.location.protocol==="https:"&&(document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax; Secure"),window.location.reload()),{success:!0}):{success:!1}}catch(e){throw new Error(e?.message||"Logout failed due to an unknown error")}}async changePassword(e){const{userId:r,currentPassword:n,newPassword:s}=e;if(!r)throw new Error("changePassword: 'userId' is required");if(!n||!s)throw new Error("changePassword: both 'currentPassword' and 'newPassword' are required");return await this.request("PUT",`/users/change-password/${r}`,{currentPassword:n,newPassword:s},{},!0)}async requestEmailVerificationOTP(e){const{userId:r,email:n}=e;if(!r)throw{message:"requestEmailVerificationOTP: 'userId' is required",status:400};if(!n)throw{message:"requestEmailVerificationOTP: 'email' is required",status:400};try{return await this.request("POST",`/users/send-verify-otp/${encodeURIComponent(r)}`,{email:n},{},!0)}catch(s){throw console.error("requestEmailVerificationOTP Error:",s),{message:s?.message||"Failed to send verification OTP",status:s?.status||500}}}async verifyEmail(e){const{email:r,otp:n}=e;if(!r)throw new Error("verifyEmail: 'email' is required");if(!n)throw new Error("verifyEmail: 'otp' is required");try{return await this.request("POST","/users/verify-email",{email:r,otp:n},{},!0)}catch(s){throw{message:s.message||"Failed to verify email",status:s.status||500}}}async checkUserSession(){if(typeof window>"u")return{authenticated:!1};const e=()=>{document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax",window.location.protocol==="https:"&&(document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax; Secure")};try{const r=await this.request("GET","/users/session",void 0,{},!0);return r?.authenticated||e(),r??{authenticated:!1}}catch{return e(),{authenticated:!1}}}async getUser(e){const r=this.appId;if(!r)throw new Error("getUser: 'appId' is required in SDK config");if(!e?.id&&!e?.username)throw new Error("getUser: either 'id' or 'username' is required");const n=new URLSearchParams;return e.id&&n.append("id",e.id),e.username&&n.append("username",e.username),await this.request("GET",`/users/${encodeURIComponent(r)}/user?${n.toString()}`,void 0,{},!0)}async updateUser(e){const{userId:r,...n}=e;if(!r)throw new Error("updateUser: 'userId' is required");if(!n.appId)throw new Error("updateUser: 'appId' is required");return await this.request("PUT",`/users/update/${r}`,n,{},!0)}async deleteUser(e){const{userId:r}=e;if(!r)throw new Error("deleteUser: 'userId' is required");return await this.request("DELETE",`/users/delete/${r}`,{},{},!0)}async getUserProfile(e){const{userId:r}=e;if(!r)throw new Error("getProfile: 'userId' and 'appId' are required");try{return await this.request("POST","/users/profile",{userId:r},{},!0)}catch(n){throw{message:n.message||"Failed to fetch profile",status:n.status||500}}}async requestResetUserPasswordOTP(e){const{email:r}=e;if(!r)throw new Error("forgotPassword: 'email' is required");return await this.request("POST","/users/forgot-password",{email:r})}async resetUserPassword(e){const{email:r,otp:n,newPassword:s}=e;if(!r||!n||!s)throw new Error("resetPassword: 'email', 'otp' and 'newPassword' are required");return await this.request("POST","/users/reset-password",{email:r,otp:n,newPassword:s})}async checkIfUserExists(e){if(!e)throw new Error("checkUser: 'userId' is required");return await this.request("GET",`/users/check-user/${e}?appId=${this.appId}`)}async addUserData(e){const{userId:r,dataCategory:n,data:s}=e;if(!r)throw new Error("addUserData: 'userId' is required");if(!n)throw new Error("addUserData: 'dataCategory' is required");if(!s)throw new Error("addUserData: 'data' is required");return await this.request("POST",`/users/${r}/data`,{dataCategory:n,...s},{},!1)}async getUserData(e){const{userId:r,limit:n=20,cursor:s,category:i,parentId:o}=e;if(!r)throw new Error("getUserData: 'userId' is required");const c=`/users/${encodeURIComponent(r)}/data`,l=new URLSearchParams;l.set("limit",String(n)),s&&l.set("cursor",s),i&&l.set("category",i),o&&l.set("parentId",o);const u=l.toString();return this.request("GET",u?`${c}?${u}`:c,void 0,{},!1)}async getSingleUserData(e){const{userId:r,dataId:n}=e;if(!r||!n)throw new Error("getSingleUserData: 'userId' and 'dataId' are required");return await this.request("GET",`/users/${r}/data/${n}`,void 0,{},!1)}async searchInUserData(e){const{userId:r,category:n,q:s,keys:i,limit:o,cursor:c}=e||{};if(!r)throw new Error("searchUserData: 'userId' is required");return await this.request("POST",`/users/${encodeURIComponent(r)}/data/search`,{category:n,q:s,keys:i&&Object.keys(i).length>0?i:{},...o!==void 0?{limit:o}:{},...c?{cursor:c}:{}},{},!1)}async*iterateUserData(e){let r;do{const n=await this.getUserData({...e,cursor:r});yield n,r=n?.nextCursor||void 0}while(r)}async updateUserData(e){const{userId:r,dataId:n,data:s,version:i}=e;if(!r||!n)throw new Error("updateUserData: 'userId' and 'dataId' are required");if(!s)throw new Error("updateUserData: 'data' is required");return await this.request("PUT",`/users/${r}/data/${n}`,{...s,...i!==void 0?{version:i}:{}},{},!1)}async deleteUserData(e){const{userId:r,dataId:n}=e;if(!r||!n)throw new Error("deleteUserData: 'userId' and 'dataId' are required");return await this.request("DELETE",`/users/${r}/data/${n}`,void 0,{},!1)}async deleteManyUserData(e){const{userId:r,dataIds:n}=e||{};if(!r)throw new Error("deleteManyUserData: 'userId' is required");if(!Array.isArray(n)||n.length===0)throw new Error("deleteManyUserData: 'dataIds' must be a non-empty array");return await this.request("POST",`/users/${encodeURIComponent(r)}/data-bulk-delete`,{dataIds:n},{},!1)}async batch(e){const{userId:r,operations:n}=e||{};if(!r)throw new Error("batch: 'userId' is required");if(!Array.isArray(n)||n.length===0)throw new Error("batch: 'operations' must be a non-empty array");const s=n.findIndex(i=>!i||!["create","update","delete"].includes(i.type));if(s!==-1)throw new Error(`batch: operations[${s}].type must be "create", "update", or "delete"`);return await this.request("POST",`/users/${encodeURIComponent(r)}/data-batch`,{operations:n},{},!1)}async addAppData(e){const r=this.appId;if(!r)throw new Error("addAppData: 'appId' is required");const{dataCategory:n,data:s}=e;if(!n)throw new Error("addAppData: 'dataCategory' is required");if(!s||typeof s!="object")throw new Error("addAppData: 'data' is required");return await this.request("POST",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(n)}`,s,{},!1)}async getAppData(e){const r=this.appId;if(!r)throw new Error("getAppData: 'appId' is required");const n=typeof e=="string"?{category:e}:e||{},{category:s,limit:i,cursor:o}=n,c=s?`/app/${encodeURIComponent(r)}/app-data/${encodeURIComponent(s)}`:`/app/${encodeURIComponent(r)}/app-data`,l=new URLSearchParams;i!==void 0&&l.set("limit",String(i)),o&&l.set("cursor",o);const u=l.toString();return await this.request("GET",u?`${c}?${u}`:c,void 0,{},!1)}async getSingleAppData(e){const r=this.appId;if(!r)throw new Error("getSingleAppData: 'appId' is required");if(!e?.dataId)throw new Error("getSingleAppData: 'dataId' is required");return await this.request("GET",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(e.dataId)}`,void 0,{},!1)}async searchInAppData(e){const r=this.appId;if(!r)throw new Error("searchInAppData: 'appId' is required");const{category:n,q:s,keys:i,limit:o,cursor:c}=e||{};return await this.request("POST",`/app/${encodeURIComponent(r)}/app-data/search`,{category:n,q:s,keys:i&&Object.keys(i).length>0?i:{},...o!==void 0?{limit:o}:{},...c?{cursor:c}:{}},{},!1)}async updateAppData(e){const r=this.appId;if(!r)throw new Error("updateAppData: 'appId' is required");if(!e?.dataId)throw new Error("updateAppData: 'dataId' is required");if(!e?.data||typeof e.data!="object")throw new Error("updateAppData: 'data' is required");return await this.request("PATCH",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(e.dataId)}`,e.data,{},!1)}async deleteAppData(e){const r=this.appId;if(!r)throw new Error("deleteAppData: 'appId' is required");if(!e?.dataId)throw new Error("deleteAppData: 'dataId' is required");return await this.request("DELETE",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(e.dataId)}`,void 0,{},!1)}async getAllUsersFromApp(e={}){const r=this.appId;if(!r)throw new Error("getAllUsersFromApp: 'appId' is required");const{cursor:n,limit:s}=e,i={};return n&&(i.cursor=n),s!==void 0&&(i.limit=s),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users`,i,{},!1)}async searchInAllAppUsers(e={}){const r=this.appId;if(!r)throw new Error("searchInAllAppUsers: 'appId' is required");const{q:n,keys:s={},limit:i,cursor:o}=e,c={};return n&&(c.q=n),s&&Object.keys(s).length>0&&(c.keys=s),i!==void 0&&(c.limit=i),o&&(c.cursor=o),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users/search`,c,{},!1)}async getAllUsersDataFromApp(e={}){const r=this.appId;if(!r)throw new Error("getAllUsersDataFromApp: 'appId' is required");const{category:n,cursor:s,limit:i}=e,o={};return n&&(o.category=n),s&&(o.cursor=s),i!==void 0&&(o.limit=i),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users-data`,o,{},!1)}async searchInAllAppUsersData(e={}){const r=this.appId;if(!r)throw new Error("searchInAllAppUsersData: 'appId' is required");const{category:n,q:s,keys:i={},limit:o,cursor:c}=e,l={};return n&&(l.category=n),s&&(l.q=s),i&&Object.keys(i).length>0&&(l.keys=i),o!==void 0&&(l.limit=o),c&&(l.cursor=c),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users-data/search`,l,{},!1)}}B.NeuctraAuthix=kr,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})}));
|
|
6
|
+
`+i):n.stack=i}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=_(this.defaults,r);const{transitional:n,paramsSerializer:s,headers:i}=r;n!==void 0&&ie.assertOptions(n,{silentJSONParsing:P.transitional(P.boolean),forcedJSONParsing:P.transitional(P.boolean),clarifyTimeoutError:P.transitional(P.boolean)},!1),s!=null&&(a.isFunction(s)?r.paramsSerializer={serialize:s}:ie.assertOptions(s,{encode:P.function,serialize:P.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),ie.assertOptions(r,{baseUrl:P.spelling("baseURL"),withXsrfToken:P.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let o=i&&a.merge(i.common,i[r.method]);i&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),r.headers=T.concat(o,i);const c=[];let l=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(r)===!1||(l=l&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let d,h=0,y;if(!l){const f=[nt.bind(this),void 0];for(f.unshift(...c),f.push(...u),y=f.length,d=Promise.resolve(r);h<y;)d=d.then(f[h++],f[h++]);return d}y=c.length;let R=r;for(;h<y;){const f=c[h++],m=c[h++];try{R=f(R)}catch(p){m.call(this,p);break}}try{d=nt.call(this,R)}catch(f){return Promise.reject(f)}for(h=0,y=u.length;h<y;)d=d.then(u[h++],u[h++]);return d}getUri(e){e=_(this.defaults,e);const r=Je(e.baseURL,e.url,e.allowAbsoluteUrls);return Le(r,e.params,e.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(e){k.prototype[e]=function(r,n){return this.request(_(n||{},{method:e,url:r,data:(n||{}).data}))}}),a.forEach(["post","put","patch"],function(e){function r(n){return function(i,o,c){return this.request(_(c||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:i,data:o}))}}k.prototype[e]=r(),k.prototype[e+"Form"]=r(!0)});let Nr=class pt{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(i){r=i});const n=this;this.promise.then(s=>{if(!n._listeners)return;let i=n._listeners.length;for(;i-- >0;)n._listeners[i](s);n._listeners=null}),this.promise.then=s=>{let i;const o=new Promise(c=>{n.subscribe(c),i=c}).then(s);return o.cancel=function(){n.unsubscribe(i)},o},e(function(i,o,c){n.reason||(n.reason=new v(i,o,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new pt(function(s){e=s}),cancel:e}}};function Fr(t){return function(r){return t.apply(null,r)}}function _r(t){return a.isObject(t)&&t.isAxiosError===!0}const be={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(be).forEach(([t,e])=>{be[e]=t});function it(t){const e=new k(t),r=j(k.prototype.request,e);return a.extend(r,k.prototype,e,{allOwnKeys:!0}),a.extend(r,e,null,{allOwnKeys:!0}),r.create=function(s){return it(_(t,s))},r}const E=it(W);E.Axios=k,E.CanceledError=v,E.CancelToken=Nr,E.isCancel=He,E.VERSION=st,E.toFormData=te,E.AxiosError=w,E.Cancel=E.CanceledError,E.all=function(e){return Promise.all(e)},E.spread=Fr,E.isAxiosError=_r,E.mergeConfig=_,E.AxiosHeaders=T,E.formToJSON=t=>je(a.isHTMLForm(t)?new FormData(t):t),E.getAdapter=rt.getAdapter,E.HttpStatusCode=be,E.default=E;const{Axios:zr,AxiosError:Vr,CanceledError:Jr,isCancel:Kr,CancelToken:Wr,VERSION:Gr,all:Xr,Cancel:Qr,isAxiosError:Zr,spread:Yr,toFormData:en,AxiosHeaders:tn,HttpStatusCode:rn,formToJSON:nn,getAdapter:sn,mergeConfig:on}=E;class kr{appName;baseUrl;apiKey;appId;client;constructor(e){if(!e||!e.baseUrl)throw new Error("NeuctraAuthix: 'baseUrl' is required in config");const r=e.apiKey;if(!r)throw new Error("NeuctraAuthix: 'apiKey' is required in config");this.appName=e.appName,this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=r,this.appId=e.appId||null,this.client=E.create({baseURL:this.baseUrl,headers:{"Content-Type":"application/json","x-api-key":r},timeout:3e4,withCredentials:!0})}async request(e,r,n,s={},i=!1){try{const o=e.toUpperCase(),c=o==="GET"||o==="HEAD"?void 0:{...this.appId?{appId:this.appId}:{},...n||{}};return(await this.client.request({url:r,method:e,data:c,headers:s,withCredentials:i})).data}catch(o){if(E.isAxiosError(o)){const c=o.response?.status??0,l=o.response?.data;let u=l?.message||o.message||"Request failed";throw c===403&&l?.code==="INSUFFICIENT_SCOPE"&&(u=`${u} (called "${r}" with an API key). This endpoint needs an API key — call it from your server, not from client code.`),c===401&&l?.code==="NO_USER_SESSION"&&(u=`${u} Sign the user in with loginUser() first — this endpoint acts on the signed-in user's own data.`),c===409&&l?.code==="VERSION_CONFLICT"?{message:`${u} Re-read the record to get its current version, then retry the update.`,status:c,code:"VERSION_CONFLICT",isConflict:!0,currentVersion:l?.currentVersion,expectedVersion:l?.expectedVersion}:c===429?{message:u,status:c,code:l?.code||"RATE_LIMITED",isRateLimited:!0,resetDate:l?.resetDate}:{message:u,status:c,code:l?.code}}throw{message:o.message||"Unexpected error occurred"}}}async signupUser(e){const{name:r,email:n,password:s}=e;if(!r||!n||!s)throw new Error("signup: 'name', 'email', and 'password' are required");return await this.request("POST","/users/signup",e,{},!0)}async loginUser(e){const{email:r,password:n}=e;if(!r||!n)throw new Error("login: 'email' and 'password' are required");try{return await this.request("POST","/users/login",{email:r,password:n},{},!0)}catch(s){throw new Error(s.message||"Login failed due to an unknown error")}}async logoutUser(){try{return(await this.request("POST","/users/logout",{},{},!0))?.success?(typeof window<"u"&&(document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax",window.location.protocol==="https:"&&(document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax; Secure"),window.location.reload()),{success:!0}):{success:!1}}catch(e){throw new Error(e?.message||"Logout failed due to an unknown error")}}async changePassword(e){const{userId:r,currentPassword:n,newPassword:s}=e;if(!r)throw new Error("changePassword: 'userId' is required");if(!n||!s)throw new Error("changePassword: both 'currentPassword' and 'newPassword' are required");return await this.request("PUT",`/users/change-password/${r}`,{currentPassword:n,newPassword:s},{},!0)}async requestEmailVerificationOTP(e){const{userId:r,email:n}=e;if(!r)throw{message:"requestEmailVerificationOTP: 'userId' is required",status:400};if(!n)throw{message:"requestEmailVerificationOTP: 'email' is required",status:400};try{return await this.request("POST",`/users/send-verify-otp/${encodeURIComponent(r)}`,{email:n},{},!0)}catch(s){throw console.error("requestEmailVerificationOTP Error:",s),{message:s?.message||"Failed to send verification OTP",status:s?.status||500}}}async verifyEmail(e){const{email:r,otp:n}=e;if(!r)throw new Error("verifyEmail: 'email' is required");if(!n)throw new Error("verifyEmail: 'otp' is required");try{return await this.request("POST","/users/verify-email",{email:r,otp:n},{},!0)}catch(s){throw{message:s.message||"Failed to verify email",status:s.status||500}}}async checkUserSession(){if(typeof window>"u")return{authenticated:!1};const e=()=>{document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax",window.location.protocol==="https:"&&(document.cookie="a_s_b=; path=/; Max-Age=0; SameSite=Lax; Secure")};try{const r=await this.request("GET","/users/session",void 0,{},!0);return r?.authenticated||e(),r??{authenticated:!1}}catch{return e(),{authenticated:!1}}}async getUser(e){const r=this.appId;if(!r)throw new Error("getUser: 'appId' is required in SDK config");if(!e?.id&&!e?.username)throw new Error("getUser: either 'id' or 'username' is required");const n=new URLSearchParams;return e.id&&n.append("id",e.id),e.username&&n.append("username",e.username),await this.request("GET",`/users/${encodeURIComponent(r)}/user?${n.toString()}`,void 0,{},!0)}async updateUser(e){const{userId:r,...n}=e;if(!r)throw new Error("updateUser: 'userId' is required");if(!n.appId)throw new Error("updateUser: 'appId' is required");return await this.request("PUT",`/users/update/${r}`,n,{},!0)}async deleteUser(e){const{userId:r}=e;if(!r)throw new Error("deleteUser: 'userId' is required");return await this.request("DELETE",`/users/delete/${r}`,{},{},!0)}async getUserProfile(e){const{userId:r}=e;if(!r)throw new Error("getProfile: 'userId' and 'appId' are required");try{return await this.request("POST","/users/profile",{userId:r},{},!0)}catch(n){throw{message:n.message||"Failed to fetch profile",status:n.status||500}}}async requestResetUserPasswordOTP(e){const{email:r}=e;if(!r)throw new Error("forgotPassword: 'email' is required");return await this.request("POST","/users/forgot-password",{email:r})}async resetUserPassword(e){const{email:r,otp:n,newPassword:s}=e;if(!r||!n||!s)throw new Error("resetPassword: 'email', 'otp' and 'newPassword' are required");return await this.request("POST","/users/reset-password",{email:r,otp:n,newPassword:s})}async checkIfUserExists(e){if(!e)throw new Error("checkUser: 'userId' is required");return await this.request("GET",`/users/check-user/${e}?appId=${this.appId}`)}async addUserData(e){const{userId:r,dataCategory:n,data:s}=e;if(!r)throw new Error("addUserData: 'userId' is required");if(!n)throw new Error("addUserData: 'dataCategory' is required");if(!s)throw new Error("addUserData: 'data' is required");return await this.request("POST",`/users/${r}/data`,{dataCategory:n,...s},{},!1)}async getUserData(e){const{userId:r,limit:n=20,cursor:s,category:i,parentId:o}=e;if(!r)throw new Error("getUserData: 'userId' is required");const c=`/users/${encodeURIComponent(r)}/data`,l=new URLSearchParams;l.set("limit",String(n)),s&&l.set("cursor",s),i&&l.set("category",i),o&&l.set("parentId",o);const u=l.toString();return this.request("GET",u?`${c}?${u}`:c,void 0,{},!1)}async getSingleUserData(e){const{userId:r,dataId:n}=e;if(!r||!n)throw new Error("getSingleUserData: 'userId' and 'dataId' are required");return await this.request("GET",`/users/${r}/data/${n}`,void 0,{},!1)}async searchInUserData(e){const{userId:r,category:n,q:s,keys:i,limit:o,cursor:c}=e||{};if(!r)throw new Error("searchUserData: 'userId' is required");return await this.request("POST",`/users/${encodeURIComponent(r)}/data/search`,{category:n,q:s,keys:i&&Object.keys(i).length>0?i:{},...o!==void 0?{limit:o}:{},...c?{cursor:c}:{}},{},!1)}async*iterateUserData(e){let r;do{const n=await this.getUserData({...e,cursor:r});yield n,r=n?.nextCursor||void 0}while(r)}async updateUserData(e){const{userId:r,dataId:n,data:s,version:i}=e;if(!r||!n)throw new Error("updateUserData: 'userId' and 'dataId' are required");if(!s)throw new Error("updateUserData: 'data' is required");return await this.request("PUT",`/users/${r}/data/${n}`,{...s,...i!==void 0?{version:i}:{}},{},!1)}async deleteUserData(e){const{userId:r,dataId:n}=e;if(!r||!n)throw new Error("deleteUserData: 'userId' and 'dataId' are required");return await this.request("DELETE",`/users/${r}/data/${n}`,void 0,{},!1)}async deleteManyUserData(e){const{userId:r,dataIds:n}=e||{};if(!r)throw new Error("deleteManyUserData: 'userId' is required");if(!Array.isArray(n)||n.length===0)throw new Error("deleteManyUserData: 'dataIds' must be a non-empty array");return await this.request("POST",`/users/${encodeURIComponent(r)}/data-bulk-delete`,{dataIds:n},{},!1)}async batch(e){const{userId:r,operations:n}=e||{};if(!r)throw new Error("batch: 'userId' is required");if(!Array.isArray(n)||n.length===0)throw new Error("batch: 'operations' must be a non-empty array");const s=n.findIndex(i=>!i||!["create","update","delete"].includes(i.type));if(s!==-1)throw new Error(`batch: operations[${s}].type must be "create", "update", or "delete"`);return await this.request("POST",`/users/${encodeURIComponent(r)}/data-batch`,{operations:n},{},!1)}async addAppData(e){const r=this.appId;if(!r)throw new Error("addAppData: 'appId' is required");const{dataCategory:n,data:s}=e;if(!n)throw new Error("addAppData: 'dataCategory' is required");if(!s||typeof s!="object")throw new Error("addAppData: 'data' is required");return await this.request("POST",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(n)}`,s,{},!1)}async getAppData(e){const r=this.appId;if(!r)throw new Error("getAppData: 'appId' is required");const n=typeof e=="string"?{category:e}:e||{},{category:s,limit:i,cursor:o}=n,c=s?`/app/${encodeURIComponent(r)}/app-data/${encodeURIComponent(s)}`:`/app/${encodeURIComponent(r)}/app-data`,l=new URLSearchParams;i!==void 0&&l.set("limit",String(i)),o&&l.set("cursor",o);const u=l.toString();return await this.request("GET",u?`${c}?${u}`:c,void 0,{},!1)}async getSingleAppData(e){const r=this.appId;if(!r)throw new Error("getSingleAppData: 'appId' is required");if(!e?.dataId)throw new Error("getSingleAppData: 'dataId' is required");return await this.request("GET",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(e.dataId)}`,void 0,{},!1)}async searchInAppData(e){const r=this.appId;if(!r)throw new Error("searchInAppData: 'appId' is required");const{category:n,q:s,keys:i,limit:o,cursor:c}=e||{};return await this.request("POST",`/app/${encodeURIComponent(r)}/app-data/search`,{category:n,q:s,keys:i&&Object.keys(i).length>0?i:{},...o!==void 0?{limit:o}:{},...c?{cursor:c}:{}},{},!1)}async updateAppData(e){const r=this.appId;if(!r)throw new Error("updateAppData: 'appId' is required");if(!e?.dataId)throw new Error("updateAppData: 'dataId' is required");if(!e?.data||typeof e.data!="object")throw new Error("updateAppData: 'data' is required");return await this.request("PATCH",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(e.dataId)}`,e.data,{},!1)}async deleteAppData(e){const r=this.appId;if(!r)throw new Error("deleteAppData: 'appId' is required");if(!e?.dataId)throw new Error("deleteAppData: 'dataId' is required");return await this.request("DELETE",`/app/${encodeURIComponent(r)}/data/${encodeURIComponent(e.dataId)}`,void 0,{},!1)}async getAllUsersFromApp(e={}){const r=this.appId;if(!r)throw new Error("getAllUsersFromApp: 'appId' is required");const{cursor:n,limit:s}=e,i={};return n&&(i.cursor=n),s!==void 0&&(i.limit=s),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users`,i,{},!1)}async searchInAllAppUsers(e={}){const r=this.appId;if(!r)throw new Error("searchInAllAppUsers: 'appId' is required");const{q:n,keys:s={},limit:i,cursor:o}=e,c={};return n&&(c.q=n),s&&Object.keys(s).length>0&&(c.keys=s),i!==void 0&&(c.limit=i),o&&(c.cursor=o),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users/search`,c,{},!1)}async getAllUsersDataFromApp(e={}){const r=this.appId;if(!r)throw new Error("getAllUsersDataFromApp: 'appId' is required");const{category:n,cursor:s,limit:i}=e,o={};return n&&(o.category=n),s&&(o.cursor=s),i!==void 0&&(o.limit=i),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users-data`,o,{},!1)}async searchInAllAppUsersData(e={}){const r=this.appId;if(!r)throw new Error("searchInAllAppUsersData: 'appId' is required");const{category:n,q:s,keys:i={},limit:o,cursor:c}=e,l={};return n&&(l.category=n),s&&(l.q=s),i&&Object.keys(i).length>0&&(l.keys=i),o!==void 0&&(l.limit=o),c&&(l.cursor=c),await this.request("POST",`/app/global/${encodeURIComponent(r)}/all-app-users-data/search`,l,{},!1)}}B.NeuctraAuthix=kr,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"})}));
|
package/dist/sdk/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/sdk/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,WAAW,EACX,oBAAoB,EACpB,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,gBAAgB,EAMhB,uBAAuB,EACvB,oBAAoB,EAEpB,mBAAmB,EACnB,WAAW,EACX,mBAAmB,EAEnB,YAAY,EACZ,oBAAoB,EACpB,gBAAgB,EACjB,MAAM,iBAAiB,CAAC;AAEzB;;GAEG;AACH,qBAAa,aAAa;IACxB,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC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C;CA0BhB"}
|
package/dist/sdk/interfaces.d.ts
CHANGED
|
@@ -32,7 +32,7 @@ export interface UpdateUserParams {
|
|
|
32
32
|
/**
|
|
33
33
|
* App scope for the update.
|
|
34
34
|
*
|
|
35
|
-
* Optional: the SDK injects the `appId` from your config
|
|
35
|
+
* Optional: the SDK injects the `appId` from your config into every non-GET request body,
|
|
36
36
|
* so you only need to pass this to override it. It was previously typed as
|
|
37
37
|
* required, which made the bundled `UserProfile` component fail to typecheck.
|
|
38
38
|
*/
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neuctra/authix",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"description": "Universal JavaScript/TypeScript SDK for Neuctra Authix authentication and user data. For React UI components use @neuctra/authix-react.",
|
|
5
5
|
"author": "Taha Asif",
|
|
6
6
|
"license": "MIT",
|