@lemoncloud/chatic-apps-sdk 0.2.0 → 0.3.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 CHANGED
@@ -1,3 +1,5 @@
1
+ > Korean: [README.ko.md](./README.ko.md). This English version is the canonical one.
2
+
1
3
  # chatic-apps-sdk
2
4
 
3
5
  Build pages that run inside the DoU app. A page on `https://<name>.apps.chatic.io` opens in the app
@@ -22,7 +24,7 @@ Or, with no bundler, one script that defines `window.ChaticAppsSDK` (pin the ver
22
24
  is not in this file):
23
25
 
24
26
  ```html
25
- <script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.2.0/chatic-apps-sdk.global.js"></script>
27
+ <script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.3.0/chatic-apps-sdk.global.js"></script>
26
28
  ```
27
29
 
28
30
  ## Start
@@ -55,7 +57,7 @@ stand-ins; deployed to your `apps.chatic.io` address, it runs in the app.
55
57
  <meta charset="utf-8" />
56
58
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
57
59
  <title>Quiz</title>
58
- <script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.2.0/chatic-apps-sdk.global.js"></script>
60
+ <script src="https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.3.0/chatic-apps-sdk.global.js"></script>
59
61
  </head>
60
62
  <body>
61
63
  <h1 id="score">0</h1>
@@ -91,23 +93,25 @@ stand-ins; deployed to your `apps.chatic.io` address, it runs in the app.
91
93
 
92
94
  ## What a page can do
