@aparte/n8n-chat 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +333 -2
  3. package/dist/cards.d.ts +3 -0
  4. package/dist/cdn/chunks/chunk-7JR7KL6J.js +2 -0
  5. package/dist/cdn/chunks/chunk-7JR7KL6J.js.map +7 -0
  6. package/dist/cdn/chunks/chunk-CZ5742JA.js +2 -0
  7. package/dist/cdn/chunks/chunk-CZ5742JA.js.map +7 -0
  8. package/dist/cdn/chunks/chunk-IPWLCOPM.js +2 -0
  9. package/dist/cdn/chunks/chunk-IPWLCOPM.js.map +7 -0
  10. package/dist/cdn/chunks/chunk-IWAJFJNA.js +353 -0
  11. package/dist/cdn/chunks/chunk-IWAJFJNA.js.map +7 -0
  12. package/dist/cdn/chunks/chunk-OJFRNS5M.js +2 -0
  13. package/dist/cdn/chunks/chunk-OJFRNS5M.js.map +7 -0
  14. package/dist/cdn/chunks/chunk-VTTH7HGO.js +206 -0
  15. package/dist/cdn/chunks/chunk-VTTH7HGO.js.map +7 -0
  16. package/dist/cdn/chunks/chunk-XAWE4EAK.js +2 -0
  17. package/dist/cdn/chunks/chunk-XAWE4EAK.js.map +7 -0
  18. package/dist/cdn/chunks/de-JS3CQEVR.js +2 -0
  19. package/dist/cdn/chunks/de-JS3CQEVR.js.map +7 -0
  20. package/dist/cdn/chunks/es-OHKGLFEF.js +2 -0
  21. package/dist/cdn/chunks/es-OHKGLFEF.js.map +7 -0
  22. package/dist/cdn/chunks/fr-6S44XMU5.js +2 -0
  23. package/dist/cdn/chunks/fr-6S44XMU5.js.map +7 -0
  24. package/dist/cdn/chunks/highlight-FGIKUPIF.js +153 -0
  25. package/dist/cdn/chunks/highlight-FGIKUPIF.js.map +7 -0
  26. package/dist/cdn/chunks/it-K4WYXXDJ.js +2 -0
  27. package/dist/cdn/chunks/it-K4WYXXDJ.js.map +7 -0
  28. package/dist/cdn/chunks/items-S4LF2DJA.js +467 -0
  29. package/dist/cdn/chunks/items-S4LF2DJA.js.map +7 -0
  30. package/dist/cdn/chunks/ja-BN7TZW62.js +2 -0
  31. package/dist/cdn/chunks/ja-BN7TZW62.js.map +7 -0
  32. package/dist/cdn/chunks/ko-ARHO7UI3.js +2 -0
  33. package/dist/cdn/chunks/ko-ARHO7UI3.js.map +7 -0
  34. package/dist/cdn/chunks/link-C46K5O7X.js +493 -0
  35. package/dist/cdn/chunks/link-C46K5O7X.js.map +7 -0
  36. package/dist/cdn/chunks/media-QI5BPERX.js +797 -0
  37. package/dist/cdn/chunks/media-QI5BPERX.js.map +7 -0
  38. package/dist/cdn/chunks/order-YISYH73K.js +839 -0
  39. package/dist/cdn/chunks/order-YISYH73K.js.map +7 -0
  40. package/dist/cdn/chunks/place-UFCH3NQE.js +689 -0
  41. package/dist/cdn/chunks/place-UFCH3NQE.js.map +7 -0
  42. package/dist/cdn/chunks/plan-KQWF73QI.js +542 -0
  43. package/dist/cdn/chunks/plan-KQWF73QI.js.map +7 -0
  44. package/dist/cdn/chunks/product-7UBLOMZ7.js +660 -0
  45. package/dist/cdn/chunks/product-7UBLOMZ7.js.map +7 -0
  46. package/dist/cdn/chunks/pt-BR-R7ZRM3GG.js +2 -0
  47. package/dist/cdn/chunks/pt-BR-R7ZRM3GG.js.map +7 -0
  48. package/dist/cdn/chunks/ru-FJNIMGMU.js +2 -0
  49. package/dist/cdn/chunks/ru-FJNIMGMU.js.map +7 -0
  50. package/dist/cdn/chunks/score-O2KEAYDS.js +882 -0
  51. package/dist/cdn/chunks/score-O2KEAYDS.js.map +7 -0
  52. package/dist/cdn/chunks/stats-GSXFRGYZ.js +491 -0
  53. package/dist/cdn/chunks/stats-GSXFRGYZ.js.map +7 -0
  54. package/dist/cdn/chunks/stock-53NVFLC3.js +707 -0
  55. package/dist/cdn/chunks/stock-53NVFLC3.js.map +7 -0
  56. package/dist/cdn/chunks/weather-VI2RCU4X.js +615 -0
  57. package/dist/cdn/chunks/weather-VI2RCU4X.js.map +7 -0
  58. package/dist/cdn/chunks/zh-CN-DUCWBXJP.js +2 -0
  59. package/dist/cdn/chunks/zh-CN-DUCWBXJP.js.map +7 -0
  60. package/dist/cdn/n8n-chat.js +103 -0
  61. package/dist/cdn/n8n-chat.js.map +7 -0
  62. package/dist/create-chat.d.ts +198 -0
  63. package/dist/highlight-DDyMJYBk.js +29 -0
  64. package/dist/highlight-DDyMJYBk.js.map +1 -0
  65. package/dist/highlight.d.ts +2 -0
  66. package/dist/icons.d.ts +7 -0
  67. package/dist/index.d.ts +11 -0
  68. package/dist/index.js +618 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/strings.d.ts +40 -0
  71. package/dist/style.css +378 -0
  72. package/dist/theme.css +376 -0
  73. package/package.json +82 -5
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aparté
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,334 @@
1
- # Temporary Holding Version
1
+ # @aparte/n8n-chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **n8n's chat widget, drawn by [aparté](https://apartejs.dev).** `createChat()` takes
4
+ [`@n8n/chat`](https://www.npmjs.com/package/@n8n/chat)'s options and mounts the same widget on
5
+ your n8n Chat Trigger — a button in the corner, or a block in your page. Change the import, keep
6
+ your call. And your workflow can answer with **rich cards**: an order, a booking, a product, the
7
+ weather. [See it live](https://n8n-chat.apartejs.dev).
8
+
9
+ <p>
10
+ <img src="docs/widget-card-order.png" alt="The widget open in a corner of a shop's page: the visitor asks where their order is, and the answer comes with the order's card, its items and total" width="300">
11
+ <img src="docs/widget-card-dark.png" alt="The same widget in its dark scheme, answering a booking with the booking's card" width="300">
12
+ </p>
13
+
14
+ - Rich cards your workflow writes as text: weather, order and booking, product, place, list, key
15
+ figures, stock, plan, score, media, link. n8n's own chat shows the same answer as a code block.
16
+ - Every option of `@n8n/chat` 1.43, the same defaults, the same session in the browser — and the
17
+ Chat nodes' messages and buttons of a workflow that answers through response nodes.
18
+ - Ten languages, keyboard and screen-reader access, readable contrast, a dark scheme.
19
+ - About 100 KB (brotli) on the first load, against about 465 KB.
20
+ - A handle to drive it from your page: `open`, `close`, `toggle`, `send`, `reset`, `setDisabled`,
21
+ `destroy`.
22
+ - MIT.
23
+
24
+ ## Install
25
+
26
+ ### From a CDN — no build step
27
+
28
+ ```html
29
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/style.css">
30
+ <script type="module">
31
+ import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/cdn/n8n-chat.js';
32
+
33
+ createChat({ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat' });
34
+ </script>
35
+ ```
36
+
37
+ `dist/cdn/n8n-chat.js` is one module with aparté inside it. What only some pages need is fetched
38
+ when used, from beside it: a language other than English, and the code highlighter with the first
39
+ code block. Keep the version in the URL: the widget you tested is the widget your visitors get.
40
+
41
+ ### From npm
42
+
43
+ ```bash
44
+ npm install @aparte/n8n-chat
45
+ ```
46
+
47
+ ```ts
48
+ import { createChat } from '@aparte/n8n-chat';
49
+ import '@aparte/n8n-chat/style.css';
50
+
51
+ const chat = createChat({ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat' });
52
+ chat.open();
53
+ ```
54
+
55
+ ## Coming from `@n8n/chat`
56
+
57
+ Replace the stylesheet and the import; the call stays as it is:
58
+
59
+ ```diff
60
+ - <link href="https://cdn.jsdelivr.net/npm/@n8n/chat/dist/style.css" rel="stylesheet" />
61
+ + <link href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/style.css" rel="stylesheet" />
62
+ <script type="module">
63
+ - import { createChat } from 'https://cdn.jsdelivr.net/npm/@n8n/chat/dist/chat.bundle.es.js';
64
+ + import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/cdn/n8n-chat.js';
65
+ createChat({ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat' });
66
+ </script>
67
+ ```
68
+
69
+ The session is kept where n8n's widget keeps it (`localStorage`, key `n8n-chat/sessionId`), so a
70
+ visitor keeps their conversation across the switch. `enableStreaming` needs no tuning: a streamed
71
+ answer and a whole one are both read.
72
+
73
+ ## Set up the workflow
74
+
75
+ In the **Chat Trigger** node:
76
+
77
+ 1. Turn on **Make Chat Publicly Available**. The production URL that ends in `/chat` is your
78
+ `webhookUrl`.
79
+ 2. Put your site's origin in **Allowed Origins (CORS)**.
80
+ 3. Choose how it answers, under **Response Mode**:
81
+ - **Streaming** — the AI Agent streams its answer as it writes it;
82
+ - **When Last Node Finishes** — one whole answer;
83
+ - **Using Response Nodes** — Chat nodes send the messages, and can ask questions with buttons
84
+ (see [Response nodes and buttons](#response-nodes-and-buttons)).
85
+ 4. **Publish** the workflow.
86
+
87
+ To show a visitor's earlier messages after a reload, attach a memory to the agent, set **Load
88
+ Previous Session** to **From Memory**, and connect that memory to the Chat Trigger as well: with the
89
+ memory on the agent only, n8n answers that request with an error.
90
+
91
+ ## Options
92
+
93
+ | Option | What it does | Default |
94
+ | --- | --- | --- |
95
+ | `webhookUrl` | the Chat Trigger's production URL, ending in `/chat` | required |
96
+ | `webhookConfig` | `headers` sent with every request, read each time (a refreshed token is sent); `method` is accepted, every request is a POST | `{}` |
97
+ | `target` | where it mounts: an element, or a selector | `'#n8n-chat'` |
98
+ | `mode` | `'window'` (a button in the corner) or `'embedded'` (a block in the page, filling its target; `'fullscreen'`, `@n8n/chat`'s name for it, works too) | `'window'` |
99
+ | `showWindowCloseButton` | a ✕ in the header, in window mode | `false` |
100
+ | `showWelcomeScreen` | a screen with a "New Conversation" button first | `false` |
101
+ | `loadPreviousSession` | keep the session in the browser and show its earlier messages | `true` |
102
+ | `sessionId` | use this session instead of the stored one | — |
103
+ | `chatInputKey`, `chatSessionKey` | the body fields the workflow reads | `'chatInput'`, `'sessionId'` |
104
+ | `defaultLanguage` | the language, as a tag (`'de'`, `'pt-BR'`) | `'en'` |
105
+ | `i18n` | the chrome's words by language, over the built-in ones | — |
106
+ | `locale` | the chat's own words, for a language not shipped | — |
107
+ | `initialMessages` | messages shown first, from the assistant | n8n's two |
108
+ | `messageHistory` | a conversation to show when n8n has none (text, `type: 'component'`, `transparent`) | — |
109
+ | `messageComponents` | functions that draw `type: 'component'` history messages | — |
110
+ | `metadata` | sent with every message, as `metadata` in the trigger's output | — |
111
+ | `allowFileUploads`, `allowedFilesMimeTypes` | let the person attach files, and which | `false`, any |
112
+ | `enableMessageActions` | "Repost" and "Reuse" on the person's own messages | `false` |
113
+ | `disabled` | block the input (`true`, or n8n's `{ value }`) | `false` |
114
+ | `beforeMessageSent`, `afterMessageSent` | hooks around each message | — |
115
+ | `suggestions` | questions offered above the input until the first message | — |
116
+ | `colorScheme` | `'light'`, `'dark'` or `'auto'` (the visitor's) | `'light'` |
117
+ | `fetch` | the `fetch` every request goes through | the global one |
118
+ | `enableStreaming`, `theme` | accepted for compatibility | — |
119
+
120
+ ## The handle
121
+
122
+ `createChat()` returns what your page drives it with:
123
+
124
+ ```ts
125
+ const chat = createChat({ webhookUrl });
126
+
127
+ chat.open(); // open the window (close, toggle too)
128
+ chat.send('Where is my order?'); // as the visitor; waits for an answer on its way
129
+ chat.reset(); // a new conversation, in a new session
130
+ chat.setDisabled(true); // block the input, or let the visitor type again
131
+ chat.destroy(); // remove it (unmount does the same)
132
+
133
+ chat.sessionId; // the session the conversation runs in
134
+ chat.element; // the widget's root element
135
+ ```
136
+
137
+ ## Response nodes and buttons
138
+
139
+ A Chat Trigger set to **Using Response Nodes** answers through **Chat** nodes placed in the
140
+ workflow. Each message a Chat node sends is drawn as a block of its own. A Chat node that **waits
141
+ for a written reply** gets the visitor's next message. A Chat node that **waits for an approval**
142
+ sends buttons, asked above the input with the labels you gave them; the one chosen goes back to n8n
143
+ and the workflow carries on.
144
+
145
+ **Block User Input**, on that Chat node, decides whether the visitor may write instead of choosing:
146
+ on, the answer has to be a button; off, the words reach n8n as a message and the node goes on as
147
+ not approved — as with n8n's own widget.
148
+
149
+ Up to n8n 2.45, Chat nodes run only when the Chat Trigger's **Mode** is **Hosted Chat**; an
150
+ embedded one stops with "Embedded chat is not supported". n8n 2.46 and 3.0 lift that limit and run
151
+ them in **Embedded** mode too; the widget has been tested with Hosted Chat. A button whose link
152
+ leads off your n8n is not shown.
153
+
154
+ ## Rich cards
155
+
156
+ n8n's chat carries only text, so a card travels as text: a code block whose language names the
157
+ card, holding its fields as JSON, after the sentence that answers.
158
+
159
+ ````md
160
+ Order 1001 left our warehouse two days ago.
161
+
162
+ ```card-order
163
+ { "number": "1001", "status": "shipped", "total": "68.00", "currency": "EUR",
164
+ "line_items": [{ "name": "Linen shirt", "quantity": 1, "total": "49.00" },
165
+ { "name": "Canvas tote bag", "quantity": 1, "total": "19.00" }] }
166
+ ```
167
+ ````
168
+
169
+ The widget draws the block as the card; n8n's own chat, an email or a model reading the history back
170
+ shows the sentence and the code. The cards: `weather`, `order` (a booking too, with
171
+ `"kind": "booking"`), `product`, `place`, `items`, `stats`, `stock`, `plan`, `score`, `media`,
172
+ `link`. Their fields are those of [`@aparte/plugin-cards`](https://apartejs.dev/guides/cards/), whose
173
+ readers also take the shapes shops already return (WooCommerce and Shopify orders, schema.org
174
+ products). Each card's code is fetched the first time an answer uses it.
175
+
176
+ Build the block in a **Code** node from your tool's real result rather than asking the model to
177
+ write JSON: it is exact every time, and a setting can turn it off for a chat that does not draw
178
+ cards. The [shop and booking workflows](https://n8n-chat.apartejs.dev/#workflows) do it that way.
179
+ `cards: false` shows the blocks as code.
180
+
181
+ ## The page the visitor is on
182
+
183
+ `metadata` is sent with every message and reaches the workflow as `$json.metadata`. Send the page,
184
+ and the workflow knows which product "this one" is:
185
+
186
+ ```js
187
+ createChat({
188
+ webhookUrl: '…',
189
+ metadata: { page: location.href, title: document.title },
190
+ });
191
+ ```
192
+
193
+ ## In the page, not in a corner
194
+
195
+ `mode: 'embedded'` puts the chat in your page as a block, filling its `target`, which needs a
196
+ height. `'fullscreen'`, `@n8n/chat`'s name for the same mode, works too.
197
+
198
+ ```html
199
+ <div id="support-chat" style="height: 600px"></div>
200
+ <script type="module">
201
+ createChat({ webhookUrl: '…', target: '#support-chat', mode: 'embedded' });
202
+ </script>
203
+ ```
204
+
205
+ ## Files
206
+
207
+ With `allowFileUploads`, the visitor picks, drops or pastes files, and n8n receives them as
208
+ `files`, as from n8n's widget. A file can be removed with the keyboard; a picture or a file the
209
+ visitor sent opens in a new tab.
210
+
211
+ ## Keeping bots out
212
+
213
+ A public Chat Trigger answers anyone who finds its URL, and every answer can cost you a call to
214
+ your AI model. [Cloudflare Turnstile](https://www.cloudflare.com/application-services/products/turnstile/)
215
+ — free, and usually invisible to people — lets the workflow stop a bot before the model runs. The
216
+ widget needs no option for it: `metadata` is read at each send and `beforeMessageSent` is awaited,
217
+ so the page puts a fresh token in `metadata` before every message.
218
+
219
+ 1. In Cloudflare, add a Turnstile widget for your site's hostname. You get a **site key** (for the
220
+ page) and a **secret key** (for n8n).
221
+ 2. In the page:
222
+
223
+ ```html
224
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/style.css">
225
+ <script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"></script>
226
+ <div id="turnstile"></div>
227
+ <script type="module">
228
+ import { createChat } from 'https://cdn.jsdelivr.net/npm/@aparte/n8n-chat@0.2.0/dist/cdn/n8n-chat.js';
229
+
230
+ // A Turnstile token is single-use and lasts five minutes: ask for a new one before each message.
231
+ let widgetId;
232
+ let pending;
233
+ function turnstileToken() {
234
+ return new Promise((resolve, reject) => {
235
+ pending = { resolve, reject };
236
+ if (widgetId === undefined) {
237
+ widgetId = turnstile.render('#turnstile', {
238
+ sitekey: '<your site key>',
239
+ execution: 'execute',
240
+ appearance: 'interaction-only', // shown only when Cloudflare needs the visitor to click
241
+ callback: (token) => pending.resolve(token),
242
+ 'error-callback': () => pending.reject(new Error('Turnstile could not check this visitor')),
243
+ });
244
+ } else {
245
+ turnstile.reset(widgetId);
246
+ }
247
+ turnstile.execute('#turnstile');
248
+ });
249
+ }
250
+
251
+ const metadata = {};
252
+ createChat({
253
+ webhookUrl: 'https://your-n8n.example.com/webhook/<id>/chat',
254
+ metadata,
255
+ beforeMessageSent: async () => {
256
+ metadata.turnstileToken = await turnstileToken();
257
+ },
258
+ });
259
+ </script>
260
+ ```
261
+
262
+ 3. In the workflow, between the Chat Trigger and your agent:
263
+ - an **HTTP Request** node: `POST https://challenges.cloudflare.com/turnstile/v0/siteverify`,
264
+ body as JSON:
265
+ `{{ JSON.stringify({ secret: '<your secret key>', response: $json.metadata?.turnstileToken ?? '' }) }}`
266
+ (anyone who can open the workflow can read the secret there);
267
+ - an **If** node on `{{ $json.success }}` is true;
268
+ - on its true branch, an **Edit Fields (Set)** node in JSON mode that gives the trigger's message
269
+ back, so the agent and its memory read `chatInput` and `sessionId` as before:
270
+ `{{ JSON.stringify($('When chat message received').item.json) }}`;
271
+ - then your agent. The false branch ends there: nothing reaches the model.
272
+
273
+ When Cloudflare refuses a visitor, the widget shows its usual "couldn't answer" message and nothing
274
+ is sent. A visitor's reply to a waiting Chat node goes over the execution's WebSocket, which was
275
+ opened by a checked message, so it needs no token. A bot that calls the webhook directly still
276
+ starts an execution, a short one (on n8n Cloud, executions count against your plan); only a proxy in
277
+ front of n8n stops it earlier. Checked on n8n 2.45.7 with Cloudflare's test keys, text messages
278
+ only: with file uploads, check that your agent still receives the files after the Set node.
279
+
280
+ ## Languages
281
+
282
+ English, French, Spanish, Portuguese (Brazil), German, Italian, Russian, Japanese, Korean and
283
+ Chinese (Simplified). A page downloads only the language it uses. Set `defaultLanguage`; override
284
+ any word of the header or the input with `i18n`; give a whole `locale` for another language.
285
+
286
+ ## Look
287
+
288
+ It wears n8n's look by default and reads n8n's main `--chat--*` variables — colors, fonts, radii,
289
+ the window's size, the button — so a page that themed n8n's widget keeps most of its theme:
290
+
291
+ ```css
292
+ :root {
293
+ --chat--color--primary: #e74266;
294
+ --chat--color--secondary: #178272;
295
+ --chat--window--width: 420px;
296
+ }
297
+ ```
298
+
299
+ CSS written against n8n's `.chat-*` classes does not carry over; the variables do.
300
+ `colorScheme: 'dark'` (or `'auto'`) gives the dark scheme. `@aparte/n8n-chat/theme.css` is the n8n
301
+ look alone, for a chat you compose yourself with
302
+ [`@aparte/runner-n8n`](https://apartejs.dev/providers/agent/n8n/) and aparté's React, Vue, Svelte
303
+ or Angular components, inside an `.aparte-n8n` element.
304
+
305
+ ## Compared with `@n8n/chat`
306
+
307
+ | | `@n8n/chat` 1.43 | `@aparte/n8n-chat` |
308
+ | --- | --- | --- |
309
+ | Drive it from the page | — | `open`, `close`, `toggle`, `send`, `reset`, `setDisabled`, `destroy` |
310
+ | A new conversation | not until the browser's storage is cleared | `reset()` |
311
+ | A tool's steps after a reload | bubbles with raw JSON | left out, as while chatting |
312
+ | An error | the raw message | a sentence in the visitor's language, the workflow's own words under it, what to fix on the console |
313
+ | Languages | English | ten, loaded one at a time |
314
+ | Keyboard and screen reader | buttons without names | named controls, a labelled window, a modal sheet on a phone |
315
+ | Contrast of the visitor's bubble | 2.55:1 | 4.7:1 (WCAG AA) |
316
+ | Dark scheme | — | ✓ |
317
+ | Rich cards | the JSON as text | drawn: order, booking, product, weather… |
318
+ | Weight, first load (brotli) | ~465 KB | ~100 KB, +~103 KB with the first code block |
319
+ | License | Sustainable Use License | MIT |
320
+
321
+ ## Versions
322
+
323
+ The widget depends on **exact** versions of aparté's packages, and moves to a newer aparté only in
324
+ a release of its own. Pin the widget's version in a CDN URL and in your `package.json`, and what you
325
+ tested is what your visitors run.
326
+
327
+ ## Links
328
+
329
+ - [n8n-chat.apartejs.dev](https://n8n-chat.apartejs.dev) — the live demo, and workflows to start from.
330
+ - [aparté](https://apartejs.dev) — the library it is built with.
331
+ - [`@aparte/runner-n8n`](https://apartejs.dev/providers/agent/n8n/) — the n8n protocol alone, to put
332
+ an n8n workflow behind a chat you compose yourself.
333
+
334
+ MIT © Paul Richez
@@ -0,0 +1,3 @@
1
+ import type { AparteConfig } from '@aparte/core';
2
+ /** Draw the card blocks in this widget's answers. Returns the function that stops it. */
3
+ export declare const setupCards: (config: AparteConfig) => (() => void);
@@ -0,0 +1,2 @@
1
+ import{a as i,b as p,i as l,j as g,p as e}from"./chunk-IWAJFJNA.js";var _="M12 2.6l2.9 5.9 6.5.95-4.7 4.6 1.1 6.5L12 17.5l-5.8 3.05 1.1-6.5-4.7-4.6 6.5-.95z",h=`<svg viewBox="0 0 120 24" xmlns="http://www.w3.org/2000/svg">${[0,24,48,72,96].map(a=>`<path transform="translate(${a} 0)" d="${_}"/>`).join("")}</svg>`;function u(a,c,{max:t=5,count:s,starsOnly:f=!1}={}){if(c===void 0||!Number.isFinite(c)||t<=0)return null;let d=Math.max(0,Math.min(t,c)),m=i("span",{class:"aparte-rich-card__stars",attrs:{"aria-hidden":"true"}},p(h,"aparte-rich-card__stars-base"),p(h,"aparte-rich-card__stars-fill"));m.style.setProperty("--aparte-rich-card-rating",`${d/t*100}%`);let n=i("span",{class:"aparte-rich-card__rating",attrs:{role:"img"}},m),o=r=>e(a.config,r,{maximumFractionDigits:1});if(!f){let r=i("span",{class:"aparte-rich-card__rating-value",attrs:{"aria-hidden":"true"}});a.bind(r,()=>o(d)),n.append(r)}if(s!==void 0&&Number.isFinite(s)){let r=i("span",{class:"aparte-rich-card__rating-count",attrs:{"aria-hidden":"true"}});a.bind(r,()=>`(${e(a.config,s,{notation:s>=1e4?"compact":"standard"})})`),n.append(r)}return a.bind(n,()=>{let r=l(a.config,"cardsRating",g.cardsRating,{value:o(d),max:o(t)});return s!==void 0&&Number.isFinite(s)?`${r}, ${l(a.config,"cardsReviews",g.cardsReviews,{count:e(a.config,s)})}`:r},"aria-label"),n}export{u as a};
2
+ //# sourceMappingURL=chunk-7JR7KL6J.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../node_modules/.pnpm/@aparte+plugin-cards@0.29.2_@aparte+core@0.29.2/node_modules/@aparte/plugin-cards/src/kit/rating.ts"],
4
+ "sourcesContent": ["/**\n * A rating: stars filled to the value, the value, and how many reviews it averages.\n *\n * Two rows of the same five stars, the coloured one clipped to the value's width, so\n * 4.6 shows six tenths of the fifth star. Read aloud as one sentence (\"Rated 4.6 out\n * of 5, 1,284 reviews\"); the stars themselves are hidden from a screen reader.\n */\nimport type { CardContext } from './define.js';\nimport { el, glyph } from './dom.js';\nimport { formatNumber } from './format.js';\nimport { KIT_WORDS, word } from './strings.js';\n\nconst STAR = 'M12 2.6l2.9 5.9 6.5.95-4.7 4.6 1.1 6.5L12 17.5l-5.8 3.05 1.1-6.5-4.7-4.6 6.5-.95z';\nconst FIVE = `<svg viewBox=\"0 0 120 24\" xmlns=\"http://www.w3.org/2000/svg\">${[0, 24, 48, 72, 96].map((x) => `<path transform=\"translate(${x} 0)\" d=\"${STAR}\"/>`).join('')}</svg>`; // safe-attr: this package's own glyph constants and loop numbers, never data // safe-text: this package's own SVG, built from its glyph constants\n\nexport interface RatingOptions {\n /** The scale's top (5 by default). */\n max?: number;\n /** How many reviews the value averages. */\n count?: number;\n /** Leave the number out and keep the stars. */\n starsOnly?: boolean;\n}\n\n/** The rating as an element, or `null` for no value. */\nexport function rating(ctx: CardContext, value: number | undefined, { max = 5, count, starsOnly = false }: RatingOptions = {}): HTMLElement | null {\n if (value === undefined || !Number.isFinite(value) || max <= 0) return null;\n const clamped = Math.max(0, Math.min(max, value));\n const stars = el('span', { class: 'aparte-rich-card__stars', attrs: { 'aria-hidden': 'true' } },\n glyph(FIVE, 'aparte-rich-card__stars-base'),\n glyph(FIVE, 'aparte-rich-card__stars-fill'));\n stars.style.setProperty('--aparte-rich-card-rating', `${(clamped / max) * 100}%`);\n const node = el('span', { class: 'aparte-rich-card__rating', attrs: { role: 'img' } }, stars);\n const shown = (n: number) => formatNumber(ctx.config, n, { maximumFractionDigits: 1 });\n if (!starsOnly) {\n const number = el('span', { class: 'aparte-rich-card__rating-value', attrs: { 'aria-hidden': 'true' } });\n ctx.bind(number, () => shown(clamped));\n node.append(number);\n }\n if (count !== undefined && Number.isFinite(count)) {\n const reviews = el('span', { class: 'aparte-rich-card__rating-count', attrs: { 'aria-hidden': 'true' } });\n ctx.bind(reviews, () => `(${formatNumber(ctx.config, count, { notation: count >= 10_000 ? 'compact' : 'standard' })})`);\n node.append(reviews);\n }\n ctx.bind(node, () => {\n const sentence = word(ctx.config, 'cardsRating', KIT_WORDS.cardsRating, { value: shown(clamped), max: shown(max) });\n return count !== undefined && Number.isFinite(count)\n ? `${sentence}, ${word(ctx.config, 'cardsReviews', KIT_WORDS.cardsReviews, { count: formatNumber(ctx.config, count) })}`\n : sentence;\n }, 'aria-label');\n return node;\n}\n"],
5
+ "mappings": "oEAYA,IAAMA,EAAO,oFACPC,EAAO,gEAAgE,CAAC,EAAG,GAAI,GAAI,GAAI,EAAE,EAAE,IAAKC,GAAM,8BAA8BA,CAAC,WAAWF,CAAI,KAAK,EAAE,KAAK,EAAE,CAAC,SAYlK,SAASG,EAAOC,EAAkBC,EAA2B,CAAE,IAAAC,EAAM,EAAG,MAAAC,EAAO,UAAAC,EAAY,EAAA,EAAyB,CAAA,EAAwB,CAC/I,GAAIH,IAAU,QAAa,CAAC,OAAO,SAASA,CAAK,GAAKC,GAAO,EAAG,OAAO,KACvE,IAAMG,EAAU,KAAK,IAAI,EAAG,KAAK,IAAIH,EAAKD,CAAK,CAAC,EAC1CK,EAAQC,EAAG,OAAQ,CAAE,MAAO,0BAA2B,MAAO,CAAE,cAAe,MAAA,CAAO,EACxFC,EAAMX,EAAM,8BAA8B,EAC1CW,EAAMX,EAAM,8BAA8B,CAAA,EAC9CS,EAAM,MAAM,YAAY,4BAA6B,GAAID,EAAUH,EAAO,GAAG,GAAG,EAChF,IAAMO,EAAOF,EAAG,OAAQ,CAAE,MAAO,2BAA4B,MAAO,CAAE,KAAM,KAAA,CAAM,EAAKD,CAAK,EACtFI,EAASC,GAAcC,EAAaZ,EAAI,OAAQW,EAAG,CAAE,sBAAuB,CAAA,CAAG,EACrF,GAAI,CAACP,EAAW,CACZ,IAAMS,EAASN,EAAG,OAAQ,CAAE,MAAO,iCAAkC,MAAO,CAAE,cAAe,MAAA,CAAA,CAAU,EACvGP,EAAI,KAAKa,EAAQ,IAAMH,EAAML,CAAO,CAAC,EACrCI,EAAK,OAAOI,CAAM,CACtB,CACA,GAAIV,IAAU,QAAa,OAAO,SAASA,CAAK,EAAG,CAC/C,IAAMW,EAAUP,EAAG,OAAQ,CAAE,MAAO,iCAAkC,MAAO,CAAE,cAAe,MAAA,CAAA,CAAU,EACxGP,EAAI,KAAKc,EAAS,IAAM,IAAIF,EAAaZ,EAAI,OAAQG,EAAO,CAAE,SAAUA,GAAS,IAAS,UAAY,UAAA,CAAY,CAAC,GAAG,EACtHM,EAAK,OAAOK,CAAO,CACvB,CACA,OAAAd,EAAI,KAAKS,EAAM,IAAM,CACjB,IAAMM,EAAWC,EAAKhB,EAAI,OAAQ,cAAeiB,EAAU,YAAa,CAAE,MAAOP,EAAML,CAAO,EAAG,IAAKK,EAAMR,CAAG,CAAA,CAAG,EAClH,OAAOC,IAAU,QAAa,OAAO,SAASA,CAAK,EAC7C,GAAGY,CAAQ,KAAKC,EAAKhB,EAAI,OAAQ,eAAgBiB,EAAU,aAAc,CAAE,MAAOL,EAAaZ,EAAI,OAAQG,CAAK,CAAA,CAAG,CAAC,GACpHY,CACV,EAAG,YAAY,EACRN,CACX",
6
+ "names": ["STAR", "FIVE", "x", "rating", "ctx", "value", "max", "count", "starsOnly", "clamped", "stars", "el", "glyph", "node", "shown", "n", "formatNumber", "number", "reviews", "sentence", "word", "KIT_WORDS"]
7
+ }
@@ -0,0 +1,2 @@
1
+ var f="http://www.w3.org/2000/svg";function k(u,{pad:c=.15,range:t}={}){let s=u.filter(Number.isFinite);if(s.length===0)return{line:"",area:"",points:[]};let l=s.length===1?[s[0],s[0]]:s,i=t?t[0]:Math.min(...s),x=(t?t[1]:Math.max(...s))-i,r=40,F=100/(l.length-1),e=l.map((n,d)=>[d*F,x===0?r/2:r-(c*r+(n-i)/x*(r-2*c*r))]),h=`M${e[0][0].toFixed(2)} ${e[0][1].toFixed(2)}`;for(let n=0;n<e.length-1;n++){let d=e[n-1]??e[n],p=e[n],o=e[n+1],$=e[n+2]??o,m=[p[0]+(o[0]-d[0])/6,p[1]+(o[1]-d[1])/6],b=[o[0]-($[0]-p[0])/6,o[1]-($[1]-p[1])/6];h+=` C${m[0].toFixed(2)} ${m[1].toFixed(2)} ${b[0].toFixed(2)} ${b[1].toFixed(2)} ${o[0].toFixed(2)} ${o[1].toFixed(2)}`}let A=e[e.length-1],g=`${h} L${A[0].toFixed(2)} ${r} L${e[0][0].toFixed(2)} ${r} Z`;return{line:h,area:g,points:e}}function v(u,c={}){let t=document.createElementNS(f,"svg");t.setAttribute("viewBox","0 0 100 40"),t.setAttribute("preserveAspectRatio","none"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),t.classList.add("aparte-rich-card__sparkline");for(let a of c.className?.split(/\s+/)??[])a&&t.classList.add(a);let{line:s,area:l}=k(u,c);if(!s)return t;if(c.area){let a=document.createElementNS(f,"path");a.setAttribute("d",l),a.setAttribute("class","aparte-rich-card__sparkline-area"),t.append(a)}let i=document.createElementNS(f,"path");return i.setAttribute("d",s),i.setAttribute("class","aparte-rich-card__sparkline-line"),i.setAttribute("vector-effect","non-scaling-stroke"),t.append(i),t}export{v as a};
2
+ //# sourceMappingURL=chunk-CZ5742JA.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../node_modules/.pnpm/@aparte+plugin-cards@0.29.2_@aparte+core@0.29.2/node_modules/@aparte/plugin-cards/src/kit/sparkline.ts"],
4
+ "sourcesContent": ["/**\n * A small line chart in SVG, with no dependency: the temperature over the next hours, a\n * price over a day. Built with `createElementNS` from numbers only, so a tool's values\n * never reach a parser. Stretched to its box (`preserveAspectRatio=\"none\"`), the stroke\n * kept at its width by `vector-effect`.\n */\nconst SVG = 'http://www.w3.org/2000/svg';\n\nexport interface SparklineOptions {\n /** Extra class on the `<svg>`. */\n className?: string;\n /** Fill the area under the line (a gradient from the stroke's colour, in the sheet). */\n area?: boolean;\n /** Padding above and below the line, as a share of the height (0.15 by default). */\n pad?: number;\n /** The value range to scale against, when several charts must share one. */\n range?: [number, number];\n}\n\n/** The points of a smooth line through `values`, in a 100 × 40 box. */\nexport function sparklinePath(values: number[], { pad = 0.15, range }: SparklineOptions = {}): { line: string; area: string; points: Array<[number, number]> } {\n // A gap (`null`, `NaN`) is left out: written into the path it would stop the drawing there.\n const finite = values.filter(Number.isFinite);\n if (finite.length === 0) return { line: '', area: '', points: [] };\n // One value is a level, drawn flat across the box: a single point would draw nothing.\n const series = finite.length === 1 ? [finite[0]!, finite[0]!] : finite;\n const lo = range ? range[0] : Math.min(...finite);\n const hi = range ? range[1] : Math.max(...finite);\n const span = hi - lo;\n const h = 40;\n const step = 100 / (series.length - 1);\n // A series that does not move is a flat line through the middle, not along the floor.\n const points = series.map((v, i): [number, number] => [\n i * step,\n span === 0 ? h / 2 : h - (pad * h + ((v - lo) / span) * (h - 2 * pad * h)),\n ]);\n // A Catmull-Rom curve through the points, written as cubic Béziers.\n let line = `M${points[0]![0].toFixed(2)} ${points[0]![1].toFixed(2)}`;\n for (let i = 0; i < points.length - 1; i++) {\n const p0 = points[i - 1] ?? points[i]!;\n const p1 = points[i]!;\n const p2 = points[i + 1]!;\n const p3 = points[i + 2] ?? p2;\n const c1: [number, number] = [p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6];\n const c2: [number, number] = [p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6];\n line += ` C${c1[0].toFixed(2)} ${c1[1].toFixed(2)} ${c2[0].toFixed(2)} ${c2[1].toFixed(2)} ${p2[0].toFixed(2)} ${p2[1].toFixed(2)}`;\n }\n const last = points[points.length - 1]!;\n const area = `${line} L${last[0].toFixed(2)} ${h} L${points[0]![0].toFixed(2)} ${h} Z`;\n return { line, area, points };\n}\n\n/** The chart as an `<svg>`; decorative (`aria-hidden`), so put the numbers in text beside it. */\nexport function sparkline(values: number[], options: SparklineOptions = {}): SVGSVGElement {\n const svg = document.createElementNS(SVG, 'svg');\n svg.setAttribute('viewBox', '0 0 100 40');\n svg.setAttribute('preserveAspectRatio', 'none');\n svg.setAttribute('aria-hidden', 'true');\n svg.setAttribute('focusable', 'false');\n svg.classList.add('aparte-rich-card__sparkline');\n // The caller's own class (its own prefix is its business), added beside ours.\n for (const name of options.className?.split(/\\s+/) ?? []) if (name) svg.classList.add(name);\n const { line, area } = sparklinePath(values, options);\n if (!line) return svg;\n if (options.area) {\n const fill = document.createElementNS(SVG, 'path');\n fill.setAttribute('d', area);\n fill.setAttribute('class', 'aparte-rich-card__sparkline-area');\n svg.append(fill);\n }\n const stroke = document.createElementNS(SVG, 'path');\n stroke.setAttribute('d', line);\n stroke.setAttribute('class', 'aparte-rich-card__sparkline-line');\n stroke.setAttribute('vector-effect', 'non-scaling-stroke');\n svg.append(stroke);\n return svg;\n}\n"],
5
+ "mappings": "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",
6
+ "names": ["SVG", "sparklinePath", "values", "pad", "range", "finite", "series", "lo", "span", "h", "step", "points", "v", "i", "line", "p0", "p1", "p2", "p3", "c1", "c2", "last", "area", "sparkline", "options", "svg", "name", "fill", "stroke"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{a as n}from"./chunk-IWAJFJNA.js";function p(a,{name:s,options:i,value:c,label:l}){if(!a.live||i.length===0)return null;let r=n("div",{class:"aparte-rich-card__segmented",attrs:{role:"group"}});l&&a.bind(r,l,"aria-label");for(let e of i){let d=e.value===c,t=n("button",{class:"aparte-rich-card__segment",attrs:{type:"button","aria-pressed":d?"true":"false","data-card-key":`${s}:${e.value}`}});typeof e.label=="function"?a.bind(t,e.label):t.textContent=e.label,t.addEventListener("click",()=>{if(t.getAttribute("aria-pressed")!=="true"){for(let u of r.querySelectorAll(".aparte-rich-card__segment"))u.setAttribute("aria-pressed",u===t?"true":"false");a.change(s,e.value)}}),r.append(t)}return r}export{p as a};
2
+ //# sourceMappingURL=chunk-IPWLCOPM.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../node_modules/.pnpm/@aparte+plugin-cards@0.29.2_@aparte+core@0.29.2/node_modules/@aparte/plugin-cards/src/kit/controls.ts"],
4
+ "sourcesContent": ["/**\n * Controls a card can carry: a row of choices, a switch, a slider. Each reports through\n * `ctx.change(name, value)`, so the card fires `aparte-card-change` and the app's\n * `onChange` answers with new data, drawn in place — a stock chart's range, a light's\n * brightness.\n *\n * A control is drawn only when something will answer it (`ctx.live`): without an\n * `onChange`, a button that does nothing would be a promise the card cannot keep\n * (ratified decision #8). Each control carries a `data-card-key`, so a redraw puts the\n * focus back on the control that was pressed.\n */\nimport type { CardContext } from './define.js';\nimport { el } from './dom.js';\n\nexport interface SegmentedOptions {\n /** The control's name in the change (`range`). */\n name: string;\n /** The choices; a label is a string or a function read again on a language switch. */\n options: Array<{ value: string; label: string | (() => string) }>;\n /** The choice in force. */\n value?: string;\n /** The group's accessible name. */\n label?: () => string;\n}\n\n/** A row of choices, one pressed (`aria-pressed`). `null` when nothing would answer it. */\nexport function segmented(ctx: CardContext, { name, options, value, label }: SegmentedOptions): HTMLElement | null {\n if (!ctx.live || options.length === 0) return null;\n const group = el('div', { class: 'aparte-rich-card__segmented', attrs: { role: 'group' } });\n if (label) ctx.bind(group, label, 'aria-label');\n for (const option of options) {\n const pressed = option.value === value;\n const button = el('button', {\n class: 'aparte-rich-card__segment',\n attrs: { type: 'button', 'aria-pressed': pressed ? 'true' : 'false', 'data-card-key': `${name}:${option.value}` },\n });\n if (typeof option.label === 'function') ctx.bind(button, option.label);\n else button.textContent = option.label;\n button.addEventListener('click', () => {\n if (button.getAttribute('aria-pressed') === 'true') return;\n // Pressed at once, before the app answers: a second press reads what was chosen.\n for (const other of group.querySelectorAll('.aparte-rich-card__segment')) other.setAttribute('aria-pressed', other === button ? 'true' : 'false');\n ctx.change(name, option.value);\n });\n group.append(button);\n }\n return group;\n}\n\nexport interface ToggleOptions {\n name: string;\n checked: boolean;\n /** What it switches (\"Living-room light\"). */\n label: () => string;\n}\n\n/** A switch (`role=\"switch\"`). `null` when nothing would answer it. */\nexport function toggle(ctx: CardContext, { name, checked, label }: ToggleOptions): HTMLElement | null {\n if (!ctx.live) return null;\n const button = el('button', {\n class: 'aparte-rich-card__toggle',\n attrs: { type: 'button', role: 'switch', 'aria-checked': checked ? 'true' : 'false', 'data-card-key': name },\n }, el('span', { class: 'aparte-rich-card__toggle-thumb', attrs: { 'aria-hidden': 'true' } }));\n ctx.bind(button, label, 'aria-label');\n button.addEventListener('click', () => {\n // Flipped at once, before the app answers: a second click before the answer flips it\n // back, rather than sending the same state twice.\n const next = button.getAttribute('aria-checked') !== 'true';\n button.setAttribute('aria-checked', next ? 'true' : 'false');\n ctx.change(name, next);\n });\n return button;\n}\n\nexport interface SliderOptions {\n name: string;\n value: number;\n min?: number;\n max?: number;\n step?: number;\n label: () => string;\n /** How the value reads beside it, and to a screen reader (\"60 %\"). */\n format?: (value: number) => string;\n}\n\n/**\n * A slider: the value beside it follows while it moves, the change is reported once it is\n * let go (`change`, not `input`) — one request for a drag, not one per pixel.\n */\nexport function slider(ctx: CardContext, { name, value, min = 0, max = 100, step = 1, label, format = String }: SliderOptions): HTMLElement | null {\n if (!ctx.live) return null;\n const input = el('input', {\n class: 'aparte-rich-card__slider-input',\n attrs: { type: 'range', min, max, step, value, 'data-card-key': name },\n });\n const shown = el('output', { class: 'aparte-rich-card__slider-value' });\n const name_ = el('span', { class: 'aparte-rich-card__slider-label' });\n ctx.bind(name_, label);\n ctx.bind(input, label, 'aria-label');\n const paint = (v: number) => {\n shown.textContent = format(v);\n input.setAttribute('aria-valuetext', format(v));\n };\n ctx.bind(shown, () => format(Number(input.value)));\n paint(value);\n input.addEventListener('input', () => paint(Number(input.value)));\n input.addEventListener('change', () => ctx.change(name, Number(input.value)));\n return el('label', { class: 'aparte-rich-card__slider' }, name_, input, shown);\n}\n"],
5
+ "mappings": "wCA0BO,SAASA,EAAUC,EAAkB,CAAE,KAAAC,EAAM,QAAAC,EAAS,MAAAC,EAAO,MAAAC,CAAA,EAA+C,CAC/G,GAAI,CAACJ,EAAI,MAAQE,EAAQ,SAAW,EAAG,OAAO,KAC9C,IAAMG,EAAQC,EAAG,MAAO,CAAE,MAAO,8BAA+B,MAAO,CAAE,KAAM,OAAA,CAAA,CAAW,EACtFF,GAAOJ,EAAI,KAAKK,EAAOD,EAAO,YAAY,EAC9C,QAAWG,KAAUL,EAAS,CAC1B,IAAMM,EAAUD,EAAO,QAAUJ,EAC3BM,EAASH,EAAG,SAAU,CACxB,MAAO,4BACP,MAAO,CAAE,KAAM,SAAU,eAAgBE,EAAU,OAAS,QAAS,gBAAiB,GAAGP,CAAI,IAAIM,EAAO,KAAK,EAAA,CAAG,CACnH,EACG,OAAOA,EAAO,OAAU,WAAAP,EAAgB,KAAKS,EAAQF,EAAO,KAAK,EAChEE,EAAO,YAAcF,EAAO,MACjCE,EAAO,iBAAiB,QAAS,IAAM,CACnC,GAAIA,EAAO,aAAa,cAAc,IAAM,OAE5C,SAAWC,KAASL,EAAM,iBAAiB,4BAA4B,EAAGK,EAAM,aAAa,eAAgBA,IAAUD,EAAS,OAAS,OAAO,EAChJT,EAAI,OAAOC,EAAMM,EAAO,KAAK,EACjC,CAAC,EACDF,EAAM,OAAOI,CAAM,CACvB,CACA,OAAOJ,CACX",
6
+ "names": ["segmented", "ctx", "name", "options", "value", "label", "group", "el", "option", "pressed", "button", "other"]
7
+ }