@lemoncloud/chatic-apps-sdk 0.0.0-stage → 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/AGENTS.md +56 -0
- package/GUIDE.md +219 -0
- package/README.md +286 -2
- package/chatic-apps-sdk.global.js +1 -0
- package/index.cjs +1 -0
- package/index.d.cts +225 -0
- package/index.d.ts +225 -0
- package/index.js +331 -0
- package/mock.cjs +1 -0
- package/mock.d.cts +109 -0
- package/mock.d.ts +109 -0
- package/mock.js +217 -0
- package/package.json +45 -5
- package/storage-BuvWwLx2.js +104 -0
- package/storage-yeS4HWKZ.cjs +1 -0
package/index.js
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { C as u, b as I, s as k } from "./storage-BuvWwLx2.js";
|
|
2
|
+
const V = "2.20.0", x = 1e4, N = 2e3;
|
|
3
|
+
let W = 0;
|
|
4
|
+
const q = () => `cas-${Date.now().toString(36)}-${(++W).toString(36)}`, R = () => typeof document < "u" && document.visibilityState === "hidden", U = (r, t = x) => {
|
|
5
|
+
const n = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
|
|
6
|
+
let h = !1;
|
|
7
|
+
const v = (a, o) => {
|
|
8
|
+
o.remaining === null || R() || (o.startedAt = Date.now(), o.timer = setTimeout(() => {
|
|
9
|
+
n.delete(a), o.reject(new u("TIMEOUT", "The app did not answer in time."));
|
|
10
|
+
}, o.remaining));
|
|
11
|
+
}, w = () => {
|
|
12
|
+
for (const [a, o] of n)
|
|
13
|
+
o.remaining !== null && (R() ? (o.timer && clearTimeout(o.timer), o.timer = null, o.remaining = Math.max(0, o.remaining - (Date.now() - o.startedAt))) : o.timer || (o.remaining = Math.max(o.remaining, N), v(a, o)));
|
|
14
|
+
};
|
|
15
|
+
typeof document < "u" && document.addEventListener("visibilitychange", w);
|
|
16
|
+
const g = r.listen((a) => {
|
|
17
|
+
let o;
|
|
18
|
+
try {
|
|
19
|
+
o = JSON.parse(a);
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (!o || typeof o != "object" || typeof o.type != "string") return;
|
|
24
|
+
const d = typeof o.refId == "string" ? n.get(o.refId) : void 0;
|
|
25
|
+
if (d && typeof o.refId == "string") {
|
|
26
|
+
if (n.delete(o.refId), d.timer && clearTimeout(d.timer), o.success === !0)
|
|
27
|
+
d.resolve(o.data);
|
|
28
|
+
else {
|
|
29
|
+
const p = typeof o.error?.code == "string" ? o.error.code : "INTERNAL_ERROR", m = typeof o.error?.message == "string" ? o.error.message : p;
|
|
30
|
+
d.reject(new u(p, m));
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
s.get(o.type)?.forEach((p) => {
|
|
35
|
+
try {
|
|
36
|
+
p(o.data);
|
|
37
|
+
} catch {
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
request: (a, o = {}, d = {}) => new Promise((p, m) => {
|
|
43
|
+
if (h) {
|
|
44
|
+
m(new u("DISCONNECTED", "The connection to the app was closed."));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const l = q(), e = d.timeoutMs === void 0 ? t : d.timeoutMs, i = {
|
|
48
|
+
resolve: p,
|
|
49
|
+
reject: m,
|
|
50
|
+
remaining: e,
|
|
51
|
+
startedAt: Date.now(),
|
|
52
|
+
timer: null
|
|
53
|
+
};
|
|
54
|
+
n.set(l, i), v(l, i), r.send(JSON.stringify({ type: a, data: o, refId: l, version: V }));
|
|
55
|
+
}),
|
|
56
|
+
onPush: (a, o) => {
|
|
57
|
+
let d = s.get(a);
|
|
58
|
+
return d || s.set(a, d = /* @__PURE__ */ new Set()), d.add(o), () => d?.delete(o);
|
|
59
|
+
},
|
|
60
|
+
close: () => {
|
|
61
|
+
if (!h) {
|
|
62
|
+
h = !0, g(), typeof document < "u" && document.removeEventListener("visibilitychange", w);
|
|
63
|
+
for (const a of n.values())
|
|
64
|
+
a.timer && clearTimeout(a.timer), a.reject(new u("DISCONNECTED", "The connection to the app was closed."));
|
|
65
|
+
n.clear(), s.clear();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}, M = () => typeof window < "u" && !!window.ReactNativeWebView, _ = () => ({
|
|
70
|
+
send: (r) => window.ReactNativeWebView?.postMessage(r),
|
|
71
|
+
listen: (r) => {
|
|
72
|
+
const t = (n) => {
|
|
73
|
+
const s = n.data;
|
|
74
|
+
typeof s == "string" && r(s);
|
|
75
|
+
};
|
|
76
|
+
return window.addEventListener("message", t), document.addEventListener("message", t), () => {
|
|
77
|
+
window.removeEventListener("message", t), document.removeEventListener("message", t);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}), b = {
|
|
81
|
+
finish: "FinishSubWebView",
|
|
82
|
+
title: "SetSubWebViewTitle",
|
|
83
|
+
haptic: "TriggerHaptic",
|
|
84
|
+
clipboard: "CopyToClipboard",
|
|
85
|
+
share: "OpenShareSheet",
|
|
86
|
+
openUrl: "OpenURL",
|
|
87
|
+
userKey: "GetSubWebViewUserKey",
|
|
88
|
+
back: "SetCanGoBack",
|
|
89
|
+
closeGuard: "SetSubWebViewCloseGuard",
|
|
90
|
+
errorReport: "ReportSubWebViewError",
|
|
91
|
+
storage: "GetSubWebViewStorage",
|
|
92
|
+
permissions: "RequestSubWebViewPermission"
|
|
93
|
+
}, O = 1, D = 1e3, $ = 4e3, A = () => typeof window < "u" && window.ChaticSubWebView || null, j = () => new Promise((r) => {
|
|
94
|
+
if (typeof document > "u" || document.readyState === "complete") {
|
|
95
|
+
r(A());
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
window.addEventListener("load", () => r(A()), { once: !0 });
|
|
99
|
+
}), G = (r) => {
|
|
100
|
+
let t, n;
|
|
101
|
+
try {
|
|
102
|
+
r instanceof Error ? (t = r.message || r.name, n = typeof r.stack == "string" ? r.stack : void 0) : typeof r == "string" ? t = r : t = `A non-Error value was thrown: ${Object.prototype.toString.call(r)}`;
|
|
103
|
+
} catch {
|
|
104
|
+
t = "An error that could not be read was thrown";
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
message: (t || "Unknown error").slice(0, D),
|
|
108
|
+
...n ? { stack: n.slice(0, $) } : {}
|
|
109
|
+
};
|
|
110
|
+
}, E = (r) => new u("NOT_SUPPORTED", `${r} is not available here: an older app, or not granted.`), S = (r) => Promise.reject(new u("NOT_IN_APP", `${r} needs the app; this page is in a browser.`)), L = (r = {}) => {
|
|
111
|
+
if (r === null || typeof r != "object" || Array.isArray(r))
|
|
112
|
+
throw new u("INVALID", "link() takes an object of query params, such as { level: 3 }.");
|
|
113
|
+
const t = new URLSearchParams();
|
|
114
|
+
for (const [s, h] of Object.entries(r)) t.append(s, String(h));
|
|
115
|
+
const n = t.toString();
|
|
116
|
+
return n ? `?${n}` : "";
|
|
117
|
+
}, P = (r) => typeof location > "u" ? `/${r}` : `${location.origin}/${r}`;
|
|
118
|
+
let y = null;
|
|
119
|
+
const Q = (r = {}) => (y || (y = (M() ? B(_(), r) : Promise.resolve(H())).catch((t) => {
|
|
120
|
+
throw y = null, t;
|
|
121
|
+
})), y), B = async (r, t = {}) => {
|
|
122
|
+
const n = U(r, t.timeoutMs);
|
|
123
|
+
try {
|
|
124
|
+
const s = await C(n, !0);
|
|
125
|
+
return K(n, s, t);
|
|
126
|
+
} catch (s) {
|
|
127
|
+
throw n.close(), s;
|
|
128
|
+
}
|
|
129
|
+
}, C = async (r, t) => {
|
|
130
|
+
const n = await r.request("WebAppReady", {}), s = n.subWebView ?? (t ? await j() : null);
|
|
131
|
+
if (s && s.protocolVersion !== O)
|
|
132
|
+
throw new u(
|
|
133
|
+
"UNSUPPORTED_PROTOCOL",
|
|
134
|
+
`The app speaks protocol ${String(s.protocolVersion)}; this library speaks ${O}.`
|
|
135
|
+
);
|
|
136
|
+
return {
|
|
137
|
+
supported: new Set(Array.isArray(n.supportedWebMessages) ? n.supportedWebMessages : []),
|
|
138
|
+
context: s
|
|
139
|
+
};
|
|
140
|
+
}, K = (r, t, n) => {
|
|
141
|
+
let s = null, h = null;
|
|
142
|
+
const v = /* @__PURE__ */ new Set(), w = [], g = (e) => t.supported.has(b[e]), a = (e, i, c, f) => {
|
|
143
|
+
const T = f ?? b[e];
|
|
144
|
+
return t.supported.has(T) ? r.request(T, i, c === void 0 ? {} : { timeoutMs: c }) : Promise.reject(E(e));
|
|
145
|
+
}, o = (e, i) => g("storage") ? r.request(e, i) : Promise.reject(E("storage")), d = (e) => v.forEach((i) => {
|
|
146
|
+
try {
|
|
147
|
+
i(e);
|
|
148
|
+
} catch (c) {
|
|
149
|
+
l.reportError(c);
|
|
150
|
+
}
|
|
151
|
+
}), p = () => {
|
|
152
|
+
g("back") && r.request(b.back, { canGoBack: !!s }).catch(() => {
|
|
153
|
+
}), g("closeGuard") && r.request(b.closeGuard, { enabled: !!h }).catch(() => {
|
|
154
|
+
});
|
|
155
|
+
}, m = (e) => {
|
|
156
|
+
if (!e.persisted) {
|
|
157
|
+
p();
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
C(r, !1).then((i) => {
|
|
161
|
+
const c = t.context;
|
|
162
|
+
t.supported = i.supported, i.context && (t.context = i.context), p();
|
|
163
|
+
const f = t.context;
|
|
164
|
+
f && (f.theme !== c?.theme || f.locale !== c?.locale) && d(f);
|
|
165
|
+
}).catch(() => {
|
|
166
|
+
});
|
|
167
|
+
};
|
|
168
|
+
typeof window < "u" && (window.addEventListener("pageshow", m), w.push(() => window.removeEventListener("pageshow", m))), w.push(
|
|
169
|
+
r.onPush("OnBackPressed", () => {
|
|
170
|
+
try {
|
|
171
|
+
s?.();
|
|
172
|
+
} catch (e) {
|
|
173
|
+
l.reportError(e);
|
|
174
|
+
}
|
|
175
|
+
})
|
|
176
|
+
), w.push(
|
|
177
|
+
r.onPush("OnSubWebViewCloseRequested", (e) => {
|
|
178
|
+
const i = h;
|
|
179
|
+
if (!i) return;
|
|
180
|
+
const c = e?.trigger ?? "control";
|
|
181
|
+
Promise.resolve().then(() => i(c)).then((f) => f ? l.finish() : void 0).catch((f) => l.reportError(f));
|
|
182
|
+
})
|
|
183
|
+
), w.push(
|
|
184
|
+
r.onPush("OnSubWebViewContextChanged", (e) => {
|
|
185
|
+
t.context && (t.context = { ...t.context, ...e }, d(t.context));
|
|
186
|
+
})
|
|
187
|
+
);
|
|
188
|
+
const l = {
|
|
189
|
+
inApp: !0,
|
|
190
|
+
get context() {
|
|
191
|
+
return t.context;
|
|
192
|
+
},
|
|
193
|
+
supports: g,
|
|
194
|
+
finish: (e) => a("finish", e === void 0 ? {} : { result: e }).then(() => {
|
|
195
|
+
}),
|
|
196
|
+
setTitle: (e) => a("title", { title: e }).then(() => {
|
|
197
|
+
}),
|
|
198
|
+
haptic: (e) => {
|
|
199
|
+
g("haptic") && r.request(b.haptic, { kind: e }).catch(() => {
|
|
200
|
+
});
|
|
201
|
+
},
|
|
202
|
+
copy: (e) => a("clipboard", { text: e }).then(() => {
|
|
203
|
+
}),
|
|
204
|
+
openUrl: (e) => a("openUrl", { url: e }).then(() => {
|
|
205
|
+
}),
|
|
206
|
+
share: (e) => a("share", e, null).then(
|
|
207
|
+
(i) => i?.action === "dismissedAction" ? "dismissed" : "shared"
|
|
208
|
+
),
|
|
209
|
+
getUserKey: () => a("userKey").then((e) => e.key),
|
|
210
|
+
permissions: {
|
|
211
|
+
query: (e) => a("permissions", { kind: e }, void 0, "GetSubWebViewPermission").then(
|
|
212
|
+
(i) => i.state
|
|
213
|
+
),
|
|
214
|
+
// Waits for the user, however long they take.
|
|
215
|
+
request: (e) => a("permissions", { kind: e }, null).then((i) => i.state)
|
|
216
|
+
},
|
|
217
|
+
openSettings: () => a("permissions", {}, void 0, "OpenSettings").then(() => {
|
|
218
|
+
}),
|
|
219
|
+
reportError: (e) => g("errorReport") ? r.request(b.errorReport, G(e)).then((i) => !!i?.recorded).catch(() => !1) : Promise.resolve(!1),
|
|
220
|
+
storage: k({
|
|
221
|
+
get: (e) => o("GetSubWebViewStorage", { keys: e }),
|
|
222
|
+
set: (e) => o("SetSubWebViewStorage", { entries: e }),
|
|
223
|
+
remove: (e) => o("RemoveSubWebViewStorage", { keys: e }),
|
|
224
|
+
clear: () => o("ClearSubWebViewStorage", {}),
|
|
225
|
+
info: () => o("GetSubWebViewStorageInfo", {})
|
|
226
|
+
}),
|
|
227
|
+
onBack: (e) => {
|
|
228
|
+
s = e, p();
|
|
229
|
+
},
|
|
230
|
+
onCloseRequest: (e) => {
|
|
231
|
+
h = e, p();
|
|
232
|
+
},
|
|
233
|
+
onContextChange: (e) => (v.add(e), () => v.delete(e)),
|
|
234
|
+
link: (e) => {
|
|
235
|
+
const i = L(e), c = t.context?.appLink;
|
|
236
|
+
return c ? `${c}${i}` : P(i);
|
|
237
|
+
},
|
|
238
|
+
disconnect: () => {
|
|
239
|
+
w.forEach((e) => e()), r.close(), y = null;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
if (n.reportErrors !== !1 && typeof window < "u") {
|
|
243
|
+
const e = (c) => {
|
|
244
|
+
l.reportError(c.error ?? c.message);
|
|
245
|
+
}, i = (c) => {
|
|
246
|
+
l.reportError(c.reason);
|
|
247
|
+
};
|
|
248
|
+
window.addEventListener("error", e), window.addEventListener("unhandledrejection", i), w.push(() => {
|
|
249
|
+
window.removeEventListener("error", e), window.removeEventListener("unhandledrejection", i);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
return l;
|
|
253
|
+
}, F = () => {
|
|
254
|
+
const r = async (t) => {
|
|
255
|
+
try {
|
|
256
|
+
const n = await navigator.permissions.query({ name: t });
|
|
257
|
+
return n.state === "granted" ? "granted" : n.state === "denied" ? "blocked" : "prompt";
|
|
258
|
+
} catch {
|
|
259
|
+
return "prompt";
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
return {
|
|
263
|
+
query: r,
|
|
264
|
+
request: async (t) => {
|
|
265
|
+
if (typeof navigator > "u" || !navigator.mediaDevices?.getUserMedia)
|
|
266
|
+
throw new u("NOT_SUPPORTED", `This browser cannot capture the ${t}.`);
|
|
267
|
+
try {
|
|
268
|
+
return (await navigator.mediaDevices.getUserMedia(
|
|
269
|
+
t === "camera" ? { video: !0 } : { audio: !0 }
|
|
270
|
+
)).getTracks().forEach((s) => s.stop()), "granted";
|
|
271
|
+
} catch (n) {
|
|
272
|
+
const s = n?.name;
|
|
273
|
+
if (s === "NotFoundError" || s === "OverconstrainedError")
|
|
274
|
+
throw new u("UNAVAILABLE", `This device has no ${t}.`);
|
|
275
|
+
if (s === "NotReadableError" || s === "SecurityError" || s === "TypeError" || s === "AbortError")
|
|
276
|
+
throw new u("INTERNAL_ERROR", `The ${t} could not be used: ${s}.`);
|
|
277
|
+
return await r(t) === "blocked" ? "blocked" : "prompt";
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
}, H = () => {
|
|
282
|
+
const r = (t) => typeof navigator < "u" && navigator.clipboard ? navigator.clipboard.writeText(t) : Promise.reject(E("The clipboard"));
|
|
283
|
+
return {
|
|
284
|
+
inApp: !1,
|
|
285
|
+
context: null,
|
|
286
|
+
supports: () => !1,
|
|
287
|
+
finish: () => S("Finishing the view"),
|
|
288
|
+
setTitle: async (t) => {
|
|
289
|
+
typeof document < "u" && (document.title = t);
|
|
290
|
+
},
|
|
291
|
+
haptic: () => {
|
|
292
|
+
typeof navigator < "u" && navigator.vibrate?.(10);
|
|
293
|
+
},
|
|
294
|
+
copy: r,
|
|
295
|
+
openUrl: async (t) => {
|
|
296
|
+
typeof window < "u" && window.open(t, "_blank", "noopener,noreferrer");
|
|
297
|
+
},
|
|
298
|
+
share: async (t) => {
|
|
299
|
+
const n = [t.message, t.url].filter(Boolean).join(" ");
|
|
300
|
+
if (!n) throw new u("INVALID", "Share a message or a url.");
|
|
301
|
+
if (typeof navigator < "u" && navigator.share)
|
|
302
|
+
try {
|
|
303
|
+
return await navigator.share(t), "shared";
|
|
304
|
+
} catch (s) {
|
|
305
|
+
if (s?.name === "AbortError") return "dismissed";
|
|
306
|
+
}
|
|
307
|
+
return await r(n), "copied";
|
|
308
|
+
},
|
|
309
|
+
getUserKey: () => S("A user key"),
|
|
310
|
+
permissions: F(),
|
|
311
|
+
openSettings: () => S("Opening the settings"),
|
|
312
|
+
reportError: async (t) => (console.error(t), !1),
|
|
313
|
+
storage: I(),
|
|
314
|
+
onBack: () => {
|
|
315
|
+
},
|
|
316
|
+
onCloseRequest: () => {
|
|
317
|
+
},
|
|
318
|
+
onContextChange: () => () => {
|
|
319
|
+
},
|
|
320
|
+
link: (t) => P(L(t)),
|
|
321
|
+
disconnect: () => {
|
|
322
|
+
y = null;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
};
|
|
326
|
+
export {
|
|
327
|
+
u as ChaticAppsError,
|
|
328
|
+
V as SDK_BRIDGE_VERSION,
|
|
329
|
+
Q as connect,
|
|
330
|
+
M as isInApp
|
|
331
|
+
};
|
package/mock.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** What the app tells the page about where it runs. A snapshot; changes arrive through `onContextChange`. */
|
|
2
|
+
declare type ChaticAppsContext = {
|
|
3
|
+
/** The protocol major the app speaks. */
|
|
4
|
+
protocolVersion: 1;
|
|
5
|
+
viewId: string;
|
|
6
|
+
platform: 'ios' | 'android';
|
|
7
|
+
/** The app's own version. */
|
|
8
|
+
appVersion: string;
|
|
9
|
+
/** The language the user chose in the app (`ko`, `en`). */
|
|
10
|
+
locale: string;
|
|
11
|
+
/** The app's theme, which can differ from the OS's. */
|
|
12
|
+
theme: Theme;
|
|
13
|
+
/** What whoever opened the page passed it; `{}` when nothing. */
|
|
14
|
+
params: {
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
};
|
|
17
|
+
/** The link that opens this page in the app; absent from older apps. */
|
|
18
|
+
appLink?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** What the user did to ask for the close: the app's close control, or Android back. */
|
|
22
|
+
declare type CloseTrigger = 'control' | 'back';
|
|
23
|
+
|
|
24
|
+
/** A device a page captures from with `getUserMedia`. */
|
|
25
|
+
declare type DeviceKind = 'camera' | 'microphone';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Turns a browser tab into a stand-in for the app, so a page can be built and tried without it. Call
|
|
29
|
+
* it before `connect`, in development only. It answers as the app does — the base set, plus what
|
|
30
|
+
* `permissions` grants, and `NOT_FOUND` for the rest — and lets the developer play the user's side
|
|
31
|
+
* through the returned controller.
|
|
32
|
+
*
|
|
33
|
+
* It is a stand-in, not the app: the share sheet is logged rather than shown, the user key is not the
|
|
34
|
+
* app's, and nothing here proves a page works on a device.
|
|
35
|
+
*/
|
|
36
|
+
export declare const installChaticAppsMock: (options?: MockOptions) => MockController;
|
|
37
|
+
|
|
38
|
+
export declare interface MockController {
|
|
39
|
+
/** The title the page last asked for, if any. */
|
|
40
|
+
readonly title: string | undefined;
|
|
41
|
+
/** How the view closed, if it has: by the page (with its result) or by the user. */
|
|
42
|
+
readonly closed: {
|
|
43
|
+
by: 'page' | 'user';
|
|
44
|
+
result?: unknown;
|
|
45
|
+
} | null;
|
|
46
|
+
/** What the page's storage holds now. */
|
|
47
|
+
readonly storage: {
|
|
48
|
+
[key: string]: unknown;
|
|
49
|
+
};
|
|
50
|
+
/** Where the app stands with the OS for each device. */
|
|
51
|
+
readonly devices: Record<DeviceKind, PermissionState_2>;
|
|
52
|
+
/** Android's back button: to the page if it took back, else back in history, else a close. */
|
|
53
|
+
pressBack(): void;
|
|
54
|
+
/** The user asks to close: to the page if it guards closing (a second ask within 3 s closes). */
|
|
55
|
+
requestClose(trigger?: CloseTrigger): void;
|
|
56
|
+
/** A theme or language change while the page shows. */
|
|
57
|
+
changeContext(change: Partial<Pick<ChaticAppsContext, 'theme' | 'locale'>>): void;
|
|
58
|
+
/** Removes the fake app. */
|
|
59
|
+
uninstall(): void;
|
|
60
|
+
}
|
|
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
|
+
|
|
65
|
+
export declare interface MockOptions {
|
|
66
|
+
/** What the page's manifest would grant. None by default, as for a page with no manifest. */
|
|
67
|
+
permissions?: MockPermission[];
|
|
68
|
+
/** Overrides for the context the page gets; the rest is filled in. */
|
|
69
|
+
context?: Partial<ChaticAppsContext>;
|
|
70
|
+
/** The key `getUserKey` answers; a stable one derived from the page's origin by default. */
|
|
71
|
+
userKey?: string;
|
|
72
|
+
/** Called when the view closes: by the page (`finish`, with its result) or by the user. */
|
|
73
|
+
onClose?: (closed: {
|
|
74
|
+
by: 'page' | 'user';
|
|
75
|
+
result?: unknown;
|
|
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>>;
|
|
83
|
+
/** What the page's storage holds when the mock starts; empty by default. Kept in memory only. */
|
|
84
|
+
storage?: {
|
|
85
|
+
[key: string]: unknown;
|
|
86
|
+
};
|
|
87
|
+
/** Log each request and reply to the console. On by default. */
|
|
88
|
+
log?: boolean;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A manifest permission, as the page would declare it in `/.well-known/chatic-app.json`. */
|
|
92
|
+
export declare type MockPermission = 'clipboard' | 'share' | 'openUrl' | 'userKey';
|
|
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
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The shapes a page sees, declared here rather than imported: the app's message definitions are a
|
|
104
|
+
* private package, and a published library cannot point at it. `types.contract.test.ts` holds each one
|
|
105
|
+
* equal to its counterpart there, so the two cannot drift apart unnoticed.
|
|
106
|
+
*/
|
|
107
|
+
declare type Theme = 'light' | 'dark';
|
|
108
|
+
|
|
109
|
+
export { }
|
package/mock.d.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** What the app tells the page about where it runs. A snapshot; changes arrive through `onContextChange`. */
|
|
2
|
+
declare type ChaticAppsContext = {
|
|
3
|
+
/** The protocol major the app speaks. */
|
|
4
|
+
protocolVersion: 1;
|
|
5
|
+
viewId: string;
|
|
6
|
+
platform: 'ios' | 'android';
|
|
7
|
+
/** The app's own version. */
|
|
8
|
+
appVersion: string;
|
|
9
|
+
/** The language the user chose in the app (`ko`, `en`). */
|
|
10
|
+
locale: string;
|
|
11
|
+
/** The app's theme, which can differ from the OS's. */
|
|
12
|
+
theme: Theme;
|
|
13
|
+
/** What whoever opened the page passed it; `{}` when nothing. */
|
|
14
|
+
params: {
|
|
15
|
+
[key: string]: unknown;
|
|
16
|
+
};
|
|
17
|
+
/** The link that opens this page in the app; absent from older apps. */
|
|
18
|
+
appLink?: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** What the user did to ask for the close: the app's close control, or Android back. */
|
|
22
|
+
declare type CloseTrigger = 'control' | 'back';
|
|
23
|
+
|
|
24
|
+
/** A device a page captures from with `getUserMedia`. */
|
|
25
|
+
declare type DeviceKind = 'camera' | 'microphone';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Turns a browser tab into a stand-in for the app, so a page can be built and tried without it. Call
|
|
29
|
+
* it before `connect`, in development only. It answers as the app does — the base set, plus what
|
|
30
|
+
* `permissions` grants, and `NOT_FOUND` for the rest — and lets the developer play the user's side
|
|
31
|
+
* through the returned controller.
|
|
32
|
+
*
|
|
33
|
+
* It is a stand-in, not the app: the share sheet is logged rather than shown, the user key is not the
|
|
34
|
+
* app's, and nothing here proves a page works on a device.
|
|
35
|
+
*/
|
|
36
|
+
export declare const installChaticAppsMock: (options?: MockOptions) => MockController;
|
|
37
|
+
|
|
38
|
+
export declare interface MockController {
|
|
39
|
+
/** The title the page last asked for, if any. */
|
|
40
|
+
readonly title: string | undefined;
|
|
41
|
+
/** How the view closed, if it has: by the page (with its result) or by the user. */
|
|
42
|
+
readonly closed: {
|
|
43
|
+
by: 'page' | 'user';
|
|
44
|
+
result?: unknown;
|
|
45
|
+
} | null;
|
|
46
|
+
/** What the page's storage holds now. */
|
|
47
|
+
readonly storage: {
|
|
48
|
+
[key: string]: unknown;
|
|
49
|
+
};
|
|
50
|
+
/** Where the app stands with the OS for each device. */
|
|
51
|
+
readonly devices: Record<DeviceKind, PermissionState_2>;
|
|
52
|
+
/** Android's back button: to the page if it took back, else back in history, else a close. */
|
|
53
|
+
pressBack(): void;
|
|
54
|
+
/** The user asks to close: to the page if it guards closing (a second ask within 3 s closes). */
|
|
55
|
+
requestClose(trigger?: CloseTrigger): void;
|
|
56
|
+
/** A theme or language change while the page shows. */
|
|
57
|
+
changeContext(change: Partial<Pick<ChaticAppsContext, 'theme' | 'locale'>>): void;
|
|
58
|
+
/** Removes the fake app. */
|
|
59
|
+
uninstall(): void;
|
|
60
|
+
}
|
|
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
|
+
|
|
65
|
+
export declare interface MockOptions {
|
|
66
|
+
/** What the page's manifest would grant. None by default, as for a page with no manifest. */
|
|
67
|
+
permissions?: MockPermission[];
|
|
68
|
+
/** Overrides for the context the page gets; the rest is filled in. */
|
|
69
|
+
context?: Partial<ChaticAppsContext>;
|
|
70
|
+
/** The key `getUserKey` answers; a stable one derived from the page's origin by default. */
|
|
71
|
+
userKey?: string;
|
|
72
|
+
/** Called when the view closes: by the page (`finish`, with its result) or by the user. */
|
|
73
|
+
onClose?: (closed: {
|
|
74
|
+
by: 'page' | 'user';
|
|
75
|
+
result?: unknown;
|
|
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>>;
|
|
83
|
+
/** What the page's storage holds when the mock starts; empty by default. Kept in memory only. */
|
|
84
|
+
storage?: {
|
|
85
|
+
[key: string]: unknown;
|
|
86
|
+
};
|
|
87
|
+
/** Log each request and reply to the console. On by default. */
|
|
88
|
+
log?: boolean;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A manifest permission, as the page would declare it in `/.well-known/chatic-app.json`. */
|
|
92
|
+
export declare type MockPermission = 'clipboard' | 'share' | 'openUrl' | 'userKey';
|
|
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
|
+
|
|
102
|
+
/**
|
|
103
|
+
* The shapes a page sees, declared here rather than imported: the app's message definitions are a
|
|
104
|
+
* private package, and a published library cannot point at it. `types.contract.test.ts` holds each one
|
|
105
|
+
* equal to its counterpart there, so the two cannot drift apart unnoticed.
|
|
106
|
+
*/
|
|
107
|
+
declare type Theme = 'light' | 'dark';
|
|
108
|
+
|
|
109
|
+
export { }
|