@lemoncloud/chatic-apps-sdk 0.1.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/GUIDE.md ADDED
@@ -0,0 +1,431 @@
1
+ > Korean: `GUIDE.ko.md` in the package (`README.ko.md` beside this file). This English version is the canonical one.
2
+
3
+ # Building a page with chatic-apps-sdk
4
+
5
+ A Chatic app is a web page that opens inside the DoU app, over everything else, at
6
+ `https://<name>.apps.chatic.io`. You build it like any web page, and `@lemoncloud/chatic-apps-sdk`
7
+ connects it to the app: closing, the title, haptics, sharing, saving data on the device, and more.
8
+ This guide is how to set a project up and what comes out of it. The library's calls, limits and error
9
+ codes are in the package `README.md`; this guide does not repeat them.
10
+
11
+ ## What you are building
12
+
13
+ - **Static files.** The app loads your page from a web address like any browser. There is no server
14
+ of yours to run for the page itself, and no server-side rendering.
15
+ - **One page, entered at the root.** The app always opens `/`. A link carries data in its query
16
+ (`/?level=3`), never in a path, so a page does not route on the path.
17
+ - **In the phone's own web view.** The page runs in WKWebView on iOS and the Android System WebView
18
+ on Android, so it can use what those engines support. Check the oldest phones you mean to support.
19
+ - **Also in a browser, while you build.** The library falls back to what a browser can do, and ships a
20
+ stand-in for the app, so you can write and try the page without a phone.
21
+
22
+ ## Choose a toolchain
23
+
24
+ The library has no runtime dependencies and no opinion about the rest, so use what you know. Three
25
+ shapes work, from least to most tooling:
26
+
27
+ | Shape | Use it when | The library comes from |
28
+ | ------------------------------- | --------------------------------------------- | ---------------------------------------------------- |
29
+ | One `index.html`, no build | A small page, a prototype | A `<script>` tag that defines `window.ChaticAppsSDK` |
30
+ | Vite and plain TypeScript or JS | A page of its own with a few screens of logic | `npm install` |
31
+ | Vite and React, Vue or Svelte | You already build interfaces in one of these | `npm install` |
32
+
33
+ Anything that ends in static files is fine, with these limits:
34
+
35
+ - **No server rendering and no server routing.** A framework's static or single-page mode, not its
36
+ server mode. Next.js needs `output: 'export'`, Nuxt needs `ssr: false` or `nuxt generate`, and
37
+ SvelteKit needs the static adapter in single-page mode.
38
+ - **Do not depend on a path.** A client-side router must work with the page entered at `/`, and must
39
+ not be needed to reach a shared link: put what a link carries in the query.
40
+ - **Do not depend on `window.opener`, popups or file downloads.** A popup opens in the same view and
41
+ replaces the page, so a login that answers through `window.opener` cannot work, and a download is not
42
+ handled on iOS; the package `README.md` says what to do instead.
43
+
44
+ Vite is the shortest road, and the rest of this guide uses it.
45
+
46
+ ## Set up a project
47
+
48
+ ```bash
49
+ npm create vite@latest quiz -- --template vanilla-ts
50
+ cd quiz
51
+ npm install @lemoncloud/chatic-apps-sdk
52
+ ```
53
+
54
+ Pick `react-ts`, `vue-ts` or `svelte-ts` for the template instead if you want one; nothing below
55
+ depends on it. Replace `src/main.ts` with a page that connects:
56
+
57
+ ```ts
58
+ import { connect, ChaticAppsError } from '@lemoncloud/chatic-apps-sdk';
59
+ import { installChaticAppsMock } from '@lemoncloud/chatic-apps-sdk/mock';
60
+
61
+ // A stand-in for the app in the browser, in development only. Vite removes a branch that is always
62
+ // false, so it is not in the production bundle. The controller lets you play the user's side.
63
+ if (import.meta.env.DEV) {
64
+ const app = installChaticAppsMock({ permissions: ['share', 'userKey'] });
65
+ Object.assign(window, { app }); // then `app.pressBack()` in the browser console
66
+ }
67
+
68
+ async function start() {
69
+ try {
70
+ const apps = await connect();
71
+ document.documentElement.dataset.theme = apps.context?.theme ?? 'light';
72
+ apps.onContextChange(context => (document.documentElement.dataset.theme = context.theme));
73
+ } catch (error) {
74
+ // `UNSUPPORTED_PROTOCOL` means the app is newer than this library: update the library.
75
+ const needsUpdate = error instanceof ChaticAppsError && error.code === 'UNSUPPORTED_PROTOCOL';
76
+ document.body.textContent = needsUpdate ? 'This page needs an update.' : 'This page could not start.';
77
+ }
78
+ }
79
+
80
+ void start();
81
+ ```
82
+
83
+ Then:
84
+
85
+ ```bash
86
+ npm run dev # the page in your browser, with the stand-in for the app
87
+ npm run build # the bundle, in dist/
88
+ ```
89
+
90
+ With React, Vue or Svelte, put the same lines where the application starts, before it renders.
91
+
92
+ ### Developing in a browser
93
+
94
+ `installChaticAppsMock` turns the tab into a fake app: it answers as the app does, logs every call, and
95
+ lets you play the user's side through the controller it returns — the Android back button, a close
96
+ 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.
97
+ It proves the page's logic and nothing about a phone: layout, the keyboard, the safe area and real
98
+ haptics need the app.
99
+
100
+ ## The bundle
101
+
102
+ What you hand over is a folder of static files. With Vite, that is `dist/`:
103
+
104
+ ```text
105
+ dist/
106
+ ├── index.html
107
+ ├── assets/
108
+ │ ├── index-3fa1c9.js
109
+ │ └── index-81b2d0.css
110
+ └── .well-known/
111
+ └── chatic-app.json
112
+ ```
113
+
114
+ - **`index.html` is at the top of the folder.** It is what `/` serves.
115
+ - **Assets are named by root-relative address** (`/assets/…`), which Vite does by default. The page is
116
+ always served from the root of its own address, so do not set a `base` path.
117
+ - **`.well-known/chatic-app.json` is the page's manifest.** The app reads it before it shows the page.
118
+ In Vite, put the file at `public/.well-known/chatic-app.json` and the build copies it as it is.
119
+ - **Nothing else is needed**: no server code, no `package.json`, no source files. Without a build, the
120
+ same layout holds: `index.html` and a `.well-known/chatic-app.json` beside it.
121
+
122
+ The manifest names the page and asks for what it needs:
123
+
124
+ ```json
125
+ {
126
+ "manifestVersion": 1,
127
+ "name": "Quiz",
128
+ "permissions": ["share", "userKey"],
129
+ "orientation": "portrait"
130
+ }
131
+ ```
132
+
133
+ A page has no bar by default: a small close button floats in the top-right corner, always, and the page
134
+ draws its own header (`"display": "clean"`). Add `"display": "titled"` to get the app's bar with the page's title and a
135
+ close button instead. A page that draws its own scenery to the screen's edges — a game, say — sets
136
+ `"display": "immersive"`: it then runs under the status bar and the home indicator, and pads its own
137
+ controls with the insets the README's Layout notes describe.
138
+
139
+ `manifestVersion` must be `1`; the app ignores a manifest it cannot read. Ask only for the permissions
140
+ the page uses — `clipboard`, `share`, `openUrl`, `userKey`, and for reading the app's data `session`,
141
+ `cloud`, `place`, `channel`, `chat`, `user` — and see the package `README.md` for what each one unlocks
142
+ and for `display` and `orientation`. Without a manifest a page still runs; it gets everything but what
143
+ those permissions unlock.
144
+
145
+ ## How the page behaves in the app
146
+
147
+ These are the facts that most often surprise a page written first for a browser. The package `README.md`
148
+ has the detail on each.
149
+
150
+ - **The app can close the page at any time.** Save as you go, and when `document` turns `hidden`.
151
+ Keep the page's own data in `apps.storage`, not `localStorage`, which goes when the system clears
152
+ website data. What must follow the user to another phone goes on your own server, under
153
+ `apps.getUserKey()`.
154
+ - **The page lies inside the safe area on every edge**, unless its manifest asks for `immersive`.
155
+ There are no insets to handle; an `immersive` page handles them itself, from the
156
+ `--chatic-safe-area-inset-*` properties in CSS, or `apps.context.safeArea` in script, which an older
157
+ app does not send — then fall back to the CSS properties.
158
+ - **Dark mode follows the app's theme**, from `apps.context.theme`, not the phone's.
159
+ - **Share `apps.link({ … })`**, not the page's address, and read what a link carries from
160
+ `location.search` when the page starts.
161
+ - **There is no title bar** unless the manifest asks for one, so the page draws its own header and title.
162
+ See [Screens and Back](#screens-and-back).
163
+ - **Android back** is yours only while you set `apps.onBack(handler)`; otherwise the app decides.
164
+ - **Errors**: every call can throw `ChaticAppsError`; branch on its `code`, never its `message`.
165
+
166
+ ## Screens and Back
167
+
168
+ A page with more than one screen — a menu, a game, a settings page — needs its own way back. There is
169
+ no bar and no back arrow to lean on: the only control the app gives is the small close button at the
170
+ top-right corner, which leaves the page. Android has a back key; iOS has none. So the page keeps a
171
+ stack of its screens, draws its own back button, and takes the Android back key only while there is a
172
+ screen to go back to:
173
+
174
+ ```ts
175
+ const screens = ['home'];
176
+
177
+ // Take Android back while a screen is stacked; give it back at the root, where the app closes the page.
178
+ const sync = () => apps.onBack(screens.length > 1 ? back : null);
179
+
180
+ function open(name: string) {
181
+ screens.push(name);
182
+ sync();
183
+ render();
184
+ }
185
+
186
+ function back() {
187
+ if (screens.length > 1) screens.pop();
188
+ sync();
189
+ render();
190
+ }
191
+
192
+ sync();
193
+ ```
194
+
195
+ Draw a back button in your header whenever `screens.length > 1` and have it call `back()`; at the root
196
+ draw none, since the close button is already there. In React, Vue or Svelte keep `screens` in state and
197
+ call `apps.onBack` from an effect that runs when its length changes. The same pattern closes a dialog:
198
+ treat an open dialog as a screen.
199
+
200
+ Three things to leave alone: do not set a handler at the root, so Android back still closes the page;
201
+ do not use `onCloseRequest` for navigation — it is for unsaved work; and keep the screens in memory, not
202
+ in the browser's history. A router that pushes entries (hash routes, `pushState`) gives the page a history,
203
+ and with a history Android back at the root walks it instead of closing the page. On iOS the edge swipe
204
+ only walks that history, so an in-memory stack needs the back button above either way.
205
+
206
+ Keep the top-right corner of every screen clear of your own controls: the close button floats there.
207
+
208
+ ## A page that uses the cloud's data
209
+
210
+ A page opened in a cloud can read that cloud — its places, rooms, messages and members — through
211
+ `apps.data`, and post a text message. The package `README.md` lists every method, its arguments and
212
+ the rows it answers; this is how to build a page around them.
213
+
214
+ **Choose permissions by what the page shows.** Each of `session`, `cloud`, `place`, `channel`, `chat`
215
+ and `user` opens a set of reads, `chatSend` opens the send, and `chatReact` opens reacting to a message. The app does not filter what a read
216
+ answers: a page with `user`, `channel` or `chat` gets users' sign-in ids, one with `place` gets each place's owner as the
217
+ account server has them, one with `cloud` the cloud's account details. Ask for the fewest that do the
218
+ job — what the page does with what it read is its author's responsibility — and do not send any of it
219
+ off the device without telling the user.
220
+
221
+ ```json
222
+ { "manifestVersion": 1, "name": "Room stats", "permissions": ["session", "channel", "chat"] }
223
+ ```
224
+
225
+ **Wait for the user.** `apps.data.connect()` is where the app asks the user whether this page may
226
+ read this cloud, and it waits as long as the user takes: show the page's own frame first, then connect.
227
+ A refusal is `CONSENT_REFUSED`: say why the page needs the data and offer to close.
228
+
229
+ ```ts
230
+ const apps = await connect();
231
+ if (!apps.supports('data')) return showNotAvailableHere(); // a browser, the desktop, an old Android WebView, an older app
232
+ try {
233
+ await apps.data.connect();
234
+ } catch (error) {
235
+ if (error instanceof ChaticAppsError && error.code === 'CONSENT_REFUSED') return showWhyWeAsk();
236
+ throw error;
237
+ }
238
+ const session = apps.data.session(); // CloudSession | null — null without `session`
239
+ const placeId = session?.committedSiteId ?? undefined; // undefined without `session`
240
+ ```
241
+
242
+ **Read with the types.** Every method the app opens is typed, so an editor completes the names and a
243
+ wrong argument fails the build. Rows are mostly optional fields: read each with a fallback.
244
+
245
+ ```ts
246
+ const rooms = await apps.data.call('channel.cacheReadList', { sid: placeId });
247
+ for (const room of rooms?.list ?? []) console.log(room.name ?? '(no name)', room.unreadCount ?? 0);
248
+ ```
249
+
250
+ **Streams are a budget.** A page holds at most 16 per page load; the next `subscribe` fails `INVALID`. Subscribe for what is on screen, `stop()`
251
+ when it leaves the screen, and hold only the rows you show — an event can carry a whole list.
252
+
253
+ **The cloud can change under the page.** If the user moves to another cloud, every stream ends with
254
+ `CLOUD_CHANGED`, `onCloudChanged` fires once, and nothing answers after. Finish the page or show a
255
+ notice; do not retry.
256
+
257
+ ```ts
258
+ apps.data.onCloudChanged(() => apps.finish());
259
+ ```
260
+
261
+ **Send only what the user chose to send.** `apps.data.sendMessage(roomId, text)` posts in the
262
+ user's name, to a room of the place the page was opened in. Send on a tap the user made, with text they
263
+ saw. The same goes for `apps.data.react(messageId, emoji, on)` with `chatReact`: it adds or removes a
264
+ reaction in the user's name — removing takes off the user's own reaction with that emoji, even one they
265
+ added by hand — so react only on the user's tap. Reactions are limited to one per 250 ms and 60 a
266
+ minute.
267
+
268
+ **Develop against the mock.** It answers from the data you give it, typed with the same map as the
269
+ app, so an answer of the wrong shape fails the build before it fails in the app:
270
+
271
+ ```ts
272
+ import { installChaticAppsMock } from '@lemoncloud/chatic-apps-sdk/mock';
273
+
274
+ const app = installChaticAppsMock({
275
+ permissions: ['session', 'channel', 'chatSend'],
276
+ data: {
277
+ session: {
278
+ context: {
279
+ cloud: { cloudId: 'cloud-1', siteId: 'place-1', isActive: true },
280
+ identity: { userId: 'user-1', isAuthenticated: true },
281
+ },
282
+ committedSiteId: 'place-1',
283
+ },
284
+ calls: {
285
+ 'channel.cacheReadList': () => ({
286
+ list: [{ id: 'room-1', cid: 'cloud-1', sid: 'place-1', isNotificationEnabled: true, name: 'Lobby' }],
287
+ meta: { total: 1 },
288
+ }),
289
+ },
290
+ },
291
+ });
292
+ // later: app.sentMessages, app.changeCloud()
293
+ ```
294
+
295
+ Use made-up ids and names in the mock, never a real cloud's. The mock does not know which methods the
296
+ app opens for which permission — it answers what you give it — so check `allowed` from `connect()` in
297
+ the app.
298
+
299
+ ## Your own server
300
+
301
+ A page is static files, and stays that way: no server rendering, no server routing. When it needs a
302
+ server of its own — scores, saved work, anything shared between users — that server is an API on its
303
+ own origin, and the page calls it with `fetch`.
304
+
305
+ **Allow the page's origin.** A call from the page is an ordinary cross-origin request from
306
+ `https://<name>.apps.chatic.io`, so the server answers it with CORS headers naming that origin, and
307
+ answers the preflight a JSON `POST` sends first:
308
+
309
+ ```http
310
+ Access-Control-Allow-Origin: https://<name>.apps.chatic.io
311
+ Access-Control-Allow-Methods: GET, POST, OPTIONS
312
+ Access-Control-Allow-Headers: Content-Type
313
+ Vary: Origin
314
+ ```
315
+
316
+ Allow your development address too while you test (see the next section), and not `*` once the page
317
+ is live.
318
+
319
+ **Tell users apart with the user key, and rely on nothing else from it.** `apps.getUserKey()` (the
320
+ `userKey` permission) answers 64 hex characters that stay the same for one device and your site. Send
321
+ it with each request and keep the user's data under it on the server. It is not a sign-in: two people
322
+ on one phone share it, and anyone who learns it can send it. Keep game progress under it, not money,
323
+ purchases or anything a user could take from another. If the page needs that, add a sign-in of your
324
+ own, with a redirect: a popup sign-in does not work in the app (`window.open` loads in the same view,
325
+ and nothing answers through `window.opener`).
326
+
327
+ **Trust nothing the page sends.** The page runs on the user's device, and anyone can call your API
328
+ directly with any body, any user key and any `params`. Check every value on the server as you would a
329
+ form on the open web. `MiniAppLaunchParams` names who is looking; it proves nothing.
330
+
331
+ **What the page read from the cloud is yours to answer for once it leaves the device.** The user
332
+ allowed the page to read the cloud with `apps.data`, not to send it elsewhere. If the page sends
333
+ members' names or messages to your server, say so in the page before it does, send only what the
334
+ feature needs, and keep it no longer than it needs.
335
+
336
+ ## Trying it in the app
337
+
338
+ A browser with the mock proves the page's logic; the app is the only place to see its layout, the
339
+ keyboard and real haptics. To open the page you are working on in the app before it is deployed, give
340
+ your development server an https address and add it to a cloud you own as a mini app.
341
+
342
+ 1. Run the development server, and expose it at an https address with a tunnel. `cloudflared` needs no
343
+ account for this:
344
+
345
+ ```bash
346
+ npm run dev # Vite, on http://localhost:5173
347
+ cloudflared tunnel --url http://localhost:5173 # prints https://<random words>.trycloudflare.com
348
+ ```
349
+
350
+ Vite refuses a host it does not know, so allow the tunnel's:
351
+
352
+ ```ts
353
+ // vite.config.ts
354
+ export default defineConfig({ server: { allowedHosts: ['.trycloudflare.com'] } });
355
+ ```
356
+
357
+ 2. In the DoU app on the phone, with a cloud you own selected, go to **My → Settings → Lab → Mini
358
+ apps** and tap **Add mini app**: a name, and that address (`https://…`, no port). The list is kept
359
+ on that phone only. Then tap **Open mini apps** and choose it on the mini app home. The first time,
360
+ DoU asks before it hands the page your name, your id in the cloud, the cloud and the place you have
361
+ open.
362
+ 3. The tunnel's address changes each time it starts: tap the mini app in the same list to edit its
363
+ address.
364
+
365
+ A tunnel's address lasts as long as the tunnel. For one that stays, put a build on any static host
366
+ with https (a preview deployment on Vercel, Netlify or the like) and add that address instead: it opens
367
+ the same way, with the same limits below, but each change needs a new deployment.
368
+
369
+ Such a page is opened as an outside site, not a reviewed page, and gets less than it will once
370
+ deployed to `apps.chatic.io`:
371
+
372
+ - **Only the base requests.** Closing, haptics, Android back, the close guard, error reports,
373
+ storage, and the camera and microphone permissions work. `setTitle` answers, but the bar keeps the
374
+ host. `getUserKey`, `copy`, `share` and
375
+ `openUrl` fail with `NOT_SUPPORTED`. The desktop app answers fewer still: closing, the title and
376
+ error reports.
377
+ - **No manifest.** The app does not read the page's `/.well-known/chatic-app.json`: the bar is always
378
+ shown, titled with the tunnel's host, and `display` and `orientation` do not apply.
379
+ - **No cloud data.** `apps.supports('data')` is `false`, so `apps.data` cannot be tried in the app this
380
+ way. Build it against the mock, and check it in the app once the page is reviewed.
381
+ - **Its own storage.** Storage is kept per origin, so what the page stores here is not what it will
382
+ find under its real address.
383
+
384
+ ## For an AI assistant in your project
385
+
386
+ The package ships `AGENTS.md`: rules for an assistant writing a Chatic app. Assistants read an
387
+ `AGENTS.md` at the top of the project, not one inside `node_modules`, so copy it there, or point your
388
+ assistant at `node_modules/@lemoncloud/chatic-apps-sdk/AGENTS.md`.
389
+
390
+ From 0.3.0 it also ships a skill, `skill/SKILL.md` (and `skill/SKILL.ko.md` in Korean): a procedure that takes
391
+ someone who has never built a web page from an idea to a zip that passes the verifier, by asking one
392
+ question at a time. It goes in three stages — the idea, the first build, the release prep — and keeps its
393
+ plan and progress in `MINIAPP.md` at the project's top, so a conversation on another day picks up where
394
+ the last one stopped. It only edits the project's files, installs the starting packages once after
395
+ asking, and runs the project's own scripts; it never uploads or submits anything.
396
+
397
+ To use it, put the `skill` folder where your assistant reads skills from, or give it `SKILL.md` and ask
398
+ it to follow it. In a project that already installed the package, copy it from `node_modules`; in an empty
399
+ folder, fetch the file of the published version you will install:
400
+
401
+ ```bash
402
+ cp -R node_modules/@lemoncloud/chatic-apps-sdk/skill ./chatic-app-skill
403
+ curl -fsSLO https://unpkg.com/@lemoncloud/chatic-apps-sdk@0.3.0/skill/SKILL.md
404
+ ```
405
+
406
+ The skill's first install needs SDK 0.3.0 and `@lemoncloud/chatic-apps-devtools` on npm; until both are
407
+ published, neither the commands above nor that install work. Then tell the assistant what you want —
408
+ "make a quiz mini-app" is enough to start. A copy does not update
409
+ with the package; the skill names the SDK version it was written for and says so when the installed one
410
+ differs.
411
+
412
+ ## Before you hand it over
413
+
414
+ - [ ] `npm run build` produces `dist/` with `index.html` and `.well-known/chatic-app.json` at its top.
415
+ - [ ] Once `@lemoncloud/chatic-apps-devtools` is published: `npx @lemoncloud/chatic-apps-devtools verify`
416
+ (or the project's `npm run verify`) ends with "Ready to hand over".
417
+ - [ ] Opened from a plain file server, the built page works at the root, with no path in the address.
418
+ - [ ] The page works in a browser with no app (`apps.inApp` is `false`) and with the stand-in.
419
+ - [ ] Every permission in the manifest is used, and every call that needs one is guarded with
420
+ `apps.supports(…)` or handles `NOT_SUPPORTED`.
421
+ - [ ] State is saved as the user goes, not only at a button.
422
+ - [ ] No `window.opener`, popup login, file download or server-side rendering.
423
+ - [ ] No user data in errors, in `reportError` or in the page's own logs.
424
+ - [ ] A page that calls its own server: the server allows the page's origin, checks every value it
425
+ receives, and puts nothing of value behind the user key alone.
426
+ - [ ] A page that reads the cloud: it asks for only the cloud data permissions it uses, handles
427
+ `CONSENT_REFUSED` and `CLOUD_CHANGED`, and stops every stream it no longer shows.
428
+
429
+ ## Deploying
430
+
431
+ How a page is submitted, reviewed and deployed to its address is not part of this guide yet.