@sanity/client 6.11.3 → 6.11.4-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +85 -4
  2. package/dist/_chunks/{browserMiddleware-1MULg59S.cjs → browserMiddleware-Pe3R-Bkh.cjs} +106 -20
  3. package/dist/_chunks/browserMiddleware-Pe3R-Bkh.cjs.map +1 -0
  4. package/dist/_chunks/{browserMiddleware-heyg-fDk.js → browserMiddleware-wklv-F5c.js} +108 -22
  5. package/dist/_chunks/browserMiddleware-wklv-F5c.js.map +1 -0
  6. package/dist/_chunks/{nodeMiddleware-CHxg1-zH.cjs → nodeMiddleware-7PkLkt-m.cjs} +107 -21
  7. package/dist/_chunks/nodeMiddleware-7PkLkt-m.cjs.map +1 -0
  8. package/dist/_chunks/{nodeMiddleware-u_fUUnxa.js → nodeMiddleware-LGORMZpx.js} +109 -23
  9. package/dist/_chunks/nodeMiddleware-LGORMZpx.js.map +1 -0
  10. package/dist/_chunks/stegaEncodeSourceMap-2y-qTNKB.cjs +230 -0
  11. package/dist/_chunks/stegaEncodeSourceMap-2y-qTNKB.cjs.map +1 -0
  12. package/dist/_chunks/stegaEncodeSourceMap-9L0STMBo.js +475 -0
  13. package/dist/_chunks/stegaEncodeSourceMap-9L0STMBo.js.map +1 -0
  14. package/dist/_chunks/stegaEncodeSourceMap-gXzb3LIV.js +226 -0
  15. package/dist/_chunks/stegaEncodeSourceMap-gXzb3LIV.js.map +1 -0
  16. package/dist/_chunks/stegaEncodeSourceMap-vNYIaMiu.cjs +479 -0
  17. package/dist/_chunks/stegaEncodeSourceMap-vNYIaMiu.cjs.map +1 -0
  18. package/dist/index.browser.cjs +1 -1
  19. package/dist/index.browser.js +2 -2
  20. package/dist/index.cjs +1 -1
  21. package/dist/index.d.ts +133 -0
  22. package/dist/index.js +2 -2
  23. package/dist/stega.browser.cjs +10 -700
  24. package/dist/stega.browser.cjs.map +1 -1
  25. package/dist/stega.browser.js +5 -693
  26. package/dist/stega.browser.js.map +1 -1
  27. package/dist/stega.cjs +10 -451
  28. package/dist/stega.cjs.js +3 -5
  29. package/dist/stega.cjs.map +1 -1
  30. package/dist/stega.d.ts +1302 -1455
  31. package/dist/stega.js +5 -444
  32. package/dist/stega.js.map +1 -1
  33. package/package.json +12 -7
  34. package/src/SanityClient.ts +40 -4
  35. package/src/config.ts +34 -12
  36. package/src/data/dataMethods.ts +37 -9
  37. package/src/stega/index.browser.ts +3 -6
  38. package/src/stega/index.ts +3 -6
  39. package/src/stega/shared.ts +1 -13
  40. package/src/stega/types.ts +11 -18
  41. package/src/types.ts +24 -0
  42. package/umd/sanityClient.js +1073 -20
  43. package/umd/sanityClient.min.js +4 -3
  44. package/dist/_chunks/browserMiddleware-1MULg59S.cjs.map +0 -1
  45. package/dist/_chunks/browserMiddleware-heyg-fDk.js.map +0 -1
  46. package/dist/_chunks/nodeMiddleware-CHxg1-zH.cjs.map +0 -1
  47. package/dist/_chunks/nodeMiddleware-u_fUUnxa.js.map +0 -1
  48. package/src/stega/SanityStegaClient.ts +0 -298
  49. package/src/stega/config.ts +0 -76
package/README.md CHANGED
@@ -657,10 +657,10 @@ useContentSourceMap(resultSourceMap)
657
657
 
658
658
  #### Using [Visual editing][visual-editing] with steganography
659
659
 
