@spiffcommerce/core 26.41.2 → 26.42.1
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/dist/index.d.ts +6 -1
- package/dist/index.js +65 -65
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2120 -2114
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1495,7 +1495,7 @@
|
|
|
1495
1495
|
}
|
|
1496
1496
|
}
|
|
1497
1497
|
}
|
|
1498
|
-
|
|
1498
|
+
`,Qo=w.gql`
|
|
1499
1499
|
${de}
|
|
1500
1500
|
query GetGlobalPropertyState($bundleId: String!) {
|
|
1501
1501
|
globalPropertyState(bundleId: $bundleId) {
|
|
@@ -1505,7 +1505,7 @@
|
|
|
1505
1505
|
}
|
|
1506
1506
|
}
|
|
1507
1507
|
}
|
|
1508
|
-
|
|
1508
|
+
`,No=async r=>(await b.getShadowGraphqlClient().query({query:Qo,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:r}})).data.globalPropertyState,Ro=w.gql`
|
|
1509
1509
|
${Ne}
|
|
1510
1510
|
fragment ProductFields on Product {
|
|
1511
1511
|
id
|
|
@@ -1551,7 +1551,7 @@
|
|
|
1551
1551
|
}
|
|
1552
1552
|
}
|
|
1553
1553
|
`,$a=w.gql`
|
|
1554
|
-
${
|
|
1554
|
+
${Ro}
|
|
1555
1555
|
fragment ProductCollectionProductFields on ProductCollectionProduct {
|
|
1556
1556
|
id
|
|
1557
1557
|
productId
|
|
@@ -1618,7 +1618,7 @@
|
|
|
1618
1618
|
}
|
|
1619
1619
|
}
|
|
1620
1620
|
}
|
|
1621
|
-
`,
|
|
1621
|
+
`,Oo=r=>w.gql`
|
|
1622
1622
|
${de}
|
|
1623
1623
|
${Ae(r)}
|
|
1624
1624
|
query GetBundle($id: String!) {
|
|
@@ -1707,7 +1707,7 @@
|
|
|
1707
1707
|
}
|
|
1708
1708
|
}
|
|
1709
1709
|
}
|
|
1710
|
-
|
|
1710
|
+
`,$o=w.gql`
|
|
1711
1711
|
query GetBundlesForCustomer($id: String!) {
|
|
1712
1712
|
customers(ids: [$id]) {
|
|
1713
1713
|
bundleStakeholders {
|
|
@@ -1736,7 +1736,7 @@
|
|
|
1736
1736
|
}
|
|
1737
1737
|
}
|
|
1738
1738
|
}
|
|
1739
|
-
`,
|
|
1739
|
+
`,Uo=w.gql`
|
|
1740
1740
|
${$a}
|
|
1741
1741
|
query GetProductCollectionProducts($id: String!, $productIds: [String!]) {
|
|
1742
1742
|
productCollections(ids: [$id], productIds: $productIds) {
|
|
@@ -1746,7 +1746,7 @@
|
|
|
1746
1746
|
}
|
|
1747
1747
|
}
|
|
1748
1748
|
}
|
|
1749
|
-
|
|
1749
|
+
`,Lo=w.gql`
|
|
1750
1750
|
query GetProductCollectionForFilteredProducts(
|
|
1751
1751
|
$id: String!
|
|
1752
1752
|
$filters: ProductCollectionProductFilterInput
|
|
@@ -1769,7 +1769,7 @@
|
|
|
1769
1769
|
}
|
|
1770
1770
|
}
|
|
1771
1771
|
}
|
|
1772
|
-
`,
|
|
1772
|
+
`,Vo=w.gql`
|
|
1773
1773
|
${$a}
|
|
1774
1774
|
query GetProductCollectionForProductsFeed(
|
|
1775
1775
|
$id: String!
|
|
@@ -1797,7 +1797,7 @@
|
|
|
1797
1797
|
}
|
|
1798
1798
|
}
|
|
1799
1799
|
}
|
|
1800
|
-
`,
|
|
1800
|
+
`,zo=r=>w.gql`
|
|
1801
1801
|
${Ae(r)}
|
|
1802
1802
|
mutation CreateBundle(
|
|
1803
1803
|
$collectionId: String
|
|
@@ -1826,7 +1826,7 @@
|
|
|
1826
1826
|
}
|
|
1827
1827
|
}
|
|
1828
1828
|
}
|
|
1829
|
-
`,
|
|
1829
|
+
`,Go=r=>w.gql`
|
|
1830
1830
|
${de}
|
|
1831
1831
|
${Ae(r)}
|
|
1832
1832
|
mutation DuplicateBundle(
|
|
@@ -1868,7 +1868,7 @@
|
|
|
1868
1868
|
}
|
|
1869
1869
|
}
|
|
1870
1870
|
}
|
|
1871
|
-
`,
|
|
1871
|
+
`,qo=w.gql`
|
|
1872
1872
|
mutation UpdateBundle(
|
|
1873
1873
|
$id: String!
|
|
1874
1874
|
$name: String
|
|
@@ -1888,19 +1888,19 @@
|
|
|
1888
1888
|
id
|
|
1889
1889
|
}
|
|
1890
1890
|
}
|
|
1891
|
-
`,
|
|
1891
|
+
`,Wo=w.gql`
|
|
1892
1892
|
mutation BundleAddTransaction($id: String!, $transactionId: String!) {
|
|
1893
1893
|
bundleAddTransaction(id: $id, transactionId: $transactionId) {
|
|
1894
1894
|
id
|
|
1895
1895
|
}
|
|
1896
1896
|
}
|
|
1897
|
-
`,
|
|
1897
|
+
`,jo=w.gql`
|
|
1898
1898
|
mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
|
|
1899
1899
|
bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
|
|
1900
1900
|
id
|
|
1901
1901
|
}
|
|
1902
1902
|
}
|
|
1903
|
-
`,
|
|
1903
|
+
`,Ho=w.gql`
|
|
1904
1904
|
mutation BundleRemoveTransaction(
|
|
1905
1905
|
$id: String!
|
|
1906
1906
|
$transactionId: String!
|
|
@@ -1915,7 +1915,7 @@
|
|
|
1915
1915
|
id
|
|
1916
1916
|
}
|
|
1917
1917
|
}
|
|
1918
|
-
`,
|
|
1918
|
+
`,Yo=w.gql`
|
|
1919
1919
|
mutation BundleRemoveTransactions(
|
|
1920
1920
|
$id: String!
|
|
1921
1921
|
$transactionIds: [String!]!
|
|
@@ -1930,7 +1930,7 @@
|
|
|
1930
1930
|
id
|
|
1931
1931
|
}
|
|
1932
1932
|
}
|
|
1933
|
-
`,
|
|
1933
|
+
`,Jo=w.gql`
|
|
1934
1934
|
mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
|
|
1935
1935
|
bundleAddStakeholder(id: $id, details: $details, type: $type) {
|
|
1936
1936
|
id
|
|
@@ -1950,13 +1950,13 @@
|
|
|
1950
1950
|
}
|
|
1951
1951
|
}
|
|
1952
1952
|
}
|
|
1953
|
-
`,
|
|
1953
|
+
`,Ko=w.gql`
|
|
1954
1954
|
mutation BundleAddStakeholder($id: String!, $emailAddress: String!) {
|
|
1955
1955
|
bundleRemoveStakeholder(id: $id, emailAddress: $emailAddress) {
|
|
1956
1956
|
id
|
|
1957
1957
|
}
|
|
1958
1958
|
}
|
|
1959
|
-
`,
|
|
1959
|
+
`,_o=w.gql`
|
|
1960
1960
|
mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
|
|
1961
1961
|
bundleUpdateStakeholders(id: $id, input: $input) {
|
|
1962
1962
|
id
|
|
@@ -1976,13 +1976,13 @@
|
|
|
1976
1976
|
}
|
|
1977
1977
|
}
|
|
1978
1978
|
}
|
|
1979
|
-
`,
|
|
1979
|
+
`,Xo=w.gql`
|
|
1980
1980
|
mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
|
|
1981
1981
|
bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
|
|
1982
1982
|
id
|
|
1983
1983
|
}
|
|
1984
1984
|
}
|
|
1985
|
-
`,
|
|
1985
|
+
`,Zo=r=>w.gql`
|
|
1986
1986
|
${Ae(r)}
|
|
1987
1987
|
mutation BundleAssignProductCollection($id: String!, $productCollectionId: String!) {
|
|
1988
1988
|
bundleAssignProductCollection(id: $id, collectionId: $productCollectionId) {
|
|
@@ -1992,13 +1992,13 @@
|
|
|
1992
1992
|
}
|
|
1993
1993
|
}
|
|
1994
1994
|
}
|
|
1995
|
-
`,
|
|
1995
|
+
`,tl=w.gql`
|
|
1996
1996
|
mutation AssignGlobalPropertyConfiguration($bundleId: String!, $globalPropertyConfigurationId: String!) {
|
|
1997
1997
|
bundleUpdate(id: $bundleId, globalPropertyConfigurationId: $globalPropertyConfigurationId) {
|
|
1998
1998
|
id
|
|
1999
1999
|
}
|
|
2000
2000
|
}
|
|
2001
|
-
`,
|
|
2001
|
+
`,el=r=>w.gql`
|
|
2002
2002
|
query CustomerBundlesFeed($id: String!, $limit: Int!, $offset: Int!, $template: Boolean, $templateStatus: BundleTemplateStatus, $ordered: Boolean) {
|
|
2003
2003
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: $template, templateStatus: $templateStatus, ordered: $ordered) {
|
|
2004
2004
|
items {
|
|
@@ -2032,27 +2032,27 @@
|
|
|
2032
2032
|
total
|
|
2033
2033
|
}
|
|
2034
2034
|
}
|
|
2035
|
-
`,
|
|
2035
|
+
`,al=w.gql`
|
|
2036
2036
|
mutation FinalizeUpdateBundle($bundleId: String!) {
|
|
2037
2037
|
bundleFinalizeUpdate(bundleId: $bundleId)
|
|
2038
2038
|
}
|
|
2039
|
-
`,
|
|
2039
|
+
`,nl=w.gql`
|
|
2040
2040
|
mutation ApproveBundle($id: String!, $note: String, $stakeholderId: String) {
|
|
2041
2041
|
bundleApprove(id: $id, note: $note, stakeholderId: $stakeholderId)
|
|
2042
2042
|
}
|
|
2043
|
-
`,
|
|
2043
|
+
`,rl=w.gql`
|
|
2044
2044
|
mutation RejectBundle($id: String!, $note: String, $stakeholderId: String) {
|
|
2045
2045
|
bundleReject(id: $id, note: $note, stakeholderId: $stakeholderId)
|
|
2046
2046
|
}
|
|
2047
|
-
`,
|
|
2047
|
+
`,il=w.gql`
|
|
2048
2048
|
mutation ApproveTransaction($id: String!, $note: String) {
|
|
2049
2049
|
transactionApprove(id: $id, note: $note)
|
|
2050
2050
|
}
|
|
2051
|
-
`,
|
|
2051
|
+
`,sl=w.gql`
|
|
2052
2052
|
mutation RejectTransaction($id: String!, $note: String) {
|
|
2053
2053
|
transactionReject(id: $id, note: $note)
|
|
2054
2054
|
}
|
|
2055
|
-
`,
|
|
2055
|
+
`,ol=w.gql`
|
|
2056
2056
|
mutation CreateRecipient(
|
|
2057
2057
|
$firstName: String
|
|
2058
2058
|
$lastName: String
|
|
@@ -2080,7 +2080,7 @@
|
|
|
2080
2080
|
id
|
|
2081
2081
|
}
|
|
2082
2082
|
}
|
|
2083
|
-
`,
|
|
2083
|
+
`,ll=w.gql`
|
|
2084
2084
|
mutation UpdateRecipient(
|
|
2085
2085
|
$id: String!
|
|
2086
2086
|
$firstName: String
|
|
@@ -2110,13 +2110,13 @@
|
|
|
2110
2110
|
id
|
|
2111
2111
|
}
|
|
2112
2112
|
}
|
|
2113
|
-
`,
|
|
2113
|
+
`,cl=w.gql`
|
|
2114
2114
|
mutation AtttachRecipient($id: String!, $recipientId: String!) {
|
|
2115
2115
|
transactionAttachRecipient(id: $id, recipientId: $recipientId) {
|
|
2116
2116
|
id
|
|
2117
2117
|
}
|
|
2118
2118
|
}
|
|
2119
|
-
`;var ue=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(ue||{});const ll=1e3;class ln extends Ba{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},ll)})}}class cl{constructor(t,e,a,n,i,s,o,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,C=!1){this.workflowStatePromiseQueue=new ba(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{var S;if(!this.previewService)return;const y=this.getCommandContext().getAllLayouts(),v=(S=this.getLayoutPreviewService())==null?void 0:S.getAll();if(v)for(const[,E]of v)E.render(y)},this.experience=t,this.client=e,this.updateTransaction=o,this.graphQlClient=l,this.commandContext=s,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=n,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.currentAdjustingStepId="",this.renderableContextService=u,this.isReloadedTransaction=p,this.workflow.steps.forEach(y=>{this.stepTags[y.stepName]=y.tags??[]}),C&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(y=>{throw console.error(y),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}async updateRecipient(t,e,a,n,i,s,o,l,c,d){var A,u,h,g,m;if((A=this.transaction.recipient)!=null&&A.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company},await this.graphQlClient().mutate({mutation:sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company}});else{const p=await this.graphQlClient().mutate({mutation:il,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d}});this.transaction.recipient={id:(h=(u=p==null?void 0:p.data)==null?void 0:u.recipientCreate)==null?void 0:h.id,firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d},await this.graphQlClient().mutate({mutation:ol,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:(m=(g=p.data)==null?void 0:g.recipientCreate)==null?void 0:m.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}this.recipientCallbacks.forEach(p=>p(this.transaction.recipient))}async initializeDefaultWorkflowState(t){const e=()=>{var d,A;const o=this.workflow.finalizeStepConfig;if(!o)return;const l=o.lookAtAnimation,c=o.modelAnimation;l&&((d=this.previewService)==null||d.executeCameraAnimation(l)),c&&((A=this.modelContainer)==null||A.executeAnimation(c))};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(o=>{this.storage[o.stepName]=o.storage||{}}),this.allScenes=await ys(t);const n=Ft(this.allScenes,this.stepSelections).map(o=>o.silentSteps).flat(),{stepElements:i,commands:s}=await this.stepElementsForIntroducedSilentSteps(n,!!this.reloadedState);this.commandContext.apply(new $(s),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.transaction.recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=N();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(n=!0,i.set(e,a)):a||(n=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Ft(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===P.Model||s.type===P.Material).forEach(s=>{var c,d,A;if(!((c=s.option)!=null&&c.id)){console.error(`Failed to read option id from step: ${s.stepName}`);return}const o=((d=this.stepSelections[s.stepName])==null?void 0:d.selectedVariants)||[];if(o.length===0)return;const l=o[0];if(s.type===P.Model){if(!this.modelContainer)throw new V("We should always have a model container when injecting a preview!");const u=(A=l.asset)==null?void 0:A.fileLink;if(!u){console.error(`Failed to read model url from variant: ${l.id} for step: ${s.stepName}`);return}const h=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:u,contextService:this.getLayoutPreviewService()},h.replaceProductModel||!1)}else{const u=l.material;if(!u){console.error(`Failed to read material from variant: ${l.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(g=>{if(!this.modelContainer)throw new V("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(g,s.option.id,u)})}}),await a.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!wn(a,this.storage)){this.storage=a;const n=new nn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{var i,s;const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=(s=(i=this.stepSelections[a.stepName])==null?void 0:i.selectedVariants)==null?void 0:s.map(o=>({id:o.id,priceModifier:o.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new ln(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new ln(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new V("Attempted to serialize state before it was initialized.");const e=Bt(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){var e;for(const a of Object.values(t.layouts).map(n=>n.elements).flat())a.type==="illustration"&&(delete a.cachedObjectURL,a.src&&delete a.svg),a.type==="frame"&&((e=a.pattern)==null||delete e.svg);return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((i,s)=>{const o=[...a[s]||[]];return n.forEach(l=>{const c=o.findIndex(d=>d.id===l.id);c>-1&&o.splice(c,1)}),i[s]=o,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(Et(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===P.Model&&!Et(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,A)=>{if(c.type===P.SilentIllustration){const u=await new rn(c,d).trigger();return{step:c,results:u}}else if(c.type===P.ProductOverlay){const u=await new rn(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||o.push(n(c,this.layouts,a));const l=await Promise.all(o);for(const c of l)s.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),s.commands=[...s.commands,...c.results.map(d=>d.command)];return s}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){var e;const t=await b.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!((e=t==null?void 0:t.data)!=null&&e.transactions)||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await b.getShadowGraphqlClient().mutate({mutation:nl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await b.getShadowGraphqlClient().mutate({mutation:rl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new Ct(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){var S;const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((E,B)=>E+B.selectedVariants.map(I=>I.priceModifier||0).reduce((I,x)=>I+x,0),0),this.workflow.steps.forEach(E=>{Et(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1,delete this.stepMetadata[E.stepName],delete this.stepSelections[E.stepName],delete this.storage[E.stepName])});const s=this.allScenes,o=Ft(s,i),l=Ft(s,this.stepSelections),c=o.map(E=>E.silentSteps).flat(),A=l.map(E=>E.silentSteps).flat().filter(E=>!c.some(B=>B.stepName===E.stepName));c.forEach(E=>{Et(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(E=>E.stepName===t);if((m==null?void 0:m.type)===P.Frame){const E=(S=this.getWorkflowExperience().getStepById(m.stepName))==null?void 0:S.frameService;E==null||E.setTargetElements(a.map(B=>B.id))}const p=u.map(E=>new Ct(E.id)),f=new nn(this.constructSerializableWorkflow()),C=[...g,...p,f];C.length>0&&this.commandContext.apply(new $(C),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const y=this.getInvalidModelVariants(),v=this.modelContainer;if(v){const E=y.map(B=>v.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(E)}await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const e=Ft(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case P.DigitalContent:a.push(Ma.init(l,this,this.reloadedState));break;case P.Frame:a.push(ut.init(l,this,this.reloadedState));break;case P.Illustration:a.push(Yt.init(l,this,this.reloadedState));break;case P.Material:a.push(Ta.init(l,this,this.reloadedState));break;case P.Model:a.push(Qa.init(l,this,this.reloadedState));break;case P.Module:this.stepSpecificServices[l.stepName]={module:await Ar(l.data.module)},a.push(Na.init(l,this,this.reloadedState));break;case P.Picture:a.push(Ra.init(l,this,this.reloadedState));break;case P.Question:a.push(Oa.init(l,this,this.reloadedState));break;case P.Shape:a.push(Mt.init(l,this,this.reloadedState));break;case P.Text:a.push(W.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=i.filter(l=>!!l&&!!l.command).map(l=>l.command),o=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);s&&s.length>0&&this.commandContext.apply(new $(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return Es(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{constructor(t){this.variantData=t}getType(){var t;return(t=this.variantData.asset)==null?void 0:t.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){var t,e,a;return(a=(e=(t=this.variantData.asset)==null?void 0:t.versions)==null?void 0:e.find(n=>n.name==="cdn"))==null?void 0:a.link}getAssetResource(){return this.variantData.asset}getThumbnail(){var a,n,i,s;const t=(i=(n=(a=this.variantData.thumbnail)==null?void 0:a.versions)==null?void 0:n.find(o=>o.name==="thumbnail"))==null?void 0:i.link,e=(s=this.variantData.thumbnail)==null?void 0:s.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const ur=class ha{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ha.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!ha.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const e=this.manager.getWorkflowSelections()[this.step.stepName],a=e==null?void 0:e.selections[0];if(a)return new rt(a)}getAvailableVariants(){var e,a;return(((a=(e=this.step.option)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new rt(n))}getAllVariants(){var e;return(((e=this.step.option)==null?void 0:e.variants)||[]).map(a=>new rt(a))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){var a;return(((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.overrideGlobalConfigurations)??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){var n;const a=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.overrideGlobalConfigurations)??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){var e;return((e=this.step.globalPropertyAspectConfigurations)==null?void 0:e.filter(a=>a.globalPropertyConfigurationId===t&&a.aspectName).map(a=>a.aspectName))??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};ur.updateState=new Map;let nt=ur;class hr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Yt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){var o;const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=L(t[0].id,this.manager.getAllLayoutData()).colors,n=(o=this.getCurrentVariant())==null?void 0:o.getAssetResource(),i=n==null?void 0:n.assetConfiguration,s=(i==null?void 0:i.defaultColorVariants)||[];if(s.length!==0){const l={};return s.forEach(c=>{var A;const d=i.channelNumbers.find(u=>u.number===c.channelNumber);if(d){const u=d.id.replace(/\W/g,"");l[c.channelNumber]={browserValue:((A=a[u])==null?void 0:A.browserValue)||""}}}),l}try{return a}catch(l){console.error(l)}}setColor(t,e,a){var l;const n=new Map,i=(l=this.getCurrentVariant())==null?void 0:l.getAssetResource(),s=i==null?void 0:i.assetConfiguration;return((s==null?void 0:s.defaultColorVariants)||[]).length!==0?s.channelNumbers.forEach(c=>{if(c.number.toString()===t){const d=c.id.replace(/\W/g,"");a?n.set(d,{browserValue:e,pmsValue:a}):n.set(d,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Yt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),n)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Yt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class gr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ta.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class mr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Qa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class pr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ra.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class fr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await Oa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){var t;return this.step.data.displayType||((t=this.step.option)==null?void 0:t.displayType)}}class Cr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Mt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Mt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Mt.availableColours(this.step)}setCustomColor(t){var e,a;return((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`),Mt.setCustomColor(t,this.step,this.manager)}getCustomColor(){var e,a,n;((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`);const t=(n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class wr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:ue.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.color)||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){var t;return(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.fillImage}getAlignment(){const t=W.findLayoutElements(this.manager,this.step);return t==null?void 0:t[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){var s;const e=((s=this.manager.getStepStorage(this.step.stepName))==null?void 0:s.inputText)||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){var d;const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,(d=a[0])==null?void 0:d.fontData),i=!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength;i||(e.input=n);const s=a.length<=0,o=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,o);const l=this.manager.getStepStorage(this.step.stepName),c=W.getProcessedInput(n,this.step.data,!!l.customiseAllText);if(s)i||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:A,errorData:u,helperData:h}=W.updateInputText(n,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!i&&!u&&this.manager.updateMetadata(this.step.stepName,{text:c})}return e}getText(){var a;const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&(e==null?void 0:e.defaultCleared)!==void 0&&!(e!=null&&e.defaultCleared)?t:((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.text)||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){const t=this.manager.getStepStorage(this.step.stepName);if(!(t!=null&&t.defaultCleared)&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){var t,e;return((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.strokeColor)==null?void 0:e.browserValue)||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}}class yr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Sr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.videoUrl)||""}async selectVideo(t){return Ma.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class vr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.text)||""}setText(t){Na.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:ue.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class pe{static get(t,e){switch(e.type){case P.DigitalContent:return new Sr(t,e,t.getStepTags(e.stepName));case P.Information:return new yr(t,e,t.getStepTags(e.stepName));case P.Question:return new fr(t,e,t.getStepTags(e.stepName));case P.Text:return new wr(t,e,t.getStepTags(e.stepName));case P.Illustration:return new hr(t,e,t.getStepTags(e.stepName));case P.Picture:return new pr(t,e,t.getStepTags(e.stepName));case P.Shape:return new Cr(t,e,t.getStepTags(e.stepName));case P.Material:return new gr(t,e,t.getStepTags(e.stepName));case P.Model:return new mr(t,e,t.getStepTags(e.stepName));case P.Frame:return new Gr(t,e,t.getStepTags(e.stepName));case P.Module:return new vr(t,e,t.getStepTags(e.stepName));default:throw new V(`Step type ${e.type} not yet supported in Core SDK`)}}}const Er=w.gql`
|
|
2119
|
+
`;var ue=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(ue||{});const dl=1e3;class ln extends Ba{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},dl)})}}class Al{constructor(t,e,a,n,i,s,o,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,C=!1){this.workflowStatePromiseQueue=new ba(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{var S;if(!this.previewService)return;const y=this.getCommandContext().getAllLayouts(),v=(S=this.getLayoutPreviewService())==null?void 0:S.getAll();if(v)for(const[,E]of v)E.render(y)},this.experience=t,this.client=e,this.updateTransaction=o,this.graphQlClient=l,this.commandContext=s,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=n,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.currentAdjustingStepId="",this.renderableContextService=u,this.isReloadedTransaction=p,this.workflow.steps.forEach(y=>{this.stepTags[y.stepName]=y.tags??[]}),C&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(y=>{throw console.error(y),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}async updateRecipient(t,e,a,n,i,s,o,l,c,d){var A,u,h,g,m;if((A=this.transaction.recipient)!=null&&A.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company},await this.graphQlClient().mutate({mutation:ll,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company}});else{const p=await this.graphQlClient().mutate({mutation:ol,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d}});this.transaction.recipient={id:(h=(u=p==null?void 0:p.data)==null?void 0:u.recipientCreate)==null?void 0:h.id,firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d},await this.graphQlClient().mutate({mutation:cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:(m=(g=p.data)==null?void 0:g.recipientCreate)==null?void 0:m.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}this.recipientCallbacks.forEach(p=>p(this.transaction.recipient))}async initializeDefaultWorkflowState(t){const e=()=>{var d,A;const o=this.workflow.finalizeStepConfig;if(!o)return;const l=o.lookAtAnimation,c=o.modelAnimation;l&&((d=this.previewService)==null||d.executeCameraAnimation(l)),c&&((A=this.modelContainer)==null||A.executeAnimation(c))};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(o=>{this.storage[o.stepName]=o.storage||{}}),this.allScenes=await ys(t);const n=Ft(this.allScenes,this.stepSelections).map(o=>o.silentSteps).flat(),{stepElements:i,commands:s}=await this.stepElementsForIntroducedSilentSteps(n,!!this.reloadedState);this.commandContext.apply(new $(s),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.transaction.recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=N();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(n=!0,i.set(e,a)):a||(n=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Ft(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===P.Model||s.type===P.Material).forEach(s=>{var c,d,A;if(!((c=s.option)!=null&&c.id)){console.error(`Failed to read option id from step: ${s.stepName}`);return}const o=((d=this.stepSelections[s.stepName])==null?void 0:d.selectedVariants)||[];if(o.length===0)return;const l=o[0];if(s.type===P.Model){if(!this.modelContainer)throw new V("We should always have a model container when injecting a preview!");const u=(A=l.asset)==null?void 0:A.fileLink;if(!u){console.error(`Failed to read model url from variant: ${l.id} for step: ${s.stepName}`);return}const h=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:u,contextService:this.getLayoutPreviewService()},h.replaceProductModel||!1)}else{const u=l.material;if(!u){console.error(`Failed to read material from variant: ${l.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(g=>{if(!this.modelContainer)throw new V("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(g,s.option.id,u)})}}),await a.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!wn(a,this.storage)){this.storage=a;const n=new nn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{var i,s;const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=(s=(i=this.stepSelections[a.stepName])==null?void 0:i.selectedVariants)==null?void 0:s.map(o=>({id:o.id,priceModifier:o.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new ln(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new ln(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new V("Attempted to serialize state before it was initialized.");const e=Bt(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){var e;for(const a of Object.values(t.layouts).map(n=>n.elements).flat())a.type==="illustration"&&(delete a.cachedObjectURL,a.src&&delete a.svg),a.type==="frame"&&((e=a.pattern)==null||delete e.svg);return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((i,s)=>{const o=[...a[s]||[]];return n.forEach(l=>{const c=o.findIndex(d=>d.id===l.id);c>-1&&o.splice(c,1)}),i[s]=o,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(Et(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===P.Model&&!Et(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,A)=>{if(c.type===P.SilentIllustration){const u=await new rn(c,d).trigger();return{step:c,results:u}}else if(c.type===P.ProductOverlay){const u=await new rn(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||o.push(n(c,this.layouts,a));const l=await Promise.all(o);for(const c of l)s.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),s.commands=[...s.commands,...c.results.map(d=>d.command)];return s}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){var e;const t=await b.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!((e=t==null?void 0:t.data)!=null&&e.transactions)||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await b.getShadowGraphqlClient().mutate({mutation:il,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await b.getShadowGraphqlClient().mutate({mutation:sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new Ct(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){var S;const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((E,B)=>E+B.selectedVariants.map(I=>I.priceModifier||0).reduce((I,x)=>I+x,0),0),this.workflow.steps.forEach(E=>{Et(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1,delete this.stepMetadata[E.stepName],delete this.stepSelections[E.stepName],delete this.storage[E.stepName])});const s=this.allScenes,o=Ft(s,i),l=Ft(s,this.stepSelections),c=o.map(E=>E.silentSteps).flat(),A=l.map(E=>E.silentSteps).flat().filter(E=>!c.some(B=>B.stepName===E.stepName));c.forEach(E=>{Et(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(E=>E.stepName===t);if((m==null?void 0:m.type)===P.Frame){const E=(S=this.getWorkflowExperience().getStepById(m.stepName))==null?void 0:S.frameService;E==null||E.setTargetElements(a.map(B=>B.id))}const p=u.map(E=>new Ct(E.id)),f=new nn(this.constructSerializableWorkflow()),C=[...g,...p,f];C.length>0&&this.commandContext.apply(new $(C),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const y=this.getInvalidModelVariants(),v=this.modelContainer;if(v){const E=y.map(B=>v.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(E)}await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const e=Ft(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case P.DigitalContent:a.push(Ma.init(l,this,this.reloadedState));break;case P.Frame:a.push(ut.init(l,this,this.reloadedState));break;case P.Illustration:a.push(Yt.init(l,this,this.reloadedState));break;case P.Material:a.push(Ta.init(l,this,this.reloadedState));break;case P.Model:a.push(Qa.init(l,this,this.reloadedState));break;case P.Module:this.stepSpecificServices[l.stepName]={module:await Ar(l.data.module)},a.push(Na.init(l,this,this.reloadedState));break;case P.Picture:a.push(Ra.init(l,this,this.reloadedState));break;case P.Question:a.push(Oa.init(l,this,this.reloadedState));break;case P.Shape:a.push(Mt.init(l,this,this.reloadedState));break;case P.Text:a.push(W.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=i.filter(l=>!!l&&!!l.command).map(l=>l.command),o=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);s&&s.length>0&&this.commandContext.apply(new $(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return Es(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{constructor(t){this.variantData=t}getType(){var t;return(t=this.variantData.asset)==null?void 0:t.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){var t,e,a;return(a=(e=(t=this.variantData.asset)==null?void 0:t.versions)==null?void 0:e.find(n=>n.name==="cdn"))==null?void 0:a.link}getAssetResource(){return this.variantData.asset}getThumbnail(){var a,n,i,s;const t=(i=(n=(a=this.variantData.thumbnail)==null?void 0:a.versions)==null?void 0:n.find(o=>o.name==="thumbnail"))==null?void 0:i.link,e=(s=this.variantData.thumbnail)==null?void 0:s.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const ur=class ha{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ha.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!ha.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const e=this.manager.getWorkflowSelections()[this.step.stepName],a=e==null?void 0:e.selections[0];if(a)return new rt(a)}getAvailableVariants(){var e,a;return(((a=(e=this.step.option)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new rt(n))}getAllVariants(){var e;return(((e=this.step.option)==null?void 0:e.variants)||[]).map(a=>new rt(a))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){var a;return(((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.overrideGlobalConfigurations)??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){var n;const a=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.overrideGlobalConfigurations)??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){var e;return((e=this.step.globalPropertyAspectConfigurations)==null?void 0:e.filter(a=>a.globalPropertyConfigurationId===t&&a.aspectName).map(a=>a.aspectName))??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};ur.updateState=new Map;let nt=ur;class hr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Yt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){var o;const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=L(t[0].id,this.manager.getAllLayoutData()).colors,n=(o=this.getCurrentVariant())==null?void 0:o.getAssetResource(),i=n==null?void 0:n.assetConfiguration,s=(i==null?void 0:i.defaultColorVariants)||[];if(s.length!==0){const l={};return s.forEach(c=>{var A;const d=i.channelNumbers.find(u=>u.number===c.channelNumber);if(d){const u=d.id.replace(/\W/g,"");l[c.channelNumber]={browserValue:((A=a[u])==null?void 0:A.browserValue)||""}}}),l}try{return a}catch(l){console.error(l)}}setColor(t,e,a){var l;const n=new Map,i=(l=this.getCurrentVariant())==null?void 0:l.getAssetResource(),s=i==null?void 0:i.assetConfiguration;return((s==null?void 0:s.defaultColorVariants)||[]).length!==0?s.channelNumbers.forEach(c=>{if(c.number.toString()===t){const d=c.id.replace(/\W/g,"");a?n.set(d,{browserValue:e,pmsValue:a}):n.set(d,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Yt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),n)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Yt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class gr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ta.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class mr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Qa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class pr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ra.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class fr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await Oa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){var t;return this.step.data.displayType||((t=this.step.option)==null?void 0:t.displayType)}}class Cr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Mt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Mt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Mt.availableColours(this.step)}setCustomColor(t){var e,a;return((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`),Mt.setCustomColor(t,this.step,this.manager)}getCustomColor(){var e,a,n;((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`);const t=(n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class wr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:ue.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.color)||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){var t;return(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.fillImage}getAlignment(){const t=W.findLayoutElements(this.manager,this.step);return t==null?void 0:t[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){var s;const e=((s=this.manager.getStepStorage(this.step.stepName))==null?void 0:s.inputText)||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){var d;const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,(d=a[0])==null?void 0:d.fontData),i=!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength;i||(e.input=n);const s=a.length<=0,o=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,o);const l=this.manager.getStepStorage(this.step.stepName),c=W.getProcessedInput(n,this.step.data,!!l.customiseAllText);if(s)i||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:A,errorData:u,helperData:h}=W.updateInputText(n,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!i&&!u&&this.manager.updateMetadata(this.step.stepName,{text:c})}return e}getText(){var a;const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&(e==null?void 0:e.defaultCleared)!==void 0&&!(e!=null&&e.defaultCleared)?t:((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.text)||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){const t=this.manager.getStepStorage(this.step.stepName);if(!(t!=null&&t.defaultCleared)&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){var t,e;return((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.strokeColor)==null?void 0:e.browserValue)||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}}class yr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Sr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.videoUrl)||""}async selectVideo(t){return Ma.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class vr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.text)||""}setText(t){Na.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:ue.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class pe{static get(t,e){switch(e.type){case P.DigitalContent:return new Sr(t,e,t.getStepTags(e.stepName));case P.Information:return new yr(t,e,t.getStepTags(e.stepName));case P.Question:return new fr(t,e,t.getStepTags(e.stepName));case P.Text:return new wr(t,e,t.getStepTags(e.stepName));case P.Illustration:return new hr(t,e,t.getStepTags(e.stepName));case P.Picture:return new pr(t,e,t.getStepTags(e.stepName));case P.Shape:return new Cr(t,e,t.getStepTags(e.stepName));case P.Material:return new gr(t,e,t.getStepTags(e.stepName));case P.Model:return new mr(t,e,t.getStepTags(e.stepName));case P.Frame:return new Gr(t,e,t.getStepTags(e.stepName));case P.Module:return new vr(t,e,t.getStepTags(e.stepName));default:throw new V(`Step type ${e.type} not yet supported in Core SDK`)}}}const Er=w.gql`
|
|
2120
2120
|
fragment CreateDesignTransaction on Transaction {
|
|
2121
2121
|
id
|
|
2122
2122
|
designName
|
|
@@ -2141,7 +2141,7 @@
|
|
|
2141
2141
|
externalProductVariantId
|
|
2142
2142
|
}
|
|
2143
2143
|
}
|
|
2144
|
-
`,
|
|
2144
|
+
`,ul=w.gql`
|
|
2145
2145
|
${Er}
|
|
2146
2146
|
mutation CreateDesign(
|
|
2147
2147
|
$name: String!
|
|
@@ -2173,7 +2173,7 @@
|
|
|
2173
2173
|
}
|
|
2174
2174
|
}
|
|
2175
2175
|
}
|
|
2176
|
-
`,
|
|
2176
|
+
`,hl=w.gql`
|
|
2177
2177
|
${Er}
|
|
2178
2178
|
mutation CreateDesigns($inputs: [DesignCreateInput]!) {
|
|
2179
2179
|
designCreateMany(inputs: $inputs) {
|
|
@@ -2187,7 +2187,7 @@
|
|
|
2187
2187
|
}
|
|
2188
2188
|
}
|
|
2189
2189
|
}
|
|
2190
|
-
`;function Ie(r){const t=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const
|
|
2190
|
+
`;function Ie(r){const t=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const gl=async r=>{var s,o;const e=((s=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken")))==null?void 0:s[0])||"",a=localStorage.getItem(e),n={};return a&&!Ie(a)&&(n.Authorization=`Bearer ${a}`),(o=(await b.getShadowGraphqlClient().mutate({mutation:ul,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants},context:{headers:n}})).data)==null?void 0:o.designCreate},ml=async r=>{var s,o;const e=((s=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken")))==null?void 0:s[0])||"",a=localStorage.getItem(e),n={};return a&&!Ie(a)&&(n.Authorization=`Bearer ${a}`),(o=(await b.getShadowGraphqlClient().mutate({mutation:hl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(l=>({name:l.name,layouts:l.layouts,workflowId:l.workflowId,transactionId:l.transactionId,previewImage:l.previewImage,useThreeDimPreview:l.useThreeDimPreview,metadata:l.metadata,selectedVariants:l.selectedVariants}))},context:{headers:n}})).data)==null?void 0:o.designCreateMany},ga=(r,t,e)=>{const a=i=>{const s={};if(i.type==="Frame"){const o=r[i.stepName],l=i.data;if(!o||!o.image||l.hideImageInCart&&e)return s;s[`${i.stepTitle} image`]=o.image}if(i.type==="Illustration"){const o=r[i.stepName],l=i.data;if(!o||l.hideColorsInCart&&e||!o.colors)return s;if(o.colors.length>0){const c=o.colors.join(", ").toUpperCase();s[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const o=r[i.stepName],l=i.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&e)return s;s[`${i.stepTitle} text`]=o.text}if(i.type==="Text"){const o=r[i.stepName];if(!o)return s;const l=i.data;(!l.hideTextInCart||!e&&o.text!==void 0&&o.text!==null)&&(s[`${i.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!e)&&(s[`${i.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!e)&&(s[`${i.stepTitle} stroke`]=o.strokeColor)}return s},n={};return t.steps.forEach(i=>{Object.assign(n,a(i))}),n},pl=(r,t,e,a)=>{const n={};let i={};e?i=ga(e,t,!1):a&&(i=a);const o=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of o){if(Object.keys(r).includes(l)){const c=r[l],d=t.steps.find(A=>A.stepTitle===l);n[`${d==null?void 0:d.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:i[c],priceModifier:0})}return n},Br=(r,t,e,a,n,i,s,o)=>{var g,m;const l=t.basePrice||0,c=r.priceModifierTotal||0,d=pl(a,e,void 0,i),u=(M.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:(g=r.integrationProduct)==null?void 0:g.additionalExternalProductId,additionalExternalVariantId:(m=r.integrationProduct)==null?void 0:m.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:c,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),n&&(h.sku=n),h},br=async(r,t,e,a,n,i,s,o,l,c)=>{var I;await(async()=>{var R;if(c!==void 0)return c;await r.outstandingRequestsPromise();const F=(M.getMap("transactionOwnerIds")||new Map).get(n.id),Q=await b.getShadowGraphqlClient().query({query:Hn,variables:{ids:[n.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:F}}),ot=(R=Q.data)==null?void 0:R.transactions[0].workflowState;return Q.errors?(Q.errors.forEach(et=>{Q.errors&&console.log("Server Error:",et.message)}),null):ot??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await r.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=r.getPreviewService(),h=(I=t==null?void 0:t.finalizeStepConfig)==null?void 0:I.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&ga(l,t,!0),p=l&&ga(l,t,!1),f=async x=>{const F={};let k=0;if(Object.keys(i).length>0)for(const Q of Object.keys(i)){const ot=i[Q],R=t.steps.find(et=>et.stepName===Q);for(let et=0;et<ot.selections.length;++et){const H=ot.selections[et];if(R&&(!x||R.option&&(R.option.variants||[]).length>1&&!R.data.hideSelectionInCart&&!R.data.hideSelectionsInCart)){const yt=R.stepTitle;F[yt]?F[yt].push({id:H.id||"",name:H.name,priceModifier:H.priceModifier}):F[yt]=[{id:H.id||"",name:H.name,priceModifier:H.priceModifier}]}k+=H.priceModifier}}return[F,k]},[C]=await f(!0),y=Object.fromEntries(Object.keys(C).map(x=>[x,C[x].map(F=>F.id)])),[v]=await f(!1),S=Object.fromEntries(Object.keys(v).map(x=>[x,v[x].map(F=>F.id)]));let E=await o(g,n.id);if(E){const x=await(await it(E)).blob();E=(await U.uploadAsset({name:`${n.id}-preview-image.png`,blob:x},Kt.Image,!0,!1)).fileLink}return{designDetails:(()=>{const x={name:s,layouts:e.map(F=>({index:F.index,panelId:F.panelId})),workflowId:t.id,transactionId:n.id,useThreeDimPreview:!!g,previewImage:E};if(p){const F=[];for(const[k,Q]of Object.entries(p))F.push({key:k,value:Q});x.metadata=F}if(y){const F=[];for(const[k,Q]of Object.entries(S))F.push({key:k,ids:Q});x.selectedVariants=F}return x})(),cartSelectionsWithPrices:C,cartMetadata:m}},Ir=async(r,t,e,a,n,i,s,o,l,c,d)=>{var f,C;l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await br(r,t,e,a,i,s,o,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await gl(A),m=(f=g==null?void 0:g.transaction)==null?void 0:f.previewImageLink;if(!(g!=null&&g.transaction))throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const p=g.transaction;return Br(p,n,t,u,g==null?void 0:g.sku,h,m,(C=g==null?void 0:g.processExecution)==null?void 0:C.id)},fl=async(r,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(r.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const n=await(async()=>{var c;const l=await b.getShadowGraphqlClient().query({query:Hn,variables:{ids:r.map(d=>d.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(d=>{l.errors&&console.log("Server Error:",d.message)}),null):(c=l.data)!=null&&c.transactions?l.data.transactions.map(d=>d.workflowState??null):null})(),i=await Promise.all(r.map(async(o,l)=>await br(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,e??(()=>Promise.resolve(void 0)),o.workflowMetadata,n?n[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const s=await ml(i.map(o=>o.designDetails));if(!s)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),s.map((o,l)=>{var u;const c=r[l],d=i[l],A=o.transaction;return Br(A,c.product,c.workflow,d.cartSelectionsWithPrices,o.sku,d.cartMetadata,A.previewImageLink,(u=o.processExecution)==null?void 0:u.id)})};class Cl{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=M.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new V("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(n=>n.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(n=>n(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),n=a.find(i=>i.transactionId===t);if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){M.set(this.localPersistenceKey,JSON.stringify(t));return}throw new V("Unexpected storage method requested")}}const we=new Cl,wl=w.gql`
|
|
2191
2191
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
2192
2192
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
2193
2193
|
id
|
|
@@ -2201,7 +2201,7 @@
|
|
|
2201
2201
|
}
|
|
2202
2202
|
}
|
|
2203
2203
|
}
|
|
2204
|
-
`,
|
|
2204
|
+
`,yl=w.gql`
|
|
2205
2205
|
mutation AddAddressToTransaction(
|
|
2206
2206
|
$transactionId: String!
|
|
2207
2207
|
$streetAddress: String
|
|
@@ -2223,13 +2223,13 @@
|
|
|
2223
2223
|
id
|
|
2224
2224
|
}
|
|
2225
2225
|
}
|
|
2226
|
-
`,
|
|
2226
|
+
`,Sl=w.gql`
|
|
2227
2227
|
mutation AddOrganizationToTransaction($transactionId: String!, $organizationName: String!) {
|
|
2228
2228
|
organizationAttachToTransaction(transactionId: $transactionId, organizationName: $organizationName) {
|
|
2229
2229
|
id
|
|
2230
2230
|
}
|
|
2231
2231
|
}
|
|
2232
|
-
`;var Pr=(r=>(r.QuantityChanged="QuantityChanged",r.PriceBreakChanged="PriceBreakChanged",r))(Pr||{});class Dr{constructor(t,e){var n;if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=yn(async()=>{await we.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async i=>new Promise((s,o)=>{try{i.toBlob(l=>{if(l){const c=URL.createObjectURL(l);s(c)}})}catch(l){o(l)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new tr,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new cl(this,t,e.workflow,((n=e.product.profanities)==null?void 0:n.map(i=>i.word))||[],a,this.commandContext,i=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(i)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(i=>{const s=i.traversableScenes.map(o=>{const l=o.renderableSteps.map(c=>c.stepName);return{id:o.name,title:o.title,renderableSteps:l,workflowScene:o}});this.renderableScenes=s,this.renderableSceneCallbacks.forEach(o=>o(s))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,n,i,s){await this.graphQlClient().mutate({mutation:Cl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:wl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){var C,y;const a=this.workflowManager.getWorkflow(),n=(C=a==null?void 0:a.finalizeStepConfig)==null?void 0:C.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await((y=this.workflowManager.getPreviewService())==null?void 0:y.renderSceneScreenshot(e??512,n))||""}let i=2048;e&&e<=2048&&(i=e);const s=pt(i,i),o=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=o.find(v=>{var S;return((S=v.layoutState)==null?void 0:S.layout.panelId)===(c==null?void 0:c.name)})||o[0],A=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new xe("Failed to obtain 2D context for preview image creation");const g=Oe(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Qt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height}}}),m=Fn(g);await(await Ca.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:pt,createImage:re,DOMParser:Sa(),fetch})).render();const f=await this.getCanvasObjectURLAsync(s);return s.toDataURL(f)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=pe.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Et(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((i,s)=>i+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){var a;const e=this.getWorkflowManager().getTransaction().integrationProduct;if((a=e==null?void 0:e.additionalIntegrationProduct)!=null&&a.product){const n=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((n,i)=>-(n.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,i)=>n+i.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){var t;return(((t=this.bundle)==null?void 0:t.getWorkflowExperiences())||[]).filter(e=>e.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&e.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),i=a==null?void 0:a.map(c=>c.getId()),s=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),o=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);s.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),o.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&(m==null?void 0:m.getType())==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&(m==null?void 0:m.getType())==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return pe.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>pe.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(a=>this.getWorkflowManager().getWorkflow().steps.find(n=>n.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>pe.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){var n,i,s;const a=(s=(i=(n=(await b.getShadowGraphqlClient().mutate({mutation:fl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data)==null?void 0:n.transactionAddStakeholder)==null?void 0:i.stakeholders)==null?void 0:s.find(o=>{var l;return((l=o.customer)==null?void 0:l.emailAddress)===t.emailAddress});if(a!=null&&a.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const o=M.getMap("transactionCustomerIds")||new Map;o.set(this.getWorkflowManager().getTransaction().id,a.customer.id),M.setMap("transactionCustomerIds",o)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new V("State undefined!");const n={title:await(async()=>{var l;if(t)return t;const i=this.getWorkflowManager().getTransaction().id,o=(l=(await we.getSavedDesigns()).find(c=>c.transactionId===i))==null?void 0:l.title;return o||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await we.addDesign(n),n}async copy(){var s;const t=Bt(this.getCommandContext().getState());if(!t)throw new V("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),n=(s=this.getWorkflowManager().getTransaction().integrationProduct)==null?void 0:s.id;if(!n)throw new V("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:os,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Ir(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),n=>e?this.createPreviewImage(n,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==P.SilentIllustration&&t.type!==P.ProductOverlay}getExportedData(){var n;const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach(i=>{const s=this.workflowManager.getWorkflow().steps.find(l=>l.stepName===i);if(!s)return;t.has(s.stepTitle)||t.set(s.stepTitle,{});const o=e[i];Object.keys(o).forEach(l=>{t.get(s.stepTitle)[l]=o[l]})}),(n=Object.keys(a))==null||n.forEach(i=>{const s=this.workflowManager.getWorkflow().steps.find(o=>o.stepName===i);s&&(t.has(s.stepTitle)||t.set(s.stepTitle,{}),t.get(s.stepTitle).selection=a[i].selections[0].name)}),t}getQuantity(){return this.getWorkflowManager().getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:es,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const yl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Sl=async(r,t,e)=>{const a=t.data,n=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),s=n.slice(0,4)==="http"?"":"https://",o=new URL(s+n);o.searchParams.append("video",Ka(JSON.stringify([{href:i}]))),o.pathname=o.pathname+(o.pathname.slice(-1)==="/"?"":"/");const l=o.toString(),d=`data:image/svg+xml;base64,${Ka(await Cn.toString(l,{type:"svg"}))}`,A=h=>{const g=r.find(p=>p.panelId===h.panelId);if(!g)throw new j(h);const m=N();return new G({id:m,src:d,type:T.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},vl=async(r,t,e,a)=>{const n=e.data,i=n.assetUrl,s=await ca(i);try{const o=Xs(n,a.option);o&&(t[a.stepName]={selectedVariants:[o]});const l=async c=>{var m;const d=await ar(c,(m=o==null?void 0:o.asset)==null?void 0:m.fileLink),A=await ce(d),u=N(),h=r.find(p=>p.panelId===c.panelId);if(!h)throw new j(c);const g=Da(s,A,{scale:n.scale,left:n.x,top:n.y},a.data.forceImageCover);return[new G({id:u,path:A.path,type:T.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:s.src,x:g.x,y:g.y,width:s.width,height:s.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:s.svg,colors:s.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(o){return console.error(o),[]}},El=async(r,t,e,a)=>{var S,E;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((S=i.variants)==null?void 0:S.find(B=>B.id===n.illustrationVariantId))||le(i);if(!s)return console.error(`No variant with ID: ${n.illustrationVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(E=s.asset)==null?void 0:E.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.illustrationVariantId}`),[];const l=await tt(o,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=(d==null?void 0:d.length)>0?d[0]:"",g=ct().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Te(g);const m={};Ot(g,B=>{yl.includes(B.tagName)&&!B.attributes.getNamedItem("fill")&&B.setAttribute("fill","#000000");const I=B.attributes.getNamedItem("fill");if(I&&I.value!=="none"){const F=I.value,Q=`spiff-fill-${F.replace(/\W/g,"")}`;B.classList.add(Q),m[Q]={browserValue:F}}const x=B.attributes.getNamedItem("stroke");if(x&&x.value!=="none"){const F=x.value,Q=`spiff-stroke-${F.replace(/\W/g,"")}`;B.classList.add(Q),m[Q]={browserValue:F}}});const f=wt().serializeToString(g),C=n.colors;if(C){for(const[B,I]of Object.entries(m))for(const x of Object.keys(C))if(I.browserValue===x){m[B]={browserValue:C[x]};break}}const y=B=>{const I=r.find(F=>F.panelId===B.panelId);if(!I)throw new j(B);const x=N();return new G({colors:m,id:x,svg:f,type:T.Illustration,y:B.top,x:B.left,rotation:B.rotation,width:B.width,height:B.height,layer:B.layer,layerIndex:B.layerIndex,immutable:B.immutable},I)},v=a.data.regions;try{return v.map(y)}catch(B){return console.error(B),[]}},Bl=async(r,t,e)=>{const a=await Ar(e.data.module),n=t.data,i=(o,l)=>{const c=r.find(A=>A.panelId===l.panelId);if(!c)throw new j(l);const d=N();return new G({colors:{},id:d,svg:o,type:T.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},s=e.data.regions;try{return s.map(o=>i(a.svgPrint(n.text,o),o))}catch(o){return console.error(o),[]}},bl=async(r,t,e,a)=>{var d,A;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((d=i.variants)==null?void 0:d.find(u=>u.id===n.pictureVariantId))||le(i);if(!s)return console.error(`No variant with ID: ${n.pictureVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(A=s.asset)==null?void 0:A.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.pictureVariantId}`),[];const l=u=>{const h=r.find(m=>m.panelId===u.panelId);if(!h)throw new j(u);const g=N();return new G({id:g,src:o,type:T.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},h)},c=a.data.regions;try{return c.map(l)}catch(u){return console.error(u),[]}},Il=async(r,t,e,a)=>{var c;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((c=i.variants)==null?void 0:c.find(d=>d.id===n.colorVariantId))||le(i);if(!s)return console.error(`No variant with ID: ${n.colorVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=d=>{const A=r.find(p=>p.panelId===d.panelId);if(!A)throw new j(d);const u=`
|
|
2232
|
+
`;var Pr=(r=>(r.QuantityChanged="QuantityChanged",r.PriceBreakChanged="PriceBreakChanged",r))(Pr||{});class Dr{constructor(t,e){var n;if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=yn(async()=>{await we.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async i=>new Promise((s,o)=>{try{i.toBlob(l=>{if(l){const c=URL.createObjectURL(l);s(c)}})}catch(l){o(l)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new tr,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Al(this,t,e.workflow,((n=e.product.profanities)==null?void 0:n.map(i=>i.word))||[],a,this.commandContext,i=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(i)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(i=>{const s=i.traversableScenes.map(o=>{const l=o.renderableSteps.map(c=>c.stepName);return{id:o.name,title:o.title,renderableSteps:l,workflowScene:o}});this.renderableScenes=s,this.renderableSceneCallbacks.forEach(o=>o(s))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,n,i,s){await this.graphQlClient().mutate({mutation:yl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Sl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){var C,y;const a=this.workflowManager.getWorkflow(),n=(C=a==null?void 0:a.finalizeStepConfig)==null?void 0:C.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await((y=this.workflowManager.getPreviewService())==null?void 0:y.renderSceneScreenshot(e??512,n))||""}let i=2048;e&&e<=2048&&(i=e);const s=pt(i,i),o=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=o.find(v=>{var S;return((S=v.layoutState)==null?void 0:S.layout.panelId)===(c==null?void 0:c.name)})||o[0],A=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new xe("Failed to obtain 2D context for preview image creation");const g=Oe(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Qt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height}}}),m=Fn(g);await(await Ca.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:pt,createImage:re,DOMParser:Sa(),fetch})).render();const f=await this.getCanvasObjectURLAsync(s);return s.toDataURL(f)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=pe.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Et(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((i,s)=>i+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){var a;const e=this.getWorkflowManager().getTransaction().integrationProduct;if((a=e==null?void 0:e.additionalIntegrationProduct)!=null&&a.product){const n=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((n,i)=>-(n.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,i)=>n+i.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){var t;return(((t=this.bundle)==null?void 0:t.getWorkflowExperiences())||[]).filter(e=>e.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&e.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),i=a==null?void 0:a.map(c=>c.getId()),s=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),o=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);s.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),o.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&(m==null?void 0:m.getType())==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&(m==null?void 0:m.getType())==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return pe.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>pe.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(a=>this.getWorkflowManager().getWorkflow().steps.find(n=>n.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>pe.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){var n,i,s;const a=(s=(i=(n=(await b.getShadowGraphqlClient().mutate({mutation:wl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data)==null?void 0:n.transactionAddStakeholder)==null?void 0:i.stakeholders)==null?void 0:s.find(o=>{var l;return((l=o.customer)==null?void 0:l.emailAddress)===t.emailAddress});if(a!=null&&a.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const o=M.getMap("transactionCustomerIds")||new Map;o.set(this.getWorkflowManager().getTransaction().id,a.customer.id),M.setMap("transactionCustomerIds",o)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new V("State undefined!");const n={title:await(async()=>{var l;if(t)return t;const i=this.getWorkflowManager().getTransaction().id,o=(l=(await we.getSavedDesigns()).find(c=>c.transactionId===i))==null?void 0:l.title;return o||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await we.addDesign(n),n}async copy(){var s;const t=Bt(this.getCommandContext().getState());if(!t)throw new V("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),n=(s=this.getWorkflowManager().getTransaction().integrationProduct)==null?void 0:s.id;if(!n)throw new V("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:os,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Ir(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),n=>e?this.createPreviewImage(n,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==P.SilentIllustration&&t.type!==P.ProductOverlay}getExportedData(){var n;const t=new Map,e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections();return Object.keys(e).forEach(i=>{const s=this.workflowManager.getWorkflow().steps.find(l=>l.stepName===i);if(!s)return;t.has(s.stepTitle)||t.set(s.stepTitle,{});const o=e[i];Object.keys(o).forEach(l=>{t.get(s.stepTitle)[l]=o[l]})}),(n=Object.keys(a))==null||n.forEach(i=>{const s=this.workflowManager.getWorkflow().steps.find(o=>o.stepName===i);s&&(t.has(s.stepTitle)||t.set(s.stepTitle,{}),t.get(s.stepTitle).selection=a[i].selections[0].name)}),t}getQuantity(){return this.getWorkflowManager().getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:es,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const vl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],El=async(r,t,e)=>{const a=t.data,n=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),s=n.slice(0,4)==="http"?"":"https://",o=new URL(s+n);o.searchParams.append("video",Ka(JSON.stringify([{href:i}]))),o.pathname=o.pathname+(o.pathname.slice(-1)==="/"?"":"/");const l=o.toString(),d=`data:image/svg+xml;base64,${Ka(await Cn.toString(l,{type:"svg"}))}`,A=h=>{const g=r.find(p=>p.panelId===h.panelId);if(!g)throw new j(h);const m=N();return new G({id:m,src:d,type:T.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},Bl=async(r,t,e,a)=>{const n=e.data,i=n.assetUrl,s=await ca(i);try{const o=Xs(n,a.option);o&&(t[a.stepName]={selectedVariants:[o]});const l=async c=>{var m;const d=await ar(c,(m=o==null?void 0:o.asset)==null?void 0:m.fileLink),A=await ce(d),u=N(),h=r.find(p=>p.panelId===c.panelId);if(!h)throw new j(c);const g=Da(s,A,{scale:n.scale,left:n.x,top:n.y},a.data.forceImageCover);return[new G({id:u,path:A.path,type:T.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:s.src,x:g.x,y:g.y,width:s.width,height:s.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:s.svg,colors:s.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(o){return console.error(o),[]}},bl=async(r,t,e,a)=>{var S,E;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((S=i.variants)==null?void 0:S.find(B=>B.id===n.illustrationVariantId))||le(i);if(!s)return console.error(`No variant with ID: ${n.illustrationVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(E=s.asset)==null?void 0:E.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.illustrationVariantId}`),[];const l=await tt(o,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=(d==null?void 0:d.length)>0?d[0]:"",g=ct().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Te(g);const m={};Ot(g,B=>{vl.includes(B.tagName)&&!B.attributes.getNamedItem("fill")&&B.setAttribute("fill","#000000");const I=B.attributes.getNamedItem("fill");if(I&&I.value!=="none"){const F=I.value,Q=`spiff-fill-${F.replace(/\W/g,"")}`;B.classList.add(Q),m[Q]={browserValue:F}}const x=B.attributes.getNamedItem("stroke");if(x&&x.value!=="none"){const F=x.value,Q=`spiff-stroke-${F.replace(/\W/g,"")}`;B.classList.add(Q),m[Q]={browserValue:F}}});const f=wt().serializeToString(g),C=n.colors;if(C){for(const[B,I]of Object.entries(m))for(const x of Object.keys(C))if(I.browserValue===x){m[B]={browserValue:C[x]};break}}const y=B=>{const I=r.find(F=>F.panelId===B.panelId);if(!I)throw new j(B);const x=N();return new G({colors:m,id:x,svg:f,type:T.Illustration,y:B.top,x:B.left,rotation:B.rotation,width:B.width,height:B.height,layer:B.layer,layerIndex:B.layerIndex,immutable:B.immutable},I)},v=a.data.regions;try{return v.map(y)}catch(B){return console.error(B),[]}},Il=async(r,t,e)=>{const a=await Ar(e.data.module),n=t.data,i=(o,l)=>{const c=r.find(A=>A.panelId===l.panelId);if(!c)throw new j(l);const d=N();return new G({colors:{},id:d,svg:o,type:T.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},s=e.data.regions;try{return s.map(o=>i(a.svgPrint(n.text,o),o))}catch(o){return console.error(o),[]}},Pl=async(r,t,e,a)=>{var d,A;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((d=i.variants)==null?void 0:d.find(u=>u.id===n.pictureVariantId))||le(i);if(!s)return console.error(`No variant with ID: ${n.pictureVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(A=s.asset)==null?void 0:A.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.pictureVariantId}`),[];const l=u=>{const h=r.find(m=>m.panelId===u.panelId);if(!h)throw new j(u);const g=N();return new G({id:g,src:o,type:T.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},h)},c=a.data.regions;try{return c.map(l)}catch(u){return console.error(u),[]}},Dl=async(r,t,e,a)=>{var c;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((c=i.variants)==null?void 0:c.find(d=>d.id===n.colorVariantId))||le(i);if(!s)return console.error(`No variant with ID: ${n.colorVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=d=>{const A=r.find(p=>p.panelId===d.panelId);if(!A)throw new j(d);const u=`
|
|
2233
2233
|
<svg
|
|
2234
2234
|
xmlns="http://www.w3.org/2000/svg"
|
|
2235
2235
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
|
@@ -2249,8 +2249,8 @@
|
|
|
2249
2249
|
fill="${s==null?void 0:s.color}"
|
|
2250
2250
|
/>
|
|
2251
2251
|
</svg>
|
|
2252
|
-
`,g={"spiff-fill-shape":{browserValue:s.color||"#000000"}},m=N();return new G({colors:g,id:m,svg:u,type:T.Illustration,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable},A)},l=a.data.regions;try{return l.map(o)}catch(d){return console.error(d),[]}},
|
|
2253
|
-
`)},f))}else n.push(new G(C,f))}return n},xl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,xr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case P.DigitalContent:n.push(...await Sl(e,s,o));break;case P.Frame:case P.Photo:n.push(...await vl(e,i,s,o));break;case P.Illustration:n.push(...await El(e,i,s,o));break;case P.Module:n.push(...await Bl(e,s,o));break;case P.Picture:n.push(...await bl(e,i,s,o));break;case P.Shape:n.push(...await Il(e,i,s,o));break;case P.Text:n.push(...await Dl(e,i,s,o));break}}for(const s of t.steps)s.type!==P.SilentIllustration&&s.type!==P.ProductOverlay||xl(s,i)&&n.push(...await Pl(e,s,a));return n};class Fl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Tl(a.id,a.name,this,{width:a.width,height:a.height}))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}}const kl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),Ml=kl();class Tl{constructor(t,e,a,n){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new ba(2),this.id=t,this.name=e,this.service=a,this.panelSize=n}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Bt(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Ql(this.getID(),a,await Ml,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e))}}class Ql extends Ba{constructor(t,e,a,n,i){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(h=>h.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const h=s/o;a/n<h?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const m=this.resizeFit({width:l,height:c});l=m.width,c=m.height}else l=i.width,c=i.height;const d=Oe(t.layoutState.layout,e,{renderingConfiguration:{purpose:Qt.ThreeD}}),A=Fn(d),u=await Ca.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:re,DOMParser:Sa(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const Nl=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===P.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Rl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new ka(l))).apply(n);const s=await xr(r,t,e,a);return new $(s).apply(n)};class Ol{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case Z.FileUpload:return new Fr(this.bundle,t).initialize();case Z.ColorOption:return new ma(this.bundle,t,t.entityId?await K.getOption(t.entityId):void 0);case Z.Option:{const e=t.entityId?await K.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new ma(this.bundle,t,e):new Ua(this.bundle,t,e)}case Z.Text:return new kr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class $e{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Fr extends $e{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await K.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await tt(t==null?void 0:t.fileLink),n=await xa(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await st(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Pe.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Me(Qe(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await st(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class kr extends $e{constructor(t,e){super(t,e)}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class Ua extends $e{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new rt(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new rt(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new rt(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new rt(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new rt(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class ma extends Ua{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case P.Shape:return s.selectVariant(t);case P.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case P.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const $l=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),Ul=(r,t,e)=>{const n=$l(r,t,e,P.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class Ll{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Bt(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Bt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Bt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await b.getShadowGraphqlClient().mutate({mutation:To,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case Z.FileUpload:{i.fileUpload=n.storage;break}case Z.Option:{i.option=n.storage;break}case Z.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){var e,a;const t=await b.getShadowGraphqlClient().mutate({mutation:Mo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Vl{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.getModelContainer()))return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const zl=w.gql`
|
|
2252
|
+
`,g={"spiff-fill-shape":{browserValue:s.color||"#000000"}},m=N();return new G({colors:g,id:m,svg:u,type:T.Illustration,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable},A)},l=a.data.regions;try{return l.map(o)}catch(d){return console.error(d),[]}},xl=async(r,t,e)=>{const a=[],i=(()=>{var c,d;return t.type===P.ProductOverlay?e||((c=t.data.asset)==null?void 0:c.fileLink)||"":((d=t.data.asset)==null?void 0:d.fileLink)||""})(),o=(()=>i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?T.Image:(i.endsWith(".svg"),T.Illustration))(),l=t.data.regions;if(o==="image")try{l.forEach(c=>{const d=r.find(u=>u.panelId===c.panelId);if(!d)throw new j(c);const A={id:N(),src:i,type:o,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===P.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new G(A,d))})}catch(c){console.error(c)}else{const c=await tt(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=(h==null?void 0:h.length)>0?h[0]:"",f=ct().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new vt("Failed to read SVG.");return Te(f),wt().serializeToString(f)};l.forEach(A=>{const u=r.find(g=>g.panelId===A.panelId);if(!u)throw new j(A);const h={id:N(),src:i,asset_key:i,svg:d(c),colors:{},type:o,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===P.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new G(h,u))})}return a},Fl=async(r,t,e,a)=>{const n=[],i=e.data,s=30,o=p=>p.vertical?"center":p.textAlign||"center",l=()=>{var y;const p=a.option;if(!p)return;const f=((y=p.variants)==null?void 0:y.find(v=>v.id===i.fontVariantId))||le(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const C=f.asset.fileLink;if(C)return C},d=await(async()=>{const p=l();if(!p)return;const f=await Pt(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=ve(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;if(!f)return;const C=K.getDefaultVariant(f);return C==null?void 0:C.color},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=r.find(y=>y.panelId===p.panelId);if(!f)continue;const C={stepName:e.name,id:N(),align:o(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||s,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:T.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[y,v]=Jt(a.data.size||s,d,p,[ve(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new G({...C,fontSize:y,text:C.curved?C.text:(v||[]).join(`
|
|
2253
|
+
`)},f))}else n.push(new G(C,f))}return n},kl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,xr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case P.DigitalContent:n.push(...await El(e,s,o));break;case P.Frame:case P.Photo:n.push(...await Bl(e,i,s,o));break;case P.Illustration:n.push(...await bl(e,i,s,o));break;case P.Module:n.push(...await Il(e,s,o));break;case P.Picture:n.push(...await Pl(e,i,s,o));break;case P.Shape:n.push(...await Dl(e,i,s,o));break;case P.Text:n.push(...await Fl(e,i,s,o));break}}for(const s of t.steps)s.type!==P.SilentIllustration&&s.type!==P.ProductOverlay||kl(s,i)&&n.push(...await xl(e,s,a));return n};class Ml{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Nl(a.id,a.name,this,{width:a.width,height:a.height}))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}}const Tl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),Ql=Tl();class Nl{constructor(t,e,a,n){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new ba(2),this.id=t,this.name=e,this.service=a,this.panelSize=n}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Bt(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Rl(this.getID(),a,await Ql,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e))}}class Rl extends Ba{constructor(t,e,a,n,i){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(h=>h.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const h=s/o;a/n<h?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const m=this.resizeFit({width:l,height:c});l=m.width,c=m.height}else l=i.width,c=i.height;const d=Oe(t.layoutState.layout,e,{renderingConfiguration:{purpose:Qt.ThreeD}}),A=Fn(d),u=await Ca.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:re,DOMParser:Sa(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const Ol=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===P.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},$l=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new ka(l))).apply(n);const s=await xr(r,t,e,a);return new $(s).apply(n)};class Ul{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case Z.FileUpload:return new Fr(this.bundle,t).initialize();case Z.ColorOption:return new ma(this.bundle,t,t.entityId?await K.getOption(t.entityId):void 0);case Z.Option:{const e=t.entityId?await K.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new ma(this.bundle,t,e):new Ua(this.bundle,t,e)}case Z.Text:return new kr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class $e{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Fr extends $e{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await K.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await tt(t==null?void 0:t.fileLink),n=await xa(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await st(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Pe.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Me(Qe(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await st(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class kr extends $e{constructor(t,e){super(t,e)}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class Ua extends $e{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new rt(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new rt(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new rt(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new rt(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new rt(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class ma extends Ua{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case P.Shape:return s.selectVariant(t);case P.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case P.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const Ll=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),Vl=(r,t,e)=>{const n=Ll(r,t,e,P.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class zl{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Bt(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Bt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Bt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await b.getShadowGraphqlClient().mutate({mutation:To,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case Z.FileUpload:{i.fileUpload=n.storage;break}case Z.Option:{i.option=n.storage;break}case Z.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){var e,a;const t=await b.getShadowGraphqlClient().mutate({mutation:Mo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Gl{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.getModelContainer()))return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const ql=w.gql`
|
|
2254
2254
|
query GetManyMetafields($entityIds: [String!]!) {
|
|
2255
2255
|
metafieldsMany(entityIds: $entityIds) {
|
|
2256
2256
|
id
|
|
@@ -2261,14 +2261,14 @@
|
|
|
2261
2261
|
}
|
|
2262
2262
|
}
|
|
2263
2263
|
}
|
|
2264
|
-
`;class
|
|
2264
|
+
`;class Wl{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(n=>{const i=this.requestKeyForEntityIfAvailable(t,n);i&&a.set(n,i)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await b.getShadowGraphqlClient().query({query:ql,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,n)=>{const i=e.data.metafieldsMany[n];this.internalMap.set(a,i.map(s=>({key:s.metafieldConfiguration.name,value:s.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const n=a.find(i=>i.key===e);return n||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),n?JSON.parse(n.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const n=this.internalMap.get(t).find(i=>i.key===e);if(n)return JSON.parse(n.value)}}const Mr=new Wl;var Tr=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(Tr||{});class La{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(t=>!!t.product).map(t=>new jt(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new jt(a));const e=await b.getShadowGraphqlClient().query({query:Uo,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new jt(a))}async filterProducts(t,e,a,n){var l,c;const i=await b.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:n}});if(!((l=i.data)!=null&&l.productCollections)||((c=i.data)==null?void 0:c.productCollections.length)===0)throw new Error("Failed to filter product collection products.");const s=this.getProducts(),o=i.data.productCollections[0].productCollectionProducts.map(d=>d.product.id);return s.filter(d=>o.includes(d.getId()))}async fetchProductsFeed(t,e,a,n,i,s){if(this.fullFetched){const d=await(a?this.filterProducts(a):this.fetchProducts());return{total:d.length,items:d.slice(t,t+e)}}const o=new AbortController,{signal:l}=o,c=b.getShadowGraphqlClient().watchQuery({query:Vo,variables:{id:this.getId(),limit:e,offset:t,filters:a?{link:"And",metafields:a}:void 0,tags:n?{include:n.include??[],exclude:n.exclude??[]}:void 0,sortKey:i,sortDescending:s},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:l}}});return new Promise(d=>{let A=!1;const u=c.subscribe({next(h){var m,p,f,C,y,v;if(A||h.partial&&(!h.data.productCollections||h.data.productCollections.length===0||!((m=h.data.productCollections[0].productCollectionProductsFeed)!=null&&m.items)||((p=h.data.productCollections[0].productCollectionProductsFeed)==null?void 0:p.items.length)===0))return;o.abort(),A=!0,u.unsubscribe();const g=((C=(f=h.data.productCollections)==null?void 0:f[0].productCollectionProductsFeed)==null?void 0:C.items.filter(S=>!!S.product).map(S=>new jt(Bt(S))))||[];d({items:g,total:((v=(y=h.data.productCollections)==null?void 0:y[0].productCollectionProductsFeed)==null?void 0:v.total)??0})},error(){A||(A=!0,u.unsubscribe(),d({items:[],total:0}))}})})}getTransformCollection(){if(this.collection.transformCollection)return new Qr(this.collection.transformCollection)}getResource(){return this.collection}}class jt{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const n=(this.product.integrationProducts||[]).find(i=>{var c,d,A;const s=(c=i.integration)==null?void 0:c.type,o=((d=i.integration)==null?void 0:d.type)===t,l=e?((A=i.integration)==null?void 0:A.externalIntegrationId)===e:!0;return s&&o&&l});if(!n)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return n}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>{var n;return(n=a.integration)==null?void 0:n.isCurrent});if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new ht("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new ht("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(n=>n.workflowName===e);if(a)return new Tt(a)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new Tt(t[0]);throw new ht("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new ht("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){var n,i,s,o;const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=(n=this.product.integrationProducts)==null?void 0:n.find(l=>{var c;return((c=l.integration)==null?void 0:c.id)===t.integrationId}):t.externalId?a=(i=this.product.integrationProducts)==null?void 0:i.find(l=>{var c;return((c=l.integration)==null?void 0:c.externalIntegrationId)===t.externalId}):a=(s=this.product.integrationProducts)==null?void 0:s.find(l=>{var c;return((c=l.integration)==null?void 0:c.type)===t.integrationType}),(o=a==null?void 0:a.additionalIntegrationProduct)!=null&&o.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return Mr.requestKeysForEntity(this.product.id,t)}}class Tt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Qr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new Nr(t))}}class Nr{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}const jl=w.gql`
|
|
2265
2265
|
${Ae(!1)}
|
|
2266
2266
|
query GetProductCollections($ids: [String!]!) {
|
|
2267
2267
|
productCollections(ids: $ids) {
|
|
2268
2268
|
...ProductCollectionFields
|
|
2269
2269
|
}
|
|
2270
2270
|
}
|
|
2271
|
-
`,
|
|
2271
|
+
`,Hl=async r=>{var e,a;return(a=(e=(await b.getShadowGraphqlClient().query({query:jl,errorPolicy:"all",variables:{ids:r}})).data)==null?void 0:e.productCollections)==null?void 0:a.map(n=>new La(n))};class Yl{constructor(){this.listeners={}}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(a=>a!==e))}emit(t,e){if(this.listeners[t])for(const a of this.listeners[t])a(e)}clear(t){if(t)delete this.listeners[t];else for(const e in this.listeners)delete this.listeners[e]}}const Jl=w.gql`
|
|
2272
2272
|
mutation AddAddressToBundle(
|
|
2273
2273
|
$bundleId: String!
|
|
2274
2274
|
$streetAddress: String
|
|
@@ -2290,26 +2290,26 @@
|
|
|
2290
2290
|
id
|
|
2291
2291
|
}
|
|
2292
2292
|
}
|
|
2293
|
-
`,
|
|
2293
|
+
`,Kl=w.gql`
|
|
2294
2294
|
mutation AddOrganizationToBundle($bundleId: String!, $organizationName: String!) {
|
|
2295
2295
|
organizationAttachToBundle(bundleId: $bundleId, organizationName: $organizationName) {
|
|
2296
2296
|
id
|
|
2297
2297
|
}
|
|
2298
2298
|
}
|
|
2299
|
-
`,
|
|
2299
|
+
`,_l=w.gql`
|
|
2300
2300
|
mutation GenerateQuoteId($id: String!) {
|
|
2301
2301
|
bundleGenerateQuoteId(id: $id) {
|
|
2302
2302
|
id
|
|
2303
2303
|
quoteId
|
|
2304
2304
|
}
|
|
2305
2305
|
}
|
|
2306
|
-
`;class Ke{constructor(t,e,a,n,i,s){var c,d,A;this.workflowExperiences=[],this.eventEmitter=new jl,this.client=t,this.id=e.id,this.name=e.name||"",this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((c=e.metadata)==null?void 0:c.map(u=>[u.key,u.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Vl(e.bundleStateData);const o=(d=this.productCollection)==null?void 0:d.globalPropertyConfiguration;this.globalConfigurationPropertyId=o==null?void 0:o.id,this.globalPropertyStateManager=new Ll(this.id,this.ownerId,o,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Ol(this),this.setPreviewService(a);const l=new Promise((u,h)=>{if(s!=null&&s.readonly){u([]);return}console.log("Setting default global variants."),this.globalPropertyHandleService.getHandles().then(g=>{const m=g.map(p=>{if(p.getType()===Z.ColorOption||p.getType()===Z.Option){const f=p;if(this.globalPropertyStateManager.getGlobalPropertyState())return f.initDefaultVariant();console.log("Attempted to set global default variant before state was initialized.")}});Promise.all(m).then(u).catch(h)})});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((A=e.transactions)==null?void 0:A.map(u=>u.id))||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)})}getTemplate(){return this.template}async generateQuoteId(){var a,n;const e=(n=(a=(await b.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data)==null?void 0:a.bundleGenerateQuoteId)==null?void 0:n.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,s){await b.getShadowGraphqlClient().mutate({mutation:Hl,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await b.getShadowGraphqlClient().mutate({mutation:Yl,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===Z.Option).map(a=>{var n;return((n=a.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new La(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){var e,a,n,i;for(const s of t.getStepsByType(P.Illustration)){const o=s.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const l of o){const c=(e=this.getGlobalPropertyConfiguration())==null?void 0:e.aspects.find(d=>d.name===l);if(c&&c.type===Z.ColorOption){const d=(a=s.getCurrentVariant())==null?void 0:a.getAssetResource(),A=((n=d==null?void 0:d.assetConfiguration)==null?void 0:n.channelNumbers)||[],u=((i=d==null?void 0:d.assetConfiguration)==null?void 0:i.defaultColorVariants)||[],h=Ul(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",l),g=[...new Set(A.map(p=>p.number))];if(g.length>h)for(const p of g){const f=this.getGlobalPropertyStateManager(),C=u.find(y=>y.channelNumber===p);C&&await f.setAspect(l,C.variant.id||"",void 0,C.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getWorkflowManager().getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=M.getMap("transactionOwnerIds")||new Map,i=e.map(o=>n.get(o));await b.getShadowGraphqlClient().mutate({mutation:qo,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(M.getMap("transactionOwnerIds")||new Map).get(a);await b.getShadowGraphqlClient().mutate({mutation:Go,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await b.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await b.getShadowGraphqlClient().mutate({mutation:jo,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const a=await b.getShadowGraphqlClient().mutate({mutation:Ho,variables:{id:this.id,details:t,type:e||_t.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=a.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){var a;if(!((a=(await b.getShadowGraphqlClient().mutate({mutation:Yo,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&a.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var n;const e=await b.getShadowGraphqlClient().mutate({mutation:Jo,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((n=e.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await b.getShadowGraphqlClient().query({query:on,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await b.getShadowGraphqlClient().query({query:on,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await b.getShadowGraphqlClient().mutate({mutation:tl,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const a=await ml(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await b.getShadowGraphqlClient().mutate({mutation:Xo,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){var a,n;const e=await b.getShadowGraphqlClient().mutate({mutation:_o(((a=this.globalPropertyStateManager.getBundleOptions())==null?void 0:a.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if((n=e.data)!=null&&n.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const i=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(i),this.globalConfigurationPropertyId=i==null?void 0:i.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var e;if(!((e=(await b.getShadowGraphqlClient().mutate({mutation:zo,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,n])=>({key:a,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await b.getShadowGraphqlClient().mutate({mutation:Ko,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);if((()=>{if(n.length!==i.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(l=>!n.includes(l));await Promise.all(o.map(l=>l.applyGlobalState()))}}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await b.getShadowGraphqlClient().mutate({mutation:el,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await b.getShadowGraphqlClient().mutate({mutation:al,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Kl=w.gql`
|
|
2306
|
+
`;class Ke{constructor(t,e,a,n,i,s){var c,d,A;this.workflowExperiences=[],this.eventEmitter=new Yl,this.client=t,this.id=e.id,this.name=e.name||"",this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((c=e.metadata)==null?void 0:c.map(u=>[u.key,u.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Gl(e.bundleStateData);const o=(d=this.productCollection)==null?void 0:d.globalPropertyConfiguration;this.globalConfigurationPropertyId=o==null?void 0:o.id,this.globalPropertyStateManager=new zl(this.id,this.ownerId,o,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Ul(this),this.setPreviewService(a);const l=new Promise((u,h)=>{if(s!=null&&s.readonly){u([]);return}console.log("Setting default global variants."),this.globalPropertyHandleService.getHandles().then(g=>{const m=g.map(p=>{if(p.getType()===Z.ColorOption||p.getType()===Z.Option){const f=p;if(this.globalPropertyStateManager.getGlobalPropertyState())return f.initDefaultVariant();console.log("Attempted to set global default variant before state was initialized.")}});Promise.all(m).then(u).catch(h)})});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((A=e.transactions)==null?void 0:A.map(u=>u.id))||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)})}getTemplate(){return this.template}async generateQuoteId(){var a,n;const e=(n=(a=(await b.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data)==null?void 0:a.bundleGenerateQuoteId)==null?void 0:n.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,s){await b.getShadowGraphqlClient().mutate({mutation:Jl,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await b.getShadowGraphqlClient().mutate({mutation:Kl,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===Z.Option).map(a=>{var n;return((n=a.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new La(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){var e,a,n,i;for(const s of t.getStepsByType(P.Illustration)){const o=s.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const l of o){const c=(e=this.getGlobalPropertyConfiguration())==null?void 0:e.aspects.find(d=>d.name===l);if(c&&c.type===Z.ColorOption){const d=(a=s.getCurrentVariant())==null?void 0:a.getAssetResource(),A=((n=d==null?void 0:d.assetConfiguration)==null?void 0:n.channelNumbers)||[],u=((i=d==null?void 0:d.assetConfiguration)==null?void 0:i.defaultColorVariants)||[],h=Vl(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",l),g=[...new Set(A.map(p=>p.number))];if(g.length>h)for(const p of g){const f=this.getGlobalPropertyStateManager(),C=u.find(y=>y.channelNumber===p);C&&await f.setAspect(l,C.variant.id||"",void 0,C.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getWorkflowManager().getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=M.getMap("transactionOwnerIds")||new Map,i=e.map(o=>n.get(o));await b.getShadowGraphqlClient().mutate({mutation:jo,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(M.getMap("transactionOwnerIds")||new Map).get(a);await b.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await b.getShadowGraphqlClient().mutate({mutation:Ho,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await b.getShadowGraphqlClient().mutate({mutation:Yo,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const a=await b.getShadowGraphqlClient().mutate({mutation:Jo,variables:{id:this.id,details:t,type:e||_t.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=a.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){var a;if(!((a=(await b.getShadowGraphqlClient().mutate({mutation:Ko,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&a.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var n;const e=await b.getShadowGraphqlClient().mutate({mutation:_o,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((n=e.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await b.getShadowGraphqlClient().query({query:on,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await b.getShadowGraphqlClient().query({query:on,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await b.getShadowGraphqlClient().mutate({mutation:al,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const a=await fl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await b.getShadowGraphqlClient().mutate({mutation:tl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){var a,n;const e=await b.getShadowGraphqlClient().mutate({mutation:Zo(((a=this.globalPropertyStateManager.getBundleOptions())==null?void 0:a.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if((n=e.data)!=null&&n.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const i=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(i),this.globalConfigurationPropertyId=i==null?void 0:i.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var e;if(!((e=(await b.getShadowGraphqlClient().mutate({mutation:qo,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,n])=>({key:a,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await b.getShadowGraphqlClient().mutate({mutation:Xo,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);if((()=>{if(n.length!==i.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(l=>!n.includes(l));await Promise.all(o.map(l=>l.applyGlobalState()))}}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await b.getShadowGraphqlClient().mutate({mutation:nl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await b.getShadowGraphqlClient().mutate({mutation:rl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Xl=w.gql`
|
|
2307
2307
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
2308
2308
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
2309
2309
|
id
|
|
2310
2310
|
}
|
|
2311
2311
|
}
|
|
2312
|
-
`;class Rr{async execute(t,e,a){var A,u,h;const i=(u=(A=(await b.getShadowGraphqlClient().mutate({mutation:
|
|
2312
|
+
`;class Rr{async execute(t,e,a){var A,u,h;const i=(u=(A=(await b.getShadowGraphqlClient().mutate({mutation:Xl,variables:{processFlowId:t,inputs:[...e.map(g=>g.getValueForTransmission())]}})).data)==null?void 0:A.processExecutionCreate)==null?void 0:u.id;if(!i)throw new Error("Failed to create process execution.");function s(g){return new Promise(m=>{setTimeout(m,g)})}let o=!1,l=0,c,d;for(;!o;){c=await b.getShadowGraphqlClient().query({query:w.gql`
|
|
2313
2313
|
query getProcessFlowExecution($ids: [String]!) {
|
|
2314
2314
|
processExecutions(ids: $ids) {
|
|
2315
2315
|
id
|
|
@@ -2322,7 +2322,7 @@
|
|
|
2322
2322
|
}
|
|
2323
2323
|
}
|
|
2324
2324
|
}
|
|
2325
|
-
`,variables:{ids:[i]}});const g=(h=c.data)==null?void 0:h.processExecutions[0];if(!c||!g)throw new Error("Failed to retrieve server response for execution.");if(g.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(g.completedAt){o=!0,d=new Or(g);break}l+=1;const m=a!=null&&a.repeats?a==null?void 0:a.repeats:5;if(l>=m)throw new Error("Maximum wait time exceeded for execution result.");await s(a!=null&&a.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class Or{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Ht(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Ht(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Ht(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Ht(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Ht{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class Va{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var $r=(r=>(r.Transaction="Transaction",r.Bundle="Bundle",r.Product="Product",r.Variant="Variant",r.Option="Option",r.LineItem="LineItem",r.Asset="Asset",r))($r||{});class
|
|
2325
|
+
`,variables:{ids:[i]}});const g=(h=c.data)==null?void 0:h.processExecutions[0];if(!c||!g)throw new Error("Failed to retrieve server response for execution.");if(g.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(g.completedAt){o=!0,d=new Or(g);break}l+=1;const m=a!=null&&a.repeats?a==null?void 0:a.repeats:5;if(l>=m)throw new Error("Maximum wait time exceeded for execution result.");await s(a!=null&&a.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class Or{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Ht(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Ht(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Ht(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Ht(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Ht{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class Va{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var $r=(r=>(r.Transaction="Transaction",r.Bundle="Bundle",r.Product="Product",r.Variant="Variant",r.Option="Option",r.LineItem="LineItem",r.Asset="Asset",r))($r||{});class Zl extends Va{constructor(t){super(`"${t}"`)}}class za extends Va{constructor(t,e){if(e!=="Asset"&&!za.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class tc extends Va{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class pa{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){var a;if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=(a=this.integrationProduct)==null?void 0:a.additionalIntegrationProduct;if(!e)return t;if(e&&!e.product)throw new Error("An additional integration product was found, but it does not have a product");return t+(e.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new Tt(t[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return t.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}}const cn=w.gql`
|
|
2326
2326
|
query GetCustomer($emailAddress: String!) {
|
|
2327
2327
|
customer(emailAddress: $emailAddress) {
|
|
2328
2328
|
id
|
|
@@ -2333,7 +2333,7 @@
|
|
|
2333
2333
|
}
|
|
2334
2334
|
}
|
|
2335
2335
|
}
|
|
2336
|
-
`,
|
|
2336
|
+
`,ec=w.gql`
|
|
2337
2337
|
mutation CustomerCreate($details: CustomerDetailsInput!) {
|
|
2338
2338
|
customerCreate(details: $details) {
|
|
2339
2339
|
id
|
|
@@ -2343,7 +2343,7 @@
|
|
|
2343
2343
|
}
|
|
2344
2344
|
}
|
|
2345
2345
|
}
|
|
2346
|
-
`,
|
|
2346
|
+
`,ac=w.gql`
|
|
2347
2347
|
mutation CustomerAuthenticate($loginToken: String!) {
|
|
2348
2348
|
customerAuthenticate(loginToken: $loginToken) {
|
|
2349
2349
|
id
|
|
@@ -2373,11 +2373,11 @@
|
|
|
2373
2373
|
}
|
|
2374
2374
|
}
|
|
2375
2375
|
}
|
|
2376
|
-
`,
|
|
2376
|
+
`,nc=w.gql`
|
|
2377
2377
|
mutation CustomerGenerateVerificationCode($emailAddress: String!) {
|
|
2378
2378
|
customerGenerateVerificationCode(emailAddress: $emailAddress)
|
|
2379
2379
|
}
|
|
2380
|
-
`,
|
|
2380
|
+
`,rc=w.gql`
|
|
2381
2381
|
mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
|
|
2382
2382
|
customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
|
|
2383
2383
|
id
|
|
@@ -2408,7 +2408,7 @@
|
|
|
2408
2408
|
}
|
|
2409
2409
|
}
|
|
2410
2410
|
}
|
|
2411
|
-
`,
|
|
2411
|
+
`,ic=w.gql`
|
|
2412
2412
|
query CustomerMetafields($id: String!) {
|
|
2413
2413
|
metafields(entityId: $id) {
|
|
2414
2414
|
id
|
|
@@ -2426,7 +2426,7 @@
|
|
|
2426
2426
|
}
|
|
2427
2427
|
}
|
|
2428
2428
|
}
|
|
2429
|
-
`;class rc{constructor(t,e=b.getShadowGraphqlClient.bind(b)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}const ic=async(r,t)=>{var n;const e=await b.getShadowGraphqlClient().query({query:us(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),$t.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Ga=async(r,t)=>{const e=r.map(o=>$t.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ic(a,t),i=a.map(o=>$t.set({id:o,options:t},sc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},oc=async(r,t)=>(await Ga([r],t))[0],lc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),cc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):lc(t.panels)};class dc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return b.getShadowGraphqlClient().mutate({...e,mutation:ts})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.41.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return U}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!Ci())throw new Error("Application key required to use Flow Service.");return new Rr}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Ur(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=M.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const a=M.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t),l=(M.getMap("partnerCustomerIds")||new Map).get(s);if(l&&await this.authenticateCustomerId(l)){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=b.getShadowGraphqlClient(),a=await e.query({query:hs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=M.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const o=M.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const p=o.get(t);if(p&&await this.authenticateCustomerId(p)){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(y=>{var v,S;return(S=(v=y.bundle)==null?void 0:v.transactions)==null?void 0:S.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(y=>{var v;return((v=y.transaction)==null?void 0:v.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}}const c=(await e.query({query:gs,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=M.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),M.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await b.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=b.getShadowGraphqlClient(),n=(await e.query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:Zl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.authenticateCustomerId(n.id);return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=b.getShadowGraphqlClient(),a=M.getMap("customerTokens");if(!(a!=null&&a.has(t)))return!1;const n=a.get(t);if(!n)return!1;const s=(o=(await e.mutate({mutation:tc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),_a(n),this.customer=s,!0):!1}async generateVerificationCode(t){await b.getShadowGraphqlClient().mutate({mutation:ec,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const n=(i=(await b.getShadowGraphqlClient().mutate({mutation:ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(n!=null&&n.loginToken){if(!((s=n.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=M.getMap("customerTokens")||new Map;return o.set(n.id,n.loginToken),M.setMap("customerTokens",o),this.storeCustomer(n),_a(n.loginToken),this.customer={...n,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await b.getShadowGraphqlClient().query({query:nc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await b.getShadowGraphqlClient().mutate({mutation:Lo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=M.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),M.setMap("bundlePartnerIds",s);const o=M.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),M.setMap("bundleOwnerIds",o);const l=new Ke(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var p,f,C,y,v,S,E,B,I,x,F;const i=M.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),l=((p=Object.entries(localStorage).find(([k,Q])=>k.startsWith("CognitoIdentityServiceProvider")&&k.endsWith("idToken")))==null?void 0:p[0])||"",c=localStorage.getItem(l),d={};c&&!Ie(c)&&(d.Authorization=`Bearer ${c}`);const A={bundleOwnerId:s,...d,...(f=n==null?void 0:n.graphql)==null?void 0:f.additionalHeaders},u=await b.getShadowGraphqlClient().query({query:No(((y=(C=n==null?void 0:n.graphql)==null?void 0:C.productCollection)==null?void 0:y.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:A}});if(!((v=u.data)!=null&&v.bundles)||((S=u.data)==null?void 0:S.bundles.length)===0||!((E=u.data)!=null&&E.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const h=(B=u.data)==null?void 0:B.bundles[0],g=M.getMap("bundlePartnerIds")||new Map;g.set(h.id,h.partner.id),M.setMap("bundlePartnerIds",g);const m=new Ke(this,h,e,a,s,{additionalHeaders:(I=n==null?void 0:n.graphql)==null?void 0:I.additionalHeaders,eagerFetchProducts:(F=(x=n==null?void 0:n.graphql)==null?void 0:x.productCollection)==null?void 0:F.eagerFetchProducts,existingGlobalPropertyState:u.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await m.getInitializationPromise(),m}async duplicateBundle(t,e,a,n){var p,f,C,y,v,S,E,B;const i=(p=M.getMap("bundleOwnerIds"))==null?void 0:p.get(t),o=((f=Object.entries(localStorage).find(([I,x])=>I.startsWith("CognitoIdentityServiceProvider")&&I.endsWith("idToken")))==null?void 0:f[0])||"",l=localStorage.getItem(o),c={};l&&!Ie(l)&&(c.Authorization=`Bearer ${l}`);const d={bundleOwnerId:i,...c,...(C=n==null?void 0:n.graphql)==null?void 0:C.additionalHeaders},u=(S=(await b.getShadowGraphqlClient().mutate({mutation:Vo(((v=(y=n==null?void 0:n.graphql)==null?void 0:y.productCollection)==null?void 0:v.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:d},fetchPolicy:"no-cache"})).data)==null?void 0:S.bundleDuplicate;if(!(u!=null&&u.id))throw new Error("Unable to duplicate bundle");const h=M.getMap("bundlePartnerIds")||new Map;h.set(u.id,u.partner.id),M.setMap("bundlePartnerIds",h);const g=M.getMap("bundleOwnerIds")||new Map;g.set(u.id,u.bundleOwnerId),M.setMap("bundleOwnerIds",g);const m=new Ke(this,u,void 0,void 0,u.bundleOwnerId,{eagerFetchProducts:(B=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:B.eagerFetchProducts,existingGlobalPropertyState:u.globalPropertyState});return await m.getInitializationPromise(),m}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await b.getShadowGraphqlClient().query({query:Zo(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await b.getShadowGraphqlClient().query({query:Ro,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=M.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),M.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=b.getShadowGraphqlClient(),n=async S=>{var x,F,k;if(S.length===0)return[];const E=S.map(Q=>Q.option.transactionId),B=await a.query({query:Zi,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=B.data.transactions;if(I.length!==S.length){const Q=((F=(x=B.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${Q}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((Q,ot)=>{var R;return{transaction:Q,workflowId:Q.workflowId,readOnly:((R=S.find(et=>et.option.transactionId===Q.id))==null?void 0:R.option.readOnly)??!1,index:S[ot].index}})},i=async S=>{var I,x,F;if(S.length===0)return[];const E=await a.mutate({mutation:Xi,variables:{inputs:S.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),B=(I=E.data)==null?void 0:I.transactionCreateMany;if(!B||B.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return B.map((k,Q)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:S[Q].index}))},s=t.map((S,E)=>({option:S,index:E})),o=s.filter(S=>S.option.type==="transaction"),l=s.filter(S=>S.option.type==="integration"||S.option.type==="external"),c=ja(o,10),d=ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(S=>S.workflowId))],h=await Ga(u,e),g=new Map(h.map(S=>[S.id,S])),m=M.getMap("transactionOwnerIds")||new Map,p=A.map(async S=>{var et;const{transaction:E,workflowId:B,readOnly:I,index:x}=S,F=g.get(B),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const Q=m.get(E.id)||void 0,ot=new rc({onMutate:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new V("State mutation is forbidden in read only mode!")}:async H=>this.updateTransactionState({...H,context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>ot,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(k.type==="transaction"&&E.workflowState){const H=JSON.parse(E.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else if(!I&&k.workflowState){const H=JSON.parse(k.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else R.layouts=cc(R.transaction,R.workflow);return R.renderableContextService=new Fl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);M.setMap("transactionOwnerIds",m);const y=f.sort((S,E)=>S.index-E.index).map(async S=>{const{experienceOptions:E,options:B}=S,I=new Dr(this,E);return await I.getWorkflowManager().getInitializationPromise(),B.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),v=await Promise.all(y);return v.forEach(S=>S.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),v}storeCustomer(t){const e=M.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),M.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await b.getShadowGraphqlClient().query({query:rs(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new pa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await b.getShadowGraphqlClient().query({query:is(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new pa(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(M.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await b.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await b.getShadowGraphqlClient().mutate({mutation:ws,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Ur=async(r,t)=>(await b.getShadowGraphqlClient().query({query:ps,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ac=async r=>{const e=await b.getShadowGraphqlClient().query({query:as,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},uc=async(r,t)=>{var a;return(a=(await b.getShadowGraphqlClient().query({query:ms,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},hc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:Cs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},gc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:fs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function Lr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=fe(r.x,t.width-c,0),o.y=fe(r.y,t.height-d,0),o}const s=r;return s.x=fe(s.x,-n,t.width),s.y=fe(s.y,-i,t.height),s}function fe(r,t,e){return Math.min(Math.max(r,t),e)}class Vr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=yn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await ce(o),c=this.frameData?this.frameData[s]:void 0;wn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=kt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Qe(this.imageData.svg,this.imageData.colors||{},!1);return Me(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new V("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=Lr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new V("Frame data not set. This is a bug");if(!this.workflowManager)throw new V("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new no(o,e,t[l]),new ro(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Da(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class mc{updateRecipient(t,e,a,n,i,s,o,l,c,d){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var zr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(zr||{});class Gr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Vr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){var n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Pe.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await st(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const pc=w.gql`
|
|
2429
|
+
`;class sc{constructor(t,e=b.getShadowGraphqlClient.bind(b)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}const oc=async(r,t)=>{var n;const e=await b.getShadowGraphqlClient().query({query:us(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),$t.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},lc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Ga=async(r,t)=>{const e=r.map(o=>$t.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=oc(a,t),i=a.map(o=>$t.set({id:o,options:t},lc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},cc=async(r,t)=>(await Ga([r],t))[0],dc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),Ac=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):dc(t.panels)};class uc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return b.getShadowGraphqlClient().mutate({...e,mutation:ts})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.42.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return U}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!Ci())throw new Error("Application key required to use Flow Service.");return new Rr}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Ur(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=M.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const a=M.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t),l=(M.getMap("partnerCustomerIds")||new Map).get(s);if(l&&await this.authenticateCustomerId(l)){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=b.getShadowGraphqlClient(),a=await e.query({query:hs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=M.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const o=M.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const p=o.get(t);if(p&&await this.authenticateCustomerId(p)){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(y=>{var v,S;return(S=(v=y.bundle)==null?void 0:v.transactions)==null?void 0:S.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(y=>{var v;return((v=y.transaction)==null?void 0:v.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}}const c=(await e.query({query:gs,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=M.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),M.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await b.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=b.getShadowGraphqlClient(),n=(await e.query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:ec,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.authenticateCustomerId(n.id);return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=b.getShadowGraphqlClient(),a=M.getMap("customerTokens");if(!(a!=null&&a.has(t)))return!1;const n=a.get(t);if(!n)return!1;const s=(o=(await e.mutate({mutation:ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),_a(n),this.customer=s,!0):!1}async generateVerificationCode(t){await b.getShadowGraphqlClient().mutate({mutation:nc,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const n=(i=(await b.getShadowGraphqlClient().mutate({mutation:rc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(n!=null&&n.loginToken){if(!((s=n.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=M.getMap("customerTokens")||new Map;return o.set(n.id,n.loginToken),M.setMap("customerTokens",o),this.storeCustomer(n),_a(n.loginToken),this.customer={...n,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await b.getShadowGraphqlClient().query({query:ic,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await b.getShadowGraphqlClient().mutate({mutation:zo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=M.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),M.setMap("bundlePartnerIds",s);const o=M.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),M.setMap("bundleOwnerIds",o);const l=new Ke(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var p,f,C,y,v,S,E,B,I,x,F;const i=M.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),l=((p=Object.entries(localStorage).find(([k,Q])=>k.startsWith("CognitoIdentityServiceProvider")&&k.endsWith("idToken")))==null?void 0:p[0])||"",c=localStorage.getItem(l),d={};c&&!Ie(c)&&(d.Authorization=`Bearer ${c}`);const A={bundleOwnerId:s,...d,...(f=n==null?void 0:n.graphql)==null?void 0:f.additionalHeaders},u=await b.getShadowGraphqlClient().query({query:Oo(((y=(C=n==null?void 0:n.graphql)==null?void 0:C.productCollection)==null?void 0:y.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:A}});if(!((v=u.data)!=null&&v.bundles)||((S=u.data)==null?void 0:S.bundles.length)===0||!((E=u.data)!=null&&E.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const h=(B=u.data)==null?void 0:B.bundles[0],g=M.getMap("bundlePartnerIds")||new Map;g.set(h.id,h.partner.id),M.setMap("bundlePartnerIds",g);const m=new Ke(this,h,e,a,s,{additionalHeaders:(I=n==null?void 0:n.graphql)==null?void 0:I.additionalHeaders,eagerFetchProducts:(F=(x=n==null?void 0:n.graphql)==null?void 0:x.productCollection)==null?void 0:F.eagerFetchProducts,existingGlobalPropertyState:u.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await m.getInitializationPromise(),m}async duplicateBundle(t,e,a,n){var p,f,C,y,v,S,E,B;const i=(p=M.getMap("bundleOwnerIds"))==null?void 0:p.get(t),o=((f=Object.entries(localStorage).find(([I,x])=>I.startsWith("CognitoIdentityServiceProvider")&&I.endsWith("idToken")))==null?void 0:f[0])||"",l=localStorage.getItem(o),c={};l&&!Ie(l)&&(c.Authorization=`Bearer ${l}`);const d={bundleOwnerId:i,...c,...(C=n==null?void 0:n.graphql)==null?void 0:C.additionalHeaders},u=(S=(await b.getShadowGraphqlClient().mutate({mutation:Go(((v=(y=n==null?void 0:n.graphql)==null?void 0:y.productCollection)==null?void 0:v.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:d},fetchPolicy:"no-cache"})).data)==null?void 0:S.bundleDuplicate;if(!(u!=null&&u.id))throw new Error("Unable to duplicate bundle");const h=M.getMap("bundlePartnerIds")||new Map;h.set(u.id,u.partner.id),M.setMap("bundlePartnerIds",h);const g=M.getMap("bundleOwnerIds")||new Map;g.set(u.id,u.bundleOwnerId),M.setMap("bundleOwnerIds",g);const m=new Ke(this,u,void 0,void 0,u.bundleOwnerId,{eagerFetchProducts:(B=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:B.eagerFetchProducts,existingGlobalPropertyState:u.globalPropertyState});return await m.getInitializationPromise(),m}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await b.getShadowGraphqlClient().query({query:el(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await b.getShadowGraphqlClient().query({query:$o,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=M.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),M.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=b.getShadowGraphqlClient(),n=async S=>{var x,F,k;if(S.length===0)return[];const E=S.map(Q=>Q.option.transactionId),B=await a.query({query:Zi,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=B.data.transactions;if(I.length!==S.length){const Q=((F=(x=B.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${Q}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((Q,ot)=>{var R;return{transaction:Q,workflowId:Q.workflowId,readOnly:((R=S.find(et=>et.option.transactionId===Q.id))==null?void 0:R.option.readOnly)??!1,index:S[ot].index}})},i=async S=>{var I,x,F;if(S.length===0)return[];const E=await a.mutate({mutation:Xi,variables:{inputs:S.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),B=(I=E.data)==null?void 0:I.transactionCreateMany;if(!B||B.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return B.map((k,Q)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:S[Q].index}))},s=t.map((S,E)=>({option:S,index:E})),o=s.filter(S=>S.option.type==="transaction"),l=s.filter(S=>S.option.type==="integration"||S.option.type==="external"),c=ja(o,10),d=ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(S=>S.workflowId))],h=await Ga(u,e),g=new Map(h.map(S=>[S.id,S])),m=M.getMap("transactionOwnerIds")||new Map,p=A.map(async S=>{var et;const{transaction:E,workflowId:B,readOnly:I,index:x}=S,F=g.get(B),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const Q=m.get(E.id)||void 0,ot=new sc({onMutate:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new V("State mutation is forbidden in read only mode!")}:async H=>this.updateTransactionState({...H,context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>ot,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(k.type==="transaction"&&E.workflowState){const H=JSON.parse(E.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else if(!I&&k.workflowState){const H=JSON.parse(k.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else R.layouts=Ac(R.transaction,R.workflow);return R.renderableContextService=new Ml(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);M.setMap("transactionOwnerIds",m);const y=f.sort((S,E)=>S.index-E.index).map(async S=>{const{experienceOptions:E,options:B}=S,I=new Dr(this,E);return await I.getWorkflowManager().getInitializationPromise(),B.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),v=await Promise.all(y);return v.forEach(S=>S.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),v}storeCustomer(t){const e=M.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),M.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await b.getShadowGraphqlClient().query({query:rs(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new pa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await b.getShadowGraphqlClient().query({query:is(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new pa(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(M.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await b.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await b.getShadowGraphqlClient().mutate({mutation:ws,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Ur=async(r,t)=>(await b.getShadowGraphqlClient().query({query:ps,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,hc=async r=>{const e=await b.getShadowGraphqlClient().query({query:as,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},gc=async(r,t)=>{var a;return(a=(await b.getShadowGraphqlClient().query({query:ms,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},mc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:Cs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},pc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:fs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function Lr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=fe(r.x,t.width-c,0),o.y=fe(r.y,t.height-d,0),o}const s=r;return s.x=fe(s.x,-n,t.width),s.y=fe(s.y,-i,t.height),s}function fe(r,t,e){return Math.min(Math.max(r,t),e)}class Vr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=yn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await ce(o),c=this.frameData?this.frameData[s]:void 0;wn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=kt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Qe(this.imageData.svg,this.imageData.colors||{},!1);return Me(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new V("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=Lr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new V("Frame data not set. This is a bug");if(!this.workflowManager)throw new V("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new no(o,e,t[l]),new ro(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Da(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class fc{updateRecipient(t,e,a,n,i,s,o,l,c,d){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var zr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(zr||{});class Gr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Vr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){var n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Pe.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await st(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Cc=w.gql`
|
|
2430
2430
|
query GetLoggedInCustomer($email: String!) {
|
|
2431
2431
|
customer(emailAddress: $email) {
|
|
2432
2432
|
id
|
|
@@ -2469,21 +2469,21 @@
|
|
|
2469
2469
|
total
|
|
2470
2470
|
}
|
|
2471
2471
|
}
|
|
2472
|
-
`,
|
|
2472
|
+
`,wc=w.gql`
|
|
2473
2473
|
mutation SetTransactionDesignName($id: String!, $name: String!) {
|
|
2474
2474
|
transactionUpdate(id: $id, designName: $name) {
|
|
2475
2475
|
id
|
|
2476
2476
|
designName
|
|
2477
2477
|
}
|
|
2478
2478
|
}
|
|
2479
|
-
`,
|
|
2479
|
+
`,yc=w.gql`
|
|
2480
2480
|
mutation DuplicateTransaction($id: String!, $template: Boolean!) {
|
|
2481
2481
|
transactionDuplicate(id: $id, template: $template) {
|
|
2482
2482
|
id
|
|
2483
2483
|
workflowViewerLink
|
|
2484
2484
|
}
|
|
2485
2485
|
}
|
|
2486
|
-
`,
|
|
2486
|
+
`,Sc=w.gql`
|
|
2487
2487
|
query GetCustomerBundles($id: String!, $limit: Int!, $offset: Int!) {
|
|
2488
2488
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset) {
|
|
2489
2489
|
items {
|
|
@@ -2498,7 +2498,7 @@
|
|
|
2498
2498
|
total
|
|
2499
2499
|
}
|
|
2500
2500
|
}
|
|
2501
|
-
`,
|
|
2501
|
+
`,vc=w.gql`
|
|
2502
2502
|
query GetTransactionsForBundle($id: String!) {
|
|
2503
2503
|
bundles(ids: [$id]) {
|
|
2504
2504
|
id
|
|
@@ -2519,21 +2519,21 @@
|
|
|
2519
2519
|
}
|
|
2520
2520
|
}
|
|
2521
2521
|
}
|
|
2522
|
-
`,
|
|
2522
|
+
`,Ec=w.gql`
|
|
2523
2523
|
mutation SetBundleName($id: String!, $name: String!) {
|
|
2524
2524
|
bundleUpdate(id: $id, name: $name) {
|
|
2525
2525
|
id
|
|
2526
2526
|
name
|
|
2527
2527
|
}
|
|
2528
2528
|
}
|
|
2529
|
-
`,
|
|
2529
|
+
`,Bc=w.gql`
|
|
2530
2530
|
mutation DuplicateBundle($id: String!, $template: Boolean!) {
|
|
2531
2531
|
bundleDuplicate(id: $id, template: $template) {
|
|
2532
2532
|
id
|
|
2533
2533
|
workflowViewerLink
|
|
2534
2534
|
}
|
|
2535
2535
|
}
|
|
2536
|
-
`,
|
|
2536
|
+
`,bc=w.gql`
|
|
2537
2537
|
query GetBundleTemplates($id: String!, $limit: Int!, $offset: Int!) {
|
|
2538
2538
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: true) {
|
|
2539
2539
|
items {
|
|
@@ -2546,7 +2546,7 @@
|
|
|
2546
2546
|
total
|
|
2547
2547
|
}
|
|
2548
2548
|
}
|
|
2549
|
-
`,
|
|
2549
|
+
`,Ic=async(r,t,e)=>await b.getShadowGraphqlClient().mutate({mutation:Ec,errorPolicy:"all",variables:{id:r,name:t},context:e}),Pc=async(r,t)=>await b.getShadowGraphqlClient().mutate({mutation:wc,errorPolicy:"all",variables:{id:r,name:t}}),Dc=async(r,t)=>await b.getShadowGraphqlClient().mutate({mutation:Bc,errorPolicy:"all",variables:{id:r,template:t}}),xc=async(r,t)=>await b.getShadowGraphqlClient().mutate({mutation:yc,errorPolicy:"all",variables:{id:r,template:t}}),Fc=async r=>(await b.getShadowGraphqlClient().query({query:Cc,errorPolicy:"all",variables:{email:r}})).data.customer,kc=async(r,t,e)=>await b.getShadowGraphqlClient().query({query:Sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,offset:e,limit:t}}),Mc=async(r,t)=>await b.getShadowGraphqlClient().query({query:vc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:t}),Tc=async(r,t,e)=>{var n;const a=await b.getShadowGraphqlClient().query({query:qa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}});return((n=a==null?void 0:a.data.customerTransactionsFeed)==null?void 0:n.items)||[]},Qc=async(r,t,e)=>{var n;const a=await b.getShadowGraphqlClient().query({query:qa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}});return((n=a==null?void 0:a.data.customerTransactionsFeed)==null?void 0:n.items)||[]},Nc=async(r,t,e)=>{var n;const a=await b.getShadowGraphqlClient().query({query:qa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}});return((n=a==null?void 0:a.data.customerTransactionsFeed)==null?void 0:n.items)||[]},Rc=async(r,t,e)=>{var n;const a=await b.getShadowGraphqlClient().query({query:bc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r,offset:e,limit:t}});return((n=a==null?void 0:a.data.customerBundlesFeed)==null?void 0:n.items)||[]};(function(){try{if(typeof document<"u"){var r=document.createElement("style");r.appendChild(document.createTextNode("#spiffThemeWrapper{width:100%;height:100%}")),document.head.appendChild(r)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();var qr=(r=>(r.Manual="Manual",r.OnStart="OnStart",r.OnQuit="OnQuit",r.OnEnd="OnEnd",r))(qr||{}),Wr=(r=>(r.Email="Email",r.FirstName="FirstName",r.LastName="LastName",r.Phone="Phone",r.Apartment="Apartment",r.City="City",r.Country="Country",r.OrganizationName="OrganizationName",r.PostCode="PostCode",r.State="State",r.StreetAddress="StreetAddress",r.DesignName="DesignName",r.PurchaseOrder="PurchaseOrder",r.DispatchDate="DispatchDate",r.Stakeholders="Stakeholders",r))(Wr||{}),J;J={__e:function(r,t,e,a){for(var n,i,s;t=t.__;)if((n=t.__c)&&!n.__)try{if((i=n.constructor)&&i.getDerivedStateFromError!=null&&(n.setState(i.getDerivedStateFromError(r)),s=n.__d),n.componentDidCatch!=null&&(n.componentDidCatch(r,a||{}),s=n.__d),s)return n.__E=n}catch(o){r=o}throw r}},typeof Promise=="function"&&Promise.prototype.then.bind(Promise.resolve());var lt,_e,dn,jr=[],Xe=[],An=J.__b,un=J.__r,hn=J.diffed,gn=J.__c,mn=J.unmount;function Oc(){for(var r;r=jr.shift();)if(r.__P&&r.__H)try{r.__H.__h.forEach(ye),r.__H.__h.forEach(fa),r.__H.__h=[]}catch(t){r.__H.__h=[],J.__e(t,r.__v)}}J.__b=function(r){lt=null,An&&An(r)},J.__r=function(r){un&&un(r);var t=(lt=r.__c).__H;t&&(_e===lt?(t.__h=[],lt.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.__V=Xe,e.__N=e.i=void 0})):(t.__h.forEach(ye),t.__h.forEach(fa),t.__h=[])),_e=lt},J.diffed=function(r){hn&&hn(r);var t=r.__c;t&&t.__H&&(t.__H.__h.length&&(jr.push(t)!==1&&dn===J.requestAnimationFrame||((dn=J.requestAnimationFrame)||$c)(Oc)),t.__H.__.forEach(function(e){e.i&&(e.__H=e.i),e.__V!==Xe&&(e.__=e.__V),e.i=void 0,e.__V=Xe})),_e=lt=null},J.__c=function(r,t){t.some(function(e){try{e.__h.forEach(ye),e.__h=e.__h.filter(function(a){return!a.__||fa(a)})}catch(a){t.some(function(n){n.__h&&(n.__h=[])}),t=[],J.__e(a,e.__v)}}),gn&&gn(r,t)},J.unmount=function(r){mn&&mn(r);var t,e=r.__c;e&&e.__H&&(e.__H.__.forEach(function(a){try{ye(a)}catch(n){t=n}}),e.__H=void 0,t&&J.__e(t,e.__v))};var pn=typeof requestAnimationFrame=="function";function $c(r){var t,e=function(){clearTimeout(a),pn&&cancelAnimationFrame(t),setTimeout(r)},a=setTimeout(e,100);pn&&(t=requestAnimationFrame(e))}function ye(r){var t=lt,e=r.__c;typeof e=="function"&&(r.__c=void 0,e()),lt=t}function fa(r){var t=lt;r.__c=r.__(),lt=t}const Hr=w.gql`
|
|
2550
2550
|
fragment AddressValidationResultFields on AddressValidationResult {
|
|
2551
2551
|
addressComplete
|
|
2552
2552
|
address {
|
|
@@ -2580,14 +2580,14 @@
|
|
|
2580
2580
|
...AddressValidationResultFields
|
|
2581
2581
|
}
|
|
2582
2582
|
}
|
|
2583
|
-
`,
|
|
2583
|
+
`,Uc=w.gql`
|
|
2584
2584
|
${Wa}
|
|
2585
2585
|
query GetAddressValidationJobs($ids: [String!]!) {
|
|
2586
2586
|
addressValidationJobs(ids: $ids) {
|
|
2587
2587
|
...AddressValidationJobFields
|
|
2588
2588
|
}
|
|
2589
2589
|
}
|
|
2590
|
-
|
|
2590
|
+
`,Lc=w.gql`
|
|
2591
2591
|
${Wa}
|
|
2592
2592
|
query GetRecipientsWithAddressValidationJobs($ids: [String!]!) {
|
|
2593
2593
|
recipients(ids: $ids) {
|
|
@@ -2597,19 +2597,19 @@
|
|
|
2597
2597
|
}
|
|
2598
2598
|
}
|
|
2599
2599
|
}
|
|
2600
|
-
`,
|
|
2600
|
+
`,Vc=w.gql`
|
|
2601
2601
|
${Hr}
|
|
2602
2602
|
mutation ValidateRecipientAddress($id: String!) {
|
|
2603
2603
|
recipientValidate(id: $id) {
|
|
2604
2604
|
...AddressValidationResultFields
|
|
2605
2605
|
}
|
|
2606
2606
|
}
|
|
2607
|
-
`,
|
|
2607
|
+
`,zc=w.gql`
|
|
2608
2608
|
${Wa}
|
|
2609
2609
|
mutation BatchValidateRecipientAddress($ids: [String!]!) {
|
|
2610
2610
|
recipientValidateBatch(ids: $ids) {
|
|
2611
2611
|
...AddressValidationJobFields
|
|
2612
2612
|
}
|
|
2613
2613
|
}
|
|
2614
|
-
`;var Yr=(r=>(r.Confirmed="Confirmed",r.Plausible="Plausible",r.Unlikely="Unlikely",r))(Yr||{}),Jr=(r=>(r.Created="Created",r.Processing="Processing",r.Completed="Completed",r.Failed="Failed",r.Cancelled="Cancelled",r))(Jr||{});const
|
|
2614
|
+
`;var Yr=(r=>(r.Confirmed="Confirmed",r.Plausible="Plausible",r.Unlikely="Unlikely",r))(Yr||{}),Jr=(r=>(r.Created="Created",r.Processing="Processing",r.Completed="Completed",r.Failed="Failed",r.Cancelled="Cancelled",r))(Jr||{});const Gc=async r=>{const t=r.map(a=>{var n;return(n=a.getWorkflowManager().getTransaction().recipient)==null?void 0:n.id}).filter(a=>!!a),e=await b.getShadowGraphqlClient().query({query:Lc,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return r.map(a=>{var i,s,o,l;const n=(i=a.getWorkflowManager().getTransaction().recipient)==null?void 0:i.id;if(n)return(l=(o=(s=e.data)==null?void 0:s.recipients)==null?void 0:o.find(c=>c.id===n))==null?void 0:l.addressValidationJob})},qc=async r=>{var e;return(e=(await b.getShadowGraphqlClient().query({query:Uc,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:r}})).data)==null?void 0:e.addressValidationJobs},Wc=async r=>{var e,a;return(e=r.getWorkflowManager().getTransaction().recipient)!=null&&e.id?(a=(await b.getShadowGraphqlClient().mutate({mutation:Vc,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r.getWorkflowManager().getTransaction().recipient.id}})).data)==null?void 0:a.recipientValidate:void 0},jc=async r=>{const t=r.map(a=>{var n;return(n=a.getWorkflowManager().getTransaction().recipient)==null?void 0:n.id}).filter(a=>!!a),e=await b.getShadowGraphqlClient().mutate({mutation:zc,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return r.map(a=>{var i,s,o;const n=(i=a.getWorkflowManager().getTransaction().recipient)==null?void 0:i.id;if(n)return(o=(s=e.data)==null?void 0:s.recipientValidateBatch)==null?void 0:o.find(l=>l.entityId===n)})};exports.AddonHandle=Pe;exports.AddressValidationJobStatus=Jr;exports.AddressValidationResultConfirmationLevel=Yr;exports.ArrayInput=tc;exports.AspectType=Z;exports.AssetNotFoundError=mt;exports.AssetType=Kt;exports.BringForwardCommand=co;exports.BringToBackCommand=lo;exports.BringToFrontCommand=oo;exports.BundleDesignCreationCartAddMode=vn;exports.CanvasCommand=O;exports.CollectionProduct=jt;exports.ColorOptionGlobalPropertyHandle=ma;exports.CommandContext=tr;exports.ConversionDataType=Wr;exports.ConversionLocation=qr;exports.CreateElementCommand=G;exports.CreateLayoutCommand=ka;exports.DeleteElementCommand=Ct;exports.DigitalContentStepHandle=Sr;exports.FileUploadGlobalPropertyHandle=Fr;exports.FlowExecutionNodeResult=Ht;exports.FlowExecutionResult=Or;exports.FlowService=Rr;exports.FontAlignmentCommand=sr;exports.FontColorCommand=rr;exports.FontSizeCommand=ir;exports.FontSourceCommand=Aa;exports.FrameService=Vr;exports.FrameStep=zr;exports.FrameStepHandle=Gr;exports.GlobalPropertyHandle=$e;exports.GroupCommand=$;exports.IllustrationStepHandle=hr;exports.InformationMessageType=ue;exports.InformationStepHandle=yr;exports.IntegrationProduct=pa;exports.IntegrationType=Bn;exports.LayoutElementFactory=Zs;exports.LayoutElementType=T;exports.LayoutNotFoundError=j;exports.LayoutRenderingPurpose=Qt;exports.MaterialStepHandle=gr;exports.MisconfigurationError=Zt;exports.MockWorkflowManager=fc;exports.ModelStepHandle=mr;exports.ModuleStepHandle=vr;exports.MoveCommand=to;exports.ObjectInput=za;exports.ObjectInputType=$r;exports.OptionGlobalPropertyHandle=Ua;exports.OptionNotFoundError=Xt;exports.ParseError=vt;exports.PictureStepHandle=pr;exports.ProductCameraRig=bn;exports.ProductCollection=La;exports.ProductCollectionProductSortKey=Tr;exports.ProductWorkflow=Tt;exports.PromiseCache=$t;exports.PromiseQueue=ba;exports.QuestionStepHandle=fr;exports.QueueablePromise=Ba;exports.ResizeCommand=ao;exports.ResourceNotFoundError=Nt;exports.RotateCommand=eo;exports.ScaleAxis=q;exports.SendBackwardsCommand=Ao;exports.ShapeStepHandle=Cr;exports.ShareActionType=En;exports.SpiffCommerceClient=uc;exports.StakeholderType=_t;exports.StepAspectType=Sn;exports.StepHandle=nt;exports.StepType=P;exports.TextAlgorithm=It;exports.TextChangeCommand=or;exports.TextGlobalPropertyHandle=kr;exports.TextInput=Zl;exports.TextStepHandle=wr;exports.Transform=Nr;exports.TransformCollection=Qr;exports.UnhandledBehaviorError=V;exports.UnitOfMeasurement=In;exports.UpdateImageSourceCommand=io;exports.Variant=rt;exports.WorkflowExperienceEventType=Pr;exports.WorkflowExperienceImpl=Dr;exports.assetService=U;exports.browserColorToHex=On;exports.cmPerPixel=Rs;exports.createDesign=Ir;exports.currentDirection=Ts;exports.dataUrlFromExternalUrl=hi;exports.designService=we;exports.determineCorrectFontSizeAndLines=Jt;exports.digitalContentStepService=Ma;exports.domParser=ct;exports.duplicateBundle=Dc;exports.duplicateTransaction=xc;exports.fetchAsString=tt;exports.findAngle=Is;exports.findElement=L;exports.findPmsColors=ki;exports.frameDataCache=kt;exports.frameStepService=ut;exports.generate=N;exports.generateCommands=xr;exports.generateSVGWithUnknownColors=st;exports.generateStateFromDesignInputSteps=$l;exports.getAddressValidationJobs=qc;exports.getAttributesFromArrayBuffer=ie;exports.getAxisAlignedBoundingBox=bs;exports.getBoundedOffsets=Lr;exports.getBundleThemeConfiguration=mc;exports.getCustomer=Fc;exports.getCustomerBundles=kc;exports.getElementVertices=Qs;exports.getFrameData=ce;exports.getGlobalPropertyStateForBundle=No;exports.getIntegration=Ur;exports.getNEPoint=ks;exports.getNWPoint=Fs;exports.getOrderedTransactions=Qc;exports.getOverrideThemeConfiguration=gc;exports.getPointOfRotation=xs;exports.getProductCollections=Hl;exports.getSEPoint=Ms;exports.getSvgElement=Oe;exports.getTemplateBundles=Rc;exports.getTemplateTransactions=Nc;exports.getTransaction=hc;exports.getTransactionThemeConfiguration=pc;exports.getTransactionsForBundle=Mc;exports.getTrueCoordinates=Ds;exports.getUnorderedTransactions=Tc;exports.getValidationJobsForWorkflowExperiences=Gc;exports.getWorkflow=cc;exports.getWorkflows=Ga;exports.graphQlManager=b;exports.illustrationStepService=Yt;exports.isCloseToValue=Ps;exports.loadFont=Pt;exports.matchHexToPms=Di;exports.materialStepService=Ta;exports.metafieldManager=Mr;exports.mmPerPixel=Ns;exports.modelStepService=Qa;exports.modifySVGColors=Qe;exports.moduleStepService=Na;exports.nameBundle=Ic;exports.nameTransaction=Pc;exports.optionService=K;exports.outlineFontsInSvg=Vs;exports.patternImageDataCache=dt;exports.persistenceService=M;exports.pictureStepService=Ra;exports.pmsToRgb=Pi;exports.questionStepService=Oa;exports.registerFetchImplementation=li;exports.registerWindowImplementation=oi;exports.rehydrateSerializedLayout=da;exports.rgbToPms=Rn;exports.rotateAroundPoint=Wt;exports.sanitizeSvgTree=Te;exports.setBearerAuthenticationToken=Qn;exports.setCanvasModule=ya;exports.shapeStepService=Mt;exports.shortenUrl=lr;exports.spiffCoreConfiguration=At;exports.stepAspectValuesToDesignInputSteps=Ol;exports.svgColorValueToDefinition=ia;exports.svgStringDimensions=Fa;exports.svgToDataUrl=Me;exports.textStepService=W;exports.toast=dr;exports.validateWorkflowExperienceRecipient=Wc;exports.validateWorkflowExperienceRecipients=jc;exports.xmlSerializer=wt;
|
|
2615
2615
|
//# sourceMappingURL=index.js.map
|