@lemoncloud/chatic-apps-sdk 0.0.0-stage → 0.1.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/README.md +288 -2
- package/chatic-apps-sdk.global.js +1 -0
- package/index.cjs +1 -0
- package/index.d.cts +192 -0
- package/index.d.ts +192 -0
- package/index.js +288 -0
- package/mock.cjs +1 -0
- package/mock.d.cts +87 -0
- package/mock.d.ts +87 -0
- package/mock.js +196 -0
- package/package.json +45 -5
- package/storage-BuvWwLx2.js +104 -0
- package/storage-yeS4HWKZ.cjs +1 -0
package/README.md
CHANGED
|
@@ -1,3 +1,289 @@
|
|
|
1
|
-
#
|
|
1
|
+
# chatic-apps-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Build pages that run inside the DoU app. A page on `https://<name>.apps.chatic.io` opens in the app
|
|
4
|
+
over everything else, and talks to the app through this library: close itself and hand back a result,
|
|
5
|
+
title the app's bar, play a haptic, share, copy, open a link outside, keep its own data on the device,
|
|
6
|
+
get a key to keep the user's data under on a server, take Android's back button, and ask before the
|
|
7
|
+
user closes it. Users reach it in the app only — a link to it never opens it in a browser — but the
|
|
8
|
+
same page runs in a plain browser tab too while you build it, where the library falls back to what the
|
|
9
|
+
browser can do.
|
|
10
|
+
|
|
11
|
+
Published as `@lemoncloud/chatic-apps-sdk`. No runtime dependencies.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @lemoncloud/chatic-apps-sdk
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Or, with no bundler, one script that defines `window.ChaticAppsSDK` (pin the version; the mock below
|
|
20
|
+
is not in this file):
|
|
21
|
+
|
|
22
|
+
```html
|
|
23
|
+
<script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.1.0/chatic-apps-sdk.global.js"></script>
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Start
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { connect, ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
const apps = await connect();
|
|
33
|
+
if (apps.inApp) await apps.setTitle('Quiz');
|
|
34
|
+
document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
|
|
35
|
+
} catch (error) {
|
|
36
|
+
// `UNSUPPORTED_PROTOCOL`: the app is newer than this library — update the library, and tell the
|
|
37
|
+
// user this page needs an update. `TIMEOUT`: the app did not answer (see "Rules worth knowing").
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Call `connect()` when the page starts. In the app it waits for the app's answer (a few
|
|
42
|
+
milliseconds); in a browser it returns at once. Calling it again returns the same connection, so any
|
|
43
|
+
part of the page may call it. Everything below is a method on what it returns.
|
|
44
|
+
|
|
45
|
+
## A complete page
|
|
46
|
+
|
|
47
|
+
One file, no build step. Save it as `index.html`, open it in a browser, and it runs with the browser
|
|
48
|
+
stand-ins; deployed to your `apps.chatic.io` address, it runs in the app.
|
|
49
|
+
|
|
50
|
+
```html
|
|
51
|
+
<!doctype html>
|
|
52
|
+
<html lang="ko">
|
|
53
|
+
<head>
|
|
54
|
+
<meta charset="utf-8" />
|
|
55
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
|
56
|
+
<title>Quiz</title>
|
|
57
|
+
<script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.1.0/chatic-apps-sdk.global.js"></script>
|
|
58
|
+
</head>
|
|
59
|
+
<body>
|
|
60
|
+
<h1 id="score">0</h1>
|
|
61
|
+
<button id="plus">+1</button>
|
|
62
|
+
<button id="share" hidden>Share</button>
|
|
63
|
+
<button id="done">Done</button>
|
|
64
|
+
<script type="module">
|
|
65
|
+
const { connect } = window.ChaticAppsSDK;
|
|
66
|
+
const apps = await connect();
|
|
67
|
+
let score = 0;
|
|
68
|
+
|
|
69
|
+
document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
|
|
70
|
+
apps.onContextChange(context => (document.documentElement.dataset.theme = context.theme));
|
|
71
|
+
|
|
72
|
+
document.getElementById('plus').onclick = () => {
|
|
73
|
+
score += 1;
|
|
74
|
+
document.getElementById('score').textContent = String(score);
|
|
75
|
+
apps.haptic('selection');
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
// Offer only what this app can do here.
|
|
79
|
+
const share = document.getElementById('share');
|
|
80
|
+
share.hidden = !(apps.supports('share') || !apps.inApp);
|
|
81
|
+
share.onclick = () => apps.share({ message: `I scored ${score}`, url: apps.link({ score }) });
|
|
82
|
+
|
|
83
|
+
document.getElementById('done').onclick = async () => {
|
|
84
|
+
if (apps.inApp) await apps.finish({ score });
|
|
85
|
+
};
|
|
86
|
+
</script>
|
|
87
|
+
</body>
|
|
88
|
+
</html>
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## What a page can do
|
|
92
|
+
|
|
93
|
+
| Call | In the app | In a browser | Needs permission |
|
|
94
|
+
| ----------------------------------------- | ------------------------------------------------------------------ | ----------------------------------- | ---------------- |
|
|
95
|
+
| `finish(result?)` | Closes the view; `result` (JSON, ≤ 16 KiB) goes back to the opener | `NOT_IN_APP` | — |
|
|
96
|
+
| `setTitle(title)` | The app's bar shows it (1–100 characters) | `document.title` | — |
|
|
97
|
+
| `haptic(kind)` | `selection`, `impact`, `success`, `warning`, `error` | a short vibration, if any | — |
|
|
98
|
+
| `onBack(handler \| null)` | Android back calls `handler` and does nothing else | never called | — |
|
|
99
|
+
| `onCloseRequest(handler \| null)` | Asks before the user closes; return `true` to close | never called | — |
|
|
100
|
+
| `reportError(error)` | Into DoU's log, under your origin (20 per page load) | `console.error` | — |
|
|
101
|
+
| `copy(text)` | The clipboard | the browser's clipboard | `clipboard` |
|
|
102
|
+
| `share({ title, message, url })` | The share sheet; waits for the user (see below) | Web Share, else copies (`'copied'`) | `share` |
|
|
103
|
+
| `openUrl(url)` | The browser, mail, phone, SMS or a store | a new tab | `openUrl` |
|
|
104
|
+
| `getUserKey()` | 64 hex characters, the same for this device and site | `NOT_IN_APP` | `userKey` |
|
|
105
|
+
| `link(params?)` | A link that opens this page in the app (see below) | the page's own root | — |
|
|
106
|
+
| `storage.get(key)`, `.set(key, value)`, … | Your page's own storage on the device (see below) | `localStorage`, same limits | — |
|
|
107
|
+
|
|
108
|
+
Plus `apps.context` (the app's language, theme, platform and the `params` you were opened with),
|
|
109
|
+
`apps.onContextChange(listener)` for a theme or language change, `apps.supports(capability)`,
|
|
110
|
+
`apps.inApp`, and `apps.disconnect()`.
|
|
111
|
+
|
|
112
|
+
- **`share`** resolves `'shared'` or `'dismissed'` on iOS. On Android it resolves `'shared'` as soon as
|
|
113
|
+
the chooser opens, whatever the user then does. It needs a non-blank `message` or a `url`; `url` must
|
|
114
|
+
be `http(s)`; `title`, `message` and `url` are at most 100, 4,000 and 2,048 characters.
|
|
115
|
+
- **`link(params)`** takes what the link should carry as an object and gives
|
|
116
|
+
`https://app.chatic.io/apps/<app id>?level=3&seed=7` for `link({ level: 3, seed: 7 })`. A tap opens
|
|
117
|
+
your page in the app **at its root** with that query — read it from `location.search`; a link carries
|
|
118
|
+
no path and no fragment. Where the app is not installed, the tap offers the app's store page, never
|
|
119
|
+
your page in the browser. The app id is the one your page was registered under, which need not be its
|
|
120
|
+
subdomain, so never write the link by hand. In a browser, or an app before links to pages existed, it
|
|
121
|
+
gives your page's own root with the same query.
|
|
122
|
+
- **`storage`** keeps JSON on the device for your site alone: `get(key)`, `getMany(keys)`,
|
|
123
|
+
`set(key, value)`, `setMany(entries)` (all or none), `remove(key or keys)`, `keys()`, `clear()` and
|
|
124
|
+
`usage()`. It survives relaunches and sign-outs and goes with an uninstall; it does not follow the user
|
|
125
|
+
to another phone. Your site gets 1,048,576 characters in all (keys plus values as JSON) — past it a
|
|
126
|
+
write fails with `QUOTA_EXCEEDED` and changes nothing — keys of 1–200 characters (not `__proto__`),
|
|
127
|
+
and at most 64 KiB in one call (`TOO_LARGE`). A value is written in one call, so one value stays
|
|
128
|
+
under 64 KiB; split anything bigger across keys.
|
|
129
|
+
- **Uncaught errors are reported for you.** `connect()` listens for `error` and `unhandledrejection` and
|
|
130
|
+
sends them to DoU's log. An `Error` sends its message and stack, a string itself, anything else only
|
|
131
|
+
its type. Pass `connect({ reportErrors: false })` to turn it off.
|
|
132
|
+
|
|
133
|
+
## Permissions
|
|
134
|
+
|
|
135
|
+
The four calls marked above need a permission your page asks for in a file on its own site,
|
|
136
|
+
`/.well-known/chatic-app.json`:
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{
|
|
140
|
+
"manifestVersion": 1,
|
|
141
|
+
"name": "Quiz",
|
|
142
|
+
"permissions": ["share", "userKey"],
|
|
143
|
+
"display": "standard",
|
|
144
|
+
"orientation": "portrait"
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
You ask; an administrator grants them when your page is reviewed, and only what was granted is
|
|
149
|
+
deployed. Without the file your page gets everything else but not these four, which then fail with
|
|
150
|
+
`NOT_SUPPORTED`. `display: "fullscreen"` hides the app's bar (a small close button stays in the
|
|
151
|
+
top-right corner — keep it clear); `orientation` is `any`, `portrait` or `landscape`. The app reads
|
|
152
|
+
the file before it shows your page, keeps it for the rest of its run, and fetches a fresh copy behind
|
|
153
|
+
each later open: a change to the file takes effect one open later.
|
|
154
|
+
|
|
155
|
+
## Errors
|
|
156
|
+
|
|
157
|
+
Every failure is a `ChaticAppsError` with a `code`:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
import { ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
const key = await apps.getUserKey();
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (error instanceof ChaticAppsError && (error.code === 'NOT_SUPPORTED' || error.code === 'NOT_IN_APP')) {
|
|
166
|
+
// A browser, an older app, or no `userKey` permission: sign in your own way.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
| Code | Means |
|
|
172
|
+
| ---------------------- | ---------------------------------------------------------------------------------------------------- |
|
|
173
|
+
| `NOT_SUPPORTED` | Not available: an older app, a permission the page does not hold, or no browser clipboard or storage |
|
|
174
|
+
| `NOT_IN_APP` | The call needs the app, and the page is in a browser |
|
|
175
|
+
| `TIMEOUT` | The app did not answer in 10 seconds (time in the background does not count) |
|
|
176
|
+
| `INVALID` | A value is missing, of the wrong type, or too long |
|
|
177
|
+
| `TOO_LARGE` | One call's data is over 65,536 characters |
|
|
178
|
+
| `LINK_NOT_ALLOWED` | The link cannot be opened or shared from a page |
|
|
179
|
+
| `NOT_OPEN` | `finish` after the view has already closed |
|
|
180
|
+
| `UNAVAILABLE` | The device has no id to make a user key from, or the app could not open the page's storage |
|
|
181
|
+
| `QUOTA_EXCEEDED` | A storage write would go past 1,048,576 characters; nothing was written |
|
|
182
|
+
| `DISCONNECTED` | The call was waiting when `disconnect()` closed the connection |
|
|
183
|
+
| `UNSUPPORTED_PROTOCOL` | `connect()` only: the app is newer than this library; update it |
|
|
184
|
+
|
|
185
|
+
Treat a code not in this table as that call failing, and nothing more.
|
|
186
|
+
|
|
187
|
+
## Rules worth knowing
|
|
188
|
+
|
|
189
|
+
- **Decide what to offer with `apps.supports(...)`**, never with a version number. A share button
|
|
190
|
+
shows only if `apps.supports('share')`.
|
|
191
|
+
- **Save as you go.** The app or the web that opened the page can close it at any time without
|
|
192
|
+
asking. Listen to `document`'s `visibilitychange` and save when it turns `hidden` — the app sends no
|
|
193
|
+
"going to the background" signal.
|
|
194
|
+
- **Share `apps.link(params)`**, not your page's address: a tap on it opens the page in the app.
|
|
195
|
+
Put what a shared link needs in its query and read it from `location.search` at start; nothing
|
|
196
|
+
after your page's root survives a link.
|
|
197
|
+
- **The user key is not an account and proves nothing.** It stays the same on one device for your site,
|
|
198
|
+
and differs on every other site. Two people on one phone share it; anyone who learns one can send it.
|
|
199
|
+
Keep game progress under it, not money.
|
|
200
|
+
- **`onCloseRequest` is for something the user would lose.** A second close within three seconds always
|
|
201
|
+
closes, so a page cannot keep the user in.
|
|
202
|
+
- **Leaving your origin leaves the bridge.** A link to another site opens in the browser; a page on
|
|
203
|
+
another `apps.chatic.io` address loads in the view but gets no answers, so `connect()` there ends in
|
|
204
|
+
`TIMEOUT`.
|
|
205
|
+
- **You cannot see the error reports.** They go to DoU's log, read by the people who review pages.
|
|
206
|
+
Send errors to your own server too if you want to see them.
|
|
207
|
+
|
|
208
|
+
## What this WebView is like
|
|
209
|
+
|
|
210
|
+
- **Use `apps.storage`, not the WebView's own**: `localStorage` and IndexedDB work, but go whenever the
|
|
211
|
+
system clears website data. Keep what must follow the user to another phone on your own server, under
|
|
212
|
+
`getUserKey()`.
|
|
213
|
+
- **No popups**: `window.open` and `target="_blank"` load in the same view, so a login that answers
|
|
214
|
+
through `window.opener` does not work. Use a redirect login.
|
|
215
|
+
- **Downloads**: a file download is not handled on iOS. Show the content instead.
|
|
216
|
+
- **Camera and microphone** work through the browser APIs, under DoU's name: the OS asks the user
|
|
217
|
+
"DoU would like to…". What your page uses is part of its review.
|
|
218
|
+
- **Your own server**: calls to it are ordinary cross-origin requests from `https://<name>.apps.chatic.io`;
|
|
219
|
+
allow that origin in its CORS settings.
|
|
220
|
+
- **Layout**: the page sits inside the safe area on every edge; there are no insets to handle. Use the
|
|
221
|
+
context's `theme`, not the OS's, for dark mode — the user can set DoU's theme apart from the phone's.
|
|
222
|
+
|
|
223
|
+
## Try it without the app
|
|
224
|
+
|
|
225
|
+
`@lemoncloud/chatic-apps-sdk/mock` turns a browser tab into a stand-in for the app. Install it before
|
|
226
|
+
`connect()`, in development only:
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
import { connect } from '@lemoncloud/chatic-apps-sdk';
|
|
230
|
+
import { installChaticAppsMock } from '@lemoncloud/chatic-apps-sdk/mock';
|
|
231
|
+
|
|
232
|
+
const app = import.meta.env.DEV ? installChaticAppsMock({ permissions: ['share', 'userKey'] }) : null;
|
|
233
|
+
const apps = await connect();
|
|
234
|
+
|
|
235
|
+
// Play the user's side from the console or a dev button:
|
|
236
|
+
app?.pressBack();
|
|
237
|
+
app?.requestClose();
|
|
238
|
+
app?.changeContext({ theme: 'dark' });
|
|
239
|
+
console.log(app?.closed); // { by: 'page', result } once the page finishes, { by: 'user' } on a close
|
|
240
|
+
console.log(app?.storage); // what the page has stored
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Pass `storage: { … }` to start with data already stored; the mock keeps it in memory only.
|
|
244
|
+
|
|
245
|
+
It answers as the app does — the base calls, plus the `permissions` you give it, and `NOT_SUPPORTED`
|
|
246
|
+
for the rest — checks what the app checks, and logs every call. It is a stand-in: the share sheet is
|
|
247
|
+
logged rather than shown, the user key is not the app's, and it proves nothing about a phone.
|
|
248
|
+
|
|
249
|
+
## For an AI assistant writing a page
|
|
250
|
+
|
|
251
|
+
Paste this list into the prompt along with what the page should do.
|
|
252
|
+
|
|
253
|
+
1. Use `@lemoncloud/chatic-apps-sdk`. Call `await connect()` once at start, inside `try/catch`.
|
|
254
|
+
2. Check `apps.inApp` and `apps.supports(capability)` before offering an app feature; never compare
|
|
255
|
+
version numbers.
|
|
256
|
+
3. Every call can throw `ChaticAppsError`; branch on `error.code` only, never on `error.message`.
|
|
257
|
+
4. Take the theme and language from `apps.context` and `apps.onContextChange`, not from the OS.
|
|
258
|
+
5. Share links built with `apps.link({ ... })`, and read what one carries from `location.search` at
|
|
259
|
+
start. The page is always entered at `/`; do not route on the path.
|
|
260
|
+
6. Keep the page's state in `apps.storage` as it changes, and at the latest on `visibilitychange` to
|
|
261
|
+
`hidden`; never in `localStorage`. What must follow the user to another phone goes on your own server
|
|
262
|
+
under `apps.getUserKey()`.
|
|
263
|
+
7. Use `apps.onBack(handler)` for in-page dialogs; clear it with `apps.onBack(null)` when they close.
|
|
264
|
+
8. Use `apps.onCloseRequest` only to protect unsaved work; return `true` to close.
|
|
265
|
+
9. No `window.opener`, no popup logins, no file downloads.
|
|
266
|
+
10. Never put the user's data in errors or in `reportError`.
|
|
267
|
+
11. List the permissions the page needs (`clipboard`, `share`, `openUrl`, `userKey`) in
|
|
268
|
+
`/.well-known/chatic-app.json` — and nothing it does not use.
|
|
269
|
+
12. In development, `installChaticAppsMock({ permissions: [...] })` before `connect()`.
|
|
270
|
+
|
|
271
|
+
## For maintainers
|
|
272
|
+
|
|
273
|
+
This library lives in the DoU app's repository so it cannot drift from the app: its public types are
|
|
274
|
+
pinned to the app's message definitions by a type-level test, and a contract test in the app runs this
|
|
275
|
+
client against the app's real page host. The protocol it speaks is specified in
|
|
276
|
+
[sub-webview-protocol.md](https://github.com/lemoncloud-io/dou-app/blob/develop/apps/mobile/docs/webview/sub-webview-protocol.md).
|
|
277
|
+
|
|
278
|
+
```bash
|
|
279
|
+
npx jest --config libs/chatic-apps-sdk/jest.config.js
|
|
280
|
+
npx tsc -b libs/chatic-apps-sdk/tsconfig.json
|
|
281
|
+
npx nx build @chatic/chatic-apps-sdk # dist/libs/chatic-apps-sdk, ready to publish
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
The build writes `package.publish.json` as the published `package.json` (`publishConfig.access` is
|
|
285
|
+
`public`, so a scoped package is never published private by mistake). Publish from the build output:
|
|
286
|
+
|
|
287
|
+
```bash
|
|
288
|
+
cd dist/libs/chatic-apps-sdk && npm publish --dry-run
|
|
289
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var ChaticAppsSDK=(function(y){"use strict";class p extends Error{code;constructor(t,r){super(r),this.name="ChaticAppsError",this.code=t}}const O="2.19.0",M=1e4,x=2e3;let W=0;const U=()=>`cas-${Date.now().toString(36)}-${(++W).toString(36)}`,R=()=>typeof document<"u"&&document.visibilityState==="hidden",G=(e,t=M)=>{const r=new Map,o=new Map;let c=!1;const h=(i,s)=>{s.remaining===null||R()||(s.startedAt=Date.now(),s.timer=setTimeout(()=>{r.delete(i),s.reject(new p("TIMEOUT","The app did not answer in time."))},s.remaining))},d=()=>{for(const[i,s]of r)s.remaining!==null&&(R()?(s.timer&&clearTimeout(s.timer),s.timer=null,s.remaining=Math.max(0,s.remaining-(Date.now()-s.startedAt))):s.timer||(s.remaining=Math.max(s.remaining,x),h(i,s)))};typeof document<"u"&&document.addEventListener("visibilitychange",d);const f=e.listen(i=>{let s;try{s=JSON.parse(i)}catch{return}if(!s||typeof s!="object"||typeof s.type!="string")return;const l=typeof s.refId=="string"?r.get(s.refId):void 0;if(l&&typeof s.refId=="string"){if(r.delete(s.refId),l.timer&&clearTimeout(l.timer),s.success===!0)l.resolve(s.data);else{const g=typeof s.error?.code=="string"?s.error.code:"INTERNAL_ERROR",v=typeof s.error?.message=="string"?s.error.message:g;l.reject(new p(g,v))}return}o.get(s.type)?.forEach(g=>{try{g(s.data)}catch{}})});return{request:(i,s={},l={})=>new Promise((g,v)=>{if(c){v(new p("DISCONNECTED","The connection to the app was closed."));return}const w=U(),n=l.timeoutMs===void 0?t:l.timeoutMs,a={resolve:g,reject:v,remaining:n,startedAt:Date.now(),timer:null};r.set(w,a),h(w,a),e.send(JSON.stringify({type:i,data:s,refId:w,version:O}))}),onPush:(i,s)=>{let l=o.get(i);return l||o.set(i,l=new Set),l.add(s),()=>l?.delete(s)},close:()=>{if(!c){c=!0,f(),typeof document<"u"&&document.removeEventListener("visibilitychange",d);for(const i of r.values())i.timer&&clearTimeout(i.timer),i.reject(new p("DISCONNECTED","The connection to the app was closed."));r.clear(),o.clear()}}}},I=e=>{try{return JSON.stringify(e)??null}catch{return null}},L=e=>{const t=r=>Object.values(r??{}).every(o=>I(o)!==null)?e.set(r).then(()=>{}):Promise.reject(new p("INVALID","Values must be JSON; remove a key rather than storing undefined."));return{get:r=>e.get([r]).then(o=>o.entries[r]),getMany:r=>e.get(r).then(o=>o.entries),set:(r,o)=>t({[r]:o}),setMany:t,remove:r=>e.remove(typeof r=="string"?[r]:r).then(()=>{}),keys:()=>e.info().then(r=>r.keys),clear:()=>e.clear().then(()=>{}),usage:()=>e.info().then(({used:r,limit:o})=>({used:r,limit:o}))}},P=1024*1024,q=200,$=64*1024,T=e=>typeof e=="string"&&e.length>=1&&e.length<=q&&e!=="__proto__",K=e=>{const t=()=>e.keys().reduce((o,c)=>o+c.length+(e.read(c)?.length??0),0),r=()=>({used:t(),limit:P});return{get(o){if(!Array.isArray(o)||!o.every(T))return{ok:!1,code:"INVALID"};const c={};for(const h of o){const d=e.read(h);if(d!==void 0)try{c[h]=JSON.parse(d)}catch{}}return{ok:!0,value:{entries:c}}},set(o){if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,code:"INVALID"};const c=[];let h=t();for(const[d,f]of Object.entries(o)){const i=I(f);if(!T(d)||i===null)return{ok:!1,code:"INVALID"};const s=e.read(d);h+=i.length-(s===void 0?-d.length:s.length),c.push([d,i])}return h>P?{ok:!1,code:"QUOTA_EXCEEDED"}:(c.forEach(([d,f])=>e.write(d,f)),{ok:!0,value:r()})},remove(o){return!Array.isArray(o)||!o.every(T)?{ok:!1,code:"INVALID"}:(o.forEach(c=>e.delete(c)),{ok:!0,value:r()})},clear(){return e.keys().forEach(o=>e.delete(o)),{ok:!0,value:{}}},info(){return{ok:!0,value:{keys:e.keys(),...r()}}}}},b="chatic-apps.storage:",B=e=>({read:t=>e.getItem(b+t)??void 0,write:(t,r)=>e.setItem(b+t,r),delete:t=>e.removeItem(b+t),keys:()=>{const t=[];for(let r=0;r<e.length;r++){const o=e.key(r);o?.startsWith(b)&&t.push(o.slice(b.length))}return t}}),F=()=>{const e=t=>{let r;try{r=t(K(B(window.localStorage)))}catch(o){return o?.name==="QuotaExceededError"?Promise.reject(new p("QUOTA_EXCEEDED","The browser's own storage is full.")):Promise.reject(new p("NOT_SUPPORTED","This browser refuses local storage."))}return r.ok?Promise.resolve(r.value):Promise.reject(new p(r.code,`The storage refused the call: ${r.code}.`))};return L({get:t=>e(r=>r.get(t)),set:t=>(I({entries:t})?.length??0)>$?Promise.reject(new p("TOO_LARGE","One call carries at most 65,536 characters.")):e(r=>r.set(t)),remove:t=>e(r=>r.remove(t)),clear:()=>e(t=>t.clear()),info:()=>e(t=>t.info())})},k=()=>typeof window<"u"&&!!window.ReactNativeWebView,J=()=>({send:e=>window.ReactNativeWebView?.postMessage(e),listen:e=>{const t=r=>{const o=r.data;typeof o=="string"&&e(o)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),E={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage"},C=1,Q=1e3,H=4e3,V=()=>typeof window<"u"&&window.ChaticSubWebView||null,X=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(V());return}window.addEventListener("load",()=>e(V()),{once:!0})}),z=e=>{let t,r;try{e instanceof Error?(t=e.message||e.name,r=typeof e.stack=="string"?e.stack:void 0):typeof e=="string"?t=e:t=`A non-Error value was thrown: ${Object.prototype.toString.call(e)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,Q),...r?{stack:r.slice(0,H)}:{}}},A=e=>new p("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),_=e=>Promise.reject(new p("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),D=(e={})=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new p("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[o,c]of Object.entries(e))t.append(o,String(c));const r=t.toString();return r?`?${r}`:""},N=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let S=null;const Y=(e={})=>(S||(S=(k()?Z(J(),e):Promise.resolve(te())).catch(t=>{throw S=null,t})),S),Z=async(e,t={})=>{const r=G(e,t.timeoutMs);try{const o=await j(r,!0);return ee(r,o,t)}catch(o){throw r.close(),o}},j=async(e,t)=>{const r=await e.request("WebAppReady",{}),o=r.subWebView??(t?await X():null);if(o&&o.protocolVersion!==C)throw new p("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(o.protocolVersion)}; this library speaks ${C}.`);return{supported:new Set(Array.isArray(r.supportedWebMessages)?r.supportedWebMessages:[]),context:o}},ee=(e,t,r)=>{let o=null,c=null;const h=new Set,d=[],f=n=>t.supported.has(E[n]),i=(n,a,u)=>f(n)?e.request(E[n],a,u===void 0?{}:{timeoutMs:u}):Promise.reject(A(n)),s=(n,a)=>f("storage")?e.request(n,a):Promise.reject(A("storage")),l=n=>h.forEach(a=>{try{a(n)}catch(u){w.reportError(u)}}),g=()=>{f("back")&&e.request(E.back,{canGoBack:!!o}).catch(()=>{}),f("closeGuard")&&e.request(E.closeGuard,{enabled:!!c}).catch(()=>{})},v=n=>{if(!n.persisted){g();return}j(e,!1).then(a=>{const u=t.context;t.supported=a.supported,a.context&&(t.context=a.context),g();const m=t.context;m&&(m.theme!==u?.theme||m.locale!==u?.locale)&&l(m)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",v),d.push(()=>window.removeEventListener("pageshow",v))),d.push(e.onPush("OnBackPressed",()=>{try{o?.()}catch(n){w.reportError(n)}})),d.push(e.onPush("OnSubWebViewCloseRequested",n=>{const a=c;if(!a)return;const u=n?.trigger??"control";Promise.resolve().then(()=>a(u)).then(m=>m?w.finish():void 0).catch(m=>w.reportError(m))})),d.push(e.onPush("OnSubWebViewContextChanged",n=>{t.context&&(t.context={...t.context,...n},l(t.context))}));const w={inApp:!0,get context(){return t.context},supports:f,finish:n=>i("finish",n===void 0?{}:{result:n}).then(()=>{}),setTitle:n=>i("title",{title:n}).then(()=>{}),haptic:n=>{f("haptic")&&e.request(E.haptic,{kind:n}).catch(()=>{})},copy:n=>i("clipboard",{text:n}).then(()=>{}),openUrl:n=>i("openUrl",{url:n}).then(()=>{}),share:n=>i("share",n,null).then(a=>a?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>i("userKey").then(n=>n.key),reportError:n=>f("errorReport")?e.request(E.errorReport,z(n)).then(a=>!!a?.recorded).catch(()=>!1):Promise.resolve(!1),storage:L({get:n=>s("GetSubWebViewStorage",{keys:n}),set:n=>s("SetSubWebViewStorage",{entries:n}),remove:n=>s("RemoveSubWebViewStorage",{keys:n}),clear:()=>s("ClearSubWebViewStorage",{}),info:()=>s("GetSubWebViewStorageInfo",{})}),onBack:n=>{o=n,g()},onCloseRequest:n=>{c=n,g()},onContextChange:n=>(h.add(n),()=>h.delete(n)),link:n=>{const a=D(n),u=t.context?.appLink;return u?`${u}${a}`:N(a)},disconnect:()=>{d.forEach(n=>n()),e.close(),S=null}};if(r.reportErrors!==!1&&typeof window<"u"){const n=u=>{w.reportError(u.error??u.message)},a=u=>{w.reportError(u.reason)};window.addEventListener("error",n),window.addEventListener("unhandledrejection",a),d.push(()=>{window.removeEventListener("error",n),window.removeEventListener("unhandledrejection",a)})}return w},te=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(A("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>_("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:e,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const r=[t.message,t.url].filter(Boolean).join(" ");if(!r)throw new p("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(t),"shared"}catch(o){if(o?.name==="AbortError")return"dismissed"}return await e(r),"copied"},getUserKey:()=>_("A user key"),reportError:async t=>(console.error(t),!1),storage:F(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>N(D(t)),disconnect:()=>{S=null}}};return y.ChaticAppsError=p,y.SDK_BRIDGE_VERSION=O,y.connect=Y,y.isInApp=k,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
|
package/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./storage-yeS4HWKZ.cjs"),R="2.19.0",P=1e4,V=2e3;let x=0;const W=()=>`cas-${Date.now().toString(36)}-${(++x).toString(36)}`,S=()=>typeof document<"u"&&document.visibilityState==="hidden",M=(t,r=P)=>{const n=new Map,i=new Map;let f=!1;const v=(a,o)=>{o.remaining===null||S()||(o.startedAt=Date.now(),o.timer=setTimeout(()=>{n.delete(a),o.reject(new p.ChaticAppsError("TIMEOUT","The app did not answer in time."))},o.remaining))},h=()=>{for(const[a,o]of n)o.remaining!==null&&(S()?(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,V),v(a,o)))};typeof document<"u"&&document.addEventListener("visibilitychange",h);const w=t.listen(a=>{let o;try{o=JSON.parse(a)}catch{return}if(!o||typeof o!="object"||typeof o.type!="string")return;const d=typeof o.refId=="string"?n.get(o.refId):void 0;if(d&&typeof o.refId=="string"){if(n.delete(o.refId),d.timer&&clearTimeout(d.timer),o.success===!0)d.resolve(o.data);else{const u=typeof o.error?.code=="string"?o.error.code:"INTERNAL_ERROR",m=typeof o.error?.message=="string"?o.error.message:u;d.reject(new p.ChaticAppsError(u,m))}return}i.get(o.type)?.forEach(u=>{try{u(o.data)}catch{}})});return{request:(a,o={},d={})=>new Promise((u,m)=>{if(f){m(new p.ChaticAppsError("DISCONNECTED","The connection to the app was closed."));return}const l=W(),e=d.timeoutMs===void 0?r:d.timeoutMs,s={resolve:u,reject:m,remaining:e,startedAt:Date.now(),timer:null};n.set(l,s),v(l,s),t.send(JSON.stringify({type:a,data:o,refId:l,version:R}))}),onPush:(a,o)=>{let d=i.get(a);return d||i.set(a,d=new Set),d.add(o),()=>d?.delete(o)},close:()=>{if(!f){f=!0,w(),typeof document<"u"&&document.removeEventListener("visibilitychange",h);for(const a of n.values())a.timer&&clearTimeout(a.timer),a.reject(new p.ChaticAppsError("DISCONNECTED","The connection to the app was closed."));n.clear(),i.clear()}}}},O=()=>typeof window<"u"&&!!window.ReactNativeWebView,N=()=>({send:t=>window.ReactNativeWebView?.postMessage(t),listen:t=>{const r=n=>{const i=n.data;typeof i=="string"&&t(i)};return window.addEventListener("message",r),document.addEventListener("message",r),()=>{window.removeEventListener("message",r),document.removeEventListener("message",r)}}}),b={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage"},A=1,_=1e3,U=4e3,C=()=>typeof window<"u"&&window.ChaticSubWebView||null,D=()=>new Promise(t=>{if(typeof document>"u"||document.readyState==="complete"){t(C());return}window.addEventListener("load",()=>t(C()),{once:!0})}),j=t=>{let r,n;try{t instanceof Error?(r=t.message||t.name,n=typeof t.stack=="string"?t.stack:void 0):typeof t=="string"?r=t:r=`A non-Error value was thrown: ${Object.prototype.toString.call(t)}`}catch{r="An error that could not be read was thrown"}return{message:(r||"Unknown error").slice(0,_),...n?{stack:n.slice(0,U)}:{}}},E=t=>new p.ChaticAppsError("NOT_SUPPORTED",`${t} is not available here: an older app, or not granted.`),T=t=>Promise.reject(new p.ChaticAppsError("NOT_IN_APP",`${t} needs the app; this page is in a browser.`)),I=(t={})=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new p.ChaticAppsError("INVALID","link() takes an object of query params, such as { level: 3 }.");const r=new URLSearchParams;for(const[i,f]of Object.entries(t))r.append(i,String(f));const n=r.toString();return n?`?${n}`:""},k=t=>typeof location>"u"?`/${t}`:`${location.origin}/${t}`;let y=null;const q=(t={})=>(y||(y=(O()?G(N(),t):Promise.resolve(B())).catch(r=>{throw y=null,r})),y),G=async(t,r={})=>{const n=M(t,r.timeoutMs);try{const i=await L(n,!0);return $(n,i,r)}catch(i){throw n.close(),i}},L=async(t,r)=>{const n=await t.request("WebAppReady",{}),i=n.subWebView??(r?await D():null);if(i&&i.protocolVersion!==A)throw new p.ChaticAppsError("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(i.protocolVersion)}; this library speaks ${A}.`);return{supported:new Set(Array.isArray(n.supportedWebMessages)?n.supportedWebMessages:[]),context:i}},$=(t,r,n)=>{let i=null,f=null;const v=new Set,h=[],w=e=>r.supported.has(b[e]),a=(e,s,c)=>w(e)?t.request(b[e],s,c===void 0?{}:{timeoutMs:c}):Promise.reject(E(e)),o=(e,s)=>w("storage")?t.request(e,s):Promise.reject(E("storage")),d=e=>v.forEach(s=>{try{s(e)}catch(c){l.reportError(c)}}),u=()=>{w("back")&&t.request(b.back,{canGoBack:!!i}).catch(()=>{}),w("closeGuard")&&t.request(b.closeGuard,{enabled:!!f}).catch(()=>{})},m=e=>{if(!e.persisted){u();return}L(t,!1).then(s=>{const c=r.context;r.supported=s.supported,s.context&&(r.context=s.context),u();const g=r.context;g&&(g.theme!==c?.theme||g.locale!==c?.locale)&&d(g)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",m),h.push(()=>window.removeEventListener("pageshow",m))),h.push(t.onPush("OnBackPressed",()=>{try{i?.()}catch(e){l.reportError(e)}})),h.push(t.onPush("OnSubWebViewCloseRequested",e=>{const s=f;if(!s)return;const c=e?.trigger??"control";Promise.resolve().then(()=>s(c)).then(g=>g?l.finish():void 0).catch(g=>l.reportError(g))})),h.push(t.onPush("OnSubWebViewContextChanged",e=>{r.context&&(r.context={...r.context,...e},d(r.context))}));const l={inApp:!0,get context(){return r.context},supports:w,finish:e=>a("finish",e===void 0?{}:{result:e}).then(()=>{}),setTitle:e=>a("title",{title:e}).then(()=>{}),haptic:e=>{w("haptic")&&t.request(b.haptic,{kind:e}).catch(()=>{})},copy:e=>a("clipboard",{text:e}).then(()=>{}),openUrl:e=>a("openUrl",{url:e}).then(()=>{}),share:e=>a("share",e,null).then(s=>s?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>a("userKey").then(e=>e.key),reportError:e=>w("errorReport")?t.request(b.errorReport,j(e)).then(s=>!!s?.recorded).catch(()=>!1):Promise.resolve(!1),storage:p.storageOver({get:e=>o("GetSubWebViewStorage",{keys:e}),set:e=>o("SetSubWebViewStorage",{entries:e}),remove:e=>o("RemoveSubWebViewStorage",{keys:e}),clear:()=>o("ClearSubWebViewStorage",{}),info:()=>o("GetSubWebViewStorageInfo",{})}),onBack:e=>{i=e,u()},onCloseRequest:e=>{f=e,u()},onContextChange:e=>(v.add(e),()=>v.delete(e)),link:e=>{const s=I(e),c=r.context?.appLink;return c?`${c}${s}`:k(s)},disconnect:()=>{h.forEach(e=>e()),t.close(),y=null}};if(n.reportErrors!==!1&&typeof window<"u"){const e=c=>{l.reportError(c.error??c.message)},s=c=>{l.reportError(c.reason)};window.addEventListener("error",e),window.addEventListener("unhandledrejection",s),h.push(()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",s)})}return l},B=()=>{const t=r=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(r):Promise.reject(E("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>T("Finishing the view"),setTitle:async r=>{typeof document<"u"&&(document.title=r)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:t,openUrl:async r=>{typeof window<"u"&&window.open(r,"_blank","noopener,noreferrer")},share:async r=>{const n=[r.message,r.url].filter(Boolean).join(" ");if(!n)throw new p.ChaticAppsError("INVALID","Share a message or a url.");if(typeof navigator<"u"&&navigator.share)try{return await navigator.share(r),"shared"}catch(i){if(i?.name==="AbortError")return"dismissed"}return await t(n),"copied"},getUserKey:()=>T("A user key"),reportError:async r=>(console.error(r),!1),storage:p.browserStorage(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:r=>k(I(r)),disconnect:()=>{y=null}}};exports.ChaticAppsError=p.ChaticAppsError;exports.SDK_BRIDGE_VERSION=R;exports.connect=q;exports.isInApp=O;
|
package/index.d.cts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/** Every code the app itself can fail a call with. */
|
|
2
|
+
export declare type AppErrorCode = 'NOT_FOUND' | 'INTERNAL_ERROR' | 'TOO_LARGE' | 'INVALID' | 'INVALID_KIND' | 'NOT_OPEN' | 'LINK_NOT_ALLOWED' | 'OPEN_URL_FAILED' | 'CLIPBOARD_WRITE_ERROR' | 'SHARE_ERROR' | 'UNAVAILABLE' | 'QUOTA_EXCEEDED';
|
|
3
|
+
|
|
4
|
+
/** What the page can do. `supports` answers from the app's handshake; a browser tab has none. */
|
|
5
|
+
export declare type Capability = 'finish' | 'title' | 'haptic' | 'clipboard' | 'share' | 'openUrl' | 'userKey' | 'back' | 'closeGuard' | 'errorReport' | 'storage';
|
|
6
|
+
|
|
7
|
+
export declare interface ChaticApps {
|
|
8
|
+
/** `true` inside the app; `false` in a browser tab, where the bridge calls fall back or fail. */
|
|
9
|
+
readonly inApp: boolean;
|
|
10
|
+
/** The app's context: view, platform, language, theme, `params`, `appLink`. `null` in a browser. */
|
|
11
|
+
readonly context: ChaticAppsContext | null;
|
|
12
|
+
/** Whether the app answers `capability` for this page: its version and the page's manifest. */
|
|
13
|
+
supports(capability: Capability): boolean;
|
|
14
|
+
/** Closes the view and hands `result` (JSON, at most 16 KiB) to whoever opened it. */
|
|
15
|
+
finish(result?: unknown): Promise<void>;
|
|
16
|
+
/** Puts a title (1–100 characters) in the app's bar; in a browser, the document's title. */
|
|
17
|
+
setTitle(title: string): Promise<void>;
|
|
18
|
+
/** Plays one short haptic. Never fails: a missing haptic costs nothing but the buzz. */
|
|
19
|
+
haptic(kind: HapticKind): void;
|
|
20
|
+
/** Copies text; in a browser, through the browser's clipboard. */
|
|
21
|
+
copy(text: string): Promise<void>;
|
|
22
|
+
/** Opens a web, mail, phone, SMS or store link outside the view. */
|
|
23
|
+
openUrl(url: string): Promise<void>;
|
|
24
|
+
/** Opens the share sheet; in a browser, the Web Share sheet, else copies. Waits for the user. */
|
|
25
|
+
share(content: ShareContent): Promise<ShareOutcome>;
|
|
26
|
+
/** This device's key for this page's origin (64 hex characters). Not an account, not a proof. */
|
|
27
|
+
getUserKey(): Promise<string>;
|
|
28
|
+
/**
|
|
29
|
+
* Writes an error to the app's log under this page's origin. `false` when it was not recorded. An
|
|
30
|
+
* `Error` sends its message and stack, a string itself, anything else only its type: a rejected
|
|
31
|
+
* value can be the user's own data, which must not reach a log.
|
|
32
|
+
*/
|
|
33
|
+
reportError(error: unknown): Promise<boolean>;
|
|
34
|
+
/**
|
|
35
|
+
* This page's own storage, on the device, apart from every other page's. In a browser tab, the
|
|
36
|
+
* browser's `localStorage` under the same limits.
|
|
37
|
+
*/
|
|
38
|
+
readonly storage: ChaticAppsStorage;
|
|
39
|
+
/**
|
|
40
|
+
* Takes Android's back button while `handler` is set: each press calls it, and nothing else
|
|
41
|
+
* happens. `null` gives back to the app.
|
|
42
|
+
*/
|
|
43
|
+
onBack(handler: (() => void) | null): void;
|
|
44
|
+
/**
|
|
45
|
+
* Asks the page before the user closes the view while `handler` is set: it gets what the user did
|
|
46
|
+
* and answers whether to close. A second close within three seconds closes anyway. `null` lets
|
|
47
|
+
* every close through. Use it only for something the user would lose.
|
|
48
|
+
*/
|
|
49
|
+
onCloseRequest(handler: ((trigger: CloseTrigger) => boolean | Promise<boolean>) | null): void;
|
|
50
|
+
/** Hears a theme or language change while the page shows; returns the function that stops it. */
|
|
51
|
+
onContextChange(listener: (context: ChaticAppsContext) => void): () => void;
|
|
52
|
+
/**
|
|
53
|
+
* A link that opens this page in the app with `params` as its query:
|
|
54
|
+
* `https://app.chatic.io/apps/<appId>?level=3`. The page is always opened at its root, so read what
|
|
55
|
+
* a link carries from `location.search`. In a browser, or an app before `appLink`, this page's own
|
|
56
|
+
* root with the same query instead.
|
|
57
|
+
*/
|
|
58
|
+
link(params?: LinkParams): string;
|
|
59
|
+
/** Stops listening to the app. Pending calls fail with `DISCONNECTED`; the next `connect()` starts afresh. */
|
|
60
|
+
disconnect(): void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What the app tells the page about where it runs. A snapshot; changes arrive through `onContextChange`. */
|
|
64
|
+
export declare type ChaticAppsContext = {
|
|
65
|
+
/** The protocol major the app speaks. */
|
|
66
|
+
protocolVersion: 1;
|
|
67
|
+
viewId: string;
|
|
68
|
+
platform: 'ios' | 'android';
|
|
69
|
+
/** The app's own version. */
|
|
70
|
+
appVersion: string;
|
|
71
|
+
/** The language the user chose in the app (`ko`, `en`). */
|
|
72
|
+
locale: string;
|
|
73
|
+
/** The app's theme, which can differ from the OS's. */
|
|
74
|
+
theme: Theme;
|
|
75
|
+
/** What whoever opened the page passed it; `{}` when nothing. */
|
|
76
|
+
params: {
|
|
77
|
+
[key: string]: unknown;
|
|
78
|
+
};
|
|
79
|
+
/** The link that opens this page in the app; absent from older apps. */
|
|
80
|
+
appLink?: string;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/** Every failure this library reports. Branch on `code`; `message` is English for a developer. */
|
|
84
|
+
export declare class ChaticAppsError extends Error {
|
|
85
|
+
readonly code: ChaticAppsErrorCode;
|
|
86
|
+
constructor(code: ChaticAppsErrorCode, message: string);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* What a call can fail with. The app's codes, plus five of this library's own:
|
|
91
|
+
* - `NOT_SUPPORTED` — this app cannot do it: an app built before it, a permission the page's manifest
|
|
92
|
+
* does not hold, or — in a browser — no clipboard;
|
|
93
|
+
* - `TIMEOUT` — the app did not answer in time;
|
|
94
|
+
* - `UNSUPPORTED_PROTOCOL` — the app speaks a protocol major this library does not know;
|
|
95
|
+
* - `NOT_IN_APP` — the call needs the app and the page is in a browser tab;
|
|
96
|
+
* - `DISCONNECTED` — the connection was closed with `disconnect()` before the app answered.
|
|
97
|
+
* A code this list does not name is still a failure of that call and nothing more.
|
|
98
|
+
*/
|
|
99
|
+
export declare type ChaticAppsErrorCode = AppErrorCode | 'NOT_SUPPORTED' | 'TIMEOUT' | 'UNSUPPORTED_PROTOCOL' | 'NOT_IN_APP' | 'DISCONNECTED' | (string & {});
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* This page's own storage in the app: kept on the device for the page's origin, shared by no other
|
|
103
|
+
* page, and kept when the user signs out. Values are JSON. At most 1,048,576 characters in all — keys
|
|
104
|
+
* plus values serialized — and at most 64 KiB in one call, the app's message limit.
|
|
105
|
+
*/
|
|
106
|
+
export declare interface ChaticAppsStorage {
|
|
107
|
+
/** The value stored under `key`, or `undefined` when there is none. */
|
|
108
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
109
|
+
/** The values stored under `keys`; a key with nothing stored is left out. */
|
|
110
|
+
getMany(keys: string[]): Promise<{
|
|
111
|
+
[key: string]: unknown;
|
|
112
|
+
}>;
|
|
113
|
+
/** Stores `value` under `key`. Fails with `QUOTA_EXCEEDED` past the page's limit. */
|
|
114
|
+
set(key: string, value: unknown): Promise<void>;
|
|
115
|
+
/** Stores every entry, or — when one is refused, or together they go past the limit — none. */
|
|
116
|
+
setMany(entries: {
|
|
117
|
+
[key: string]: unknown;
|
|
118
|
+
}): Promise<void>;
|
|
119
|
+
/** Removes one key or several; a key with nothing stored is no failure. */
|
|
120
|
+
remove(keys: string | string[]): Promise<void>;
|
|
121
|
+
/** Every key this page has stored. */
|
|
122
|
+
keys(): Promise<string[]>;
|
|
123
|
+
/** Removes everything this page has stored. */
|
|
124
|
+
clear(): Promise<void>;
|
|
125
|
+
/** What the page's storage holds and may hold, in characters. */
|
|
126
|
+
usage(): Promise<StorageUsage>;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** What the user did to ask for the close: the app's close control, or Android back. */
|
|
130
|
+
export declare type CloseTrigger = 'control' | 'back';
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Connects to the app, or — in a browser tab — to nothing, returning the same interface with browser
|
|
134
|
+
* fallbacks, so one page runs in both. In the app it shakes hands first: what the app answers, and the
|
|
135
|
+
* context, come from that reply.
|
|
136
|
+
*
|
|
137
|
+
* One connection per page: a second call returns the first one's result, so two parts of a page — or a
|
|
138
|
+
* component mounted twice — cannot undo each other's back handler or report every error twice.
|
|
139
|
+
*
|
|
140
|
+
* Rejects with `UNSUPPORTED_PROTOCOL` when the app speaks a protocol major this library does not know
|
|
141
|
+
* (update the library, and tell the user the page needs updating), and with `TIMEOUT` when the app
|
|
142
|
+
* does not answer — as for a page the view navigated to from the one it opened.
|
|
143
|
+
*/
|
|
144
|
+
export declare const connect: (options?: ConnectOptions) => Promise<ChaticApps>;
|
|
145
|
+
|
|
146
|
+
export declare interface ConnectOptions {
|
|
147
|
+
/** Default wait for a reply, in milliseconds, while the page is visible. 10 seconds. */
|
|
148
|
+
timeoutMs?: number;
|
|
149
|
+
/** Report uncaught errors and unhandled rejections to the app's log. On by default. */
|
|
150
|
+
reportErrors?: boolean;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The feel of a haptic: a tick, a tap, or the outcome of something the user did. */
|
|
154
|
+
export declare type HapticKind = 'selection' | 'impact' | 'success' | 'warning' | 'error';
|
|
155
|
+
|
|
156
|
+
/** Whether this page runs inside the app's WebView, which defines this before the page's scripts. */
|
|
157
|
+
export declare const isInApp: () => boolean;
|
|
158
|
+
|
|
159
|
+
/** What a link hands the page it opens, as its query: `{ level: 3 }` opens the page at `/?level=3`. */
|
|
160
|
+
export declare type LinkParams = Readonly<Record<string, string | number | boolean>>;
|
|
161
|
+
|
|
162
|
+
/** The bridge version this library is written against, sent as each request's `version`. */
|
|
163
|
+
export declare const SDK_BRIDGE_VERSION = "2.19.0";
|
|
164
|
+
|
|
165
|
+
export declare interface ShareContent {
|
|
166
|
+
title?: string;
|
|
167
|
+
message?: string;
|
|
168
|
+
/** `http(s)` only. Share `apps.link(params)` so a tap opens the page in the app. */
|
|
169
|
+
url?: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* How a share went. `copied` is this library's fallback in a browser with no share sheet: the link
|
|
174
|
+
* or message went to the clipboard instead. On Android the app answers `shared` as soon as the chooser
|
|
175
|
+
* opens, whatever the user then does; only iOS reports `dismissed`.
|
|
176
|
+
*/
|
|
177
|
+
export declare type ShareOutcome = 'shared' | 'dismissed' | 'copied';
|
|
178
|
+
|
|
179
|
+
/** What the page's storage holds and may hold, in characters: keys plus values serialized. */
|
|
180
|
+
export declare type StorageUsage = {
|
|
181
|
+
used: number;
|
|
182
|
+
limit: number;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* The shapes a page sees, declared here rather than imported: the app's message definitions are a
|
|
187
|
+
* private package, and a published library cannot point at it. `types.contract.test.ts` holds each one
|
|
188
|
+
* equal to its counterpart there, so the two cannot drift apart unnoticed.
|
|
189
|
+
*/
|
|
190
|
+
export declare type Theme = 'light' | 'dark';
|
|
191
|
+
|
|
192
|
+
export { }
|