@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/AGENTS.md +56 -0
- package/GUIDE.md +219 -0
- package/README.md +51 -53
- package/chatic-apps-sdk.global.js +1 -1
- package/index.cjs +1 -1
- package/index.d.cts +36 -3
- package/index.d.ts +36 -3
- package/index.js +196 -153
- package/mock.cjs +1 -1
- package/mock.d.cts +22 -0
- package/mock.d.ts +22 -0
- package/mock.js +112 -91
- package/package.json +2 -2
package/AGENTS.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Rules for an AI assistant writing a Chatic app
|
|
2
|
+
|
|
3
|
+
You are writing a web page that opens inside the DoU app, at `https://<name>.apps.chatic.io`, using
|
|
4
|
+
`@lemoncloud/chatic-apps-sdk`. Follow these rules. `GUIDE.md` in this package says how to set the
|
|
5
|
+
project up and what the bundle looks like; `README.md` is the reference for every call, limit and error
|
|
6
|
+
code. Read the part you need before you write code that depends on it.
|
|
7
|
+
|
|
8
|
+
## The project
|
|
9
|
+
|
|
10
|
+
1. **Static files only.** The output is a folder with `index.html` at its top and
|
|
11
|
+
`.well-known/chatic-app.json` beside it. No server code, no server-side rendering, no server routing.
|
|
12
|
+
With Vite, put the manifest at `public/.well-known/chatic-app.json`.
|
|
13
|
+
2. **The page is always entered at `/`.** Do not route on the path and do not set a `base`. A shared
|
|
14
|
+
link carries its data in the query: read it from `location.search` when the page starts.
|
|
15
|
+
3. **Install the mock in development only**, before `connect()`:
|
|
16
|
+
`if (import.meta.env.DEV) installChaticAppsMock({ permissions: [...] })`, imported from
|
|
17
|
+
`@lemoncloud/chatic-apps-sdk/mock`.
|
|
18
|
+
|
|
19
|
+
## The calls
|
|
20
|
+
|
|
21
|
+
4. Use `@lemoncloud/chatic-apps-sdk`. Call `await connect()` once at start, inside `try/catch`.
|
|
22
|
+
5. Check `apps.inApp` and `apps.supports(capability)` before offering an app feature; never compare
|
|
23
|
+
version numbers.
|
|
24
|
+
6. Every call can throw `ChaticAppsError`; branch on `error.code` only, never on `error.message`.
|
|
25
|
+
7. Take the theme and language from `apps.context` and `apps.onContextChange`, not from the OS.
|
|
26
|
+
8. Share links built with `apps.link({ ... })`, never the page's own address.
|
|
27
|
+
9. Keep the page's state in `apps.storage` as it changes, and at the latest on `visibilitychange` to
|
|
28
|
+
`hidden`; never in `localStorage`. What must follow the user to another phone goes on your own server
|
|
29
|
+
under `apps.getUserKey()`.
|
|
30
|
+
10. For screens and dialogs inside the page, keep a stack: while it holds more than one screen,
|
|
31
|
+
`apps.onBack(back)`; at the root, `apps.onBack(null)`, so Android back closes the page. iOS has no
|
|
32
|
+
back key, so draw a back button that calls the same `back()` whenever there is a screen to go back to.
|
|
33
|
+
Keep the stack in memory: a router that pushes browser history (hash routes, `pushState`) makes
|
|
34
|
+
Android back at the root walk that history instead of closing the page.
|
|
35
|
+
11. Use `apps.onCloseRequest` only to protect unsaved work; return `true` to close.
|
|
36
|
+
12. For the camera or microphone, call `apps.permissions.request(kind)` when the user reaches for the
|
|
37
|
+
feature, never at start, then `getUserMedia`. No manifest permission is needed. Do not time the
|
|
38
|
+
request out, and send `'blocked'` to `apps.openSettings()`. Treat the request's answer, not
|
|
39
|
+
`query`'s, as the truth: on Android `query` can read `'prompt'` for a blocked permission.
|
|
40
|
+
|
|
41
|
+
## The page
|
|
42
|
+
|
|
43
|
+
13. No `window.opener`, no popup logins, no file downloads.
|
|
44
|
+
14. Never put the user's data in errors or in `reportError`.
|
|
45
|
+
15. List the permissions the page needs (`clipboard`, `share`, `openUrl`, `userKey`) in
|
|
46
|
+
`/.well-known/chatic-app.json` — and nothing it does not use. A call that needs one fails with
|
|
47
|
+
`NOT_SUPPORTED` without it.
|
|
48
|
+
16. Do not draw for the safe area: the page already lies inside it on every edge.
|
|
49
|
+
17. The page has no title bar unless the manifest sets `"display": "standard"`: draw your own header and
|
|
50
|
+
title, and keep the top-right corner clear, where the app's close button floats.
|
|
51
|
+
|
|
52
|
+
## Before you say it is done
|
|
53
|
+
|
|
54
|
+
Run the build, and check that `dist/index.html` and `dist/.well-known/chatic-app.json` exist. Say what
|
|
55
|
+
you could not check: a browser with the mock proves a page's logic and nothing about a phone — layout,
|
|
56
|
+
the keyboard and real haptics need the app.
|
package/GUIDE.md
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# Building a page with chatic-apps-sdk
|
|
2
|
+
|
|
3
|
+
A Chatic app is a web page that opens inside the DoU app, over everything else, at
|
|
4
|
+
`https://<name>.apps.chatic.io`. You build it like any web page, and `@lemoncloud/chatic-apps-sdk`
|
|
5
|
+
connects it to the app: closing, the title, haptics, sharing, saving data on the device, and more.
|
|
6
|
+
This guide is how to set a project up and what comes out of it. The library's calls, limits and error
|
|
7
|
+
codes are in the package `README.md`; this guide does not repeat them.
|
|
8
|
+
|
|
9
|
+
## What you are building
|
|
10
|
+
|
|
11
|
+
- **Static files.** The app loads your page from a web address like any browser. There is no server
|
|
12
|
+
of yours to run for the page itself, and no server-side rendering.
|
|
13
|
+
- **One page, entered at the root.** The app always opens `/`. A link carries data in its query
|
|
14
|
+
(`/?level=3`), never in a path, so a page does not route on the path.
|
|
15
|
+
- **In the phone's own web view.** The page runs in WKWebView on iOS and the Android System WebView
|
|
16
|
+
on Android, so it can use what those engines support. Check the oldest phones you mean to support.
|
|
17
|
+
- **Also in a browser, while you build.** The library falls back to what a browser can do, and ships a
|
|
18
|
+
stand-in for the app, so you can write and try the page without a phone.
|
|
19
|
+
|
|
20
|
+
## Choose a toolchain
|
|
21
|
+
|
|
22
|
+
The library has no runtime dependencies and no opinion about the rest, so use what you know. Three
|
|
23
|
+
shapes work, from least to most tooling:
|
|
24
|
+
|
|
25
|
+
| Shape | Use it when | The library comes from |
|
|
26
|
+
| ------------------------------- | --------------------------------------------- | ---------------------------------------------------- |
|
|
27
|
+
| One `index.html`, no build | A small page, a prototype | A `<script>` tag that defines `window.ChaticAppsSDK` |
|
|
28
|
+
| Vite and plain TypeScript or JS | A page of its own with a few screens of logic | `npm install` |
|
|
29
|
+
| Vite and React, Vue or Svelte | You already build interfaces in one of these | `npm install` |
|
|
30
|
+
|
|
31
|
+
Anything that ends in static files is fine, with these limits:
|
|
32
|
+
|
|
33
|
+
- **No server rendering and no server routing.** A framework's static or single-page mode, not its
|
|
34
|
+
server mode. Next.js needs `output: 'export'`, Nuxt needs `ssr: false` or `nuxt generate`, and
|
|
35
|
+
SvelteKit needs the static adapter in single-page mode.
|
|
36
|
+
- **Do not depend on a path.** A client-side router must work with the page entered at `/`, and must
|
|
37
|
+
not be needed to reach a shared link: put what a link carries in the query.
|
|
38
|
+
- **Do not depend on `window.opener`, popups or file downloads.** A popup opens in the same view and
|
|
39
|
+
replaces the page, so a login that answers through `window.opener` cannot work, and a download is not
|
|
40
|
+
handled on iOS; the package `README.md` says what to do instead.
|
|
41
|
+
|
|
42
|
+
Vite is the shortest road, and the rest of this guide uses it.
|
|
43
|
+
|
|
44
|
+
## Set up a project
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
npm create vite@latest quiz -- --template vanilla-ts
|
|
48
|
+
cd quiz
|
|
49
|
+
npm install @lemoncloud/chatic-apps-sdk
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Pick `react-ts`, `vue-ts` or `svelte-ts` for the template instead if you want one; nothing below
|
|
53
|
+
depends on it. Replace `src/main.ts` with a page that connects:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { connect, ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
|
|
57
|
+
import { installChaticAppsMock } from '@lemoncloud/chatic-apps-sdk/mock';
|
|
58
|
+
|
|
59
|
+
// A stand-in for the app in the browser, in development only. Vite removes a branch that is always
|
|
60
|
+
// false, so it is not in the production bundle. The controller lets you play the user's side.
|
|
61
|
+
if (import.meta.env.DEV) {
|
|
62
|
+
const app = installChaticAppsMock({ permissions: ['share', 'userKey'] });
|
|
63
|
+
Object.assign(window, { app }); // then `app.pressBack()` in the browser console
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function start() {
|
|
67
|
+
try {
|
|
68
|
+
const apps = await connect();
|
|
69
|
+
document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
|
|
70
|
+
apps.onContextChange(context => (document.documentElement.dataset.theme = context.theme));
|
|
71
|
+
} catch (error) {
|
|
72
|
+
// `UNSUPPORTED_PROTOCOL` means the app is newer than this library: update the library.
|
|
73
|
+
const needsUpdate = error instanceof ChaticAppsError && error.code === 'UNSUPPORTED_PROTOCOL';
|
|
74
|
+
document.body.textContent = needsUpdate ? 'This page needs an update.' : 'This page could not start.';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
void start();
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Then:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
npm run dev # the page in your browser, with the stand-in for the app
|
|
85
|
+
npm run build # the bundle, in dist/
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
With React, Vue or Svelte, put the same lines where the application starts, before it renders.
|
|
89
|
+
|
|
90
|
+
### Developing in a browser
|
|
91
|
+
|
|
92
|
+
`installChaticAppsMock` turns the tab into a fake app: it answers as the app does, logs every call, and
|
|
93
|
+
lets you play the user's side through the controller it returns — the Android back button, a close
|
|
94
|
+
request, a theme change (the example above puts it on `window`, so the browser console can reach it). It grants only the permissions you list, as the app grants only what the page's manifest holds.
|
|
95
|
+
It proves the page's logic and nothing about a phone: layout, the keyboard, the safe area and real
|
|
96
|
+
haptics need the app.
|
|
97
|
+
|
|
98
|
+
## The bundle
|
|
99
|
+
|
|
100
|
+
What you hand over is a folder of static files. With Vite, that is `dist/`:
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
dist/
|
|
104
|
+
├── index.html
|
|
105
|
+
├── assets/
|
|
106
|
+
│ ├── index-3fa1c9.js
|
|
107
|
+
│ └── index-81b2d0.css
|
|
108
|
+
└── .well-known/
|
|
109
|
+
└── chatic-app.json
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
- **`index.html` is at the top of the folder.** It is what `/` serves.
|
|
113
|
+
- **Assets are named by root-relative address** (`/assets/…`), which Vite does by default. The page is
|
|
114
|
+
always served from the root of its own address, so do not set a `base` path.
|
|
115
|
+
- **`.well-known/chatic-app.json` is the page's manifest.** The app reads it before it shows the page.
|
|
116
|
+
In Vite, put the file at `public/.well-known/chatic-app.json` and the build copies it as it is.
|
|
117
|
+
- **Nothing else is needed**: no server code, no `package.json`, no source files. Without a build, the
|
|
118
|
+
same layout holds: `index.html` and a `.well-known/chatic-app.json` beside it.
|
|
119
|
+
|
|
120
|
+
The manifest names the page and asks for what it needs:
|
|
121
|
+
|
|
122
|
+
```json
|
|
123
|
+
{
|
|
124
|
+
"manifestVersion": 1,
|
|
125
|
+
"name": "Quiz",
|
|
126
|
+
"permissions": ["share", "userKey"],
|
|
127
|
+
"orientation": "portrait"
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
A page has no bar by default: a small close button floats in the top-right corner, always, and the page
|
|
132
|
+
draws its own header. Add `"display": "standard"` to get the app's bar with the page's title and a
|
|
133
|
+
close button instead.
|
|
134
|
+
|
|
135
|
+
`manifestVersion` must be `1`; the app ignores a manifest it cannot read. Ask only for the permissions
|
|
136
|
+
the page uses — `clipboard`, `share`, `openUrl`, `userKey` — and see the
|
|
137
|
+
package `README.md` for what each one unlocks and for `display` and `orientation`. Without a manifest a
|
|
138
|
+
page still runs; it gets everything but those four.
|
|
139
|
+
|
|
140
|
+
## How the page behaves in the app
|
|
141
|
+
|
|
142
|
+
These are the facts that most often surprise a page written first for a browser. The package `README.md`
|
|
143
|
+
has the detail on each.
|
|
144
|
+
|
|
145
|
+
- **The app can close the page at any time.** Save as you go, and when `document` turns `hidden`.
|
|
146
|
+
Keep the page's own data in `apps.storage`, not `localStorage`, which goes when the system clears
|
|
147
|
+
website data. What must follow the user to another phone goes on your own server, under
|
|
148
|
+
`apps.getUserKey()`.
|
|
149
|
+
- **The page lies inside the safe area on every edge.** There are no insets to handle.
|
|
150
|
+
- **Dark mode follows the app's theme**, from `apps.context.theme`, not the phone's.
|
|
151
|
+
- **Share `apps.link({ … })`**, not the page's address, and read what a link carries from
|
|
152
|
+
`location.search` when the page starts.
|
|
153
|
+
- **There is no title bar** unless the manifest asks for one, so the page draws its own header and title.
|
|
154
|
+
See [Screens and Back](#screens-and-back).
|
|
155
|
+
- **Android back** is yours only while you set `apps.onBack(handler)`; otherwise the app decides.
|
|
156
|
+
- **Errors**: every call can throw `ChaticAppsError`; branch on its `code`, never its `message`.
|
|
157
|
+
|
|
158
|
+
## Screens and Back
|
|
159
|
+
|
|
160
|
+
A page with more than one screen — a menu, a game, a settings page — needs its own way back. There is
|
|
161
|
+
no bar and no back arrow to lean on: the only control the app gives is the small close button at the
|
|
162
|
+
top-right corner, which leaves the page. Android has a back key; iOS has none. So the page keeps a
|
|
163
|
+
stack of its screens, draws its own back button, and takes the Android back key only while there is a
|
|
164
|
+
screen to go back to:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
const screens = ['home'];
|
|
168
|
+
|
|
169
|
+
// Take Android back while a screen is stacked; give it back at the root, where the app closes the page.
|
|
170
|
+
const sync = () => apps.onBack(screens.length > 1 ? back : null);
|
|
171
|
+
|
|
172
|
+
function open(name: string) {
|
|
173
|
+
screens.push(name);
|
|
174
|
+
sync();
|
|
175
|
+
render();
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function back() {
|
|
179
|
+
if (screens.length > 1) screens.pop();
|
|
180
|
+
sync();
|
|
181
|
+
render();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
sync();
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Draw a back button in your header whenever `screens.length > 1` and have it call `back()`; at the root
|
|
188
|
+
draw none, since the close button is already there. In React, Vue or Svelte keep `screens` in state and
|
|
189
|
+
call `apps.onBack` from an effect that runs when its length changes. The same pattern closes a dialog:
|
|
190
|
+
treat an open dialog as a screen.
|
|
191
|
+
|
|
192
|
+
Three things to leave alone: do not set a handler at the root, so Android back still closes the page;
|
|
193
|
+
do not use `onCloseRequest` for navigation — it is for unsaved work; and keep the screens in memory, not
|
|
194
|
+
in the browser's history. A router that pushes entries (hash routes, `pushState`) gives the page a history,
|
|
195
|
+
and with a history Android back at the root walks it instead of closing the page. On iOS the edge swipe
|
|
196
|
+
only walks that history, so an in-memory stack needs the back button above either way.
|
|
197
|
+
|
|
198
|
+
Keep the top-right corner of every screen clear of your own controls: the close button floats there.
|
|
199
|
+
|
|
200
|
+
## For an AI assistant in your project
|
|
201
|
+
|
|
202
|
+
The package ships `AGENTS.md`: rules for an assistant writing a Chatic app. Assistants read an
|
|
203
|
+
`AGENTS.md` at the top of the project, not one inside `node_modules`, so copy it there, or point your
|
|
204
|
+
assistant at `node_modules/@lemoncloud/chatic-apps-sdk/AGENTS.md`.
|
|
205
|
+
|
|
206
|
+
## Before you hand it over
|
|
207
|
+
|
|
208
|
+
- [ ] `npm run build` produces `dist/` with `index.html` and `.well-known/chatic-app.json` at its top.
|
|
209
|
+
- [ ] Opened from a plain file server, the built page works at the root, with no path in the address.
|
|
210
|
+
- [ ] The page works in a browser with no app (`apps.inApp` is `false`) and with the stand-in.
|
|
211
|
+
- [ ] Every permission in the manifest is used, and every call that needs one is guarded with
|
|
212
|
+
`apps.supports(…)` or handles `NOT_SUPPORTED`.
|
|
213
|
+
- [ ] State is saved as the user goes, not only at a button.
|
|
214
|
+
- [ ] No `window.opener`, popup login, file download or server-side rendering.
|
|
215
|
+
- [ ] No user data in errors, in `reportError` or in the page's own logs.
|
|
216
|
+
|
|
217
|
+
## Deploying
|
|
218
|
+
|
|
219
|
+
How a page is submitted, reviewed and deployed to its address is not part of this guide yet.
|
package/README.md
CHANGED
|
@@ -2,13 +2,15 @@
|
|
|
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
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,
|
|
5
|
+
title the app's bar (when the page asks for one), play a haptic, share, copy, open a link outside, keep its own data on the device,
|
|
6
6
|
get a key to keep the user's data under on a server, take Android's back button, and ask before the
|
|
7
7
|
user closes it. Users reach it in the app only — a link to it never opens it in a browser — but the
|
|
8
8
|
same page runs in a plain browser tab too while you build it, where the library falls back to what the
|
|
9
9
|
browser can do.
|
|
10
10
|
|
|
11
|
-
Published as `@lemoncloud/chatic-apps-sdk`. No runtime dependencies.
|
|
11
|
+
Published as `@lemoncloud/chatic-apps-sdk`. No runtime dependencies. `GUIDE.md` in the package says how
|
|
12
|
+
to set up a project and what the bundle looks like; `AGENTS.md` holds the rules for an AI assistant
|
|
13
|
+
writing a page.
|
|
12
14
|
|
|
13
15
|
## Install
|
|
14
16
|
|
|
@@ -20,7 +22,7 @@ Or, with no bundler, one script that defines `window.ChaticAppsSDK` (pin the ver
|
|
|
20
22
|
is not in this file):
|
|
21
23
|
|
|
22
24
|
```html
|
|
23
|
-
<script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.
|
|
25
|
+
<script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.2.0/chatic-apps-sdk.global.js"></script>
|
|
24
26
|
```
|
|
25
27
|
|
|
26
28
|
## Start
|
|
@@ -30,7 +32,6 @@ import { connect, ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
|
|
|
30
32
|
|
|
31
33
|
try {
|
|
32
34
|
const apps = await connect();
|
|
33
|
-
if (apps.inApp) await apps.setTitle('Quiz');
|
|
34
35
|
document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
|
|
35
36
|
} catch (error) {
|
|
36
37
|
// `UNSUPPORTED_PROTOCOL`: the app is newer than this library — update the library, and tell the
|
|
@@ -54,7 +55,7 @@ stand-ins; deployed to your `apps.chatic.io` address, it runs in the app.
|
|
|
54
55
|
<meta charset="utf-8" />
|
|
55
56
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
|
56
57
|
<title>Quiz</title>
|
|
57
|
-
<script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.
|
|
58
|
+
<script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.2.0/chatic-apps-sdk.global.js"></script>
|
|
58
59
|
</head>
|
|
59
60
|
<body>
|
|
60
61
|
<h1 id="score">0</h1>
|
|
@@ -90,20 +91,21 @@ stand-ins; deployed to your `apps.chatic.io` address, it runs in the app.
|
|
|
90
91
|
|
|
91
92
|
## What a page can do
|
|
92
93
|
|
|
93
|
-
| Call
|
|
94
|
-
|
|
|
95
|
-
| `finish(result?)`
|
|
96
|
-
| `setTitle(title)`
|
|
97
|
-
| `haptic(kind)`
|
|
98
|
-
| `onBack(handler \| null)`
|
|
99
|
-
| `onCloseRequest(handler \| null)`
|
|
100
|
-
| `reportError(error)`
|
|
101
|
-
| `copy(text)`
|
|
102
|
-
| `share({ title, message, url })`
|
|
103
|
-
| `openUrl(url)`
|
|
104
|
-
| `getUserKey()`
|
|
105
|
-
| `link(params?)`
|
|
106
|
-
| `storage.get(key)`, `.set(key, value)`, …
|
|
94
|
+
| Call | In the app | In a browser | Needs permission |
|
|
95
|
+
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------- | ---------------- |
|
|
96
|
+
| `finish(result?)` | Closes the view; `result` (JSON, ≤ 16 KiB) goes back to the opener | `NOT_IN_APP` | — |
|
|
97
|
+
| `setTitle(title)` | The app's bar shows it, if the page asked for the bar (1–100 characters) | `document.title` | — |
|
|
98
|
+
| `haptic(kind)` | `selection`, `impact`, `success`, `warning`, `error` | a short vibration, if any | — |
|
|
99
|
+
| `onBack(handler \| null)` | Android back calls `handler` and does nothing else | never called | — |
|
|
100
|
+
| `onCloseRequest(handler \| null)` | Asks before the user closes; return `true` to close | never called | — |
|
|
101
|
+
| `reportError(error)` | Into DoU's log, under your origin (20 per page load) | `console.error` | — |
|
|
102
|
+
| `copy(text)` | The clipboard | the browser's clipboard | `clipboard` |
|
|
103
|
+
| `share({ title, message, url })` | The share sheet; waits for the user (see below) | Web Share, else copies (`'copied'`) | `share` |
|
|
104
|
+
| `openUrl(url)` | The browser, mail, phone, SMS or a store | a new tab | `openUrl` |
|
|
105
|
+
| `getUserKey()` | 64 hex characters, the same for this device and site | `NOT_IN_APP` | `userKey` |
|
|
106
|
+
| `link(params?)` | A link that opens this page in the app (see below) | the page's own root | — |
|
|
107
|
+
| `storage.get(key)`, `.set(key, value)`, … | Your page's own storage on the device (see below) | `localStorage`, same limits | — |
|
|
108
|
+
| `permissions.query(kind)`, `.request(kind)`, `openSettings()` | Where the app stands with the OS for `'camera'` or `'microphone'`, and asking it (see below) | the browser's own permission | — |
|
|
107
109
|
|
|
108
110
|
Plus `apps.context` (the app's language, theme, platform and the `params` you were opened with),
|
|
109
111
|
`apps.onContextChange(listener)` for a theme or language change, `apps.supports(capability)`,
|
|
@@ -126,6 +128,16 @@ Plus `apps.context` (the app's language, theme, platform and the `params` you we
|
|
|
126
128
|
write fails with `QUOTA_EXCEEDED` and changes nothing — keys of 1–200 characters (not `__proto__`),
|
|
127
129
|
and at most 64 KiB in one call (`TOO_LARGE`). A value is written in one call, so one value stays
|
|
128
130
|
under 64 KiB; split anything bigger across keys.
|
|
131
|
+
- **`permissions`** is for the camera and the microphone, which a page uses with the browser's own
|
|
132
|
+
`getUserMedia` — the OS asks the user the first time, under DoU's name, so the user's answer is for
|
|
133
|
+
every page, not yours alone. `query(kind)` reports `'granted'`, `'prompt'` (not asked, or refused and
|
|
134
|
+
may be asked again) or `'blocked'` (the OS will not ask again) without showing anything — on Android
|
|
135
|
+
it can read `'prompt'` for one the OS will no longer ask for, so trust what `request` answers;
|
|
136
|
+
`request(kind)` shows the prompt and resolves with the answer; `openSettings()` opens DoU's page in
|
|
137
|
+
the OS settings, the way back for `'blocked'`. Ask when the user reaches for the feature, not at
|
|
138
|
+
start, and do not time `request` out: it waits for the user. A page can skip all this and call
|
|
139
|
+
`getUserMedia`; it then meets the prompt in the middle of the capture. In a browser the same calls
|
|
140
|
+
read and ask the browser's own permission, and `openSettings()` is `NOT_IN_APP`.
|
|
129
141
|
- **Uncaught errors are reported for you.** `connect()` listens for `error` and `unhandledrejection` and
|
|
130
142
|
sends them to DoU's log. An `Error` sends its message and stack, a string itself, anything else only
|
|
131
143
|
its type. Pass `connect({ reportErrors: false })` to turn it off.
|
|
@@ -147,8 +159,9 @@ The four calls marked above need a permission your page asks for in a file on it
|
|
|
147
159
|
|
|
148
160
|
You ask; an administrator grants them when your page is reviewed, and only what was granted is
|
|
149
161
|
deployed. Without the file your page gets everything else but not these four, which then fail with
|
|
150
|
-
`NOT_SUPPORTED`.
|
|
151
|
-
|
|
162
|
+
`NOT_SUPPORTED`. A page has **no bar by default**: a small close button floats in the top-right corner
|
|
163
|
+
(keep it clear) and the page draws its own header. `display: "standard"` asks for the app's bar, with
|
|
164
|
+
the page's title and a close button; `orientation` is `any`, `portrait` or `landscape`. The app reads
|
|
152
165
|
the file before it shows your page, keeps it for the rest of its run, and fetches a fresh copy behind
|
|
153
166
|
each later open: a change to the file takes effect one open later.
|
|
154
167
|
|
|
@@ -168,19 +181,20 @@ try {
|
|
|
168
181
|
}
|
|
169
182
|
```
|
|
170
183
|
|
|
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` |
|
|
181
|
-
| `
|
|
182
|
-
| `
|
|
183
|
-
| `
|
|
184
|
+
| Code | Means |
|
|
185
|
+
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
186
|
+
| `NOT_SUPPORTED` | Not available: an older app, a permission the page does not hold, or no browser clipboard or storage |
|
|
187
|
+
| `NOT_IN_APP` | The call needs the app, and the page is in a browser |
|
|
188
|
+
| `TIMEOUT` | The app did not answer in 10 seconds (time in the background does not count) |
|
|
189
|
+
| `INVALID` | A value is missing, of the wrong type, or too long |
|
|
190
|
+
| `TOO_LARGE` | One call's data is over 65,536 characters |
|
|
191
|
+
| `LINK_NOT_ALLOWED` | The link cannot be opened or shared from a page |
|
|
192
|
+
| `NOT_OPEN` | `finish` after the view has already closed |
|
|
193
|
+
| `UNAVAILABLE` | No device id to make a user key from, the page's storage could not be opened, or the device has no camera or microphone |
|
|
194
|
+
| `SETTINGS_ERROR` | `openSettings()`: the OS would not open the settings |
|
|
195
|
+
| `QUOTA_EXCEEDED` | A storage write would go past 1,048,576 characters; nothing was written |
|
|
196
|
+
| `DISCONNECTED` | The call was waiting when `disconnect()` closed the connection |
|
|
197
|
+
| `UNSUPPORTED_PROTOCOL` | `connect()` only: the app is newer than this library; update it |
|
|
184
198
|
|
|
185
199
|
Treat a code not in this table as that call failing, and nothing more.
|
|
186
200
|
|
|
@@ -248,25 +262,9 @@ logged rather than shown, the user key is not the app's, and it proves nothing a
|
|
|
248
262
|
|
|
249
263
|
## For an AI assistant writing a page
|
|
250
264
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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()`.
|
|
265
|
+
`AGENTS.md` in this package holds the rules for an assistant writing a page: the project, the calls
|
|
266
|
+
and the page. Copy it to the top of your project, where an assistant looks for it, or paste it into the
|
|
267
|
+
prompt along with what the page should do. `GUIDE.md` says how to set the project up.
|
|
270
268
|
|
|
271
269
|
## For maintainers
|
|
272
270
|
|
|
@@ -1 +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})({});
|
|
1
|
+
var ChaticAppsSDK=(function(y){"use strict";class u extends Error{code;constructor(t,r){super(r),this.name="ChaticAppsError",this.code=t}}const R="2.20.0",U=1e4,W=2e3;let q=0;const x=()=>`cas-${Date.now().toString(36)}-${(++q).toString(36)}`,P=()=>typeof document<"u"&&document.visibilityState==="hidden",G=(e,t=U)=>{const r=new Map,o=new Map;let c=!1;const h=(a,s)=>{s.remaining===null||P()||(s.startedAt=Date.now(),s.timer=setTimeout(()=>{r.delete(a),s.reject(new u("TIMEOUT","The app did not answer in time."))},s.remaining))},d=()=>{for(const[a,s]of r)s.remaining!==null&&(P()?(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,W),h(a,s)))};typeof document<"u"&&document.addEventListener("visibilitychange",d);const f=e.listen(a=>{let s;try{s=JSON.parse(a)}catch{return}if(!s||typeof s!="object"||typeof s.type!="string")return;const p=typeof s.refId=="string"?r.get(s.refId):void 0;if(p&&typeof s.refId=="string"){if(r.delete(s.refId),p.timer&&clearTimeout(p.timer),s.success===!0)p.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;p.reject(new u(g,v))}return}o.get(s.type)?.forEach(g=>{try{g(s.data)}catch{}})});return{request:(a,s={},p={})=>new Promise((g,v)=>{if(c){v(new u("DISCONNECTED","The connection to the app was closed."));return}const w=x(),n=p.timeoutMs===void 0?t:p.timeoutMs,i={resolve:g,reject:v,remaining:n,startedAt:Date.now(),timer:null};r.set(w,i),h(w,i),e.send(JSON.stringify({type:a,data:s,refId:w,version:R}))}),onPush:(a,s)=>{let p=o.get(a);return p||o.set(a,p=new Set),p.add(s),()=>p?.delete(s)},close:()=>{if(!c){c=!0,f(),typeof document<"u"&&document.removeEventListener("visibilitychange",d);for(const a of r.values())a.timer&&clearTimeout(a.timer),a.reject(new u("DISCONNECTED","The connection to the app was closed."));r.clear(),o.clear()}}}},T=e=>{try{return JSON.stringify(e)??null}catch{return null}},L=e=>{const t=r=>Object.values(r??{}).every(o=>T(o)!==null)?e.set(r).then(()=>{}):Promise.reject(new u("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}))}},k=1024*1024,$=200,K=64*1024,A=e=>typeof e=="string"&&e.length>=1&&e.length<=$&&e!=="__proto__",B=e=>{const t=()=>e.keys().reduce((o,c)=>o+c.length+(e.read(c)?.length??0),0),r=()=>({used:t(),limit:k});return{get(o){if(!Array.isArray(o)||!o.every(A))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 a=T(f);if(!A(d)||a===null)return{ok:!1,code:"INVALID"};const s=e.read(d);h+=a.length-(s===void 0?-d.length:s.length),c.push([d,a])}return h>k?{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(A)?{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()}}}}},S="chatic-apps.storage:",F=e=>({read:t=>e.getItem(S+t)??void 0,write:(t,r)=>e.setItem(S+t,r),delete:t=>e.removeItem(S+t),keys:()=>{const t=[];for(let r=0;r<e.length;r++){const o=e.key(r);o?.startsWith(S)&&t.push(o.slice(S.length))}return t}}),J=()=>{const e=t=>{let r;try{r=t(B(F(window.localStorage)))}catch(o){return o?.name==="QuotaExceededError"?Promise.reject(new u("QUOTA_EXCEEDED","The browser's own storage is full.")):Promise.reject(new u("NOT_SUPPORTED","This browser refuses local storage."))}return r.ok?Promise.resolve(r.value):Promise.reject(new u(r.code,`The storage refused the call: ${r.code}.`))};return L({get:t=>e(r=>r.get(t)),set:t=>(T({entries:t})?.length??0)>K?Promise.reject(new u("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())})},N=()=>typeof window<"u"&&!!window.ReactNativeWebView,Q=()=>({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",permissions:"RequestSubWebViewPermission"},V=1,H=1e3,X=4e3,C=()=>typeof window<"u"&&window.ChaticSubWebView||null,z=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(C());return}window.addEventListener("load",()=>e(C()),{once:!0})}),Y=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,H),...r?{stack:r.slice(0,X)}:{}}},O=e=>new u("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),I=e=>Promise.reject(new u("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),_=(e={})=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new u("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}`:""},D=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let b=null;const Z=(e={})=>(b||(b=(N()?ee(Q(),e):Promise.resolve(oe())).catch(t=>{throw b=null,t})),b),ee=async(e,t={})=>{const r=G(e,t.timeoutMs);try{const o=await M(r,!0);return te(r,o,t)}catch(o){throw r.close(),o}},M=async(e,t)=>{const r=await e.request("WebAppReady",{}),o=r.subWebView??(t?await z():null);if(o&&o.protocolVersion!==V)throw new u("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(o.protocolVersion)}; this library speaks ${V}.`);return{supported:new Set(Array.isArray(r.supportedWebMessages)?r.supportedWebMessages:[]),context:o}},te=(e,t,r)=>{let o=null,c=null;const h=new Set,d=[],f=n=>t.supported.has(E[n]),a=(n,i,l,m)=>{const j=m??E[n];return t.supported.has(j)?e.request(j,i,l===void 0?{}:{timeoutMs:l}):Promise.reject(O(n))},s=(n,i)=>f("storage")?e.request(n,i):Promise.reject(O("storage")),p=n=>h.forEach(i=>{try{i(n)}catch(l){w.reportError(l)}}),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}M(e,!1).then(i=>{const l=t.context;t.supported=i.supported,i.context&&(t.context=i.context),g();const m=t.context;m&&(m.theme!==l?.theme||m.locale!==l?.locale)&&p(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 i=c;if(!i)return;const l=n?.trigger??"control";Promise.resolve().then(()=>i(l)).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},p(t.context))}));const w={inApp:!0,get context(){return t.context},supports:f,finish:n=>a("finish",n===void 0?{}:{result:n}).then(()=>{}),setTitle:n=>a("title",{title:n}).then(()=>{}),haptic:n=>{f("haptic")&&e.request(E.haptic,{kind:n}).catch(()=>{})},copy:n=>a("clipboard",{text:n}).then(()=>{}),openUrl:n=>a("openUrl",{url:n}).then(()=>{}),share:n=>a("share",n,null).then(i=>i?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>a("userKey").then(n=>n.key),permissions:{query:n=>a("permissions",{kind:n},void 0,"GetSubWebViewPermission").then(i=>i.state),request:n=>a("permissions",{kind:n},null).then(i=>i.state)},openSettings:()=>a("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:n=>f("errorReport")?e.request(E.errorReport,Y(n)).then(i=>!!i?.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 i=_(n),l=t.context?.appLink;return l?`${l}${i}`:D(i)},disconnect:()=>{d.forEach(n=>n()),e.close(),b=null}};if(r.reportErrors!==!1&&typeof window<"u"){const n=l=>{w.reportError(l.error??l.message)},i=l=>{w.reportError(l.reason)};window.addEventListener("error",n),window.addEventListener("unhandledrejection",i),d.push(()=>{window.removeEventListener("error",n),window.removeEventListener("unhandledrejection",i)})}return w},re=()=>{const e=async t=>{try{const r=await navigator.permissions.query({name:t});return r.state==="granted"?"granted":r.state==="denied"?"blocked":"prompt"}catch{return"prompt"}};return{query:e,request:async t=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new u("NOT_SUPPORTED",`This browser cannot capture the ${t}.`);try{return(await navigator.mediaDevices.getUserMedia(t==="camera"?{video:!0}:{audio:!0})).getTracks().forEach(o=>o.stop()),"granted"}catch(r){const o=r?.name;if(o==="NotFoundError"||o==="OverconstrainedError")throw new u("UNAVAILABLE",`This device has no ${t}.`);if(o==="NotReadableError"||o==="SecurityError"||o==="TypeError"||o==="AbortError")throw new u("INTERNAL_ERROR",`The ${t} could not be used: ${o}.`);return await e(t)==="blocked"?"blocked":"prompt"}}}},oe=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(O("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>I("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 u("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:()=>I("A user key"),permissions:re(),openSettings:()=>I("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:J(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>D(_(t)),disconnect:()=>{b=null}}};return y.ChaticAppsError=u,y.SDK_BRIDGE_VERSION=R,y.connect=Z,y.isInApp=N,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
|
package/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./storage-yeS4HWKZ.cjs"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./storage-yeS4HWKZ.cjs"),O="2.20.0",V=1e4,N=2e3;let x=0;const q=()=>`cas-${Date.now().toString(36)}-${(++x).toString(36)}`,T=()=>typeof document<"u"&&document.visibilityState==="hidden",W=(r,t=V)=>{const n=new Map,s=new Map;let f=!1;const v=(a,o)=>{o.remaining===null||T()||(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))},w=()=>{for(const[a,o]of n)o.remaining!==null&&(T()?(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)))};typeof document<"u"&&document.addEventListener("visibilitychange",w);const g=r.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}s.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=q(),e=d.timeoutMs===void 0?t:d.timeoutMs,i={resolve:u,reject:m,remaining:e,startedAt:Date.now(),timer:null};n.set(l,i),v(l,i),r.send(JSON.stringify({type:a,data:o,refId:l,version:O}))}),onPush:(a,o)=>{let d=s.get(a);return d||s.set(a,d=new Set),d.add(o),()=>d?.delete(o)},close:()=>{if(!f){f=!0,g(),typeof document<"u"&&document.removeEventListener("visibilitychange",w);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(),s.clear()}}}},I=()=>typeof window<"u"&&!!window.ReactNativeWebView,U=()=>({send:r=>window.ReactNativeWebView?.postMessage(r),listen:r=>{const t=n=>{const s=n.data;typeof s=="string"&&r(s)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),b={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage",permissions:"RequestSubWebViewPermission"},R=1,M=1e3,_=4e3,C=()=>typeof window<"u"&&window.ChaticSubWebView||null,D=()=>new Promise(r=>{if(typeof document>"u"||document.readyState==="complete"){r(C());return}window.addEventListener("load",()=>r(C()),{once:!0})}),$=r=>{let t,n;try{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)}`}catch{t="An error that could not be read was thrown"}return{message:(t||"Unknown error").slice(0,M),...n?{stack:n.slice(0,_)}:{}}},S=r=>new p.ChaticAppsError("NOT_SUPPORTED",`${r} is not available here: an older app, or not granted.`),y=r=>Promise.reject(new p.ChaticAppsError("NOT_IN_APP",`${r} needs the app; this page is in a browser.`)),P=(r={})=>{if(r===null||typeof r!="object"||Array.isArray(r))throw new p.ChaticAppsError("INVALID","link() takes an object of query params, such as { level: 3 }.");const t=new URLSearchParams;for(const[s,f]of Object.entries(r))t.append(s,String(f));const n=t.toString();return n?`?${n}`:""},L=r=>typeof location>"u"?`/${r}`:`${location.origin}/${r}`;let E=null;const j=(r={})=>(E||(E=(I()?G(U(),r):Promise.resolve(F())).catch(t=>{throw E=null,t})),E),G=async(r,t={})=>{const n=W(r,t.timeoutMs);try{const s=await k(n,!0);return B(n,s,t)}catch(s){throw n.close(),s}},k=async(r,t)=>{const n=await r.request("WebAppReady",{}),s=n.subWebView??(t?await D():null);if(s&&s.protocolVersion!==R)throw new p.ChaticAppsError("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(s.protocolVersion)}; this library speaks ${R}.`);return{supported:new Set(Array.isArray(n.supportedWebMessages)?n.supportedWebMessages:[]),context:s}},B=(r,t,n)=>{let s=null,f=null;const v=new Set,w=[],g=e=>t.supported.has(b[e]),a=(e,i,c,h)=>{const A=h??b[e];return t.supported.has(A)?r.request(A,i,c===void 0?{}:{timeoutMs:c}):Promise.reject(S(e))},o=(e,i)=>g("storage")?r.request(e,i):Promise.reject(S("storage")),d=e=>v.forEach(i=>{try{i(e)}catch(c){l.reportError(c)}}),u=()=>{g("back")&&r.request(b.back,{canGoBack:!!s}).catch(()=>{}),g("closeGuard")&&r.request(b.closeGuard,{enabled:!!f}).catch(()=>{})},m=e=>{if(!e.persisted){u();return}k(r,!1).then(i=>{const c=t.context;t.supported=i.supported,i.context&&(t.context=i.context),u();const h=t.context;h&&(h.theme!==c?.theme||h.locale!==c?.locale)&&d(h)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",m),w.push(()=>window.removeEventListener("pageshow",m))),w.push(r.onPush("OnBackPressed",()=>{try{s?.()}catch(e){l.reportError(e)}})),w.push(r.onPush("OnSubWebViewCloseRequested",e=>{const i=f;if(!i)return;const c=e?.trigger??"control";Promise.resolve().then(()=>i(c)).then(h=>h?l.finish():void 0).catch(h=>l.reportError(h))})),w.push(r.onPush("OnSubWebViewContextChanged",e=>{t.context&&(t.context={...t.context,...e},d(t.context))}));const l={inApp:!0,get context(){return t.context},supports:g,finish:e=>a("finish",e===void 0?{}:{result:e}).then(()=>{}),setTitle:e=>a("title",{title:e}).then(()=>{}),haptic:e=>{g("haptic")&&r.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(i=>i?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>a("userKey").then(e=>e.key),permissions:{query:e=>a("permissions",{kind:e},void 0,"GetSubWebViewPermission").then(i=>i.state),request:e=>a("permissions",{kind:e},null).then(i=>i.state)},openSettings:()=>a("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:e=>g("errorReport")?r.request(b.errorReport,$(e)).then(i=>!!i?.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=>{s=e,u()},onCloseRequest:e=>{f=e,u()},onContextChange:e=>(v.add(e),()=>v.delete(e)),link:e=>{const i=P(e),c=t.context?.appLink;return c?`${c}${i}`:L(i)},disconnect:()=>{w.forEach(e=>e()),r.close(),E=null}};if(n.reportErrors!==!1&&typeof window<"u"){const e=c=>{l.reportError(c.error??c.message)},i=c=>{l.reportError(c.reason)};window.addEventListener("error",e),window.addEventListener("unhandledrejection",i),w.push(()=>{window.removeEventListener("error",e),window.removeEventListener("unhandledrejection",i)})}return l},K=()=>{const r=async t=>{try{const n=await navigator.permissions.query({name:t});return n.state==="granted"?"granted":n.state==="denied"?"blocked":"prompt"}catch{return"prompt"}};return{query:r,request:async t=>{if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)throw new p.ChaticAppsError("NOT_SUPPORTED",`This browser cannot capture the ${t}.`);try{return(await navigator.mediaDevices.getUserMedia(t==="camera"?{video:!0}:{audio:!0})).getTracks().forEach(s=>s.stop()),"granted"}catch(n){const s=n?.name;if(s==="NotFoundError"||s==="OverconstrainedError")throw new p.ChaticAppsError("UNAVAILABLE",`This device has no ${t}.`);if(s==="NotReadableError"||s==="SecurityError"||s==="TypeError"||s==="AbortError")throw new p.ChaticAppsError("INTERNAL_ERROR",`The ${t} could not be used: ${s}.`);return await r(t)==="blocked"?"blocked":"prompt"}}}},F=()=>{const r=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(S("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>y("Finishing the view"),setTitle:async t=>{typeof document<"u"&&(document.title=t)},haptic:()=>{typeof navigator<"u"&&navigator.vibrate?.(10)},copy:r,openUrl:async t=>{typeof window<"u"&&window.open(t,"_blank","noopener,noreferrer")},share:async t=>{const n=[t.message,t.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(t),"shared"}catch(s){if(s?.name==="AbortError")return"dismissed"}return await r(n),"copied"},getUserKey:()=>y("A user key"),permissions:K(),openSettings:()=>y("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:p.browserStorage(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>L(P(t)),disconnect:()=>{E=null}}};exports.ChaticAppsError=p.ChaticAppsError;exports.SDK_BRIDGE_VERSION=O;exports.connect=j;exports.isInApp=I;
|