93
95
 
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 | — |
109
-
110
- Plus `apps.context` (the app's language, theme, platform and the `params` you were opened with),
96
+ | Call | In the app | In a browser | Needs permission |
97
+ | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------ |
98
+ | `finish(result?)` | Closes the view; `result` (JSON, ≤ 16 KiB) goes back to the opener | `NOT_IN_APP` | — |
99
+ | `setTitle(title)` | The app's bar shows it, if the page asked for the bar (1–100 characters) | `document.title` | — |
100
+ | `haptic(kind)` | `selection`, `impact`, `success`, `warning`, `error` | a short vibration, if any | — |
101
+ | `onBack(handler \| null)` | Android back calls `handler` and does nothing else | never called | — |
102
+ | `onCloseRequest(handler \| null)` | Asks before the user closes; return `true` to close | never called | — |
103
+ | `reportError(error)` | Into DoU's log, under your origin (20 per page load) | `console.error` | — |
104
+ | `copy(text)` | The clipboard | the browser's clipboard | `clipboard` |
105
+ | `share({ title, message, url })` | The share sheet; waits for the user (see below) | Web Share, else copies (`'copied'`) | `share` |
106
+ | `openUrl(url)` | The browser, mail, phone, SMS or a store | a new tab | `openUrl` |
107
+ | `getUserKey()` | 64 hex characters, the same for this device and site | `NOT_IN_APP` | `userKey` |
108
+ | `link(params?)` | A link that opens this page in the app (see below) | the page's own root | — |
109
+ | `storage.get(key)`, `.set(key, value)`, … | Your page's own storage on the device (see below) | `localStorage`, same limits | — |
110
+ | `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 | — |
111
+ | `data.connect()`, `.call(…)`, `.subscribe(…)`, `.sendMessage(…)`, `.react(…)` | Reads the app's own data — the current cloud — as DoU's screens do; posts text with `chatSend`, reacts with `chatReact` | `NOT_IN_APP` | `session`, `cloud`, `place`, `channel`, `chat`, `user`; `chatSend` to send, `chatReact` to react |
112
+
113
+ Plus `apps.context` (the app's language, theme, platform — `ios`, `android` or `desktop` — and the
114
+ `params` you were opened with; DoU's own web opens a mini app with `MiniAppLaunchParams`, see below),
111
115
  `apps.onContextChange(listener)` for a theme or language change, `apps.supports(capability)`,
112
116
  `apps.inApp`, and `apps.disconnect()`.
113
117
 
@@ -142,9 +146,218 @@ Plus `apps.context` (the app's language, theme, platform and the `params` you we
142
146
  sends them to DoU's log. An `Error` sends its message and stack, a string itself, anything else only
143
147
  its type. Pass `connect({ reportErrors: false })` to turn it off.
144
148
 
149
+ ## Reading the app's data: `apps.data`
150
+
151
+ A page can read the cloud it was opened in — its places, rooms, messages, members — with the same
152
+ reads DoU's own screens make, hear them change, and send a text message:
153
+
154
+ ```ts
155
+ const apps = await connect();
156
+ const placeId = (apps.context?.params as Partial<MiniAppLaunchParams> | undefined)?.place?.id;
157
+ if (apps.supports('data') && placeId) {
158
+ const { allowed } = await apps.data.connect(); // the app asks the user once, here
159
+ const rooms = await apps.data.call('channel.cacheReadList', { sid: placeId });
160
+ // rooms: CloudList<CloudChannel> | null
161
+ const stream = await apps.data.subscribe('channel.observeList', [{ sid: placeId }], result => {
162
+ render(result?.list ?? []);
163
+ });
164
+ apps.data.onCloudChanged(() => apps.finish());
165
+ }
166
+ ```
167
+
168
+ - **Typed by the app's own names.** Every method the app opens to a page is in `DataCalls` or
169
+ `DataStreams`, under the app's `<repository>.<method>` name, with its arguments and its answer:
170
+ a wrong argument or a misused answer fails the type check. A name the library does not know still
171
+ goes through and answers `unknown` — an app newer than this library may open more. `call<T>(name)`
172
+ with an explicit type still reaches any method untyped, as it did before the types.
173
+ - **What comes back is the app's own data**, as the app holds it — the rows below, field for field,
174
+ not reshaped or filtered for pages. `SDK_DATA_CONTRACTS` lists the cloud data contract versions this
175
+ library speaks.
176
+ - **Reads, and two writes, only as your manifest asks.** Each cloud data permission opens a fixed set of
177
+ methods (the table below); `connect()` answers the names this page may use (`allowed.calls`,
178
+ `allowed.streams`), and `can(name)` checks one — the types say what a method would be, `can` says
179
+ whether it is open now. Anything else is refused with `RUNTIME_NOT_ALLOWED`. Apart from the message
180
+ `chatSend` opens and the reaction `chatReact` opens, nothing a page can call changes anything, switches the cloud or the place,
181
+ or reads another cloud.
182
+ - **The user is asked once** whether your page may read this cloud. `connect()` waits for the answer
183
+ however long the user takes, with no timeout. A refusal is `CONSENT_REFUSED`; `connect()` asks again
184
+ the next time the page is opened.
185
+ - **Streams**: `subscribe(name, args, listener, onEnd)` hands `listener` each event. For a typed stream
186
+ pass only the arguments in the table: the library puts the listener right after them, where the
187
+ app's method takes its callback. For a name the library does not know, put `LISTENER` where that
188
+ method takes its callback (left out, it goes last). Pass nothing after the listener. `onEnd` hears a
189
+ stream the app ended: `CLOUD_CHANGED`, a too-large event, or `DISCONNECTED` after the page came back
190
+ from the back-forward cache (subscribe again). At most 16 per page load — the next `subscribe` fails
191
+ `INVALID` — so `stop()` each one you no longer need.
192
+ - **The cloud is fixed.** If the user's cloud changes under the view, every stream ends with
193
+ `CLOUD_CHANGED`, `onCloudChanged` fires once, and nothing answers after.
194
+ - **So is the place.** What belongs to a place — its rooms, their members and messages, its
195
+ profiles — is read only in the place your page was opened in, while the user is still there: a list
196
+ names that place (`sid`) or one of its rooms, and a room or a message is checked against it. Anything
197
+ else is `RUNTIME_NOT_ALLOWED`, and so is every read of a place once the user moved to another; open
198
+ a new view there. The places themselves and the cloud's own row are not a place's and stay open.
199
+ Read the place's id from `session().committedSiteId` or the launch parameters (`place.id`).
200
+ - **Server reads are budgeted**: one per 250 ms and 60 a minute per view, `RATE_LIMITED` past it, with
201
+ `error.details.retryAfterMs`. So are cache reads, apart: 600 a minute per view, each room the app
202
+ checks for a read or a message counting as one.
203
+ - **Only some launches answer it**: the app has to hold the session itself, the page has to be a
204
+ reviewed one on the phone, a cloud — Home included — has to be selected when it opens, and on
205
+ Android the WebView has to tell the page's own messages from a frame's inside it (an old Android
206
+ System WebView cannot, and the app then answers none of `apps.data` there).
207
+ `supports('data')` is `false` everywhere else, and every call is `NOT_IN_APP` in a browser.
208
+ - **The types cannot hold every argument the app checks.** An object passed from a variable may carry
209
+ fields its type does not list, and `call<T>` skips the argument types altogether; the app still
210
+ refuses what its checks refuse (an extra field on a send, `pageSize` on `user.listPlaceMembers`), with
211
+ `RUNTIME_NOT_ALLOWED`.
212
+ - **It reads what the app holds.** Nothing a page calls fetches into the app's cache, so it sees what
213
+ DoU has already synced, plus the methods marked "server" below.
214
+
215
+ ### Methods, by permission
216
+
217
+ | Permission | Method | Arguments | Answer |
218
+ | ----------- | ------------------------------------------------------ | -------------------------------------------------------- | ------------------------------------- |
219
+ | `session` | — (the hello's answer: `session()`, `onSessionChange`) | — | `CloudSession` |
220
+ | `cloud` | `cloud.cacheRead` | `id` — the current cloud's | `CloudInfo \| null` |
221
+ | `cloud` | `cloud.getCloud` (server) | `{ id }` — the current cloud's, `{ cache: false }` | `CloudInfo` |
222
+ | `cloud` | `cloud.observeItem` (stream) | `id` — the current cloud's | `CloudInfo \| null` |
223
+ | `place` | `place.cacheReadList` | `{}` (optional) | `CloudList<CloudPlace> \| null` |
224
+ | `place` | `place.observeList` (stream) | `{}` | `CloudList<CloudPlace> \| null` |
225
+ | `place` | `place.observeItem` (stream) | place `id` | `CloudPlace \| null` |
226
+ | `place` | `place.isPlaceDeleted` (server) | place `id` | `boolean` |
227
+ | `channel` | `channel.cacheRead` | room `id` — a room of the place | `CloudChannel \| null` |
228
+ | `channel` | `channel.cacheReadList` | `CloudChannelListQuery` — `sid` the place's, required | `CloudList<CloudChannel> \| null` |
229
+ | `channel` | `channel.fetchList` (server) | `CloudChannelListQuery` — `sid` the place's, required | `CloudList<CloudChannel>` |
230
+ | `channel` | `channel.observeList` (stream) | `CloudChannelListQuery` — `sid` the place's, required | `CloudList<CloudChannel> \| null` |
231
+ | `channel` | `channel.observeItem` (stream) | room `id` — a room of the place | `CloudChannel \| null` |
232
+ | `channel` | `join.cacheReadList` | `{ channelId, activeOnly? }` — a room of the place | `CloudList<CloudJoin> \| null` |
233
+ | `channel` | `join.observeList` (stream) | `{ channelId, activeOnly? }` — a room of the place | `CloudList<CloudJoin> \| null` |
234
+ | `chat` | `chat.cacheRead` | message `id` — answered if its room is the place's | `CloudChat \| null` |
235
+ | `chat` | `chat.cacheReadList` | `{ channelId, cursorNo?, limit? }` | `CloudList<CloudChat> \| null` |
236
+ | `chat` | `chat.listPendingImageChats` | room `id` | `CloudChat[]` |
237
+ | `chat` | `chat.observeList` (stream) | `{ channelId, cursorNo?, limit?, includeUnsent? }` | `CloudList<CloudChat> \| null` |
238
+ | `chat` | `chat.observeLastList` (stream) | room ids | `CloudLastChat[]` |
239
+ | `chat` | `chat.observeFeedCoverage` (stream) | room `id` | `[low, high][]` message-number ranges |
240
+ | `user` | `user.cacheReadList` | `{ channelId, limit?, page?, detail? }` | `CloudList<CloudUser> \| null` |
241
+ | `user` | `user.listPlaceMembers` (server) | `{ placeId, sessionPlaceId }` — both the current place's | `CloudPlaceMembers` |
242
+ | `user` | `user.observeList` (stream) | `{ channelId, limit?, page?, detail? }` | `CloudList<CloudUser> \| null` |
243
+ | `user` | `profile.cacheRead` | `<place id>@<user id>` — the place's | `CloudProfile \| null` |
244
+ | `user` | `profile.cacheReadList` | `{ sid, uid? }` — `sid` the place's, required | `CloudList<CloudProfile> \| null` |
245
+ | `user` | `profile.observeList` (stream) | `{ sid, uid? }` — `sid` the place's, required | `CloudList<CloudProfile> \| null` |
246
+ | `user` | `profile.observeItem` (stream) | `<place id>@<user id>` — the place's | `CloudProfile \| null` |
247
+ | `chatSend` | `chat.sendChat` — call it as `sendMessage` | `{ channelId, content }` | `CloudChat` |
248
+ | `chatReact` | `chat.setReaction` — call it as `react` | `{ chatId, emoji, action: 'on' \| 'off' }` | `CloudChat` |
249
+
250
+ ### The rows
251
+
252
+ All exported as types. Most fields are optional because the same row is filled from different answers
253
+ over time: a field is there only when the server or the app filled it, so read each with a fallback.
254
+
255
+ | Type | What it is | Fields worth knowing |
256
+ | -------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
257
+ | `CloudChannel` | A room | `id`, `sid` (its place), `name`, `stereo` (`dm`, `self`, …), `memberIds`, `chatNo`, `unreadCount`, `lastChat$` |
258
+ | `CloudJoin` | A member's place in a room | `channelId`, `userId`, `stereo` (`owner`, `member`), `readNo`, `nick`, `notify` |
259
+ | `CloudChat` | A message | `id`, `channelId`, `chatNo` (`0` while sending), `content`, `ownerId`, `createdAtMs` (always set), `upload$$`, `isPending`, `isFailed` |
260
+ | `CloudPlace` | A place of the cloud | `id`, `name`, `order`, `isOwner`, `owner$` |
261
+ | `CloudUser` | A user of the cloud | `id`, `name`, `nick`, `thumbnail` |
262
+ | `CloudProfile` | A user's name and picture in one place | `id` (`<place>@<user>`), `sid`, `userId`, `nick`, `thumbnail` |
263
+ | `CloudInfo` | The current cloud | `id`, `name`, `status`, `ownerId`, `cloudType` |
264
+ | `CloudSession` | The current cloud's part of the session | `context.cloud.cloudId`, `context.identity.userId`, `committedSiteId` |
265
+
266
+ `CloudList<Row>` is `{ list, meta: { total, limit?, page?, cursorNo?, readNo?, source? } }`.
267
+
268
+ ### What each permission hands over
269
+
270
+ The app does not filter a row for pages: what DoU's screens read, your page reads. That includes
271
+ contact and account details, marked in the types as such. Ask only for the permissions the page needs —
272
+ what it does with what it read is its author's responsibility — keep such details on the device, and
273
+ never send them to a third party without telling the user.
274
+
275
+ | Permission | Hands over |
276
+ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
277
+ | `session` | Which cloud and place the user is on, the user's id in this cloud, whether signed in. Nothing of the user's other clouds, no server address, no token |
278
+ | `cloud` | The current cloud's row; from the device cache, also its server addresses (`backend`, `wss`) and the device user ids that accepted an invite (`acceptedBy`). Through `cloud.getCloud`, for a cloud the user owns: its owner, the verified **email**, the linked **account** (`accountId`, `account$`), the subscription id, the cloud server's **account number** (`accountNo`) and service endpoints (`$envs`); for any other cloud, the relay's minimal `{ id, name, status }` |
279
+ | `place` | The cloud's places, with their server endpoints (`$envs`). A place's `owner$` is the account server's view of its owner, whose type includes **phone, email, address, birth date**, sign-in details and fields named after secrets (`loginPw`, `$account.otp$`, `$account.key$`) — filled as the server chooses. Never read, keep or send the secret-named ones |
280
+ | `channel` | Rooms of the place, their member ids, each member's join (role, nickname, read position), and the embedded owners (`owner$`, with **sign-in ids**) |
281
+ | `chat` | Messages in the place's rooms, with their files' addresses, any webhook cards, and the embedded senders (`owner$`, with **sign-in ids**) |
282
+ | `user` | Users of the place's rooms (names, nicknames, pictures, **sign-in ids**), the place's profiles, and its member list |
283
+ | `chatSend` | Nothing: it lets the page send |
284
+ | `chatReact` | Nothing: it lets the page add and remove the user's reactions; the reply is the message's row, which `chat` reads anyway |
285
+
286
+ ### Sending a message: `sendMessage`
287
+
288
+ ```ts
289
+ const sent = await apps.data.sendMessage(roomId, 'Round 3: 120 points'); // CloudChat
290
+ ```
291
+
292
+ With `chatSend`, `sendMessage(channelId, text)` posts `text` as plain text, in the user's name and
293
+ unmarked, to a room of the place the user was in when your page opened, and resolves with the sent
294
+ message. It is `call('chat.sendChat', { channelId, content: text })`, which still works. Text only — no
295
+ attachment, mention or reply — at most 1,000 characters with something besides white space in it; a
296
+ room in another place, one the user is not in, or any room once the user moved to another place, is
297
+ refused with `RUNTIME_NOT_ALLOWED`. The user is told, when asked, that the page sends messages, and is
298
+ asked per place. A send that fails leaves a failed message in the room on the user's device, as a
299
+ failed send from DoU's own composer does. Messages have their own budget, one per 500 ms and 30 a
300
+ minute, `RATE_LIMITED` past it. Get the room's id from a read (`channel`) or the launch parameters. In
301
+ a browser it is `NOT_IN_APP`.
302
+
303
+ ### Reacting to a message: `react`
304
+
305
+ ```ts
306
+ await apps.data.react(messageId, '👍', true); // CloudChat, the reaction on
307
+ await apps.data.react(messageId, '👍', false); // and off again
308
+ ```
309
+
310
+ With `chatReact`, `react(messageId, emoji, on)` adds (`true`) or removes (`false`) one emoji on a
311
+ message, in the user's name and unmarked, exactly as the user's own tap does, and resolves with the
312
+ message's row, the reaction applied. It is `call('chat.setReaction', { chatId, emoji, action })`, with
313
+ `action` `'on'` or `'off'`. `emoji` is one character as a person sees it — one emoji however many code
314
+ points build it, a skin tone or a flag included — and any emoji, not only DoU's picker's. **Removing
315
+ takes off the user's reaction with that emoji whoever set it**, one the user added by hand included:
316
+ nothing tells the two apart, and the user is told so when asked. The message must be one the device
317
+ holds, in a room of the place the user was in when your page opened, and one DoU's own screen offers a
318
+ reaction on — not deleted, sending or failed, nor a row that records an edit or a reaction; anything else, or any message once the user moved, is
319
+ `RUNTIME_NOT_ALLOWED`. Reactions have a budget of their own, one per 250 ms and 60 a minute, spent
320
+ before the message is read, so one refused for its message counts too (`RATE_LIMITED`). Read the message ids with `chat`. In a browser it is
321
+ `NOT_IN_APP`.
322
+
323
+ ### Place profiles: `placeProfile`, `placeProfiles`, `myProfile`
324
+
325
+ ```ts
326
+ const me = await apps.data.myProfile(); // CloudProfile | null
327
+ const sender = chat.ownerId ? await apps.data.placeProfile(chat.ownerId) : null; // a member of the place
328
+ const named = await apps.data.placeProfiles(); // CloudList<CloudProfile> | null: name the place's members
329
+ const stop = await apps.data.observePlaceProfile(userId, profile => renderName(profile?.nick));
330
+ ```
331
+
332
+ A place profile is what a member is called in one place of a cloud: the app keys it to the member's
333
+ id in that cloud, `<place id>@<user id>`, and it mostly holds the name shown there (`nick`) and a
334
+ picture — DoU names a member by it, and by the member's own name where there is none. As every read of
335
+ a place, it answers only for the place your page was opened in.
336
+
337
+ - `placeProfile(userId)` reads one member's profile as the device holds it, and
338
+ `observePlaceProfile(userId, listener, { onEnd? })` hears it and each change.
339
+ - `placeProfiles()` lists the place's profiles the device holds.
340
+ - `myProfile()` and `observeMyProfile(listener, { onEnd? })` do the same with the user's own id.
341
+
342
+ They need `user`, which reads profiles, and `session`, which names the place and the user's id:
343
+ without `session`, or before the session is on a place, they are `NOT_SUPPORTED`; without `user`, or
344
+ once the user moved to another place, `RUNTIME_NOT_ALLOWED`. `null` means the device holds no profile
345
+ for that member there: fall back to the member's own name. They are
346
+ `call('profile.cacheRead', '<place id>@<user id>')`, `call('profile.cacheReadList', { sid })` and
347
+ `subscribe('profile.observeItem', [id], …)`, which still work.
348
+
349
+ ### In the mock
350
+
351
+ The mock answers from `data: { calls, streams, session, consent }`, typed with the same map — an
352
+ answer of the wrong shape fails the type check — and plays the cloud change with `changeCloud()`. It
353
+ does not know the app's whitelist: it answers what you give it. With `chatSend` it opens
354
+ `chat.sendChat` itself, checks a send's shape as the app does (not the room's place, nor the send
355
+ budget), and records each send that went through in `sentMessages`. With `chatReact` it does the same
356
+ for `chat.setReaction`, recording each reaction in `reactions` (`{ messageId, emoji, on }`).
357
+
145
358
  ## Permissions
146
359
 
147
- The four calls marked above need a permission your page asks for in a file on its own site,
360
+ The calls marked above need a permission your page asks for in a file on its own site,
148
361
  `/.well-known/chatic-app.json`:
149
362
 
150
363
  ```json
@@ -152,16 +365,25 @@ The four calls marked above need a permission your page asks for in a file on it
152
365
  "manifestVersion": 1,
153
366
  "name": "Quiz",
154
367
  "permissions": ["share", "userKey"],
155
- "display": "standard",
368
+ "display": "titled",
156
369
  "orientation": "portrait"
157
370
  }