660
- A turnkey integration with [Visual editing][visual-editing] is available in [`@sanity/client/stega`]. It creates edit intent links for all the string values in your query result, using [steganography](https://npmjs.com/package/@vercel/stega) under the hood.
660
+ A turnkey integration with [Visual editing][visual-editing] is available in [`@sanity/client`], with additional utils available on [`@sanity/client/stega`]. It creates edit intent links for all the string values in your query result, using [steganography](https://npmjs.com/package/@vercel/stega) under the hood. The code that handles stega is lazy loaded on demand when `client.fetch` is called, if `client.config().stega.enabled` is `true`.
661
661
 
662
662
  ```ts
663
- import {createClient} from '@sanity/client/stega'
663
+ import {createClient} from '@sanity/client'
664
664
 
665
665
  const client = createClient({
666
666
  // ...base config options
@@ -713,7 +713,7 @@ const debugClient = client.withConfig({
713
713
  })
714
714
  ```
715
715
 
716
- Removing stega from part of the result:
716
+ Removing stega from part of the result, available on [`@sanity/client/stega`]:
717
717
 
718
718
  ```ts
719
719
  import {vercelStegaCleanAll} from '@sanity/client/stega'
@@ -723,12 +723,91 @@ const result = await client.fetch('*[_type == "video"][0]')
723
723
  const videoAsset = vercelStegaCleanAll(result.videoAsset)
724
724
  ```
725
725
 
726
+ #### [Visual editing][visual-editing] with the [GraphQL API][graphql-csm]
727
+
728
+ It's possible to enable stega for the GraphQL API as well, with the `stegaEncodeSourceMap` utility available on [`@sanity/client/stega`]. On your GraphQL API request add the search param `resultSourceMap=true`
729
+
730
+ Your GraphQL API response should now look something like this:
731
+
732
+ ```json
733
+ {
734
+ "data": {
735
+ "allPost": [
736
+ {
737
+ "title": "GraphQL CSM"
738
+ }
739
+ ]
740
+ },
741
+ "extensions": {
742
+ "sanitySourceMap": {
743
+ "documents": [
744
+ {
745
+ "_id": "75bbbd60-0aa9-4b20-9c00-0b40cb010ff6",
746
+ "_type": "post"
747
+ }
748
+ ],
749
+ "paths": ["$['title']"],
750
+ "mappings": {
751
+ "$['allPost'][0]['title']": {
752
+ "source": {
753
+ "document": 0,
754
+ "path": 0,
755
+ "type": "documentValue"
756
+ },
757
+ "type": "value"
758
+ }
759
+ }
760
+ }
761
+ }
762
+ }
763
+ ```
764
+
765
+ To encode the CSMs to Stega payloads, use the `stegaEncodeSourceMap` utility, this creates the same result as with GROQ and `client.fetch` and is compatible with the Vercel Visual Editing integration, and the upcoming GraphQL support in [Presentation][presentation]:
766
+
767
+ ```ts
768
+ import {ApolloClient, gql} from '@apollo/client'
769
+ import {stegaEncodeSourceMap} from '@sanity/client/stega'
770
+
771
+ const client = new ApolloClient({
772
+ uri: `https://${projectId}.api.sanity.io/v${apiVersion}/graphql/${dataset}/${graphqlTag}?resultSourceMap=true`,
773
+ // other base config options
774
+ })
775
+
776
+ const posts = await client.query({
777
+ query: gql`
778
+ query allPost {
779
+ allPost {
780
+ title
781
+ }
782
+ }
783
+ `,
784
+ })
785
+
786
+ // Later in the App, when you want to encode the CSMs to Stega payloads
787
+ const data = stegaEncodeSourceMap(posts.data, posts.extensions.sanitySourceMap, {
788
+ // The options are the same as for the `stega` config option, except for which ones are optional and which ones are required
789
+ enabled: true, // required
790
+ studioUrl: 'https://test.sanity.studio', // required
791
+ filter: (props) => props.filterDefault(props), // optional
792
+ logger: console, // optional
793
+ })
794
+
795
+ // The `title` field now has a CSM embedded using Steganography, to verify the payloads you can use the `vercelStegaDecode` utilities in `@vercel/stega` and test the URLs it reports
796
+
797
+ // Check for a single URL:
798
+ import {vercelStegaDecode} from '@vercel/stega'
799
+ console.log(vercelStegaDecode(data.allPost[0].title)) // {"href": "https://test.sanity.studio/intent/edit/mode=presentation;id=75bbbd60-0aa9-4b20-9c00-0b40cb010ff6;type=post;path=title", "origin": "sanity.io"}
800
+ // Find all URLs in a payload
801
+ import {vercelStegaDecodeAll} from '@vercel/stega'
802
+ console.log(vercelStegaDecodeAll(JSON.stringify(data))) // [{"href": "https://test.sanity.studio/intent/edit/mode=presentation;id=75bbbd60-0aa9-4b20-9c00-0b40cb010ff6;type=post;path=title", "origin": "sanity.io"}]
803
+ ```
804
+
726
805
  #### Creating Studio edit intent links
727
806
 
728
807
  If you want to create an edit link to something that isn't a string, or a field that isn't rendered directly, like a `slug` used in a URL but not rendered on the page, you can use the `resolveEditUrl` function.
729
808
 
730
809
  ```ts
