@lemoncloud/chatic-apps-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/mock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const G=require("./storage-yeS4HWKZ.cjs"),D=["WebAppReady","Ping","FinishSubWebView","SetSubWebViewTitle","TriggerHaptic","SetCanGoBack","SetSubWebViewCloseGuard","ReportSubWebViewError","GetSubWebViewStorage","SetSubWebViewStorage","RemoveSubWebViewStorage","ClearSubWebViewStorage","GetSubWebViewStorageInfo"],M={clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey"},_=["selection","impact","success","warning","error"],U=64*1024,x=16*1024,K=3e3,B=s=>{if(/^(mailto|tel|sms|itms-apps|market):/i.test(s))return!0;const o=/^https?:\/\/([^/?#:@]+)/i.exec(s)?.[1]?.toLowerCase();return o?!/\.(apps|apps-dev)\.chatic\.io$/.test(o)&&!/^app(-dev)?\.chatic\.io$/.test(o):!1},$=(s,o)=>{if(s===void 0)return!0;try{const l=JSON.stringify(s);return l!==void 0&&l.length<=o}catch{return!1}},k=(s,o)=>s==null||typeof s=="string"&&s.length<=o,F=s=>{let o="";for(let l=0;o.length<64;l++){let p=2166136261^l;for(let u=0;u<s.length;u++)p=Math.imul(p^s.charCodeAt(u),16777619);o+=(p>>>0).toString(16).padStart(8,"0")}return o.slice(0,64)},J=s=>{const o=/^https:\/\/([a-z0-9-]+)\.(apps|apps-dev)\.chatic\.io$/.exec(s);return o?`https://${o[2]==="apps"?"app":"app-dev"}.chatic.io/apps/${o[1]}`:s},P=(s={})=>{const o=new Set([...D,...(s.permissions??[]).map(r=>M[r])]),l=window.location.origin,p={protocolVersion:1,viewId:"mock-view",platform:"ios",appVersion:"0.0.0-mock",locale:"ko",theme:"light",params:{},appLink:J(l),...s.context},u=s.log===!1?()=>{}:(...r)=>console.info("[chatic-apps mock]",...r);let O=!1;const C=[];let T,b=null;const m={theme:p.theme,locale:p.locale};let v=!1,I=!1,V=null,N=0;const d=new Map,E={read:r=>d.get(r),write:(r,n)=>{d.set(r,n)},delete:r=>{d.delete(r)},keys:()=>[...d.keys()]},g=G.ruledStore(E);if(s.storage&&!g.set(s.storage).ok)throw new Error("[chatic-apps mock] options.storage must be JSON entries within the storage limits.");const W=r=>{const n=JSON.stringify(r);if(!O){C.push(n);return}setTimeout(()=>window.dispatchEvent(new MessageEvent("message",{data:n})),0)},y=(r,n)=>W({type:r,success:!0,data:n,refId:`mock-push-${Date.now().toString(36)}`}),c=(r,n,i={})=>W({type:r,success:!0,data:i,refId:n}),a=(r,n,i,e)=>W({type:r,success:!1,error:{code:i,message:e},refId:n}),A=r=>{let n;try{n=JSON.parse(r)}catch{return}const{type:i,refId:e}=n;if(typeof i!="string")return;const t=n.data??{};if(O||(O=!0,C.splice(0).forEach(S=>setTimeout(()=>window.dispatchEvent(new MessageEvent("message",{data:S})),0))),u("←",i,t),b)return i==="FinishSubWebView"?a("OnFinishSubWebView",e,"NOT_OPEN","The view has closed."):u("view closed; no answer to",i);if(r.length>U)return a("ERROR",e,"TOO_LARGE","The message is over 65,536 characters.");if(!o.has(i))return a("ERROR",e,"NOT_FOUND",`${i} is not answered for this page.`);switch(i){case"WebAppReady":return c("OnWebAppReady",e,{appVersion:"2.19.0",protocolVersion:"2.19.0",supportedWebMessages:[...o],supportedAppMessages:[],subWebView:{...p,...m}});case"Ping":return c("Pong",e,{payload:t.payload??""});case"FinishSubWebView":return $(t.result,x)?(b={by:"page",result:t.result},s.onClose?.(b),u("view finished",t.result),c("OnFinishSubWebView",e)):a("OnFinishSubWebView",e,"INVALID","result must be JSON of at most 16 KiB.");case"SetSubWebViewTitle":{const S=typeof t.title=="string"?t.title.trim():"";return!S||S.length>100?a("OnSetSubWebViewTitle",e,"INVALID","title must be 1 to 100 characters."):(T=S,c("OnSetSubWebViewTitle",e))}case"TriggerHaptic":return _.includes(t.kind)?c("OnTriggerHaptic",e):a("OnTriggerHaptic",e,"INVALID_KIND",`Unknown haptic kind: ${String(t.kind)}`);case"SetCanGoBack":return typeof t.canGoBack!="boolean"?a("OnSetCanGoBack",e,"INVALID","canGoBack must be a boolean."):(v=t.canGoBack,c("OnSetCanGoBack",e));case"SetSubWebViewCloseGuard":return typeof t.enabled!="boolean"?a("OnSetSubWebViewCloseGuard",e,"INVALID","enabled must be a boolean."):(I=t.enabled,c("OnSetSubWebViewCloseGuard",e));case"ReportSubWebViewError":return typeof t.message!="string"||!t.message.trim()?a("OnReportSubWebViewError",e,"INVALID","message must be a non-empty string."):N>=20?c("OnReportSubWebViewError",e,{recorded:!1}):(N+=1,console.warn("[chatic-apps mock] page error",t.message,t.stack??""),c("OnReportSubWebViewError",e,{recorded:!0}));case"CopyToClipboard":return typeof t.text!="string"?a("OnCopyToClipboard",e,"INVALID","text must be a string."):(navigator.clipboard?.writeText(t.text).catch(()=>{}),c("OnCopyToClipboard",e,{copied:!0}));case"OpenURL":return typeof t.url!="string"||!B(t.url)?a("OnOpenURL",e,"LINK_NOT_ALLOWED","This link cannot be opened from a page."):(window.open(t.url,"_blank","noopener,noreferrer"),c("OnOpenURL",e));case"OpenShareSheet":{const{title:S,message:h,url:w}=t,L=!(typeof h=="string"&&h.trim())&&w==null;return!k(S,100)||!k(h,4e3)||!k(w,2048)||w===""||L?a("OnOpenShareSheet",e,"INVALID","Share a message or a url within their limits."):typeof w=="string"&&!/^https?:\/\//i.test(w)?a("OnOpenShareSheet",e,"LINK_NOT_ALLOWED","Only an http or https url can be shared."):(u("share sheet",t),c("OnOpenShareSheet",e,{action:"sharedAction",activityType:null}))}case"GetSubWebViewStorage":case"SetSubWebViewStorage":case"RemoveSubWebViewStorage":case"ClearSubWebViewStorage":case"GetSubWebViewStorageInfo":{const h={GetSubWebViewStorage:()=>g.get(t.keys),SetSubWebViewStorage:()=>g.set(t.entries),RemoveSubWebViewStorage:()=>g.remove(t.keys),ClearSubWebViewStorage:()=>g.clear(),GetSubWebViewStorageInfo:()=>g.info()}[i]();return h.ok?c(`On${i}`,e,h.value):a(`On${i}`,e,h.code,h.code==="QUOTA_EXCEEDED"?"This would take the page's storage past 1,048,576 characters.":"Keys are 1 to 200 characters; values must be JSON.")}case"GetSubWebViewUserKey":return c("OnGetSubWebViewUserKey",e,{key:s.userKey??F(l)});default:return a("ERROR",e,"NOT_FOUND",`${i} is not answered for this page.`)}},f=window;f.ReactNativeWebView={postMessage:A},f.ChaticSubWebView=p;const R={get title(){return T},get closed(){return b},get storage(){return Object.fromEntries([...d].map(([r,n])=>[r,JSON.parse(n)]))},pressBack:()=>{b||(v?y("OnBackPressed",{}):history.length>1?history.back():R.requestClose("back"))},requestClose:(r="control")=>{if(b)return;const n=Date.now();if(I&&(V===null||n-V>K)){V=n,y("OnSubWebViewCloseRequested",{trigger:r});return}b={by:"user"},s.onClose?.(b),u("view closed by the user")},changeContext:r=>{Object.assign(m,r),y("OnSubWebViewContextChanged",{...m})},uninstall:()=>{delete f.ReactNativeWebView,delete f.ChaticSubWebView}};return R};exports.installChaticAppsMock=P;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("./storage-yeS4HWKZ.cjs"),_=["WebAppReady","Ping","FinishSubWebView","SetSubWebViewTitle","TriggerHaptic","SetCanGoBack","SetSubWebViewCloseGuard","ReportSubWebViewError","GetSubWebViewStorage","SetSubWebViewStorage","RemoveSubWebViewStorage","ClearSubWebViewStorage","GetSubWebViewStorageInfo","GetSubWebViewPermission","RequestSubWebViewPermission","OpenSettings"],M={clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey"},U=["camera","microphone"],$=["selection","impact","success","warning","error"],K=64*1024,x=16*1024,B=3e3,P=r=>{if(/^(mailto|tel|sms|itms-apps|market):/i.test(r))return!0;const a=/^https?:\/\/([^/?#:@]+)/i.exec(r)?.[1]?.toLowerCase();return a?!/\.(apps|apps-dev)\.chatic\.io$/.test(a)&&!/^app(-dev)?\.chatic\.io$/.test(a):!1},F=(r,a)=>{if(r===void 0)return!0;try{const p=JSON.stringify(r);return p!==void 0&&p.length<=a}catch{return!1}},v=(r,a)=>r==null||typeof r=="string"&&r.length<=a,J=r=>{let a="";for(let p=0;a.length<64;p++){let h=2166136261^p;for(let b=0;b<r.length;b++)h=Math.imul(h^r.charCodeAt(b),16777619);a+=(h>>>0).toString(16).padStart(8,"0")}return a.slice(0,64)},q=r=>{const a=/^https:\/\/([a-z0-9-]+)\.(apps|apps-dev)\.chatic\.io$/.exec(r);return a?`https://${a[2]==="apps"?"app":"app-dev"}.chatic.io/apps/${a[1]}`:r},j=(r={})=>{const a=new Set([..._,...(r.permissions??[]).map(s=>M[s])]),p={camera:"prompt",microphone:"prompt"},h=window.location.origin,b={protocolVersion:1,viewId:"mock-view",platform:"ios",appVersion:"0.0.0-mock",locale:"ko",theme:"light",params:{},appLink:q(h),...r.context},d=r.log===!1?()=>{}:(...s)=>console.info("[chatic-apps mock]",...s);let O=!1;const C=[];let I,S=null;const V={theme:b.theme,locale:b.locale};let T=!1,N=!1,W=null,R=0;const w=new Map,A={read:s=>w.get(s),write:(s,n)=>{w.set(s,n)},delete:s=>{w.delete(s)},keys:()=>[...w.keys()]},g=D.ruledStore(A);if(r.storage&&!g.set(r.storage).ok)throw new Error("[chatic-apps mock] options.storage must be JSON entries within the storage limits.");const y=s=>{const n=JSON.stringify(s);if(!O){C.push(n);return}setTimeout(()=>window.dispatchEvent(new MessageEvent("message",{data:n})),0)},k=(s,n)=>y({type:s,success:!0,data:n,refId:`mock-push-${Date.now().toString(36)}`}),c=(s,n,o={})=>y({type:s,success:!0,data:o,refId:n}),i=(s,n,o,e)=>y({type:s,success:!1,error:{code:o,message:e},refId:n}),L=s=>{let n;try{n=JSON.parse(s)}catch{return}const{type:o,refId:e}=n;if(typeof o!="string")return;const t=n.data??{};if(O||(O=!0,C.splice(0).forEach(u=>setTimeout(()=>window.dispatchEvent(new MessageEvent("message",{data:u})),0))),d("←",o,t),S)return o==="FinishSubWebView"?i("OnFinishSubWebView",e,"NOT_OPEN","The view has closed."):d("view closed; no answer to",o);if(s.length>K)return i("ERROR",e,"TOO_LARGE","The message is over 65,536 characters.");if(!a.has(o))return i("ERROR",e,"NOT_FOUND",`${o} is not answered for this page.`);switch(o){case"WebAppReady":return c("OnWebAppReady",e,{appVersion:"2.20.0",protocolVersion:"2.20.0",supportedWebMessages:[...a],supportedAppMessages:[],subWebView:{...b,...V}});case"Ping":return c("Pong",e,{payload:t.payload??""});case"FinishSubWebView":return F(t.result,x)?(S={by:"page",result:t.result},r.onClose?.(S),d("view finished",t.result),c("OnFinishSubWebView",e)):i("OnFinishSubWebView",e,"INVALID","result must be JSON of at most 16 KiB.");case"SetSubWebViewTitle":{const u=typeof t.title=="string"?t.title.trim():"";return!u||u.length>100?i("OnSetSubWebViewTitle",e,"INVALID","title must be 1 to 100 characters."):(I=u,c("OnSetSubWebViewTitle",e))}case"TriggerHaptic":return $.includes(t.kind)?c("OnTriggerHaptic",e):i("OnTriggerHaptic",e,"INVALID_KIND",`Unknown haptic kind: ${String(t.kind)}`);case"SetCanGoBack":return typeof t.canGoBack!="boolean"?i("OnSetCanGoBack",e,"INVALID","canGoBack must be a boolean."):(T=t.canGoBack,c("OnSetCanGoBack",e));case"SetSubWebViewCloseGuard":return typeof t.enabled!="boolean"?i("OnSetSubWebViewCloseGuard",e,"INVALID","enabled must be a boolean."):(N=t.enabled,c("OnSetSubWebViewCloseGuard",e));case"ReportSubWebViewError":return typeof t.message!="string"||!t.message.trim()?i("OnReportSubWebViewError",e,"INVALID","message must be a non-empty string."):R>=20?c("OnReportSubWebViewError",e,{recorded:!1}):(R+=1,console.warn("[chatic-apps mock] page error",t.message,t.stack??""),c("OnReportSubWebViewError",e,{recorded:!0}));case"CopyToClipboard":return typeof t.text!="string"?i("OnCopyToClipboard",e,"INVALID","text must be a string."):(navigator.clipboard?.writeText(t.text).catch(()=>{}),c("OnCopyToClipboard",e,{copied:!0}));case"OpenURL":return typeof t.url!="string"||!P(t.url)?i("OnOpenURL",e,"LINK_NOT_ALLOWED","This link cannot be opened from a page."):(window.open(t.url,"_blank","noopener,noreferrer"),c("OnOpenURL",e));case"OpenShareSheet":{const{title:u,message:l,url:m}=t,G=!(typeof l=="string"&&l.trim())&&m==null;return!v(u,100)||!v(l,4e3)||!v(m,2048)||m===""||G?i("OnOpenShareSheet",e,"INVALID","Share a message or a url within their limits."):typeof m=="string"&&!/^https?:\/\//i.test(m)?i("OnOpenShareSheet",e,"LINK_NOT_ALLOWED","Only an http or https url can be shared."):(d("share sheet",t),c("OnOpenShareSheet",e,{action:"sharedAction",activityType:null}))}case"GetSubWebViewStorage":case"SetSubWebViewStorage":case"RemoveSubWebViewStorage":case"ClearSubWebViewStorage":case"GetSubWebViewStorageInfo":{const l={GetSubWebViewStorage:()=>g.get(t.keys),SetSubWebViewStorage:()=>g.set(t.entries),RemoveSubWebViewStorage:()=>g.remove(t.keys),ClearSubWebViewStorage:()=>g.clear(),GetSubWebViewStorageInfo:()=>g.info()}[o]();return l.ok?c(`On${o}`,e,l.value):i(`On${o}`,e,l.code,l.code==="QUOTA_EXCEEDED"?"This would take the page's storage past 1,048,576 characters.":"Keys are 1 to 200 characters; values must be JSON.")}case"GetSubWebViewPermission":case"RequestSubWebViewPermission":{const u=t.kind;if(!U.includes(u))return i(`On${o}`,e,"INVALID","kind must be camera or microphone.");if(r.deviceAnswers?.[u]==="unavailable")return i(`On${o}`,e,"UNAVAILABLE","This device has no such hardware.");if(o==="RequestSubWebViewPermission"&&p[u]==="prompt"){const l=r.deviceAnswers?.[u]??"allow";p[u]=l==="allow"?"granted":l==="deny"?"prompt":"blocked",d("the user answered",u,l)}return c(`On${o}`,e,{state:p[u]})}case"OpenSettings":return d("settings opened"),c("OnOpenSettings",e);case"GetSubWebViewUserKey":return c("OnGetSubWebViewUserKey",e,{key:r.userKey??J(h)});default:return i("ERROR",e,"NOT_FOUND",`${o} is not answered for this page.`)}},f=window;f.ReactNativeWebView={postMessage:L},f.ChaticSubWebView=b;const E={get title(){return I},get closed(){return S},get storage(){return Object.fromEntries([...w].map(([s,n])=>[s,JSON.parse(n)]))},get devices(){return{...p}},pressBack:()=>{S||(T?k("OnBackPressed",{}):history.length>1?history.back():E.requestClose("back"))},requestClose:(s="control")=>{if(S)return;const n=Date.now();if(N&&(W===null||n-W>B)){W=n,k("OnSubWebViewCloseRequested",{trigger:s});return}S={by:"user"},r.onClose?.(S),d("view closed by the user")},changeContext:s=>{Object.assign(V,s),k("OnSubWebViewContextChanged",{...V})},uninstall:()=>{delete f.ReactNativeWebView,delete f.ChaticSubWebView}};return E};exports.installChaticAppsMock=j;
package/mock.d.cts CHANGED
@@ -21,6 +21,9 @@ declare type ChaticAppsContext = {
21
21
  /** What the user did to ask for the close: the app's close control, or Android back. */
22
22
  declare type CloseTrigger = 'control' | 'back';
23
23
 
24
+ /** A device a page captures from with `getUserMedia`. */
25
+ declare type DeviceKind = 'camera' | 'microphone';
26
+
24
27
  /**
25
28
  * Turns a browser tab into a stand-in for the app, so a page can be built and tried without it. Call
26
29
  * it before `connect`, in development only. It answers as the app does — the base set, plus what
@@ -44,6 +47,8 @@ export declare interface MockController {
44
47
  readonly storage: {
45
48
  [key: string]: unknown;
46
49
  };
50
+ /** Where the app stands with the OS for each device. */
51
+ readonly devices: Record<DeviceKind, PermissionState_2>;
47
52
  /** Android's back button: to the page if it took back, else back in history, else a close. */
48
53
  pressBack(): void;
49
54
  /** The user asks to close: to the page if it guards closing (a second ask within 3 s closes). */
@@ -54,6 +59,9 @@ export declare interface MockController {
54
59
  uninstall(): void;
55
60
  }
56
61
 
62
+ /** How the user answers when the page asks for a device: allows it, refuses it, or the OS blocks it. */
63
+ export declare type MockDeviceAnswer = 'allow' | 'deny' | 'blocked' | 'unavailable';
64
+
57
65
  export declare interface MockOptions {
58
66
  /** What the page's manifest would grant. None by default, as for a page with no manifest. */
59
67
  permissions?: MockPermission[];
@@ -66,6 +74,12 @@ export declare interface MockOptions {
66
74
  by: 'page' | 'user';
67
75
  result?: unknown;
68
76
  }) => void;
77
+ /**
78
+ * How the user answers each device the page asks for; `allow` by default, `unavailable` for a device
79
+ * the phone does not have. A `deny` leaves the device `prompt`, as on Android; iOS reports a refusal as
80
+ * `blocked`. Only the answer is played: the page's `getUserMedia` still meets the browser's own prompt.
81
+ */
82
+ deviceAnswers?: Partial<Record<DeviceKind, MockDeviceAnswer>>;
69
83
  /** What the page's storage holds when the mock starts; empty by default. Kept in memory only. */
70
84
  storage?: {
71
85
  [key: string]: unknown;
@@ -77,6 +91,14 @@ export declare interface MockOptions {
77
91
  /** A manifest permission, as the page would declare it in `/.well-known/chatic-app.json`. */
78
92
  export declare type MockPermission = 'clipboard' | 'share' | 'openUrl' | 'userKey';
79
93
 
94
+ /**
95
+ * Where the app stands with the OS for one device:
96
+ * - `granted` — `getUserMedia` for it asks nothing further;
97
+ * - `prompt` — the OS has not been asked, or was refused and may be asked again;
98
+ * - `blocked` — only the OS settings can change it (`openSettings()`).
99
+ */
100
+ declare type PermissionState_2 = 'granted' | 'prompt' | 'blocked';
101
+
80
102
  /**
81
103
  * The shapes a page sees, declared here rather than imported: the app's message definitions are a
82
104
  * private package, and a published library cannot point at it. `types.contract.test.ts` holds each one
package/mock.d.ts CHANGED
@@ -21,6 +21,9 @@ declare type ChaticAppsContext = {
21
21
  /** What the user did to ask for the close: the app's close control, or Android back. */
22
22
  declare type CloseTrigger = 'control' | 'back';
23
23
 
24
+ /** A device a page captures from with `getUserMedia`. */
25
+ declare type DeviceKind = 'camera' | 'microphone';
26
+
24
27
  /**
25
28
  * Turns a browser tab into a stand-in for the app, so a page can be built and tried without it. Call
26
29
  * it before `connect`, in development only. It answers as the app does — the base set, plus what
@@ -44,6 +47,8 @@ export declare interface MockController {
44
47
  readonly storage: {
45
48
  [key: string]: unknown;
46
49
  };
50
+ /** Where the app stands with the OS for each device. */
51
+ readonly devices: Record<DeviceKind, PermissionState_2>;
47
52
  /** Android's back button: to the page if it took back, else back in history, else a close. */
48
53
  pressBack(): void;
49
54
  /** The user asks to close: to the page if it guards closing (a second ask within 3 s closes). */
@@ -54,6 +59,9 @@ export declare interface MockController {
54
59
  uninstall(): void;
55
60
  }
56
61
 
62
+ /** How the user answers when the page asks for a device: allows it, refuses it, or the OS blocks it. */
63
+ export declare type MockDeviceAnswer = 'allow' | 'deny' | 'blocked' | 'unavailable';
64
+
57
65
  export declare interface MockOptions {
58
66
  /** What the page's manifest would grant. None by default, as for a page with no manifest. */
59
67
  permissions?: MockPermission[];
@@ -66,6 +74,12 @@ export declare interface MockOptions {
66
74
  by: 'page' | 'user';
67
75
  result?: unknown;
68
76
  }) => void;
77
+ /**
78
+ * How the user answers each device the page asks for; `allow` by default, `unavailable` for a device
79
+ * the phone does not have. A `deny` leaves the device `prompt`, as on Android; iOS reports a refusal as
80
+ * `blocked`. Only the answer is played: the page's `getUserMedia` still meets the browser's own prompt.
81
+ */
82
+ deviceAnswers?: Partial<Record<DeviceKind, MockDeviceAnswer>>;
69
83
  /** What the page's storage holds when the mock starts; empty by default. Kept in memory only. */
70
84
  storage?: {
71
85
  [key: string]: unknown;
@@ -77,6 +91,14 @@ export declare interface MockOptions {
77
91
  /** A manifest permission, as the page would declare it in `/.well-known/chatic-app.json`. */
78
92
  export declare type MockPermission = 'clipboard' | 'share' | 'openUrl' | 'userKey';
79
93
 
94
+ /**
95
+ * Where the app stands with the OS for one device:
96
+ * - `granted` — `getUserMedia` for it asks nothing further;
97
+ * - `prompt` — the OS has not been asked, or was refused and may be asked again;
98
+ * - `blocked` — only the OS settings can change it (`openSettings()`).
99
+ */
100
+ declare type PermissionState_2 = 'granted' | 'prompt' | 'blocked';
101
+
80
102
  /**
81
103
  * The shapes a page sees, declared here rather than imported: the app's message definitions are a
82
104
  * private package, and a published library cannot point at it. `types.contract.test.ts` holds each one
package/mock.js CHANGED
@@ -1,5 +1,5 @@
1
- import { r as A } from "./storage-BuvWwLx2.js";
2
- const G = [
1
+ import { r as G } from "./storage-BuvWwLx2.js";
2
+ const D = [
3
3
  "WebAppReady",
4
4
  "Ping",
5
5
  "FinishSubWebView",
@@ -12,37 +12,40 @@ const G = [
12
12
  "SetSubWebViewStorage",
13
13
  "RemoveSubWebViewStorage",
14
14
  "ClearSubWebViewStorage",
15
- "GetSubWebViewStorageInfo"
16
- ], D = {
15
+ "GetSubWebViewStorageInfo",
16
+ "GetSubWebViewPermission",
17
+ "RequestSubWebViewPermission",
18
+ "OpenSettings"
19
+ ], _ = {
17
20
  clipboard: "CopyToClipboard",
18
21
  share: "OpenShareSheet",
19
22
  openUrl: "OpenURL",
20
23
  userKey: "GetSubWebViewUserKey"
21
- }, _ = ["selection", "impact", "success", "warning", "error"], x = 64 * 1024, M = 16 * 1024, U = 3e3, K = (s) => {
22
- if (/^(mailto|tel|sms|itms-apps|market):/i.test(s)) return !0;
23
- const o = /^https?:\/\/([^/?#:@]+)/i.exec(s)?.[1]?.toLowerCase();
24
- return o ? !/\.(apps|apps-dev)\.chatic\.io$/.test(o) && !/^app(-dev)?\.chatic\.io$/.test(o) : !1;
25
- }, B = (s, o) => {
26
- if (s === void 0) return !0;
24
+ }, U = ["camera", "microphone"], $ = ["selection", "impact", "success", "warning", "error"], x = 64 * 1024, K = 16 * 1024, M = 3e3, B = (r) => {
25
+ if (/^(mailto|tel|sms|itms-apps|market):/i.test(r)) return !0;
26
+ const a = /^https?:\/\/([^/?#:@]+)/i.exec(r)?.[1]?.toLowerCase();
27
+ return a ? !/\.(apps|apps-dev)\.chatic\.io$/.test(a) && !/^app(-dev)?\.chatic\.io$/.test(a) : !1;
28
+ }, F = (r, a) => {
29
+ if (r === void 0) return !0;
27
30
  try {
28
- const l = JSON.stringify(s);
29
- return l !== void 0 && l.length <= o;
31
+ const p = JSON.stringify(r);
32
+ return p !== void 0 && p.length <= a;
30
33
  } catch {
31
34
  return !1;
32
35
  }
33
- }, k = (s, o) => s == null || typeof s == "string" && s.length <= o, F = (s) => {
34
- let o = "";
35
- for (let l = 0; o.length < 64; l++) {
36
- let p = 2166136261 ^ l;
37
- for (let u = 0; u < s.length; u++) p = Math.imul(p ^ s.charCodeAt(u), 16777619);
38
- o += (p >>> 0).toString(16).padStart(8, "0");
36
+ }, v = (r, a) => r == null || typeof r == "string" && r.length <= a, P = (r) => {
37
+ let a = "";
38
+ for (let p = 0; a.length < 64; p++) {
39
+ let h = 2166136261 ^ p;
40
+ for (let b = 0; b < r.length; b++) h = Math.imul(h ^ r.charCodeAt(b), 16777619);
41
+ a += (h >>> 0).toString(16).padStart(8, "0");
39
42
  }
40
- return o.slice(0, 64);
41
- }, $ = (s) => {
42
- const o = /^https:\/\/([a-z0-9-]+)\.(apps|apps-dev)\.chatic\.io$/.exec(s);
43
- return o ? `https://${o[2] === "apps" ? "app" : "app-dev"}.chatic.io/apps/${o[1]}` : s;
44
- }, H = (s = {}) => {
45
- const o = /* @__PURE__ */ new Set([...G, ...(s.permissions ?? []).map((r) => D[r])]), l = window.location.origin, p = {
43
+ return a.slice(0, 64);
44
+ }, J = (r) => {
45
+ const a = /^https:\/\/([a-z0-9-]+)\.(apps|apps-dev)\.chatic\.io$/.exec(r);
46
+ return a ? `https://${a[2] === "apps" ? "app" : "app-dev"}.chatic.io/apps/${a[1]}` : r;
47
+ }, j = (r = {}) => {
48
+ const a = /* @__PURE__ */ new Set([...D, ...(r.permissions ?? []).map((s) => _[s])]), p = { camera: "prompt", microphone: "prompt" }, h = window.location.origin, b = {
46
49
  protocolVersion: 1,
47
50
  viewId: "mock-view",
48
51
  platform: "ios",
@@ -50,147 +53,165 @@ const G = [
50
53
  locale: "ko",
51
54
  theme: "light",
52
55
  params: {},
53
- appLink: $(l),
54
- ...s.context
55
- }, u = s.log === !1 ? () => {
56
- } : (...r) => console.info("[chatic-apps mock]", ...r);
56
+ appLink: J(h),
57
+ ...r.context
58
+ }, d = r.log === !1 ? () => {
59
+ } : (...s) => console.info("[chatic-apps mock]", ...s);
57
60
  let O = !1;
58
61
  const C = [];
59
- let T, b = null;
60
- const m = { theme: p.theme, locale: p.locale };
61
- let I = !1, v = !1, V = null, N = 0;
62
- const d = /* @__PURE__ */ new Map(), g = A({
63
- read: (r) => d.get(r),
64
- write: (r, n) => {
65
- d.set(r, n);
62
+ let I, S = null;
63
+ const V = { theme: b.theme, locale: b.locale };
64
+ let N = !1, R = !1, W = null, T = 0;
65
+ const w = /* @__PURE__ */ new Map(), g = G({
66
+ read: (s) => w.get(s),
67
+ write: (s, n) => {
68
+ w.set(s, n);
66
69
  },
67
- delete: (r) => {
68
- d.delete(r);
70
+ delete: (s) => {
71
+ w.delete(s);
69
72
  },
70
- keys: () => [...d.keys()]
73
+ keys: () => [...w.keys()]
71
74
  });
72
- if (s.storage && !g.set(s.storage).ok)
75
+ if (r.storage && !g.set(r.storage).ok)
73
76
  throw new Error("[chatic-apps mock] options.storage must be JSON entries within the storage limits.");
74
- const W = (r) => {
75
- const n = JSON.stringify(r);
77
+ const k = (s) => {
78
+ const n = JSON.stringify(s);
76
79
  if (!O) {
77
80
  C.push(n);
78
81
  return;
79
82
  }
80
83
  setTimeout(() => window.dispatchEvent(new MessageEvent("message", { data: n })), 0);
81
- }, y = (r, n) => W({ type: r, success: !0, data: n, refId: `mock-push-${Date.now().toString(36)}` }), c = (r, n, i = {}) => W({ type: r, success: !0, data: i, refId: n }), a = (r, n, i, e) => W({ type: r, success: !1, error: { code: i, message: e }, refId: n }), E = (r) => {
84
+ }, y = (s, n) => k({ type: s, success: !0, data: n, refId: `mock-push-${Date.now().toString(36)}` }), c = (s, n, o = {}) => k({ type: s, success: !0, data: o, refId: n }), i = (s, n, o, e) => k({ type: s, success: !1, error: { code: o, message: e }, refId: n }), A = (s) => {
82
85
  let n;
83
86
  try {
84
- n = JSON.parse(r);
87
+ n = JSON.parse(s);
85
88
  } catch {
86
89
  return;
87
90
  }
88
- const { type: i, refId: e } = n;
89
- if (typeof i != "string") return;
91
+ const { type: o, refId: e } = n;
92
+ if (typeof o != "string") return;
90
93
  const t = n.data ?? {};
91
94
  if (O || (O = !0, C.splice(0).forEach(
92
- (S) => setTimeout(() => window.dispatchEvent(new MessageEvent("message", { data: S })), 0)
93
- )), u("←", i, t), b)
94
- return i === "FinishSubWebView" ? a("OnFinishSubWebView", e, "NOT_OPEN", "The view has closed.") : u("view closed; no answer to", i);
95
- if (r.length > x)
96
- return a("ERROR", e, "TOO_LARGE", "The message is over 65,536 characters.");
97
- if (!o.has(i)) return a("ERROR", e, "NOT_FOUND", `${i} is not answered for this page.`);
98
- switch (i) {
95
+ (u) => setTimeout(() => window.dispatchEvent(new MessageEvent("message", { data: u })), 0)
96
+ )), d("←", o, t), S)
97
+ return o === "FinishSubWebView" ? i("OnFinishSubWebView", e, "NOT_OPEN", "The view has closed.") : d("view closed; no answer to", o);
98
+ if (s.length > x)
99
+ return i("ERROR", e, "TOO_LARGE", "The message is over 65,536 characters.");
100
+ if (!a.has(o)) return i("ERROR", e, "NOT_FOUND", `${o} is not answered for this page.`);
101
+ switch (o) {
99
102
  case "WebAppReady":
100
103
  return c("OnWebAppReady", e, {
101
- appVersion: "2.19.0",
102
- protocolVersion: "2.19.0",
103
- supportedWebMessages: [...o],
104
+ appVersion: "2.20.0",
105
+ protocolVersion: "2.20.0",
106
+ supportedWebMessages: [...a],
104
107
  supportedAppMessages: [],
105
- subWebView: { ...p, ...m }
108
+ subWebView: { ...b, ...V }
106
109
  });
107
110
  case "Ping":
108
111
  return c("Pong", e, { payload: t.payload ?? "" });
109
112
  case "FinishSubWebView":
110
- return B(t.result, M) ? (b = { by: "page", result: t.result }, s.onClose?.(b), u("view finished", t.result), c("OnFinishSubWebView", e)) : a("OnFinishSubWebView", e, "INVALID", "result must be JSON of at most 16 KiB.");
113
+ return F(t.result, K) ? (S = { by: "page", result: t.result }, r.onClose?.(S), d("view finished", t.result), c("OnFinishSubWebView", e)) : i("OnFinishSubWebView", e, "INVALID", "result must be JSON of at most 16 KiB.");
111
114
  case "SetSubWebViewTitle": {
112
- const S = typeof t.title == "string" ? t.title.trim() : "";
113
- return !S || S.length > 100 ? a("OnSetSubWebViewTitle", e, "INVALID", "title must be 1 to 100 characters.") : (T = S, c("OnSetSubWebViewTitle", e));
115
+ const u = typeof t.title == "string" ? t.title.trim() : "";
116
+ return !u || u.length > 100 ? i("OnSetSubWebViewTitle", e, "INVALID", "title must be 1 to 100 characters.") : (I = u, c("OnSetSubWebViewTitle", e));
114
117
  }
115
118
  case "TriggerHaptic":
116
- return _.includes(t.kind) ? c("OnTriggerHaptic", e) : a("OnTriggerHaptic", e, "INVALID_KIND", `Unknown haptic kind: ${String(t.kind)}`);
119
+ return $.includes(t.kind) ? c("OnTriggerHaptic", e) : i("OnTriggerHaptic", e, "INVALID_KIND", `Unknown haptic kind: ${String(t.kind)}`);
117
120
  case "SetCanGoBack":
118
- return typeof t.canGoBack != "boolean" ? a("OnSetCanGoBack", e, "INVALID", "canGoBack must be a boolean.") : (I = t.canGoBack, c("OnSetCanGoBack", e));
121
+ return typeof t.canGoBack != "boolean" ? i("OnSetCanGoBack", e, "INVALID", "canGoBack must be a boolean.") : (N = t.canGoBack, c("OnSetCanGoBack", e));
119
122
  case "SetSubWebViewCloseGuard":
120
- return typeof t.enabled != "boolean" ? a("OnSetSubWebViewCloseGuard", e, "INVALID", "enabled must be a boolean.") : (v = t.enabled, c("OnSetSubWebViewCloseGuard", e));
123
+ return typeof t.enabled != "boolean" ? i("OnSetSubWebViewCloseGuard", e, "INVALID", "enabled must be a boolean.") : (R = t.enabled, c("OnSetSubWebViewCloseGuard", e));
121
124
  case "ReportSubWebViewError":
122
- return typeof t.message != "string" || !t.message.trim() ? a("OnReportSubWebViewError", e, "INVALID", "message must be a non-empty string.") : N >= 20 ? c("OnReportSubWebViewError", e, { recorded: !1 }) : (N += 1, console.warn("[chatic-apps mock] page error", t.message, t.stack ?? ""), c("OnReportSubWebViewError", e, { recorded: !0 }));
125
+ return typeof t.message != "string" || !t.message.trim() ? i("OnReportSubWebViewError", e, "INVALID", "message must be a non-empty string.") : T >= 20 ? c("OnReportSubWebViewError", e, { recorded: !1 }) : (T += 1, console.warn("[chatic-apps mock] page error", t.message, t.stack ?? ""), c("OnReportSubWebViewError", e, { recorded: !0 }));
123
126
  case "CopyToClipboard":
124
- return typeof t.text != "string" ? a("OnCopyToClipboard", e, "INVALID", "text must be a string.") : (navigator.clipboard?.writeText(t.text).catch(() => {
127
+ return typeof t.text != "string" ? i("OnCopyToClipboard", e, "INVALID", "text must be a string.") : (navigator.clipboard?.writeText(t.text).catch(() => {
125
128
  }), c("OnCopyToClipboard", e, { copied: !0 }));
126
129
  case "OpenURL":
127
- return typeof t.url != "string" || !K(t.url) ? a("OnOpenURL", e, "LINK_NOT_ALLOWED", "This link cannot be opened from a page.") : (window.open(t.url, "_blank", "noopener,noreferrer"), c("OnOpenURL", e));
130
+ return typeof t.url != "string" || !B(t.url) ? i("OnOpenURL", e, "LINK_NOT_ALLOWED", "This link cannot be opened from a page.") : (window.open(t.url, "_blank", "noopener,noreferrer"), c("OnOpenURL", e));
128
131
  case "OpenShareSheet": {
129
- const { title: S, message: h, url: w } = t, L = !(typeof h == "string" && h.trim()) && w == null;
130
- return !k(S, 100) || !k(h, 4e3) || !k(w, 2048) || w === "" || L ? a("OnOpenShareSheet", e, "INVALID", "Share a message or a url within their limits.") : typeof w == "string" && !/^https?:\/\//i.test(w) ? a(
132
+ const { title: u, message: l, url: m } = t, L = !(typeof l == "string" && l.trim()) && m == null;
133
+ return !v(u, 100) || !v(l, 4e3) || !v(m, 2048) || m === "" || L ? i("OnOpenShareSheet", e, "INVALID", "Share a message or a url within their limits.") : typeof m == "string" && !/^https?:\/\//i.test(m) ? i(
131
134
  "OnOpenShareSheet",
132
135
  e,
133
136
  "LINK_NOT_ALLOWED",
134
137
  "Only an http or https url can be shared."
135
- ) : (u("share sheet", t), c("OnOpenShareSheet", e, { action: "sharedAction", activityType: null }));
138
+ ) : (d("share sheet", t), c("OnOpenShareSheet", e, { action: "sharedAction", activityType: null }));
136
139
  }
137
140
  case "GetSubWebViewStorage":
138
141
  case "SetSubWebViewStorage":
139
142
  case "RemoveSubWebViewStorage":
140
143
  case "ClearSubWebViewStorage":
141
144
  case "GetSubWebViewStorageInfo": {
142
- const h = {
145
+ const l = {
143
146
  GetSubWebViewStorage: () => g.get(t.keys),
144
147
  SetSubWebViewStorage: () => g.set(t.entries),
145
148
  RemoveSubWebViewStorage: () => g.remove(t.keys),
146
149
  ClearSubWebViewStorage: () => g.clear(),
147
150
  GetSubWebViewStorageInfo: () => g.info()
148
- }[i]();
149
- return h.ok ? c(`On${i}`, e, h.value) : a(
150
- `On${i}`,
151
+ }[o]();
152
+ return l.ok ? c(`On${o}`, e, l.value) : i(
153
+ `On${o}`,
151
154
  e,
152
- h.code,
153
- h.code === "QUOTA_EXCEEDED" ? "This would take the page's storage past 1,048,576 characters." : "Keys are 1 to 200 characters; values must be JSON."
155
+ l.code,
156
+ l.code === "QUOTA_EXCEEDED" ? "This would take the page's storage past 1,048,576 characters." : "Keys are 1 to 200 characters; values must be JSON."
154
157
  );
155
158
  }
159
+ case "GetSubWebViewPermission":
160
+ case "RequestSubWebViewPermission": {
161
+ const u = t.kind;
162
+ if (!U.includes(u))
163
+ return i(`On${o}`, e, "INVALID", "kind must be camera or microphone.");
164
+ if (r.deviceAnswers?.[u] === "unavailable")
165
+ return i(`On${o}`, e, "UNAVAILABLE", "This device has no such hardware.");
166
+ if (o === "RequestSubWebViewPermission" && p[u] === "prompt") {
167
+ const l = r.deviceAnswers?.[u] ?? "allow";
168
+ p[u] = l === "allow" ? "granted" : l === "deny" ? "prompt" : "blocked", d("the user answered", u, l);
169
+ }
170
+ return c(`On${o}`, e, { state: p[u] });
171
+ }
172
+ case "OpenSettings":
173
+ return d("settings opened"), c("OnOpenSettings", e);
156
174
  case "GetSubWebViewUserKey":
157
- return c("OnGetSubWebViewUserKey", e, { key: s.userKey ?? F(l) });
175
+ return c("OnGetSubWebViewUserKey", e, { key: r.userKey ?? P(h) });
158
176
  default:
159
- return a("ERROR", e, "NOT_FOUND", `${i} is not answered for this page.`);
177
+ return i("ERROR", e, "NOT_FOUND", `${o} is not answered for this page.`);
160
178
  }
161
179
  }, f = window;
162
- f.ReactNativeWebView = { postMessage: E }, f.ChaticSubWebView = p;
163
- const R = {
180
+ f.ReactNativeWebView = { postMessage: A }, f.ChaticSubWebView = b;
181
+ const E = {
164
182
  get title() {
165
- return T;
183
+ return I;
166
184
  },
167
185
  get closed() {
168
- return b;
186
+ return S;
169
187
  },
170
188
  get storage() {
171
- return Object.fromEntries([...d].map(([r, n]) => [r, JSON.parse(n)]));
189
+ return Object.fromEntries([...w].map(([s, n]) => [s, JSON.parse(n)]));
190
+ },
191
+ get devices() {
192
+ return { ...p };
172
193
  },
173
194
  pressBack: () => {
174
- b || (I ? y("OnBackPressed", {}) : history.length > 1 ? history.back() : R.requestClose("back"));
195
+ S || (N ? y("OnBackPressed", {}) : history.length > 1 ? history.back() : E.requestClose("back"));
175
196
  },
176
- requestClose: (r = "control") => {
177
- if (b) return;
197
+ requestClose: (s = "control") => {
198
+ if (S) return;
178
199
  const n = Date.now();
179
- if (v && (V === null || n - V > U)) {
180
- V = n, y("OnSubWebViewCloseRequested", { trigger: r });
200
+ if (R && (W === null || n - W > M)) {
201
+ W = n, y("OnSubWebViewCloseRequested", { trigger: s });
181
202
  return;
182
203
  }
183
- b = { by: "user" }, s.onClose?.(b), u("view closed by the user");
204
+ S = { by: "user" }, r.onClose?.(S), d("view closed by the user");
184
205
  },
185
- changeContext: (r) => {
186
- Object.assign(m, r), y("OnSubWebViewContextChanged", { ...m });
206
+ changeContext: (s) => {
207
+ Object.assign(V, s), y("OnSubWebViewContextChanged", { ...V });
187
208
  },
188
209
  uninstall: () => {
189
210
  delete f.ReactNativeWebView, delete f.ChaticSubWebView;
190
211
  }
191
212
  };
192
- return R;
213
+ return E;
193
214
  };
194
215
  export {
195
- H as installChaticAppsMock
216
+ j as installChaticAppsMock
196
217
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lemoncloud/chatic-apps-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Build pages that run inside the DoU app",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "unpkg": "./chatic-apps-sdk.global.js",
40
40
  "jsdelivr": "./chatic-apps-sdk.global.js",
41
- "files": ["*.js", "*.cjs", "*.d.ts", "*.d.cts", "README.md"],
41
+ "files": ["*.js", "*.cjs", "*.d.ts", "*.d.cts", "README.md", "GUIDE.md", "AGENTS.md"],
42
42
  "publishConfig": {
43
43
  "access": "public"
44
44
  },