158
371
  ```
159
372
 
160
373
  You ask; an administrator grants them when your page is reviewed, and only what was granted is
161
- deployed. Without the file your page gets everything else but not these four, which then fail with
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
374
+ deployed. Without the file your page gets everything else but not what these permissions unlock: a call
375
+ that needs one fails with `NOT_SUPPORTED`, and without a cloud data permission `supports('data')` is
376
+ `false`. `display` says how the page is shown:
377
+
378
+ | `display` | What the user sees |
379
+ | ----------------- | ------------------------------------------------------------------------------------------------------ |
380
+ | `clean` (default) | The page alone, with a small close button floating in the top-right corner (keep it clear) |
381
+ | `titled` | The app's bar above the page, with its title and a close button |
382
+ | `immersive` | `clean`, but the page fills the whole screen, under the status bar and the home indicator (see Layout) |
383
+
384
+ Apps from before bridge 2.29.0 called `titled` `standard` and `clean` `fullscreen`, and know only
385
+ those names: they show a new name as `clean`. Current apps read both. `orientation` is `any`,
386
+ `portrait` or `landscape`. The app reads
165
387
  the file before it shows your page, keeps it for the rest of its run, and fetches a fresh copy behind
166
388
  each later open: a change to the file takes effect one open later.
167
389
 
@@ -181,22 +403,27 @@ try {
181
403
  }
182
404
  ```
