UNPKG

frappe-sdk-react-i4z

Version:
23 lines (22 loc) 15.8 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const u=require("react"),$=require("swr");var D={exports:{}},v={};/** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var q;function ae(){if(q)return v;q=1;var c=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function t(n,a,s){var i=null;if(s!==void 0&&(i=""+s),a.key!==void 0&&(i=""+a.key),"key"in a){s={};for(var l in a)l!=="key"&&(s[l]=a[l])}else s=a;return a=s.ref,{$$typeof:c,type:n,key:i,ref:a!==void 0?a:null,props:s}}return v.Fragment=r,v.jsx=t,v.jsxs=t,v}var O={};/** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var M;function oe(){return M||(M=1,process.env.NODE_ENV!=="production"&&(function(){function c(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===re?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case k:return"Fragment";case V:return"Profiler";case C:return"StrictMode";case Z:return"Suspense";case K:return"SuspenseList";case te:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case y:return"Portal";case Q:return(e.displayName||"Context")+".Provider";case X:return(e._context.displayName||"Context")+".Consumer";case B:var d=e.render;return e=e.displayName,e||(e=d.displayName||d.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ee:return d=e.displayName||null,d!==null?d:c(e.type)||"Memo";case U:d=e._payload,e=e._init;try{return c(e(d))}catch{}}return null}function r(e){return""+e}function t(e){try{r(e);var d=!1}catch{d=!0}if(d){d=console;var g=d.error,E=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return g.call(d,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",E),r(e)}}function n(e){if(e===k)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===U)return"<...>";try{var d=c(e);return d?"<"+d+">":"<...>"}catch{return"<...>"}}function a(){var e=P.A;return e===null?null:e.getOwner()}function s(){return Error("react-stack-top-frame")}function i(e){if(N.call(e,"key")){var d=Object.getOwnPropertyDescriptor(e,"key").get;if(d&&d.isReactWarning)return!1}return e.key!==void 0}function l(e,d){function g(){L||(L=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",d))}g.isReactWarning=!0,Object.defineProperty(e,"key",{get:g,configurable:!0})}function o(){var e=c(this.type);return I[e]||(I[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function f(e,d,g,E,_,T,A,F){return g=T.ref,e={$$typeof:b,type:e,key:d,props:T,_owner:_},(g!==void 0?g:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:o}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:A}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:F}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function h(e,d,g,E,_,T,A,F){var S=d.children;if(S!==void 0)if(E)if(ne(S)){for(E=0;E<S.length;E++)p(S[E]);Object.freeze&&Object.freeze(S)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else p(S);if(N.call(d,"key")){S=c(e);var R=Object.keys(d).filter(function(se){return se!=="key"});E=0<R.length?"{key: someKey, "+R.join(": ..., ")+": ...}":"{key: someKey}",G[S+E]||(R=0<R.length?"{"+R.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`,E,S,R,S),G[S+E]=!0)}if(S=null,g!==void 0&&(t(g),S=""+g),i(d)&&(t(d.key),S=""+d.key),"key"in d){g={};for(var j in d)j!=="key"&&(g[j]=d[j])}else g=d;return S&&l(g,typeof e=="function"?e.displayName||e.name||"Unknown":e),f(e,S,T,_,a(),g,A,F)}function p(e){typeof e=="object"&&e!==null&&e.$$typeof===b&&e._store&&(e._store.validated=1)}var m=u,b=Symbol.for("react.transitional.element"),y=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),C=Symbol.for("react.strict_mode"),V=Symbol.for("react.profiler"),X=Symbol.for("react.consumer"),Q=Symbol.for("react.context"),B=Symbol.for("react.forward_ref"),Z=Symbol.for("react.suspense"),K=Symbol.for("react.suspense_list"),ee=Symbol.for("react.memo"),U=Symbol.for("react.lazy"),te=Symbol.for("react.activity"),re=Symbol.for("react.client.reference"),P=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,N=Object.prototype.hasOwnProperty,ne=Array.isArray,x=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(e){return e()}};var L,I={},Y=m.react_stack_bottom_frame.bind(m,s)(),J=x(n(s)),G={};O.Fragment=k,O.jsx=function(e,d,g,E,_){var T=1e4>P.recentlyCreatedOwnerStacks++;return h(e,d,g,!1,E,_,T?Error("react-stack-top-frame"):Y,T?x(n(e)):J)},O.jsxs=function(e,d,g,E,_){var T=1e4>P.recentlyCreatedOwnerStacks++;return h(e,d,g,!0,E,_,T?Error("react-stack-top-frame"):Y,T?x(n(e)):J)}})()),O}var z;function ce(){return z||(z=1,process.env.NODE_ENV==="production"?D.exports=ae():D.exports=oe()),D.exports}var le=ce();class H{baseUrl;token;useToken;constructor(r={}){this.baseUrl=r.url||(typeof window<"u"?window.location.origin:""),this.useToken=r.useToken||!1,this.token=r.tokenParams?.token}getHeaders(){const r={"Content-Type":"application/json",Accept:"application/json"};return this.useToken&&this.token&&(r.Authorization=`token ${this.token}`),r}async handleResponse(r){const t=await r.json();if(!r.ok)throw{message:t.message||t.exc||"An error occurred",exception:t.exception,exc_type:t.exc_type,indicator:t.indicator};return t.message||t}async call(r){const{method:t,args:n={},httpMethod:a="POST"}=r,s=`${this.baseUrl}/api/method/${t}`;if(a==="GET"){const l=new URLSearchParams;Object.entries(n).forEach(([h,p])=>{l.append(h,JSON.stringify(p))});const o=l.toString()?`${s}?${l.toString()}`:s,f=await fetch(o,{method:"GET",headers:this.getHeaders(),credentials:this.useToken?"omit":"include"});return this.handleResponse(f)}const i=await fetch(s,{method:"POST",headers:this.getHeaders(),credentials:this.useToken?"omit":"include",body:JSON.stringify(n)});return this.handleResponse(i)}async login(r,t){const n=await fetch(`${this.baseUrl}/api/method/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},credentials:"include",body:JSON.stringify({usr:r,pwd:t})});return this.handleResponse(n)}async logout(){const r=await fetch(`${this.baseUrl}/api/method/logout`,{method:"POST",headers:this.getHeaders(),credentials:this.useToken?"omit":"include"});await this.handleResponse(r)}async getCurrentUser(){return this.call({method:"frappe.auth.get_logged_user"})}async getDoc(r,t){const n=await fetch(`${this.baseUrl}/api/resource/${r}/${encodeURIComponent(t)}`,{method:"GET",headers:this.getHeaders(),credentials:this.useToken?"omit":"include"});return(await this.handleResponse(n)).data}async getDocList(r){const{doctype:t,fields:n=["*"],filters:a={},or_filters:s,order_by:i,limit_start:l=0,limit_page_length:o=20,group_by:f,parent:h}=r,p=new URLSearchParams({fields:JSON.stringify(n),filters:JSON.stringify(a),limit_start:l.toString(),limit_page_length:o.toString()});s&&p.append("or_filters",JSON.stringify(s)),i&&p.append("order_by",i),f&&p.append("group_by",f),h&&p.append("parent",h);const m=await fetch(`${this.baseUrl}/api/resource/${t}?${p.toString()}`,{method:"GET",headers:this.getHeaders(),credentials:this.useToken?"omit":"include"});return(await this.handleResponse(m)).data}async getDocCount(r){const{doctype:t,filters:n={},cache:a=!0}=r,s=new URLSearchParams({filters:JSON.stringify(n),cache:a.toString()}),i=await fetch(`${this.baseUrl}/api/resource/${t}?${s.toString()}&limit_page_length=1&fields=["name"]`,{method:"GET",headers:this.getHeaders(),credentials:this.useToken?"omit":"include"});return(await this.handleResponse(i)).count||0}async createDoc(r){const{doctype:t,doc:n}=r,a=await fetch(`${this.baseUrl}/api/resource/${t}`,{method:"POST",headers:this.getHeaders(),credentials:this.useToken?"omit":"include",body:JSON.stringify(n)});return(await this.handleResponse(a)).data}async updateDoc(r){const{doctype:t,name:n,doc:a}=r,s=await fetch(`${this.baseUrl}/api/resource/${t}/${encodeURIComponent(n)}`,{method:"PUT",headers:this.getHeaders(),credentials:this.useToken?"omit":"include",body:JSON.stringify(a)});return(await this.handleResponse(s)).data}async deleteDoc(r){const{doctype:t,name:n}=r,a=await fetch(`${this.baseUrl}/api/resource/${t}/${encodeURIComponent(n)}`,{method:"DELETE",headers:this.getHeaders(),credentials:this.useToken?"omit":"include"});await this.handleResponse(a)}async uploadFile(r){const{file:t,is_private:n=!1,doctype:a,docname:s,fieldname:i}=r,l=new FormData;l.append("file",t),l.append("is_private",n.toString()),a&&l.append("doctype",a),s&&l.append("docname",s),i&&l.append("fieldname",i);const o={};this.useToken&&this.token&&(o.Authorization=`token ${this.token}`);const f=await fetch(`${this.baseUrl}/api/method/upload_file`,{method:"POST",headers:o,credentials:this.useToken?"omit":"include",body:l});return this.handleResponse(f)}async searchLink(r,t,n={}){return this.call({method:"frappe.desk.search.search_link",args:{doctype:r,txt:t,filters:n}})}}const W=u.createContext(null),ie=({children:c,config:r={}})=>{const[t]=u.useState(()=>new H(r)),[n,a]=u.useState(null),[s,i]=u.useState(!1);u.useEffect(()=>{const o=async()=>{try{const f=await t.getCurrentUser();a(f),i(!0)}catch{a(null),i(!1)}};r.useToken?r.tokenParams?.token&&i(!0):o()},[t,r.useToken,r.tokenParams?.token]);const l={url:t.baseUrl,call:async o=>t.call(o),db:{getDoc:async(o,f)=>t.getDoc(o,f),getDocList:async o=>t.getDocList(o),getDocCount:async o=>t.getDocCount(o),createDoc:async o=>t.createDoc(o),updateDoc:async o=>t.updateDoc(o),deleteDoc:async o=>t.deleteDoc(o)},auth:{login:async(o,f)=>{const h=await t.login(o,f);try{const p=await t.getCurrentUser();a(p),i(!0)}catch(p){console.error("Failed to get user after login:",p)}return h},logout:async()=>{await t.logout(),a(null),i(!1)},getUser:async()=>{const o=await t.getCurrentUser();return a(o),o},currentUser:n,isLoggedIn:s},file:{upload:async o=>t.uploadFile(o)}};return le.jsx(W.Provider,{value:l,children:c})},w=()=>{const c=u.useContext(W);if(!c)throw new Error("useFrappeContext must be used within a FrappeProvider");return c},ue=()=>{const{auth:c}=w();return c},de=(c,r,t="POST")=>{const{call:n}=w(),[a,s]=u.useState(null),[i,l]=u.useState(null),[o,f]=u.useState(!1),h=u.useCallback(async(m={})=>{if(!c&&!m.method)throw new Error("Method is required");const b={method:m.method||c,args:{...r,...m.args},httpMethod:m.httpMethod||t};f(!0),l(null);try{const y=await n(b);return s(y),y}catch(y){const k=y instanceof Error?y:new Error(String(y));throw l(k),k}finally{f(!1)}},[n,c,r,t]),p=u.useCallback(()=>{s(null),l(null),f(!1)},[]);return{call:h,data:a,error:i,loading:o,reset:p}},fe=c=>{const{db:r}=w(),[t,n]=u.useState(null),[a,s]=u.useState(null),[i,l]=u.useState(!1),o=u.useCallback(async h=>{if(!c)throw new Error("Doctype is required");const p={doctype:c,doc:h};l(!0),s(null);try{const m=await r.createDoc(p);return n(m),m}catch(m){const b=m instanceof Error?m:new Error(String(m));throw s(b),b}finally{l(!1)}},[r,c]),f=u.useCallback(()=>{n(null),s(null),l(!1)},[]);return{createDoc:o,data:t,error:a,loading:i,reset:f}},pe=c=>{const{db:r}=w(),[t,n]=u.useState(null),[a,s]=u.useState(!1),i=u.useCallback(async o=>{if(!c)throw new Error("Doctype is required");const f={doctype:c,name:o};s(!0),n(null);try{await r.deleteDoc(f)}catch(h){const p=h instanceof Error?h:new Error(String(h));throw n(p),p}finally{s(!1)}},[r,c]),l=u.useCallback(()=>{n(null),s(!1)},[]);return{deleteDoc:i,error:t,loading:a,reset:l}},he=()=>{const{file:c}=w(),[r,t]=u.useState(null),[n,a]=u.useState(null),[s,i]=u.useState(!1),[l,o]=u.useState(null),f=u.useCallback(async(p,m={})=>{const b={file:p,is_private:!1,...m};i(!0),a(null),o({loaded:0,total:p.size,percentage:0});try{const y=await c.upload(b);return t(y),o({loaded:p.size,total:p.size,percentage:100}),y}catch(y){const k=y instanceof Error?y:new Error(String(y));throw a(k),k}finally{i(!1)}},[c]),h=u.useCallback(()=>{t(null),a(null),i(!1),o(null)},[]);return{upload:f,data:r,error:n,loading:s,progress:l,reset:h}},me=(c,r,t={})=>{const{db:n}=w(),a=c&&r?`${c}/${r}`:null,{data:s,error:i,mutate:l,isValidating:o,isLoading:f}=$(a,a?async()=>n.getDoc(c,r):null,{revalidateIfStale:!0,revalidateOnFocus:!1,revalidateOnReconnect:!0,...t});return{data:s,error:i,mutate:l,isValidating:o,isLoading:f}},ge=(c,r={})=>{const{db:t}=w(),n=c?.doctype?JSON.stringify({...c,type:"count"}):null,{data:a,error:s,mutate:i,isValidating:l,isLoading:o}=$(n,n?async()=>t.getDocCount(c):null,{revalidateIfStale:!0,revalidateOnFocus:!1,revalidateOnReconnect:!0,...r});return{data:a||0,error:s,mutate:i,isValidating:l,isLoading:o}},ye=(c,r={})=>{const{db:t}=w(),n=c?.doctype?JSON.stringify(c):null,{data:a,error:s,mutate:i,isValidating:l,isLoading:o}=$(n,n?async()=>t.getDocList(c):null,{revalidateIfStale:!0,revalidateOnFocus:!1,revalidateOnReconnect:!0,...r});return{data:a||[],error:s,mutate:i,isValidating:l,isLoading:o}},be=(c,r={},t=300)=>{const{call:n}=w(),[a,s]=u.useState([]),[i,l]=u.useState(null),[o,f]=u.useState(!1),[h,p]=u.useState(""),m=u.useCallback(y=>{p(y)},[]);u.useEffect(()=>{if(!h.trim()||!c){s([]);return}const y=setTimeout(async()=>{f(!0),l(null);try{const k=await n({method:"frappe.desk.search.search_link",args:{doctype:c,txt:h,filters:r}});s(k||[])}catch(k){const C=k instanceof Error?k:new Error(String(k));l(C),s([])}finally{f(!1)}},t);return()=>clearTimeout(y)},[h,c,r,t,n]);const b=u.useCallback(()=>{s([]),l(null),f(!1),p("")},[]);return{search:m,data:a,error:i,loading:o,reset:b}},Ee=c=>{const{db:r}=w(),[t,n]=u.useState(null),[a,s]=u.useState(null),[i,l]=u.useState(!1),o=u.useCallback(async(h,p)=>{if(!c)throw new Error("Doctype is required");const m={doctype:c,name:h,doc:p};l(!0),s(null);try{const b=await r.updateDoc(m);return n(b),b}catch(b){const y=b instanceof Error?b:new Error(String(b));throw s(y),y}finally{l(!1)}},[r,c]),f=u.useCallback(()=>{n(null),s(null),l(!1)},[]);return{updateDoc:o,data:t,error:a,loading:i,reset:f}};exports.FrappeClient=H;exports.FrappeProvider=ie;exports.useFrappeAuth=ue;exports.useFrappeCall=de;exports.useFrappeContext=w;exports.useFrappeCreateDoc=fe;exports.useFrappeDeleteDoc=pe;exports.useFrappeFileUpload=he;exports.useFrappeGetDoc=me;exports.useFrappeGetDocCount=ge;exports.useFrappeGetDocList=ye;exports.useFrappeSearch=be;exports.useFrappeUpdateDoc=Ee;