@atproto/lex 0.0.0-spaces-alpha-20260818163953

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,1804 @@
1
+ Type-safe Lexicon tooling for AT Protocol data.
2
+
3
+ - Fetch and manage Lexicon schemas, generate TypeScript validators
4
+ - Compile-time and runtime type safety for AT Protocol data structures
5
+ - Fully typed XRPC client with authentication support
6
+ - Tree-shaking and composition friendly
7
+
8
+ ```typescript
9
+ // Build and validate data with generated utilities
10
+
11
+ const newPost = app.bsky.feed.post.$build({
12
+ text: 'Hello, world!',
13
+ createdAt: new Date().toISOString(),
14
+ })
15
+
16
+ app.bsky.actor.profile.$validate({
17
+ $type: 'app.bsky.actor.profile',
18
+ displayName: 'Ha'.repeat(32) + '!',
19
+ }) // Error: grapheme too big (maximum 64, got 65) at $.displayName
20
+ ```
21
+
22
+ ```typescript
23
+ // Trivially make type-safe XRPC requests towards a service
24
+
25
+ const profile = await xrpc('https://api.bsky.app', app.bsky.actor.getProfile, {
26
+ params: { actor: 'pfrazee.com' },
27
+ })
28
+ ```
29
+
30
+ ```typescript
31
+ // Manipulate records with the Client API in the context of an authenticated session
32
+
33
+ const client = new Client(oauthSession)
34
+
35
+ await client.create(app.bsky.feed.post, {
36
+ text: 'Hello, world!',
37
+ createdAt: new Date().toISOString(),
38
+ })
39
+
40
+ const posts = await client.list(app.bsky.feed.post, { limit: 10 })
41
+ ```
42
+
43
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
44
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
45
+
46
+ - [Quick Start](#quick-start)
47
+ - [Lexicon Schemas](#lexicon-schemas)
48
+ - [TypeScript Schemas](#typescript-schemas)
49
+ - [Generated Schema Structure](#generated-schema-structure)
50
+ - [Type definitions](#type-definitions)
51
+ - [Building data](#building-data)
52
+ - [Validation Helpers](#validation-helpers)
53
+ - [Record / typed-object helpers](#record--typed-object-helpers)
54
+ - [`$type` - Type Identifier](#type---type-identifier)
55
+ - [`$build(data)` - Build with Defaults](#builddata---build-with-defaults)
56
+ - [`$isTypeOf(data)` - Type Discriminator](#istypeofdata---type-discriminator)
57
+ - [Universal validation helpers](#universal-validation-helpers)
58
+ - [`$matches(data)` - Type Guard](#matchesdata---type-guard)
59
+ - [`$assert(data)` - Type-Narrowing Assertion](#assertdata---type-narrowing-assertion)
60
+ - [`$parse(data)` - Parse and Validate](#parsedata---parse-and-validate)
61
+ - [`$validate(data)` - Validate a value against the schema](#validatedata---validate-a-value-against-the-schema)
62
+ - [`$safeParse(data, options?)` - Parse a value against a schema and get the resulting value](#safeparsedata-options---parse-a-value-against-a-schema-and-get-the-resulting-value)
63
+ - [Data Model](#data-model)
64
+ - [Types](#types)
65
+ - [JSON Encoding](#json-encoding)
66
+ - [CBOR Encoding](#cbor-encoding)
67
+ - [Making simple XRPC Requests](#making-simple-xrpc-requests)
68
+ - [Client API](#client-api)
69
+ - [Creating a Client](#creating-a-client)
70
+ - [Unauthenticated Client](#unauthenticated-client)
71
+ - [Authenticated Client with OAuth](#authenticated-client-with-oauth)
72
+ - [Authenticated Client with Password](#authenticated-client-with-password)
73
+ - [Client with Service Proxy (authenticated only)](#client-with-service-proxy-authenticated-only)
74
+ - [Validation and Strictness Options](#validation-and-strictness-options)
75
+ - [Core Methods](#core-methods)
76
+ - [`client.call()`](#clientcall)
77
+ - [`client.create()`](#clientcreate)
78
+ - [`client.get()`](#clientget)
79
+ - [`client.put()`](#clientput)
80
+ - [`client.delete()`](#clientdelete)
81
+ - [`client.list()`](#clientlist)
82
+ - [`client.applyWrites()`](#clientapplywrites)
83
+ - [Error Handling](#error-handling)
84
+ - [Safe Methods](#safe-methods)
85
+ - [XrpcFailure Type](#xrpcfailure-type)
86
+ - [Authentication Methods](#authentication-methods)
87
+ - [`client.did`](#clientdid)
88
+ - [`client.assertAuthenticated()`](#clientassertauthenticated)
89
+ - [`client.assertDid`](#clientassertdid)
90
+ - [Labeler Configuration](#labeler-configuration)
91
+ - [Low-Level XRPC](#low-level-xrpc)
92
+ - [Utilities](#utilities)
93
+ - [Datetime Strings](#datetime-strings)
94
+ - [Advanced Usage](#advanced-usage)
95
+ - [Workflow Integration](#workflow-integration)
96
+ - [Development Workflow](#development-workflow)
97
+ - [Tree-Shaking](#tree-shaking)
98
+ - [Namespace notation](#namespace-notation)
99
+ - [Explicit `.main` reference](#explicit-main-reference)
100
+ - [Direct named import from the schema file](#direct-named-import-from-the-schema-file)
101
+ - [Default import (recommended)](#default-import-recommended)
102
+ - [Drawbacks of the default export](#drawbacks-of-the-default-export)
103
+ - [Summary](#summary)
104
+ - [Blob references](#blob-references)
105
+ - [TypedBlobRef: The Current Standard](#typedblobref-the-current-standard)
106
+ - [LegacyBlobRef: Historical Format](#legacyblobref-historical-format)
107
+ - [Working with Both Formats](#working-with-both-formats)
108
+ - [Actions](#actions)
109
+ - [What are Actions?](#what-are-actions)
110
+ - [Using Actions](#using-actions)
111
+ - [Composing Multiple Operations](#composing-multiple-operations)
112
+ - [Higher-Order Actions](#higher-order-actions)
113
+ - [Using a Single Client for Multiple Services](#using-a-single-client-for-multiple-services)
114
+ - [Building Library-Style APIs with Actions](#building-library-style-apis-with-actions)
115
+ - [Creating Posts](#creating-posts)
116
+ - [Following Users](#following-users)
117
+ - [Updating Profile with Retry Logic](#updating-profile-with-retry-logic)
118
+ - [Packaging Actions as a Library](#packaging-actions-as-a-library)
119
+ - [Best Practices for Actions](#best-practices-for-actions)
120
+ - [Standard Schema Compatibility](#standard-schema-compatibility)
121
+ - [Validating Generic Schemas with `$check`](#validating-generic-schemas-with-check)
122
+ - [License](#license)
123
+
124
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
125
+
126
+ ## Quick Start
127
+
128
+ **1. Install Lexicons**
129
+
130
+ Install the Lexicon schemas you need for your application:
131
+
132
+ ```bash
133
+ lex install app.bsky.feed.post app.bsky.feed.like
134
+ ```
135
+
136
+ This creates:
137
+
138
+ - `lexicons.json` - manifest tracking installed Lexicons and their versions (CIDs)
139
+ - `lexicons/` - directory containing the Lexicon JSON files
140
+
141
+ > [!NOTE]
142
+ >
143
+ > The `lex` command might conflict with other binaries installed on your system.
144
+ > If that happens, you can also run the CLI using `ts-lex`, `pnpm exec lex` or
145
+ > `npx @atproto/lex`.
146
+
147
+ **2. Verify and commit installed Lexicons**
148
+
149
+ Make sure to commit the `lexicons.json` manifest and the `lexicons/` directory containing the JSON files to version control.
150
+
151
+ ```bash
152
+ git add lexicons.json lexicons/
153
+ git commit -m "Install Lexicons"
154
+ ```
155
+
156
+ **3. Build TypeScript schemas**
157
+
158
+ Generate TypeScript schemas from the installed Lexicons:
159
+
160
+ ```bash
161
+ lex build
162
+ ```
163
+
164
+ This generates TypeScript files in `./src/lexicons` (by default) with type-safe validation, type guards, and builder utilities.
165
+
166
+ > [!TIP]
167
+ >
168
+ > If you wish to customize the output location or any other build options, pass the appropriate flags to the `lex build` command. See the [TypeScript Schemas](#typescript-schemas) section for available options.
169
+
170
+ > [!NOTE]
171
+ >
172
+ > The generated TypeScript files don't need to be committed to version control. Instead, they can be generated during your project's build step. See [Workflow Integration](#workflow-integration) for details.
173
+ >
174
+ > To avoid committing generated files, add the output directory to your `.gitignore`:
175
+ >
176
+ > ```bash
177
+ > echo "/src/lexicons" >> .gitignore
178
+ > ```
179
+
180
+ **4. Use in your code**
181
+
182
+ ```typescript
183
+ import { xrpc } from '@atproto/lex'
184
+ import { app } from './lexicons/index.js'
185
+
186
+ const profile = await xrpc('https://api.bsky.app', app.bsky.actor.getProfile, {
187
+ params: { actor: 'pfrazee.com' },
188
+ })
189
+ ```
190
+
191
+ ## Lexicon Schemas
192
+
193
+ The `lex install` command fetches Lexicon schemas from the Atmosphere network and manages them locally (in the `lexicons/` directory by default). It also updates the `lexicons.json` manifest file to track installed Lexicons and their versions.
194
+
195
+ ```bash
196
+ # Install Lexicons and update lexicons.json (default behavior)
197
+ lex install app.bsky.feed.post
198
+
199
+ # Install all Lexicons from lexicons.json manifest
200
+ lex install
201
+
202
+ # Install specific Lexicons without updating manifest
203
+ lex install --no-save app.bsky.feed.post app.bsky.actor.profile
204
+
205
+ # Update (re-fetch) all installed Lexicons to latest versions
206
+ lex install --update
207
+
208
+ # Fetch any missing Lexicons and verify against manifest
209
+ lex install --ci
210
+ ```
211
+
212
+ Options:
213
+
214
+ - `--manifest <path>` - Path to lexicons.json manifest file (default: `./lexicons.json`)
215
+ - `--no-save` - Don't update lexicons.json with installed lexicons (save is enabled by default)
216
+ - `--update` - Update all installed lexicons to their latest versions by re-resolving and re-installing them
217
+ - `--ci` - Error if the installed lexicons do not match the CIDs in the lexicons.json manifest
218
+ - `--lexicons <dir>` - Directory containing lexicon JSON files (default: `./lexicons`)
219
+
220
+ ## TypeScript Schemas
221
+
222
+ After installing Lexicon JSON files, use the `lex build` command to generate TypeScript schemas. These generated schemas provide type-safe validation, type guards, and builder utilities for working with AT Protocol data structures.
223
+
224
+ ```bash
225
+ lex build --lexicons ./lexicons --out ./src/lexicons
226
+ ```
227
+
228
+ Options:
229
+
230
+ - `--lexicons <dir>` - Directory containing lexicon JSON files (default: `./lexicons`)
231
+ - `--out <dir>` - Output directory for generated TypeScript (default: `./src/lexicons`)
232
+ - `--clear` - Clear output directory before generating
233
+ - `--override` - Override existing files (has no effect with --clear)
234
+ - `--no-pretty` - Don't run prettier on generated files (prettier is enabled by default)
235
+ - `--ignore-errors` - Skip files that fail to parse or compile instead of aborting the build
236
+ - `--ignore-invalid-lexicons` - Skip lexicon files that fail validation instead of exiting with an error
237
+ - `--exclude <patterns...>` - List of strings or regex patterns to exclude lexicon documents by their IDs
238
+ - `--include <patterns...>` - List of strings or regex patterns to include lexicon documents by their IDs
239
+ - `--lib <package>` - Package name of the library to import the lex schema utility "l" from (default: `@atproto/lex`)
240
+ - `--import-ext <ext>` - File extension to use for import statements in generated files (default: `.js`). Use `--import-ext ""` to generate extension-less imports
241
+ - `--file-ext <ext>` - File extension to use for generated files (default: `.ts`)
242
+ - `--index-file` - Generate an "index" file that re-exports all root-level namespaces (disabled by default)
243
+ - `--defs-export` - When some definitions conflict with child namespaces, export lexicon definitions under a separate `$defs` namespace (e.g. `com.example.foo.$defs`)
244
+ - `--no-default-export` - Disable generation of a `default` export of the `main` schema in each schema's namespace file (default exports are enabled by default; see [Tree-Shaking](#tree-shaking))
245
+
246
+ ### Generated Schema Structure
247
+
248
+ Each Lexicon generates a TypeScript module with:
249
+
250
+ - **Type definitions** - TypeScript types extracted from the schema
251
+ - **Schema instances** - Runtime validation objects with methods
252
+ - **Exported utilities** - Convenience functions for common operations
253
+
254
+ ### Type definitions
255
+
256
+ You can extract TypeScript types from the generated schemas for use in you application:
257
+
258
+ ```typescript
259
+ import * as app from './lexicons/app.js'
260
+
261
+ function renderPost(p: app.bsky.feed.post.Main) {
262
+ console.log(p.$type) // 'app.bsky.feed.post'
263
+ console.log(p.text)
264
+ }
265
+ ```
266
+
267
+ ### Building data
268
+
269
+ It is recommended to use the generated builders to create data that conforms to the schema. TypeScript ensures that all required fields are present at compile time.
270
+
271
+ ```typescript
272
+ import { l } from '@atproto/lex'
273
+ import * as app from './lexicons/app.js'
274
+
275
+ // variable type will be inferred as "app.bsky.feed.post.Main"
276
+ const post = app.bsky.feed.post.$build({
277
+ // No need to specify $type when using $build
278
+ text: 'Hello, world!',
279
+ createdAt: l.currentDatetimeString(),
280
+ })
281
+
282
+ // For runtime validation, use $parse()/$validate() instead
283
+ const postWithDefaults = app.bsky.feed.post.$parse(post)
284
+ app.bsky.feed.post.$validate(post)
285
+ ```
286
+
287
+ ### Validation Helpers
288
+
289
+ Generated namespaces expose a handful of `$`-prefixed helpers bound to the namespace's `main` schema. They come in two groups:
290
+
291
+ - [**Universal validation helpers**](#universal-validation-helpers) are available on every schema's `main`: `$matches`, `$assert`, `$check`, `$parse`, `$safeParse`, `$validate`, `$safeValidate` (and `$cast` / `$ifMatches`). These work for records, typed objects, queries, procedures, and subscriptions.
292
+ - [**Record / typed-object helpers**](#record--typed-object-helpers) are only emitted for record and typed-object schemas: `$type`, `$build`, `$isTypeOf`.
293
+
294
+ In addition, every generated namespace file exports a top-level `$nsid` constant containing the NSID of the lexicon document:
295
+
296
+ ```typescript
297
+ import * as app from './lexicons/app.js'
298
+
299
+ console.log(app.bsky.feed.defs.$nsid) // 'app.bsky.feed.defs'
300
+ ```
301
+
302
+ The Schema instance itself (for example `app.bsky.feed.post.main`) also exposes the underlying methods both with and without the `$` prefix (e.g. `main.parse()` and `main.$parse()`).
303
+
304
+ #### Record / typed-object helpers
305
+
306
+ ##### `$type` - Type Identifier
307
+
308
+ Returns the `$type` string of the schema (only available on record and typed-object schemas):
309
+
310
+ ```typescript
311
+ import * as app from './lexicons/app.js'
312
+
313
+ console.log(app.bsky.feed.post.$type) // 'app.bsky.feed.post'
314
+ console.log(app.bsky.actor.defs.profileViewBasic.$type) // 'app.bsky.actor.defs#profileViewBasic'
315
+ ```
316
+
317
+ Prefer `$type` over hard-coding the equivalent string literal in your code. The constant is emitted exactly once per schema in the generated namespace file, so every reference reuses the same string instance. Inlining `'app.bsky.feed.post'` everywhere instead leaks the same string into every call site, increases bundle size, and creates a typo-prone source of drift between your code and the schema.
318
+
319
+ ##### `$build(data)` - Build with Defaults
320
+
321
+ Builds data by adding the `$type` property and properly types the result. This also allows to declare a variable with the correct type without having to explicitly specify it.
322
+
323
+ ```typescript
324
+ import { l } from '@atproto/lex'
325
+ import * as app from './lexicons/app.js'
326
+
327
+ // The type of the "like" variable will be "app.bsky.feed.like.Main" (no need to explicitly specify the type)
328
+ const like = app.bsky.feed.like.$build({
329
+ subject: {
330
+ uri: 'at://did:plc:abc/app.bsky.feed.post/123',
331
+ cid: 'bafyrei...',
332
+ },
333
+ createdAt: l.currentDatetimeString(),
334
+ })
335
+ ```
336
+
337
+ > [!NOTE]
338
+ >
339
+ > `$build()` does not perform validation, and expects properly typed input data - use `$parse()` if you need validation.
340
+
341
+ ##### `$isTypeOf(data)` - Type Discriminator
342
+
343
+ Discriminates (pre-validated) data based on its `$type` property, without re-validating. This is especially useful when working with union types:
344
+
345
+ ```typescript
346
+ import { l } from '@atproto/lex'
347
+ import * as app from './lexicons/app.js'
348
+
349
+ declare const data:
350
+ app.bsky.feed.post.Main | app.bsky.feed.like.Main | l.Unknown$TypedObject
351
+
352
+ // Discriminate by $type without re-validating
353
+ if (app.bsky.feed.post.$isTypeOf(data)) {
354
+ // data is a post
355
+ }
356
+ ```
357
+
358
+ #### Universal validation helpers
359
+
360
+ ##### `$matches(data)` - Type Guard
361
+
362
+ Returns `true` if data matches the schema, `false` otherwise. Acts as a TypeScript type guard:
363
+
364
+ ```typescript
365
+ import { l } from '@atproto/lex'
366
+ import * as app from './lexicons/app.js'
367
+
368
+ const data: unknown = {
369
+ $type: 'app.bsky.feed.post',
370
+ text: 'Hello!',
371
+ createdAt: l.currentDatetimeString(),
372
+ }
373
+
374
+ if (app.bsky.feed.post.$matches(data)) {
375
+ // TypeScript knows data is a Post here
376
+ console.log(data.text)
377
+ }
378
+ ```
379
+
380
+ > [!NOTE]
381
+ >
382
+ > Performs validation so [`$isTypeOf`](#istypeofdata---type-discriminator) is preferred for pre-validated & properly typed data.
383
+
384
+ ##### `$assert(data)` - Type-Narrowing Assertion
385
+
386
+ Throws if `data` does not match the schema. When the schema is statically known (e.g. `app.bsky.feed.post`), TypeScript narrows the type of `data` after the call:
387
+
388
+ ```typescript
389
+ import { l } from '@atproto/lex'
390
+ import * as app from './lexicons/app.js'
391
+
392
+ const data: unknown = {
393
+ $type: 'app.bsky.feed.post',
394
+ text: 'Hello!',
395
+ createdAt: l.currentDatetimeString(),
396
+ }
397
+
398
+ app.bsky.feed.post.$assert(data)
399
+
400
+ // TypeScript now knows data is app.bsky.feed.post.Main
401
+ console.log(data.text)
402
+ ```
403
+
404
+ For library code that operates on a schema parameter whose type cannot be fully expressed, see [Validating Generic Schemas with `$check`](#validating-generic-schemas-with-check).
405
+
406
+ ##### `$parse(data)` - Parse and Validate
407
+
408
+ Validates and returns typed data, throwing an error if validation fails:
409
+
410
+ ```typescript
411
+ import { l } from '@atproto/lex'
412
+ import * as app from './lexicons/app.js'
413
+
414
+ try {
415
+ const post = app.bsky.feed.post.$parse({
416
+ $type: 'app.bsky.feed.post',
417
+ text: 'Hello!',
418
+ createdAt: l.currentDatetimeString(),
419
+ })
420
+
421
+ // post is now typed and validated
422
+ console.log(post.text)
423
+ } catch (error) {
424
+ console.error('Validation failed:', error)
425
+ }
426
+ ```
427
+
428
+ > [!NOTE]
429
+ >
430
+ > The `$parse` method will apply defaults defined in the schema for optional fields, as well as data coercion (e.g., CID strings to Cid types). This means that the returned value might be different from the input data if defaults were applied. Use `$validate()` for value validation.
431
+
432
+ ##### `$validate(data)` - Validate a value against the schema
433
+
434
+ Validates an existing value against a schema, returning the value itself if, and only if, it already matches the schema (ie. without applying defaults or coercion).
435
+
436
+ ```typescript
437
+ import { l } from '@atproto/lex'
438
+ import * as app from './lexicons/app.js'
439
+
440
+ const value = {
441
+ $type: 'app.bsky.feed.post',
442
+ text: 'Hello!',
443
+ createdAt: l.currentDatetimeString(),
444
+ }
445
+
446
+ // Throws if no valid
447
+ const result = app.bsky.feed.post.$validate(value)
448
+
449
+ value === result // true
450
+ ```
451
+
452
+ ##### `$safeParse(data, options?)` - Parse a value against a schema and get the resulting value
453
+
454
+ Returns a detailed validation result object without throwing:
455
+
456
+ ```typescript
457
+ import { l } from '@atproto/lex'
458
+ import * as app from './lexicons/app.js'
459
+
460
+ const result = app.bsky.feed.post.$safeParse({
461
+ $type: 'app.bsky.feed.post',
462
+ text: 'Hello!',
463
+ createdAt: l.currentDatetimeString(),
464
+ })
465
+
466
+ if (result.success) {
467
+ console.log('Valid post:', result.value)
468
+ } else {
469
+ console.error('Validation failed:', result.error)
470
+ }
471
+ ```
472
+
473
+ All schema methods that perform validation (`$parse`, `$safeParse`, `$validate`, `$safeValidate`) accept an optional `{ strict }` option. When `strict` is `false`, validation becomes more lenient: datetime string format checks are relaxed (e.g. datetimes without timezones are accepted; other string formats remain strict), blob MIME type and size constraints are not enforced, non-raw CIDs are allowed in blob references, and legacy blob reference format (objects with `cid` and `mimeType` properties) is accepted. This is primarily used internally by the XRPC client when `strictResponseProcessing` is disabled, but can also be used directly:
474
+
475
+ ```typescript
476
+ // Strict mode (default) - rejects datetime without timezone
477
+ app.bsky.feed.post.$safeParse(data) // { strict: true } is the default
478
+
479
+ // Non-strict mode - accepts more lenient data
480
+ app.bsky.feed.post.$safeParse(data, { strict: false })
481
+ ```
482
+
483
+ ## Data Model
484
+
485
+ The AT Protocol uses a [data model](https://atproto.com/specs/data-model) that extends JSON with two additional data structures: **CIDs** (content-addressed links) and **bytes** (for raw data). This data model can be encoded either as JSON for XRPC (HTTP API) or as [CBOR](https://dasl.ing/drisl.html) for storage and authentication (see [`@atproto/lex-cbor`](../lex-cbor)).
486
+
487
+ ### Types
488
+
489
+ The package exports TypeScript types and type guards for working with the data model:
490
+
491
+ ```typescript
492
+ import type {
493
+ LexValue,
494
+ LexMap,
495
+ LexScalar,
496
+ TypedLexMap,
497
+ Cid,
498
+ } from '@atproto/lex'
499
+ import { isLexValue, isLexMap, isTypedLexMap, isCid } from '@atproto/lex'
500
+
501
+ // LexScalar: number | string | boolean | null | Cid | Uint8Array
502
+ // LexValue: LexScalar | LexValue[] | { [key: string]?: LexValue }
503
+ // LexMap: { [key: string]?: LexValue }
504
+ // TypedLexMap: LexMap & { $type: string }
505
+ // Cid: Content Identifier (link by hash)
506
+
507
+ if (isTypedLexMap(data)) {
508
+ console.log(data.$type) // some string
509
+ }
510
+ ```
511
+
512
+ ### JSON Encoding
513
+
514
+ In JSON, CIDs are represented as `{"$link": "bafyrei..."}` and bytes as `{"$bytes": "base64..."}`. This package provides utilities to parse and stringify data model values to/from JSON:
515
+
516
+ ```typescript
517
+ import { Cid, lexParse, lexStringify, jsonToLex, lexToJson } from '@atproto/lex'
518
+
519
+ // Parse JSON string → data model (decodes $link and $bytes)
520
+ const parsed = lexParse<{
521
+ ref: Cid
522
+ data: Uint8Array
523
+ }>(`{
524
+ "ref": { "$link": "bafyrei..." },
525
+ "data": { "$bytes": "SGVsbG8sIHdvcmxkIQ==" }
526
+ }`)
527
+
528
+ assert(isCid(parsed.ref))
529
+ assert(parsed.data instanceof Uint8Array)
530
+
531
+ const someCid = lexParse<Cid>('{"$link": "bafyrei..."}')
532
+ const someBytes = lexParse<Uint8Array>('{"$bytes": "SGVsbG8sIHdvcmxkIQ=="}')
533
+
534
+ // Data model → JSON string (encodes CIDs and bytes)
535
+ const json = lexStringify({ ref: someCid, data: someBytes })
536
+
537
+ // Convert between parsed JSON objects and data model values
538
+ const lex = jsonToLex({
539
+ ref: { $link: 'bafyrei...' }, // Converted to Cid
540
+ data: { $bytes: 'SGVsbG8sIHdvcmxkIQ==' }, // Converted to Uint8Array
541
+ })
542
+
543
+ const obj = lexToJson({
544
+ ref: someCid, // Converted to { $link: string }
545
+ data: someBytes, // Converted to { $bytes: string }
546
+ })
547
+ ```
548
+
549
+ ### CBOR Encoding
550
+
551
+ Use `@atproto/lex-cbor` to encode/decode the data model to/from CBOR ([DRISL](https://dasl.ing/drisl.html)) format for storage and authentication:
552
+
553
+ ```typescript
554
+ import { encode, decode } from '@atproto/lex-cbor'
555
+ import type { LexValue } from '@atproto/lex'
556
+
557
+ // Encode data model to CBOR bytes
558
+ const cborBytes = encode(someLexValue)
559
+
560
+ // Decode CBOR bytes to data model
561
+ const lexValue: LexValue = decode(cborBytes)
562
+ ```
563
+
564
+ ## Making simple XRPC Requests
565
+
566
+ [XRPC](https://atproto.com/specs/xrpc) (short for "Lexicon RPC") is the set of HTTP conventions used by AT Protocol for client-server and server-server communication. Endpoints follow the pattern `/xrpc/<nsid>`, where the NSID maps to a Lexicon schema that defines the request and response types. XRPC has three method types: **queries** (HTTP GET) for read operations, **procedures** (HTTP POST) for mutations and **subscriptions** (WebSockets) for real-time updates.
567
+
568
+ The `xrpc()` and `xrpcSafe()` functions can be used to make simple XRPC requests. They are typically used in places that don't require an authenticated session, or when more granular control over the request/response is needed. For most use cases, the `Client` API provides a more ergonomic way to work with XRPC in the context of an authenticated session.
569
+
570
+ ```typescript
571
+ import { xrpc, xrpcSafe } from '@atproto/lex'
572
+ import * as com from './lexicons/com.js'
573
+
574
+ const response = await xrpc(
575
+ 'https://bsky.network',
576
+ com.atproto.identity.resolveHandle,
577
+ {
578
+ params: { handle: 'atproto.com' },
579
+ headers: { 'user-agent': 'MyApp/1.0.0' },
580
+ },
581
+ )
582
+
583
+ response.status // number
584
+ response.headers // Headers
585
+ response.body.did // `did:${string}:${string}`
586
+
587
+ // Or use the safe variant (returns errors instead of throwing)
588
+ const result = await xrpcSafe(
589
+ 'https://bsky.network',
590
+ com.atproto.identity.resolveHandle,
591
+ {
592
+ params: { handle: 'atproto.com' },
593
+ signal: AbortSignal.timeout(5000), // Abort after 5 seconds
594
+ },
595
+ )
596
+
597
+ if (result.success) {
598
+ console.log(result.body)
599
+ } else {
600
+ console.error(result.error) // XRPC error code
601
+ console.error(result.message) // Error message
602
+ }
603
+ ```
604
+
605
+ Both `xrpc()` and `xrpcSafe()` accept `validateRequest`, `validateResponse`, and `strictResponseProcessing` options to control validation and strictness per-call. See [Validation and Strictness Options](#validation-and-strictness-options) for details.
606
+
607
+ ## Client API
608
+
609
+ The `Client` class provides high-level helpers for common AT Protocol "repo" operations: `create()`, `get()`, `put()`, `delete()`, `list()`, `uploadBlob()`, and more. A `Client` instance is typically useful for making requests in the context of an authenticated user session, as it automatically handles headers and provides default values based on the authenticated user's DID.
610
+
611
+ A `Client` instance is also useful to encapsulate configuration for a specific service, by specifying the `service` option (for proxying) and `labelers` option (for content labeling). These act as _defaults_ for the client's requests and can be overridden — or disabled with `null` — on a per-request basis, allowing a single client to talk both to a proxied service (e.g. an AppView) and directly to the user's PDS.
612
+
613
+ ### Creating a Client
614
+
615
+ #### Unauthenticated Client
616
+
617
+ Just provide the service URL:
618
+
619
+ ```typescript
620
+ import { Client } from '@atproto/lex'
621
+
622
+ const client = new Client('https://public.api.bsky.app')
623
+ ```
624
+
625
+ #### Authenticated Client with OAuth
626
+
627
+ ```typescript
628
+ import { Client } from '@atproto/lex'
629
+ import { OAuthClient } from '@atproto/oauth-client-node'
630
+
631
+ // Setup OAuth client (see @atproto/oauth-client documentation)
632
+ const oauthClient = new OAuthClient({/* ... */})
633
+ const session = await oauthClient.restore(userDid)
634
+
635
+ // Create authenticated client
636
+ const client = new Client(session)
637
+ ```
638
+
639
+ For detailed OAuth setup, see the [@atproto/oauth-client](../../../oauth/oauth-client) documentation.
640
+
641
+ #### Authenticated Client with Password
642
+
643
+ For CLI tools, scripts, and bots, you can use password-based authentication with [`@atproto/lex-password-session`](../lex-password-session):
644
+
645
+ ```typescript
646
+ import { Client } from '@atproto/lex'
647
+ import { PasswordSession } from '@atproto/lex-password-session'
648
+
649
+ const session = await PasswordSession.login({
650
+ service: 'https://bsky.social',
651
+ identifier: 'alice.bsky.social',
652
+ password: 'xxxx-xxxx-xxxx-xxxx', // App password
653
+ onUpdated: (data) => saveToStorage(data),
654
+ onDeleted: (data) => clearStorage(data.did),
655
+ })
656
+
657
+ const client = new Client(session)
658
+ ```
659
+
660
+ For detailed password session setup, see the [@atproto/lex-password-session](../lex-password-session) documentation.
661
+
662
+ #### Client with Service Proxy (authenticated only)
663
+
664
+ ```typescript
665
+ import { Client } from '@atproto/lex'
666
+
667
+ // Route requests through a specific service
668
+ const client = new Client(session, {
669
+ service: 'did:web:api.bsky.app#bsky_appview',
670
+ })
671
+ ```
672
+
673
+ #### Validation and Strictness Options
674
+
675
+ The `Client` constructor accepts options to control request/response validation and how invalid Lex data is handled. These defaults apply to all XRPC calls made through the client, and can be overridden per-call via `client.call()`, `client.xrpc()` or `client.xrpcSafe()`.
676
+
677
+ ```typescript
678
+ const client = new Client(session, {
679
+ // Validate requests against the method's input schema (default: false)
680
+ validateRequest: true,
681
+
682
+ // Validate responses against the method's output schema (default: true)
683
+ validateResponse: true,
684
+
685
+ // Strictly process responses according to Lex encoding rules. When set to
686
+ // false, accepts responses containing invalid Lex data such as floats or
687
+ // malformed $bytes/$link objects (default: true)
688
+ strictResponseProcessing: false,
689
+ })
690
+ ```
691
+
692
+ - **`validateRequest`** — When `true`, outgoing request bodies are validated against the Lexicon input schema before sending. Useful in development to catch errors early. Default: `false`.
693
+ - **`validateResponse`** — When `true`, incoming response bodies are validated against the Lexicon output schema. Disabling this can improve performance when you trust the upstream service. Default: `true`.
694
+ - **`strictResponseProcessing`** — When `true` (default), the client will strictly process responses according to Lex encoding rules, rejecting responses containing invalid Lex data (e.g. floating-point numbers, malformed `$bytes` or `$link` objects). When `false`, the client accepts such responses in a lenient mode: invalid values are returned as-is rather than being rejected or converted, `datetime` string format checks become more lenient (e.g. datetimes without timezones are accepted) while other string formats remain strict, blob MIME type and size constraints are not enforced, and legacy blob reference format (objects with `cid` and `mimeType` properties) is accepted. Default: `true`.
695
+
696
+ ### Core Methods
697
+
698
+ #### `client.call()`
699
+
700
+ Call procedures or queries defined in Lexicons.
701
+
702
+ ```typescript
703
+ import * as app from './lexicons/app.js'
704
+
705
+ // Query (GET request)
706
+ const profile = await client.call(app.bsky.actor.getProfile, {
707
+ actor: 'pfrazee.com',
708
+ })
709
+
710
+ // Procedure (POST request)
711
+ const result = await client.call(app.bsky.feed.sendInteractions, {
712
+ interactions: [/* ... */],
713
+ })
714
+
715
+ // With options
716
+ const timeline = await client.call(
717
+ app.bsky.feed.getTimeline,
718
+ {
719
+ limit: 50,
720
+ },
721
+ {
722
+ signal: abortSignal,
723
+ },
724
+ )
725
+ ```
726
+
727
+ #### `client.create()`
728
+
729
+ Create a new record un the authenticated user's repo.
730
+
731
+ ```typescript
732
+ import { l } from '@atproto/lex'
733
+ import * as app from './lexicons/app.js'
734
+
735
+ const result = await client.create(app.bsky.feed.post, {
736
+ text: 'Hello, world!',
737
+ createdAt: l.currentDatetimeString(),
738
+ })
739
+
740
+ console.log(result.uri) // at://did:plc:...
741
+ console.log(result.cid)
742
+ ```
743
+
744
+ Options:
745
+
746
+ - `rkey` - Custom record key (auto-generated if not provided)
747
+ - `validate` - Tri-state instruction to the PDS. `true` forces server-side schema validation, `false` explicitly disables it, and `undefined` (default) lets the PDS decide (it validates only collections whose schemas it knows)
748
+ - `validateRequest` - Validate the record locally against schema before submitting the request
749
+ - `swapCommit` - CID for optimistic concurrency control
750
+
751
+ #### `client.get()`
752
+
753
+ Retrieve a record.
754
+
755
+ ```typescript
756
+ import * as app from './lexicons/app.js'
757
+
758
+ // No need to specify the "rkey" for records with literal keys (e.g. profile)
759
+ const profile = await client.get(app.bsky.actor.profile)
760
+
761
+ console.log(profile.displayName)
762
+ console.log(profile.description)
763
+ ```
764
+
765
+ For records with non-literal keys:
766
+
767
+ ```typescript
768
+ const post = await client.get(app.bsky.feed.post, {
769
+ rkey: '3jxf7z2k3q2',
770
+ })
771
+ ```
772
+
773
+ #### `client.put()`
774
+
775
+ Update an existing record.
776
+
777
+ ```typescript
778
+ import * as app from './lexicons/app.js'
779
+
780
+ await client.put(app.bsky.actor.profile, {
781
+ displayName: 'New Name',
782
+ description: 'Updated bio',
783
+ })
784
+ ```
785
+
786
+ Options:
787
+
788
+ - `rkey` - Record key (required for non-literal keys)
789
+ - `validate` - Tri-state instruction to the PDS. `true` forces server-side schema validation, `false` explicitly disables it, and `undefined` (default) lets the PDS decide (it validates only collections whose schemas it knows)
790
+ - `validateRequest` - Validate the record locally against schema before submitting the request
791
+ - `swapCommit` - Expected repo commit CID
792
+ - `swapRecord` - Expected record CID
793
+
794
+ #### `client.delete()`
795
+
796
+ Delete a record.
797
+
798
+ ```typescript
799
+ import * as app from './lexicons/app.js'
800
+
801
+ await client.delete(app.bsky.feed.post, {
802
+ rkey: '3jxf7z2k3q2',
803
+ })
804
+ ```
805
+
806
+ #### `client.list()`
807
+
808
+ List records in a collection.
809
+
810
+ ```typescript
811
+ import * as app from './lexicons/app.js'
812
+
813
+ const result = await client.list(app.bsky.feed.post, {
814
+ limit: 50,
815
+ reverse: true,
816
+ })
817
+
818
+ for (const record of result.records) {
819
+ console.log(record.uri, record.value.text)
820
+ }
821
+
822
+ // Records that failed local schema validation are returned separately
823
+ for (const invalid of result.invalid) {
824
+ console.warn('Invalid record:', invalid)
825
+ }
826
+
827
+ // Pagination
828
+ if (result.cursor) {
829
+ const nextPage = await client.list(app.bsky.feed.post, {
830
+ cursor: result.cursor,
831
+ limit: 50,
832
+ })
833
+ }
834
+ ```
835
+
836
+ The result includes:
837
+
838
+ - `records` - Records that successfully validated against the schema
839
+ - `invalid` - Records returned by the server that failed local schema validation (raw `LexMap` values)
840
+ - `cursor` - Pagination cursor (if more results are available)
841
+
842
+ #### `client.applyWrites()`
843
+
844
+ Perform an atomic batch of create, update, and delete operations in a single request.
845
+
846
+ ```typescript
847
+ import { l } from '@atproto/lex'
848
+ import * as app from './lexicons/app.js'
849
+
850
+ const response = await client.applyWrites((op) => [
851
+ // Create a new post
852
+ op.create(app.bsky.feed.post, {
853
+ text: 'Hello, world!',
854
+ createdAt: l.currentDatetimeString(),
855
+ }),
856
+
857
+ // Update profile
858
+ op.update(app.bsky.actor.profile, {
859
+ displayName: 'Alice',
860
+ description: 'Updated bio',
861
+ }),
862
+
863
+ // Delete an existing post by rkey
864
+ op.delete(app.bsky.feed.post, {
865
+ rkey: '3jxf7z2k3q2',
866
+ }),
867
+ ])
868
+
869
+ // Check results
870
+ for (const result of response.body.results) {
871
+ console.log(result.uri, result.cid)
872
+ }
873
+ ```
874
+
875
+ Options:
876
+
877
+ - `repo` - Repository identifier (defaults to authenticated user's DID)
878
+ - `validate` - Tri-state instruction to the PDS. `true` forces server-side schema validation, `false` explicitly disables it, and `undefined` (default) lets the PDS decide (it validates only collections whose schemas it knows)
879
+ - `swapCommit` - CID for optimistic concurrency control
880
+
881
+ > [!NOTE]
882
+ >
883
+ > All operations in an `applyWrites()` call are atomic - they either all succeed or all fail together. This is useful for maintaining consistency when making multiple related changes.
884
+
885
+ ### Error Handling
886
+
887
+ By default, all client methods throw errors when requests fail. For more ergonomic error handling, the client provides "Safe" variants that return errors instead of throwing them.
888
+
889
+ #### Safe Methods
890
+
891
+ The `xrpcSafe()` method catches errors and returns them as part of the result type instead of throwing:
892
+
893
+ #### XrpcFailure Type
894
+
895
+ The `xrpcSafe()` method returns a union type that includes the success case (`XrpcResponse`) and failure cases (`XrpcFailure`):
896
+
897
+ ```typescript
898
+ import {
899
+ Client,
900
+ XrpcResponseError,
901
+ XrpcInvalidResponseError,
902
+ XrpcInternalError,
903
+ } from '@atproto/lex'
904
+ import * as com from './lexicons/com.js'
905
+
906
+ const client = new Client(session)
907
+
908
+ // Using a safe method
909
+ const result = await client.xrpcSafe(com.atproto.identity.resolveHandle, {
910
+ params: { handle: 'alice.bsky.social' },
911
+ })
912
+
913
+ if (result.success) {
914
+ // Handle success
915
+ console.log(result.body)
916
+ } else {
917
+ // Handle failure - result is an XrpcFailure.
918
+ //
919
+ // All XrpcFailure subclasses inherit from XrpcError and share these members:
920
+ result.error // string error code (e.g. "HandleNotFound", "UpstreamFailure")
921
+ result.message // string
922
+ result.shouldRetry() // boolean - whether the error is transient
923
+
924
+ if (result.matchesSchemaErrors()) {
925
+ // Check if the error matches a declared error in the schema.
926
+ // TypeScript narrows `result.error` to one of the method's declared error codes.
927
+ result.error // "HandleNotFound"
928
+ }
929
+
930
+ // Branch on the specific error class to access additional members:
931
+ if (result instanceof XrpcResponseError) {
932
+ // The server responded with an error status code (4xx or 5xx).
933
+ // This is used for all error responses, whether or not they have a valid XRPC error payload.
934
+ result.response.status // number
935
+ result.response.headers // Headers
936
+ result.payload // undefined | { body: unknown; encoding: string }
937
+
938
+ // Coerce to a valid XRPC error payload using toJSON():
939
+ result.toJSON() // { error: string, message?: string }
940
+ } else if (result instanceof XrpcInvalidResponseError) {
941
+ // The response was truly invalid (3xx redirect, malformed JSON, schema mismatch, etc.).
942
+ // This is a more specific error for responses that are not processable.
943
+ result.response.status // number
944
+ result.response.headers // Headers
945
+ result.payload // undefined | { body: unknown; encoding: string }
946
+ } else if (result instanceof XrpcInternalError) {
947
+ // Something went wrong on the client side (network error, etc.)
948
+ }
949
+ }
950
+ ```
951
+
952
+ The `XrpcFailure<M>` type is a union of three error classes:
953
+
954
+ 1. **`XrpcResponseError`** - The server responded with a 4xx/5xx error status code. This is used for all error responses from the upstream server.
955
+
956
+ 2. **`XrpcInvalidResponseError`** - The upstream server returned a 2xx/3xx that does not comply with XRPC specifications for successful responses. A sub-class, `XrpcResponseValidationError`, is used for payload schema validation failures specifically.
957
+
958
+ 3. **`XrpcInternalError`** - Client-side errors (network failures, timeouts, etc.)
959
+
960
+ ### Authentication Methods
961
+
962
+ #### `client.did`
963
+
964
+ Get the authenticated user's DID.
965
+
966
+ ```typescript
967
+ const did = client.did // Returns Did | undefined
968
+ ```
969
+
970
+ #### `client.assertAuthenticated()`
971
+
972
+ Assert that the client is authenticated (throws if not).
973
+
974
+ ```typescript
975
+ client.assertAuthenticated()
976
+ // After this call, TypeScript knows client.did is defined
977
+ const did = client.did // Type: Did (not undefined)
978
+ ```
979
+
980
+ #### `client.assertDid`
981
+
982
+ Get the authenticated user's DID, asserting that the client is authenticated.
983
+
984
+ ```typescript
985
+ const did = client.assertDid // Type: Did (throws if not authenticated)
986
+ ```
987
+
988
+ This is equivalent to calling `client.assertAuthenticated()` followed by accessing `client.did`, but provides a more concise way to get the DID when you know authentication is required.
989
+
990
+ ### Labeler Configuration
991
+
992
+ Configure content labelers for moderation.
993
+
994
+ ```typescript
995
+ import { Client } from '@atproto/lex'
996
+
997
+ // Global app-level labelers
998
+ Client.configure({
999
+ appLabelers: ['did:plc:labeler1', 'did:plc:labeler2'],
1000
+ })
1001
+
1002
+ // Client-specific labelers
1003
+ const client = new Client(session, {
1004
+ labelers: ['did:plc:labeler3'],
1005
+ })
1006
+
1007
+ // Add labelers dynamically
1008
+ client.addLabelers(['did:plc:labeler4'])
1009
+
1010
+ // Replace all labelers
1011
+ client.setLabelers(['did:plc:labeler5'])
1012
+
1013
+ // Clear labelers
1014
+ client.clearLabelers()
1015
+ ```
1016
+
1017
+ The client's `labelers` act as a default for its requests. A per-request `labelers` option replaces that default for that request, and `labelers: null` disables the `atproto-accept-labelers` header entirely:
1018
+
1019
+ ```typescript
1020
+ // Uses the client's labelers
1021
+ await client.call(app.bsky.actor.getProfile, { actor })
1022
+
1023
+ // Uses only 'did:plc:other' for this request
1024
+ await client.xrpc(app.bsky.actor.getProfile, {
1025
+ params: { actor },
1026
+ labelers: ['did:plc:other'],
1027
+ })
1028
+
1029
+ // No atproto-accept-labelers header for this request (except appLabelers,
1030
+ // which are applied unless explicitly disabled)
1031
+ await client.xrpc(app.bsky.actor.getProfile, {
1032
+ params: { actor },
1033
+ labelers: null,
1034
+ })
1035
+ ```
1036
+
1037
+ App-level labelers (`appLabelers`) are always added to the `atproto-accept-labelers` header with the `;redact` param. They default to the static `Client.appLabelers` (set via `Client.configure()`), and can be overridden through the client's or a request's `appLabelers` option (`appLabelers: null` disables them for that client or request).
1038
+
1039
+ The same defaulting logic applies to the `service` option (`atproto-proxy` header): a per-request `service` replaces the client's default, and `service: null` disables proxying for that request.
1040
+
1041
+ ### Low-Level XRPC
1042
+
1043
+ For advanced use cases, use `client.xrpc()` to get the full response (headers, status, body):
1044
+
1045
+ ```typescript
1046
+ import * as app from './lexicons/app.js'
1047
+
1048
+ const response = await client.xrpc(app.bsky.feed.getTimeline, {
1049
+ params: { limit: 50 },
1050
+ signal: abortSignal,
1051
+ headers: { 'custom-header': 'value' },
1052
+ })
1053
+
1054
+ console.log(response.status)
1055
+ console.log(response.headers)
1056
+ console.log(response.body)
1057
+ ```
1058
+
1059
+ Validation and strictness options (`validateRequest`, `validateResponse`, `strictResponseProcessing`) can also be passed per-call to override the client defaults:
1060
+
1061
+ ```typescript
1062
+ const response = await client.xrpc(app.bsky.feed.getTimeline, {
1063
+ params: { limit: 50 },
1064
+ strictResponseProcessing: false, // Accept non-strict Lex data for this call
1065
+ validateResponse: false, // Skip schema validation for this call
1066
+ })
1067
+ ```
1068
+
1069
+ ## Utilities
1070
+
1071
+ Various utilities for working with CIDs, datetime strings, string lengths, language tags, and low-level JSON encoding are exported from the package:
1072
+
1073
+ ```typescript
1074
+ import {
1075
+ // CID utilities
1076
+ parseCid, // Parse CID string (throws on invalid)
1077
+ ifCid, // Coerce to Cid or null
1078
+ isCid, // Type guard for Cid values
1079
+
1080
+ // Datetime string utilities
1081
+ toDatetimeString, // Convert Date to DatetimeString (throws on invalid)
1082
+ asDatetimeString, // Cast string to DatetimeString (throws on invalid)
1083
+ isDatetimeString, // Type guard for DatetimeString
1084
+ ifDatetimeString, // Returns DatetimeString or undefined
1085
+
1086
+ // Blob references
1087
+ BlobRef, // TypedBlobRef | LegacyBlobRef
1088
+ LegacyBlobRef, // { cid: string, mimeType: string }
1089
+ TypedBlobRef, // { $type: 'blob', ref: Cid, mimeType: string, size: number }
1090
+ isBlobRef, // Type guard for BlobRef (accepts both TypedBlobRef and LegacyBlobRef)
1091
+ isLegacyBlobRef, // Type guard for LegacyBlobRef objects
1092
+ isTypedBlobRef, // Type guard for TypedBlobRef objects
1093
+ getBlobCid, // Extract Cid from BlobRef or LegacyBlobRef
1094
+ getBlobCidString, // Extract CID string from BlobRef or LegacyBlobRef
1095
+ getBlobMime, // Extract MIME type from BlobRef or LegacyBlobRef
1096
+ getBlobSize, // Extract size from BlobRef (returns undefined for LegacyBlobRef)
1097
+
1098
+ // Equality
1099
+ lexEquals, // Deep equality (handles CIDs and bytes)
1100
+
1101
+ // String length for Lexicon validation
1102
+ graphemeLen, // Count user-perceived characters
1103
+ utf8Len, // Count UTF-8 bytes
1104
+
1105
+ // Language tag validation (BCP-47)
1106
+ isLanguageString, // Validate language tags (e.g., 'en', 'pt-BR')
1107
+
1108
+ // Low-level JSON encoding helpers
1109
+ parseLexLink, // { $link: string } → Cid | undefined
1110
+ encodeLexLink, // Cid → { $link: string }
1111
+ parseLexBytes, // { $bytes: string } → Uint8Array | undefined
1112
+ encodeLexBytes, // Uint8Array → { $bytes: string }
1113
+ } from '@atproto/lex'
1114
+
1115
+ const cid = parseCid('bafyreiabc...')
1116
+ graphemeLen('👨‍👩‍👧‍👦') // 1
1117
+ utf8Len('👨‍👩‍👧‍👦') // 25
1118
+ isLanguageString('en-US') // true
1119
+ ```
1120
+
1121
+ ### Datetime Strings
1122
+
1123
+ Many AT Protocol records (such as posts, likes, and follows) include a `createdAt` field that expects a valid `DatetimeString`. While `new Date().toISOString()` produces a string that looks like a valid datetime, it is not guaranteed to always conform to the AT Protocol's [datetime format requirements](https://atproto.com/specs/lexicon#datetime) (for example, `Date` objects representing dates before year 0 or after year 9999 will produce non-conforming strings). To ensure correctness and type safety, use the `DatetimeString` utilities exported from `@atproto/lex`:
1124
+
1125
+ - **`toDatetimeString(date: Date)`** - Converts a `Date` object into a valid `DatetimeString`, throwing an `InvalidDatetimeError` if the date cannot be represented as a valid AT Protocol datetime.
1126
+ - **`asDatetimeString(input: string)`** - Validates and casts an arbitrary string to `DatetimeString`, throwing an `InvalidDatetimeError` if the string does not conform.
1127
+ - **`isDatetimeString(input)`** - Type guard that returns `true` if the input is a valid `DatetimeString`.
1128
+ - **`ifDatetimeString(input)`** - Returns the input as a `DatetimeString` if valid, or `undefined` otherwise.
1129
+ - **`currentDatetimeString()`** - Returns the current date and time as `DatetimeString`.
1130
+
1131
+ ```typescript
1132
+ import { l } from '@atproto/lex'
1133
+
1134
+ // Convert a Date object to a DatetimeString (or throws)
1135
+ const someDate = new Date('2024-01-15T12:30:00Z')
1136
+ const now = l.toDatetimeString(someDate)
1137
+
1138
+ // Get the current datetime as a DatetimeString
1139
+ const now = l.currentDatetimeString()
1140
+
1141
+ // Validate and cast an existing string
1142
+ const dt = l.asDatetimeString('2024-01-15T12:30:00.000Z')
1143
+
1144
+ // Type guard for conditional checks
1145
+ if (l.isDatetimeString(someString)) {
1146
+ // someString is now typed as DatetimeString
1147
+ }
1148
+ ```
1149
+
1150
+ ## Advanced Usage
1151
+
1152
+ ### Workflow Integration
1153
+
1154
+ #### Development Workflow
1155
+
1156
+ Add these scripts to your `package.json`:
1157
+
1158
+ ```json
1159
+ {
1160
+ "scripts": {
1161
+ "update-lexicons": "lex install --update --save",
1162
+ "postinstall": "lex install --ci",
1163
+ "prebuild": "lex build",
1164
+ "build": "# Your build command here"
1165
+ }
1166
+ }
1167
+ ```
1168
+
1169
+ This ensures that:
1170
+
1171
+ 1. Lexicons are verified against the manifest after every `npm install` or `pnpm install`.
1172
+ 2. TypeScript schemas are built before your project is built.
1173
+ 3. You can easily update lexicons with `npm run update-lexicons` or `pnpm update-lexicons`.
1174
+
1175
+ ### Tree-Shaking
1176
+
1177
+ The generated TypeScript code is structured to be tree-shakeable, but the way you reference schemas has a meaningful impact on the final bundle size. There are several ways to refer to a generated schema, and each comes with different trade-offs.
1178
+
1179
+ #### Namespace notation
1180
+
1181
+ The most ergonomic style is to use a namespace import and reference schemas through dotted paths:
1182
+
1183
+ ```typescript
1184
+ import * as com from './lexicons/com.js'
1185
+
1186
+ await client.call(com.atproto.repo.getRecord, {/* ... */})
1187
+ ```
1188
+
1189
+ This style is convenient and reads naturally as it mirrors the NSID of the schema. However, it produces the largest bundles. From the bundler's point of view, `com.atproto.repo.getRecord` is the whole schema namespace (which contains the `main` schema as well as helpers, and any other definitions). The bundler cannot know that `client.call()` only consumes the `main` schema, so it has to keep the rest of the namespace alive in the bundle.
1190
+
1191
+ #### Explicit `.main` reference
1192
+
1193
+ You can mitigate the bundle-size cost by explicitly naming the `main` definition:
1194
+
1195
+ ```typescript
1196
+ import * as com from './lexicons/com.js'
1197
+
1198
+ await client.call(com.atproto.repo.getRecord.main, {/* ... */})
1199
+ ```
1200
+
1201
+ This lets the bundler drop the sibling definitions inside `getRecord` that aren't referenced. The drawback is that it leaks an implementation detail: the `main` segment of the path. In Lexicon, `main` is typically implicit:
1202
+
1203
+ - Records use a `$type` of `app.bsky.feed.post` (no `#main`)
1204
+ - XRPC endpoints are exposed as `/xrpc/com.atproto.repo.getRecord` (no `main`)
1205
+
1206
+ So writing `.main` in application code feels verbose compared to how Lexicons are normally referred to.
1207
+
1208
+ #### Direct named import from the schema file
1209
+
1210
+ You can also import the `main` schema directly from the file that defines it:
1211
+
1212
+ ```typescript
1213
+ import { main as getRecord } from './lexicons/com/atproto/repo/getRecord.js'
1214
+
1215
+ await client.call(getRecord, {/* ... */})
1216
+ ```
1217
+
1218
+ This produces equally small bundles as the explicit `.main` reference, but it still surfaces the `main` identifier: you have to know to import `main` and likely rename it.
1219
+
1220
+ #### Default import (recommended)
1221
+
1222
+ To make the small-bundle path also the ergonomic path, every namespace file generated by `lex build` re-exports the `main` schema as its `default` export:
1223
+
1224
+ ```typescript
1225
+ // generated file: ./lexicons/com/atproto/repo/getRecord.js
1226
+ export * from './getRecord.defs.js'
1227
+ export { main as default } from './getRecord.defs.js'
1228
+ ```
1229
+
1230
+ This means you can write:
1231
+
1232
+ ```typescript
1233
+ import getRecord from './lexicons/com/atproto/repo/getRecord.js'
1234
+ import post from './lexicons/app/bsky/feed/post.js'
1235
+
1236
+ await client.call(getRecord, {/* ... */})
1237
+ await client.create(post, {/* ... */})
1238
+ ```
1239
+
1240
+ This is the most bundle-friendly style: the bundler only pulls in the `main` schema, and the import name doesn't have to mention `main` at all. This helps keeping application code aligned with how Lexicons are usually identified.
1241
+
1242
+ #### Drawbacks of the default export
1243
+
1244
+ The `default` re-export is enabled by default but has two minor drawbacks:
1245
+
1246
+ 1. It is one additional property on the namespace module, which can very slightly increase bundle size if you also use the namespace in some places.
1247
+ 2. Any Lexicon document whose path segment is literally `default` (for example a hypothetical `com.example.records.default`) would conflict with the generated `default` export.
1248
+
1249
+ If either of these matters for your use case, you can disable the generation of `default` exports with the `--no-defaultExport` flag:
1250
+
1251
+ ```bash
1252
+ lex build --no-defaultExport
1253
+ ```
1254
+
1255
+ #### Summary
1256
+
1257
+ | Style | Bundle size | Ergonomics |
1258
+ | ------------------------------------------------------ | ----------- | ---------------------------- |
1259
+ | `com.atproto.repo.getRecord` (namespace) | Largest | Best: matches the NSID |
1260
+ | `com.atproto.repo.getRecord.main` | Small | Leaks the `main` identifier |
1261
+ | `import { main as getRecord } from '.../getRecord.js'` | Small | Verbose, leaks `main` |
1262
+ | `import getRecord from '.../getRecord.js'` | Small | Concise, no `main` in source |
1263
+
1264
+ For libraries and applications where bundle size matters (typically anything shipped to a browser), prefer the default-import style. For scripts, tests, and server-side code where the bundle size of generated schemas is not a concern, the namespace style is perfectly fine.
1265
+
1266
+ ### Blob references
1267
+
1268
+ In AT Protocol, binary data (blobs) are referenced using blob references, which include metadata like MIME type and size. These references allow PDSs to determine which binary data ("files") is referenced by records.
1269
+
1270
+ #### TypedBlobRef: The Current Standard
1271
+
1272
+ The current standard format for blob references is `TypedBlobRef`:
1273
+
1274
+ ```typescript
1275
+ import { TypedBlobRef } from '@atproto/lex'
1276
+
1277
+ const blobRef: TypedBlobRef = {
1278
+ $type: 'blob',
1279
+ ref: parseCid('bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'),
1280
+ mimeType: 'image/png',
1281
+ size: 12345,
1282
+ }
1283
+ ```
1284
+
1285
+ **When creating new blobs**, always use the `TypedBlobRef` format. This is the format returned by `client.uploadBlob()` and expected by PDS endpoints.
1286
+
1287
+ #### LegacyBlobRef: Historical Format
1288
+
1289
+ Historically, blob references used a simpler format without the `$type` property:
1290
+
1291
+ ```typescript
1292
+ type LegacyBlobRef = {
1293
+ cid: string // CID as a string (not a Cid object)
1294
+ mimeType: string // No size property
1295
+ }
1296
+ ```
1297
+
1298
+ **Legacy blob references still exist in the AT Protocol network** in older records created before the format migration. While new blobs should always be created as `TypedBlobRef`, your code must be prepared to handle both formats when reading existing data.
1299
+
1300
+ #### Working with Both Formats
1301
+
1302
+ The `BlobRef` type is a union that accepts both formats:
1303
+
1304
+ ```typescript
1305
+ import {
1306
+ BlobRef,
1307
+ isBlobRef,
1308
+ isTypedBlobRef,
1309
+ isLegacyBlobRef,
1310
+ } from '@atproto/lex'
1311
+
1312
+ // When reading data, always use BlobRef to handle both formats
1313
+ function processBlobRef(blob: BlobRef) {
1314
+ if (isTypedBlobRef(blob)) {
1315
+ console.log('Modern blob:', blob.ref, blob.mimeType, blob.size)
1316
+ } else if (isLegacyBlobRef(blob)) {
1317
+ console.log('Legacy blob:', blob.cid, blob.mimeType)
1318
+ }
1319
+ }
1320
+
1321
+ // Or use the isBlobRef type guard which accepts both
1322
+ if (isBlobRef(value)) {
1323
+ // value is BlobRef (either TypedBlobRef or LegacyBlobRef)
1324
+ }
1325
+ ```
1326
+
1327
+ Helper functions work with both formats:
1328
+
1329
+ ```typescript
1330
+ import {
1331
+ getBlobCid,
1332
+ getBlobCidString,
1333
+ getBlobMime,
1334
+ getBlobSize,
1335
+ } from '@atproto/lex'
1336
+
1337
+ // These utilities work with both TypedBlobRef and LegacyBlobRef
1338
+ const cid = getBlobCid(blobRef) // Returns Cid object
1339
+ const cidStr = getBlobCidString(blobRef) // Returns string (optimized)
1340
+ const mime = getBlobMime(blobRef) // Returns mimeType
1341
+ const size = getBlobSize(blobRef) // Returns number | undefined (legacy refs lack size)
1342
+ ```
1343
+
1344
+ > [!IMPORTANT]
1345
+ >
1346
+ > **Validation behavior with legacy blobs:**
1347
+ >
1348
+ > - In **strict mode** (`strict: true`, the default): Legacy blob references are rejected during validation. Use this mode when you control the data source and expect only modern blobs.
1349
+ > - In **non-strict mode** (`strict: false`): Legacy blob references are accepted. This mode is used automatically when `strictResponseProcessing: false` is set on the Client, allowing your application to handle older records from the network gracefully.
1350
+ >
1351
+ > ```typescript
1352
+ > // Strict mode (default) - rejects legacy blobs
1353
+ > schema.$safeParse(data) // { strict: true }
1354
+ >
1355
+ > // Non-strict mode - accepts legacy blobs
1356
+ > schema.$safeParse(data, { strict: false })
1357
+ > ```
1358
+
1359
+ ### Actions
1360
+
1361
+ Actions are composable functions that combine multiple XRPC calls into higher-level operations. They can be invoked using `client.call()` just like Lexicon methods, making them a powerful tool for building library-style APIs on top of the low-level client.
1362
+
1363
+ #### What are Actions?
1364
+
1365
+ An `Action` is a function with this signature:
1366
+
1367
+ ```typescript
1368
+ type Action<Input, Output> = (
1369
+ client: Client,
1370
+ input: Input,
1371
+ options: ActionOptions,
1372
+ ) => Output | Promise<Output>
1373
+ ```
1374
+
1375
+ Actions receive:
1376
+
1377
+ - `client` - The Client instance (to make XRPC calls)
1378
+ - `input` - The input data for the action
1379
+ - `options` - `ActionOptions` (currently just `{ signal?: AbortSignal }`)
1380
+
1381
+ #### Using Actions
1382
+
1383
+ Actions are called using `client.call()`, the same method used for XRPC queries and procedures:
1384
+
1385
+ ```typescript
1386
+ import { Action, Client, l } from '@atproto/lex'
1387
+ import * as app from './lexicons/app.js'
1388
+
1389
+ // Define an action
1390
+ export const likePost: Action<
1391
+ { uri: string; cid: string },
1392
+ { uri: string; cid: string }
1393
+ > = async (client, { uri, cid }, options) => {
1394
+ client.assertAuthenticated()
1395
+
1396
+ const result = await client.create(
1397
+ app.bsky.feed.like,
1398
+ {
1399
+ subject: { uri, cid },
1400
+ createdAt: l.currentDatetimeString(),
1401
+ },
1402
+ options,
1403
+ )
1404
+
1405
+ return result
1406
+ }
1407
+
1408
+ // Use the action
1409
+ const client = new Client(session)
1410
+ const like = await client.call(likePost, {
1411
+ uri: 'at://did:plc:abc/app.bsky.feed.post/123',
1412
+ cid: 'bafyreiabc...',
1413
+ })
1414
+ ```
1415
+
1416
+ #### Composing Multiple Operations
1417
+
1418
+ Actions excel at combining multiple XRPC calls:
1419
+
1420
+ ```typescript
1421
+ import { Action, Client } from '@atproto/lex'
1422
+ import * as app from './lexicons/app.js'
1423
+
1424
+ type Preference = app.bsky.actor.defs.Preferences[number]
1425
+
1426
+ // Action that reads, modifies, and writes preferences
1427
+ const upsertPreference: Action<Preference, Preference[]> = async (
1428
+ client,
1429
+ newPref,
1430
+ options,
1431
+ ) => {
1432
+ // Read current preferences
1433
+ const { preferences } = await client.call(
1434
+ app.bsky.actor.getPreferences,
1435
+ options,
1436
+ )
1437
+
1438
+ // Update the preference list
1439
+ const updated = [
1440
+ ...preferences.filter((p) => p.$type !== newPref.$type),
1441
+ newPref,
1442
+ ]
1443
+
1444
+ // Save updated preferences
1445
+ await client.call(
1446
+ app.bsky.actor.putPreferences,
1447
+ { preferences: updated },
1448
+ options,
1449
+ )
1450
+
1451
+ return updated
1452
+ }
1453
+
1454
+ // Use it
1455
+ await client.call(
1456
+ upsertPreference,
1457
+ app.bsky.actor.defs.adultContentPref.build({ enabled: true }),
1458
+ )
1459
+ ```
1460
+
1461
+ #### Higher-Order Actions
1462
+
1463
+ Actions can call other actions, enabling powerful composition:
1464
+
1465
+ ```typescript
1466
+ import { Action } from '@atproto/lex'
1467
+ import * as app from './lexicons/app.js'
1468
+
1469
+ type Preference = app.bsky.actor.defs.Preferences[number]
1470
+
1471
+ // Low-level action: update preferences with a function
1472
+ const updatePreferences: Action<
1473
+ (prefs: Preference[]) => Preference[] | false,
1474
+ Preference[]
1475
+ > = async (client, updateFn, options) => {
1476
+ const { preferences } = await client.call(
1477
+ app.bsky.actor.getPreferences,
1478
+ options,
1479
+ )
1480
+
1481
+ const updated = updateFn(preferences)
1482
+ if (updated === false) return preferences
1483
+
1484
+ await client.call(
1485
+ app.bsky.actor.putPreferences,
1486
+ { preferences: updated },
1487
+ options,
1488
+ )
1489
+
1490
+ return updated
1491
+ }
1492
+
1493
+ // Higher-level action: upsert a specific preference
1494
+ const upsertPreference: Action<Preference, Preference[]> = async (
1495
+ client,
1496
+ pref,
1497
+ options,
1498
+ ) => {
1499
+ return updatePreferences(
1500
+ client,
1501
+ (prefs) => [...prefs.filter((p) => p.$type !== pref.$type), pref],
1502
+ options,
1503
+ )
1504
+ }
1505
+
1506
+ // Even higher-level: enable adult content
1507
+ const enableAdultContent: Action<void, Preference[]> = async (
1508
+ client,
1509
+ _,
1510
+ options,
1511
+ ) => {
1512
+ return upsertPreference(
1513
+ client,
1514
+ app.bsky.actor.defs.adultContentPref.build({ enabled: true }),
1515
+ options,
1516
+ )
1517
+ }
1518
+
1519
+ // Use the high-level action
1520
+ await client.call(enableAdultContent)
1521
+ ```
1522
+
1523
+ ### Using a Single Client for Multiple Services
1524
+
1525
+ Because the client's `service` and `labelers` options are just _defaults_, a single `Client` instance can be used to talk to multiple services. This is the recommended pattern for SDK-style code: configure the client to talk to an AppView by default, and override `service` on a per-request basis when a request must reach another service — or the user's PDS directly (`service: null`).
1526
+
1527
+ ```typescript
1528
+ import { Client } from '@atproto/lex'
1529
+ import * as app from './lexicons/app.js'
1530
+ import * as com from './lexicons/com.js'
1531
+
1532
+ const client = new Client(session, {
1533
+ // All requests are proxied to the AppView by default
1534
+ service: 'did:web:api.bsky.app#bsky_appview',
1535
+ })
1536
+
1537
+ // Proxied to the AppView (client default)
1538
+ const { feed } = await client.call(app.bsky.feed.getTimeline)
1539
+
1540
+ // Sent directly to the user's PDS (no atproto-proxy header)
1541
+ const { body } = await client.xrpc(com.atproto.repo.getRecord, {
1542
+ service: null,
1543
+ params: {
1544
+ repo: client.assertDid,
1545
+ collection: 'app.bsky.actor.profile',
1546
+ rkey: 'self',
1547
+ },
1548
+ })
1549
+
1550
+ // Proxied to a different service, just for this request
1551
+ await client.xrpc(app.bsky.actor.getProfile, {
1552
+ service: 'did:web:com.example.other#other_service',
1553
+ params: { actor: client.assertDid },
1554
+ })
1555
+ ```
1556
+
1557
+ > [!NOTE]
1558
+ >
1559
+ > The record helpers (`create()`, `get()`, `put()`, `delete()`, `list()`, `createRecord()`, `getRecord()`, `putRecord()`, `deleteRecord()`, `listRecords()`, `applyWrites()`, `uploadBlob()`, `getBlob()`) always target the user's PDS: they default to `service: null` and `labelers: null`, ignoring the client's instance-wide defaults (unless explicitly overridden in their options).
1560
+
1561
+ If you need clients with different configurations sharing the same authentication, create them from the same session (or reuse an existing client's `agent`):
1562
+
1563
+ ```typescript
1564
+ const pdsClient = new Client(session)
1565
+ const bskyClient = new Client(pdsClient.agent, {
1566
+ service: 'did:web:api.bsky.app#bsky_appview',
1567
+ })
1568
+ ```
1569
+
1570
+ > [!NOTE]
1571
+ >
1572
+ > In previous version of this library, `Client` implemented the `Agent` interface, and its `fetchHandler` method could be used as the agent of another `Client`. This lead to confusing bugs ([#5110](https://github.com/bluesky-social/atproto/issues/5110)) where the inner agent (client) would set `atproto-proxy` and `atproto-accept-labelers` headers on requests where the outer client explicitly set `service: null` and `labelers: null`. This is no longer the case: a `Client` can no longer be used as the agent of another `Client`. To share authentication between differently-configured clients, build them from the same session.
1573
+
1574
+ ### Building Library-Style APIs with Actions
1575
+
1576
+ Actions enable you to create high-level, convenience APIs similar to [@atproto/api](https://www.npmjs.com/package/@atproto/api)'s `Agent` class. Here are patterns for common operations:
1577
+
1578
+ #### Creating Posts
1579
+
1580
+ ```typescript
1581
+ import { Action, l } from '@atproto/lex'
1582
+ import * as app from './lexicons/app.js'
1583
+
1584
+ type PostInput = Partial<app.bsky.feed.post.Main> &
1585
+ Omit<app.bsky.feed.post.Main, 'createdAt'>
1586
+
1587
+ export const post: Action<PostInput, { uri: string; cid: string }> = async (
1588
+ client,
1589
+ record,
1590
+ options,
1591
+ ) => {
1592
+ return client.create(
1593
+ app.bsky.feed.post,
1594
+ {
1595
+ ...record,
1596
+ createdAt: record.createdAt || l.currentDatetimeString(),
1597
+ },
1598
+ options,
1599
+ )
1600
+ }
1601
+
1602
+ // Usage
1603
+ await client.call(post, {
1604
+ text: 'Hello, AT Protocol!',
1605
+ langs: ['en'],
1606
+ })
1607
+ ```
1608
+
1609
+ #### Following Users
1610
+
1611
+ ```typescript
1612
+ import { Action, l } from '@atproto/lex'
1613
+ import { AtUri } from '@atproto/syntax'
1614
+ import * as app from './lexicons/app.js'
1615
+
1616
+ export const follow: Action<
1617
+ { did: string },
1618
+ { uri: string; cid: string }
1619
+ > = async (client, { did }, options) => {
1620
+ return client.create(
1621
+ app.bsky.graph.follow,
1622
+ {
1623
+ subject: did,
1624
+ createdAt: l.currentDatetimeString(),
1625
+ },
1626
+ options,
1627
+ )
1628
+ }
1629
+
1630
+ export const unfollow: Action<{ followUri: string }, void> = async (
1631
+ client,
1632
+ { followUri },
1633
+ options,
1634
+ ) => {
1635
+ const uri = new AtUri(followUri)
1636
+ await client.delete(app.bsky.graph.follow, {
1637
+ ...options,
1638
+ rkey: uri.rkey,
1639
+ })
1640
+ }
1641
+
1642
+ // Usage
1643
+ const { uri } = await client.call(follow, { did: 'did:plc:abc123' })
1644
+ await client.call(unfollow, { followUri: uri })
1645
+ ```
1646
+
1647
+ #### Updating Profile with Retry Logic
1648
+
1649
+ ```typescript
1650
+ import { Action, XrpcResponseError } from '@atproto/lex'
1651
+ import * as app from './lexicons/app.js'
1652
+ import * as com from './lexicons/com.js'
1653
+
1654
+ type ProfileUpdate = Partial<Omit<app.bsky.actor.profile.Main, '$type'>>
1655
+
1656
+ export const updateProfile: Action<ProfileUpdate, void> = async (
1657
+ client,
1658
+ updates,
1659
+ options,
1660
+ ) => {
1661
+ const maxRetries = 5
1662
+ for (let attempt = 0; ; attempt++) {
1663
+ try {
1664
+ // Get current profile and its CID
1665
+ const res = await client.xrpc(com.atproto.repo.getRecord, {
1666
+ ...options,
1667
+ params: {
1668
+ repo: client.assertDid,
1669
+ collection: 'app.bsky.actor.profile',
1670
+ rkey: 'self',
1671
+ },
1672
+ })
1673
+
1674
+ const current = app.bsky.actor.profile.$safeValidate(res.body.record)
1675
+
1676
+ // Merge updates with current profile (if valid)
1677
+ const updated = app.bsky.actor.profile.$build({
1678
+ ...(current.success ? current.value : undefined),
1679
+ ...updates,
1680
+ })
1681
+
1682
+ // Save with optimistic concurrency control
1683
+ await client.put(app.bsky.actor.profile, updated, {
1684
+ ...options,
1685
+ swapRecord: res?.body.cid ?? null,
1686
+ })
1687
+
1688
+ return
1689
+ } catch (error) {
1690
+ // Retry on swap/concurrent modification errors
1691
+ if (
1692
+ error instanceof XrpcResponseError &&
1693
+ error.name === 'SwapError' &&
1694
+ attempt < maxRetries - 1
1695
+ ) {
1696
+ continue
1697
+ }
1698
+
1699
+ throw error
1700
+ }
1701
+ }
1702
+ }
1703
+
1704
+ // Usage
1705
+ await client.call(updateProfile, {
1706
+ displayName: 'Alice',
1707
+ description: 'Software engineer',
1708
+ })
1709
+ ```
1710
+
1711
+ #### Packaging Actions as a Library
1712
+
1713
+ Create a collection of actions for your application:
1714
+
1715
+ ```typescript
1716
+ // actions.ts
1717
+ import { Action, Client } from '@atproto/lex'
1718
+ import * as app from './lexicons/app.js'
1719
+
1720
+ export const post: Action</* ... */> = async (client, input, options) => {
1721
+ /* ... */
1722
+ }
1723
+ export const like: Action</* ... */> = async (client, input, options) => {
1724
+ /* ... */
1725
+ }
1726
+ export const follow: Action</* ... */> = async (client, input, options) => {
1727
+ /* ... */
1728
+ }
1729
+ export const updateProfile: Action</* ... */> = async (
1730
+ client,
1731
+ input,
1732
+ options,
1733
+ ) => {
1734
+ /* ... */
1735
+ }
1736
+ ```
1737
+
1738
+ Usage:
1739
+
1740
+ ```typescript
1741
+ import * as actions from './actions.js'
1742
+
1743
+ await client.call(actions.post, { text: 'Hello!' })
1744
+ ```
1745
+
1746
+ #### Best Practices for Actions
1747
+
1748
+ 1. **Type Safety**: Always provide explicit type parameters for `Action<Input, Output>`
1749
+ 2. **Authentication**: Use `client.assertAuthenticated()` when auth is required
1750
+ 3. **Abort Signals**: Check `options.signal?.throwIfAborted()` between long operations
1751
+ 4. **Composition**: Build complex actions from simpler ones
1752
+ 5. **Retries**: Implement retry logic for operations with optimistic concurrency control
1753
+ 6. **Tree-shaking**: Export actions individually to allow tree-shaking (instead of bundling them in a single class)
1754
+
1755
+ ### Standard Schema Compatibility
1756
+
1757
+ All generated schemas implement the [Standard Schema](https://standardschema.dev/) interface (`StandardSchemaV1`), which means they can be used with any library or framework that supports Standard Schema, such as form validation libraries, API frameworks, and more.
1758
+
1759
+ Every `Schema` instance exposes a `~standard` property conforming to the spec:
1760
+
1761
+ ```typescript
1762
+ import * as app from './lexicons/app.js'
1763
+
1764
+ // Use with any Standard Schema-compatible library
1765
+ const schema = app.bsky.feed.post
1766
+
1767
+ schema['~standard'].version // 1
1768
+ schema['~standard'].vendor // '@atproto/lex-schema'
1769
+
1770
+ // Validate using the Standard Schema interface
1771
+ const result = schema['~standard'].validate(someData)
1772
+
1773
+ if ('value' in result) {
1774
+ console.log(result.value) // Parsed and validated data
1775
+ } else {
1776
+ console.error(result.issues)
1777
+ }
1778
+ ```
1779
+
1780
+ When validated through the Standard Schema interface, schemas operate in "parse" mode, meaning transformations like defaults and coercions are applied to the output.
1781
+
1782
+ ### Validating Generic Schemas with `$check`
1783
+
1784
+ `$check(data)` is the non-narrowing counterpart to [`$assert(data)`](#assertdata---type-narrowing-assertion): both throw when `data` does not match the schema, but `$check` does not refine the static type of its argument.
1785
+
1786
+ `$check` is rarely needed in application code — prefer `$assert`. It is intended for library-style code that takes a schema as a generic parameter, where TypeScript cannot satisfy the assertion-signature requirement and `$assert` produces the following error:
1787
+
1788
+ > 'schema' needs an explicit type annotation.
1789
+ > Assertions require every name in the call target to be declared with an explicit type annotation. `ts(2775)`
1790
+
1791
+ In that situation, switch to `$check`:
1792
+
1793
+ ```typescript
1794
+ import type { Schema } from '@atproto/lex'
1795
+
1796
+ function ensureMatches<S extends Schema>(schema: S, data: unknown) {
1797
+ // schema.$assert(data) // ❌ ts(2775): needs an explicit type annotation
1798
+ schema.$check(data) // ✅ throws on invalid, no type narrowing
1799
+ }
1800
+ ```
1801
+
1802
+ ## License
1803
+
1804
+ MIT or Apache2