183
405
 
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 |
198
-
199
- Treat a code not in this table as that call failing, and nothing more.
406
+ | Code | Means |
407
+ | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
408
+ | `NOT_SUPPORTED` | Not available: an older app, a permission the page does not hold, or no browser clipboard or storage |
409
+ | `NOT_IN_APP` | The call needs the app, and the page is in a browser |
410
+ | `TIMEOUT` | The app did not answer in 10 seconds (time in the background does not count) |
411
+ | `INVALID` | A value is missing, of the wrong type, or too long |
412
+ | `TOO_LARGE` | One call's data is over 65,536 characters |
413
+ | `LINK_NOT_ALLOWED` | The link cannot be opened or shared from a page |
414
+ | `NOT_OPEN` | `finish` after the view has already closed |
415
+ | `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 |
416
+ | `SETTINGS_ERROR` | `openSettings()`: the OS would not open the settings |
417
+ | `QUOTA_EXCEEDED` | A storage write would go past 1,048,576 characters; nothing was written |
418
+ | `DISCONNECTED` | The call was waiting when `disconnect()` closed the connection; or, for a cloud data stream, the page came back from the back-forward cache and the stream ended (subscribe again) |
419
+ | `RUNTIME_NOT_ALLOWED` | `data`: not a method this page may use, or an argument the app holds to the current cloud or place — for a message, its shape or its room |
420
+ | `CLOUD_CHANGED` | `data`: the user's cloud is no longer the one this view opened on; nothing answers after |
421
+ | `CONSENT_REFUSED` | `data.connect()`: the user did not allow this page to read this cloud |
422
+ | `RATE_LIMITED` | `data`: too many server reads, cache reads or messages sent; wait `error.details.retryAfterMs` |
423
+ | `UNSUPPORTED_PROTOCOL` | `connect()` only: the app is newer than this library; update it |
424
+
425
+ Treat a code not in this table as that call failing, and nothing more. The codes are the app's own,
426
+ so a few keep the app's older wording (`RUNTIME_NOT_ALLOWED` is about `apps.data`).
200
427
 
201
428
  ## Rules worth knowing
202
429
 
@@ -219,6 +446,22 @@ Treat a code not in this table as that call failing, and nothing more.
219
446
  - **You cannot see the error reports.** They go to DoU's log, read by the people who review pages.
220
447
  Send errors to your own server too if you want to see them.
221
448
 
449
+ ## Opened from DoU: `MiniAppLaunchParams`
450
+
451
+ When DoU itself opens your page — a cloud's owner registered it as the cloud's mini app — `params` has
452
+ this shape (exported as a type):
453
+
454
+ ```ts
455
+ import type { MiniAppLaunchParams } from '@lemoncloud/chatic-apps-sdk';
456
+
457
+ const params = apps.context?.params as Partial<MiniAppLaunchParams> | undefined;
458
+ // { cloud: { id, name }, place: { id, name } | null, user: { id, name } }
459
+ ```
460
+
461
+ `user.id` is the user's id in that cloud. These are names to show, not proof of who is looking: there
462
+ is no token, and your server must not treat them as a sign-in. `user.isOwner` and `miniApps` are sent
463
+ to DoU's own hub only; your page never receives them.
464
+
222
465
  ## What this WebView is like
223
466
 
224
467
  - **Use `apps.storage`, not the WebView's own**: `localStorage` and IndexedDB work, but go whenever the
@@ -226,13 +469,42 @@ Treat a code not in this table as that call failing, and nothing more.
226
469
  `getUserKey()`.
227
470
  - **No popups**: `window.open` and `target="_blank"` load in the same view, so a login that answers
228
471
  through `window.opener` does not work. Use a redirect login.
229
- - **Downloads**: a file download is not handled on iOS. Show the content instead.
472
+ - **Downloads**: a file download is not handled on iOS, nor on the desktop. Show the content instead.
473
+ - **On the desktop** (`platform: 'desktop'`) the page opens in a window over DoU with a bar: the
474
+ base requests only (`finish`, `setTitle`, error reports), no camera or microphone, and a site that is
475
+ not under `apps.chatic.io` always shows its own address in the bar.
230
476
  - **Camera and microphone** work through the browser APIs, under DoU's name: the OS asks the user
231
477
  "DoU would like to…". What your page uses is part of its review.
232
478
  - **Your own server**: calls to it are ordinary cross-origin requests from `https://<name>.apps.chatic.io`;
