@sane-shopify/sync-utils
Version:
Syncing utility for Node & the browser
1 lines • 65 kB
JavaScript
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var n,t,r,o,a,c,i,u=require("@good-idea/unwind-edges"),s=e(require("@sanity/client")),p=e(require("p-queue")),f=require("xstate"),d=require("@sane-shopify/types"),l=e(require("debug")),h=e(require("cross-fetch")),y=e(require("@good-idea/leaky-bucket")),m=e(require("graphql-tag")),v=e(require("deepmerge")),g=require("lodash");function x(){x=function(){return e};var e={},n=Object.prototype,t=n.hasOwnProperty,r=Object.defineProperty||function(e,n,t){e[n]=t.value},o="function"==typeof Symbol?Symbol:{},a=o.iterator||"@@iterator",c=o.asyncIterator||"@@asyncIterator",i=o.toStringTag||"@@toStringTag";function u(e,n,t){return Object.defineProperty(e,n,{value:t,enumerable:!0,configurable:!0,writable:!0}),e[n]}try{u({},"")}catch(e){u=function(e,n,t){return e[n]=t}}function s(e,n,t,o){var a=Object.create((n&&n.prototype instanceof d?n:d).prototype),c=new P(o||[]);return r(a,"_invoke",{value:b(e,t,c)}),a}function p(e,n,t){try{return{type:"normal",arg:e.call(n,t)}}catch(e){return{type:"throw",arg:e}}}e.wrap=s;var f={};function d(){}function l(){}function h(){}var y={};u(y,a,(function(){return this}));var m=Object.getPrototypeOf,v=m&&m(m(I([])));v&&v!==n&&t.call(v,a)&&(y=v);var g=h.prototype=d.prototype=Object.create(y);function w(e){["next","throw","return"].forEach((function(n){u(e,n,(function(e){return this._invoke(n,e)}))}))}function k(e,n){var o;r(this,"_invoke",{value:function(r,a){function c(){return new n((function(o,c){!function r(o,a,c,i){var u=p(e[o],e,a);if("throw"!==u.type){var s=u.arg,f=s.value;return f&&"object"==typeof f&&t.call(f,"__await")?n.resolve(f.__await).then((function(e){r("next",e,c,i)}),(function(e){r("throw",e,c,i)})):n.resolve(f).then((function(e){s.value=e,c(s)}),(function(e){return r("throw",e,c,i)}))}i(u.arg)}(r,a,o,c)}))}return o=o?o.then(c,c):c()}})}function b(e,n,t){var r="suspendedStart";return function(o,a){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===o)throw a;return{value:void 0,done:!0}}for(t.method=o,t.arg=a;;){var c=t.delegate;if(c){var i=_(c,t);if(i){if(i===f)continue;return i}}if("next"===t.method)t.sent=t._sent=t.arg;else if("throw"===t.method){if("suspendedStart"===r)throw r="completed",t.arg;t.dispatchException(t.arg)}else"return"===t.method&&t.abrupt("return",t.arg);r="executing";var u=p(e,n,t);if("normal"===u.type){if(r=t.done?"completed":"suspendedYield",u.arg===f)continue;return{value:u.arg,done:t.done}}"throw"===u.type&&(r="completed",t.method="throw",t.arg=u.arg)}}}function _(e,n){var t=n.method,r=e.iterator[t];if(void 0===r)return n.delegate=null,"throw"===t&&e.iterator.return&&(n.method="return",n.arg=void 0,_(e,n),"throw"===n.method)||"return"!==t&&(n.method="throw",n.arg=new TypeError("The iterator does not provide a '"+t+"' method")),f;var o=p(r,e.iterator,n.arg);if("throw"===o.type)return n.method="throw",n.arg=o.arg,n.delegate=null,f;var a=o.arg;return a?a.done?(n[e.resultName]=a.value,n.next=e.nextLoc,"return"!==n.method&&(n.method="next",n.arg=void 0),n.delegate=null,f):a:(n.method="throw",n.arg=new TypeError("iterator result is not an object"),n.delegate=null,f)}function S(e){var n={tryLoc:e[0]};1 in e&&(n.catchLoc=e[1]),2 in e&&(n.finallyLoc=e[2],n.afterLoc=e[3]),this.tryEntries.push(n)}function E(e){var n=e.completion||{};n.type="normal",delete n.arg,e.completion=n}function P(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(S,this),this.reset(!0)}function I(e){if(e){var n=e[a];if(n)return n.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,o=function n(){for(;++r<e.length;)if(t.call(e,r))return n.value=e[r],n.done=!1,n;return n.value=void 0,n.done=!0,n};return o.next=o}}return{next:C}}function C(){return{value:void 0,done:!0}}return l.prototype=h,r(g,"constructor",{value:h,configurable:!0}),r(h,"constructor",{value:l,configurable:!0}),l.displayName=u(h,i,"GeneratorFunction"),e.isGeneratorFunction=function(e){var n="function"==typeof e&&e.constructor;return!!n&&(n===l||"GeneratorFunction"===(n.displayName||n.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,h):(e.__proto__=h,u(e,i,"GeneratorFunction")),e.prototype=Object.create(g),e},e.awrap=function(e){return{__await:e}},w(k.prototype),u(k.prototype,c,(function(){return this})),e.AsyncIterator=k,e.async=function(n,t,r,o,a){void 0===a&&(a=Promise);var c=new k(s(n,t,r,o),a);return e.isGeneratorFunction(t)?c:c.next().then((function(e){return e.done?e.value:c.next()}))},w(g),u(g,i,"Generator"),u(g,a,(function(){return this})),u(g,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var n=Object(e),t=[];for(var r in n)t.push(r);return t.reverse(),function e(){for(;t.length;){var r=t.pop();if(r in n)return e.value=r,e.done=!1,e}return e.done=!0,e}},e.values=I,P.prototype={constructor:P,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(E),!e)for(var n in this)"t"===n.charAt(0)&&t.call(this,n)&&!isNaN(+n.slice(1))&&(this[n]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var n=this;function r(t,r){return c.type="throw",c.arg=e,n.next=t,r&&(n.method="next",n.arg=void 0),!!r}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],c=a.completion;if("root"===a.tryLoc)return r("end");if(a.tryLoc<=this.prev){var i=t.call(a,"catchLoc"),u=t.call(a,"finallyLoc");if(i&&u){if(this.prev<a.catchLoc)return r(a.catchLoc,!0);if(this.prev<a.finallyLoc)return r(a.finallyLoc)}else if(i){if(this.prev<a.catchLoc)return r(a.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return r(a.finallyLoc)}}}},abrupt:function(e,n){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&t.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var a=o;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=n&&n<=a.finallyLoc&&(a=null);var c=a?a.completion:{};return c.type=e,c.arg=n,a?(this.method="next",this.next=a.finallyLoc,f):this.complete(c)},complete:function(e,n){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&n&&(this.next=n),f},finish:function(e){for(var n=this.tryEntries.length-1;n>=0;--n){var t=this.tryEntries[n];if(t.finallyLoc===e)return this.complete(t.completion,t.afterLoc),E(t),f}},catch:function(e){for(var n=this.tryEntries.length-1;n>=0;--n){var t=this.tryEntries[n];if(t.tryLoc===e){var r=t.completion;if("throw"===r.type){var o=r.arg;E(t)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,t){return this.delegate={iterator:I(e),resultName:n,nextLoc:t},"next"===this.method&&(this.arg=void 0),f}},e}function w(e,n,t,r,o,a,c){try{var i=e[a](c),u=i.value}catch(e){return void t(e)}i.done?n(u):Promise.resolve(u).then(r,o)}function k(e){return function(){var n=this,t=arguments;return new Promise((function(r,o){var a=e.apply(n,t);function c(e){w(a,r,o,c,i,"next",e)}function i(e){w(a,r,o,c,i,"throw",e)}c(void 0)}))}}function b(){return(b=Object.assign?Object.assign.bind():function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}function _(e,n){return n||(n=e.slice(0)),e.raw=n,e}var S=f.Machine({id:"syncMachine",initial:d.SyncStates.INIT,context:{documentsFetched:[],toSync:[],syncOperations:[],toLink:[],linkOperations:[],error:void 0,errorMessage:void 0,valid:!1,ready:!1,shopName:void 0},states:(i={},i[d.SyncStates.INIT]={on:(n={},n[d.SyncEventType.Valid]={target:d.SyncStates.READY,actions:["onReady"]},n[d.SyncEventType.Invalid]={target:d.SyncStates.SETUP,actions:["onSetup"]},n)},i[d.SyncStates.SETUP]={on:(t={},t[d.SyncEventType.Valid]={target:d.SyncStates.READY,actions:["onReady"]},t[d.SyncEventType.Invalid]={target:d.SyncStates.SETUP,actions:["onError"]},t)},i[d.SyncStates.READY]={on:(r={},r[d.SyncEventType.Sync]=d.SyncStates.SYNCING,r[d.SyncEventType.ClearedSecrets]={target:d.SyncStates.SETUP,actions:"reset"},r)},i[d.SyncStates.SYNCING]={on:(o={},o[d.SyncEventType.DocumentsFetched]={internal:!0,actions:["onDocumentsFetched"]},o[d.SyncEventType.FetchComplete]={internal:!0,actions:["onFetchedComplete"]},o[d.SyncEventType.DocumentsSynced]={internal:!0,actions:["onDocumentsSynced"]},o[d.SyncEventType.DocumentsLinked]={internal:!0,actions:["onDocumentLinked"]},o[d.SyncEventType.Complete]=d.SyncStates.COMPLETE,o[d.SyncEventType.Errored]={target:d.SyncStates.SYNC_ERROR,actions:["onError"]},o)},i[d.SyncStates.COMPLETE]={on:(a={},a[d.SyncEventType.Reset]=d.SyncStates.READY,a)},i[d.SyncStates.SYNC_ERROR]={on:(c={},c[d.SyncEventType.Reset]=d.SyncStates.READY,c)},i)},{actions:{onReady:f.assign((function(e,n){return{valid:!0,ready:!0,shopName:n.shopName,errorMessage:void 0,error:void 0}})),onSetup:f.assign({valid:!1,ready:!0}),onError:f.assign({errorMessage:function(e,n){return n.errorMessage},error:function(e,n){return n.error},valid:!1}),onDocumentsFetched:f.assign({documentsFetched:function(e,n){return[].concat(e.documentsFetched,n.shopifyDocuments)}}),onFetchedComplete:f.assign({toSync:function(e){return e.documentsFetched},toLink:function(e){return e.documentsFetched}}),onDocumentsSynced:f.assign({syncOperations:function(e,n){return[].concat(e.syncOperations,[n.op])}}),onDocumentLinked:f.assign({linkOperations:function(e,n){return[].concat(e.linkOperations,[n.op])}})}}),E=l("sane-shopify:patch"),P=function(e){return void 0===e&&(e={}),{logFetched:function(n){var t=Array.isArray(n)?n:[n];E("fetched initial shopify documents:",t),e.onProgress&&e.onProgress({type:"fetched",shopifyDocuments:t})},logLinked:function(n,t){E("linked documents:",t),e.onProgress&&e.onProgress({type:"link",sourceDoc:n,pairs:t})},logSynced:function(n){E("synced document",n),e.onProgress&&e.onProgress(n)},logComplete:function(n){E("completed sync operations",n);var t=Array.isArray(n)?n:[n];e.onComplete&&e.onComplete(t,"completed sync operations")},logArchived:function(n){E("archived document:",n),e.onProgress&&e.onProgress({type:"archive",sourceDoc:n})}}},I="sane-shopify.storefront-config",C=function(e){switch(e.status){case 401:case 403:return"Authentication failed. Please make sure you have entered the correct Storefront name and API Key.";default:return"There was an error connecting to Shopify ("+e.status+": "+e.statusText+")"}},D=function(e){if(!e)throw new Error("No query string provided");return e.split(/\n\s+\n/).map((function(e){return e.replace(/^([\n\s])+/,"").replace(/\n+$/,"")})).reduce((function(e,n){return e.includes(n)?e:[].concat(e,[n])}),[]).join("\n\n")},N=function(e){if(!e)return{query:(n=k(x().mark((function e(){return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:throw new Error("You must provide a shopify storefront name and access token");case 1:case"end":return e.stop()}}),e)}))),function(){return n.apply(this,arguments)}),shopName:""};var n,t=e.shopName,r="https://"+t+".myshopify.com/api/2022-10/graphql.json",o={"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":e.accessToken},a=new y({capacity:40,interval:30});return{shopName:t,query:function(){var e=k(x().mark((function e(n,t){var c,i;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i="string"==typeof n?n:D(null==n||null==(c=n.loc)?void 0:c.source.body),e.next=3,a.throttle();case 3:return e.abrupt("return",h(r,{headers:o,method:"POST",body:JSON.stringify({variables:t,query:i})}).then(function(){var e=k(x().mark((function e(n){return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n.ok){e.next=2;break}throw new Error(C(n));case 2:return e.next=4,n.json();case 4:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}}),e)})));return function(n){return e.apply(this,arguments)}}()));case 4:case"end":return e.stop()}}),e)})));return function(n,t){return e.apply(this,arguments)}}()}},T=function(e,n){return Object.entries(e).reduce((function(e,t){var r,o=t[0];return o===n?e:b({},e,((r={})[o]=t[1],r))}),{})},F=function e(n){var t,r,o=b({},n,{metafields:{pageInfo:{hasNextPage:!1,hasPreviousPage:!1},edges:[]}}),a=Object.entries(n).reduce((function(e,n){var t,r=n[0],o=n[1],a=r.match(/metafield_/);if(null!=a&&a.input&&null===o)return T(e,r);if(null!=a&&a.input&&(t=o,Boolean(t&&t.value&&t.namespace&&t.key))){var c,i=T(e,a.input),u=(null==e||null==(c=e.metafields)?void 0:c.edges)||[],s=o.value,p=o.namespace,f=o.key;return b({},i,{metafields:b({},e.metafields,{edges:[].concat(u,[{_key:p+"-"+f+"-"+s,cursor:p+"-"+f+"-"+s,node:{namespace:p,key:f,value:s}}])})})}return e}),o);return"Product"===a.__typename&&"variants"in a&&null!=a&&null!=(t=a.variants)&&null!=(r=t.edges)&&r.length?b({},a,{variants:b({},a.variants,{edges:a.variants.edges.map((function(n){return b({},n,{node:e(n.node)})}))})}):a},A=function(e){return"shopifyProduct"===e._type},R=function(e){return"shopifyCollection"===e._type},O=function(e){return"Product"===e.__typename},L=function(e){return"Collection"===e.__typename};function $(e){return e?e.filter((function(e){return Boolean(e)})):[]}var B,q,V,j,M,Y,H,U,G,W,Q=function(e){if(!e.edges||0===e.edges.length)return null;var n,t=(n=null==e?void 0:e.edges)[n.length-1];return t?t.cursor:null},z=function(e,n){if(!e.pageInfo||!n.pageInfo)throw new Error("Page info was not suplied");return{pageInfo:{hasPrevPage:e.pageInfo.hasPreviousPage,hasPreviousPage:e.pageInfo.hasPreviousPage,hasNextPage:n.pageInfo.hasNextPage},edges:[].concat($(e.edges),$(n.edges))}},K=function(e){return e.startsWith("gid://")?btoa(e):e},X=function(e){return e.startsWith("gid://")?e:atob(e)},J="\n fragment ImageFragment on Image {\n __typename\n id\n altText\n originalSrc\n w100: transformedSrc(maxWidth: 100, crop: CENTER)\n w300: transformedSrc(maxWidth: 300, crop: CENTER)\n w800: transformedSrc(maxWidth: 800, crop: CENTER)\n w1200: transformedSrc(maxWidth: 1200, crop: CENTER)\n w1600: transformedSrc(maxWidth: 1600, crop: CENTER)\n }\n",Z=function(e){return e?e.map((function(e){var n=e.namespace,t=e.key;return"\n metafield_"+n+"_"+t+': metafield(namespace: "'+n+'", key: "'+t+'"){\n namespace\n key\n value\n }\n '})):""},ee=function(e){var n;return m(q||(q=_(["\n fragment ProductFragment on Product {\n __typename\n id\n updatedAt\n handle\n title\n description\n descriptionHtml\n availableForSale\n productType\n tags\n vendor\n createdAt\n publishedAt\n options {\n id\n name\n values\n }\n variants(first: 99) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n ...ProductVariantFragment\n }\n }\n }\n ","\n compareAtPriceRange {\n minVariantPrice {\n ...MoneyV2Fragment\n }\n maxVariantPrice {\n ...MoneyV2Fragment\n }\n }\n priceRange {\n minVariantPrice {\n ...MoneyV2Fragment\n }\n maxVariantPrice {\n ...MoneyV2Fragment\n }\n }\n media(first: 50) {\n edges {\n cursor\n node {\n ...MediaImageFragment\n ...VideoFragment\n }\n }\n }\n images(first: 50) {\n edges {\n cursor\n node {\n ...ImageFragment\n }\n }\n }\n }\n ","\n ","\n ","\n ","\n ","\n"])),Z(null==e||null==(n=e.products)?void 0:n.metafields),"\n fragment MoneyV2Fragment on MoneyV2 {\n amount\n currencyCode\n }\n","\n fragment MediaImageFragment on MediaImage {\n image {\n __typename\n id\n altText\n originalSrc\n w100: transformedSrc(maxWidth: 100, crop: CENTER)\n w300: transformedSrc(maxWidth: 300, crop: CENTER)\n w800: transformedSrc(maxWidth: 800, crop: CENTER)\n w1200: transformedSrc(maxWidth: 1200, crop: CENTER)\n w1600: transformedSrc(maxWidth: 1600, crop: CENTER)\n }\n }\n",J,"\n fragment VideoFragment on Video {\n id\n alt\n sources {\n url\n format\n mimeType\n }\n }\n",function(e){var n;return m(B||(B=_(["\n fragment ProductVariantFragment on ProductVariant {\n __typename\n availableForSale\n currentlyNotInStock\n id\n image {\n ...ImageFragment\n }\n priceV2 {\n ...MoneyV2Fragment\n }\n compareAtPriceV2 {\n ...MoneyV2Fragment\n }\n selectedOptions {\n value\n name\n }\n ","\n requiresShipping\n sku\n title\n weight\n weightUnit\n }\n"])),Z(null==e||null==(n=e.variants)?void 0:n.metafields))}(e))},ne=function(e){var n;return m(V||(V=_(["\n fragment CollectionFragment on Collection {\n __typename\n id\n updatedAt\n handle\n title\n description\n descriptionHtml\n ","\n image {\n ...ImageFragment\n }\n }\n ","\n"])),Z(null==e||null==(n=e.collections)?void 0:n.metafields),J)},te=l("sane-shopify:fetching"),re=function(e){return m(j||(j=_(["\n query ProductQuery(\n $handle: String!\n $collectionsFirst: Int!\n $collectionsAfter: String\n ) {\n productByHandle(handle: $handle) {\n ...ProductFragment\n collections(first: $collectionsFirst, after: $collectionsAfter) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n ","\n"])),ee(e))},oe=function(e){return m(M||(M=_(["\n query NodeQuery(\n $id: ID!\n $collectionsFirst: Int!\n $collectionsAfter: String\n ) {\n node(id: $id) {\n ... on Product {\n ...ProductFragment\n collections(first: $collectionsFirst, after: $collectionsAfter) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n }\n ","\n"])),ee(e))},ae=function(e){return{PRODUCT_BY_ID:oe(e),PRODUCT_BY_HANDLE:re(e)}},ce=function(){var e=k(x().mark((function e(n,t,r,o){var a,c,i;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.query(t,{handle:r,collectionsFirst:200,collectionsAfter:o});case 2:return i=null==(c=e.sent)||null==(a=c.data)?void 0:a.productByHandle,e.abrupt("return",i?F(i):void 0);case 5:case"end":return e.stop()}}),e)})));return function(n,t,r,o){return e.apply(this,arguments)}}(),ie=function(){var e=k(x().mark((function e(n,t,r,o){var a,c,i;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.query(t,{id:r,collectionsFirst:20,collectionsAfter:o});case 2:return i=null==(c=e.sent)||null==(a=c.data)?void 0:a.node,e.abrupt("return",i?F(i):void 0);case 5:case"end":return e.stop()}}),e)})));return function(n,t,r,o){return e.apply(this,arguments)}}(),ue=function(){var e=k(x().mark((function e(n,t,r){var o,a,c,i,u,s,p,f,d;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(o=r.collections)&&null!=(a=o.pageInfo)&&a.hasNextPage){e.next=3;break}return te("Fetched all collections for product "+r.handle,r),e.abrupt("return",r);case 3:return u=Q(r.collections),te("Fetching further products for product "+r.handle,r),s=ae(t),p=s.PRODUCT_BY_HANDLE,e.next=8,ce(n,p,r.handle,u||void 0);case 8:if(null==(d=(f=e.sent)?b({},f,{collections:f.collections?z(r.collections,f.collections):r.collections}):r)||null==(c=d.collections)||null==(i=c.pageInfo)||!i.hasNextPage){e.next=12;break}return e.abrupt("return",ue(n,t,d));case 12:return te("Fetched all collections for product "+r.handle,r),e.abrupt("return",d);case 14:case"end":return e.stop()}}),e)})));return function(n,t,r){return e.apply(this,arguments)}}(),se=function(e,n,t){return function(){var r=k(x().mark((function r(o){var a,c,i,u,s,p,f,d,l;return x().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,n();case 2:if(a=r.sent,i=o.handle,(c=o.id)||i){r.next=6;break}throw new Error("You must provide either an id or handle");case 6:if(u=ae(a),s=u.PRODUCT_BY_ID,p=u.PRODUCT_BY_HANDLE,!(f=c?t.getProductById(c):i?t.getProductByHandle(i):null)){r.next=10;break}return r.abrupt("return",ue(e,a,f));case 10:if(!c){r.next=16;break}return r.next=13,ie(e,s,c);case 13:r.t0=r.sent,r.next=24;break;case 16:if(!i){r.next=22;break}return r.next=19,ce(e,p,i);case 19:r.t1=r.sent,r.next=23;break;case 22:r.t1=null;case 23:r.t0=r.t1;case 24:if(d=r.t0){r.next=27;break}return r.abrupt("return",null);case 27:return r.next=29,ue(e,a,d);case 29:return t.set(l=r.sent),r.abrupt("return",l);case 32:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()},pe=l("sane-shopify:fetching"),fe=function(e){return m(Y||(Y=_(["\n query CollectionQuery(\n $handle: String!\n $productsFirst: Int!\n $productsAfter: String\n ) {\n collectionByHandle(handle: $handle) {\n ...CollectionFragment\n products(first: $productsFirst, after: $productsAfter) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n ","\n"])),ne(e))},de=function(e){return m(H||(H=_(["\n query NodeQuery($id: ID!, $productsFirst: Int!, $productsAfter: String) {\n node(id: $id) {\n ... on Collection {\n ...CollectionFragment\n products(first: $productsFirst, after: $productsAfter) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n }\n ","\n"])),ne(e))},le=function(e){return{COLLECTION_BY_ID:de(e),COLLECTION_BY_HANDLE:fe(e)}},he=function(){var e=k(x().mark((function e(n,t,r,o){var a,c;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.query(t,{handle:r,productsFirst:50,productsAfter:o});case 2:return e.abrupt("return",null==(c=e.sent)||null==(a=c.data)?void 0:a.collectionByHandle);case 4:case"end":return e.stop()}}),e)})));return function(n,t,r,o){return e.apply(this,arguments)}}(),ye=function(){var e=k(x().mark((function e(n,t,r,o){var a,c;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.query(t,{id:r,productsFirst:200,productsAfter:o});case 2:return e.abrupt("return",null==(c=e.sent)||null==(a=c.data)?void 0:a.node);case 4:case"end":return e.stop()}}),e)})));return function(n,t,r,o){return e.apply(this,arguments)}}(),me=function(){var e=k(x().mark((function e(n,t,r){var o,a,c,i,u,s,p,f,d;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=(o=r.products)&&null!=(a=o.pageInfo)&&a.hasNextPage){e.next=3;break}return pe("Fetched all products for collection "+r.handle,r),e.abrupt("return",r);case 3:return u=Q(r.products),pe("Fetching further products for collection "+r.handle,r),s=le(t),p=s.COLLECTION_BY_HANDLE,e.next=8,he(n,p,r.handle,u||void 0);case 8:if(null==(d=(f=e.sent)?b({},f,{products:z(r.products,f.products)}):r)||null==(c=d.products)||null==(i=c.pageInfo)||!i.hasNextPage){e.next=12;break}return e.abrupt("return",me(n,t,d));case 12:return pe("Fetched all products for collection "+r.handle,r),e.abrupt("return",d);case 14:case"end":return e.stop()}}),e)})));return function(n,t,r){return e.apply(this,arguments)}}(),ve=function(e,n,t){return function(){var r=k(x().mark((function r(o){var a,c,i,u,s,p,f,d,l;return x().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,n();case 2:if(a=r.sent,i=o.handle,(c=o.id)||i){r.next=6;break}throw new Error("You must provide either an id or handle");case 6:if(!(u=c?t.getCollectionById(c):i?t.getCollectionByHandle(i):null)){r.next=9;break}return r.abrupt("return",me(e,a,u));case 9:if(s=le(a),p=s.COLLECTION_BY_ID,f=s.COLLECTION_BY_HANDLE,!c){r.next=16;break}return r.next=13,ye(e,p,c);case 13:r.t0=r.sent,r.next=24;break;case 16:if(!i){r.next=22;break}return r.next=19,he(e,f,i);case 19:r.t1=r.sent,r.next=23;break;case 22:r.t1=null;case 23:r.t0=r.t1;case 24:if(d=r.t0){r.next=27;break}return r.abrupt("return",null);case 27:return r.next=29,me(e,a,d);case 29:return t.set(l=r.sent),r.abrupt("return",l);case 32:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()},ge=function(e,n,t){return function(){var r=k(x().mark((function r(o,a){var c,i,u,s,p,f,d;return x().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return r.next=2,n();case 2:if(l=i=r.sent,u=m(U||(U=_(["\n query NodeQuery($id: ID!) {\n node(id: $id) {\n ... on Product {\n ...ProductFragment\n collections(first: 20) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n ... on Collection {\n ...CollectionFragment\n products(first: 50) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n }\n ","\n ","\n"])),ee(l),ne(l)),!(s=t.getCollectionById(o)||t.getProductById(o))){r.next=7;break}return r.abrupt("return",s);case 7:return r.next=9,e.query(u,{id:X(o)});case 9:if(f=null!=(p=r.sent)&&null!=(c=p.data)&&c.node?F(p.data.node):void 0,!p.errors){r.next=14;break}throw d=p.errors.map((function(e){return e.message})).join(" | "),new Error(("Could not fetch item "+o+": ").concat(d));case 14:if(f){r.next=16;break}return r.abrupt("return",null);case 16:if(a){r.next=18;break}return r.abrupt("return",f);case 18:if("Product"!==f.__typename){r.next=23;break}return r.next=21,ue(e,i,f);case 21:return r.abrupt("return",r.sent);case 23:if("Collection"!==f.__typename){r.next=25;break}return r.abrupt("return",me(e,i,f));case 25:throw new Error("Cannot fetch item "+o+" with typename "+f.__typename);case 26:case"end":return r.stop()}var l}),r)})));return function(e,n){return r.apply(this,arguments)}}()},xe=l("sane-shopify:fetching"),we=function(e){return e.errors.some((function(e){return"Timeout"===e.message}))},ke=function(){},be=function(e,n,t){return function(){var r=k(x().mark((function r(o){var a,c,i,s,f,d,l,h;return x().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return void 0===o&&(o=ke),r.next=3,n();case 3:return y=a=r.sent,c=m(G||(G=_(["\n query CollectionsQuery($first: Int!, $after: String) {\n collections(first: $first, after: $after) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n ...CollectionFragment\n products(first: 25) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n }\n }\n ","\n"])),ne(y)),i=new Date,s=function(){var n=k(x().mark((function n(r,a){var i,p,f,d,l,h,y,m,v,g,w;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return void 0===r&&(r=30),i=a?Q(a):void 0,p=new Date,n.next=5,e.query(c,{first:r,after:i});case 5:if(!("errors"in(f=n.sent))){n.next=16;break}if(!we(f)){n.next=13;break}if(1!==r){n.next=10;break}throw new Error("Collections query timed out with a page size of 1.");case 10:return d=Math.round(r/2),xe("Collections query timed out. Falling back to smaller page size ("+d+")"),n.abrupt("return",s(d,a));case 13:throw xe("Collections request failed: "+f.errors),l="Collections request failed: "+f.errors.map((function(e){return e.message})).join(" | "),new Error(l);case 16:if(h=(new Date).getTime()-p.getTime(),xe("Fetched page of Shopify Collections in "+h/1e3+"s",f),m=u.unwindEdges(y=f.data.collections),o(m[0]),(v=a?z(a,y):y).pageInfo){n.next=24;break}throw new Error("Pagination info was not fetched");case 24:if(!v.pageInfo.hasNextPage){n.next=26;break}return n.abrupt("return",s(r,v));case 26:return g=u.unwindEdges(v),(w=g[0]).forEach((function(e){return t.set(e)})),n.abrupt("return",w);case 29:case"end":return n.stop()}}),n)})));return function(e,t){return n.apply(this,arguments)}}(),r.next=9,s();case 9:return f=r.sent.map(F),d=(new Date).getTime()-i.getTime(),xe("Fetched all Shopify Collections in "+d/1e3+"s",f),l=new p({concurrency:1}),r.next=16,l.addAll(f.map((function(n){return function(){return me(e,a,n)}})));case 16:return xe("Fetched all Shopify Collections in "+d/1e3+"s",h=r.sent),r.abrupt("return",h);case 19:case"end":return r.stop()}var y}),r)})));return function(e){return r.apply(this,arguments)}}()},_e=function(){},Se=function(e,n,t){return function(){var r=k(x().mark((function r(o){var a,c,i,s,f,d,l,h;return x().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return void 0===o&&(o=_e),r.next=3,n();case 3:return y=a=r.sent,c=m(W||(W=_(["\n query ProductsQuery($first: Int!, $after: String) {\n products(first: $first, after: $after) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n ...ProductFragment\n collections(first: 99) {\n pageInfo {\n hasNextPage\n hasPreviousPage\n }\n edges {\n cursor\n node {\n id\n handle\n }\n }\n }\n }\n }\n }\n }\n ","\n"])),ee(y)),i=new Date,s=function(){var n=k(x().mark((function n(r,a){var i,p,f,d,l,h,y,m,v,g,w;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return void 0===r&&(r=30),i=a?Q(a):void 0,p=new Date,xe("Fetching products - page size: "+r+", previous results: "+((null==a?void 0:a.edges.length)||0)),n.next=6,e.query(c,{first:r,after:i});case 6:if(!("errors"in(f=n.sent))){n.next=17;break}if(!we(f)){n.next=14;break}if(1!==r){n.next=11;break}throw new Error("Product query timed out with a page size of 1.");case 11:return d=Math.round(r/2),xe("Product query timed out. Falling back to smaller page size ("+d+")"),n.abrupt("return",s(d,a));case 14:throw xe("Product request failed: "+f.errors),l="Product request failed: "+f.errors.map((function(e){return e.message})).join(" | "),new Error(l);case 17:if(h=(new Date).getTime()-p.getTime(),xe("Fetched page of Shopify Products in "+h/1e3+"s",f),m=u.unwindEdges(y=f.data.products),o(m[0]),(v=a?z(a,y):y).pageInfo){n.next=25;break}throw new Error("Products page info was not fetched");case 25:if(!v.pageInfo.hasNextPage){n.next=27;break}return n.abrupt("return",s(r,v));case 27:return g=u.unwindEdges(v),(w=g[0]).forEach((function(e){return t.set(e)})),n.abrupt("return",w);case 30:case"end":return n.stop()}}),n)})));return function(e,t){return n.apply(this,arguments)}}(),r.next=9,s();case 9:return f=r.sent.map(F),d=new p({concurrency:1}),r.next=14,d.addAll(f.map((function(n){return function(){return ue(e,a,n)}})));case 14:return l=r.sent,h=(new Date).getTime()-i.getTime(),xe("Fetched all Shopify Products in "+h/1e3+"s",l),r.abrupt("return",l);case 18:case"end":return r.stop()}var y}),r)})));return function(e){return r.apply(this,arguments)}}()},Ee=function(){var e=k(x().mark((function e(n){var t,r,o;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n){e.next=2;break}return e.abrupt("return",{isError:!1,message:"You must provide an API Key and Storefront Name"});case 2:if(r=n.accessToken,(t=n.shopName)&&t.length){e.next=5;break}return e.abrupt("return",{isError:!0,message:"You must provide a Storefront name"});case 5:if(r&&r.length){e.next=7;break}return e.abrupt("return",{isError:!0,message:"You must provide a Storefront API Key"});case 7:return e.prev=7,o=N(n),e.next=11,o.query("\n {\n shop {\n name\n }\n }\n").then((function(){return{isError:!1,message:"Successfully connected to "+t}}));case 11:return e.abrupt("return",e.sent);case 15:return e.prev=15,e.t0=e.catch(7),e.abrupt("return",{isError:!0,message:e.t0 instanceof Error?e.t0.message:"There was an error connecting to Shopify. Check your console for more information."});case 18:case"end":return e.stop()}}),e,null,[[7,15]])})));return function(n){return e.apply(this,arguments)}}();require("es6-promise").polyfill(),require("isomorphic-fetch");var Pe=function(e,n){var t,r,o,a,c=(t={},r={},o={},a={},{getProductById:function(e){return o[e]||null},getProductByHandle:function(e){return a[e]||null},getCollectionById:function(e){return t[e]||null},getCollectionByHandle:function(e){return r[e]||null},set:function(e){"Collection"===e.__typename?(t[e.id]=e,r[e.handle]=e):"Product"===e.__typename&&(o[e.id]=e,a[e.handle]=e)}});return{client:e,fetchItemById:ge(e,n,c),fetchShopifyProduct:se(e,n,c),fetchShopifyCollection:ve(e,n,c),fetchAllShopifyProducts:Se(e,n,c),fetchAllShopifyCollections:be(e,n,c),testSecrets:Ee}},Ie=["id"],Ce=function(e){return new Promise((function(n){return setTimeout(n,e)}))},De=function(e,n){return e.map((function(e){var t=e.cursor;return{cursor:t,node:e.node,_type:n,_key:t}}))},Ne={__typename:"Image",altText:"",id:"",originalSrc:"",w100:"",w300:"",w800:"",w1200:"",w1600:""},Te=function(e){var n;if(O(e))return b({},e,{_type:"shopifySourceProduct",options:e.options.map((function(e){var n=e.id;return b({},function(e,n){if(null==e)return{};var t,r,o={},a=Object.keys(e);for(r=0;r<a.length;r++)n.indexOf(t=a[r])>=0||(o[t]=e[t]);return o}(e,Ie),{_key:n})})),collections:b({},e.collections,{edges:De($(null==e||null==(n=e.collections)?void 0:n.edges),"shopifySourceCollectionEdge")}),variants:b({},e.variants,{edges:De($(null==e?void 0:e.variants.edges),"shopifySourceProductVariantEdges")}),media:b({},e.media,{edges:De($(e.media.edges),"shopifySourceMediaEdge")}),images:b({},e.images,{edges:De($(e.images.edges),"shopifySourceImageEdge")})});if(L(e))return b({},e,{_type:"shopifySourceCollection",image:e.image||{},products:b({},e.products,{edges:De($(e.products.edges),"shopifySourceProductEdge")})});throw new Error("prepareImages can only be used for Products and Collections")},Fe={amount:"0",currencyCode:"NONE"},Ae=function(e){return e?parseFloat(e):void 0},Re=function(e){var n=function(e){switch(e.__typename){case"Product":return"shopifyProduct";case"Collection":return"shopifyCollection";case void 0:throw new Error("The supplied item does not have a __typename");default:throw new Error("The __typename '"+e.__typename+"' is not currently supported")}}(e);if(O(e)){var t,r,o,a,c=Te(e),i=Ae(null==(t=e.priceRange)||null==(r=t.minVariantPrice)?void 0:r.amount),s=Ae(null==e||null==(o=e.priceRange)||null==(a=o.maxVariantPrice)?void 0:a.amount),p=function(e){return e.options.map((function(e){return{_type:"shopifyProductOption",_key:e.id,shopifyOptionId:e.id,name:e.name,values:e.values.map((function(e){return{_type:"shopifyProductOptionValue",_key:(n=e,n.toString().toLowerCase().replace(/\s+/g,"-").replace(/[^\w\-]+/g,"").replace(/\-\-+/g,"-").replace(/^-+/,"").replace(/-+$/,"")),value:e};var n}))}}))}(e),f=function(e){return u.unwindEdges(e.variants)[0].map((function(e){var n;return{_type:"shopifyProductVariant",_key:e.id,id:e.id,shopifyVariantID:e.id,title:e.title,sourceData:b({},e,{_type:"shopifySourceProductVariant",compareAtPriceV2:null!=(n=e.compareAtPriceV2)?n:Fe,image:e.image?e.image:Ne,selectedOptions:e.selectedOptions?e.selectedOptions.map((function(e){var n=e.name,t=e.value;return{_key:(n+"_"+t).replace(/\s/,"_"),_type:"shopifySourceSelectedOption",name:n,value:t}})):[]})}}))||[]}(e);return{_type:n,archived:!1,minVariantPrice:i,maxVariantPrice:s,title:e.title,shopifyId:e.id,handle:e.handle,sourceData:b({},c),options:p,variants:f}}if(L(e)){var d=Te(e);return{_type:n,archived:!1,title:e.title,shopifyId:e.id,handle:e.handle,sourceData:d}}throw new Error('Could not prepare document with type "'+e.__typename+'"')},Oe=function(e){return e.reduce((function(e,n){return e.some((function(e){return g.isMatch(e,n)}))?e:[].concat(e,[n])}),[])},Le=function(e,n){if(R(e)&&R(n))return b({},v(n,e),{sourceData:b({},e.sourceData,{products:b({},e.sourceData.products,{edges:Oe($(e.sourceData.products.edges))})})});if(A(e)&&A(n)){var t,r,o=v(n,e),a=e.variants||[],c=e.options||[];return b({},o,{sourceData:b({},e.sourceData,{collections:b({},e.sourceData.collections,{edges:Oe($(null==e||null==(t=e.sourceData)||null==(r=t.collections)?void 0:r.edges))}),media:b({},e.sourceData.media,{edges:Oe($(e.sourceData.media.edges))}),images:b({},e.sourceData.images,{edges:Oe($(e.sourceData.images.edges))})}),options:c.map((function(e){var t=n.options?null==n?void 0:n.options.find((function(n){return n._key===e._key||X(n._key)===e._key})):void 0,r=[].concat(t?t.values:[],e?e.values:[]).reduce((function(e,n){var t=e.findIndex((function(e){return e._key===n._key}));if(t>-1){var r=b({},e[t],n);return[].concat(e.slice(0,t),[r],e.slice(t+1))}return[].concat(e,[n])}),[]);return b({},t,e,{values:r})})),variants:a.map((function(e){return b({},n.variants&&n.variants.find((function(n){return n.shopifyVariantID===e.shopifyVariantID}))||{},e)}))})}throw new Error('The document with the shopifyId "'+n.shopifyId+'" could not be merged. Be sure that the document includes a _type property')},$e=function(e){return Array.isArray(e)?e:[e]},Be=function(e){return b({},e,{_id:e._id.replace(/^drafts\./,"")})},qe=function(e,n){return function(){var t=k(x().mark((function t(r,o){var a,c;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(a=A(i=r)?i.collectionRefs||[]:R(i)&&i.productRefs||[],0!==(c=$e(o).map((function(e){return a.find((function(n){return n._ref===e._id}))})).map((function(e){return e&&A(r)?'collections[_key=="'+e._key+'"]':e&&R(r)?'products[_key=="'+e._key+'"]':""})).filter(Boolean)).length){t.next=4;break}return t.abrupt("return",null);case 4:return t.next=6,e.patch(r._id).unset(c).commit({returnDocuments:!0});case 6:return n.set(t.sent),t.abrupt("return",null);case 9:case"end":return t.stop()}var i}),t)})));return function(e,n){return t.apply(this,arguments)}}()},Ve=function(e,n){if(A(n)){var t=n.collections.find((function(n){return n._ref===e._id}));if(!t)return;return['collections[_key=="'+t._key+'"]']}if(R(n)){var r=n.products.find((function(n){return n._ref===e._id}));if(!r)return;return['products[_key=="'+r._key+'"]']}throw new Error("Could not get relationships for this document")},je=["shopifyCollection","shopifyProduct"],Me=l("sane-shopify:migrations"),Ye=[function(){var e=k(x().mark((function e(n){var t,r,o;return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.fetch("*[_type == $type]",{type:"sane-shopify.keys"});case 2:return t=e.sent,e.next=5,n.fetch("*[_type == $type]",{type:I});case 5:if(r=e.sent,!t||!t.length){e.next=11;break}return o=t.reduce((function(e,n){if(r.find((function(e){return e.shopName===n.shopName})))return e.delete(n._id),e;var t=b({},n,{_id:"sane-shopify-storefront-config-".concat(n.shopName),_type:I});return e.create(t).delete(n._id),e}),n.transaction()),Me("Updated sanity config document type"),e.next=11,o.commit();case 11:case"end":return e.stop()}}),e)})));return function(n){return e.apply(this,arguments)}}()],He=function(){var e=k(x().mark((function e(n){return x().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Promise.all(Ye.map((function(e){return e(n)})));case 2:case"end":return e.stop()}}),e)})));return function(n){return e.apply(this,arguments)}}(),Ue=function(){},Ge=function(e,n,t){void 0===t&&(t=Ue);var r=function(e,n){var t,r,o,a,c=(t={},r={},o={},a={},{getById:function(e){return t[e]||null},getByHandle:function(e,n){var t="collection"===n?r:"product"===n?o:null;if(!t)throw new Error('There is no handle cache for type "'+n+'"');return t[e]||null},getByShopifyId:function(e){return a[e]||null},set:function(e){if(e){t[e._id]=e;var n="shopifyCollection"===e._type?r:"shopifyProduct"===e._type?o:null;if(!n)throw new Error('There is no handle cache for type "'+e._type+'"');n[e.handle]=e,e.shopifyId&&(a[e.shopifyId]=e)}}}),i=function(e,n){return function(){var t=k(x().mark((function t(r){var o,a;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return o=(r&&r.types?r.types:je).map((function(e){return"_type == '"+e+"'"})).join(" || "),t.next=4,e.fetch("\n *[\n shopifyId != null &&\n !(_id in path('drafts.**')) &&\n ("+o+')\n ]{\n ...,\n products[]->{\n "collectionRefs": collections[],\n ...\n },\n collections[]->{\n "productRefs": products[],\n ...\n },\n "collectionRefs": collections[],\n "productRefs": products[],\n }\n ');case 4:return(a=t.sent).forEach((function(e){return n.set(e)})),t.abrupt("return",a);case 7:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}()}(e,c),u=function(e,n,t){return function(){var r=k(x().mark((function r(o){var a,c;return x().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return a=t.shopName,c=function(){var t=k(x().mark((function t(r){var o,a,c,i;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=K(r),a=X(r),!(c=n.getByShopifyId(o))){t.next=5;break}return t.abrupt("return",c);case 5:return t.next=7,e.fetch('\n *[shopifyId == $shopifyId || shopifyId == $adminApiId]{\n ...,\n products[]->{\n "collectionRefs": collections[],\n ...\n },\n collections[]->{\n "productRefs": products[],\n ...\n },\n "collectionRefs": collections[],\n "productRefs": products[],\n }[0]',{shopifyId:o,adminApiId:a});case 7:return(i=t.sent)&&n.set(i),t.abrupt("return",i);case 10:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}(),r.abrupt("return",function(){var t=k(x().mark((function t(r,o){var a,i,u,s,p,f,d;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return a=Re(b({},r,{shopName:o})),t.next=3,c(r.id);case 3:if(!(i=t.sent)||(l=a,!g.isMatch(g.pick(i,h=["_type","handle","shopifyId","title","minVariantPrice","maxVariantPrice","sourceData","options","variants"]),g.pick(l,h)))){t.next=6;break}return t.abrupt("return",{type:"skip",sanityDocument:i,shopifySource:r});case 6:return t.next=8,Ce(201);case 8:if(i){t.next=19;break}return t.next=11,e.create(a);case 11:return u=t.sent,t.next=14,c(u.shopifyId);case 14:if(s=t.sent){t.next=17;break}throw new Error("Could not fetch updated document with shopifyId "+u.shopifyId);case 17:return n.set(s),t.abrupt("return",{type:"create",sanityDocument:u,shopifySource:r});case 19:return p=g.omit(Le(a,i),["products","collections","productRefs","collectionRefs"]),t.next=22,e.patch(i._id).set(p).commit();case 22:return f=t.sent,t.next=25,c(f.shopifyId);case 25:if(d=t.sent){t.next=28;break}throw new Error("Could not fetch updated document with shopifyId "+f.shopifyId);case 28:return n.set(d),t.abrupt("return",{type:"update",sanityDocument:d,shopifySource:r});case 30:case"end":return t.stop()}var l,h}),t)})));return function(e,n){return t.apply(this,arguments)}}()(o,a));case 4:case"end":return r.stop()}}),r)})));return function(e){return r.apply(this,arguments)}}()}(e,c,n),s=function(e,n){return function(){var t=k(x().mark((function t(r){var o,a,c,i,u,s,p,f,d,l;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o=r.map((function(e){return e.id})),a=o.map((function(e){return{cachedItem:n.getByShopifyId(e),id:e}})).reduce((function(e,n){return b({},e,null===n.cachedItem?{idsNotInCache:[].concat(e.idsNotInCache,[n.id])}:{cachedDocs:[].concat(e.cachedDocs,[n.cachedItem])})}),{cachedDocs:[],idsNotInCache:[]}),c=a.cachedDocs,u=(i=a.idsNotInCache).map(K),s=i.map(X),p=[].concat(u,s),!i.length){t.next=11;break}return t.next=8,e.fetch('\n *[shopifyId in $relatedIds && defined(archived) && archived != true && !(_id in path(\'drafts.**\'))]{\n ...,\n products[]->{\n "collectionRefs": collections[],\n ...\n },\n collections[]->{\n "productRefs": products[],\n ...\n },\n "collectionRefs": collections[],\n "productRefs": products[],\n }',{relatedIds:p});case 8:t.t0=t.sent,t.next=12;break;case 11:t.t0=[];case 12:return(f=t.t0).forEach((function(e){return n.set(e)})),d=[].concat(c,f),l=r.map((function(e){return{shopifyNode:e,sanityDocument:d.find((function(n){return n.shopifyId===e.id||X(n.shopifyId)===e.id}))||null}})),t.abrupt("return",l);case 17:case"end":return t.stop()}}),t)})));return function(e){return t.apply(this,arguments)}}()}(e,c),f=function(e,n){return function(){var t=k(x().mark((function t(r,o){var a,c,i,u,s,f,d,l,h,y,m,v;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(c=$($e(o).map(Be)),i=A(r)?r.collections||[]:R(r)&&r.products||[],u=c.length===i.length&&c.every((function(e,n){return Boolean(i[n]&&i[n]._id===e._id)})),s="shopifyProduct"===r._type?"products":"collections",f=c.filter((function(e){return Array.isArray(e[s])||(e[s]=[]),!e[s].some((function(e){return e._ref||e._id===r._id}))})),!u||0!==f.length){t.next=7;break}return t.abrupt("return",{type:"link",sourceDoc:r,pairs:c.map((function(e){return{from:r,to:e}}))});case 7:return d=c.map((function(e){return{_type:"reference",_ref:e._id,_key:e._rev+"-"+e._id}})).reduce((function(e,n){return e.some((function(e){return e._ref===n._ref}))?e:[].concat(e,[n])}),[]),l="shopifyProduct"===r._type?"collections":"products",t.next=11,e.patch(r._id).set((a={},a[l]=d,a)).commit({returnDocuments:!0});case 11:if(n.set(t.sent),!(h=i.filter((function(e){return!e.archived&&null!==e.shopifyId&&!c.some((function(n){return n._id===e._id}))}),[])).length){t.next=19;break}return y=qe(e,n),m=new p({concurrency:1}),t.next=19,m.addAll(h.map((function(e){return k(x().mark((function n(){return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.abrupt("return",y(e,r));case 1:case"end":return n.stop()}}),n)})))})));case 19:return v=new p({concurrency:1}),t.next=22,v.addAll(f.map((function(n){return k(x().mark((function t(){var o,a;return x().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(o={from:r,to:n},n[s].some((function(e){return e._id===r._id}))){t.next=5;break}return t.next=5,e.patch(n._id.replace(/^draft\./,"")).setIfMissing((a={},a[s]=[],a)).append(s,[{_type:"reference",_ref:r._id.replace(/^draft\./,""),_key:r._id+"-"+r._rev}]).commit();case 5:return t.abrupt("return",o);case 6:case"end":return t.stop()}}),t)})))})));case 22:return t.abrupt("return",{type:"link",sourceDoc:r,pairs:t.sent});case 25:case"end":return t.stop()}}),t)})));return function(e,n){return t.apply(this,arguments)}}()}(e,c),d=qe(e,c),l=function(e){return function(){var n=k(x().mark((function n(t){var r,o,a,c;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r="Collection"===t.sourceData.__typename?"products":"collections",o=function(){var n=k(x().mark((function n(r){var o;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(o=Ve(t,r)){n.next=3;break}return n.abrupt("return");case 3:return n.next=5,e.patch(r._id).unset(o).commit();case 5:case"end":return n.stop()}}),n)})));return function(e){return n.apply(this,arguments)}}(),!(a=A(t)?t.collections:R(t)?t.products:void 0)){n.next=6;break}return n.next=6,Promise.all(a.map((function(e){return o(e)})));case 6:return n.prev=6,n.next=9,e.delete(t._id);case 9:n.next=15;break;case 11:return n.prev=11,n.t0=n.catch(6),n.next=15,e.patch(t._id).set((c={archived:!0,shopifyId:null},c[r]=[],c)).commit();case 15:return n.abrupt("return",t);case 16:case"end":return n.stop()}}),n,null,[[6,11]])})));return function(e){return n.apply(this,arguments)}}()}(e),h=function(e){return function(){var n=k(x().mark((function n(t){var r;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,e.fetch("*[_type == $type && shopName == $shopName][0]",{type:I,shopName:t});case 2:if(r=n.sent){n.next=5;break}throw new Error('Could not find config document for storefront "'+t+'"');case 5:return n.next=7,e.delete(r._id);case 7:case"end":return n.stop()}}),n)})));return function(e){return n.apply(this,arguments)}}()}(e),y=function(e){return function(){var n=k(x().mark((function n(t,r){var o;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return o=b({_id:"sane-shopify-storefront-config-".concat(t),_type:I},r),n.next=3,e.createIfNotExists(o);case 3:return n.next=5,e.patch(o._id).set(b({},o)).commit();case 5:return n.abrupt("return",n.sent);case 7:case"end":return n.stop()}}),n)})));return function(e,t){return n.apply(this,arguments)}}()}(e),m=function(e){return function(){var n=k(x().mark((function n(t){var r;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.next=2,e.fetch("*[_type == $type && shopName == $shopName][0]",{type:I,shopName:t});case 2:if(r=n.sent){n.next=5;break}throw new Error('Could not find config document for storefront "'+t+'"');case 5:return n.abrupt("return",r);case 6:case"end":return n.stop()}}),n)})));return function(e){return n.apply(this,arguments)}}()}(e);return{fetchAllSanityDocuments:i,syncSanityDocument:u,syncRelationships:f,removeRelationships:d,fetchRelatedDocs:s,documentByShopifyId:function(){var n=k(x().mark((function n(t){var r,o;return x().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(!(r=c.getByShopifyId(t))){n.next=3;break}return n.abrupt("return",r);case 3:return n.next=5,e.fetch('*[shopifyId == $s