@sanity/client 7.1.0-views.0 → 7.1.0-views.2

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 (80) hide show
  1. package/README.md +810 -40
  2. package/dist/_chunks-cjs/config.cjs +14 -0
  3. package/dist/_chunks-cjs/config.cjs.map +1 -1
  4. package/dist/_chunks-cjs/dataMethods.cjs +197 -32
  5. package/dist/_chunks-cjs/dataMethods.cjs.map +1 -1
  6. package/dist/_chunks-cjs/isRecord.cjs +6 -0
  7. package/dist/_chunks-cjs/isRecord.cjs.map +1 -0
  8. package/dist/_chunks-cjs/resolveEditInfo.cjs +3 -5
  9. package/dist/_chunks-cjs/resolveEditInfo.cjs.map +1 -1
  10. package/dist/_chunks-cjs/stegaClean.cjs +4 -0
  11. package/dist/_chunks-cjs/stegaClean.cjs.map +1 -1
  12. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs +2 -5
  13. package/dist/_chunks-cjs/stegaEncodeSourceMap.cjs.map +1 -1
  14. package/dist/_chunks-es/config.js +15 -1
  15. package/dist/_chunks-es/config.js.map +1 -1
  16. package/dist/_chunks-es/dataMethods.js +200 -33
  17. package/dist/_chunks-es/dataMethods.js.map +1 -1
  18. package/dist/_chunks-es/isRecord.js +7 -0
  19. package/dist/_chunks-es/isRecord.js.map +1 -0
  20. package/dist/_chunks-es/resolveEditInfo.js +1 -3
  21. package/dist/_chunks-es/resolveEditInfo.js.map +1 -1
  22. package/dist/_chunks-es/stegaClean.js +4 -0
  23. package/dist/_chunks-es/stegaClean.js.map +1 -1
  24. package/dist/_chunks-es/stegaEncodeSourceMap.js +1 -4
  25. package/dist/_chunks-es/stegaEncodeSourceMap.js.map +1 -1
  26. package/dist/index.browser.cjs +1019 -59
  27. package/dist/index.browser.cjs.map +1 -1
  28. package/dist/index.browser.d.cts +1950 -149
  29. package/dist/index.browser.d.ts +1950 -149
  30. package/dist/index.browser.js +1021 -60
  31. package/dist/index.browser.js.map +1 -1
  32. package/dist/index.cjs +825 -29
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.d.cts +1950 -149
  35. package/dist/index.d.ts +1950 -149
  36. package/dist/index.js +826 -31
  37. package/dist/index.js.map +1 -1
  38. package/dist/stega.browser.d.cts +1950 -149
  39. package/dist/stega.browser.d.ts +1950 -149
  40. package/dist/stega.d.cts +1950 -149
  41. package/dist/stega.d.ts +1950 -149
  42. package/dist/views.cjs +21 -5
  43. package/dist/views.cjs.map +1 -1
  44. package/dist/views.d.cts +54 -36
  45. package/dist/views.d.ts +54 -36
  46. package/dist/views.js +22 -5
  47. package/dist/views.js.map +1 -1
  48. package/package.json +2 -1
  49. package/src/SanityClient.ts +652 -12
  50. package/src/agent/actions/AgentActionsClient.ts +29 -2
  51. package/src/agent/actions/commonTypes.ts +57 -17
  52. package/src/agent/actions/generate.ts +36 -2
  53. package/src/agent/actions/patch.ts +136 -0
  54. package/src/agent/actions/prompt.ts +145 -0
  55. package/src/agent/actions/transform.ts +105 -7
  56. package/src/agent/actions/translate.ts +5 -2
  57. package/src/config.ts +3 -1
  58. package/src/csm/walkMap.ts +1 -1
  59. package/src/data/dataMethods.ts +170 -12
  60. package/src/data/encodeQueryString.ts +1 -1
  61. package/src/data/eventsource.ts +16 -7
  62. package/src/data/listen.ts +10 -4
  63. package/src/data/live.ts +13 -5
  64. package/src/datasets/DatasetsClient.ts +4 -1
  65. package/src/defineCreateClient.ts +7 -1
  66. package/src/http/errors.ts +92 -27
  67. package/src/http/request.ts +3 -3
  68. package/src/http/requestOptions.ts +4 -0
  69. package/src/projects/ProjectsClient.ts +6 -2
  70. package/src/releases/ReleasesClient.ts +693 -0
  71. package/src/releases/createRelease.ts +53 -0
  72. package/src/types.ts +293 -10
  73. package/src/users/UsersClient.ts +7 -3
  74. package/src/util/codeFrame.ts +174 -0
  75. package/src/util/createVersionId.ts +79 -0
  76. package/src/{csm → util}/isRecord.ts +1 -1
  77. package/src/validators.ts +23 -1
  78. package/src/views/index.ts +65 -15
  79. package/umd/sanityClient.js +1067 -61
  80. package/umd/sanityClient.min.js +2 -2
package/README.md CHANGED
@@ -27,6 +27,10 @@ export const client = createClient({
27
27
  projectId: 'your-project-id',
28
28
  dataset: 'your-dataset-name',
29
29
  useCdn: true, // set to `false` to bypass the edge cache
30
+ // Set default headers to be included with all requests
31
+ headers: {
32
+ 'X-Custom-Header': 'custom-value'
33
+ },
30
34
  apiVersion: '2025-02-06', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
31
35
  // token: process.env.SANITY_SECRET_TOKEN // Needed for certain operations like updating content, accessing drafts or using draft perspectives
32
36
  })