233
479
  allow that origin in its CORS settings.
234
- - **Layout**: the page sits inside the safe area on every edge; there are no insets to handle. Use the
480
+ - **Layout**: the page sits inside the safe area on every edge, unless its manifest sets `immersive`
481
+ (below); there are no insets to handle. Use the
235
482
  context's `theme`, not the OS's, for dark mode — the user can set DoU's theme apart from the phone's.
483
+ - **Immersive** (`display: "immersive"`, app bridge 2.29.0): the page fills the whole screen,
484
+ under the status bar, the home indicator and a landscape notch, and keeps its own controls clear of
485
+ them. The status bar stays visible. The app sets `--chatic-safe-area-inset-top`, `-right`, `-bottom` and `-left` on `<html>`; read
486
+ them first and fall back to `env()`, which not every Android WebView reports. The viewport meta must
487
+ say `viewport-fit=cover`: without it iOS keeps the page out of a landscape notch itself, and padding
488
+ by the properties as well pads that side twice:
489
+
490
+ ```css
491
+ .hud {
492
+ padding-top: var(--chatic-safe-area-inset-top, env(safe-area-inset-top, 0px));
493
+ }
494
+ .dock {
495
+ padding-bottom: var(--chatic-safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
496
+ }
497
+ ```
498
+
499
+ An older app shows the page padded, as `clean` (an older desktop app, with the bar), and the
500
+ insets read 0, so the same CSS is right on both.
501
+
502
+ A page that lays out in script — a canvas game — reads the same values from
503
+ `apps.context.safeArea` (`{ top, right, bottom, left }` in CSS px, 0 on every edge of a padded page)
504
+ and hears a rotation through `onContextChange`, once the insets have settled. `apps.context.display`
505
+ says which display the app actually used. Both are absent from apps before bridge 2.30.0 and from the
506
+ desktop: their absence is the signal to fall back to the CSS properties above. The close button still floats top-right, below the status bar. The status bar's icons follow
507
+ the app's theme.
236
508
 
237
509
  ## Try it without the app
238
510
 
@@ -250,28 +522,74 @@ const apps = await connect();
250
522
  app?.pressBack();
251
523
  app?.requestClose();
252
524
  app?.changeContext({ theme: 'dark' });
525
+ app?.rotate(); // an immersive page gets the other orientation's insets
253
526
  console.log(app?.closed); // { by: 'page', result } once the page finishes, { by: 'user' } on a close
254
527
  console.log(app?.storage); // what the page has stored
