@sanity/cross-dataset-duplicator 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";const e=["pluginConfig"];function t(e,t){if(null==e)return{};var n,i,o=function(e,t){if(null==e)return{};var n,i,o={},s=Object.keys(e);for(i=0;i<s.length;i++)n=s[i],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(i=0;i<s.length;i++)n=s[i],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function i(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?n(Object(i),!0).forEach((function(t){o(e,t,i[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))}))}return e}function o(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(exports,"__esModule",{value:!0});var s=require("sanity"),a=require("react/jsx-runtime"),r=require("react"),d=require("@sanity/icons"),l=require("@sanity/studio-secrets"),c=require("@sanity/ui"),u=require("async/mapLimit"),h=require("async/asyncify"),p=require("@sanity/mutator"),f=require("dset"),g=require("@sanity/asset-utils");function x(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var m=x(r),j=x(u),b=x(h);function y(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return[1===e?"This Document contains":"These ".concat(e," Documents contain"),1===t?"1 Reference.":"".concat(t," References."),1===t?"That Document":"Those Documents","may have References too. If referenced Documents do not exist at the target Destination, this transaction will fail."].join(" ")}const v=function(){return{position:"sticky",top:0,zIndex:100,backgroundColor:!(arguments.length>0&&void 0!==arguments[0])||arguments[0]?"rgba(10,10,10,0.95)":"rgba(255,255,255,0.95)"}};async function S(e){const{fetchIds:t,client:n,pluginConfig:i,currentIds:o,projection:s}=e,a=[],r=["_id in $fetchIds",i.filter].filter(Boolean).join(" && "),d="*[".concat(r,"]").concat(null!=s?s:""),l=await n.fetch(d,{fetchIds:null!=t?t:[]});if(!(null==l?void 0:l.length))return[];const c=null!=o?o:new Set,u=new Set(l.map((e=>e._id)).filter((e=>(null==o?void 0:o.size)?!c.has(e):Boolean(e))));u.size&&(a.push(...l),c.add(...u),await Promise.all(l.map((async e=>{const t=p.extractWithPath(".._ref",e).map((e=>e.value));if(t.length){const e=new Set(t.filter((e=>!c.has(e))));if(e.size){const t=await S({fetchIds:Array.from(e),currentIds:c,client:n,pluginConfig:i});(null==t?void 0:t.length)&&a.push(...t)}}}))));return a.filter(Boolean).reduce(((e,t)=>e.some((e=>e._id===t._id))?e:[...e,t]),[])}const w=["All","None",null,"New","Existing","Older",null,"Documents","Assets"];function D(e){const{payload:t,setPayload:n}=e,[i,o]=r.useState([]);return r.useEffect((()=>{!(null==i?void 0:i.length)&&t.every((e=>e.include))&&o(["ALL"])}),[null==i?void 0:i.length,t]),a.jsx(c.Card,{padding:1,radius:3,shadow:1,children:a.jsx(c.Flex,{gap:2,children:w.map(((e,s)=>e?a.jsx(c.Button,{fontSize:1,mode:"bleed",padding:2,text:e,disabled:i.includes(e.toUpperCase()),onClick:()=>function(e){if(!e||!t.length)return;const i=[...t];switch(e){case"ALL":i.map((e=>e.include=!0));break;case"NONE":i.map((e=>e.include=!1));break;case"NEW":i.map((e=>e.include=Boolean("CREATE"===e.status)));break;case"EXISTING":i.map((e=>e.include=Boolean("EXISTS"===e.status)));break;case"OLDER":i.map((e=>e.include=Boolean("OVERWRITE"===e.status)));break;case"ASSETS":i.map((e=>e.include=g.isAssetId(e.doc._id)));break;case"DOCUMENTS":i.map((e=>e.include=!g.isAssetId(e.doc._id)))}o([e]),n(i)}(e.toUpperCase())},e):a.jsx(c.Card,{borderLeft:!0},"divider-".concat(s))))})})}const C={EXISTS:"primary",OVERWRITE:"critical",UPDATE:"caution",CREATE:"positive",UNPUBLISHED:"caution"},E={EXISTS:"critical",OVERWRITE:"critical",UPDATE:"critical",CREATE:"positive",UNPUBLISHED:"default"},T={EXISTS:"This document already exists at the Destination with the same ID with the same Updated time.",OVERWRITE:"A newer version of this document exists at the Destination, and it will be overwritten with this version.",UPDATE:"An older version of this document exists at the Destination, and it will be overwritten with this version.",CREATE:"This document will be created at the destination.",UNPUBLISHED:"A Draft version of this Document exists in this Dataset, but only the Published version will be duplicated to the destination."},I={EXISTS:"This Asset already exists at the Destination",OVERWRITE:"This Asset already exists at the Destination",UPDATE:"This Asset already exists at the Destination",CREATE:"This Asset does not yet exist at the Destination",UNPUBLISHED:""},A={EXISTS:"RE-UPLOAD",OVERWRITE:"RE-UPLOAD",UPDATE:"RE-UPLOAD",CREATE:"UPLOAD",UNPUBLISHED:""};function O(e){const{status:t,isAsset:n}=e;if(!t)return null;const i=n?E[t]:C[t];if(!i)return a.jsx(c.Badge,{muted:!0,padding:2,fontSize:1,mode:"outline",children:"Checking..."});const o=n?I[t]:T[t],s=n?A[t]:t;return a.jsx(c.Tooltip,{content:a.jsx(c.Box,{padding:3,style:{maxWidth:200},children:a.jsx(c.Text,{size:1,children:o})}),fallbackPlacements:["right","left"],placement:"top",portal:!0,children:a.jsx(c.Badge,{muted:!0,padding:2,fontSize:1,tone:i,mode:"outline",children:s})})}function _(e){const{children:t,tone:n="caution"}=e;return a.jsx(c.Card,{padding:3,radius:2,shadow:1,tone:n,children:a.jsx(c.Text,{size:1,children:t})})}const k={apiVersion:"2021-05-19"};function P(e){var t,n,o;const{docs:l,token:u,pluginConfig:h}=e,x=c.useTheme().sanity.color.dark,w=s.useClient(k),C=s.useSchema(),E=s.useWorkspaces(),T=E.map((e=>i(i({},e),{},{disabled:e.dataset===w.config().dataset}))),[I,A]=r.useState(E.length&&null!=(t=T.find((e=>!e.disabled)))?t:null),[P,R]=r.useState(null),[B,U]=r.useState([]),[L,z]=r.useState(!1),[N,q]=r.useState(!1),[F,W]=r.useState(!1),[X,V]=r.useState([0,0]);async function G(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const t=e.length?e:B;if(!t.length||!(null==I?void 0:I.name))return;const n=t.map((e=>{let{doc:t}=e;return t._id})),o=w.withConfig(i(i({},k),{},{dataset:I.dataset,projectId:I.projectId})),s=await o.fetch("*[_id in $payloadIds]{ _id, _updatedAt }",{payloadIds:n}),a=t.map((e=>{var t;const n=s.find((t=>t._id===e.doc._id));return(null==n?void 0:n._updatedAt)&&(null==(t=null==e?void 0:e.doc)?void 0:t._updatedAt)?n._updatedAt===e.doc._updatedAt?e.status="EXISTS":n._updatedAt&&e.doc._updatedAt&&(e.status=new Date(n._updatedAt)>new Date(e.doc._updatedAt)?"OVERWRITE":"UPDATE"):e.status="CREATE",e}));U(a)}r.useEffect((()=>{const e=[],t=[];l.forEach((n=>{const i=p.extractWithPath(".._ref",n).map((e=>e.value));e.push(...i),t.push({include:!0,doc:n})})),U(t);const n=l.length,i=e.length;e.length&&(z(!0),R({tone:"caution",text:y(n,i)}))}),[l]),r.useEffect((()=>{G()}),[I]);const H=B.length,Q=B.findIndex((e=>{let{doc:t}=e;return"svg"===t.extension})),M=B.filter((e=>e.include&&!g.isAssetId(e.doc._id))).length,$=B.filter((e=>e.include&&g.isAssetId(e.doc._id))).length,Y=M+$,J=null!=(n=null==I?void 0:I.title)?n:null==I?void 0:I.name,K=new Set(T.map((e=>null==e?void 0:e.projectId)).filter(Boolean)).size>1,Z=[Y,"/",H,"Documents and Assets selected"].join(" "),ee=m.default.useMemo((()=>{const e=["Duplicate"];return M>1&&e.push(String(M),1===M?"Document":"Documents"),$>1&&e.push("and",String($),1===$?"Asset":"Assets"),w.config().projectId!==(null==I?void 0:I.projectId)&&e.push("between Projects"),e.push("to",String(J)),e.join(" ")}),[M,$,w,null==I?void 0:I.projectId,J]);return T.length<2?a.jsxs(_,{tone:"critical",children:[a.jsx("code",{children:"sanity.config.ts"})," must contain at least two Workspaces to use this plugin."]}):a.jsx(c.Container,{width:1,children:a.jsx(c.Card,{border:!0,children:a.jsx(c.Stack,{children:a.jsxs(a.Fragment,{children:[a.jsx(c.Card,{borderBottom:!0,padding:4,style:v(x),children:a.jsxs(c.Stack,{space:4,children:[a.jsxs(c.Flex,{gap:3,children:[a.jsxs(c.Stack,{style:{flex:1},space:3,children:[a.jsx(c.Label,{children:"Duplicate from"}),a.jsx(c.Select,{readOnly:!0,value:null==(o=T.find((e=>e.disabled)))?void 0:o.name,children:T.filter((e=>e.disabled)).map((e=>{var t;return a.jsxs("option",{value:e.name,disabled:e.disabled,children:[null!=(t=e.title)?t:e.name,K?" (".concat(e.projectId,")"):""]},e.name)}))})]}),a.jsx(c.Box,{padding:4,paddingTop:5,paddingBottom:0,children:a.jsx(c.Text,{size:3,children:a.jsx(d.ArrowRightIcon,{})})}),a.jsxs(c.Stack,{style:{flex:1},space:3,children:[a.jsx(c.Label,{children:"To Destination"}),a.jsx(c.Select,{onChange:function(e){if(!T.length)return;const t=T.find((t=>t.name===e.currentTarget.value));t&&A(t)},children:T.map((e=>{var t;return a.jsxs("option",{value:e.name,disabled:e.disabled,children:[null!=(t=e.title)?t:e.name,K?" (".concat(e.projectId,")"):"",e.disabled?" (Current)":""]},e.name)}))})]})]}),N&&a.jsx(c.Card,{border:!0,radius:2,children:a.jsx(c.Card,{style:{width:"100%",transform:"scaleX(".concat(X[0]/X[1],")"),transformOrigin:"left",transition:"transform .2s ease",boxSizing:"border-box"},padding:1,tone:"positive"})}),B.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(c.Label,{children:Z}),a.jsx(D,{payload:B,setPayload:U})]})]})}),P&&a.jsx(c.Box,{paddingX:4,paddingTop:4,children:a.jsx(c.Card,{padding:3,radius:2,shadow:1,tone:P.tone,children:a.jsx(c.Text,{size:1,children:P.text})})}),B.length>0&&a.jsx(c.Stack,{padding:4,space:3,children:B.map(((e,t)=>{let{doc:n,include:i,status:o,hasDraft:r}=e;const d=C.get(n._type);return a.jsxs(m.default.Fragment,{children:[a.jsxs(c.Flex,{align:"center",children:[a.jsx(c.Checkbox,{checked:i,onChange:()=>function(e){const t=B.map((t=>(t.doc._id===e&&(t.include=!t.include),t)));U(t)}(n._id)}),a.jsx(c.Box,{flex:1,paddingX:3,children:d?a.jsx(s.Preview,{value:n,schemaType:d}):a.jsx(c.Card,{tone:"caution",children:"Invalid schema type"})}),a.jsxs(c.Flex,{align:"center",gap:2,children:[r?a.jsx(O,{status:"UNPUBLISHED",isAsset:!1}):null,a.jsx(O,{status:o,isAsset:g.isAssetId(n._id)})]})]}),"svg"===(null==n?void 0:n.extension)&&t===Q&&a.jsx(c.Card,{padding:3,radius:2,shadow:1,tone:"caution",children:a.jsxs(c.Text,{size:1,children:["Due to how SVGs are sanitized after first uploaded, duplicated SVG assets may have new ",a.jsx("code",{children:"_id"}),"'s at the destination. The newly generated ",a.jsx("code",{children:"_id"})," will be the same in each duplication, but it will never be the same ",a.jsx("code",{children:"_id"})," as the first time this Asset was uploaded. References to the asset will be updated to use the new"," ",a.jsx("code",{children:"_id"}),"."]})})]},n._id)}))}),a.jsxs(c.Stack,{space:2,padding:4,paddingTop:0,children:[L&&a.jsx(c.Button,{fontSize:2,padding:4,tone:"positive",mode:"ghost",icon:d.SearchIcon,onClick:async function(){W(!0);const e=l.map((e=>e._id)),t=await S({fetchIds:e,client:w,pluginConfig:h}),n=await S({fetchIds:e.map((e=>"drafts.".concat(e))),client:w,projection:"{_id}",pluginConfig:h}),i=new Set(n.map((e=>{let{_id:t}=e;return t}))),o=t.map((e=>({doc:e,include:!0,status:void 0,hasDraft:i.has("drafts.".concat(e._id))})));U(o),G(o),W(!1)},text:"Gather References",disabled:N||!Y||F}),a.jsx(c.Button,{fontSize:2,padding:4,tone:"positive",icon:d.LaunchIcon,onClick:async function(){if(!I)return;q(!0);const e=B.filter((e=>{let{doc:t,include:n}=e;return n&&g.isAssetId(t._id)})).length;let t=0;V([t,e]),R({text:"Duplicating...",tone:"default"});const n=w.withConfig(i(i({},k),{},{dataset:I.dataset,projectId:I.projectId})),o=[],s=[];async function a(i){if(g.isAssetId(i._id)){const a=g.isSanityFileAsset(i),r=a?i.url:"".concat(i.url,"?dlRaw=true"),d=a?{}:{headers:{Authorization:"Bearer ".concat(u)}};return await fetch(r,d).then((async e=>{const t=await e.blob(),r={filename:i.originalFilename},d=await n.assets.upload(a?"file":"image",t,r);"svg"===(null==i?void 0:i.extension)&&s.push({old:i._id,new:d._id}),o.push(d)})),t+=1,R({text:"Duplicating ".concat(t,"/").concat(e," ").concat("Assets"),tone:"default"}),V([t,e])}return o.push(i)}const r=new Promise(((e,t)=>{const n=B.filter((e=>e.include)).map((e=>e.doc));j.default(n,3,b.default(a),(n=>{n&&(q(!1),R({tone:"critical",text:"Duplication Failed"}),console.error(n),t(new Error("Duplication Failed"))),e()}))}));await r;const d=o.map((e=>{const t=p.extractWithPath(".._ref",e);return t.length?(t.forEach((t=>{var n;const i=null==(n=s.find((e=>e.old===t.value)))?void 0:n.new;if(i){const n=t.path.join(".");f.dset(e,n,i)}})),e):e})),l=n.transaction();d.forEach((e=>{l.createOrReplace(e)})),await l.commit().then((e=>{R({tone:"positive",text:"Duplication complete!"}),G()})).catch((e=>{R({tone:"critical",text:e.details.description})})),q(!1),V([0,0])},text:ee,disabled:N||!Y||F})]})]})})})})}function R(e){var t,n;const{token:i,pluginConfig:o}=e,d=s.useClient(k),l=s.useSchema().getTypeNames(),[u,h]=r.useState(""),[p,f]=r.useState({docs:[]});function g(e){e&&e.preventDefault(),d.fetch(u).then((e=>{const t=e.length?e.filter((e=>l.includes(e._type))).filter((e=>!e._id.startsWith("drafts."))):[];f({docs:t})})).catch((e=>console.error(e)))}return r.useEffect((()=>{var e;!(null==(e=p.docs)?void 0:e.length)&&u&&g()}),[]),a.jsx(c.Container,{width:[1,1,1,3],padding:[0,0,0,5],children:a.jsxs(c.Grid,{columns:[1,1,1,2],gap:[1,1,1,4],children:[a.jsx(c.Box,{padding:[2,2,2,0],children:a.jsx(c.Card,{padding:4,radius:3,border:!0,children:a.jsxs(c.Stack,{space:4,children:[a.jsx(c.Box,{children:a.jsx(c.Label,{children:"Initial Documents Query"})}),a.jsx(c.Box,{children:a.jsx(c.Text,{children:"Start with a valid GROQ query to load initial documents. The query will need to return an Array of Objects. Drafts will be removed from the results."})}),a.jsx("form",{onSubmit:g,children:a.jsxs(c.Flex,{children:[a.jsx(c.Box,{flex:1,paddingRight:2,children:a.jsx(c.TextInput,{style:{fontFamily:"monospace"},fontSize:2,onChange:e=>h(e.currentTarget.value),padding:4,placeholder:'*[_type == "article"]',value:null!=u?u:""})}),a.jsx(c.Button,{padding:2,paddingX:4,tone:"primary",onClick:g,text:"Query",disabled:!u})]})})]})})}),!(null==(t=p.docs)?void 0:t.length)||p.docs.length<1&&a.jsx(c.Container,{width:1,children:a.jsx(c.Card,{padding:5,children:u?"No Documents registered to the Schema match this query":"Start with a valid GROQ query"})}),(null==(n=p.docs)?void 0:n.length)>0&&a.jsx(P,{docs:p.docs,token:i,pluginConfig:o})]})})}function B(e){const{docs:t,token:n,pluginConfig:i}=e,[o,d]=r.useState([]),{follow:l=[]}=i,[u,h]=r.useState(1===l.length?l[0]:"outbound"),p=s.useClient();return r.useEffect((()=>{(async()=>{if(l.includes("inbound")){const n=await p.fetch("*[references($id)]",{id:t[0]._id});d([...e.docs,...n])}})()}),[]),a.jsxs(c.Container,{children:[l.length>1&&(l.includes("inbound")||l.includes("outbound"))?a.jsx(c.Card,{paddingX:4,paddingBottom:4,marginBottom:4,borderBottom:!0,children:a.jsxs(c.Grid,{columns:2,gap:4,children:[l.includes("outbound")?a.jsx(c.Button,{mode:"ghost",tone:"primary",selected:"outbound"===u,onClick:()=>h("outbound"),text:"Outbound"}):null,l.includes("inbound")?a.jsx(c.Button,{mode:"ghost",tone:"primary",selected:"inbound"===u,onClick:()=>h("inbound"),disabled:0===o.length,text:o.length>0?"Inbound (".concat(o.length,")"):"No inbound references"}):null]})}):null,a.jsx(P,{docs:"outbound"===u?t:o,token:n,pluginConfig:i})]})}const U="CrossDatasetDuplicator",L={tool:!0,types:[],filter:"",follow:["outbound"]};function z(){const e=s.useClient(k),t=m.default.useCallback((()=>{e.delete({query:'*[_id == "secrets.'.concat(U,'"]')})}),[e]);return a.jsx(c.Flex,{align:"center",justify:"flex-end",paddingX:[2,2,2,5],paddingY:5,children:a.jsx(c.Button,{text:"Reset Secret",onClick:t,mode:"ghost",tone:"critical",fontSize:1,padding:2})})}const N=r.createContext(L);function q(){return r.useContext(N)}const F=[{key:"bearerToken",title:"An API token with Viewer permissions is required to duplicate the original files of assets, and will be used for all Duplications. Create one at sanity.io/manage",description:""}];function W(e){const{mode:t="tool",docs:n=[]}=null!=e?e:{},i=q(),{loading:o,secrets:s}=l.useSecrets(U),[d,u]=r.useState(!1);return r.useEffect((()=>{s&&u(!(null==s?void 0:s.bearerToken))}),[s]),o?a.jsx(c.Flex,{justify:"center",align:"center",children:a.jsx(c.Box,{padding:5,children:a.jsx(c.Spinner,{})})}):!o&&d||!(null==s?void 0:s.bearerToken)?a.jsx(l.SettingsView,{title:"Token Required",namespace:U,keys:F,onClose:()=>u(!1)}):"tool"===t&&i?a.jsxs(a.Fragment,{children:[a.jsx(R,{token:null==s?void 0:s.bearerToken,pluginConfig:i}),a.jsx(z,{})]}):(null==n?void 0:n.length)?i?a.jsx(B,{docs:n,token:null==s?void 0:s.bearerToken,pluginConfig:i}):a.jsx(_,{children:"No plugin config"}):a.jsx(_,{children:"No docs passed into Duplicator Tool"})}function X(e){const{docs:t=[]}=e;return a.jsx(W,{mode:"action",docs:t})}const V=e=>{const{draft:t,published:n,onComplete:i}=e,[o,s]=r.useState(!1);return{disabled:t,title:t?"Document must be Published to begin":null,label:"Duplicate to...",dialog:o&&n&&{type:"modal",title:"Cross Dataset Duplicator",content:a.jsx(X,{docs:[n]}),onClose:()=>{i(),s(!1)}},onHandle:()=>s(!0),icon:d.LaunchIcon}};function G(e){var t;const{docs:n=[]}=null!=(t=e.tool.options)?t:{};return a.jsx(W,{mode:"tool",docs:n})}V.action="duplicateTo";const H=s.definePlugin((function(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const o=i(i({},L),n),{types:s}=o;return{name:"@sanity/cross-dataset-duplicator",tools:e=>o.tool?[...e,{title:"Duplicator",name:"duplicator",icon:d.LaunchIcon,component:G,options:{docs:[]}}]:e,studio:{components:{layout:n=>function(n){const{pluginConfig:i}=n,o=t(n,e);return a.jsx(N.Provider,{value:i,children:n.renderDefault(o)})}(i(i({},n),{},{pluginConfig:o}))}},document:{actions:(e,t)=>{let{schemaType:n}=t;return s&&s.includes(n)?[...e,V]:e}}}}));exports.CrossDatasetDuplicatorAction=X,exports.DuplicateToAction=V,exports.crossDatasetDuplicator=H,exports.useCrossDatasetDuplicatorConfig=q;//# sourceMappingURL=index.js.map
package/lib/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}