@napplet/sdk 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,371 @@
1
+ # @napplet/sdk
2
+
3
+ > Named TypeScript exports for napplet developers using a bundler. Wraps `window.napplet` at call time.
4
+
5
+ ## Getting Started
6
+
7
+ ### Prerequisites
8
+
9
+ - `@napplet/shim` must be imported (side-effect) to install `window.napplet` before SDK methods are called
10
+ - A shell host running a napplet protocol shell implementation
11
+
12
+ ### How It Works
13
+
14
+ 1. Import `@napplet/shim` in your entry point to install the `window.napplet` global
15
+ 2. Import named exports from `@napplet/sdk` -- `relay`, `ipc`, `storage`, `keys`
16
+ 3. Each SDK method delegates to its `window.napplet.*` counterpart at call time
17
+ 4. If `window.napplet` is not installed when a method is called, a descriptive error is thrown
18
+
19
+ ### Installation
20
+
21
+ ```bash
22
+ npm install @napplet/sdk @napplet/shim
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```ts
28
+ import '@napplet/shim';
29
+ import { relay, ipc, storage, keys, media, notify, config, type NostrEvent } from '@napplet/sdk';
30
+
31
+ // Subscribe to kind 1 notes
32
+ const sub = relay.subscribe(
33
+ { kinds: [1], limit: 20 },
34
+ (event) => console.log('New note:', event.content),
35
+ () => console.log('End of stored events'),
36
+ );
37
+
38
+ // Publish a signed note
39
+ const signed = await relay.publish({
40
+ kind: 1,
41
+ content: 'Hello from my napplet!',
42
+ tags: [],
43
+ created_at: Math.floor(Date.now() / 1000),
44
+ });
45
+
46
+ // Inter-pane messaging
47
+ ipc.emit('chat:message', [], JSON.stringify({ text: 'hi' }));
48
+ const ipcSub = ipc.on('bot:response', (payload) => {
49
+ console.log('Bot says:', payload);
50
+ });
51
+
52
+ // Scoped storage
53
+ await storage.setItem('theme', 'dark');
54
+ const theme = await storage.getItem('theme'); // 'dark'
55
+
56
+ // Register keyboard action
57
+ const result = await keys.registerAction({
58
+ id: 'editor.save', label: 'Save', defaultKey: 'Ctrl+S',
59
+ });
60
+
61
+ // Listen for bound key locally
62
+ const keySub = keys.onAction('editor.save', () => {
63
+ console.log('Save triggered!');
64
+ });
65
+
66
+ // Create a media session
67
+ const { sessionId } = await media.createSession({
68
+ title: 'My Song', artist: 'The Artist',
69
+ });
70
+ media.reportState(sessionId, { status: 'playing', position: 42.5, duration: 240 });
71
+
72
+ // Send a notification
73
+ const { notificationId } = await notify.send({
74
+ title: 'Task complete', body: 'Build succeeded', priority: 'normal',
75
+ });
76
+ notify.badge(1);
77
+
78
+ // Read per-napplet config (shell-validated + defaulted)
79
+ const values = await config.get();
80
+ console.log('Current theme:', values.theme);
81
+
82
+ // Subscribe to live config updates
83
+ const configSub = config.subscribe((v) => {
84
+ applyTheme(v.theme);
85
+ });
86
+
87
+ // Deep-link settings UI
88
+ config.openSettings({ section: 'appearance' });
89
+
90
+ // Clean up
91
+ sub.close();
92
+ ipcSub.close();
93
+ keySub.close();
94
+ configSub.close();
95
+ ```
96
+
97
+ ## API Reference
98
+
99
+ ### `relay`
100
+
101
+ Relay operations through the shell's relay pool. Mirrors `window.napplet.relay`.
102
+
103
+ | Method | Returns | Description |
104
+ |--------|---------|-------------|
105
+ | `subscribe(filters, onEvent, onEose, options?)` | `Subscription` | Open a live relay subscription through the shell's relay pool |
106
+ | `publish(template, options?)` | `Promise<NostrEvent>` | Send event template to the shell for signing and broadcast |
107
+ | `publishEncrypted(template, recipient, encryption?)` | `Promise<NostrEvent>` | Send event template for encryption, signing, and broadcast |
108
+ | `query(filters)` | `Promise<NostrEvent[]>` | One-shot query: subscribe, collect until EOSE, resolve |
109
+
110
+ ### `ipc`
111
+
112
+ Inter-napplet communication between napplets. Mirrors `window.napplet.ipc`.
113
+
114
+ Messages are sent as JSON envelope objects (`{ type: 'ifc.emit', topic, payload }`) and received as
115
+ (`{ type: 'ifc.event', topic, payload, sender }`).
116
+
117
+ | Method | Returns | Description |
118
+ |--------|---------|-------------|
119
+ | `emit(topic, extraTags?, content?)` | `void` | Broadcast an IFC event to other napplets via the shell |
120
+ | `on(topic, callback)` | `{ close(): void }` | Subscribe to IFC events on a topic |
121
+
122
+ ### `storage`
123
+
124
+ Sandboxed key-value storage. Mirrors `window.napplet.storage`. 512 KB quota per napplet.
125
+
126
+ | Method | Returns | Description |
127
+ |--------|---------|-------------|
128
+ | `getItem(key)` | `Promise<string \| null>` | Retrieve a stored value |
129
+ | `setItem(key, value)` | `Promise<void>` | Store a key-value pair |
130
+ | `removeItem(key)` | `Promise<void>` | Remove a stored key |
131
+ | `keys()` | `Promise<string[]>` | List all stored keys |
132
+
133
+ ### `media`
134
+
135
+ Media session control. Mirrors `window.napplet.media`.
136
+
137
+ | Method | Returns | Description |
138
+ |--------|---------|-------------|
139
+ | `createSession(metadata?)` | `Promise<{ sessionId }>` | Create a new media session with optional metadata |
140
+ | `updateSession(sessionId, metadata)` | `void` | Update metadata for an existing session |
141
+ | `destroySession(sessionId)` | `void` | Destroy a session |
142
+ | `reportState(sessionId, state)` | `void` | Report playback state |
143
+ | `reportCapabilities(sessionId, actions)` | `void` | Declare supported media actions |
144
+ | `onCommand(sessionId, callback)` | `{ close(): void }` | Listen for shell media commands |
145
+ | `onControls(sessionId, callback)` | `{ close(): void }` | Listen for the shell's supported control list |
146
+
147
+ ### `notify`
148
+
149
+ Shell-rendered notifications. Mirrors `window.napplet.notify`.
150
+
151
+ | Method | Returns | Description |
152
+ |--------|---------|-------------|
153
+ | `send(notification)` | `Promise<{ notificationId }>` | Send a notification to the shell |
154
+ | `dismiss(notificationId)` | `void` | Dismiss a notification |
155
+ | `badge(count)` | `void` | Set badge count (0 to clear) |
156
+ | `registerChannel(channel)` | `void` | Register a notification channel |
157
+ | `requestPermission(channel?)` | `Promise<{ granted }>` | Request permission to send notifications |
158
+ | `onAction(callback)` | `{ close(): void }` | Listen for action button clicks |
159
+ | `onClicked(callback)` | `{ close(): void }` | Listen for notification body clicks |
160
+ | `onDismissed(callback)` | `{ close(): void }` | Listen for dismissals |
161
+ | `onControls(callback)` | `{ close(): void }` | Listen for shell's notification capabilities |
162
+
163
+ ### `config`
164
+
165
+ Per-napplet declarative configuration (NUB-CONFIG). Mirrors `window.napplet.config`.
166
+
167
+ | Method | Returns | Description |
168
+ |--------|---------|-------------|
169
+ | `get()` | `Promise<Record<string, unknown>>` | One-shot snapshot of validated + defaulted config values |
170
+ | `subscribe(callback)` | `{ close(): void }` | Live push stream (initial snapshot + updates on change) |
171
+ | `openSettings(options?)` | `void` | Open shell's settings UI, optionally deep-linked to `x-napplet-section` |
172
+ | `registerSchema(schema, version?)` | `Promise<void>` | Runtime schema registration (escape hatch; prefer vite-plugin configSchema) |
173
+ | `onSchemaError(callback)` | `() => void` | Listen for `config.schemaError` pushes (returns plain teardown fn) |
174
+ | `schema` (accessor) | `Record<string, unknown> \| null` | Readonly current schema |
175
+
176
+ ### FromSchema type inference (NUB-CONFIG)
177
+
178
+ `json-schema-to-ts` is declared as an optional `peerDependency` of `@napplet/nub-config`. Install it in your napplet to get `FromSchema<typeof schema>` typing for your `config.subscribe` callback -- the `values` parameter is inferred directly from your schema (enums, required fields, defaults all flow through). Authors who skip `json-schema-to-ts` pay no install cost and `config.subscribe` still works with the default `Record<string, unknown>` typing.
179
+
180
+ ```ts
181
+ import '@napplet/shim';
182
+ import { config } from '@napplet/sdk';
183
+ import type { FromSchema } from 'json-schema-to-ts';
184
+
185
+ const schema = {
186
+ type: 'object',
187
+ properties: {
188
+ theme: { type: 'string', enum: ['light', 'dark'], default: 'dark' },
189
+ },
190
+ required: ['theme'],
191
+ } as const;
192
+
193
+ type MyConfig = FromSchema<typeof schema>;
194
+
195
+ const sub = config.subscribe((values: MyConfig) => {
196
+ // values.theme is typed 'light' | 'dark'
197
+ });
198
+ ```
199
+
200
+ Install the peer when you want typed callbacks:
201
+
202
+ ```bash
203
+ npm install --save-dev json-schema-to-ts
204
+ ```
205
+
206
+ ### `keys`
207
+
208
+ Keyboard forwarding and action keybindings. Mirrors `window.napplet.keys`.
209
+
210
+ | Method | Returns | Description |
211
+ |--------|---------|-------------|
212
+ | `registerAction(action)` | `Promise<{ actionId, binding? }>` | Declare a named action the shell can bind to a key |
213
+ | `unregisterAction(actionId)` | `void` | Remove a previously registered action |
214
+ | `onAction(actionId, callback)` | `{ close(): void }` | Register a local handler for a bound key (zero-latency, not a wire message) |
215
+
216
+ ### `shell`
217
+
218
+ Namespaced capability query. Access via `window.napplet.shell.supports()` after importing `@napplet/shim`.
219
+
220
+ > Note: The SDK does not export a top-level `shell` object. Use `window.napplet.shell.supports()` directly.
221
+
222
+ | Method | Returns | Description |
223
+ |--------|---------|-------------|
224
+ | `supports(capability)` | `boolean` | Check shell support for a NUB (`nub:relay`) or permission (`perm:popups`). Bare NUB names also accepted (`relay`). |
225
+
226
+ **Example:**
227
+
228
+ ```ts
229
+ import '@napplet/shim';
230
+
231
+ // NUB domains (bare shorthand or nub: prefix)
232
+ if (window.napplet.shell.supports('relay')) { /* ... */ }
233
+ if (window.napplet.shell.supports('nub:identity')) { /* ... */ }
234
+
235
+ // Permissions
236
+ if (window.napplet.shell.supports('perm:popups')) { /* ... */ }
237
+ ```
238
+
239
+ ### Namespace Import
240
+
241
+ `import * as napplet from '@napplet/sdk'` produces an object structurally identical to `window.napplet`:
242
+
243
+ ```ts
244
+ import * as napplet from '@napplet/sdk';
245
+
246
+ napplet.relay.subscribe({ kinds: [1] }, (e) => console.log(e));
247
+ napplet.storage.setItem('key', 'value');
248
+ napplet.config.subscribe((v) => console.log(v));
249
+ ```
250
+
251
+ ## Types
252
+
253
+ All protocol types are re-exported from `@napplet/core` and the NUB packages:
254
+
255
+ ```ts
256
+ import type {
257
+ // Protocol types (from @napplet/core)
258
+ NostrEvent,
259
+ NostrFilter,
260
+ Subscription,
261
+ EventTemplate,
262
+ NappletMessage,
263
+ NubDomain,
264
+ NamespacedCapability,
265
+ ShellSupports,
266
+ // NUB message types (re-exported from NUB packages)
267
+ RelayNubMessage,
268
+ IdentityNubMessage,
269
+ StorageNubMessage,
270
+ IfcNubMessage,
271
+ KeysNubMessage,
272
+ Action,
273
+ } from '@napplet/sdk';
274
+ ```
275
+
276
+ ### Core Protocol Types
277
+
278
+ | Type | Description |
279
+ |------|-------------|
280
+ | `NostrEvent` | Standard Nostr event object |
281
+ | `NostrFilter` | Relay subscription filter |
282
+ | `Subscription` | Handle with `close()` method |
283
+ | `EventTemplate` | Unsigned event for `relay.publish()` |
284
+ | `NappletMessage` | Base JSON envelope type for all protocol messages |
285
+ | `NubDomain` | String literal union of NUB domain names |
286
+ | `NamespacedCapability` | Union of `NubDomain \| nub:* \| perm:*` for `supports()` |
287
+ | `ShellSupports` | Interface for the shell capability query API |
288
+
289
+ ### NUB Message Types
290
+
291
+ These are discriminated union types covering all messages in each NUB domain. Useful for writing typed message
292
+ handlers in shell implementations or protocol-aware code.
293
+
294
+ | Type | NUB Package | Description |
295
+ |------|-------------|-------------|
296
+ | `RelayNubMessage` | `@napplet/nub-relay` | Discriminated union of all relay domain messages |
297
+ | `IdentityNubMessage` | `@napplet/nub-identity` | Discriminated union of all identity domain messages |
298
+ | `StorageNubMessage` | `@napplet/nub-storage` | Discriminated union of all storage domain messages |
299
+ | `IfcNubMessage` | `@napplet/nub-ifc` | Discriminated union of all IFC domain messages |
300
+ | `KeysNubMessage` | `@napplet/nub-keys` | Discriminated union of all keys domain messages |
301
+ | `MediaNubMessage` | `@napplet/nub-media` | Discriminated union of all media domain messages |
302
+ | `NotifyNubMessage` | `@napplet/nub-notify` | Discriminated union of all notify domain messages |
303
+ | `ConfigNubMessage` | `@napplet/nub-config` | Discriminated union of all config domain messages |
304
+
305
+ Individual message types (e.g., `RelaySubscribeMessage`, `IdentityGetPublicKeyMessage`) are also re-exported from
306
+ `@napplet/sdk` for fine-grained typing.
307
+
308
+ ## NUB Domain Constants
309
+
310
+ Each NUB domain has a string constant re-exported from its package:
311
+
312
+ ```ts
313
+ import { RELAY_DOMAIN, IDENTITY_DOMAIN, STORAGE_DOMAIN, IFC_DOMAIN, THEME_DOMAIN, KEYS_DOMAIN, MEDIA_DOMAIN, NOTIFY_DOMAIN, CONFIG_DOMAIN } from '@napplet/sdk';
314
+ // Values: 'relay', 'identity', 'storage', 'ifc', 'theme', 'keys', 'media', 'notify', 'config'
315
+ ```
316
+
317
+ These constants are re-exported from the individual NUB packages. Use them with the shell capability query
318
+ API for type-safe conditional logic:
319
+
320
+ ```ts
321
+ if (window.napplet.shell.supports('nub:relay')) {
322
+ // relay operations are available
323
+ }
324
+
325
+ if (window.napplet.shell.supports('nub:identity')) {
326
+ // identity queries are available
327
+ }
328
+
329
+ if (window.napplet.shell.supports('nub:config')) {
330
+ // NUB-CONFIG is available -- schema registration and subscribe()
331
+ }
332
+ ```
333
+
334
+ ## Runtime Guard
335
+
336
+ If `window.napplet` is not installed when an SDK method is called, a clear error is thrown:
337
+
338
+ ```
339
+ Error: window.napplet not installed -- import @napplet/shim first
340
+ ```
341
+
342
+ This protects against importing `@napplet/sdk` without the side-effect shim import.
343
+
344
+ ## SDK vs Shim
345
+
346
+ | | `@napplet/sdk` | `@napplet/shim` |
347
+ |---|---|---|
348
+ | **Import style** | `import { relay } from '@napplet/sdk'` | `import '@napplet/shim'` (side-effect) |
349
+ | **What it does** | Named exports wrapping `window.napplet` | Installs `window.napplet` + shell registration |
350
+ | **Dependencies** | `@napplet/core` (types only) | None (types from `@napplet/core`) |
351
+ | **Side effects** | None | Yes -- installs globals, registers with shell |
352
+ | **Required** | Optional convenience | Required in every napplet |
353
+
354
+ **Typical usage:** Import both -- shim for runtime, SDK for developer API:
355
+
356
+ ```ts
357
+ import '@napplet/shim'; // required: installs window.napplet
358
+ import { relay, ipc, storage, keys, media, notify } from '@napplet/sdk'; // optional: typed API
359
+ ```
360
+
361
+ If you are writing a vanilla napplet with no build step, use `window.napplet.*` directly after importing the shim -- the SDK is not required.
362
+
363
+ ## Protocol Reference
364
+
365
+ - [NIP-5D](../../specs/NIP-5D.md) -- Napplet-shell protocol specification
366
+ - [@napplet/shim](../shim/) -- Window installer package
367
+ - [@napplet/core](../core/) -- Shared protocol types
368
+
369
+ ## License
370
+
371
+ MIT