255
528
  ```
256
529
 
257
- Pass `storage: { … }` to start with data already stored; the mock keeps it in memory only.
530
+ Pass `storage: { … }` to start with data already stored; the mock keeps it in memory only. Pass
531
+ `context: { display: 'immersive' }` to try an immersive page: the mock sets a phone's insets in
532
+ `apps.context.safeArea` and the `--chatic-safe-area-inset-*` properties, and `rotate()` turns them.
533
+ `context: { display: undefined, safeArea: undefined }` stands in for an app before bridge 2.29.0, which
534
+ sends neither and shows the page padded.
258
535
 
259
536
  It answers as the app does — the base calls, plus the `permissions` you give it, and `NOT_SUPPORTED`
260
537
  for the rest — checks what the app checks, and logs every call. It is a stand-in: the share sheet is
261
538
  logged rather than shown, the user key is not the app's, and it proves nothing about a phone.
262
539
 
540
+ ## Versions
541
+
542
+ While the library is `0.x`, a release that adds anything — a call, a typed method, a field — raises the
543
+ minor version (`0.3.0`), and one that only fixes raises the patch (`0.3.1`). Pin the version you build
544
+ with, and read the changes before moving to a new minor.
545
+
546
+ Which app a page meets is the app's business, not the library's: a call the app cannot answer fails with
547
+ `NOT_SUPPORTED`, so decide with `apps.supports(...)`, never with a version number. The library's own
548
+ numbers, for reading a bug report:
549
+
550
+ | Library | Bridge it was built against (`SDK_BRIDGE_VERSION`) | Data contracts (`SDK_DATA_CONTRACTS`) | Added |
551
+ | ------- | -------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
552
+ | 0.1.0 | 2.19.0 | — | The base calls, storage, share, user key |
553
+ | 0.2.0 | 2.20.0 | — | Camera and microphone permissions; `GUIDE.md` and `AGENTS.md` in the package |
554
+ | 0.3.0 | 2.33.0 | `[1]` | `apps.data` with its typed methods, rows and session; `sendMessage`; place profiles (`placeProfile`, `placeProfiles`, `myProfile` and their `observe…`); the typed mock; `platform: 'desktop'`; the `MiniAppLaunchParams` type; the skill (`skill/SKILL.md`); `react` (`chatReact`); `context.display` and `context.safeArea`; the mock's `display`, `rotate()` and `reactions` |
555
+
556
+ What 0.3.0 needs from the app, for reading a bug report (bridge versions; the page still decides with
557
+ `apps.supports(...)`, and an older app answers `false` or `NOT_SUPPORTED` rather than breaking the page):
558
+
559
+ - `apps.data` reads: bridge 2.26.0; `sendMessage`: 2.27.0.
560
+ - `context.display` and `context.safeArea`: 2.30.0 (absent before it).
561
+ - The cache budget and merged events while hidden: 2.31.0.
562
+ - `react` (`chatReact`): 2.32.0.
563
+ - 2.33.0 is the bridge this build was made against; no further call needs it.
564
+
565
+ A page written for 0.2.0 needs no change: nothing it called was removed or renamed.
566
+
567
+ The data contract is the app's own version for what `apps.data` reads. The app answers a
568
+ page with the newest contract both speak; a library that speaks none the app does is answered
569
+ `NOT_SUPPORTED`.
570
+
263
571
  ## For an AI assistant writing a page
264
572
 
265
573
  `AGENTS.md` in this package holds the rules for an assistant writing a page: the project, the calls
266
574
  and the page. Copy it to the top of your project, where an assistant looks for it, or paste it into the
267
575
  prompt along with what the page should do. `GUIDE.md` says how to set the project up.
268
576
 
577
+ `skill/SKILL.md` (Korean: `skill/SKILL.ko.md`) is a procedure for the assistant: it asks the author one
578
+ question at a time and goes from an idea to a zip that passes the verifier, in three stages. `GUIDE.md`,
579
+ "For an AI assistant in your project", says how to copy it into a project.
580
+
269
581
  ## For maintainers
270
582
 
271
583
  This library lives in the DoU app's repository so it cannot drift from the app: its public types are
272
584
  pinned to the app's message definitions by a type-level test, and a contract test in the app runs this
273
- client against the app's real page host. The protocol it speaks is specified in
274
- [sub-webview-protocol.md](https://github.com/lemoncloud-io/dou-app/blob/develop/apps/mobile/docs/webview/sub-webview-protocol.md).
585
+ client against the app's real page host. The cloud data rows, arguments and session are declared by hand
586
+ here (the app's types are private packages) and held to the app's by the app's contract test
587
+ (`chaticAppsSdkRuntime.contract.test.ts`):
588
+ the typed methods must be exactly what the whitelist opens, permission by permission, and every row
589
+ (and its embedded views, four levels deep)
590
+ field must match the app's in name, optionality and type. That test compiles itself, because neither
591
+ its transform nor CI type checks the app; dropping or retyping a field of an app row fails it. The protocol it speaks is specified in
592
+ [mini-app-protocol.md](https://github.com/lemoncloud-io/dou-app/blob/develop/apps/mobile/docs/webview/mini-app-protocol.md).
275
593
 
276
594
  ```bash
277
595
  npx jest --config libs/chatic-apps-sdk/jest.config.js