@@ -91,6 +95,7 @@ export async function updateDocumentTitle(_id, title) {
91
95
  - [Delete documents](#delete-documents)
92
96
  - [Multiple mutations in a transaction](#multiple-mutations-in-a-transaction)
93
97
  - [Clientless patches \& transactions](#clientless-patches--transactions)
98
+ - [Release and version operations](#release-and-version-operations)
94
99
  - [Uploading assets](#uploading-assets)
95
100
  - [Examples: Uploading assets from Node.js](#examples-uploading-assets-from-nodejs)
96
101
  - [Examples: Uploading assets from the Browser](#examples-uploading-assets-from-the-browser)
@@ -106,11 +111,46 @@ export async function updateDocumentTitle(_id, title) {
106
111
  - [Action options](#action-options)
107
112
  - [Create Action](#create-action)
108
113
  - [Delete Action](#delete-action)
109
- - [Discard Action](#discard-action)
110
114
  - [Edit Action](#edit-action)
111
115
  - [Publish Action](#publish-action)
112
- - [ReplaceDraft Action](#replacedraft-action)
113
116
  - [Unpublish Action](#unpublish-action)
117
+ - [Agent Actions API](#agent-actions-api)
118
+ - [Overview](#overview)
119
+ - [Generating Content](#generating-content)
120
+ - [Generating images](#generating-images)
121
+ - [Example: Using GROQ in instructionParams](#example-using-groq-in-instructionparams)
122
+ - [Example: Using the async flag](#example-using-the-async-flag)
123
+ - [Transforming Documents](#transforming-documents)
124
+ - [Transforming images](#transforming-images)
125
+ - [Image descriptions](#image-descriptions)
126
+ - [Example: Field-based transformation](#example-field-based-transformation)
127
+ - [Translating Documents](#translating-documents)
128
+ - [Example: Storing language in a field](#example-storing-language-in-a-field)
129
+ - [Prompt the LLM](#prompt-the-llm)
130
+ - [Patch with a schema-aware API](#patch-with-a-schema-aware-api)
131
+ - [Version actions](#version-actions)
132
+ - [Create Version Action](#create-version)
133
+ - [Discard Version Action](#discard-version)
134
+ - [Replace Version Action](#replace-version)
135
+ - [Unpublish Version Action](#unpublish-action)
136
+ - [Release Actions](#release-actions)
137
+ - [Create Release Action](#create-release)
138
+ - [Edit Release Action](#edit-release)
139
+ - [Published Release Action](#publish-release)
140
+ - [Schedule Release Action](#schedule-release)
141
+ - [Unschedule Release Action](#unarchive-release)
142
+ - [Archive Release Action](#archive-release)
143
+ - [Unarchive Release Action](#unarchive-release)
144
+ - [Delete Release Action](#delete-release)
145
+ - [Views API](#views-api)
146
+ - [Quickstart](#quickstart-1)
147
+ - [Creating a views client instance](#creating-a-views-client-instance)
148
+ - [ESM](#esm-1)
149
+ - [CommonJS](#commonjs-1)
150
+ - [TypeScript](#typescript-1)
151
+ - [Other frameworks, type safety, etc](#other-frameworks-type-safety-etc)
152
+ - [Using a view](#using-a-view)
153
+ - [Developing a view](#developing-a-view)
114
154
  - [License](#license)
115
155
  - [From `v5`](#from-v5)
116
156
  - [The default `useCdn` is changed to `true`](#the-default-usecdn-is-changed-to-true)
@@ -1284,6 +1324,113 @@ client.mutate(transaction)
1284
1324
 
1285
1325
  An important note on this approach is that you cannot call `commit()` on transactions or patches instantiated this way, instead you have to pass them to `client.mutate()`
1286
1326
 
1327
+ ### Release and version operations
1328
+
1329
+ Release and version actions can be taken directly using the client's [actions API](#version-actions). Additionally, helper methods are provided which abstract some esoteric nomenclature with the release and version processing.
1330
+
1331
+ 0. Setup the client
1332
+
1333
+ ```js
1334
+ import {createClient} from '@sanity/client'
1335
+
1336
+ const client = createClient({
1337
+ projectId: 'your-project-id',
1338
+ dataset: 'bikeshop',
1339
+ })
1340
+ ```
1341
+
1342
+ 1. Create a new release
1343
+
1344
+ ```js
1345
+ const {releaseId} = await client.release.create({
1346
+ metadata: {
1347
+ title: 'New bike drop'
1348
+ releaseType: 'scheduled'
1349
+ }
1350
+ })
1351
+ ```
1352
+
1353
+ 2. Create a new document into the release
1354
+
1355
+ ```js
1356
+ client.createVersion({
1357
+ document: {
1358
+ _type: 'bike',
1359
+ name: 'Upgraded black bike',
1360
+ },
1361
+ releaseId,
1362
+ publishedId: 'bike-123',
1363
+ })
1364
+ ```
1365
+
1366
+ 3. Mark a document to be unpublished when the release is run
1367
+
1368
+ ```js
1369
+ client.unpublishVersion({
1370
+ publishedId: 'old-red-bike',
1371
+ releaseId,
1372
+ })
1373
+ ```
1374
+
1375
+ 4. List the release and all the documents within the release
1376
+
1377
+ ```js
1378
+ const newBikesRelease = await client.releases.get({releaseId})
1379
+ /**
1380
+ * {
1381
+ * _type: 'system.release',
1382
+ * _id: '_.releases.releaseId',
1383
+ * name: 'releaseId',
1384
+ * state: 'active',
1385
+ * metadata: {
1386
+ * name: 'New bike drop',
1387
+ * releaseType: 'scheduled'
1388
+ * }
1389
+ * }
1390
+ */
1391
+
1392
+ const releaseDocuments = await client.releases.getDocuments({
1393
+ releaseId,
1394
+ })
1395
+
1396
+ /**
1397
+ * Returns a list of documents eg.
1398
+ *
1399
+ * [{
1400
+ * _type: 'bike',
1401
+ * _id: 'versions.releaseId.bike-123',
1402
+ * name: 'Upgraded black bike',
1403
+ * ...
1404
+ * },
1405
+ * {
1406
+ * _type: 'bike',
1407
+ * _id: 'versions.releaseId.old-red-bike',
1408
+ * _system: {
1409
+ * delete: true
1410
+ * }
1411
+ * }]
1412
+ */
1413
+ ```
1414
+
1415
+ 5. Schedule the release (to run in 1 hours time)
1416
+
1417
+ ```js
1418
+ client.release.schedule({
1419
+ releaseId,
1420
+ publishAt: new Date(Date.now() + 3600000).toISOString(),
1421
+ })
1422
+ ```
1423
+
1424
+ 6. After the release has run, check and delete the release
1425
+
1426
+ ```js
1427
+ const runRelease = await client.releases.get({releaseId})
1428
+
1429
+ if (runRelease.state === 'published' && !runRelease.error) {
1430
+ client.releases.delete({releaseId})
1431
+ }
1432
+ ```
1433
+
1287
1434
  ### Actions
1288
1435
 
1289
1436
  The Actions API provides a new interface for creating, updating and publishing documents. It is a wrapper around the [Actions API](https://www.sanity.io/docs/http-actions).
@@ -1343,27 +1490,6 @@ client
1343
1490
  })
1344
1491
  ```
1345
1492
 
1346
- #### Discard Action
1347
-
1348
- A draft document can be deleted by specifying a discard action type:
1349
-
1350
- ```js
1351
- client
1352
- .action(
1353
- {
1354
- actionType: 'sanity.action.document.discard',
1355
- draftId: 'draft.bike-123',
1356
- },
1357
- actionOptions,
1358
- )
1359
- .then(() => {
1360
- console.log('Bike draft deleted')
1361
- })
1362
- .catch((err) => {
1363
- console.error('Discard failed: ', err.message)
1364
- })
1365
- ```
1366
-
1367
1493
  #### Edit Action
1368
1494
 
1369
1495
  A patch can be applied to an existing document draft or create a new one by specifying an edit action type:
@@ -1410,47 +1536,268 @@ client
1410
1536
  })
1411
1537
  ```
1412
1538
 
1413
- #### ReplaceDraft Action
1539
+ #### Unpublish Action
1414
1540
 
1415
- An existing document draft can be deleted and replaced by a new one by specifying a replaceDraft action type:
1541
+ A published document can be retracted by specifying an unpublish action type:
1416
1542
 
1417
1543
  ```js
1418
1544
  client
1419
1545
  .action(
1420
1546
  {
1421
- actionType: 'sanity.action.document.replaceDraft',
1547
+ actionType: 'sanity.action.document.unpublish',
1548
+ draftId: 'draft.bike-123',
1422
1549
  publishedId: 'bike-123',
1423
- attributes: {name: 'Sanity Tandem Extraordinaire', _type: 'bike', seats: 1},
1424
1550
  },
1425
1551
  actionOptions,
1426
1552
  )
1427
1553
  .then(() => {
1428
- console.log('Bike draft replaced')
1554
+ console.log('Bike draft unpublished')
1429
1555
  })
1430
1556
  .catch((err) => {
1431
- console.error('Replace draft failed: ', err.message)
1557
+ console.error('Unpublish draft failed: ', err.message)
1432
1558
  })
1433
1559
  ```
1434
1560
 
1435
- #### Unpublish Action
1561
+ ## Version actions
1436
1562
 
1437
- A published document can be retracted by specifying an unpublish action type:
1563
+ ### Create version
1564
+
1565
+ Create a draft or release version of a published document.
1566
+
1567
+ ```js
1568
+ client.action(
1569
+ {
1570
+ actionType: 'sanity.action.document.version.create',
1571
+ publishedId: 'bike-123',
1572
+ document: {
1573
+ _id: 'versions.new-bike-release.bike-123'
1574
+ _type: 'bike'
1575
+ }
1576
+ }
1577
+ ).then(() => {
1578
+ console.log('Copy of published `bike-123` created in release `new-bike-release`')
1579
+ }).catch((err) => {
1580
+ console.error('Create version failed: ', err.message)
1581
+ })
1582
+ ```
1583
+
1584
+ > [!NOTE]
1585
+ > Replacing `versions.<releaseId>` with `drafts` will create a new draft version from the published document.
1586
+
1587
+ ### Discard version
1588
+
1589
+ Discard a draft or release version.
1438
1590
 
1439
1591
  ```js
1440
1592
  client
1441
- .action(
1442
- {
1443
- actionType: 'sanity.action.document.unpublish',
1444
- draftId: 'draft.bike-123',
1445
- publishedId: 'bike-123',
1593
+ .action({
1594
+ actionType: 'sanity.action.document.version.discard',
1595
+ versionId: 'versions.new-bike-release.bike-123',
1596
+ })
1597
+ .then(() => {
1598
+ console.log('Discarded the version of `bike-123` within the `new-bike-release` release')
1599
+ })
1600
+ .catch((err) => {
1601
+ console.error('Discard version failed: ', err.message)
1602
+ })
1603
+ ```
1604
+
1605
+ ### Replace version
1606
+
1607
+ Replaces the contents of an existing draft or release version document.
1608
+
1609
+ ```js
1610
+ client
1611
+ .action({
1612
+ actionType: 'sanity.action.document.version.replace',
1613
+ document: {
1614
+ _id: 'versions.new-bike-release.bike-123',
1615
+ color: 'red',
1616
+ _type: 'bike',
1446
1617
  },
1447
- actionOptions,
1448
- )
1618
+ })
1449
1619
  .then(() => {
1450
- console.log('Bike draft unpublished')
1620
+ console.log('Replaced the existing `bike-123` document within the `new-bike-release` release')
1451
1621
  })
1452
1622
  .catch((err) => {
1453
- console.error('Unpublish draft failed: ', err.message)
1623
+ console.error('Replace version failed: ', err.message)
1624
+ })
1625
+ ```
1626
+
1627
+ ### Unpublish version
1628
+
1629
+ Marks a document to be unpublished when the release it is part of is run.
1630
+
1631
+ ```js
1632
+ client
1633
+ .action({
1634
+ actionType: 'sanity.action.document.version.unpublish',
1635
+ publishedId: 'bike-123',
1636
+ versionId: 'versions.new-bike-release.bike-123',
1637
+ })
1638
+ .then(() => {
1639
+ console.log('`bike-123` will be unpublished when `new-bike-release` release is run')
1640
+ })
1641
+ .catch((err) => {
1642
+ console.error('Unpublish version failed: ', err.message)
1643
+ })
1644
+ ```
1645
+
1646
+ ## Release Actions
1647
+
1648
+ ### Create release
1649
+
1650
+ Create a new release.
1651
+
1652
+ ```js
1653
+ client
1654
+ .action({
1655
+ actionType: 'sanity.action.release.create',
1656
+ releaseId: 'new-bikes-release',
1657
+ metadata: {
1658
+ title: 'New bikes',
1659
+ releaseType: 'undecided',
1660
+ },
1661
+ })
1662
+ .then(() => {
1663
+ console.log('`new-bikes-release` created')
1664
+ })
1665
+ .catch((err) => {
1666
+ console.error('Create release failed: ', err.message)
1667
+ })
1668
+ ```
1669
+
1670
+ ### Edit release
1671
+
1672
+ Edit the metadata on an existing release.
1673
+
1674
+ ```js
1675
+ client
1676
+ .action({
1677
+ actionType: 'sanity.action.release.edit',
1678
+ releaseId: 'new-bikes-release',
1679
+ patch: {
1680
+ set: {
1681
+ metadata: {
1682
+ releaseType: 'asap',
1683
+ },
1684
+ },
1685
+ },
1686
+ })
1687
+ .then(() => {
1688
+ console.log('`new-bikes-release` changed to `asap` release type')
1689
+ })
1690
+ .catch((err) => {
1691
+ console.error('Edit release failed: ', err.message)
1692
+ })
1693
+ ```
1694
+
1695
+ ### Publish release
1696
+
1697
+ Publish all document versions within a release.
1698
+
1699
+ ```js
1700
+ client
1701
+ .action({
1702
+ actionType: 'sanity.action.release.publish',
1703
+ releaseId: 'new-bikes-release',
1704
+ })
1705
+ .then(() => {
1706
+ console.log('`new-bikes-release` published')
1707
+ })
1708
+ .catch((err) => {
1709
+ console.error('Publish release failed: ', err.message)
1710
+ })
1711
+ ```
1712
+
1713
+ ### Schedule release
1714
+
1715
+ Schedule a release to be run now or in the future
1716
+
1717
+ ```js
1718
+ client
1719
+ .action({
1720
+ actionType: 'sanity.action.release.schedule',
1721
+ releaseId: 'new-bikes-release',
1722
+ publishAt: '2025-01-01T00:00:00.000Z',
1723
+ })
1724
+ .then(() => {
1725
+ console.log('`new-bikes-release` scheduled')
1726
+ })
1727
+ .catch((err) => {
1728
+ console.error('Schedule release failed: ', err.message)
1729
+ })
1730
+ ```
1731
+
1732
+ ### Unschedule release
1733
+
1734
+ Unschedule a currently scheduled release, to stop the release being run.
1735
+
1736
+ ```js
1737
+ client
1738
+ .action({
1739
+ actionType: 'sanity.action.release.unschedule',
1740
+ releaseId: 'new-bikes-release',
1741
+ })
1742
+ .then(() => {
1743
+ console.log('`new-bikes-release` unscheduled')
1744
+ })
1745
+ .catch((err) => {
1746
+ console.error('Unschedule release failed: ', err.message)
1747
+ })
1748
+ ```
1749
+
1750
+ ### Archive release
1751
+
1752
+ Mark an active (not published) release as archived.
1753
+
1754
+ ```js
1755
+ client
1756
+ .action({
1757
+ actionType: 'sanity.action.release.archive',
1758
+ releaseId: 'new-bikes-release',
1759
+ })
1760
+ .then(() => {
1761
+ console.log('`new-bikes-release` archived')
1762
+ })
1763
+ .catch((err) => {
1764
+ console.error('Archive release failed: ', err.message)
1765
+ })
1766
+ ```
1767
+
1768
+ ### Unarchive release
1769
+
1770
+ Once a release has been archived, the archive process may be undone by unarchiving the release.
1771
+
1772
+ ```js
1773
+ client
1774
+ .action({
1775
+ actionType: 'sanity.action.release.unarchive',
1776
+ releaseId: 'new-bikes-release',
1777
+ })
1778
+ .then(() => {
1779
+ console.log('`new-bikes-release` unarchived')
1780
+ })
1781
+ .catch((err) => {
1782
+ console.error('Unarchive release failed: ', err.message)
1783
+ })
1784
+ ```
1785
+
1786
+ ### Delete release
1787
+
1788
+ An archived release can be deleted, which will remove the system release document permanently from the dataset.
1789
+
1790
+ ```js
1791
+ client
1792
+ .action({
1793
+ actionType: 'sanity.action.release.delete',
1794
+ releaseId: 'new-bikes-release',
1795
+ })
1796
+ .then(() => {
1797
+ console.log('`new-bikes-release` deleted')
1798
+ })
1799
+ .catch((err) => {
1800
+ console.error('Delete release failed: ', err.message)
1454
1801
  })
1455
1802
  ```
1456
1803
 
@@ -1632,6 +1979,429 @@ client.config({dataset: 'newDataset'})
1632
1979
 
1633
1980
  Set client configuration. Required options are `projectId` and `dataset`.
1634
1981
 
1982
+ ### Agent Actions API
1983
+
1984
+ The Agent Actions API provides programmatic access to AI-powered content generation, transformation, and translation for your Sanity documents. These APIs are available on the `client.agent.action` namespace.
1985
+
1986
+ > **Note:** These APIs are currently in beta and may change in future releases.
1987
+
1988
+ #### Overview
1989
+
1990
+ Agent Actions allow you to:
1991
+
1992
+ - **Generate** new content for a document or specific fields using LLM instructions.
1993
+ - **Transform** a document based on instructions, optionally copying from a source document.
1994
+ - **Translate** a document or fields from one language to another, with support for style guides and protected phrases.
1995
+ - **Prompt** the LLM using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
1996
+ - **Patch** documents using a schema-aware API; validates that provided paths and values are schema compliant and handles `setIfMissing` semantics for deep value operations
1997
+
1998
+ All methods are available in both Promise and Observable forms:
1999
+
2000
+ - `client.agent.action.generate`, `client.agent.action.transform`, `client.agent.action.translate`, `client.agent.action.prompt`, `client.agent.action.patch` (Promise-based)
2001
+ - `client.observable.agent.action.generate`, etc. (Observable-based, for streaming or RxJS use)
2002
+
2003
+ ---
2004
+
2005
+ #### Generating Content
2006
+
2007
+ ```ts
2008
+ const result = await client.agent.action.generate({
2009
+ schemaId: 'your-schema-id',
2010
+ documentId: 'your-document-id',
2011
+ instruction: 'Write a summary for the following topic: $topic',
2012
+ instructionParams: {
2013
+ topic: 'Grapefruit',
2014
+ },
2015
+ target: {path: ['body']},
2016
+ })
2017
+ ```
2018
+
2019
+ - **schemaId**: The schema identifier for the document type.
2020
+ - **documentId**: The ID of the document to generate content for.
2021
+ - **instruction**: A string template describing what to generate. Use `$variable` for dynamic values.
2022
+ - **instructionParams**: Values for variables in the instruction. Supports constants, fields, documents, or GROQ queries.
2023
+ - **target**: (Optional) Specifies which fields or paths to generate content for.
2024
+ - **temperature**: (Optional) Controls variance, 0-1 – defaults to 0.3
2025
+ - **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
2026
+ - **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
2027
+ - **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
2028
+
2029
+ ##### Generating images
2030
+
2031
+ Generate will generate images the same was as AI Assist, for images that have been configured using
2032
+ [AI Assist schema options](https://github.com/sanity-io/assist/tree/main/plugin#image-generation).
2033
+
2034
+ To generate images _without_ changing the schema, directly target an image asset path.
2035
+
2036
+ For example, all the following will generate an image into the provided asset:
2037
+
2038
+ - `target: {path: ['image', 'asset'] }`
2039
+ - `target: {path: 'image', include: ['asset'] }`
2040
+
2041
+ Image generation can be combined with regular content targets:
2042
+
2043
+ - `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
2044
+
2045
+ Since Generate happens in a single LLM pass, the image will be contextually related to other generated content.
2046
+
2047
+ ##### Example: Using GROQ in instructionParams
2048
+
2049
+ ```ts
2050
+ await client.agent.action.generate({
2051
+ schemaId,
2052
+ documentId,
2053
+ instruction: 'Generate a title based on these: $list',
2054
+ instructionParams: {
2055
+ list: {
2056
+ type: 'groq',
2057
+ query: '*[_type==$type].title',
2058
+ params: {type: 'article'},
2059
+ },
2060
+ },
2061
+ target: {path: ['body']},
2062
+ })
2063
+ ```
2064
+
2065
+ #### Example: Using the async flag
2066
+
2067
+ The `async` parameter allows you to fire and forget and will not wait for a response from the LLMj, this works also in the Transform and Translate APIs.
2068
+
2069
+ ```ts
2070
+ const result = await client.agent.action.generate({
2071
+ schemaId: 'article',
2072
+ documentId: 'article-123',
2073
+ instruction: 'Write a comprehensive article about $topic',
2074
+ instructionParams: {
2075
+ topic: 'Climate Change',
2076
+ },
2077
+ target: {path: ['body']},
2078
+ async: true, // Enable async mode for long-running tasks or where you don't want to wait for the result
2079
+ })
2080
+
2081
+ // result will return back the document id
2082
+ console.log('Generation task started:', result._id)
2083
+ ```
2084
+
2085
+ #### Transforming Documents
2086
+
2087
+ ```ts
2088
+ const result = await client.agent.action.transform({
2089
+ schemaId: 'your-schema-id',
2090
+ documentId: 'source-document-id',
2091
+ instruction: 'Transform the content to a more formal tone.',
2092
+ targetDocument: {operation: 'edit', _id: 'target-document-id'},
2093
+ target: {path: ['body']},
2094
+ })
2095
+ ```
2096
+
2097
+ - **schemaId**: The schema identifier for the document type.
2098
+ - **documentId**: The source document ID.
2099
+ - **instruction**: A string template describing the transformation.
2100
+ - **targetDocument**: (Optional) Specify a different document to write the result to, or create a new one.
2101
+ - **target**: (Optional) Specifies which fields or paths to transform.
2102
+ - **temperature**: (Optional) Controls variance, 0-1 – defaults to 0
2103
+ - **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
2104
+ - **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
2105
+ - **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
2106
+
2107
+ ##### Transforming images
2108
+
2109
+ To transform an existing image, directly target an image asset path.
2110
+
2111
+ For example, all the following will transform the image into the provided asset:
2112
+
2113
+ - `target: {path: ['image', 'asset'] }`
2114
+ - `target: {path: 'image', include: ['asset'] }`
2115
+
2116
+ Image transform can be combined with regular content targets:
2117
+
2118
+ - `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
2119
+
2120
+ Image transform can have per-path instructions, just like any other target paths:
2121
+
2122
+ - `target: [{path: ['image', 'asset'], instruction: 'Make the sky blue' }`
2123
+
2124
+ ##### Image descriptions
2125
+
2126
+ ## Image description
2127
+
2128
+ Images can be transformed to a textual description by targeting a `string`, `text` or Portable Text field (`array` with `block`)
2129
+ with `operation: {type: 'image-description'}`.
2130
+
2131
+ Custom instructions for image description targets will be used to generate the description.
2132
+
2133
+ ###### Targeting image fields
2134
+ If a target is a descendant field of an image object, no `sourcePath` is required in the operation:
2135
+
2136
+ For example:
2137
+ - `target: {path: ['image', 'description'], operation: {type: 'image-description'} }`
2138
+ - `target: {path: ['array', {_key: 'abc'}, 'alt'], operation: {type: 'image-description'} } //assuming the item in the array on the key-ed path is an image`
2139
+ - `target: {path: ['image'], include: ['portableTextField'], operation: {type: 'image-description'}, instruction: 'Use formatting and headings to describe the image in great detail' }`
2140
+
2141
+ ###### Targeting non-image fields
2142
+ If the target image description lives outside an image object, use the `sourcePath` option to specify the path to the image field.
2143
+ `sourcePath` must be an image or image asset field.
2144
+
2145
+ For example:
2146
+ - `target: {path: ['description'], operation: {type: 'image-description', sourcePath: ['image', 'asset'] }`
2147
+ - `target: {path: ['wrapper', 'title'], operation: {type: 'image-description', sourcePath: ['array', {_key: 'abc'}, 'image'] }`
2148
+ - `target: {path: ['wrapper'], include: ['portableTextField'], operation: {type: 'image-description', sourcePath: ['image', 'asset'] }, instruction: 'Use formatting and headings to describe the image in great detail' }`
2149
+
2150
+ ##### Example: Field-based transformation
2151
+
2152
+ ```ts
2153
+ await client.agent.action.transform({
2154
+ schemaId,
2155
+ documentId,
2156
+ instruction: 'Summarize the following field: $content',
2157
+ instructionParams: {
2158
+ content: {type: 'field', path: ['body']},
2159
+ },
2160
+ target: {path: ['body']},
2161
+ })
2162
+ ```
2163
+
2164
+ ---
2165
+
2166
+ #### Translating Documents
2167
+
2168
+ ```ts
2169
+ const result = await client.agent.action.translate({
2170
+ schemaId: 'your-schema-id',
2171
+ documentId: 'source-document-id',
2172
+ targetDocument: {operation: 'create'},
2173
+ fromLanguage: {id: 'en', title: 'English'},
2174
+ toLanguage: {id: 'es', title: 'Spanish'},
2175
+ styleGuide: 'Use a friendly tone.',
2176
+ protectedPhrases: ['Sanity', 'Grapefruit'],
2177
+ target: {path: ['body']},
2178
+ })
2179
+ ```
2180
+
2181
+ - **schemaId**: The schema identifier for the document type.
2182
+ - **documentId**: The source document ID.
2183
+ - **targetDocument**: (Optional) Specify a different document to write the result to, or create a new one.
2184
+ - **fromLanguage**: (Optional) The source language code and title.
2185
+ - **toLanguage**: The target language code and title.
2186
+ - **styleGuide**: (Optional) Instructions for translation style.
2187
+ - **protectedPhrases**: (Optional) Array of phrases to leave untranslated.
2188
+ - **target**: (Optional) Specifies which fields or paths to translate.
2189
+ - **temperature**: (Optional) Controls variance, 0-1 – defaults to 0
2190
+ - **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
2191
+ - **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
2192
+ - **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
2193
+
2194
+ ##### Example: Storing language in a field
2195
+
2196
+ ```ts
2197
+ await client.agent.action.translate({
2198
+ schemaId,
2199
+ documentId,
2200
+ toLanguage: {id: 'fr', title: 'French'},
2201
+ languageFieldPath: ['language'],
2202
+ target: {path: ['body']},
2203
+ })
2204
+ ```
2205
+
2206
+ #### Prompt the LLM
2207
+
2208
+ ```ts
2209
+ const result = await client.agent.action.prompt({
2210
+ instruction: 'Say: Oh, hi $name!',
2211
+ instructionParams: {
2212
+ name: 'Mark',
2213
+ },
2214
+ temperature: 0.5,
2215
+ format: 'text',
2216
+ })
2217
+ ```
2218
+
2219
+ - **instruction**: A string template describing what the LLM should do. Use `$variable` for dynamic values.
2220
+ - **instructionParams**: Values for variables in the instruction. Supports constants, fields, documents, or GROQ queries.
2221
+ - **format**: (Optional) 'text' or 'json'. Defaults to 'text'. Note that when specifying 'json', the instruction MUST include the word "json" (ignoring case) in some form.
2222
+ - **temperature**: (Optional) Controls variance, 0-1 – defaults to 0
2223
+
2224
+ #### Patch with a schema-aware API
2225
+
2226
+ The `client.patch` and `client.transaction` API are not schema aware. This allows patching documents any way you want, but the operations will not fail if they deviate from the document schema.
2227
+
2228
+ To ensure schema-compliant operation, `client.agent.action.patch` is available. It will ensure that provided paths and values adhere to the document schema,
2229
+ ensure no duplicate keys are inserted, and merge object values so `set` operations dont accidentally remove existing values.
2230
+
2231
+ ```ts
2232
+ const result = await client.agent.action.patch({
2233
+ schemaId,
2234
+ documentId,
2235
+ target: [
2236
+ {path: 'title', operation: 'set', value: 'New title'},
2237
+ {
2238
+ path: ['wrapper', 'array'],
2239
+ operation: 'append',
2240
+ value: [{_type: 'item', title: 'Item title'}],
2241
+ },
2242
+ ],
2243
+ })
2244
+ ```
2245
+
2246
+ - **schemaId**: The schema identifier for the document type.
2247
+ - **documentId**: The source document ID OR use `targetDocument`
2248
+ - **targetDocument**: (Optional) Specify a different document to write the result to, or create a new one. Incompatible with `documentId`
2249
+ - **target**: Specify patch operations and values for paths in the document.
2250
+ - **async**: (Optional) when true, the request will respond with the document id; the LLM request and mutations will continue on the server.
2251
+ - **noWrite**: (Optional) when true, the document will not be changed. The response will contain the document value with the changes.
2252
+ - **conditionalPaths**: (Optional) control how conditionally readOnly and hidden fields and types will be treated
2253
+
2254
+ #### Appending into array after a key
2255
+
2256
+ When appending to arrays, providing a `_key` is optional.
2257
+ When a path targets a key in an array, the values provided will be appended after that key'ed item in the array.
2258
+ Note that when appending to arrays, `value` must be an array itself, even when only a single item should be appended.
2259
+
2260
+ ```ts
2261
+ const result = await client.agent.action.patch({
2262
+ schemaId,
2263
+ documentId,
2264
+ target: {
2265
+ path: ['array', {_key: 'existingKey'}],
2266
+ operation: 'append',
2267
+ value: [{_type: 'item', title: 'Item title', _key: 'isOptionalAndWillBeGeneratedIfMissing'}],
2268
+ },
2269
+ })
2270
+ ```
2271
+
2272
+ ### Views API
2273
+
2274
+ #### Quickstart
2275
+
2276
+ ```js
2277
+ import {createViewClient} from '@sanity/client/views'
2278
+
2279
+ const config: ViewClientConfig = {
2280
+ apiVersion: '2025-06-25', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
2281
+ }
2282
+ const client = createViewClient(config)
2283
+
2284
+ const data = await client.fetch('viewId', 'count(*)') // this will now query the view, or the overrides if specified
2285
+ console.log(`Number of documents: ${data}`)
2286
+ ```
2287
+
2288
+ #### Creating a views client instance
2289
+
2290
+ ```js
2291
+ const client = createViewClient(options)
2292
+ ```
2293
+
2294
+ Initializes a new Sanity View Client. Required options are `apiVersion`.
2295
+
2296
+ ##### [ESM](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/)
2297
+
2298
+ ```js
2299
+ import {createViewClient} from '@sanity/client/views'
2300
+
2301
+ const client = createViewClient({
2302
+ apiVersion: '2025-06-25', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
2303
+ })
2304
+
2305
+ const data = await client.fetch('viewId', 'count(*)')
2306
+ console.log(`Number of documents: ${data}`)
2307
+ ```
2308
+
2309
+ ##### [CommonJS]
2310
+
2311
+ ```js
2312
+ const { createViewClient } = require('@sanity/client/views')
2313
+
2314
+ const client = createViewClient({
2315
+ apiVersion: '2025-06-25', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
2316
+ })
2317
+
2318
+ client.fetch('viewId', 'count(*)')
2319
+ .then((data) => console.log(`Number of documents: ${data}`))
2320
+ .catch(console.error);
2321
+ ```
2322
+
2323
+ ##### [TypeScript]
2324
+
2325
+ ```ts
2326
+ import {createViewClient, ViewClientConfig} from '@sanity/client/views'
2327
+
2328
+ const config: ViewClientConfig = {
2329
+ apiVersion: '2025-06-25', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
2330
+ }
2331
+ const client = createViewClient(config)
2332
+
2333
+ const data = await client.fetch<number>('viewId', 'count(*)')
2334
+ console.log(`Number of documents: ${data}`)
2335
+ ```
2336
+
2337
+ ##### Other frameworks, type safety, etc
2338
+ The Views client supports the same conventions as the `sanityClient`. You can follow the same patterns [documented for the sanity client](#creating-a-client-instance) to achieve integration with your framework, typesafety, etc.
2339
+
2340
+ #### Using a view
2341
+
2342
+ Once the View client has been initialized you can use the `fetch` method to query a view. The `fetch` method required two arguments: `viewId` and `query`.
2343
+
2344
+ ```js
2345
+ const data = await client.fetch('viewId', 'count(*)')
2346
+ console.log(`Number of documents: ${data}`)
2347
+ ```
2348
+
2349
+ If the view you are querying is a private view you will need to specify a `token` in the client config.
2350
+
2351
+ ```js
2352
+ const client = createViewClient({
2353
+ apiVersion: '2025-06-25', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
2354
+ token: process.env.SANITY_API_TOKEN,
2355
+ })
2356
+
2357
+ const data = await client.fetch('viewId', 'count(*)')
2358
+ console.log(`Number of documents: ${data}`)
2359
+ ```
2360
+
2361
+ The fetch method can also accept parameters and options, the same as the sanity client.
2362
+
2363
+ ```js
2364
+ const data = await client.fetch('viewId', 'count(*[_type == $type])', {type: 'post'})
2365
+ console.log(`Number of documents: ${data}`)
2366
+ ```
2367
+
2368
+ Unlike the sanity client the views client does not support the `dataset`, `projectId`, or `useProjectHostname` options as it does not belong to any single project or dataset. `apiCdn` is not supported, and all requests will be routed via the CDN. Other options are the same as `sanityClient`.
2369
+
2370
+ #### Developing a view
2371
+
2372
+ Views are deployed in the form of a series of view connections which can take some minutes to build. In order to facilitate an improved developer workflow the views client supports a `viewOverrides` option, which will allow the development of views locally at the cost of some performance.
2373
+
2374
+ To do this we must specify the new option `viewOverrides` on instantiation of the client. Note that a token is required to access this development workflow.
2375
+
2376
+ ```js
2377
+ const config: ViewClientConfig = {
2378
+ apiVersion: '2025-06-25', // use current date (YYYY-MM-DD) to target the latest API version. Note: this should always be hard coded. Setting API version based on a dynamic value (e.g. new Date()) may break your application at a random point in the future.
2379
+ token: process.env.SANITY_API_TOKEN, // this is required to use the override functionality
2380
+ viewOverrides: [
2381
+ {
2382
+ resourceType: ViewResourceType.View,
2383
+ resourceId: 'vw2x09caysNaZdjksWEsToG43meSg', // the view id you are developing
2384
+ connections: [
2385
+ {
2386
+ query: '*[_type == "location"]', // the query to use for this connection - this is what you would deploy later
2387
+ resourceType: ViewResourceType.Dataset, // currently only dataset is supported
2388
+ resourceId: '469jfrel.eu_data', // the project and dataset to use for this connection, note the format is `projectId.datasetName`
2389
+ },
2390
+ {
2391
+ query: '*[_type == "location"]', // You can stack as many connections as you require
2392
+ resourceType: ViewResourceType.Dataset,
2393
+ resourceId: '469jfrel.us_data',
2394
+ }
2395
+ ]
2396
+ }
2397
+ ]
2398
+ }
2399
+ const client = createViewClient(config)
2400
+
2401
+ const data = await client.fetch('viewId', 'count(*)') // this query is now run against the result of all the queries above
2402
+ console.log(`Number of documents: ${data}`)
2403
+ ```
2404
+
1635
2405
  ## License
1636
2406
 
1637
2407
  MIT © [Sanity.io](https://www.sanity.io/)