@idolchat/miniapp-sdk 0.1.0 → 0.2.0
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.mjs
CHANGED
|
@@ -553,6 +553,7 @@ function authModule(core) {
|
|
|
553
553
|
}
|
|
554
554
|
function paymentModule(core) {
|
|
555
555
|
return {
|
|
556
|
+
/** IdolChat's confirm dialog for your server's invoice; grant from the webhook, never this result. */
|
|
556
557
|
open: (p) => core.call("payment.open", p)
|
|
557
558
|
};
|
|
558
559
|
}
|
|
@@ -970,6 +971,14 @@ ${text ?? ""}`))
|
|
|
970
971
|
return null;
|
|
971
972
|
},
|
|
972
973
|
"analytics.track": (p) => (analyticsEvent(p), null),
|
|
974
|
+
// No invoice is read and nothing is charged: the app's server still grants only from its webhook.
|
|
975
|
+
"payment.open": (p) => {
|
|
976
|
+
const invoiceId = requiredString(p, "invoiceId");
|
|
977
|
+
if (!/^inv_[A-Za-z0-9_-]{22}$/.test(invoiceId)) invalid("invoiceId is not an invoice id");
|
|
978
|
+
if (dialogs && !dialogs.confirm(`Pay invoice ${invoiceId}? (mock: no stars move)`))
|
|
979
|
+
return { status: "cancelled" };
|
|
980
|
+
return { status: opts.payment ?? "paid" };
|
|
981
|
+
},
|
|
973
982
|
"device.getInfo": () => ({
|
|
974
983
|
platform: "web",
|
|
975
984
|
hostVersion: "mock",
|
package/dist/miniapp-sdk.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";(()=>{var Tt=Object.defineProperty;var At=(e,t,n)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var M=(e,t,n)=>At(e,typeof t!="symbol"?t+"":t,n);var re=["app.init","app.ready","app.setLoadingProgress","app.close","ui.showToast","ui.showAlert","ui.showConfirm","ui.showPopup","ui.setBackButtonVisible","ui.setHeaderColor","ui.setBackgroundColor","ui.setOrientation","ui.getTheme","haptic.impact","haptic.notification","haptic.selection","storage.get","storage.getMany","storage.set","storage.remove","storage.keys","storage.clear","link.open","clipboard.writeText","clipboard.readText","share.system","share.toChat","share.toPost","share.toStory","analytics.track","device.getInfo","permissions.query","permissions.request","qr.scan","location.get","media.saveImage","auth.getLaunchToken","auth.requestProfile","payment.open","notifications.requestPermission","notifications.getPermission","ads.loadRewarded","ads.showRewarded","ads.loadInterstitial","ads.showInterstitial","ads.showBanner","ads.hideBanner"],oe=["lifecycle.pause","lifecycle.resume","lifecycle.closing","ui.backButtonPressed","ui.themeChanged","ui.viewportChanged","permissions.changed","ads.loaded","ads.failed","ads.shown","ads.closed","ads.rewarded"],St=["app.beforeClose","ads.beforeBreak"];function Ee(e){return e.startsWith("payment.")||e.startsWith("ads.")||e.startsWith("share.")||e==="ui.showAlert"||e==="ui.showConfirm"||e==="ui.showPopup"||e==="permissions.request"||z(e)!==void 0}var se=1024*1024,ie=128,L=/^[A-Za-z0-9_-]{1,64}$/,ae=500,be=/^[A-Za-z0-9_-]{1,64}$/,Re=new Set(["link.open","clipboard.writeText","clipboard.readText","share.system","share.toChat","share.toPost","share.toStory","permissions.request","qr.scan","media.saveImage","payment.open","notifications.requestPermission","ads.showRewarded"]),xe=["profile","camera","microphone","location","notifications","photos"],Et={"auth.requestProfile":"profile","qr.scan":"camera","location.get":"location","media.saveImage":"photos","notifications.requestPermission":"notifications"},bt=new Map(Object.entries(Et)),z=e=>bt.get(e);var en=1,tn=["METHOD_NOT_SUPPORTED","INVALID_PARAMS","TIMEOUT","QUOTA_EXCEEDED","PERMISSION_DENIED","CANCELLED","INTERNAL_ERROR"],p=class extends Error{constructor(n,o){super(o);M(this,"code");this.name="MiniAppError",this.code=n}toWire(){return{code:this.code,message:this.message}}},w=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),A=e=>typeof e=="string"?e:void 0;function Ce(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}return w(t)&&t.v===1?t:null}function Ne(e){let t=Ce(e);if(!t)return null;let n=A(t.id),o=A(t.name);switch(t.type){case"result":return n===void 0?null:t.ok===!0?{v:1,type:"result",id:n,ok:!0,data:t.data}:t.ok!==!1||!w(t.error)?null:{v:1,type:"result",id:n,ok:!1,error:Rt(t.error)};case"event":return o===void 0?null:{v:1,type:"event",name:o,data:t.data};case"request":return n===void 0||o===void 0?null:{v:1,type:"request",id:n,name:o,data:t.data,timeoutMs:typeof t.timeoutMs=="number"?t.timeoutMs:3e3};default:return null}}function Rt(e){return{code:A(e.code)??"INTERNAL_ERROR",message:A(e.message)??""}}function nn(e){let t=Ce(e);return!t||typeof t.id!="string"||typeof t.method!="string"?null:{v:1,id:t.id,method:t.method,params:t.params,gesture:t.gesture===!0}}function le(e){return!w(e)||typeof e.id!="string"?null:{id:e.id,displayName:A(e.displayName),avatarUrl:A(e.avatarUrl),locale:A(e.locale)}}function _e(e){if(!w(e))throw new p("INTERNAL_ERROR","app.init returned no result");return{protocol:typeof e.protocol=="number"?e.protocol:1,methods:Array.isArray(e.methods)?e.methods.filter(t=>typeof t=="string"):[],limits:w(e.limits)?e.limits:{},user:le(e.user),startParam:A(e.startParam)??null,launchToken:A(e.launchToken)??null}}var Ie=1e4,F=1e4,D=class{constructor(t,n={}){M(this,"transport");M(this,"timeoutMs");M(this,"now");M(this,"pending",new Map);M(this,"events",new Map);M(this,"requests",new Map);M(this,"seq",0);M(this,"lastGestureAt",Number.NEGATIVE_INFINITY);M(this,"initPromise");M(this,"methods");this.transport=t,this.timeoutMs=n.timeoutMs??Ie,this.now=n.now??Date.now;let o=()=>{this.lastGestureAt=this.now()};n.gestureTarget?.addEventListener("pointerdown",o,{capture:!0}),n.gestureTarget?.addEventListener("keydown",o,{capture:!0}),t.listen(s=>this.receive(s))}init(){return this.initPromise??(this.initPromise=this.send("app.init",{protocol:1},{}).then(t=>{let n=_e(t);return this.methods=new Set(n.methods),n},t=>{throw this.initPromise=void 0,t})),this.initPromise}supports(t){return this.methods?.has(t)??!1}async call(t,n,o={}){let a=await this.init();if(t!=="app.init"){if(!this.supports(t))throw new p("METHOD_NOT_SUPPORTED",`host does not support ${t}`);a=await this.send(t,n,o)}return a}on(t,n){let o=a=>n(a),s=this.events.get(t);return s||this.events.set(t,s=new Set),s.add(o),()=>s.delete(o)}onRequest(t,n){return this.requests.set(t,n),()=>{this.requests.get(t)===n&&this.requests.delete(t)}}nextId(){return`c_${++this.seq}`}hasGesture(){return this.now()-this.lastGestureAt<=F}post(t,n,o){let s={v:1,id:o,method:t,gesture:this.hasGesture()};n!==void 0&&(s.params=n),this.transport.send(s)}send(t,n,o){let s=this.nextId(),a=o.timeoutMs??(Ee(t)?0:this.timeoutMs);return new Promise((c,f)=>{let g=a>0?setTimeout(()=>{this.pending.delete(s),f(new p("TIMEOUT",`${t} timed out after ${a} ms`))},a):void 0;this.pending.set(s,{resolve:c,reject:f,timer:g});try{this.post(t,n,s)}catch(m){clearTimeout(g),this.pending.delete(s),f(new p("INTERNAL_ERROR",`transport failed: ${String(m)}`))}})}receive(t){let n=Ne(t);if(n)if(n.type==="result"){let o=this.pending.get(n.id);if(!o)return;this.pending.delete(n.id),clearTimeout(o.timer),n.ok?o.resolve(n.data):o.reject(new p(n.error.code,n.error.message))}else if(n.type==="event")for(let o of this.events.get(n.name)??[])try{o(n.data)}catch(s){setTimeout(()=>{throw s})}else this.answer(n)}async answer(t){let n=this.requests.get(t.name),o;if(!n)o={id:t.id,ok:!1,error:{code:"METHOD_NOT_SUPPORTED",message:t.name}};else try{o={id:t.id,ok:!0,data:await n(t.data)}}catch(s){let a=s instanceof p?s:new p("INTERNAL_ERROR",String(s));o={id:t.id,ok:!1,error:a.toWire()}}this.post("_reply",o,this.nextId())}};function Oe(e){return{init:()=>e.init(),ready:()=>e.call("app.ready"),setLoadingProgress:t=>e.call("app.setLoadingProgress",{progress:Math.max(0,Math.min(100,Math.round(t)))}),close:()=>e.call("app.close")}}function Ue(e){return{onPause:t=>e.on("lifecycle.pause",t),onResume:t=>e.on("lifecycle.resume",t),onClosing:t=>e.on("lifecycle.closing",t),onBeforeClose:t=>e.onRequest("app.beforeClose",t)}}function Le(e){return{getInfo:()=>e.call("device.getInfo")}}function De(e){return{query:t=>e.call("permissions.query",{name:t}),request:t=>e.call("permissions.request",{name:t}),onChanged:t=>e.on("permissions.changed",t)}}function Be(e){return{scan:()=>e.call("qr.scan")}}function qe(e){return{get:()=>e.call("location.get")}}function We(e){return{saveImage:t=>e.call("media.saveImage",{dataUrl:t})}}var x={maxBytes:2097152,maxSide:2048,types:["image/png","image/jpeg","image/webp"]},xt=/^data:([^;,]+);base64,/,Ct=/^[A-Za-z0-9+/]*={0,2}$/,Nt=Math.ceil(x.maxBytes/3)*4;function B(e){if(typeof e!="string")return{ok:!1,reason:"image must be a data: URL string"};let t=xt.exec(e.slice(0,40));if(!t)return{ok:!1,reason:"image must be a base64 data: URL"};let n=x.types.find(a=>a===t[1]);if(!n)return{ok:!1,reason:`image type must be ${x.types.join(", ")}`};let o=e.slice(t[0].length);if(o.length>Nt)return{ok:!1,reason:`image is over ${x.maxBytes} bytes`};if(o.length===0||o.length%4!==0||!Ct.test(o))return{ok:!1,reason:"image is not valid base64"};let s=o.length/4*3-(o.endsWith("==")?2:o.endsWith("=")?1:0);return s>x.maxBytes?{ok:!1,reason:`image is over ${x.maxBytes} bytes`}:{ok:!0,type:n,bytes:s}}function d(e){throw new p("INVALID_PARAMS",e)}function v(e,t){let n=e[t];return typeof n=="string"?n:d(`${t} must be a string`)}var S=(e,t)=>e[t]===void 0?void 0:v(e,t),ue=e=>typeof e=="string"&&e.trim()!=="";function ce(e,t){let n=t?v(e,"text"):S(e,"text");n!==void 0&&!ue(n)&&d("text must not be empty")}function q(e,t,n){let o=e[t];return n.find(s=>s===o)??d(`${t} must be one of ${n.join(", ")}`)}function pe(e){let t=e.color;return typeof t=="string"&&/^#[0-9a-f]{6}$/i.test(t)?t:d("color must be #rrggbb")}function $e(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.min(100,t)):d("progress must be a number from 0 to 100")}function de(e,t="url"){let n=e[t];if(typeof n=="string")try{let o=new URL(n);if(o.protocol==="https:"||o.protocol==="http:")return o.href}catch{}return d(`${t} must be an http(s) URL`)}function He(e){let t=e.startParam;if(t!==void 0)return typeof t=="string"&&L.test(t)?t:d("startParam must be 1-64 chars of [A-Za-z0-9_-]")}function Ve(e){let t=S(e,"text");if(t===void 0){e.image===void 0&&d("a story needs an image or text");return}let n=t.trim().length;(n<1||n>ae)&&d(`text must be 1-${ae} chars`)}var Ge=e=>q(e,"name",xe);function je(e){let t=e.buttons;return(!Array.isArray(t)||t.length===0||t.length>3)&&d("buttons must hold 1-3 buttons"),t.map(n=>{let o=w(n)?n:{},s=o.type==="cancel"||o.type==="destructive"?o.type:"default";return{id:v(o,"id"),text:v(o,"text"),type:s}})}function Ke(e){let t=v(e,"name");t.length===0&&d("name must not be empty");let n=e.props??{};if(!w(n)||Array.isArray(n))return d("props must be an object");for(let[o,s]of Object.entries(n))typeof s!="string"&&typeof s!="boolean"&&!(typeof s=="number"&&Number.isFinite(s))&&d(`props.${o} must be a string, number or boolean`);return{name:t,props:n}}function ze(e){return{open:t=>e.call("link.open",{url:t})}}function Fe(e){return{writeText:t=>e.call("clipboard.writeText",{text:t}),readText:async()=>(await e.call("clipboard.readText")).text}}function X(e,t,n,o){if(o&&(n.text!==void 0||o==="required")&&!ue(n.text))return Promise.reject(new p("INVALID_PARAMS","text must not be empty"));if(n.image!==void 0){let s=B(n.image);if(!s.ok)return Promise.reject(new p("INVALID_PARAMS",s.reason))}return e.call(t,n)}function Xe(e){return{system:t=>X(e,"share.system",t),toChat:t=>X(e,"share.toChat",t,"required"),toPost:t=>X(e,"share.toPost",t,"nonBlank"),toStory:t=>X(e,"share.toStory",t,"nonBlank")}}function Ye(e){return{track:(t,n)=>e.call("analytics.track",{name:t,props:n})}}var _t=e=>e&&(e.displayName??e.avatarUrl??e.locale)!==void 0?e:null;function Qe(e){let t,n=async()=>{let o=await e.init();if(!e.supports("auth.requestProfile"))return{user:_t(o.user)};let s=await e.call("auth.requestProfile");return{user:le(s?.user)}};return{getLaunchToken:async(o={})=>(await e.call("auth.getLaunchToken",o)).token,requestProfile:()=>t??(t=n().finally(()=>{t=void 0}))}}function Ze(e){return{open:t=>e.call("payment.open",t)}}function Je(e){return{requestPermission:()=>e.call("notifications.requestPermission"),getPermission:()=>e.call("notifications.getPermission")}}function et(e){return{loadRewarded:t=>e.call("ads.loadRewarded",{placement:t}),showRewarded:t=>e.call("ads.showRewarded",{placement:t}),loadInterstitial:t=>e.call("ads.loadInterstitial",{placement:t}),showInterstitial:t=>e.call("ads.showInterstitial",{placement:t}),showBanner:t=>e.call("ads.showBanner",t),hideBanner:()=>e.call("ads.hideBanner"),on:(t,n)=>e.on(t,n),onBeforeBreak:t=>e.onRequest("ads.beforeBreak",t)}}function tt(e){return{get:async t=>(await e.call("storage.get",{key:t})).value??null,getMany:async t=>(await e.call("storage.getMany",{keys:t})).values,set:(t,n)=>e.call("storage.set",{key:t,value:n}),remove:t=>e.call("storage.remove",{key:t}),keys:async()=>(await e.call("storage.keys")).keys,clear:()=>e.call("storage.clear")}}function nt(e){return{showToast:t=>e.call("ui.showToast",t),showAlert:t=>e.call("ui.showAlert",t),showConfirm:t=>e.call("ui.showConfirm",t),showPopup:t=>e.call("ui.showPopup",t),setBackButtonVisible:t=>e.call("ui.setBackButtonVisible",{visible:t}),setHeaderColor:t=>e.call("ui.setHeaderColor",{color:t}),setBackgroundColor:t=>e.call("ui.setBackgroundColor",{color:t}),setOrientation:t=>e.call("ui.setOrientation",{orientation:t}),getTheme:()=>e.call("ui.getTheme"),onBackButtonPressed:t=>e.on("ui.backButtonPressed",t),onThemeChanged:t=>e.on("ui.themeChanged",t),onViewportChanged:t=>e.on("ui.viewportChanged",t)}}function rt(e){return{impact:(t="medium")=>e.call("haptic.impact",{style:t}),notification:t=>e.call("haptic.notification",{type:t}),selection:()=>e.call("haptic.selection")}}var ot="0.1.0";function me(e,t){let n=new D(e,t);return{version:ot,transport:e.name,supports:o=>n.supports(o),call:(o,s,a)=>n.call(o,s,a),on:(o,s)=>n.on(o,s),app:Oe(n),lifecycle:Ue(n),ui:nt(n),haptic:rt(n),storage:tt(n),link:ze(n),clipboard:Fe(n),share:Xe(n),analytics:Ye(n),device:Le(n),permissions:De(n),qr:Be(n),location:qe(n),media:We(n),auth:Qe(n),payment:Ze(n),notifications:Je(n),ads:et(n)}}var fe=new Set;function Y(e,t){return e.__idcMiniApp??(e.__idcMiniApp={_dispatch(n){for(let o of fe)o(n)}}),fe.add(t),()=>fe.delete(t)}var st=e=>typeof e.MiniAppAndroid?.call=="function";function it(e){return{name:"android",send:t=>e.MiniAppAndroid?.call(JSON.stringify(t)),listen:t=>Y(e,t)}}var at=e=>typeof e.webkit?.messageHandlers?.miniapp?.postMessage=="function";function lt(e){return{name:"ios",send:t=>e.webkit?.messageHandlers?.miniapp?.postMessage(JSON.stringify(t)),listen:t=>Y(e,t)}}var T=(e,t)=>e>>>t|e<<32-t,ut=e=>(e-Math.floor(e))*4294967296>>>0,W=[];for(let e=2;W.length<64;e++)W.every(t=>e%t!==0)&&W.push(e);var It=Uint32Array.from(W,e=>ut(Math.cbrt(e))),Ot=Uint32Array.from(W.slice(0,8),e=>ut(Math.sqrt(e)));function ct(e){let t=e.length+72&-64,n=new Uint8Array(t);n.set(e),n[e.length]=128;let o=new DataView(n.buffer);o.setUint32(t-8,Math.floor(e.length/2**29)),o.setUint32(t-4,e.length*8>>>0);let s=Uint32Array.from(Ot),a=new Uint32Array(64),c=new Uint32Array(8);for(let m=0;m<t;m+=64){for(let u=0;u<16;u++)a[u]=o.getUint32(m+u*4);for(let u=16;u<64;u++){let y=a[u-15],P=a[u-2];a[u]=a[u-16]+(T(y,7)^T(y,18)^y>>>3)+a[u-7]+(T(P,17)^T(P,19)^P>>>10)}c.set(s);for(let u=0;u<64;u++){let[y,P,C,J,k,N,_,E]=Array.from(c),H=E+(T(k,6)^T(k,11)^T(k,25))+(k&N^~k&_)+It[u]+a[u],V=(T(y,2)^T(y,13)^T(y,22))+(y&P^y&C^P&C);c.set([H+V,y,P,C,J+H,k,N,_])}for(let u=0;u<8;u++)s[u]=s[u]+c[u]}let f=new Uint8Array(32),g=new DataView(f.buffer);for(let m=0;m<8;m++)g.setUint32(m*4,s[m]);return f}var b="idcMiniApp:",$=new TextEncoder,Ut=["pointerup","touchend","keydown","click"],Lt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGN46uELAAOQAXsmNkYKAAAAAElFTkSuQmCC",pt={id:"mockUserId_00000000000",displayName:"Mock User",avatarUrl:Lt,locale:"en"},he=/^[A-Za-z0-9_-]{1,32}$/;function Dt(e){if(e===void 0)return pt;let t=ct($.encode(e)),n=btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").slice(0,22);return{...pt,id:n,displayName:`Mock User ${e}`}}var dt=3e3;function Q(e){if(He(e),e.url!==void 0&&de(e),e.image!==void 0){let t=B(e.image);t.ok||d(t.reason)}}function Bt(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},key:t=>[...e.keys()][t]??null,get length(){return e.size}}}function Z(e){let t=e.key;return(typeof t!="string"||t.length===0||t.length>ie)&&d(`key must be a 1-${ie} char string`),t}var ge=e=>{let t=S(e,"title"),n=v(e,"message");return t===void 0?n:`${t}
|
|
1
|
+
"use strict";(()=>{var Tt=Object.defineProperty;var At=(e,t,n)=>t in e?Tt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var M=(e,t,n)=>At(e,typeof t!="symbol"?t+"":t,n);var re=["app.init","app.ready","app.setLoadingProgress","app.close","ui.showToast","ui.showAlert","ui.showConfirm","ui.showPopup","ui.setBackButtonVisible","ui.setHeaderColor","ui.setBackgroundColor","ui.setOrientation","ui.getTheme","haptic.impact","haptic.notification","haptic.selection","storage.get","storage.getMany","storage.set","storage.remove","storage.keys","storage.clear","link.open","clipboard.writeText","clipboard.readText","share.system","share.toChat","share.toPost","share.toStory","analytics.track","device.getInfo","permissions.query","permissions.request","qr.scan","location.get","media.saveImage","auth.getLaunchToken","auth.requestProfile","payment.open","notifications.requestPermission","notifications.getPermission","ads.loadRewarded","ads.showRewarded","ads.loadInterstitial","ads.showInterstitial","ads.showBanner","ads.hideBanner"],oe=["lifecycle.pause","lifecycle.resume","lifecycle.closing","ui.backButtonPressed","ui.themeChanged","ui.viewportChanged","permissions.changed","ads.loaded","ads.failed","ads.shown","ads.closed","ads.rewarded"],St=["app.beforeClose","ads.beforeBreak"];function Ee(e){return e.startsWith("payment.")||e.startsWith("ads.")||e.startsWith("share.")||e==="ui.showAlert"||e==="ui.showConfirm"||e==="ui.showPopup"||e==="permissions.request"||z(e)!==void 0}var se=1024*1024,ie=128,L=/^[A-Za-z0-9_-]{1,64}$/,ae=500,be=/^[A-Za-z0-9_-]{1,64}$/,Re=new Set(["link.open","clipboard.writeText","clipboard.readText","share.system","share.toChat","share.toPost","share.toStory","permissions.request","qr.scan","media.saveImage","payment.open","notifications.requestPermission","ads.showRewarded"]),xe=["profile","camera","microphone","location","notifications","photos"],Et={"auth.requestProfile":"profile","qr.scan":"camera","location.get":"location","media.saveImage":"photos","notifications.requestPermission":"notifications"},bt=new Map(Object.entries(Et)),z=e=>bt.get(e);var en=1,tn=["METHOD_NOT_SUPPORTED","INVALID_PARAMS","TIMEOUT","QUOTA_EXCEEDED","PERMISSION_DENIED","CANCELLED","INTERNAL_ERROR"],p=class extends Error{constructor(n,o){super(o);M(this,"code");this.name="MiniAppError",this.code=n}toWire(){return{code:this.code,message:this.message}}},w=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),A=e=>typeof e=="string"?e:void 0;function Ce(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}return w(t)&&t.v===1?t:null}function Ne(e){let t=Ce(e);if(!t)return null;let n=A(t.id),o=A(t.name);switch(t.type){case"result":return n===void 0?null:t.ok===!0?{v:1,type:"result",id:n,ok:!0,data:t.data}:t.ok!==!1||!w(t.error)?null:{v:1,type:"result",id:n,ok:!1,error:Rt(t.error)};case"event":return o===void 0?null:{v:1,type:"event",name:o,data:t.data};case"request":return n===void 0||o===void 0?null:{v:1,type:"request",id:n,name:o,data:t.data,timeoutMs:typeof t.timeoutMs=="number"?t.timeoutMs:3e3};default:return null}}function Rt(e){return{code:A(e.code)??"INTERNAL_ERROR",message:A(e.message)??""}}function nn(e){let t=Ce(e);return!t||typeof t.id!="string"||typeof t.method!="string"?null:{v:1,id:t.id,method:t.method,params:t.params,gesture:t.gesture===!0}}function le(e){return!w(e)||typeof e.id!="string"?null:{id:e.id,displayName:A(e.displayName),avatarUrl:A(e.avatarUrl),locale:A(e.locale)}}function _e(e){if(!w(e))throw new p("INTERNAL_ERROR","app.init returned no result");return{protocol:typeof e.protocol=="number"?e.protocol:1,methods:Array.isArray(e.methods)?e.methods.filter(t=>typeof t=="string"):[],limits:w(e.limits)?e.limits:{},user:le(e.user),startParam:A(e.startParam)??null,launchToken:A(e.launchToken)??null}}var Ie=1e4,F=1e4,D=class{constructor(t,n={}){M(this,"transport");M(this,"timeoutMs");M(this,"now");M(this,"pending",new Map);M(this,"events",new Map);M(this,"requests",new Map);M(this,"seq",0);M(this,"lastGestureAt",Number.NEGATIVE_INFINITY);M(this,"initPromise");M(this,"methods");this.transport=t,this.timeoutMs=n.timeoutMs??Ie,this.now=n.now??Date.now;let o=()=>{this.lastGestureAt=this.now()};n.gestureTarget?.addEventListener("pointerdown",o,{capture:!0}),n.gestureTarget?.addEventListener("keydown",o,{capture:!0}),t.listen(s=>this.receive(s))}init(){return this.initPromise??(this.initPromise=this.send("app.init",{protocol:1},{}).then(t=>{let n=_e(t);return this.methods=new Set(n.methods),n},t=>{throw this.initPromise=void 0,t})),this.initPromise}supports(t){return this.methods?.has(t)??!1}async call(t,n,o={}){let a=await this.init();if(t!=="app.init"){if(!this.supports(t))throw new p("METHOD_NOT_SUPPORTED",`host does not support ${t}`);a=await this.send(t,n,o)}return a}on(t,n){let o=a=>n(a),s=this.events.get(t);return s||this.events.set(t,s=new Set),s.add(o),()=>s.delete(o)}onRequest(t,n){return this.requests.set(t,n),()=>{this.requests.get(t)===n&&this.requests.delete(t)}}nextId(){return`c_${++this.seq}`}hasGesture(){return this.now()-this.lastGestureAt<=F}post(t,n,o){let s={v:1,id:o,method:t,gesture:this.hasGesture()};n!==void 0&&(s.params=n),this.transport.send(s)}send(t,n,o){let s=this.nextId(),a=o.timeoutMs??(Ee(t)?0:this.timeoutMs);return new Promise((c,f)=>{let g=a>0?setTimeout(()=>{this.pending.delete(s),f(new p("TIMEOUT",`${t} timed out after ${a} ms`))},a):void 0;this.pending.set(s,{resolve:c,reject:f,timer:g});try{this.post(t,n,s)}catch(m){clearTimeout(g),this.pending.delete(s),f(new p("INTERNAL_ERROR",`transport failed: ${String(m)}`))}})}receive(t){let n=Ne(t);if(n)if(n.type==="result"){let o=this.pending.get(n.id);if(!o)return;this.pending.delete(n.id),clearTimeout(o.timer),n.ok?o.resolve(n.data):o.reject(new p(n.error.code,n.error.message))}else if(n.type==="event")for(let o of this.events.get(n.name)??[])try{o(n.data)}catch(s){setTimeout(()=>{throw s})}else this.answer(n)}async answer(t){let n=this.requests.get(t.name),o;if(!n)o={id:t.id,ok:!1,error:{code:"METHOD_NOT_SUPPORTED",message:t.name}};else try{o={id:t.id,ok:!0,data:await n(t.data)}}catch(s){let a=s instanceof p?s:new p("INTERNAL_ERROR",String(s));o={id:t.id,ok:!1,error:a.toWire()}}this.post("_reply",o,this.nextId())}};function Oe(e){return{init:()=>e.init(),ready:()=>e.call("app.ready"),setLoadingProgress:t=>e.call("app.setLoadingProgress",{progress:Math.max(0,Math.min(100,Math.round(t)))}),close:()=>e.call("app.close")}}function Ue(e){return{onPause:t=>e.on("lifecycle.pause",t),onResume:t=>e.on("lifecycle.resume",t),onClosing:t=>e.on("lifecycle.closing",t),onBeforeClose:t=>e.onRequest("app.beforeClose",t)}}function Le(e){return{getInfo:()=>e.call("device.getInfo")}}function De(e){return{query:t=>e.call("permissions.query",{name:t}),request:t=>e.call("permissions.request",{name:t}),onChanged:t=>e.on("permissions.changed",t)}}function Be(e){return{scan:()=>e.call("qr.scan")}}function qe(e){return{get:()=>e.call("location.get")}}function $e(e){return{saveImage:t=>e.call("media.saveImage",{dataUrl:t})}}var x={maxBytes:2097152,maxSide:2048,types:["image/png","image/jpeg","image/webp"]},xt=/^data:([^;,]+);base64,/,Ct=/^[A-Za-z0-9+/]*={0,2}$/,Nt=Math.ceil(x.maxBytes/3)*4;function B(e){if(typeof e!="string")return{ok:!1,reason:"image must be a data: URL string"};let t=xt.exec(e.slice(0,40));if(!t)return{ok:!1,reason:"image must be a base64 data: URL"};let n=x.types.find(a=>a===t[1]);if(!n)return{ok:!1,reason:`image type must be ${x.types.join(", ")}`};let o=e.slice(t[0].length);if(o.length>Nt)return{ok:!1,reason:`image is over ${x.maxBytes} bytes`};if(o.length===0||o.length%4!==0||!Ct.test(o))return{ok:!1,reason:"image is not valid base64"};let s=o.length/4*3-(o.endsWith("==")?2:o.endsWith("=")?1:0);return s>x.maxBytes?{ok:!1,reason:`image is over ${x.maxBytes} bytes`}:{ok:!0,type:n,bytes:s}}function d(e){throw new p("INVALID_PARAMS",e)}function P(e,t){let n=e[t];return typeof n=="string"?n:d(`${t} must be a string`)}var S=(e,t)=>e[t]===void 0?void 0:P(e,t),ue=e=>typeof e=="string"&&e.trim()!=="";function ce(e,t){let n=t?P(e,"text"):S(e,"text");n!==void 0&&!ue(n)&&d("text must not be empty")}function q(e,t,n){let o=e[t];return n.find(s=>s===o)??d(`${t} must be one of ${n.join(", ")}`)}function pe(e){let t=e.color;return typeof t=="string"&&/^#[0-9a-f]{6}$/i.test(t)?t:d("color must be #rrggbb")}function We(e){let t=e.progress;return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.min(100,t)):d("progress must be a number from 0 to 100")}function de(e,t="url"){let n=e[t];if(typeof n=="string")try{let o=new URL(n);if(o.protocol==="https:"||o.protocol==="http:")return o.href}catch{}return d(`${t} must be an http(s) URL`)}function He(e){let t=e.startParam;if(t!==void 0)return typeof t=="string"&&L.test(t)?t:d("startParam must be 1-64 chars of [A-Za-z0-9_-]")}function Ve(e){let t=S(e,"text");if(t===void 0){e.image===void 0&&d("a story needs an image or text");return}let n=t.trim().length;(n<1||n>ae)&&d(`text must be 1-${ae} chars`)}var Ge=e=>q(e,"name",xe);function je(e){let t=e.buttons;return(!Array.isArray(t)||t.length===0||t.length>3)&&d("buttons must hold 1-3 buttons"),t.map(n=>{let o=w(n)?n:{},s=o.type==="cancel"||o.type==="destructive"?o.type:"default";return{id:P(o,"id"),text:P(o,"text"),type:s}})}function Ke(e){let t=P(e,"name");t.length===0&&d("name must not be empty");let n=e.props??{};if(!w(n)||Array.isArray(n))return d("props must be an object");for(let[o,s]of Object.entries(n))typeof s!="string"&&typeof s!="boolean"&&!(typeof s=="number"&&Number.isFinite(s))&&d(`props.${o} must be a string, number or boolean`);return{name:t,props:n}}function ze(e){return{open:t=>e.call("link.open",{url:t})}}function Fe(e){return{writeText:t=>e.call("clipboard.writeText",{text:t}),readText:async()=>(await e.call("clipboard.readText")).text}}function X(e,t,n,o){if(o&&(n.text!==void 0||o==="required")&&!ue(n.text))return Promise.reject(new p("INVALID_PARAMS","text must not be empty"));if(n.image!==void 0){let s=B(n.image);if(!s.ok)return Promise.reject(new p("INVALID_PARAMS",s.reason))}return e.call(t,n)}function Xe(e){return{system:t=>X(e,"share.system",t),toChat:t=>X(e,"share.toChat",t,"required"),toPost:t=>X(e,"share.toPost",t,"nonBlank"),toStory:t=>X(e,"share.toStory",t,"nonBlank")}}function Ye(e){return{track:(t,n)=>e.call("analytics.track",{name:t,props:n})}}var _t=e=>e&&(e.displayName??e.avatarUrl??e.locale)!==void 0?e:null;function Qe(e){let t,n=async()=>{let o=await e.init();if(!e.supports("auth.requestProfile"))return{user:_t(o.user)};let s=await e.call("auth.requestProfile");return{user:le(s?.user)}};return{getLaunchToken:async(o={})=>(await e.call("auth.getLaunchToken",o)).token,requestProfile:()=>t??(t=n().finally(()=>{t=void 0}))}}function Ze(e){return{open:t=>e.call("payment.open",t)}}function Je(e){return{requestPermission:()=>e.call("notifications.requestPermission"),getPermission:()=>e.call("notifications.getPermission")}}function et(e){return{loadRewarded:t=>e.call("ads.loadRewarded",{placement:t}),showRewarded:t=>e.call("ads.showRewarded",{placement:t}),loadInterstitial:t=>e.call("ads.loadInterstitial",{placement:t}),showInterstitial:t=>e.call("ads.showInterstitial",{placement:t}),showBanner:t=>e.call("ads.showBanner",t),hideBanner:()=>e.call("ads.hideBanner"),on:(t,n)=>e.on(t,n),onBeforeBreak:t=>e.onRequest("ads.beforeBreak",t)}}function tt(e){return{get:async t=>(await e.call("storage.get",{key:t})).value??null,getMany:async t=>(await e.call("storage.getMany",{keys:t})).values,set:(t,n)=>e.call("storage.set",{key:t,value:n}),remove:t=>e.call("storage.remove",{key:t}),keys:async()=>(await e.call("storage.keys")).keys,clear:()=>e.call("storage.clear")}}function nt(e){return{showToast:t=>e.call("ui.showToast",t),showAlert:t=>e.call("ui.showAlert",t),showConfirm:t=>e.call("ui.showConfirm",t),showPopup:t=>e.call("ui.showPopup",t),setBackButtonVisible:t=>e.call("ui.setBackButtonVisible",{visible:t}),setHeaderColor:t=>e.call("ui.setHeaderColor",{color:t}),setBackgroundColor:t=>e.call("ui.setBackgroundColor",{color:t}),setOrientation:t=>e.call("ui.setOrientation",{orientation:t}),getTheme:()=>e.call("ui.getTheme"),onBackButtonPressed:t=>e.on("ui.backButtonPressed",t),onThemeChanged:t=>e.on("ui.themeChanged",t),onViewportChanged:t=>e.on("ui.viewportChanged",t)}}function rt(e){return{impact:(t="medium")=>e.call("haptic.impact",{style:t}),notification:t=>e.call("haptic.notification",{type:t}),selection:()=>e.call("haptic.selection")}}var ot="0.1.0";function me(e,t){let n=new D(e,t);return{version:ot,transport:e.name,supports:o=>n.supports(o),call:(o,s,a)=>n.call(o,s,a),on:(o,s)=>n.on(o,s),app:Oe(n),lifecycle:Ue(n),ui:nt(n),haptic:rt(n),storage:tt(n),link:ze(n),clipboard:Fe(n),share:Xe(n),analytics:Ye(n),device:Le(n),permissions:De(n),qr:Be(n),location:qe(n),media:$e(n),auth:Qe(n),payment:Ze(n),notifications:Je(n),ads:et(n)}}var fe=new Set;function Y(e,t){return e.__idcMiniApp??(e.__idcMiniApp={_dispatch(n){for(let o of fe)o(n)}}),fe.add(t),()=>fe.delete(t)}var st=e=>typeof e.MiniAppAndroid?.call=="function";function it(e){return{name:"android",send:t=>e.MiniAppAndroid?.call(JSON.stringify(t)),listen:t=>Y(e,t)}}var at=e=>typeof e.webkit?.messageHandlers?.miniapp?.postMessage=="function";function lt(e){return{name:"ios",send:t=>e.webkit?.messageHandlers?.miniapp?.postMessage(JSON.stringify(t)),listen:t=>Y(e,t)}}var T=(e,t)=>e>>>t|e<<32-t,ut=e=>(e-Math.floor(e))*4294967296>>>0,$=[];for(let e=2;$.length<64;e++)$.every(t=>e%t!==0)&&$.push(e);var It=Uint32Array.from($,e=>ut(Math.cbrt(e))),Ot=Uint32Array.from($.slice(0,8),e=>ut(Math.sqrt(e)));function ct(e){let t=e.length+72&-64,n=new Uint8Array(t);n.set(e),n[e.length]=128;let o=new DataView(n.buffer);o.setUint32(t-8,Math.floor(e.length/2**29)),o.setUint32(t-4,e.length*8>>>0);let s=Uint32Array.from(Ot),a=new Uint32Array(64),c=new Uint32Array(8);for(let m=0;m<t;m+=64){for(let u=0;u<16;u++)a[u]=o.getUint32(m+u*4);for(let u=16;u<64;u++){let y=a[u-15],k=a[u-2];a[u]=a[u-16]+(T(y,7)^T(y,18)^y>>>3)+a[u-7]+(T(k,17)^T(k,19)^k>>>10)}c.set(s);for(let u=0;u<64;u++){let[y,k,C,J,v,N,_,E]=Array.from(c),H=E+(T(v,6)^T(v,11)^T(v,25))+(v&N^~v&_)+It[u]+a[u],V=(T(y,2)^T(y,13)^T(y,22))+(y&k^y&C^k&C);c.set([H+V,y,k,C,J+H,v,N,_])}for(let u=0;u<8;u++)s[u]=s[u]+c[u]}let f=new Uint8Array(32),g=new DataView(f.buffer);for(let m=0;m<8;m++)g.setUint32(m*4,s[m]);return f}var b="idcMiniApp:",W=new TextEncoder,Ut=["pointerup","touchend","keydown","click"],Lt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGN46uELAAOQAXsmNkYKAAAAAElFTkSuQmCC",pt={id:"mockUserId_00000000000",displayName:"Mock User",avatarUrl:Lt,locale:"en"},he=/^[A-Za-z0-9_-]{1,32}$/;function Dt(e){if(e===void 0)return pt;let t=ct(W.encode(e)),n=btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").slice(0,22);return{...pt,id:n,displayName:`Mock User ${e}`}}var dt=3e3;function Q(e){if(He(e),e.url!==void 0&&de(e),e.image!==void 0){let t=B(e.image);t.ok||d(t.reason)}}function Bt(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)},key:t=>[...e.keys()][t]??null,get length(){return e.size}}}function Z(e){let t=e.key;return(typeof t!="string"||t.length===0||t.length>ie)&&d(`key must be a 1-${ie} char string`),t}var ge=e=>{let t=S(e,"title"),n=P(e,"message");return t===void 0?n:`${t}
|
|
2
2
|
|
|
3
|
-
${n}`};function mt(e,t){if(t===null)return null;let n=t.trim().toLowerCase();return e.find((s,a)=>String(a+1)===n||s.id.toLowerCase()===n||s.text.toLowerCase()===n)?.id??null}function ye(e={}){let t=e.storage??Bt(),n=e.limitBytes??se,o=e.now??Date.now,s=e.dialogs,a=e.userName!==void 0&&he.test(e.userName)?e.userName:void 0,c=e.user===void 0?Dt(a):e.user,f=async()=>{let r=e.user===void 0?await e.avatar?.catch(()=>null):null;return c&&r?{...c,avatarUrl:r}:c},g=e.notifications??"prompt",m=r=>{g=r,e.onNotificationsConsent?.(r,a)};m(g);let u=c===null?"denied":e.profile??"prompt",y="",
|
|
3
|
+
${n}`};function mt(e,t){if(t===null)return null;let n=t.trim().toLowerCase();return e.find((s,a)=>String(a+1)===n||s.id.toLowerCase()===n||s.text.toLowerCase()===n)?.id??null}function ye(e={}){let t=e.storage??Bt(),n=e.limitBytes??se,o=e.now??Date.now,s=e.dialogs,a=e.userName!==void 0&&he.test(e.userName)?e.userName:void 0,c=e.user===void 0?Dt(a):e.user,f=async()=>{let r=e.user===void 0?await e.avatar?.catch(()=>null):null;return c&&r?{...c,avatarUrl:r}:c},g=e.notifications??"prompt",m=r=>{g=r,e.onNotificationsConsent?.(r,a)};m(g);let u=c===null?"denied":e.profile??"prompt",y="",k=e.colorScheme??"light",C=!1,J=0,v=new Map,N=null,_={},E=null,H=Promise.all([Promise.resolve(e.scopes).then(r=>{N=r?new Set(r):null},()=>{}),Promise.resolve(e.permissionReasons).then(r=>{_=r??{}},()=>{}),Promise.resolve(e.launchTokens).then(r=>{E=c?r??null:null},()=>{})]),V=(r,i)=>_[i]?`${r}
|
|
4
4
|
|
|
5
|
-
${_[i]}`:r,U=r=>N===null||N.has(r),Pe=Number.NEGATIVE_INFINITY,ee=new Set,G=r=>setTimeout(()=>ee.forEach(i=>i(r)),0),I=(r,i)=>G({v:1,type:"event",name:r,data:i}),te=()=>{let r=[];for(let i=0;i<t.length;i++){let l=t.key(i);l?.startsWith(b)&&r.push(l.slice(b.length))}return r},ht=r=>te().filter(i=>i!==r).reduce((i,l)=>i
|
|
5
|
+
${_[i]}`:r,U=r=>N===null||N.has(r),Pe=Number.NEGATIVE_INFINITY,ee=new Set,G=r=>setTimeout(()=>ee.forEach(i=>i(r)),0),I=(r,i)=>G({v:1,type:"event",name:r,data:i}),te=()=>{let r=[];for(let i=0;i<t.length;i++){let l=t.key(i);l?.startsWith(b)&&r.push(l.slice(b.length))}return r},ht=r=>te().filter(i=>i!==r).reduce((i,l)=>i+W.encode(l).length+W.encode(t.getItem(b+l)??"").length,0),ke=()=>{if(g!=="prompt")return g;let r=s?s.confirm(V("Allow this app to send you notifications?","notifications")):!0;return m(r?"granted":"denied"),I("permissions.changed",{name:"notifications",state:g}),g},ve=()=>(u!=="prompt"||(u=(s?s.confirm(V("Allow this app to see your name and avatar?","profile")):!0)?"granted":"denied",I("permissions.changed",{name:"profile",state:u})),u),Te=(r,i)=>{let l=Ge(r);return U(l)?l==="notifications"?{state:i?ke():g}:l==="profile"?{state:i?ve():u}:{state:"unavailable"}:{state:"unavailable"}},ne={"app.ready":()=>null,"app.setLoadingProgress":r=>(We(r),null),"app.close":()=>null,"ui.showToast":r=>(P(r,"message"),null),"ui.showAlert":r=>{let i=ge(r);return s?.alert(i),null},"ui.showConfirm":r=>{let i=ge(r);return{confirmed:s?s.confirm(i):!0}},"ui.showPopup":r=>{let i=ge(r),l=je(r);if(!s)return{buttonId:l[0]?.id??null};let h=l.map((K,vt)=>`${vt+1}. ${K.text}`).join(`
|
|
6
6
|
`),O=`
|
|
7
7
|
|
|
8
8
|
Pick 1-${l.length}, or Cancel to dismiss.`,j=K=>mt(l,K)===null&&!!K?.trim(),R=s.prompt(`${i}
|
|
9
9
|
|
|
10
10
|
${h}`,"1");return j(R)&&(R=s.prompt(`${i}
|
|
11
11
|
|
|
12
|
-
${h}${O}`,"1")),j(R)&&console.warn(`[miniapp-sdk] ui.showPopup: "${R}" matches no button, treated as dismissed`),{buttonId:mt(l,R)}},"ui.setBackButtonVisible":r=>(typeof r.visible!="boolean"&&d("visible must be a boolean"),C=r.visible,null),"ui.setHeaderColor":r=>(pe(r),null),"ui.setBackgroundColor":r=>(pe(r),null),"ui.setOrientation":r=>(q(r,"orientation",["portrait","landscape","auto"]),null),"ui.getTheme":()=>({colorScheme:
|
|
12
|
+
${h}${O}`,"1")),j(R)&&console.warn(`[miniapp-sdk] ui.showPopup: "${R}" matches no button, treated as dismissed`),{buttonId:mt(l,R)}},"ui.setBackButtonVisible":r=>(typeof r.visible!="boolean"&&d("visible must be a boolean"),C=r.visible,null),"ui.setHeaderColor":r=>(pe(r),null),"ui.setBackgroundColor":r=>(pe(r),null),"ui.setOrientation":r=>(q(r,"orientation",["portrait","landscape","auto"]),null),"ui.getTheme":()=>({colorScheme:k}),"haptic.impact":r=>(q(r,"style",["light","medium","heavy"]),null),"haptic.notification":r=>(q(r,"type",["success","warning","error"]),null),"haptic.selection":()=>null,"storage.get":r=>({value:t.getItem(b+Z(r))}),"storage.getMany":r=>{Array.isArray(r.keys)||d("keys must be an array");let i={};for(let l of r.keys)i[Z({key:l})]=t.getItem(b+String(l));return{values:i}},"storage.set":r=>{let i=Z(r),l=P(r,"value");if(ht(i)+W.encode(i).length+W.encode(l).length>n)throw new p("QUOTA_EXCEEDED",`storage is limited to ${n} bytes`);return t.setItem(b+i,l),null},"storage.remove":r=>(t.removeItem(b+Z(r)),null),"storage.keys":()=>({keys:te()}),"storage.clear":()=>(te().forEach(r=>t.removeItem(b+r)),null),"link.open":r=>{let i=de(r);return s?.open(i,"_blank","noopener,noreferrer"),null},"clipboard.writeText":r=>(y=P(r,"text"),null),"clipboard.readText":()=>({text:y}),"share.toChat":r=>(ce(r,!0),Q(r),e.onShare?.("share.toChat",r),{shared:!0}),"share.toPost":r=>{ce(r,!1);let i=S(r,"text");return Q(r),s&&!s.confirm(`Share to your IdolChat feed?
|
|
13
13
|
|
|
14
14
|
${i??""}`)?{shared:!1}:(e.onShare?.("share.toPost",r),{shared:!0})},"share.toStory":r=>{let i=S(r,"text");return Ve(r),Q(r),s&&!s.confirm(`Share to your IdolChat story?
|
|
15
15
|
|
|
16
|
-
${i??""}`)?{shared:!1}:(e.onShare?.("share.toStory",r),{shared:!0})},"share.system":r=>(S(r,"text"),S(r,"title"),Q(r),e.onShare?.("share.system",r),null),"analytics.track":r=>(Ke(r),null),"device.getInfo":()=>({platform:"web",hostVersion:"mock",safeArea:{top:0,bottom:0,left:0,right:0}}),"permissions.query":r=>Te(r,!1),"permissions.request":r=>Te(r,!0),"notifications.requestPermission":()=>({state:ke()}),"notifications.getPermission":()=>({state:U("notifications")?g:"unavailable"}),"auth.requestProfile":async()=>({user:ve()==="granted"?await f():null})},Ae=()=>U("profile")&&u==="granted",Se=async r=>{let i=S(r,"nonce");if(i!==void 0&&!be.test(i)&&d("nonce must be 1-64 chars of [A-Za-z0-9_-]"),!E)throw new p("METHOD_NOT_SUPPORTED","no launch tokens here");try{return{token:await E({...i===void 0?{}:{nonce:i},profile:Ae(),...a===void 0||e.user!==void 0?{}:{user:a}})}}catch(l){throw new p("INTERNAL_ERROR",`launch token: ${String(l)}`)}};ne["app.init"]=async()=>({protocol:1,methods:[...Object.keys(ne),...E?["auth.getLaunchToken"]:[]].filter(r=>{let i=z(r);return i===void 0||U(i)}),limits:{storageBytes:n},user:c&&(Ae()?await f():{id:c.id}),startParam:e.startParam??null,launchToken:E?(await Se({}).catch(()=>null))?.token??null:null});let yt=new Set(re),Mt=r=>{if(r.method==="_reply"){let h=w(r.params)?r.params.id:void 0;typeof h=="string"&&
|
|
16
|
+
${i??""}`)?{shared:!1}:(e.onShare?.("share.toStory",r),{shared:!0})},"share.system":r=>(S(r,"text"),S(r,"title"),Q(r),e.onShare?.("share.system",r),null),"analytics.track":r=>(Ke(r),null),"payment.open":r=>{let i=P(r,"invoiceId");return/^inv_[A-Za-z0-9_-]{22}$/.test(i)||d("invoiceId is not an invoice id"),s&&!s.confirm(`Pay invoice ${i}? (mock: no stars move)`)?{status:"cancelled"}:{status:e.payment??"paid"}},"device.getInfo":()=>({platform:"web",hostVersion:"mock",safeArea:{top:0,bottom:0,left:0,right:0}}),"permissions.query":r=>Te(r,!1),"permissions.request":r=>Te(r,!0),"notifications.requestPermission":()=>({state:ke()}),"notifications.getPermission":()=>({state:U("notifications")?g:"unavailable"}),"auth.requestProfile":async()=>({user:ve()==="granted"?await f():null})},Ae=()=>U("profile")&&u==="granted",Se=async r=>{let i=S(r,"nonce");if(i!==void 0&&!be.test(i)&&d("nonce must be 1-64 chars of [A-Za-z0-9_-]"),!E)throw new p("METHOD_NOT_SUPPORTED","no launch tokens here");try{return{token:await E({...i===void 0?{}:{nonce:i},profile:Ae(),...a===void 0||e.user!==void 0?{}:{user:a}})}}catch(l){throw new p("INTERNAL_ERROR",`launch token: ${String(l)}`)}};ne["app.init"]=async()=>({protocol:1,methods:[...Object.keys(ne),...E?["auth.getLaunchToken"]:[]].filter(r=>{let i=z(r);return i===void 0||U(i)}),limits:{storageBytes:n},user:c&&(Ae()?await f():{id:c.id}),startParam:e.startParam??null,launchToken:E?(await Se({}).catch(()=>null))?.token??null:null});let yt=new Set(re),Mt=r=>{if(r.method==="_reply"){let h=w(r.params)?r.params.id:void 0;typeof h=="string"&&v.get(h)?.();return}let i=h=>{let O=h instanceof p?h:new p("INTERNAL_ERROR",String(h));G({v:1,type:"result",id:r.id,ok:!1,error:O.toWire()})},l=o()-Pe<=F;H.then(()=>wt(r,l,i))},wt=(r,i,l)=>{try{let h=z(r.method);if(h!==void 0&&!U(h))throw new p("PERMISSION_DENIED",`no ${h} scope`);let O=r.method==="auth.getLaunchToken"&&E?Se:ne[r.method];if(O===void 0)throw new p("METHOD_NOT_SUPPORTED",yt.has(r.method)?`${r.method} can only be tested inside IdolChat`:`unknown method ${r.method}`);if(Re.has(r.method)&&!i)throw new p("PERMISSION_DENIED","gesture required");let j=O(w(r.params)?r.params:{});Promise.resolve(j).then(R=>G({v:1,type:"result",id:r.id,ok:!0,data:R}),l)}catch(h){l(h)}},Pt=r=>{r.isTrusted&&(Pe=o())};for(let r of Ut)e.doc?.addEventListener(r,Pt,{capture:!0});e.doc?.addEventListener("visibilitychange",()=>{let r=e.doc?.visibilityState==="hidden"?"lifecycle.pause":"lifecycle.resume";I(r,{reason:"background"})});let kt=new Set(oe);return{name:"mock",send:Mt,listen(r){return ee.add(r),()=>ee.delete(r)},controls:{emit(r,i){if(!kt.has(r))throw new TypeError(`${r} is not a host event`);if(w(i)&&r==="ui.themeChanged"&&(k=i.colorScheme==="dark"?"dark":"light"),w(i)&&r==="permissions.changed"){let l=i.state;(l==="prompt"||l==="granted"||l==="denied")&&(i.name==="notifications"&&m(l),i.name==="profile"&&c!==null&&(u=l))}I(r,i)},async close(){if(C)return I("ui.backButtonPressed",void 0),"backButtonPressed";let r=`mock_close_${++J}`;return await new Promise(i=>{let l=setTimeout(i,dt);v.set(r,()=>(clearTimeout(l),i())),G({v:1,type:"request",id:r,name:"app.beforeClose",timeoutMs:dt})}),v.delete(r),I("lifecycle.closing",void 0),"closing"}}}}var ft=e=>e.parent!==e;function gt(e){return{name:"postmessage",send:t=>e.parent.postMessage(t,"*"),listen(t){let n=o=>{o.source===e.parent&&t(o.data)};return e.addEventListener("message",n),()=>e.removeEventListener("message",n)}}}function Me(e){if(at(e))return lt(e);if(st(e))return it(e);if(ft(e))return gt(e);let t=qt(e),n=Kt(e),o=ye({storage:Yt(e),doc:e.document,dialogs:e,avatar:zt(e,t),scopes:t.then($t),permissionReasons:t.then(Wt),launchTokens:n.then(s=>s?.mint??null),onNotificationsConsent:(s,a)=>{n.then(c=>c?.consent(s,a))},...Ft(Xt(e))});return Object.defineProperty(e,"__idolchatMock",{value:o.controls,configurable:!0}),o}async function qt(e){try{let t=new URL("manifest.json",e.location.href),n=await e.fetch(t);if(!n.ok)return null;let o=await n.json();return we(o)?{url:t,body:o}:null}catch{return null}}function $t(e){if(e===null)return null;let t=e.body.scopes??[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Wt(e){let t=e?.body.permissionReasons;return we(t)?Object.fromEntries(Object.entries(t).filter(n=>typeof n[1]=="string")):{}}var Ht="/__idolchat/jwks.json",Vt="/__idolchat/launch-token",Gt="/__idolchat/consent",jt="x-idolchat-dev";async function Kt(e){try{let c=await e.fetch(new URL(Ht,e.location.href),{cache:"no-store"});if(!c.ok||c.headers.get(jt)!=="1")return null}catch{return null}let t=new URL(Vt,e.location.href),n=new URL(Gt,e.location.href),o=Promise.resolve();return{mint:async c=>{let f=await e.fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(c)}),g=await f.json(),m=we(g)?g.token:void 0;if(!f.ok||typeof m!="string")throw new Error(`dev server answered ${f.status}`);return m},consent:(c,f)=>o=o.then(()=>e.fetch(n,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(f===void 0?{state:c}:{state:c,user:f})})).then(()=>{},()=>{})}}async function zt(e,t){try{let n=await t,o=n?.body.icon;if(n===null||typeof o!="string")return null;let s=e.document.createElement("img");s.src=new URL(o,n.url).href,await s.decode();let a=Math.min(256,s.naturalWidth,s.naturalHeight);if(a===0)return null;let c=e.document.createElement("canvas");return c.width=c.height=a,c.getContext("2d")?.drawImage(s,0,0,a,a),c.toDataURL("image/png")}catch{return null}}var we=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ft(e){let t=new URLSearchParams(e),n={},o=t.get("startapp");o!==null&&(n.startParam=L.test(o)?o:null,n.startParam===null&&console.warn(`[miniapp-sdk] ?startapp=${o} ignored: a startParam is 1-64 chars of [A-Za-z0-9_-], so IdolChat would never send it`)),t.get("profile")==="0"&&(n.profile="denied"),t.get("theme")==="dark"&&(n.colorScheme="dark");let s=t.get("user");s!==null&&(he.test(s)?n.userName=s:console.warn(`[miniapp-sdk] ?user=${s} ignored: a test user name is 1-32 chars of [A-Za-z0-9_-]`));let a=t.get("notifications");return(a==="granted"||a==="denied"||a==="prompt")&&(n.notifications=a),n}function Xt(e){try{return e.location.search}catch{return""}}function Yt(e){try{return e.localStorage}catch{return}}var er=typeof window>"u"?void 0:window.MiniApp??(window.MiniApp=me(Me(window),{gestureTarget:window.document}));})();
|
package/dist/types/client.d.ts
CHANGED
|
@@ -141,10 +141,9 @@ export declare function createMiniApp(transport: Transport, opts?: CoreOptions):
|
|
|
141
141
|
};
|
|
142
142
|
payment: {
|
|
143
143
|
open: (p: {
|
|
144
|
-
|
|
145
|
-
payload?: string;
|
|
144
|
+
invoiceId: string;
|
|
146
145
|
}) => Promise<{
|
|
147
|
-
status: "paid" | "cancelled" | "failed";
|
|
146
|
+
status: "paid" | "cancelled" | "failed" | "processing";
|
|
148
147
|
}>;
|
|
149
148
|
};
|
|
150
149
|
notifications: {
|
|
@@ -16,11 +16,11 @@ export declare function authModule(core: MiniAppCore): {
|
|
|
16
16
|
}>;
|
|
17
17
|
};
|
|
18
18
|
export declare function paymentModule(core: MiniAppCore): {
|
|
19
|
+
/** IdolChat's confirm dialog for your server's invoice; grant from the webhook, never this result. */
|
|
19
20
|
open: (p: {
|
|
20
|
-
|
|
21
|
-
payload?: string;
|
|
21
|
+
invoiceId: string;
|
|
22
22
|
}) => Promise<{
|
|
23
|
-
status: "paid" | "cancelled" | "failed";
|
|
23
|
+
status: "paid" | "cancelled" | "failed" | "processing";
|
|
24
24
|
}>;
|
|
25
25
|
};
|
|
26
26
|
export declare function notificationsModule(core: MiniAppCore): {
|
|
@@ -61,6 +61,8 @@ export interface MockOptions {
|
|
|
61
61
|
permissionReasons?: Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>;
|
|
62
62
|
/** Without one (the default), `launchToken` is null and `auth.getLaunchToken` is not offered. */
|
|
63
63
|
launchTokens?: LaunchTokenMinter | Promise<LaunchTokenMinter | null> | null;
|
|
64
|
+
/** What `payment.open` answers once the confirm is accepted; a declined confirm is `cancelled`. */
|
|
65
|
+
payment?: "paid" | "failed" | "processing";
|
|
64
66
|
/** Called with each accepted `share.*` call, i.e. what a host would send. */
|
|
65
67
|
onShare?: (method: "share.toChat" | "share.system" | "share.toPost" | "share.toStory", params: Record<string, unknown>) => void;
|
|
66
68
|
}
|