@@ -1 +1 @@
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})({});
1
+ var ChaticAppsSDK=(function(A){"use strict";class u extends Error{code;details;constructor(t,r,n){super(r),this.name="ChaticAppsError",this.code=t,n!==void 0&&(this.details=n)}}const V="2.33.0",te=1e4,re=2e3;let ne=0;const oe=()=>`cas-${Date.now().toString(36)}-${(++ne).toString(36)}`,U=()=>typeof document<"u"&&document.visibilityState==="hidden",se=(e,t=te)=>{const r=new Map,n=new Map;let p=!1;const w=(c,s)=>{s.remaining===null||U()||(s.startedAt=Date.now(),s.timer=setTimeout(()=>{r.delete(c),s.reject(new u("TIMEOUT","The app did not answer in time."))},s.remaining))},d=()=>{for(const[c,s]of r)s.remaining!==null&&(U()?(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,re),w(c,s)))};typeof document<"u"&&document.addEventListener("visibilitychange",d);const y=e.listen(c=>{let s;try{s=JSON.parse(c)}catch{return}if(!s||typeof s!="object"||typeof s.type!="string")return;const f=typeof s.refId=="string"?r.get(s.refId):void 0;if(f&&typeof s.refId=="string"){if(r.delete(s.refId),f.timer&&clearTimeout(f.timer),s.success===!0)f.resolve(s.data);else{const b=typeof s.error?.code=="string"?s.error.code:"INTERNAL_ERROR",v=typeof s.error?.message=="string"?s.error.message:b;f.reject(new u(b,v,s.error?.details))}return}n.get(s.type)?.forEach(b=>{try{b(s.data)}catch{}})});return{request:(c,s={},f={})=>new Promise((b,v)=>{if(p){v(new u("DISCONNECTED","The connection to the app was closed."));return}const T=oe(),E=f.timeoutMs===void 0?t:f.timeoutMs,o={resolve:b,reject:v,remaining:E,startedAt:Date.now(),timer:null};r.set(T,o),w(T,o),e.send(JSON.stringify({type:c,data:s,refId:T,version:V}))}),onPush:(c,s)=>{let f=n.get(c);return f||n.set(c,f=new Set),f.add(s),()=>f?.delete(s)},close:()=>{if(!p){p=!0,y(),typeof document<"u"&&document.removeEventListener("visibilitychange",d);for(const c of r.values())c.timer&&clearTimeout(c.timer),c.reject(new u("DISCONNECTED","The connection to the app was closed."));r.clear(),n.clear()}}}},j=[1],q=Object.freeze({$listener:!0}),$="data",ie=e=>typeof e=="object"&&e!==null&&e.$listener===!0,ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return null;const t=e.$ended;return t&&typeof t=="object"?t:null},ce=(e,t,r)=>{let n=null,p=null,w=null,d=null,y=!1,c=0;const s=new Map,f=new Set,b=new Set,v=i=>{try{i()}catch(a){r(a)}},T=()=>{y||(y=!0,b.forEach(i=>v(i)))},E=i=>{throw i instanceof u&&i.code==="CLOUD_CHANGED"&&T(),i},o=i=>{const a=[...s.values()];s.clear(),a.forEach(h=>v(()=>h.onEnd?.(i)))},l=e.onPush("OnRuntimeEvent",i=>{const{subscriptionId:a,event:h}=i??{},O=typeof a=="string"?s.get(a):void 0;if(!O||typeof a!="string")return;const S=ae(h);if(S){s.delete(a);const L=typeof S.code=="string"?S.code:"INTERNAL_ERROR",Ae=typeof S.message=="string"?S.message:L;L==="CLOUD_CHANGED"&&T(),v(()=>O.onEnd?.(new u(L,Ae)));return}v(()=>O.listener(...Array.isArray(h)?h:[h]))}),g=e.onPush("OnRuntimeSessionChanged",i=>{const{seq:a,session:h}=i??{};!w||typeof a!="number"||a<=w.seq||(w={...w,seq:a},d=h??null,f.forEach(O=>v(()=>O(d))))}),m=()=>{if(!t())return Promise.reject(new u("NOT_SUPPORTED","This app does not answer this page's cloud data requests."));if(!n){const i=new Promise((h,O)=>{p=O}),a=Promise.race([e.request("RuntimeHello",{contracts:[...j]},{timeoutMs:null}),i]).then(h=>(n===a&&(w=h,d=h.session??null),h)).catch(h=>(n===a&&(n=null),E(h)));n=a}return n},R=async(i,a)=>{if(!(await m()).allowed[i].includes(a))throw new u("RUNTIME_NOT_ALLOWED",`${a} is not one this page may ${i==="calls"?"call":"subscribe to"}.`)},N=async(i,...a)=>(await R("calls",i),(await e.request("RuntimeCall",{target:$,method:i,args:a}).catch(E)).value),Q=async(i,a,h,O)=>{await R("streams",i);const S=`cas-s${(++c).toString(36)}`;s.set(S,{listener:h,onEnd:O});try{await e.request("RuntimeSubscribe",{subscriptionId:S,target:$,topic:i,args:a.some(ie)?a:[...a,q]})}catch(L){s.delete(S),E(L)}return{stop:async()=>{s.delete(S)&&await e.request("RuntimeUnsubscribe",{subscriptionId:S}).catch(()=>{})}}},X=async()=>{await m();const i=d?.committedSiteId;if(!i)throw new u("NOT_SUPPORTED","A place profile needs the session permission, while the session is on a place.");return i},z=async()=>{await m();const i=d?.context.identity.userId;if(!i)throw new u("NOT_SUPPORTED","The user's own profile needs the session permission.");return i},Y=async i=>`${await X()}@${i}`,Z=async i=>N("profile.cacheRead",await Y(i)),ee=async(i,a,h)=>Q("profile.observeItem",[await Y(i)],a,h?.onEnd);return{connect:()=>m().then(({contract:i,allowed:a})=>({contract:i,allowed:a})),can:i=>!!w&&(w.allowed.calls.includes(i)||w.allowed.streams.includes(i)),call:N,subscribe:Q,sendMessage:(i,a)=>N("chat.sendChat",{channelId:i,content:a}),react:(i,a,h)=>N("chat.setReaction",{chatId:i,emoji:a,action:h?"on":"off"}),placeProfile:Z,placeProfiles:async()=>N("profile.cacheReadList",{sid:await X()}),observePlaceProfile:ee,myProfile:async()=>Z(await z()),observeMyProfile:async(i,a)=>ee(await z(),i,a),session:()=>d,onSessionChange:i=>(f.add(i),()=>f.delete(i)),onCloudChanged:i=>(b.add(i),()=>b.delete(i)),reset:()=>{p?.(new u("DISCONNECTED","The page was restored before the app answered. Connect again.")),p=null,n=null,w=null,d=null,o(new u("DISCONNECTED","The page was restored; its streams ended. Subscribe again."))},dispose:()=>{l(),g(),s.clear()}}},de=()=>{const e=()=>Promise.reject(new u("NOT_IN_APP","The app's data is read only in the app."));return{connect:e,can:()=>!1,call:e,subscribe:e,sendMessage:e,react:e,placeProfile:e,placeProfiles:e,observePlaceProfile:e,myProfile:e,observeMyProfile:e,session:()=>null,onSessionChange:()=>()=>{},onCloudChanged:()=>()=>{}}},D=e=>{try{return JSON.stringify(e)??null}catch{return null}},W=e=>{const t=r=>Object.values(r??{}).every(n=>D(n)!==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(n=>n.entries[r]),getMany:r=>e.get(r).then(n=>n.entries),set:(r,n)=>t({[r]:n}),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:n})=>({used:r,limit:n}))}},x=1024*1024,le=200,ue=64*1024,_=e=>typeof e=="string"&&e.length>=1&&e.length<=le&&e!=="__proto__",pe=e=>{const t=()=>e.keys().reduce((n,p)=>n+p.length+(e.read(p)?.length??0),0),r=()=>({used:t(),limit:x});return{get(n){if(!Array.isArray(n)||!n.every(_))return{ok:!1,code:"INVALID"};const p={};for(const w of n){const d=e.read(w);if(d!==void 0)try{p[w]=JSON.parse(d)}catch{}}return{ok:!0,value:{entries:p}}},set(n){if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,code:"INVALID"};const p=[];let w=t();for(const[d,y]of Object.entries(n)){const c=D(y);if(!_(d)||c===null)return{ok:!1,code:"INVALID"};const s=e.read(d);w+=c.length-(s===void 0?-d.length:s.length),p.push([d,c])}return w>x?{ok:!1,code:"QUOTA_EXCEEDED"}:(p.forEach(([d,y])=>e.write(d,y)),{ok:!0,value:r()})},remove(n){return!Array.isArray(n)||!n.every(_)?{ok:!1,code:"INVALID"}:(n.forEach(p=>e.delete(p)),{ok:!0,value:r()})},clear(){return e.keys().forEach(n=>e.delete(n)),{ok:!0,value:{}}},info(){return{ok:!0,value:{keys:e.keys(),...r()}}}}},C="chatic-apps.storage:",fe=e=>({read:t=>e.getItem(C+t)??void 0,write:(t,r)=>e.setItem(C+t,r),delete:t=>e.removeItem(C+t),keys:()=>{const t=[];for(let r=0;r<e.length;r++){const n=e.key(r);n?.startsWith(C)&&t.push(n.slice(C.length))}return t}}),he=()=>{const e=t=>{let r;try{r=t(pe(fe(window.localStorage)))}catch(n){return n?.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 W({get:t=>e(r=>r.get(t)),set:t=>(D({entries:t})?.length??0)>ue?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())})},G=()=>typeof window<"u"&&!!window.ReactNativeWebView,we=()=>({send:e=>window.ReactNativeWebView?.postMessage(e),listen:e=>{const t=r=>{const n=r.data;typeof n=="string"&&e(n)};return window.addEventListener("message",t),document.addEventListener("message",t),()=>{window.removeEventListener("message",t),document.removeEventListener("message",t)}}}),I={finish:"FinishSubWebView",title:"SetSubWebViewTitle",haptic:"TriggerHaptic",clipboard:"CopyToClipboard",share:"OpenShareSheet",openUrl:"OpenURL",userKey:"GetSubWebViewUserKey",back:"SetCanGoBack",closeGuard:"SetSubWebViewCloseGuard",errorReport:"ReportSubWebViewError",storage:"GetSubWebViewStorage",permissions:"RequestSubWebViewPermission",data:"RuntimeHello"},K=1,ge=1e3,me=4e3,B=()=>typeof window<"u"&&window.ChaticSubWebView||null,ye=()=>new Promise(e=>{if(typeof document>"u"||document.readyState==="complete"){e(B());return}window.addEventListener("load",()=>e(B()),{once:!0})}),ve=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,ge),...r?{stack:r.slice(0,me)}:{}}},k=e=>new u("NOT_SUPPORTED",`${e} is not available here: an older app, or not granted.`),M=e=>Promise.reject(new u("NOT_IN_APP",`${e} needs the app; this page is in a browser.`)),H=(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[n,p]of Object.entries(e))t.append(n,String(p));const r=t.toString();return r?`?${r}`:""},F=e=>typeof location>"u"?`/${e}`:`${location.origin}/${e}`;let P=null;const Ee=(e={})=>(P||(P=(G()?be(we(),e):Promise.resolve(Oe())).catch(t=>{throw P=null,t})),P),be=async(e,t={})=>{const r=se(e,t.timeoutMs);try{const n=await J(r,!0);return Se(r,n,t)}catch(n){throw r.close(),n}},J=async(e,t)=>{const r=await e.request("WebAppReady",{}),n=r.subWebView??(t?await ye():null);if(n&&n.protocolVersion!==K)throw new u("UNSUPPORTED_PROTOCOL",`The app speaks protocol ${String(n.protocolVersion)}; this library speaks ${K}.`);return{supported:new Set(Array.isArray(r.supportedWebMessages)?r.supportedWebMessages:[]),context:n}},Se=(e,t,r)=>{let n=null,p=null;const w=new Set,d=[],y=o=>t.supported.has(I[o]),c=(o,l,g,m)=>{const R=m??I[o];return t.supported.has(R)?e.request(R,l,g===void 0?{}:{timeoutMs:g}):Promise.reject(k(o))},s=ce(e,()=>y("data"),o=>{E.reportError(o)});d.push(()=>s.dispose());const f=(o,l)=>y("storage")?e.request(o,l):Promise.reject(k("storage")),b=o=>w.forEach(l=>{try{l(o)}catch(g){E.reportError(g)}}),v=()=>{y("back")&&e.request(I.back,{canGoBack:!!n}).catch(()=>{}),y("closeGuard")&&e.request(I.closeGuard,{enabled:!!p}).catch(()=>{})},T=o=>{if(!o.persisted){v();return}J(e,!1).then(l=>{const g=t.context;t.supported=l.supported,l.context&&(t.context=l.context),v(),s.reset();const m=t.context,R=m&&(m.theme!==g?.theme||m.locale!==g?.locale||JSON.stringify(m.safeArea)!==JSON.stringify(g?.safeArea));m&&R&&b(m)}).catch(()=>{})};typeof window<"u"&&(window.addEventListener("pageshow",T),d.push(()=>window.removeEventListener("pageshow",T))),d.push(e.onPush("OnBackPressed",()=>{try{n?.()}catch(o){E.reportError(o)}})),d.push(e.onPush("OnSubWebViewCloseRequested",o=>{const l=p;if(!l)return;const g=o?.trigger??"control";Promise.resolve().then(()=>l(g)).then(m=>m?E.finish():void 0).catch(m=>E.reportError(m))})),d.push(e.onPush("OnSubWebViewContextChanged",o=>{t.context&&(t.context={...t.context,...o},b(t.context))}));const E={inApp:!0,get context(){return t.context},supports:y,finish:o=>c("finish",o===void 0?{}:{result:o}).then(()=>{}),setTitle:o=>c("title",{title:o}).then(()=>{}),haptic:o=>{y("haptic")&&e.request(I.haptic,{kind:o}).catch(()=>{})},copy:o=>c("clipboard",{text:o}).then(()=>{}),openUrl:o=>c("openUrl",{url:o}).then(()=>{}),share:o=>c("share",o,null).then(l=>l?.action==="dismissedAction"?"dismissed":"shared"),getUserKey:()=>c("userKey").then(o=>o.key),permissions:{query:o=>c("permissions",{kind:o},void 0,"GetSubWebViewPermission").then(l=>l.state),request:o=>c("permissions",{kind:o},null).then(l=>l.state)},openSettings:()=>c("permissions",{},void 0,"OpenSettings").then(()=>{}),reportError:o=>y("errorReport")?e.request(I.errorReport,ve(o)).then(l=>!!l?.recorded).catch(()=>!1):Promise.resolve(!1),data:s,storage:W({get:o=>f("GetSubWebViewStorage",{keys:o}),set:o=>f("SetSubWebViewStorage",{entries:o}),remove:o=>f("RemoveSubWebViewStorage",{keys:o}),clear:()=>f("ClearSubWebViewStorage",{}),info:()=>f("GetSubWebViewStorageInfo",{})}),onBack:o=>{n=o,v()},onCloseRequest:o=>{p=o,v()},onContextChange:o=>(w.add(o),()=>w.delete(o)),link:o=>{const l=H(o),g=t.context?.appLink;return g?`${g}${l}`:F(l)},disconnect:()=>{d.forEach(o=>o()),e.close(),P=null}};if(r.reportErrors!==!1&&typeof window<"u"){const o=g=>{E.reportError(g.error??g.message)},l=g=>{E.reportError(g.reason)};window.addEventListener("error",o),window.addEventListener("unhandledrejection",l),d.push(()=>{window.removeEventListener("error",o),window.removeEventListener("unhandledrejection",l)})}return E},Te=()=>{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(n=>n.stop()),"granted"}catch(r){const n=r?.name;if(n==="NotFoundError"||n==="OverconstrainedError")throw new u("UNAVAILABLE",`This device has no ${t}.`);if(n==="NotReadableError"||n==="SecurityError"||n==="TypeError"||n==="AbortError")throw new u("INTERNAL_ERROR",`The ${t} could not be used: ${n}.`);return await e(t)==="blocked"?"blocked":"prompt"}}}},Oe=()=>{const e=t=>typeof navigator<"u"&&navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(k("The clipboard"));return{inApp:!1,context:null,supports:()=>!1,finish:()=>M("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(n){if(n?.name==="AbortError")return"dismissed"}return await e(r),"copied"},getUserKey:()=>M("A user key"),permissions:Te(),data:de(),openSettings:()=>M("Opening the settings"),reportError:async t=>(console.error(t),!1),storage:he(),onBack:()=>{},onCloseRequest:()=>{},onContextChange:()=>()=>{},link:t=>F(H(t)),disconnect:()=>{P=null}}};return A.ChaticAppsError=u,A.LISTENER=q,A.SDK_BRIDGE_VERSION=V,A.SDK_DATA_CONTRACTS=j,A.connect=Ee,A.isInApp=G,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),A})({});