2 lines
12 KiB
JavaScript
2 lines
12 KiB
JavaScript
/*! Capacitor: https://capacitorjs.com/ - MIT License */var C;(function(s){s.Unimplemented="UNIMPLEMENTED",s.Unavailable="UNAVAILABLE"})(C||(C={}));class E extends Error{constructor(e,t,n){super(e),this.message=e,this.code=t,this.data=n}}const M=s=>{var e,t;return s!=null&&s.androidBridge?"android":!((t=(e=s==null?void 0:s.webkit)===null||e===void 0?void 0:e.messageHandlers)===null||t===void 0)&&t.bridge?"ios":"web"},B=s=>{const e=s.CapacitorCustomPlatform||null,t=s.Capacitor||{},n=t.Plugins=t.Plugins||{},r=()=>e!==null?e.name:M(s),a=()=>r()!=="web",i=l=>{const d=u.get(l);return!!(d!=null&&d.platforms.has(r())||o(l))},o=l=>{var d;return(d=t.PluginHeaders)===null||d===void 0?void 0:d.find(k=>k.name===l)},c=l=>s.console.error(l),u=new Map,v=(l,d={})=>{const k=u.get(l);if(k)return console.warn(`Capacitor plugin "${l}" already registered. Cannot register plugins twice.`),k.proxy;const y=r(),P=o(l);let g;const H=async()=>(!g&&y in d?g=typeof d[y]=="function"?g=await d[y]():g=d[y]:e!==null&&!g&&"web"in d&&(g=typeof d.web=="function"?g=await d.web():g=d.web),g),D=(m,f)=>{var h,w;if(P){const b=P==null?void 0:P.methods.find(p=>f===p.name);if(b)return b.rtype==="promise"?p=>t.nativePromise(l,f.toString(),p):(p,x)=>t.nativeCallback(l,f.toString(),p,x);if(m)return(h=m[f])===null||h===void 0?void 0:h.bind(m)}else{if(m)return(w=m[f])===null||w===void 0?void 0:w.bind(m);throw new E(`"${l}" plugin is not implemented on ${y}`,C.Unimplemented)}},A=m=>{let f;const h=(...w)=>{const b=H().then(p=>{const x=D(p,m);if(x){const O=x(...w);return f=O==null?void 0:O.remove,O}else throw new E(`"${l}.${m}()" is not implemented on ${y}`,C.Unimplemented)});return m==="addListener"&&(b.remove=async()=>f()),b};return h.toString=()=>`${m.toString()}() { [capacitor code] }`,Object.defineProperty(h,"name",{value:m,writable:!1,configurable:!1}),h},j=A("addListener"),T=A("removeListener"),W=(m,f)=>{const h=j({eventName:m},f),w=async()=>{const p=await h;T({eventName:m,callbackId:p},f)},b=new Promise(p=>h.then(()=>p({remove:w})));return b.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await w()},b},R=new Proxy({},{get(m,f){switch(f){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return P?W:j;case"removeListener":return T;default:return A(f)}}});return n[l]=R,u.set(l,{name:l,proxy:R,platforms:new Set([...Object.keys(d),...P?[y]:[]])}),R};return t.convertFileSrc||(t.convertFileSrc=l=>l),t.getPlatform=r,t.handleError=c,t.isNativePlatform=a,t.isPluginAvailable=i,t.registerPlugin=v,t.Exception=E,t.DEBUG=!!t.DEBUG,t.isLoggingEnabled=!!t.isLoggingEnabled,t},K=s=>s.Capacitor=B(s),$=K(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),S=$.registerPlugin;class _{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(e,t){let n=!1;this.listeners[e]||(this.listeners[e]=[],n=!0),this.listeners[e].push(t);const a=this.windowListeners[e];a&&!a.registered&&this.addWindowListener(a),n&&this.sendRetainedArgumentsForEvent(e);const i=async()=>this.removeListener(e,t);return Promise.resolve({remove:i})}async removeAllListeners(){this.listeners={};for(const e in this.windowListeners)this.removeWindowListener(this.windowListeners[e]);this.windowListeners={}}notifyListeners(e,t,n){const r=this.listeners[e];if(!r){if(n){let a=this.retainedEventArguments[e];a||(a=[]),a.push(t),this.retainedEventArguments[e]=a}return}r.forEach(a=>a(t))}hasListeners(e){return!!this.listeners[e].length}registerWindowListener(e,t){this.windowListeners[t]={registered:!1,windowEventName:e,pluginEventName:t,handler:n=>{this.notifyListeners(t,n)}}}unimplemented(e="not implemented"){return new $.Exception(e,C.Unimplemented)}unavailable(e="not available"){return new $.Exception(e,C.Unavailable)}async removeListener(e,t){const n=this.listeners[e];if(!n)return;const r=n.indexOf(t);this.listeners[e].splice(r,1),this.listeners[e].length||this.removeWindowListener(this.windowListeners[e])}addWindowListener(e){window.addEventListener(e.windowEventName,e.handler),e.registered=!0}removeWindowListener(e){e&&(window.removeEventListener(e.windowEventName,e.handler),e.registered=!1)}sendRetainedArgumentsForEvent(e){const t=this.retainedEventArguments[e];t&&(delete this.retainedEventArguments[e],t.forEach(n=>{this.notifyListeners(e,n)}))}}const F=s=>encodeURIComponent(s).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),I=s=>s.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class G extends _{async getCookies(){const e=document.cookie,t={};return e.split(";").forEach(n=>{if(n.length<=0)return;let[r,a]=n.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");r=I(r).trim(),a=I(a).trim(),t[r]=a}),t}async setCookie(e){try{const t=F(e.key),n=F(e.value),r=`; expires=${(e.expires||"").replace("expires=","")}`,a=(e.path||"/").replace("path=",""),i=e.url!=null&&e.url.length>0?`domain=${e.url}`:"";document.cookie=`${t}=${n||""}${r}; path=${a}; ${i};`}catch(t){return Promise.reject(t)}}async deleteCookie(e){try{document.cookie=`${e.key}=; Max-Age=0`}catch(t){return Promise.reject(t)}}async clearCookies(){try{const e=document.cookie.split(";")||[];for(const t of e)document.cookie=t.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(e){return Promise.reject(e)}}async clearAllCookies(){try{await this.clearCookies()}catch(e){return Promise.reject(e)}}}S("CapacitorCookies",{web:()=>new G});const z=async s=>new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const r=n.result;e(r.indexOf(",")>=0?r.split(",")[1]:r)},n.onerror=r=>t(r),n.readAsDataURL(s)}),V=(s={})=>{const e=Object.keys(s);return Object.keys(s).map(r=>r.toLocaleLowerCase()).reduce((r,a,i)=>(r[a]=s[e[i]],r),{})},J=(s,e=!0)=>s?Object.entries(s).reduce((n,r)=>{const[a,i]=r;let o,c;return Array.isArray(i)?(c="",i.forEach(u=>{o=e?encodeURIComponent(u):u,c+=`${a}=${o}&`}),c.slice(0,-1)):(o=e?encodeURIComponent(i):i,c=`${a}=${o}`),`${n}&${c}`},"").substr(1):null,Q=(s,e={})=>{const t=Object.assign({method:s.method||"GET",headers:s.headers},e),r=V(s.headers)["content-type"]||"";if(typeof s.data=="string")t.body=s.data;else if(r.includes("application/x-www-form-urlencoded")){const a=new URLSearchParams;for(const[i,o]of Object.entries(s.data||{}))a.set(i,o);t.body=a.toString()}else if(r.includes("multipart/form-data")||s.data instanceof FormData){const a=new FormData;if(s.data instanceof FormData)s.data.forEach((o,c)=>{a.append(c,o)});else for(const o of Object.keys(s.data))a.append(o,s.data[o]);t.body=a;const i=new Headers(t.headers);i.delete("content-type"),t.headers=i}else(r.includes("application/json")||typeof s.data=="object")&&(t.body=JSON.stringify(s.data));return t};class X extends _{async request(e){const t=Q(e,e.webFetchExtra),n=J(e.params,e.shouldEncodeUrlParams),r=n?`${e.url}?${n}`:e.url,a=await fetch(r,t),i=a.headers.get("content-type")||"";let{responseType:o="text"}=a.ok?e:{};i.includes("application/json")&&(o="json");let c,u;switch(o){case"arraybuffer":case"blob":u=await a.blob(),c=await z(u);break;case"json":c=await a.json();break;case"document":case"text":default:c=await a.text()}const v={};return a.headers.forEach((l,d)=>{v[d]=l}),{data:c,headers:v,status:a.status,url:a.url}}async get(e){return this.request(Object.assign(Object.assign({},e),{method:"GET"}))}async post(e){return this.request(Object.assign(Object.assign({},e),{method:"POST"}))}async put(e){return this.request(Object.assign(Object.assign({},e),{method:"PUT"}))}async patch(e){return this.request(Object.assign(Object.assign({},e),{method:"PATCH"}))}async delete(e){return this.request(Object.assign(Object.assign({},e),{method:"DELETE"}))}}S("CapacitorHttp",{web:()=>new X});var L;(function(s){s.Prompt="PROMPT",s.Camera="CAMERA",s.Photos="PHOTOS"})(L||(L={}));var U;(function(s){s.Rear="REAR",s.Front="FRONT"})(U||(U={}));var q;(function(s){s.Uri="uri",s.Base64="base64",s.DataUrl="dataUrl"})(q||(q={}));class Y extends _{async getPhoto(e){return new Promise(async(t,n)=>{if(e.webUseInput||e.source===L.Photos)this.fileInputExperience(e,t,n);else if(e.source===L.Prompt){let r=document.querySelector("pwa-action-sheet");r||(r=document.createElement("pwa-action-sheet"),document.body.appendChild(r)),r.header=e.promptLabelHeader||"Photo",r.cancelable=!1,r.options=[{title:e.promptLabelPhoto||"From Photos"},{title:e.promptLabelPicture||"Take Picture"}],r.addEventListener("onSelection",async a=>{a.detail===0?this.fileInputExperience(e,t,n):this.cameraExperience(e,t,n)})}else this.cameraExperience(e,t,n)})}async pickImages(e){return new Promise(async(t,n)=>{this.multipleFileInputExperience(t,n)})}async cameraExperience(e,t,n){if(customElements.get("pwa-camera-modal")){const r=document.createElement("pwa-camera-modal");r.facingMode=e.direction===U.Front?"user":"environment",document.body.appendChild(r);try{await r.componentOnReady(),r.addEventListener("onPhoto",async a=>{const i=a.detail;i===null?n(new E("User cancelled photos app")):i instanceof Error?n(i):t(await this._getCameraPhoto(i,e)),r.dismiss(),document.body.removeChild(r)}),r.present()}catch{this.fileInputExperience(e,t,n)}}else console.error("Unable to load PWA Element 'pwa-camera-modal'. See the docs: https://capacitorjs.com/docs/web/pwa-elements."),this.fileInputExperience(e,t,n)}fileInputExperience(e,t,n){let r=document.querySelector("#_capacitor-camera-input");const a=()=>{var i;(i=r.parentNode)===null||i===void 0||i.removeChild(r)};r||(r=document.createElement("input"),r.id="_capacitor-camera-input",r.type="file",r.hidden=!0,document.body.appendChild(r),r.addEventListener("change",i=>{const o=r.files[0];let c="jpeg";if(o.type==="image/png"?c="png":o.type==="image/gif"&&(c="gif"),e.resultType==="dataUrl"||e.resultType==="base64"){const u=new FileReader;u.addEventListener("load",()=>{if(e.resultType==="dataUrl")t({dataUrl:u.result,format:c});else if(e.resultType==="base64"){const v=u.result.split(",")[1];t({base64String:v,format:c})}a()}),u.readAsDataURL(o)}else t({webPath:URL.createObjectURL(o),format:c}),a()}),r.addEventListener("cancel",i=>{n(new E("User cancelled photos app")),a()})),r.accept="image/*",r.capture=!0,e.source===L.Photos||e.source===L.Prompt?r.removeAttribute("capture"):e.direction===U.Front?r.capture="user":e.direction===U.Rear&&(r.capture="environment"),r.click()}multipleFileInputExperience(e,t){let n=document.querySelector("#_capacitor-camera-input-multiple");const r=()=>{var a;(a=n.parentNode)===null||a===void 0||a.removeChild(n)};n||(n=document.createElement("input"),n.id="_capacitor-camera-input-multiple",n.type="file",n.hidden=!0,n.multiple=!0,document.body.appendChild(n),n.addEventListener("change",a=>{const i=[];for(let o=0;o<n.files.length;o++){const c=n.files[o];let u="jpeg";c.type==="image/png"?u="png":c.type==="image/gif"&&(u="gif"),i.push({webPath:URL.createObjectURL(c),format:u})}e({photos:i}),r()}),n.addEventListener("cancel",a=>{t(new E("User cancelled photos app")),r()})),n.accept="image/*",n.click()}_getCameraPhoto(e,t){return new Promise((n,r)=>{const a=new FileReader,i=e.type.split("/")[1];t.resultType==="uri"?n({webPath:URL.createObjectURL(e),format:i,saved:!1}):(a.readAsDataURL(e),a.onloadend=()=>{const o=a.result;t.resultType==="dataUrl"?n({dataUrl:o,format:i,saved:!1}):n({base64String:o.split(",")[1],format:i,saved:!1})},a.onerror=o=>{r(o)})})}async checkPermissions(){if(typeof navigator>"u"||!navigator.permissions)throw this.unavailable("Permissions API not available in this browser");try{return{camera:(await window.navigator.permissions.query({name:"camera"})).state,photos:"granted"}}catch{throw this.unavailable("Camera permissions are not available in this browser")}}async requestPermissions(){throw this.unimplemented("Not implemented on web.")}async pickLimitedLibraryPhotos(){throw this.unavailable("Not implemented on web.")}async getLimitedLibraryPhotos(){throw this.unavailable("Not implemented on web.")}}const Z=S("Camera",{web:()=>new Y});export{$ as C,Z as a};
|