731
- import {createClient} from '@sanity/client' // or '@sanity/client/stega'
810
+ import {createClient} from '@sanity/client'
732
811
  import {resolveEditUrl} from '@sanity/client/csm'
733
812
 
734
813
  const client = createClient({
@@ -1608,3 +1687,5 @@ await client.request<void>({uri: '/auth/logout', method: 'POST'})
1608
1687
  [visual-editing]: https://www.sanity.io/docs/vercel-visual-editing?utm_source=github.com&utm_medium=referral&utm_campaign=may-vercel-launch
1609
1688
  [content-source-maps]: https://www.sanity.io/docs/content-source-maps?utm_source=github.com&utm_medium=referral&utm_campaign=may-vercel-launch
1610
1689
  [content-source-maps-intro]: https://www.sanity.io/blog/content-source-maps-announce?utm_source=github.com&utm_medium=referral&utm_campaign=may-vercel-launch
1690
+ [graphql-csm]: https://www.sanity.io/docs/graphql#e52e2285f14f
1691
+ [presentation]: https://www.sanity.io/blog/introducing-presentation
@@ -4,6 +4,7 @@ var getIt = require('get-it');
4
4
  var middleware = require('get-it/middleware');
5
5
  var rxjs = require('rxjs');
6
6
  var operators = require('rxjs/operators');
7
+ var stega = require('@vercel/stega');
7
8
 
8
9
  const MAX_ITEMS_IN_ERROR_MESSAGE = 5;
9
10
  class ClientError extends Error {
@@ -653,7 +654,8 @@ const defaultCdnHost = "apicdn.sanity.io";
653
654
  const defaultConfig = {
654
655
  apiHost: "https://api.sanity.io",
655
656
  apiVersion: "1",
656
- useProjectHostname: true
657
+ useProjectHostname: true,
658
+ stega: { enabled: false }
657
659
  };
658
660
  const LOCALHOSTS = ["localhost", "127.0.0.1", "0.0.0.0"];
659
661
  const isLocal = (host) => LOCALHOSTS.indexOf(host) !== -1;
@@ -680,11 +682,21 @@ const validateApiPerspective = function validateApiPerspective2(perspective) {
680
682
  }
681
683
  };
682
684
  const initConfig = (config, prevConfig) => {
683
- const specifiedConfig = Object.assign({}, prevConfig, config);
685
+ const specifiedConfig = {
686
+ ...prevConfig,
687
+ ...config,
688
+ stega: {
689
+ ...typeof prevConfig.stega === "boolean" ? { enabled: prevConfig.stega } : prevConfig.stega || defaultConfig.stega,
690
+ ...typeof config.stega === "boolean" ? { enabled: config.stega } : config.stega || {}
691
+ }
692
+ };
684
693
  if (!specifiedConfig.apiVersion) {
685
694
  printNoApiVersionSpecifiedWarning();
686
695
  }
687
- const newConfig = Object.assign({}, defaultConfig, specifiedConfig);
696
+ const newConfig = {
697
+ ...defaultConfig,
698
+ ...specifiedConfig
699
+ };
688
700
  const projectBased = newConfig.useProjectHostname;
689
701
  if (typeof Promise === "undefined") {
690
702
  const helpUrl = generateHelpUrl("js-client-promise-polyfill");
@@ -696,14 +708,25 @@ const initConfig = (config, prevConfig) => {
696
708
  if (typeof newConfig.perspective === "string") {
697
709
  validateApiPerspective(newConfig.perspective);
698
710
  }
699
- if ("encodeSourceMapAtPath" in newConfig || "encodeSourceMap" in newConfig || "studioUrl" in newConfig || "logger" in newConfig) {
711
+ if ("encodeSourceMap" in newConfig) {
700
712
  throw new Error(
701
- "It looks like you're using options meant for '@sanity/preview-kit/client', such as 'encodeSourceMapAtPath', 'encodeSourceMap', 'studioUrl' and 'logger'. Make sure you're using the right import."
713
+ "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMap' is not supported in '@sanity/client'. Did you mean 'stega.enabled'?"
702
714
  );
703
715
  }
704
- if ("stega" in newConfig && newConfig["stega"] !== void 0 && newConfig["stega"] !== false) {
716
+ if ("encodeSourceMapAtPath" in newConfig) {
717
+ throw new Error(
718
+ "It looks like you're using options meant for '@sanity/preview-kit/client'. 'encodeSourceMapAtPath' is not supported in '@sanity/client'. Did you mean 'stega.filter'?"
719
+ );
720
+ }
721
+ if (typeof newConfig.stega.enabled !== "boolean") {
722
+ throw new Error("stega.enabled must be a boolean, received ".concat(newConfig.stega.enabled));
723
+ }
724
+ if (newConfig.stega.enabled && newConfig.stega.studioUrl === void 0) {
725
+ throw new Error("stega.studioUrl must be defined when stega.enabled is true");
726
+ }
727
+ if (newConfig.stega.enabled && typeof newConfig.stega.studioUrl !== "string" && typeof newConfig.stega.studioUrl !== "function") {
705
728
  throw new Error(
706
- "It looks like you're using options meant for '@sanity/client/stega'. Make sure you're using the right import. Or set 'stega' in 'createClient' to 'false'."
729
+ "stega.studioUrl must be a string or a function, received ".concat(newConfig.stega.studioUrl)
707
730
  );
708
731
  }
709
732
  const isBrowser = typeof window !== "undefined" && window.location && window.location.hostname;
@@ -764,6 +787,20 @@ function requestOptions(config, overrides = {}) {
764
787
  });
765
788
  }
766
789
 
790
+ function vercelStegaCleanAll(result) {
791
+ try {
792
+ return JSON.parse(
793
+ JSON.stringify(result, (key, value) => {
794
+ if (typeof value !== "string")
795
+ return value;
796
+ return stega.vercelStegaSplit(value).cleaned;
797
+ })
798
+ );
799
+ } catch {
800
+ return result;
801
+ }
802
+ }
803
+
767
804
  const encodeQueryString = ({
768
805
  query,
769
806
  params = {},
@@ -805,21 +842,38 @@ const indexBy = (docs, attr) => docs.reduce((indexed, doc) => {
805
842
  return indexed;
806
843
  }, /* @__PURE__ */ Object.create(null));
807
844
  const getQuerySizeLimit = 11264;
808
- function _fetch(client, httpRequest, query, params, options = {}) {
809
- if ("stega" in options && options["stega"] !== void 0 && options["stega"] !== false) {
810
- throw new Error(
811
- "It looks like you're using options meant for '@sanity/client/stega'. Make sure you're using the right import. Or set 'stega' in 'fetch' to 'false'."
812
- );
813
- }
845
+ function _fetch(client, httpRequest, _stega, query, _params, options = {}) {
846
+ const stega = "stega" in options ? {
847
+ ..._stega || {},
848
+ ...typeof options.stega === "boolean" ? { enabled: options.stega } : options.stega || {}
849
+ } : _stega;
850
+ const params = stega.enabled ? vercelStegaCleanAll(_params) : _params;
814
851
  const mapResponse = options.filterResponse === false ? (res) => res : (res) => res.result;
815
852
  const { cache, next, ...opts } = {
816
853
  // Opt out of setting a `signal` on an internal `fetch` if one isn't provided.
817
854
  // This is necessary in React Server Components to avoid opting out of Request Memoization.
818
855
  useAbortSignal: typeof options.signal !== "undefined",
856
+ // Set `resultSourceMap' when stega is enabled, as it's required for encoding.
857
+ resultSourceMap: stega.enabled ? "withKeyArraySelector" : options.resultSourceMap,
819
858
  ...options
820
859
  };
821
860
  const reqOpts = typeof cache !== "undefined" || typeof next !== "undefined" ? { ...opts, fetch: { cache, next } } : opts;
822
- return _dataRequest(client, httpRequest, "query", { query, params }, reqOpts).pipe(operators.map(mapResponse));
861
+ const $request = _dataRequest(client, httpRequest, "query", { query, params }, reqOpts);
862
+ return stega.enabled ? $request.pipe(
863
+ operators.combineLatestWith(
864
+ rxjs.from(
865
+ Promise.resolve().then(function () { return require('./stegaEncodeSourceMap-vNYIaMiu.cjs'); }).then(function (n) { return n.stegaEncodeSourceMap$1; }).then(
866
+ ({ stegaEncodeSourceMap }) => stegaEncodeSourceMap
867
+ )
868
+ )
869
+ ),
870
+ operators.map(
871
+ ([res, stegaEncodeSourceMap]) => {
872
+ const result = stegaEncodeSourceMap(res.result, res.resultSourceMap, stega);
873
+ return mapResponse({ ...res, result });
874
+ }
875
+ )
876
+ ) : $request.pipe(operators.map(mapResponse));
823
877
  }
824
878
  function _getDocument(client, httpRequest, id, opts = {}) {
825
879
  const options = { uri: _getDataUrl(client, "doc", id), json: true, tag: opts.tag };
@@ -1560,10 +1614,25 @@ const _ObservableSanityClient = class _ObservableSanityClient {
1560
1614
  * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1561
1615
  */
1562
1616
  withConfig(newConfig) {
1563
- return new _ObservableSanityClient(__privateGet(this, _httpRequest), { ...this.config(), ...newConfig });
1617
+ const thisConfig = this.config();
1618
+ return new _ObservableSanityClient(__privateGet(this, _httpRequest), {
1619
+ ...this.config(),
1620
+ ...newConfig,
1621
+ stega: {
1622
+ ...thisConfig.stega || {},
1623
+ ...typeof (newConfig == null ? void 0 : newConfig.stega) === "boolean" ? { enabled: newConfig.stega } : (newConfig == null ? void 0 : newConfig.stega) || {}
1624
+ }
1625
+ });
1564
1626
  }
1565
1627
  fetch(query, params, options = {}) {
1566
- return _fetch(this, __privateGet(this, _httpRequest), query, params, options);
1628
+ return _fetch(
1629
+ this,
1630
+ __privateGet(this, _httpRequest),
1631
+ __privateGet(this, _clientConfig).stega,
1632
+ query,
1633
+ params,
1634
+ options
1635
+ );
1567
1636
  }
1568
1637
  /**
1569
1638
  * Fetch a single document with the given ID.
@@ -1695,10 +1764,27 @@ const _SanityClient = class _SanityClient {
1695
1764
  * @param newConfig - New client configuration properties, shallowly merged with existing configuration
1696
1765
  */
1697
1766
  withConfig(newConfig) {
1698
- return new _SanityClient(__privateGet(this, _httpRequest2), { ...this.config(), ...newConfig });
1767
+ const thisConfig = this.config();
1768
+ return new _SanityClient(__privateGet(this, _httpRequest2), {
1769
+ ...thisConfig,
1770
+ ...newConfig,
1771
+ stega: {
1772
+ ...thisConfig.stega || {},
1773
+ ...typeof (newConfig == null ? void 0 : newConfig.stega) === "boolean" ? { enabled: newConfig.stega } : (newConfig == null ? void 0 : newConfig.stega) || {}
1774
+ }
1775
+ });
1699
1776
  }
1700
1777
  fetch(query, params, options = {}) {
1701
- return rxjs.lastValueFrom(_fetch(this, __privateGet(this, _httpRequest2), query, params, options));
1778
+ return rxjs.lastValueFrom(
1779
+ _fetch(
1780
+ this,
1781
+ __privateGet(this, _httpRequest2),
1782
+ __privateGet(this, _clientConfig2).stega,
1783
+ query,
1784
+ params,
1785
+ options
1786
+ )
1787
+ );
1702
1788
  }
1703
1789
  /**
1704
1790
  * Fetch a single document with the given ID.
@@ -1831,8 +1917,8 @@ exports.Patch = Patch;
1831
1917
  exports.SanityClient = SanityClient;
1832
1918
  exports.ServerError = ServerError;
1833
1919
  exports.Transaction = Transaction;
1834
- exports.defaultConfig = defaultConfig;
1835
1920
  exports.defineCreateClientExports = defineCreateClientExports;
1836
1921
  exports.envMiddleware = envMiddleware;
1837
1922
  exports.printNoDefaultExport = printNoDefaultExport;
1838
- //# sourceMappingURL=browserMiddleware-1MULg59S.cjs.map
1923
+ exports.vercelStegaCleanAll = vercelStegaCleanAll;
1924
+ //# sourceMappingURL=browserMiddleware-Pe3R-Bkh.cjs.map