@spiffcommerce/core 36.0.0 → 36.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.cjs +118 -110
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.mjs +566 -549
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -183,7 +183,15 @@
|
|
|
183
183
|
...OptionFields
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
`,No=
|
|
186
|
+
`,No=C.gql`
|
|
187
|
+
query GetTagsMany($ids: [String!]!) {
|
|
188
|
+
tagsMany(entityIds: $ids) {
|
|
189
|
+
id
|
|
190
|
+
entityId
|
|
191
|
+
name
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
`,Qo=async n=>{const t=await S.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{ids:n}});return t.data.options.forEach(e=>{e.colorProfile&&W.cacheAsset(e.colorProfile),e.variants?.forEach(a=>{a.asset&&W.cacheAsset(a.asset),a.thumbnail&&W.cacheAsset(a.thumbnail),a.material&&W.cacheMaterial(a.material)})}),t.data.options},Oo=async(n,t)=>(await t).find(a=>a.id===n),ta=async n=>{const t=new Map(n.map(i=>[i,ie.get({id:i})])),e=n.filter(i=>t.get(i)===void 0);if(e.length>0){const i=Qo(e);e.forEach(r=>t.set(r,ie.set({id:r},Oo(r,i))))}return(await Promise.all(n.map(i=>t.get(i)))).filter(i=>i!==void 0)},mn=n=>n?n.versions?.find(e=>e.name==="thumbnail")?.link||n.fileLink:void 0,pn=(n,t,e)=>{if(n.length===1)return n[0];if(e){const a=n.find(i=>i.id===e);if(a)return a}if(t.defaultVariant!==void 0)return n.find(a=>a.id===t.defaultVariant?.id)};class Ro{constructor(){this.getDefaultVariant=async(t,e)=>{const a=t?.variants;if(a)return pn(a,t,e);const r=(await this.getOption(t.id))?.variants;if(r)return pn(r,t,e)},this.getTagsForAssets=async t=>{const e=t?.map(o=>o.asset?.key)||[],a=t?.map(o=>o.material?.id)||[],i=[...e,...a].filter(o=>!!o);return i.length===0?[]:(await S.getShadowGraphqlClient().query({query:No,errorPolicy:"all",variables:{ids:i}})).data.tagsMany}}async getOption(t){return t?(await ta([t]))[0]:void 0}async getOptions(t){return ta(t)}async getOptionForStep(t){return this.ensureFullOption(t.option)}async ensureFullOption(t){return t?.variants?t:t?.id?(await ta([t.id]))[0]:void 0}async getAssetTileImageForVariant(t){const e=mn(t.thumbnail)??mn(t.asset);return e||(t.material?t.material.id:"")}}const P=new Ro,ci=C.gql`
|
|
187
195
|
fragment ActiveIntegrationFields on Integration {
|
|
188
196
|
id
|
|
189
197
|
logo
|
|
@@ -271,7 +279,7 @@
|
|
|
271
279
|
}
|
|
272
280
|
}
|
|
273
281
|
}
|
|
274
|
-
|
|
282
|
+
`,$o=C.gql`
|
|
275
283
|
${di}
|
|
276
284
|
mutation CreateTransactions(
|
|
277
285
|
$inputs: [TransactionCreateInput]!
|
|
@@ -317,7 +325,7 @@
|
|
|
317
325
|
precedence
|
|
318
326
|
url
|
|
319
327
|
}
|
|
320
|
-
|
|
328
|
+
`,Uo=C.gql`
|
|
321
329
|
${Ge}
|
|
322
330
|
${de}
|
|
323
331
|
${ci}
|
|
@@ -409,7 +417,7 @@
|
|
|
409
417
|
}
|
|
410
418
|
}
|
|
411
419
|
}
|
|
412
|
-
`,
|
|
420
|
+
`,Vo=C.gql`
|
|
413
421
|
${ui}
|
|
414
422
|
${Ai}
|
|
415
423
|
${di}
|
|
@@ -461,32 +469,32 @@
|
|
|
461
469
|
integrationProductId
|
|
462
470
|
}
|
|
463
471
|
}
|
|
464
|
-
`,
|
|
472
|
+
`,Lo=C.gql`
|
|
465
473
|
mutation UpdateTransactionWorkflowState($id: String!, $workflowState: String!) {
|
|
466
474
|
transactionUpdate(id: $id, workflowState: $workflowState) {
|
|
467
475
|
id
|
|
468
476
|
}
|
|
469
477
|
}
|
|
470
|
-
`,
|
|
478
|
+
`,qo=C.gql`
|
|
471
479
|
mutation UpdateTransactionQuantity($id: String!, $quantity: Int) {
|
|
472
480
|
transactionUpdate(id: $id, quantity: $quantity) {
|
|
473
481
|
id
|
|
474
482
|
}
|
|
475
483
|
}
|
|
476
|
-
`,
|
|
484
|
+
`,zo=C.gql`
|
|
477
485
|
mutation UpdateTransactionWorkflow($id: String!, $workflowId: String!) {
|
|
478
486
|
transactionUpdate(id: $id, workflowId: $workflowId) {
|
|
479
487
|
id
|
|
480
488
|
}
|
|
481
489
|
}
|
|
482
|
-
`,
|
|
490
|
+
`,Go=C.gql`
|
|
483
491
|
${de}
|
|
484
492
|
query ReadConversionConfigurationQuery($id: String!) {
|
|
485
493
|
conversionConfiguration(id: $id) {
|
|
486
494
|
...ConversionConfigurationFields
|
|
487
495
|
}
|
|
488
496
|
}
|
|
489
|
-
`,
|
|
497
|
+
`,jo=C.gql`
|
|
490
498
|
${de}
|
|
491
499
|
query ReadTransactionForDesignCreation($id: String!) {
|
|
492
500
|
transactions(ids: [$id]) {
|
|
@@ -545,7 +553,7 @@
|
|
|
545
553
|
workflowViewerReadOnlyLink
|
|
546
554
|
}
|
|
547
555
|
}
|
|
548
|
-
`,
|
|
556
|
+
`,Ho=C.gql`
|
|
549
557
|
${Ai}
|
|
550
558
|
query ReadTransactionForShareActions($id: String!) {
|
|
551
559
|
transactions(ids: [$id]) {
|
|
@@ -556,7 +564,7 @@
|
|
|
556
564
|
}
|
|
557
565
|
}
|
|
558
566
|
}
|
|
559
|
-
`,
|
|
567
|
+
`,Wo=C.gql`
|
|
560
568
|
query ConfirmWorkflowStates($transactions: [TransactionConfirmInput!]!) {
|
|
561
569
|
transactionConfirmWorkflowStates(transactions: $transactions)
|
|
562
570
|
}
|
|
@@ -643,14 +651,14 @@
|
|
|
643
651
|
`:""}
|
|
644
652
|
}
|
|
645
653
|
}
|
|
646
|
-
`,
|
|
654
|
+
`,Yo=n=>C.gql`
|
|
647
655
|
${hi(n)}
|
|
648
656
|
query GetIntegrationProducts($ids: [String!]!) {
|
|
649
657
|
integrationProducts(ids: $ids) {
|
|
650
658
|
...IntegrationProductFields
|
|
651
659
|
}
|
|
652
660
|
}
|
|
653
|
-
`,
|
|
661
|
+
`,Jo=n=>C.gql`
|
|
654
662
|
${hi(n)}
|
|
655
663
|
query GetIntegrationProductFromExternalIds($externalIntegrationId: String!, $externalProductId: String!) {
|
|
656
664
|
integrationProductFromExternalIds(
|
|
@@ -660,7 +668,7 @@
|
|
|
660
668
|
...IntegrationProductFields
|
|
661
669
|
}
|
|
662
670
|
}
|
|
663
|
-
`,
|
|
671
|
+
`,Ko=C.gql`
|
|
664
672
|
${ui}
|
|
665
673
|
query ReadTransactionForStakeholders($id: String!) {
|
|
666
674
|
transactions(ids: [$id]) {
|
|
@@ -672,11 +680,11 @@
|
|
|
672
680
|
}
|
|
673
681
|
}
|
|
674
682
|
}
|
|
675
|
-
`,
|
|
683
|
+
`,_o=C.gql`
|
|
676
684
|
mutation FinalizeUpdateTransaction($transactionId: String!) {
|
|
677
685
|
transactionFinalizeUpdate(transactionId: $transactionId)
|
|
678
686
|
}
|
|
679
|
-
`,
|
|
687
|
+
`,Xo=C.gql`
|
|
680
688
|
fragment RegionFields on Region {
|
|
681
689
|
width
|
|
682
690
|
top
|
|
@@ -694,7 +702,7 @@
|
|
|
694
702
|
height
|
|
695
703
|
}
|
|
696
704
|
}
|
|
697
|
-
`,
|
|
705
|
+
`,Zo=C.gql`
|
|
698
706
|
fragment LookAtAnimationFields on LookAtAnimation {
|
|
699
707
|
latDeg
|
|
700
708
|
lonDeg
|
|
@@ -705,7 +713,7 @@
|
|
|
705
713
|
z
|
|
706
714
|
}
|
|
707
715
|
}
|
|
708
|
-
`,
|
|
716
|
+
`,ts=C.gql`
|
|
709
717
|
fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
|
|
710
718
|
antiAliasing {
|
|
711
719
|
samples
|
|
@@ -789,20 +797,20 @@
|
|
|
789
797
|
weight
|
|
790
798
|
}
|
|
791
799
|
}
|
|
792
|
-
`,
|
|
800
|
+
`,es=C.gql`
|
|
793
801
|
fragment ModelAnimationFields on ModelAnimation {
|
|
794
802
|
from
|
|
795
803
|
to
|
|
796
804
|
loop
|
|
797
805
|
name
|
|
798
806
|
}
|
|
799
|
-
`,
|
|
807
|
+
`,as=n=>C.gql`
|
|
800
808
|
${ze(n)}
|
|
801
809
|
${ko}
|
|
802
|
-
${_o}
|
|
803
810
|
${Xo}
|
|
804
811
|
${Zo}
|
|
805
812
|
${ts}
|
|
813
|
+
${es}
|
|
806
814
|
query GetWorkflows($ids: [String!]!) {
|
|
807
815
|
workflows(ids: $ids) {
|
|
808
816
|
partner {
|
|
@@ -1256,14 +1264,14 @@
|
|
|
1256
1264
|
}
|
|
1257
1265
|
}
|
|
1258
1266
|
}
|
|
1259
|
-
`,
|
|
1267
|
+
`,ns=C.gql`
|
|
1260
1268
|
${je}
|
|
1261
1269
|
query GetMarketplaceThemeInstallConfiguration($themeConfigurationId: String!, $themeInstallId: String!) {
|
|
1262
1270
|
marketplaceThemeInstallConfiguration(id: $themeConfigurationId, themeInstallId: $themeInstallId, raw: false) {
|
|
1263
1271
|
...MarketplaceThemeInstallConfigurationFields
|
|
1264
1272
|
}
|
|
1265
1273
|
}
|
|
1266
|
-
`,
|
|
1274
|
+
`,is=C.gql`
|
|
1267
1275
|
${ci}
|
|
1268
1276
|
${je}
|
|
1269
1277
|
query GetCurrentIntegration($themeConfigurationId: String) {
|
|
@@ -1276,7 +1284,7 @@
|
|
|
1276
1284
|
...ActiveIntegrationFields
|
|
1277
1285
|
}
|
|
1278
1286
|
}
|
|
1279
|
-
`,
|
|
1287
|
+
`,rs=C.gql`
|
|
1280
1288
|
${je}
|
|
1281
1289
|
query ReadTransactionForMarketplaceTheme($id: String!) {
|
|
1282
1290
|
transactions(ids: [$id]) {
|
|
@@ -1285,7 +1293,7 @@
|
|
|
1285
1293
|
}
|
|
1286
1294
|
}
|
|
1287
1295
|
}
|
|
1288
|
-
`,
|
|
1296
|
+
`,os=C.gql`
|
|
1289
1297
|
${je}
|
|
1290
1298
|
query ReadBundleForMarketplaceTheme($id: String!) {
|
|
1291
1299
|
bundles(ids: [$id]) {
|
|
@@ -1294,14 +1302,14 @@
|
|
|
1294
1302
|
}
|
|
1295
1303
|
}
|
|
1296
1304
|
}
|
|
1297
|
-
`,
|
|
1305
|
+
`,ss=C.gql`
|
|
1298
1306
|
mutation CreateOrder($orderItems: [OrderItemInput]!) {
|
|
1299
1307
|
orderCreate(orderItems: $orderItems, paid: false, generateInternalId: true) {
|
|
1300
1308
|
id
|
|
1301
1309
|
internalId
|
|
1302
1310
|
}
|
|
1303
1311
|
}
|
|
1304
|
-
`,
|
|
1312
|
+
`,ls=C.gql`
|
|
1305
1313
|
query CurrencyConversion($from: String!, $to: String!) {
|
|
1306
1314
|
currencyConversion(from: $from, to: $to) {
|
|
1307
1315
|
rateFrom
|
|
@@ -1309,7 +1317,7 @@
|
|
|
1309
1317
|
timestamp
|
|
1310
1318
|
}
|
|
1311
1319
|
}
|
|
1312
|
-
`,ea=[E.SilentIllustration,E.ProductOverlay],fn=n=>{const t=[];for(const a of n.steps){const i=
|
|
1320
|
+
`,ea=[E.SilentIllustration,E.ProductOverlay],fn=n=>{const t=[];for(const a of n.steps){const i=cs(a.stepName,n.stepGroups);if(!i)throw new Error("Workflow step does not belong to a group, all steps must belong to a group. Step: "+a.stepName);const r=t.find(o=>o.name===i.name);r?ea.includes(a.type)?r.silentSteps.push(a):r.renderableSteps.push(a):t.push({name:i.name,title:i.name,renderableSteps:ea.includes(a.type)?[]:[a],silentSteps:ea.includes(a.type)?[a]:[]})}const e="workflow.steps.finish.confirmDesign";return t.push({name:"Finish",title:e,renderableSteps:[{type:E.Finish,stepName:"Finish",stepTitle:e,helpText:"",data:{modelAnimation:n.finalizeStepConfig?n.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:n.finalizeStepConfig?n.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),t},cs=(n,t)=>t.find(e=>e.stepNames.includes(n)),Bt=(n,t)=>(n.conditions||[]).every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const i=a.selectedVariants;return e.requiredVariantSelections.some(r=>i.find(o=>o.id===r)!==void 0)}return!1}),ds=(n,t)=>{const e={name:n.name,title:n.title,renderableSteps:n.renderableSteps.filter(a=>Bt(a,t)),silentSteps:n.silentSteps.filter(a=>Bt(a,t))};return e.silentSteps.length===0&&e.renderableSteps.length===0?null:e},dt=(n,t)=>n.map(e=>ds(e,t)).filter(e=>e!==null),us=async(n,t,e=!1)=>{const a=dt(n,t),i=[];for(const o of a)for(const s of o.renderableSteps){let l=0;if(s.type!=="Finish"&&s.type!=="Module"){let c;s.option?.variants?(c=s.option,l=c?.variants?.length||0):(c=await P.getOption(s.option?.id),l=c?.variants?.length||0)}s.silent||(s.type===E.Model||s.type===E.Material||s.type===E.Picture||s.type===E.Shape?(l>1||e)&&i.push(s.stepName):i.push(s.stepName))}const r=a.filter(o=>o.renderableSteps.filter(l=>i.includes(l.stepName)).length>0);for(const o of r)o.renderableSteps=o.renderableSteps.filter(s=>i.includes(s.stepName));return r};class Ua{constructor(){this.timestamp=Date.now()}}class Va{constructor(t,e=!0){this.queue=[],this.activePromise=void 0,this.queueMaxSize=void 0,this.queueMaxSize=t,this.isEnabled=e}enqueue(t){if(this.queue.push(t),this.queueMaxSize!==void 0&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let a=0;a<e;++a)this.queue.shift()}this.isEnabled&&(this.activePromise||(this.activePromise=this.dequeue()))}get enabled(){return this.isEnabled}set enabled(t){!this.isEnabled&&t&&!this.activePromise&&this.getRemainingQueueSize()>0&&(this.activePromise=this.dequeue()),this.isEnabled=t}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async dequeue(){const t=this.queue.shift();if(!t){this.activePromise=void 0;return}try{await t.execute()}catch(e){console.log(e)}finally{await this.dequeue()}}}const N=()=>{const n=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);return n()+n()+"-"+n()+"-"+n()+"-"+n()+"-"+n()+n()+n()},As=({backgroundColor:n,outlineColor:t,borderRadius:e,configuration:a,elements:i,height:r,maxHeight:o,maxWidth:s,outlineArea:l,position:c,preserveAspectRatio:d,viewBox:u,width:A})=>{const h=e||0,g=2*(l?.scale||1),p=u||{x:0,y:0,width:A,height:r},m=`${p.x} ${p.y} ${p.width} ${p.height}`,f=N(),y=a.purpose===Ot.FreeDesign&&B.jsx("defs",{children:B.jsx("clipPath",{id:"viewboxClip",children:B.jsx("rect",{width:p.width,height:p.height,rx:h})})}),w=a.colorProfiles?.map((v,I)=>B.jsx("color-profile",{name:v.name,xlinkHref:v.key,children:" "},I)),F=i.map(v=>({...v,_renderingConfiguration:a,mask:l?`url(#viewmask-${f})`:void 0})),b=La(F);return B.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",preserveAspectRatio:d,width:A,height:r,style:{gridColumn:1,gridRow:1,maxWidth:s,maxHeight:o,position:c},viewBox:m,children:[w,y,!!n&&B.jsx("rect",{id:"layout-background",width:p.width,height:p.height,fill:n,rx:h}),B.jsx("g",{id:"element-group",clipPath:a.purpose===Ot.FreeDesign?"url(#viewboxClip)":void 0,children:b.map(v=>vi(v)).filter(v=>!!v)}),l&&B.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"none",stroke:l.hidden?"none":t||"#aaaaaa",strokeWidth:g/2,strokeDasharray:`${g*2} ${g}`}),l&&B.jsxs("mask",{id:`viewmask-${f}`,children:[B.jsx("rect",{x:p.x,y:p.y,width:p.width,height:p.height,fill:"black"}),B.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"white"})]})]})},hs=(n,t,e,a,i)=>{const r=St(i),o=e/2,s=a/2,l=n+o,c=t+s,d=Math.sin(r),u=Math.cos(r),A=o,h=o,g=-s,p=s,m=A*u-g*d,f=h*u-p*d,y=A*d+g*u,w=h*d+p*u,F=Math.max(Math.abs(m),Math.abs(f)),b=Math.max(Math.abs(y),Math.abs(w));return{minX:l-F,maxX:l+F,minY:c-b,maxY:c+b}},gs=(n,t,e)=>{const a=Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2)),i=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),r=Math.sqrt(Math.pow(e.x-n.x,2)+Math.pow(e.y-n.y,2));return Math.acos((i*i+a*a-r*r)/(2*i*a))*(180/Math.PI)},St=n=>n*(Math.PI/180),ms=(n,t,e)=>Math.abs(n-t)<e,ps=(n,t,e)=>{const a=Math.sin(St(e)),i=Math.cos(St(e));return{x:(n.x-t.x)*i-(n.y-t.y)*a+t.x,y:(n.x-t.x)*a+(n.y-t.y)*i+t.y}},fs=(n,t)=>({x:(n.x+t.x)/2,y:(n.y+t.y)/2}),Cs=(n,t,e,a)=>({x:n.x+t?.x*e,y:n.y+t?.y*a}),ws=(n,t,e,a)=>({x:n.x+(t?.x+t?.width)*e,y:n.y+t?.y*a}),ys=(n,t,e,a)=>({x:n.x+(t?.x+t?.width)*e,y:n.y+(t?.y+t?.height)*a}),kt=n=>{switch(n){case H.North:return H.East;case H.East:return H.South;case H.South:return H.West;case H.West:return H.North;case H.Northwest:return H.Northeast;case H.Northeast:return H.Southeast;case H.Southeast:return H.Southwest;case H.Southwest:return H.Northwest}},Ss=(n,t)=>t>45&&t<=135?kt(n):t>135&&t<=225?kt(kt(n)):t>225&&t<=315?kt(kt(kt(n))):n,vs=(n,t={x:0,y:0},e={x:1,y:1})=>{const a=St(n.rotation),i={x:t.x+n.x*e.x,y:t.x+n.y*e.y},r={x:n.x+n.width,y:n.y},o={x:t.x+(n.x+n.width)*e.x,y:t.y+(n.height+n.y)*e.y},s={x:t.x+n.x*e.x,y:t.y+(n.height+n.y)*e.y},l={x:(s.x+o.x)/2,y:s.y-n.height*e.y/2};return{a:Ht(i,l,a),b:Ht(r,l,a),c:Ht(o,l,a),d:Ht(s,l,a),center:l}},Ht=(n,t,e)=>{const a=Math.sin(e),i=Math.cos(e);return{x:(n.x-t.x)*i-(n.y-t.y)*a+t.x,y:(n.x-t.x)*a+(n.y-t.y)*i+t.y}},Es=.352778,bs=.035277,gi=n=>{const t=n.rotation||0,e=St(t),a=Math.cos(e),i=-Math.sin(e);return B.jsx("g",{mask:n.stepName||n.productOverlay?void 0:n.mask,children:B.jsx("g",{transform:`
|
|
1313
1321
|
matrix(1, 0, 0, 1, ${n.x}, ${n.y})
|
|
1314
1322
|
matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
|
|
1315
1323
|
matrix(${a}, ${-i}, ${i}, ${a}, 0, 0)
|
|
@@ -1319,7 +1327,7 @@
|
|
|
1319
1327
|
matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
|
|
1320
1328
|
matrix(${i}, ${-r}, ${r}, ${i}, 0, 0)
|
|
1321
1329
|
matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
|
|
1322
|
-
`,children:[n._renderingConfiguration?.debug?B.jsx("rect",{stroke:"red",opacity:.3,fill:"none",x:0,y:0,width:n.width,height:n.height}):void 0,o.map(l=>vi(l)).filter(l=>!!l).map(l=>B.jsx("g",{clipPath:`url(#${t})`,children:l}))]})]})},
|
|
1330
|
+
`,children:[n._renderingConfiguration?.debug?B.jsx("rect",{stroke:"red",opacity:.3,fill:"none",x:0,y:0,width:n.width,height:n.height}):void 0,o.map(l=>vi(l)).filter(l=>!!l).map(l=>B.jsx("g",{clipPath:`url(#${t})`,children:l}))]})]})},Is=n=>{const t=`spiff-frame-${n.id}`,e=`spiff-frame-threshold-${n.id}`,a=()=>{if(!n.pattern)return"";if(n.pattern.svg){const u=qe(n.pattern.svg,n.pattern.colors||{},!1);return Ve(u)}return n.pattern.src};if(!a())return B.jsx(B.Fragment,{});const i=()=>n.threshold?n.invertThreshold?"1 ".repeat(n.threshold)+"0 ".repeat(256-n.threshold):"0 ".repeat(n.threshold)+"1 ".repeat(256-n.threshold):"",r=()=>B.jsx(B.Fragment,{children:n.useThreshold&&B.jsx("defs",{children:B.jsxs("filter",{id:e,"color-interpolation-filters":"sRGB",children:[B.jsx("feColorMatrix",{type:"matrix",values:`
|
|
1323
1331
|
${n.thresholdSaturation} ${n.thresholdSaturation} ${n.thresholdSaturation} 0 0
|
|
1324
1332
|
${n.thresholdSaturation} ${n.thresholdSaturation} ${n.thresholdSaturation} 0 0
|
|
1325
1333
|
${n.thresholdSaturation} ${n.thresholdSaturation} ${n.thresholdSaturation} 0 0
|
|
@@ -1330,27 +1338,27 @@
|
|
|
1330
1338
|
matrix(${l}, ${-c}, ${c}, ${l}, 0, 0)
|
|
1331
1339
|
matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
|
|
1332
1340
|
matrix(${n.scaleX}, 0, 0, ${n.scaleY}, 0, 0)
|
|
1333
|
-
`,children:B.jsx(mi,{id:t,x:0,y:0,rotation:0,width:n.width,height:n.height,clipPath:n.path,children:d()})})})]})},pi=new Map;class
|
|
1341
|
+
`,children:B.jsx(mi,{id:t,x:0,y:0,rotation:0,width:n.width,height:n.height,clipPath:n.path,children:d()})})})]})},pi=new Map;class Bs{constructor(t){this.font=t,this.glyphsFromText=new Map,this.kerningValues=new Map,this.height=this.calculateApproximateHeight()}getFont(){return this.font}getGlyphs(t){const e=this.glyphsFromText.get(t);if(e)return e;const a=this.font.stringToGlyphs(t);return this.glyphsFromText.set(t,a),a}getApproximateHeight(){return this.height}getExactHeight(t){const e=this.font.stringToGlyphs(t);let a=0,i=0;return e.forEach(r=>{const o=r.getMetrics();a=Math.max(a,o.yMax),i=Math.min(i,o.yMin)}),a-i}getKerningValue(t,e){if(!t.name||!e.name)return;let a=this.kerningValues.get(t.name);a||(a=new Map,this.kerningValues.set(t.name,a));let i=a.get(e.name);return i||(i=this.font.getKerningValue(t,e),a.set(e.name,i)),i}calculateApproximateHeight(){const e=this.font.stringToGlyphs("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");let a=0,i=0;return e.forEach(r=>{const o=r.getMetrics();a=Math.max(a,o.yMax),i=Math.min(i,o.yMin)}),a-i}}const Ps=n=>n.substring(0,5).toLowerCase().trim()==="data:",aa=new Map,Ft=async n=>{if(aa.has(n))return aa.get(n);const e=(async()=>{try{return vt(n).getFont()}catch{if(Ps(n)){const a=_n(n),i=ga.parse(a);return Sa(n,i),i}else{const a=await $e(n,!0),i=ga.parse(a);return Sa(n,i),await Yr(i,n),i}}})();return aa.set(n,e),e},xs=n=>{const t=_n(n),e=ga.parse(t);return Sa(n,e),e},vt=n=>{const t=pi.get(n);if(t)return t;throw new Error("Font metrics unavailable for font")},Sa=(n,t)=>{const e=new Bs(t);return pi.set(n,e),e},Fs=async n=>{const t=ct(),e=t.parseFromString(n,"image/svg+xml"),a=e.firstElementChild,i=new Map;a.querySelectorAll("style").forEach(d=>{Rn.parse(d.innerHTML).stylesheet?.rules.forEach(A=>{if(A.type==="font-face"&&A.declarations){const h=A.declarations.find(m=>m.property==="font-family")?.value,p=A.declarations.find(m=>m.property==="src")?.value?.match(/'(https.*?)'/)?.[1];h&&p&&i.set(h,p)}})});const o=e.querySelectorAll("tspan");for(let d=0;d<o.length;d++){const u=o.item(d),A=u.closest("text"),h=u.closest("g"),g=A.getAttribute("font-family"),p=await Ft(i.get(g)),m=Mr.decode(u.innerHTML),f=A.getAttribute("fill"),y=A.getAttribute("stroke"),w=A.getAttribute("stroke-width"),F=p.getPath(m,0,0,parseInt(A.getAttribute("font-size")??"72")),b=F.getBoundingBox().x2-F.getBoundingBox().x1;let v=0;const I=u.getAttribute("text-anchor");I==="middle"?v=b/2:I==="end"&&(v=b);const M=p.getPath(m,parseFloat(u.getAttribute("x")??"0")-v,parseFloat(u.getAttribute("y")??"0"),parseInt(A.getAttribute("font-size")??"72"));M.fill=f,M.stroke=y,M.strokeWidth=parseFloat(w??"0");const R=M.toSVG(2),T=t.parseFromString(R,"image/svg+xml").firstElementChild;h.appendChild(T)}return e.querySelectorAll("text").forEach(d=>d.remove()),Et().serializeToString(a)},xe=(n,t,e,a)=>Math.max(Ts(n.join(`
|
|
1334
1342
|
`),e,a),t),Cn=(n,t,e,a,i,r)=>{const o=(r||wi)*i.getApproximateHeight(),s=t.split(`
|
|
1335
|
-
`);try{const l=s.flatMap(d=>be(d,n.width,a,i)),c=l.flatMap(d=>d.lines);return{lines:c,requiredHeight:l.flatMap(d=>d.lines).length*(a*o),fontSize:e,requiredWidth:xe(c,n.width,a,i)}}catch{const c=t.split("");return{lines:c,requiredHeight:c.length*(a*o),fontSize:e,requiredWidth:xe(c,n.width,a,i)}}},be=(n,t,e,a)=>{const i=Ct(n,e,a);if(i<=t)return{lines:[n],width:i};if(!(n.indexOf(" ")>-1)){if(n.length<=1)throw new Error(`Character ${n} is wider than region`);const d=Math.floor(n.length/2),u=be(n.slice(0,d),t,e,a),A=be(n.slice(d),t,e,a);return{lines:[...u.lines,...A.lines],width:Math.max(u.width,A.width)}}const o=n.split(" "),s=[];let l=-1/0,c=0;for(;c<o.length;){const d=o[c];if(Ct(d,e,a)>t){const u=be(d,t,e,a);s.push(...u.lines),l=Math.max(l,u.width),c++}else{const u=[d];l=Math.max(l,Ct(d,e,a));let A=c+1,h=!0;for(;A<o.length&&h;){const g=o[A],p=Ct(`${u.join(" ")} ${g}`,e,a);p<=t?(u.push(g),l=Math.max(l,p),A++):h=!1}s.push(u.join(" ")),c=A}}if(l<0)throw new Error(`No max width calculated for text: ${s}.`);return{lines:s,width:l}},
|
|
1343
|
+
`);try{const l=s.flatMap(d=>be(d,n.width,a,i)),c=l.flatMap(d=>d.lines);return{lines:c,requiredHeight:l.flatMap(d=>d.lines).length*(a*o),fontSize:e,requiredWidth:xe(c,n.width,a,i)}}catch{const c=t.split("");return{lines:c,requiredHeight:c.length*(a*o),fontSize:e,requiredWidth:xe(c,n.width,a,i)}}},be=(n,t,e,a)=>{const i=Ct(n,e,a);if(i<=t)return{lines:[n],width:i};if(!(n.indexOf(" ")>-1)){if(n.length<=1)throw new Error(`Character ${n} is wider than region`);const d=Math.floor(n.length/2),u=be(n.slice(0,d),t,e,a),A=be(n.slice(d),t,e,a);return{lines:[...u.lines,...A.lines],width:Math.max(u.width,A.width)}}const o=n.split(" "),s=[];let l=-1/0,c=0;for(;c<o.length;){const d=o[c];if(Ct(d,e,a)>t){const u=be(d,t,e,a);s.push(...u.lines),l=Math.max(l,u.width),c++}else{const u=[d];l=Math.max(l,Ct(d,e,a));let A=c+1,h=!0;for(;A<o.length&&h;){const g=o[A],p=Ct(`${u.join(" ")} ${g}`,e,a);p<=t?(u.push(g),l=Math.max(l,p),A++):h=!1}s.push(u.join(" ")),c=A}}if(l<0)throw new Error(`No max width calculated for text: ${s}.`);return{lines:s,width:l}},Ds=(n,t,e,a,i,r)=>{const o=(r??wi)*t.getApproximateHeight(),s=1/e.unitsPerEm,l=fi(n,s,t),c=n.length*o*s,d=a/l,u=i/c;return Math.min(u,d)},ks=(n,t,e,a)=>{const i=vt(t.fontData.assetUrl),r=i.getFont(),o=t.fontSize/r.unitsPerEm;if(!e)return Cn(t,n,t.fontSize,o,i,a);let s;if(t.text?s=t.text.split(`
|
|
1336
1344
|
`):s=t.input?.split(`
|
|
1337
|
-
`)??[""],e.input===n&&t.width===e.width&&t.height===e.height&&t.lineHeight===e.lineHeight)return{lines:s,requiredHeight:t.height,requiredWidth:xe(s,t.width,o,i),fontSize:t.fontSize};const l=t.width!==e.width!=(t.height!==e.height);return t.lineHeight===e.lineHeight&&!l&&e.input===n?{lines:s,requiredHeight:t.height,requiredWidth:xe(s,t.width,o,i),fontSize:
|
|
1338
|
-
`)),a},
|
|
1339
|
-
`),height:i.requiredHeight,width:i.requiredWidth,fontSize:i.fontSize,input:t}}else return{text:t}})()}:n,wi=1.1;function Nt(n,t){return yi(n,t.getTemplatingContext())}function yi(n,t){try{n=Tr.compile(n)(t)}catch(e){console.error("failed to render templated text",e)}return n}const
|
|
1345
|
+
`)??[""],e.input===n&&t.width===e.width&&t.height===e.height&&t.lineHeight===e.lineHeight)return{lines:s,requiredHeight:t.height,requiredWidth:xe(s,t.width,o,i),fontSize:t.fontSize};const l=t.width!==e.width!=(t.height!==e.height);return t.lineHeight===e.lineHeight&&!l&&e.input===n?{lines:s,requiredHeight:t.height,requiredWidth:xe(s,t.width,o,i),fontSize:Ds(s,i,r,t.width,t.height,a)}:Cn(t,n,t.fontSize,o,i,a)},Ms=(n,t,e,a,i)=>{const o=vt(t.assetUrl).getFont();let s={...n};const l={...n},c=fi(a,e/o.unitsPerEm,vt(t.assetUrl));return c&&c<s.width&&(l.width=c,i==="left"?(l.left+=Math.sin(s.rotation*Math.PI/360)*(s.width-c),l.top+=Math.sin(s.rotation*Math.PI/180)*(c-s.width)/2):i==="right"?l.left+=s.width-c:l.left+=(s.width-c)/2,a&&Ns(a,a).every(([d,u])=>d===u)&&(s=l)),s},na=1,Ct=(n,t,e)=>{let a=0;const i=e.getGlyphs(n);return i.forEach((r,o)=>{if(r.advanceWidth&&(a+=r.advanceWidth),o<i.length-1){const s=e.getKerningValue(r,i[o+1]);a+=s||0}}),a*=t,a},Ts=(n,t,e)=>{let a=0;const i=e.getGlyphs(n);return i.forEach((r,o)=>{if(r.advanceWidth&&(a=Math.max(a,r.advanceWidth)),o<i.length-1){const s=e.getKerningValue(r,i[o+1]);a=Math.max(a,s||0)}}),a*=t,a},fi=(n,t,e)=>{let a=0;return n.forEach(i=>{a=Math.max(a,Ct(i,t,e))}),a},wn={stripControlCharacters:!0,vertical:!1,uppercase:!1},Fe=(n,t=wn)=>{const e={...wn,...t};let a=n||"";return e.stripControlCharacters&&(a=a.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,"")),e.uppercase&&(a=a.toUpperCase()),e.vertical&&(a=a.split("").join(`
|
|
1346
|
+
`)),a},Ns=(n,t)=>n.map((e,a)=>[e,t[a]]),Qs=(n="center",t=!1)=>t?"center":n,Ci=n=>n==="left"?"start":n==="right"?"end":"middle",ue=(n,t,e)=>n.fontData?{...n,...(()=>{if(n.algorithm===xt.Traditional){const i=ks(t,n,e,n.lineHeight);return{text:i.lines.join(`
|
|
1347
|
+
`),height:i.requiredHeight,width:i.requiredWidth,fontSize:i.fontSize,input:t}}else return{text:t}})()}:n,wi=1.1;function Nt(n,t){return yi(n,t.getTemplatingContext())}function yi(n,t){try{n=Tr.compile(n)(t)}catch(e){console.error("failed to render templated text",e)}return n}const Os=n=>{const e=(n.rotation||0)*Math.PI/180,a=Math.cos(e),i=-Math.sin(e),r=`text-path-${n.id}`,o=`text-fill-${n.id}`,s=n.x+(n.curved?0:n.width/2),l=n.y+(n.curved?0:n.height/2),c=yi(n.text||"",n._renderingConfiguration?.templatingContext),d=c.split(`
|
|
1340
1348
|
`),u=n.strokeColor?.browserValue&&n.strokeThickness?n.strokeColor?.browserValue:void 0,A=n.strokeColor?.browserValue&&n.strokeThickness?n.strokeThickness:void 0;if(n.curved&&!n.paths||!n.fontData)return null;const h=()=>n.textFillImage?`url("#${o}")`:n._renderingConfiguration?.spotColors&&n.fillSpotColorDefinition?`${n.fill} ${ni(n.fillSpotColorDefinition)}`:n.fill;return B.jsxs(B.Fragment,{children:[B.jsxs("defs",{children:[n.textFillImage&&B.jsx("pattern",{id:o,patternUnits:"userSpaceOnUse",width:n.textFillImage.scale*n.textFillImage.width,height:n.textFillImage.scale*n.textFillImage.height,x:0,y:0,children:B.jsx("image",{href:n.textFillImage.src,xlinkHref:n.textFillImage.src,width:n.textFillImage.scale*n.textFillImage.width,height:n.textFillImage.scale*n.textFillImage.height})}),B.jsx("style",{type:"text/css",dangerouslySetInnerHTML:{__html:`
|
|
1341
1349
|
@font-face {
|
|
1342
1350
|
font-family: '${n.fontData.name}';
|
|
1343
1351
|
src: url('${n.fontData.assetUrl}') format('truetype');
|
|
1344
1352
|
}
|
|
1345
|
-
`}}),n.curved&&n.paths?B.jsx("path",{id:r,d:n.paths[0]}):void 0]}),n._renderingConfiguration?.debug?B.jsx("rect",{stroke:"blue",fill:"none",x:n.x,y:n.y,width:n.width,height:n.height}):void 0,B.jsx("g",{mask:n.stepName?void 0:n.mask,children:B.jsx("g",{transform:`matrix(${a}, ${-i}, ${i}, ${a}, ${s}, ${l})`,children:B.jsx("text",{xmlSpace:"preserve",fontFamily:`'${n.fontData.name}'`,fontSize:n.fontSize,fontStyle:"normal",fontWeight:"normal",fill:h(),style:{whiteSpace:"pre",userSelect:"none"},stroke:u,strokeWidth:A,children:n.curved?B.jsx(
|
|
1353
|
+
`}}),n.curved&&n.paths?B.jsx("path",{id:r,d:n.paths[0]}):void 0]}),n._renderingConfiguration?.debug?B.jsx("rect",{stroke:"blue",fill:"none",x:n.x,y:n.y,width:n.width,height:n.height}):void 0,B.jsx("g",{mask:n.stepName?void 0:n.mask,children:B.jsx("g",{transform:`matrix(${a}, ${-i}, ${i}, ${a}, ${s}, ${l})`,children:B.jsx("text",{xmlSpace:"preserve",fontFamily:`'${n.fontData.name}'`,fontSize:n.fontSize,fontStyle:"normal",fontWeight:"normal",fill:h(),style:{whiteSpace:"pre",userSelect:"none"},stroke:u,strokeWidth:A,children:n.curved?B.jsx($s,{text:c,curvedPathId:r,align:n.align}):d.map((g,p)=>B.jsx(Rs,{align:n.vertical?"center":n.align,fontSize:n.fontSize,thisLineIdx:p,amountLines:d.length,text:g,textboxHeight:n.height,textboxWidth:n.width,lineHeight:n.lineHeight,vertical:n.vertical,verticalAlign:n.verticalAlign,fontData:n.fontData},p))})})})]})},Rs=n=>{const t=()=>{if(n.lineHeight!==void 0)return n.lineHeight*n.fontSize;const i=vt(n.fontData.assetUrl),r=i.getFont(),o=n.fontSize/r.unitsPerEm;return i.getApproximateHeight()*o},e=()=>n.align==="left"?-n.textboxWidth/2:n.align==="right"?n.textboxWidth/2:0,a=()=>{const i=t(),r=n.textboxHeight/2;if(n.verticalAlign==="top")return-r+n.fontSize*3/4+n.thisLineIdx*i;if(n.verticalAlign==="bottom"){const s=n.amountLines-1-n.thisLineIdx;return r-n.fontSize/4-s*i}const o=(n.amountLines-1)/2;return(n.thisLineIdx-o)*i+n.fontSize/4};return B.jsx("tspan",{textAnchor:Ci(n.align),x:e(),y:`${a()}px`,children:n.text})},$s=n=>{const t=`#${n.curvedPathId}`,e=()=>n.align==="left"?"0%":n.align==="right"?"100%":"50%";return B.jsx("textPath",{startOffset:e(),textAnchor:Ci(n.align),href:t,xlinkHref:t,children:n.text})},Us=n=>{if(n.cachedObjectURL&&!n._renderingConfiguration?.omitCachedFields)return B.jsx(gi,{id:n.id,src:n.cachedObjectURL,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,preserveAspectRatio:"none",immutable:n.immutable,mask:n.stepName?void 0:n.mask});const t=n.rotation||0,e=St(t),a=Math.cos(e),i=-Math.sin(e),r=`
|
|
1346
1354
|
matrix(1, 0, 0, 1, ${n.x}, ${n.y})
|
|
1347
1355
|
matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
|
|
1348
1356
|
matrix(${a}, ${-i}, ${i}, ${a}, 0, 0)
|
|
1349
1357
|
matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
|
|
1350
|
-
`;if(!n.svg)throw new Error(`Illustration element ${n.id} (stepName ${n.stepName}) lacked svg from src ${n.src} at render time.`);return B.jsx("g",{mask:n.stepName?void 0:n.mask,children:B.jsx("g",{transform:r,dangerouslySetInnerHTML:{__html:$a(n.svg,n.width,n.height,n.colors,n._renderingConfiguration?.spotColors)}})})};class Si{constructor(){this.id=N(),this.stateCallbacks=[],this.prevCommands=[],this.nextCommands=[]}registerStateCallback(t){this.stateCallbacks.push(t)}unregisterStateCallback(t){this.stateCallbacks.filter(e=>e!==t)}getState(){return this.state}runStateCallbacks(){this.stateCallbacks.forEach(t=>t())}apply(t,e){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.nextCommands=[],e||this.prevCommands.push(t)}undo(){if(!this.state)return;const t=this.prevCommands.pop();if(!t)return;const e=t.undo();this.state={...this.state,transaction:e},this.nextCommands.push(t),this.runStateCallbacks()}redo(){if(!this.state)return;const t=this.nextCommands.pop();t&&(this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.prevCommands.push(t))}flattenSequence(t,e){const i=this.prevCommands.filter(r=>r.sequenceId===t).pop();i&&(this.prevCommands=this.prevCommands.filter(r=>r.sequenceId!==t),i?.overrideOldState(e),this.prevCommands.push(i))}getLayoutById(t){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const e=this.state.transaction?.layouts?.[t],a=e?.layout;if(!a)throw new Error(`No layout: ${t}`);const i=[...e?.elements||[]];return this.getLayoutDataWithState(a,i)}getAllLayouts(){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const t=[...Object.keys(this.state.transaction?.layouts)];return[...new Set(t)].map(a=>this.getLayoutById(a))}getLayoutDataWithState(t,e){return{layoutState:{layout:t,elements:e},getComponentWithProps:a=>He(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(i=>{a=new ja(i).apply(a)}),this.runStateCallbacks(),this.state={transaction:a}}commandReducer(t,e){const a=t.transaction||{layouts:{},serializableWorkflow:{steps:[]}};return{...t,transaction:e.apply(a)}}}const vi=n=>n.type===D.Image?B.jsx(gi,{...n},n.id):n.type===D.Frame?B.jsx(
|
|
1358
|
+
`;if(!n.svg)throw new Error(`Illustration element ${n.id} (stepName ${n.stepName}) lacked svg from src ${n.src} at render time.`);return B.jsx("g",{mask:n.stepName?void 0:n.mask,children:B.jsx("g",{transform:r,dangerouslySetInnerHTML:{__html:$a(n.svg,n.width,n.height,n.colors,n._renderingConfiguration?.spotColors)}})})};class Si{constructor(){this.id=N(),this.stateCallbacks=[],this.prevCommands=[],this.nextCommands=[]}registerStateCallback(t){this.stateCallbacks.push(t)}unregisterStateCallback(t){this.stateCallbacks.filter(e=>e!==t)}getState(){return this.state}runStateCallbacks(){this.stateCallbacks.forEach(t=>t())}apply(t,e){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.nextCommands=[],e||this.prevCommands.push(t)}undo(){if(!this.state)return;const t=this.prevCommands.pop();if(!t)return;const e=t.undo();this.state={...this.state,transaction:e},this.nextCommands.push(t),this.runStateCallbacks()}redo(){if(!this.state)return;const t=this.nextCommands.pop();t&&(this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.prevCommands.push(t))}flattenSequence(t,e){const i=this.prevCommands.filter(r=>r.sequenceId===t).pop();i&&(this.prevCommands=this.prevCommands.filter(r=>r.sequenceId!==t),i?.overrideOldState(e),this.prevCommands.push(i))}getLayoutById(t){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const e=this.state.transaction?.layouts?.[t],a=e?.layout;if(!a)throw new Error(`No layout: ${t}`);const i=[...e?.elements||[]];return this.getLayoutDataWithState(a,i)}getAllLayouts(){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const t=[...Object.keys(this.state.transaction?.layouts)];return[...new Set(t)].map(a=>this.getLayoutById(a))}getLayoutDataWithState(t,e){return{layoutState:{layout:t,elements:e},getComponentWithProps:a=>He(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(i=>{a=new ja(i).apply(a)}),this.runStateCallbacks(),this.state={transaction:a}}commandReducer(t,e){const a=t.transaction||{layouts:{},serializableWorkflow:{steps:[]}};return{...t,transaction:e.apply(a)}}}const vi=n=>n.type===D.Image?B.jsx(gi,{...n},n.id):n.type===D.Frame?B.jsx(Is,{...n},n.id):n.type===D.Illustration?B.jsx(Us,{...n},n.id):n.type===D.Textbox?B.jsx(Os,{...n},n.id):n.type===D.Group?B.jsx(mi,{...n},n.id):null,He=(n,t,e)=>{const a=e.renderingConfiguration,i=a?.removeExcludedElements?t.filter(r=>!r.excludeFromExport):t;return B.jsx(As,{preserveAspectRatio:void 0,elements:i,backgroundColor:n.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||n.width,height:e.height||n.height,viewBox:a?.region?{x:a.region.left,y:a.region.top,width:a.region.width,height:a.region.height}:{x:0,y:0,width:n.width,height:n.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function La(n){return n.sort((t,e)=>{const a=t.layer||0,i=e.layer||0;if(a<i)return-1;if(a>i)return 1;const r=t.layerIndex||0,o=e.layerIndex||0;return r<o?-1:r>o?1:0})}const At=new Map,Mt=new Map,ia=new Map,Ei=async(n,t)=>{if(!t){if(!n)throw new Error("No region or src supplied. Cannot construct frame!");return va(n)}return et(t)},va=n=>{const t=n.width,e=n.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
|
|
1351
1359
|
<path id="target-path" d='M0 0 h ${t} v ${e} h ${-t} Z' />
|
|
1352
1360
|
</svg>
|
|
1353
|
-
`},
|
|
1361
|
+
`},Vs=async(n,t)=>{if(!t)return;const e=await P.getDefaultVariant(t,n.frameVariantId);if(!e)throw new Error(`No variant with ID: ${n.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${n.frameVariantId}`);return e},Ae=async n=>{if(ia.has(n))return ia.get(n);const e=(async()=>{if(Mt.has(n))return Mt.get(n);await new Promise(A=>setTimeout(A,0));const i=ct().parseFromString(n,"image/svg+xml"),r=i.querySelector("svg");if(!r)throw new Error("Malformed frame SVG: <svg> tag not found");const o=r.getAttribute("viewBox");if(!o)throw new Error("SVG missing viewBox.");const s=o.split(" "),l=parseFloat(s[3])||1,c=parseFloat(s[2])||1,d=i.getElementById("target-path"),u=i.getElementsByClassName("st0").item(0);if(d){const A=d.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}if(u){const A=u.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}throw new Error("Malformed frame SVG")})();return ia.set(n,e),e},qa=(n,t,e,a)=>{const i=t.width/t.height,r=n.width/n.height;let o;a?r>i?o=t.height/n.height:o=t.width/n.width:r>i?o=t.width/n.width:o=t.height/n.height,e?.scale!==void 0&&(o*=e?.scale);const s=t.width/2,l=t.height/2,c=s-n.width/2*o,d=e?.left||c,u=l-n.height/2*o,A=e?.top||u;return{x:d,y:A,zoom:o}},Ea=async n=>{if(At.has(n))return At.get(n);if(n.startsWith("data:image/svg+xml")){const e=Nr.dataUriToBuffer(n),a=new TextDecoder().decode(e.buffer),i=Ga(a),r={src:n,width:i.width,height:i.height,aspect:i.width/i.height};return At.set(n,r),r}if((n.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await za(n),a=e.width,i=e.height,r={src:n,width:a,height:i,aspect:a/i};return At.set(n,r),r}else{const e=await $e(n,!0),a=await ce(e),i={src:n,width:a.width,height:a.height,aspect:a.width/a.height};return At.set(n,i),i}},za=async n=>{const t=await et(n);return Ga(t)},yn=n=>n.endsWith("mm")?Number(n.replace("mm",""))*3.7795275591:n.endsWith("px")?Number(n.replace("px","")):Number(n),Ga=n=>{const a=ct().parseFromString(n,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const i=a.getAttribute("viewBox"),r=a.getAttribute("width"),o=a.getAttribute("height"),s=o&&r?[0,0,yn(r),yn(o)]:i?.split(" ").map(l=>Number(l));if(!s)throw new Error("No viewbox or width/height values detected on SVG file!");return{width:s[2],height:s[3]}},zt=(n,t)=>{const e=n.layoutState.elements.filter(i=>i.layer===t),a=Math.max(...e.map(i=>i.layerIndex).filter(i=>i!==void 0));return Math.max(a,0)+1},bi=async n=>new Promise(t=>{et(n).then(e=>{t(e)}).catch(e=>console.error(e))}),ra=new Map,re=async n=>{if(ra.has(n))return ra.get(n);const t=async i=>new Promise((r,o)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");i.toBlob(l=>{if(!l)throw i.width===0||i.height===0?new Error(`Canvas dimensions are invalid (${i.width},${i.height})`):i.width*i.height>=268435456?new Error(`Canvas dimensions exceed device limit (${i.width},${i.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");r(URL.createObjectURL(l))})}catch(s){o(s)}}),a=(async()=>{const o=ct().parseFromString(n,"image/svg+xml").firstElementChild;if(!o)throw new Error("Failed to read SVG");const l=Et().serializeToString(o),c=yt(),d=c.getContext("2d"),u=await Ma.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch:it}),A=o.getAttribute("width"),h=o.getAttribute("height"),g=2048;if(h&&A){const p=parseFloat(h),f=parseFloat(A)/p;f>1?u.resize(g,g/f):u.resize(g*f,g)}else u.resize(g,g);return await u.render(),await t(c)})();return ra.set(n,a),a},Gt=async(n,t,e,a)=>{const i=n.layoutState.layout.useEditableArea&&n.layoutState.layout.editableArea||{width:n.layoutState.layout.width,height:n.layoutState.layout.height,x:0,y:0},r=i.width<i.height?i.width:i.height,o=n.layoutState.layout.useEditableArea?r/1.3:r/2,s={top:i.y+i.height/2-o/2,left:i.x+i.width/2-o/2,width:o,height:o,rotation:0,panelId:n.layoutState.layout.panelId};if(e&&t===D.Illustration){const l=await rt(await bi(e)),A=ct().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!A)throw new Error("SVG missing viewBox.");const h=s.height,g=A.split(" "),p=parseFloat(g[2])||1,m=parseFloat(g[3])||1,f=p/m;s.height=s.width/f,s.top+=(h-s.height)/2}if(e&&t===D.Image){const l=s.height,c=await $e(e),d=await ce(c),u=d.width/d.height;s.height=s.width/u,s.top+=(l-s.height)/2}if(e&&t===D.Textbox&&a?.text&&a?.fontScale){await Ft(e);const l=vt(e),c=Ct(a.text,a?.fontScale,l);s.width=Math.min(c,i.width*.85),s.left=i.x+i.width/2-s.width/2}return s};class Ls{static async getFrame(t,e){const a=await Ei(e.region,e.src),i=await Ae(a),r=e.region||await Gt(t,D.Frame);return{id:N(),x:r.left,y:r.top,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||zt(t,r.layer||0),rotation:r.rotation,scaleX:r.width/i.width,scaleY:r.height/i.height,path:i.path,dataWidth:i.width,dataHeight:i.height,type:D.Frame,disablePlaceholder:e.configuration.disablePlaceholder,focalBlur:e.configuration.focalBlur,focalBlurStrength:e.configuration.focalBlurStrength,focalBlurRadius:e.configuration.focalBlurRadius,forceImageCover:e.configuration.forceImageCover,pattern:void 0,immutable:r.immutable}}static async getImage(t,e){const a=e.region||await Gt(t,D.Image,e.src);return{id:N(),src:e.src,type:D.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||zt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:i,designInputStep:r}=e,o=await Ft(i),s={assetUrl:i,name:o.names.fullName.en},l=r?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=Fe(c,{vertical:a.vertical,uppercase:a.uppercase}),u=e.region||await Gt(t,D.Textbox,i,{text:d,fontScale:a.size?a.size/o.unitsPerEm:void 0}),A=ue({id:N(),type:D.Textbox,x:u.left,y:u.top,width:u.width,height:u.height,align:Qs(a.textAlign,a.vertical),curved:a.curved,fill:r?.color||a.colour||"#000000",fontData:s,layer:u.layer||0,layerIndex:u.layerIndex||zt(t,u.layer||0),paths:a.paths,rotation:u.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:xt.Traditional,fontSize:a.size||Math.max(Math.round(u.height*.025),1),text:d,input:l},d),h=Ms({...u,height:A.height},s,A.fontSize,A?.text?.split(`
|
|
1354
1362
|
`)||[],A.align);return{...A,x:h.left,y:h.top+(u.height-h.height)/2,width:h.width,height:h.height}}static async getShape(t,e){const a=`
|
|
1355
1363
|
<svg
|
|
1356
1364
|
xmlns="http://www.w3.org/2000/svg"
|
|
@@ -1371,7 +1379,7 @@
|
|
|
1371
1379
|
fill="${e.color}"
|
|
1372
1380
|
/>
|
|
1373
1381
|
</svg>
|
|
1374
|
-
`,i={};i["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Gt(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i,id:o,svg:a,type:D.Illustration,y:r.top,x:r.left,rotation:r.rotation,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||zt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Gt(t,D.Illustration,e.src),i=await rt(await bi(e.src)),r=await re(i.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i.colors,id:o,src:e.src,svg:i.svg,type:D.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||zt(t,a.layer||0),immutable:a.immutable}}}class z extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,z.prototype)}}const V=(n,t)=>_(n,t).elements.find(i=>i.id===n),_=(n,t)=>{const e=Object.values(t).find(a=>a.elements.some(i=>i.id===n));if(!e)throw new z;return e},tt=(n,t)=>{const e=[...t.elements.filter(i=>i.id!==n.id),n],a=La(e);return{layout:t.layout,elements:a,modificationID:N()}},ba=async n=>{const t=[...Object.keys(n.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const i=e[a],r=n.layouts[i];await Promise.all(r.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await et(s.src),c=await rt(l);s.svg=$a(c.svg,s.width,s.height,s.colors)}}else if(o.type==="frame"){const s=o;if(s.pattern?.colors&&s.pattern?.src){const l=await et(s.pattern?.src),c=await rt(l);s.pattern.svg=c.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const a in n.layouts){const i=n.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<i.length;++o){const s=i[o];if(s.src&&s.svg)try{s.cachedObjectURL=await re(s.svg)}catch(l){console.log(l)}}const r=n.layouts[a].elements.filter(o=>o.type===D.Textbox);for(let o=0;o<r.length;++o){const s=r[o];s.fontData?.assetUrl&&await Ft(s.fontData.assetUrl)}}};class ${undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class Sn extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Ls extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,x:this.x,y:this.y},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class qs extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,rotation:this.angle},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class zs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ue(o,s,e)}const i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class U extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class ja extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class G extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const i=e[e.length-1],r=i.productOverlay?i:null;r&&e.pop();let o;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)o=[...e,this.element].sort((s,l)=>s.layerIndex!==void 0&&l.layerIndex!==void 0?s.layerIndex-l.layerIndex:0);else{const s=this.assignIndex(this.element,e);this.element.layerIndex=s!==void 0?s:0,o=[...e,this.element]}return r&&o.push(r),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:N()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(i=>(i.layer||0)===(t.layer||0)).sort((i,r)=>(i.layerIndex||0)-(r.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class Dt extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(r=>(r.elements.filter(s=>s.id!==this.id).length!==r.elements.length&&(e=!0),{...r,elements:r.elements.filter(s=>s.id!==this.id),modificationID:N()}));e||console.log(`Failed to delete element ${this.id}`);const i={};return a.forEach(r=>{i[r.layout.id]=r}),{...t,layouts:i}}}class Ii extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class oa extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,textFillImage:this.imageFill},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Bi extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,fontSize:this.size},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Ia extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,fontData:this.fontData},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Pi extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,align:this.align},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),i=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...i,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const o={...e,elements:r,modificationID:N()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class js extends ${constructor(t,e,a,i,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=i,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Hs extends ${constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,src:this.src},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class xi extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a=_(e.id,Object.values(t.layouts)),i=tt(ue(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:i}}}}class sa extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ba extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a=e.colors||{},i=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:i?.spotColor,pmsValue:i?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:i?.spotColor,pmsValue:this.fill.pmsValue};const r={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=tt(r,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class Ws extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ys extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(i,1)[0]);const r=[...a.elements];return r.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Js extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(i,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(i,1)[0];return r.splice(i,0,o),r.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Ks extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(l=>l.id===this.id),r=i+1,o=[...a.elements],s=o.splice(i,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(l=>l.id===this.id),r=i-1,o=[...a.elements],s=o.splice(i,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class vn{constructor(t,e,a){this.processRegion=async i=>{const r=this.layouts.find(l=>l.panelId===i.panelId);if(!r)throw new Y(i);let o="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new lt(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===D.Image){const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!l)throw new Error("Undefined raster silent step source");const c={stepName:this.configuration.stepName,id:N(),src:l,type:s,y:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:i.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:i},command:new G(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await re(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,rotation:i.rotation,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:i},command:new G(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new Y(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Fi=async n=>{const t=`${ht.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:n}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Re("Failed to shorten URL, see console.")}};class Di{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,i=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=i,this.maxAttempts=r,this.poll()}}class Xs{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=i?.storage?.videoShortUrl,d=i?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,i){const r=async()=>{const h=(await Pe([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Di(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Rt(p.asset);h({rel:"mpeg4",href:p.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Dt(h.id)));const s=i.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+i.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([o]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Re("Cannot create QR code, URL too long.");const d=await Fi(c);if(!i.data||!i.data.regions)throw new lt(i,"Missing regions.");const u=await this.regionElements(i),A=await this.command(d,u,a,i.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(i.stepName,[],u,async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,i)=>({id:N(),region:a,regionIndex:i});return t.data.regions.map(e)}async command(t,e,a,i){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Un.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new Y(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new G({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:i,id:c.id,src:s,type:D.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},u)});return{command:new U(l),followup:async()=>{}}}}const Ha=new Xs;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return va(e);const a=t.asset;if(!a)throw new wt(t);const i=a.fileLink;if(i)return et(i,!0);throw new Rt(a)}}async init(t,e,a){const i=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(i?.storage&&Object.keys(i.storage).length!==0||i?.selectedVariants&&i.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let r;const o=e.getWorkflowExperience().getBundle();if(o&&t.globalPropertyAspectConfigurations){const s=o.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=s.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(r=(await W.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const s=t.option,l=await P.getDefaultVariant(s,t.overrideDefaultVariantId);return l?this.selectVariantCommand(t,l,[],e,void 0,r||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>va(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(i){const c=async()=>{const d=i.storage?.colors,u=i.storage?.framePatternSrc,A=i.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:u}),u){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,h,!0,d),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(A?.some(h=>h.zoom)){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");h.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(i.selectedVariants&&i.selectedVariants.length>0){const d=i.selectedVariants[0].id;if(t.option&&d){const u=t.option.variants?.find(A=>A.id===d);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const A=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(u,h)));e.updateStorage(t.stepName,{currentFrameSources:A}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return(await P.ensureFullOption(t.data.colorOption))?.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name}))??[]}selectImage(t,e,a,i=!0){const r=De.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===r)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const s=e.fileLink||"";return s.endsWith(".pdf")||s.endsWith(".eps")||s.endsWith(".ai")?new Promise(l=>{a.addPoller(new Di(async()=>{const d=(await W.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{W.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,i).then(l)})},()=>{throw new Re("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,i)}async selectVariant(t,e,a,i,r){const o=await this.selectVariantCommand(t,e,a,i,r);o&&(o.command&&i.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,i,r){return new G({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e,a=!0,i=void 0,r){if(t.endsWith("svg")){const o=await za(t),s=o.width,l=o.height,c=await et(t);if(r){const A=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(A&&A.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await rt(c),u={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:i??d.colors};At.set(t,u),e.setPatternData(u,a)}else{const o=await $e(t,!0),s=await ce(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};At.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const i=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!i||!i.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(i,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),i.setPatternData({...i.getImageData(),colors:r.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const i=a.getImageData()?.colors??{},r=[];for(const o in i){const s=i[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ai(s.browserValue);r.includes(l)||r.push(l)}}return r.length}async calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const i={...t.getImageData().colors??{}},r={};Object.entries(i).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())i[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(i)).map(l=>l.browserValue);const s=await P.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:i,metadataColors:o,storageColors:r}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,i,r,o){const s=i.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!s)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(e,h)));r&&r(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await Ae(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),y=m?qa(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:y?.x||0,y:y?.y||0,width:m.width,height:m.height,scaleX:y?.zoom||1,scaleY:y?.zoom||1,rotation:0}:void 0,F=N(),v=i.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new Y(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:f}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new U([...u,...A]),followup:async()=>{r&&r(!1),await i.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(i.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=i.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(o,h,!0)}})}}}static patternSource(t){const e=t.versions?.find(i=>i.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Rt(t)}async loadPatternFromAsset(t,e,a,i){const r=De.patternSource(t),o=a.markUpdatePending(),s=a.getWorkflowExperience().getStepById(e.stepName)?.frameService;if(!s)throw a.markUpdateCompleted(o),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(r,s,i,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=await this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:r,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:r,colors:l.storageColors}),a.markUpdateCompleted(o),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(c=>c.stepID===e.stepName)),this.validateColorCount(e,a)}}const pt=new De;class Zs{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,i,r){return new G({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return V(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{colors:i.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await P.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,i,r){const o={};for(const[d,u]of r.entries())typeof u=="string"?o[d]={browserValue:u,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:u.browserValue,spotColor:u.spotColor,pmsValue:u.pmsValue};const s=$a(t,e,a,o),l=await re(s),c=[];for(const d of i){for(const[u,A]of r.entries())c.push(new Ba(d,u,A));c.push(new Ws(d,s,l))}return new U(c)}async changeColors(t,e,a,i){if(e.length===0)return;const r=V(e[0].id,a.getCommandContext().getAllLayouts().map(A=>A.layoutState)),o={...r.colors},s={};Object.entries(o).forEach(([A,h])=>{const g={browserValue:h.browserValue,pmsValue:h.pmsValue},p=h.spotColor;p&&(g.spotColor={profileName:p.profileName,namedColor:p.namedColor}),s[A]=g});for(const[A,h]of i.entries()){const g=typeof h=="string"?h:h.browserValue,p=typeof h=="string"?void 0:h.pmsValue;A===""?Object.keys(o).forEach(m=>{o[m]={browserValue:g,spotColor:o[m]?.spotColor,pmsValue:p},s[m]={browserValue:g}}):(o[A]={browserValue:g,spotColor:o[A]?.spotColor,pmsValue:p},s[A]={browserValue:g})}let l=Array.from(Object.values(o)).map(A=>A.browserValue);const c=await P.ensureFullOption(t.data.colorOption);c&&c.variants?.forEach(A=>{l=l.map(h=>h.toLowerCase()===A.color?.toLowerCase()?A.name:h)}),a.updateMetadata(t.stepName,{colors:l});const d=new Map;if(Object.entries(o).forEach(([A,h])=>{d.set(A,h)}),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(r.svg,r.width,r.height,e.map(A=>A.id),d);a.updateStorage(t.stepName,{colors:s}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,i,r){i(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{i(!1)}}async selectVariantCommand(t,e,a,i){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new wt(e);const o=r.fileLink;if(!o)throw new Rt(r);t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await re(l.svg),d=(m,f)=>{const y=i.getLayouts().find(F=>F.panelId===m.panelId);if(!y)throw new Y(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,y,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await P.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(f=>f.toLowerCase()===m.color?.toLowerCase()?m.name:f)}),i.updateMetadata(t.stepName,{colors:g}),{command:new U(h),followup:async()=>{const m=u.map(y=>y.regionElement);await i.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const y={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(y[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,i,new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],w=Object.keys(l.colors),F=y.length===1&&w.length===1;if(F){const b=y[0],v=w[0];await this.changeColors(t,m,i,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,i,new Map)}}}}}const Jt=new Zs;class tl{async init(t,e,a){const i=t.option;if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(!l)throw new ae(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(c){const d=l.variants?.find(u=>u.id===c);if(d){const u=d.material,A=s.map(h=>({id:h.id,region:h.stepRegion,regionIndex:h.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(g)}})}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){const r=a.getModelContainer();i(!0);const o=e.material;if(!o)throw i(!1),new wt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{r&&t.data.targetMaterials.forEach(s=>{t.option&&r.applyMaterialVariant(s,t.option.id||"",o)})}finally{i(!1)}})}}}}const Wa=new tl;class el{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const A=e.getModelContainer();if(A&&t.option){const h=d.asset?.fileLink;if(!h)throw new wt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){i(!0);const r=e.asset?.fileLink;if(!r)throw new wt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{i(!1)}})}}}}const Ya=new el;class al{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:i?.storage?.text}),e.setMandatoryFulfilled(t.stepName,i?.storage?.text!=="")})}async changeText(t,e,a,i){const r=await this.changeTextCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,i){const r=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getWorkflowExperience().getProfanityList(),l=this.validateInput(t,e,s,i);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(d,u,A,h)=>{const g=h||N(),m=a.getLayouts().find(y=>y.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Dt(g)),f.push(new G({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},m)),{id:g,region:u,command:new U(f)}};if(r.length>0){const u=r.map(A=>{if(!A.region)return null;const h=o.svgPrint(e,A.region);return c(h,A.region,A.regionIndex,A.id)}).filter(A=>!!A).filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{}}}else{const d=t.data.regions.map((A,h)=>c(o.svgPrint(e,A),A,h)),u=d.filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{const A=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,e,a,i){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return i("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return i("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=ma.split(e.toLowerCase());for(const o of r)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return i("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return i(""),{input:e,helperData:{}}}}const Ja=new al;class nl{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r,e,()=>{})}return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u)}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,i){const r=e.asset;if(!r)throw new wt(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;i(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(u=>new Dt(u.id)),c=(u,A)=>{const g=a.getLayouts().find(m=>m.panelId===u.panelId);if(!g)throw new Y(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new G({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.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"},g)}},d=t.data.regions.map(c);return{command:new U([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{i(!1)})}}}}const Ka=new nl;class il{async init(t,e,a){const i=t.option;if(!i)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await P.getOptionForStep(t);if(i?.selectedVariants){const o=i.selectedVariants[0].id;if(r&&o){const s=r.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){const i=await this.selectVariantLambda(t,e,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for question step");const r=i.variants;if(!r)throw new lt(t,"Option for question step is missing variants");const o=r.length>1?r.find(s=>s.id===e):r[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${i.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const _a=new il;class rl{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await P.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const i=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!i.find(d=>d.panelId===l?.panelId))throw new Y(l);return new Ba(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new U(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateStorage(t.stepName,{colour:i?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,i){const r=i.getLayouts(),o=i.getStepStorage(t.stepName)?.colour,s=()=>{if(e.variant?.color==="#custom")return o||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const l=d=>{const u=d.region;if(!r.find(g=>g.panelId===u?.panelId))throw new Y(u);const h=s();return new Ba(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new U(c),followup:async()=>{await i.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),i.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new Y(A);const p=s(),m=`
|
|
1382
|
+
`,i={};i["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Gt(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i,id:o,svg:a,type:D.Illustration,y:r.top,x:r.left,rotation:r.rotation,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||zt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Gt(t,D.Illustration,e.src),i=await rt(await bi(e.src)),r=await re(i.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:i.colors,id:o,src:e.src,svg:i.svg,type:D.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||zt(t,a.layer||0),immutable:a.immutable}}}class z extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,z.prototype)}}const V=(n,t)=>_(n,t).elements.find(i=>i.id===n),_=(n,t)=>{const e=Object.values(t).find(a=>a.elements.some(i=>i.id===n));if(!e)throw new z;return e},tt=(n,t)=>{const e=[...t.elements.filter(i=>i.id!==n.id),n],a=La(e);return{layout:t.layout,elements:a,modificationID:N()}},ba=async n=>{const t=[...Object.keys(n.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const i=e[a],r=n.layouts[i];await Promise.all(r.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await et(s.src),c=await rt(l);s.svg=$a(c.svg,s.width,s.height,s.colors)}}else if(o.type==="frame"){const s=o;if(s.pattern?.colors&&s.pattern?.src){const l=await et(s.pattern?.src),c=await rt(l);s.pattern.svg=c.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const a in n.layouts){const i=n.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<i.length;++o){const s=i[o];if(s.src&&s.svg)try{s.cachedObjectURL=await re(s.svg)}catch(l){console.log(l)}}const r=n.layouts[a].elements.filter(o=>o.type===D.Textbox);for(let o=0;o<r.length;++o){const s=r[o];s.fontData?.assetUrl&&await Ft(s.fontData.assetUrl)}}};class ${undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class Sn extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class qs extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,x:this.x,y:this.y},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class zs extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,rotation:this.angle},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ue(o,s,e)}const i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class U extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class ja extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class G extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const i=e[e.length-1],r=i.productOverlay?i:null;r&&e.pop();let o;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)o=[...e,this.element].sort((s,l)=>s.layerIndex!==void 0&&l.layerIndex!==void 0?s.layerIndex-l.layerIndex:0);else{const s=this.assignIndex(this.element,e);this.element.layerIndex=s!==void 0?s:0,o=[...e,this.element]}return r&&o.push(r),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:N()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(i=>(i.layer||0)===(t.layer||0)).sort((i,r)=>(i.layerIndex||0)-(r.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class Dt extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(r=>(r.elements.filter(s=>s.id!==this.id).length!==r.elements.length&&(e=!0),{...r,elements:r.elements.filter(s=>s.id!==this.id),modificationID:N()}));e||console.log(`Failed to delete element ${this.id}`);const i={};return a.forEach(r=>{i[r.layout.id]=r}),{...t,layouts:i}}}class Ii extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class oa extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,textFillImage:this.imageFill},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Bi extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,fontSize:this.size},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Ia extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,fontData:this.fontData},i=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ue(a,r),i);return{...t,layouts:{...t.layouts,[i.layout.id]:o}}}}class Pi extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,align:this.align},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class js extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),i=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...i,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const o={...e,elements:r,modificationID:N()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class Hs extends ${constructor(t,e,a,i,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=i,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ws extends ${constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,src:this.src},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class xi extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a=_(e.id,Object.values(t.layouts)),i=tt(ue(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:i}}}}class sa extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Ba extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a=e.colors||{},i=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:i?.spotColor,pmsValue:i?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:i?.spotColor,pmsValue:this.fill.pmsValue};const r={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=tt(r,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class Ys extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},i=_(e.id,Object.values(t.layouts)),r=tt(a,i);return{...t,layouts:{...t.layouts,[i.layout.id]:r}}}}class Js extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(i,1)[0]);const r=[...a.elements];return r.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Ks extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=V(this.id,Object.values(t.layouts));if(!e.id)throw new z;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(i,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(i,1)[0];return r.splice(i,0,o),r.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(l=>l.id===this.id),r=i+1,o=[...a.elements],s=o.splice(i,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class Xs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!V(this.id,Object.values(t.layouts)).id)throw new z;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const i=a.elements.findIndex(l=>l.id===this.id),r=i-1,o=[...a.elements],s=o.splice(i,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class vn{constructor(t,e,a){this.processRegion=async i=>{const r=this.layouts.find(l=>l.panelId===i.panelId);if(!r)throw new Y(i);let o="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new lt(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===D.Image){const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!l)throw new Error("Undefined raster silent step source");const c={stepName:this.configuration.stepName,id:N(),src:l,type:s,y:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:i.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:i},command:new G(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await re(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:i.top,x:i.left,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,rotation:i.rotation,immutable:i.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:i},command:new G(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new Y(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Fi=async n=>{const t=`${ht.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:n}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Re("Failed to shorten URL, see console.")}};class Di{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,i=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=i,this.maxAttempts=r,this.poll()}}class Zs{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=i?.storage?.videoShortUrl,d=i?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,i){const r=async()=>{const h=(await Pe([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Di(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Rt(p.asset);h({rel:"mpeg4",href:p.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Dt(h.id)));const s=i.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+i.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([o]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Re("Cannot create QR code, URL too long.");const d=await Fi(c);if(!i.data||!i.data.regions)throw new lt(i,"Missing regions.");const u=await this.regionElements(i),A=await this.command(d,u,a,i.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(i.stepName,[],u,async()=>{a.updateStorage(i.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,i)=>({id:N(),region:a,regionIndex:i});return t.data.regions.map(e)}async command(t,e,a,i){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Un.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new Y(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new G({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:i,id:c.id,src:s,type:D.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},u)});return{command:new U(l),followup:async()=>{}}}}const Ha=new Zs;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return va(e);const a=t.asset;if(!a)throw new wt(t);const i=a.fileLink;if(i)return et(i,!0);throw new Rt(a)}}async init(t,e,a){const i=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(i?.storage&&Object.keys(i.storage).length!==0||i?.selectedVariants&&i.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let r;const o=e.getWorkflowExperience().getBundle();if(o&&t.globalPropertyAspectConfigurations){const s=o.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=s.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(r=(await W.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const s=t.option,l=await P.getDefaultVariant(s,t.overrideDefaultVariantId);return l?this.selectVariantCommand(t,l,[],e,void 0,r||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>va(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(i){const c=async()=>{const d=i.storage?.colors,u=i.storage?.framePatternSrc,A=i.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:u}),u){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,h,!0,d),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(A?.some(h=>h.zoom)){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");h.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(i.selectedVariants&&i.selectedVariants.length>0){const d=i.selectedVariants[0].id;if(t.option&&d){const u=t.option.variants?.find(A=>A.id===d);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const A=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(u,h)));e.updateStorage(t.stepName,{currentFrameSources:A}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return(await P.ensureFullOption(t.data.colorOption))?.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name}))??[]}selectImage(t,e,a,i=!0){const r=De.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===r)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const s=e.fileLink||"";return s.endsWith(".pdf")||s.endsWith(".eps")||s.endsWith(".ai")?new Promise(l=>{a.addPoller(new Di(async()=>{const d=(await W.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{W.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,i).then(l)})},()=>{throw new Re("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,i)}async selectVariant(t,e,a,i,r){const o=await this.selectVariantCommand(t,e,a,i,r);o&&(o.command&&i.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,i,r){return new G({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e,a=!0,i=void 0,r){if(t.endsWith("svg")){const o=await za(t),s=o.width,l=o.height,c=await et(t);if(r){const A=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(A&&A.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await rt(c),u={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:i??d.colors};At.set(t,u),e.setPatternData(u,a)}else{const o=await $e(t,!0),s=await ce(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};At.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const i=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!i||!i.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(i,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),i.setPatternData({...i.getImageData(),colors:r.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const i=a.getImageData()?.colors??{},r=[];for(const o in i){const s=i[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ai(s.browserValue);r.includes(l)||r.push(l)}}return r.length}async calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const i={...t.getImageData().colors??{}},r={};Object.entries(i).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())i[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(i)).map(l=>l.browserValue);const s=await P.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:i,metadataColors:o,storageColors:r}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,i,r,o){const s=i.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!s)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(e,h)));r&&r(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await Ae(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),y=m?qa(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:y?.x||0,y:y?.y||0,width:m.width,height:m.height,scaleX:y?.zoom||1,scaleY:y?.zoom||1,rotation:0}:void 0,F=N(),v=i.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new Y(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:f}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new U([...u,...A]),followup:async()=>{r&&r(!1),await i.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(i.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=i.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(o,h,!0)}})}}}static patternSource(t){const e=t.versions?.find(i=>i.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Rt(t)}async loadPatternFromAsset(t,e,a,i){const r=De.patternSource(t),o=a.markUpdatePending(),s=a.getWorkflowExperience().getStepById(e.stepName)?.frameService;if(!s)throw a.markUpdateCompleted(o),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(r,s,i,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=await this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:r,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:r,colors:l.storageColors}),a.markUpdateCompleted(o),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(c=>c.stepID===e.stepName)),this.validateColorCount(e,a)}}const pt=new De;class tl{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,i,r){return new G({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return V(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{colors:i.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await P.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,i,r){const o={};for(const[d,u]of r.entries())typeof u=="string"?o[d]={browserValue:u,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:u.browserValue,spotColor:u.spotColor,pmsValue:u.pmsValue};const s=$a(t,e,a,o),l=await re(s),c=[];for(const d of i){for(const[u,A]of r.entries())c.push(new Ba(d,u,A));c.push(new Ys(d,s,l))}return new U(c)}async changeColors(t,e,a,i){if(e.length===0)return;const r=V(e[0].id,a.getCommandContext().getAllLayouts().map(A=>A.layoutState)),o={...r.colors},s={};Object.entries(o).forEach(([A,h])=>{const g={browserValue:h.browserValue,pmsValue:h.pmsValue},p=h.spotColor;p&&(g.spotColor={profileName:p.profileName,namedColor:p.namedColor}),s[A]=g});for(const[A,h]of i.entries()){const g=typeof h=="string"?h:h.browserValue,p=typeof h=="string"?void 0:h.pmsValue;A===""?Object.keys(o).forEach(m=>{o[m]={browserValue:g,spotColor:o[m]?.spotColor,pmsValue:p},s[m]={browserValue:g}}):(o[A]={browserValue:g,spotColor:o[A]?.spotColor,pmsValue:p},s[A]={browserValue:g})}let l=Array.from(Object.values(o)).map(A=>A.browserValue);const c=await P.ensureFullOption(t.data.colorOption);c&&c.variants?.forEach(A=>{l=l.map(h=>h.toLowerCase()===A.color?.toLowerCase()?A.name:h)}),a.updateMetadata(t.stepName,{colors:l});const d=new Map;if(Object.entries(o).forEach(([A,h])=>{d.set(A,h)}),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(r.svg,r.width,r.height,e.map(A=>A.id),d);a.updateStorage(t.stepName,{colors:s}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,i,r){i(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{i(!1)}}async selectVariantCommand(t,e,a,i){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new wt(e);const o=r.fileLink;if(!o)throw new Rt(r);t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await re(l.svg),d=(m,f)=>{const y=i.getLayouts().find(F=>F.panelId===m.panelId);if(!y)throw new Y(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,y,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await P.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(f=>f.toLowerCase()===m.color?.toLowerCase()?m.name:f)}),i.updateMetadata(t.stepName,{colors:g}),{command:new U(h),followup:async()=>{const m=u.map(y=>y.regionElement);await i.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const y={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(y[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,i,new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],w=Object.keys(l.colors),F=y.length===1&&w.length===1;if(F){const b=y[0],v=w[0];await this.changeColors(t,m,i,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,i,new Map)}}}}}const Jt=new tl;class el{async init(t,e,a){const i=t.option;if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(!l)throw new ae(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(c){const d=l.variants?.find(u=>u.id===c);if(d){const u=d.material,A=s.map(h=>({id:h.id,region:h.stepRegion,regionIndex:h.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(g)}})}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){const r=a.getModelContainer();i(!0);const o=e.material;if(!o)throw i(!1),new wt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{r&&t.data.targetMaterials.forEach(s=>{t.option&&r.applyMaterialVariant(s,t.option.id||"",o)})}finally{i(!1)}})}}}}const Wa=new el;class al{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const A=e.getModelContainer();if(A&&t.option){const h=d.asset?.fileLink;if(!h)throw new wt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantLambda(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,i){i(!0);const r=e.asset?.fileLink;if(!r)throw new wt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{i(!1)}})}}}}const Ya=new al;class nl{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:i?.storage?.text}),e.setMandatoryFulfilled(t.stepName,i?.storage?.text!=="")})}async changeText(t,e,a,i){const r=await this.changeTextCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,i){const r=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getWorkflowExperience().getProfanityList(),l=this.validateInput(t,e,s,i);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(d,u,A,h)=>{const g=h||N(),m=a.getLayouts().find(y=>y.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Dt(g)),f.push(new G({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},m)),{id:g,region:u,command:new U(f)}};if(r.length>0){const u=r.map(A=>{if(!A.region)return null;const h=o.svgPrint(e,A.region);return c(h,A.region,A.regionIndex,A.id)}).filter(A=>!!A).filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{}}}else{const d=t.data.regions.map((A,h)=>c(o.svgPrint(e,A),A,h)),u=d.filter(A=>!!A).map(A=>A&&A.command);return{command:new U(u),followup:async()=>{const A=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,e,a,i){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return i("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return i("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=ma.split(e.toLowerCase());for(const o of r)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return i("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return i(""),{input:e,helperData:{}}}}const Ja=new nl;class il{async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r,e,()=>{})}return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u)}}}}async selectVariant(t,e,a,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,i){const r=e.asset;if(!r)throw new wt(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;i(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(u=>new Dt(u.id)),c=(u,A)=>{const g=a.getLayouts().find(m=>m.panelId===u.panelId);if(!g)throw new Y(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new G({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.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"},g)}},d=t.data.regions.map(c);return{command:new U([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{i(!1)})}}}}const Ka=new il;class rl{async init(t,e,a){const i=t.option;if(!i)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await P.getOptionForStep(t);if(i?.selectedVariants){const o=i.selectedVariants[0].id;if(r&&o){const s=r.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){const i=await this.selectVariantLambda(t,e,a);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new lt(t,"Missing option for question step");const r=i.variants;if(!r)throw new lt(t,"Option for question step is missing variants");const o=r.length>1?r.find(s=>s.id===e):r[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${i.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const _a=new rl;class ol{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await P.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const i=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!i.find(d=>d.panelId===l?.panelId))throw new Y(l);return new Ba(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new U(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)throw new ae(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(i,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,i){const r=await this.selectVariantCommand(t,e,a,i);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateStorage(t.stepName,{colour:i?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,i){const r=i.getLayouts(),o=i.getStepStorage(t.stepName)?.colour,s=()=>{if(e.variant?.color==="#custom")return o||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const l=d=>{const u=d.region;if(!r.find(g=>g.panelId===u?.panelId))throw new Y(u);const h=s();return new Ba(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new U(c),followup:async()=>{await i.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),i.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new Y(A);const p=s(),m=`
|
|
1375
1383
|
<svg
|
|
1376
1384
|
xmlns="http://www.w3.org/2000/svg"
|
|
1377
1385
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
|
@@ -1391,14 +1399,14 @@
|
|
|
1391
1399
|
fill="${p}"
|
|
1392
1400
|
/>
|
|
1393
1401
|
</svg>
|
|
1394
|
-
`,f={};f[this.shapeFillId]={browserValue:p};const y=N();return{id:y,region:A,command:new G({stepRegion:A,stepRegionIndex:h,stepName:t.stepName,colors:f,id:y,svg:m,type:D.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},g)}},c=t.data.regions.map(l),d=c.filter(A=>!!A).map(A=>A?.command),u=c.filter(A=>!!A).map((A,h)=>({id:A.id,region:A.region,regionIndex:h}));return{command:new U(d),followup:async()=>{await i.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],u,async()=>{i.updateStorage(t.stepName,{colour:s()})})}}}}}const Tt=new
|
|
1395
|
-
`)).flat(),o=r.length,s=r.map(d=>Ct(d,a,i));const l=i.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(o-1)*e>n.height)return[null,null];const u=Math.max(...s);if(u<=n.width)return[r,u];const A=s.reduce((m,f,y,w)=>f>w[m]?y:m,0),h=r[A];let g=!1,p=h.length;for(;!g&&p>-1;){p=h.lastIndexOf(" ",p-1);const m=[h.slice(0,p),h.slice(p+1)],f=m.map(w=>Ct(w,a,i));f[0]<=n.width&&(r=[...r.slice(0,A),...m,...r.slice(A+1)],s=[...s.slice(0,A),...f,...s.slice(A+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Kt=(n,t,e,a,i)=>{let r,o;const s=vt(t.assetUrl),l=s.getFont();if(i.size){const A=n/l.unitsPerEm;return[r,o]=la(e,a,n,A,s),[i.size,r,o]}const c=6;let d=c-na;if(a.length>0){let A=a,h=0;for(;(!i.maxSize||d<=i.maxSize)&&A;)d+=na,h=d/l.unitsPerEm,[A,o]=la(e,a,d,h,s)}d>c&&(d-=na),i.minSize&&d<i.minSize&&(d=i.minSize);const u=d/l.unitsPerEm;return[r,o]=la(e,a,d,u,s),[d,r,o]},ca=30;class ke extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ke.name}}const
|
|
1396
|
-
`];class Me extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Me.name}}class
|
|
1402
|
+
`,f={};f[this.shapeFillId]={browserValue:p};const y=N();return{id:y,region:A,command:new G({stepRegion:A,stepRegionIndex:h,stepName:t.stepName,colors:f,id:y,svg:m,type:D.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},g)}},c=t.data.regions.map(l),d=c.filter(A=>!!A).map(A=>A?.command),u=c.filter(A=>!!A).map((A,h)=>({id:A.id,region:A.region,regionIndex:h}));return{command:new U(d),followup:async()=>{await i.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],u,async()=>{i.updateStorage(t.stepName,{colour:s()})})}}}}}const Tt=new ol;class sl{constructor(){this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}removeToastCallback(t){this.toastCallbacks=this.toastCallbacks.filter(e=>e!==t)}setLatestToast(t,e){this.latestToast=t,this.toastType=e,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach(t=>t({toastMessage:this.latestToast,toastType:this.toastType}))}}const ki=new sl,la=(n,t,e,a,i)=>{if(t.some(d=>d==null))throw new Error(`Failed to autosize lines: ${t.join(", ")}`);let r=t.map(d=>d.split(`
|
|
1403
|
+
`)).flat(),o=r.length,s=r.map(d=>Ct(d,a,i));const l=i.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(o-1)*e>n.height)return[null,null];const u=Math.max(...s);if(u<=n.width)return[r,u];const A=s.reduce((m,f,y,w)=>f>w[m]?y:m,0),h=r[A];let g=!1,p=h.length;for(;!g&&p>-1;){p=h.lastIndexOf(" ",p-1);const m=[h.slice(0,p),h.slice(p+1)],f=m.map(w=>Ct(w,a,i));f[0]<=n.width&&(r=[...r.slice(0,A),...m,...r.slice(A+1)],s=[...s.slice(0,A),...f,...s.slice(A+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Kt=(n,t,e,a,i)=>{let r,o;const s=vt(t.assetUrl),l=s.getFont();if(i.size){const A=n/l.unitsPerEm;return[r,o]=la(e,a,n,A,s),[i.size,r,o]}const c=6;let d=c-na;if(a.length>0){let A=a,h=0;for(;(!i.maxSize||d<=i.maxSize)&&A;)d+=na,h=d/l.unitsPerEm,[A,o]=la(e,a,d,h,s)}d>c&&(d-=na),i.minSize&&d<i.minSize&&(d=i.minSize);const u=d/l.unitsPerEm;return[r,o]=la(e,a,d,u,s),[d,r,o]},ca=30;class ke extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ke.name}}const ll=["‘","’","“","”",`
|
|
1404
|
+
`];class Me extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Me.name}}class cl{constructor(){this.cachedColors=new Map,this.cachedStrokeColors=new Map,this.filterUnsupportedCharacters=(t,e)=>{let a=t.replace(/(\r\n|\r|(\u2665|\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const i=[],r=e?vt(e.assetUrl):void 0;if(r){const o=a.split("").filter(l=>!ll.includes(l)).join(""),s=o.split("").map(l=>r.getFont().charToGlyph(l));for(let l=0;l<s.length;l++)s[l].name===".notdef"&&i.push(String.fromCharCode(o.charCodeAt(l)))}for(let o=0;o<i.length;o++)a=a.replaceAll(i[o],"");return a},this.textAlign=t=>t.vertical?"center":t.textAlign||"center",this.getErrorsForText=(t,e,a,i)=>{let r;a.data&&a.data.maxLength&&e.length>a.data.maxLength&&(r||(r={}),r.hitCharacterLimit=!0);const o=i.getWorkflowExperience().getProfanityList(),s=ma.split(t.toLowerCase());for(const c of s)for(const d in o){const u=o[d].toLowerCase().replace(/\s/g,"");if(c===u){r||(r={}),r.blockedProfanity=!0;break}}return!a.data.allowNewlines&&(t.includes(`
|
|
1397
1405
|
`)||t.includes("\r"))&&(r||(r={}),r.illegalMultipleLines=!0),r}}async init(t,e,a){const i=await P.getOptionForStep(t);if(!i)return null;if(a)await this.reload(t,e,a);else{const r=await this.getDefaultImageFillVariant(t.data),o=r?.asset?.fileLink,s=o?await Ea(o):void 0,l=s?{src:s.src,height:s.height,width:s.width,scale:t.data.imageFillScale||1}:void 0,c=await this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let u=t.data.defaultText||"";const A=e.getWorkflowExperience().getBundle();if(A&&t.globalPropertyAspectConfigurations){const p=A.getGlobalPropertyConfiguration()?.aspects?.find(m=>m.type===q.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(m.name));if(p){const f=A.getGlobalPropertyStateManager().getAspect(p.name);f&&(u=f)}}e.updateStorage(t.stepName,{text:u,inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:u,color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:r?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=await P.getDefaultVariant(i,t.overrideDefaultVariantId);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(r=>V(r.id,t.getAllLayoutData()))}async availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=await P.ensureFullOption(t.data.colorOption);if(a){const i=a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r}))||[];return this.cachedColors.set(t.stepName,i),i}return[]}changeAlignment(t,e,a,i){if(!t.data||!t.data.regions)return;const r=i.getCommandDispatcher();for(const o of a){const s=new Pi(o.id,e);r(s)}}async changeFillColor(t,e,a,i){if(!t.data||!t.data.regions)return;const r=i.getCommandDispatcher();e.variant?i.updateMetadata(t.stepName,{color:e.variant.name}):i.updateMetadata(t.stepName,{color:e.fill});const o=await P.ensureFullOption(t.data.colorOption),s=o?this.createTextFillSpotColor(o,e.variant):void 0;o?i.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:o.colorProfile?.key}):i.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new Ii(l.id,e.fill,s);r(c)}}async availableFillImages(t){const e=await P.ensureFullOption(t.data.imageFillOption);if(e){const a=e.variants?.map(i=>i.asset?.fileLink)?.filter(i=>!!i)||[];return Promise.all(a.map(async i=>{const r=await Ea(i);return{src:i,width:r.width,height:r.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,i){if(!t.data||!t.data.regions)return;const r=i.getCommandDispatcher(),o=t.option?.variants?.find(s=>s.asset?.fileLink===e.src);i.updateMetadata(t.stepName,{fillImage:o?.name}),i.updateStorage(t.stepName,{fillImage:e});for(const s of a){const l=new oa(s.id,e);r(l)}}async availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=await P.ensureFullOption(t.data.strokeOption);if(a){const i=a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r}))||[];return this.cachedStrokeColors.set(t.stepName,i),i}return[]}async changeStrokeColor(t,e,a,i){if(!t.data||!t.data.regions)return;const r=i.getCommandDispatcher();e?.variant?i.updateMetadata(t.stepName,{strokeColor:e.variant.name}):i.updateMetadata(t.stepName,{strokeColor:e?.fill});const o=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;i.updateStorage(t.stepName,{strokeColor:o});for(const s of a){const l=new sa(s.id,o,t.data?.strokeThickness);r(l)}}getProcessedInput(t,e,a){const i=a?t:this.injectReplaceableText(t,e);return Fe(i,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,i){const r=i.getStepStorage(a.stepName),o=Nt(t,i),s=this.getProcessedInput(o,a.data,r?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,i)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new O("Failed to resolve font data for text.");const[h,g]=Kt(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation},[s],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(A.id,h),u.set(A.id,g);const p=a.data.curved?s:(g||[]).join(`
|
|
1398
1406
|
`);c.push(this.generateTextChangeCommandsForRegion(h,a.data,A.id,p))}return!a.data.curved&&e.length>0&&!Array.from(u.values()).every(h=>h)?(l.errorData||(l.errorData={}),l.errorData.doesNotFit=!0,l):(i.updateStorage(a.stepName,{text:t}),i.updateMetadata(a.stepName,{text:s}),(r?.defaultCleared||!a.data.deleteDefaultOnFocus)&&s.trim()!==""&&i.setMandatoryFulfilled(a.stepName,!0),l.command=new U(c),l)}async selectVariant(t,e,a,i,r){const o=await this.selectVariantCommand(t,e,a.getStepStorage(t.stepName)||{},a.getRegionElements(t.stepName),a,i,r);o&&(o.command&&a.getCommandDispatcher()(o.command),o.followup&&await o.followup())}createTextFillSpotColor(t,e){const a=t.colorProfile;if(a){const i=(a.name||"").replace(/\s/g,"-"),r=i.lastIndexOf("/"),s=i.slice(r+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:s,namedColor:e.namedColor}}}async reload(t,e,a){const i=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(i?.selectedVariants){const c=i.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=await this.fontDataFromVariant(d),A=s.map(m=>({id:m.id,region:m.stepRegion,regionIndex:m.stepRegionIndex})),h=i.storage?.color;let g=i.storage?.text;const p=e.getWorkflowExperience().getBundle();if(p&&t.globalPropertyAspectConfigurations){const f=p.getGlobalPropertyConfiguration()?.aspects?.find(y=>y.type===q.Text&&t.globalPropertyAspectConfigurations?.map(w=>w.aspectName).includes(y.name));if(f){const w=p.getGlobalPropertyStateManager().getAspect(f.name);w&&(g=w)}}if(await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateMetadata(t.stepName,{color:h,text:g}),e.updateStorage(t.stepName,{text:g,inputText:g});const m=s.map(y=>new Ia(y.id,u)),f=new U(m);e.getCommandDispatcher()(f)}),s.length===0&&l){const m=await P.getDefaultVariant(l,t.overrideDefaultVariantId);if(m){const f=await this.selectVariantCommand(t,m,{text:g},[],e,()=>{},()=>{});f?.command&&e.getCommandDispatcher()(f.command)}}else{const{command:m}=j.updateInputText(g||"",s,t,e);m&&e.getCommandDispatcher()(m)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const u=c.getGlobalPropertyConfiguration()?.aspects?.find(A=>A.type===q.Text&&t.globalPropertyAspectConfigurations?.map(h=>h.aspectName).includes(A.name));if(u){const h=c.getGlobalPropertyStateManager().getAspect(u.name);if(h)if(s.length===0&&l){const g=await P.getDefaultVariant(l,t.overrideDefaultVariantId);if(g){const p=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});p?.command&&e.getCommandDispatcher()(p.command)}}else{const{command:g}=j.updateInputText(h,s,t,e);g&&e.getCommandDispatcher()(g)}}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return P.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;return e?(await P.getDefaultVariant(e))?.color:void 0}async getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return P.getDefaultVariant(e)}async getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(e)return P.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new wt(t);const a=e.fileLink;if(!a)throw new Rt(e);const i=await Ft(a);return{assetUrl:a,name:i.names.fullName.en}}async selectVariantCommand(t,e,a,i,r,o,s,l,c){const d=r.markUpdatePending(),u=await this.fontDataFromVariant(e);let A=!0;const h=g=>{o(g),g&&(A=!1)};if(i.length>0){const g=i.map(f=>new Ia(f.id,u));if(l){const f=i.map(y=>new oa(y.id,l));g.push(...f)}if(c){const f=i.map(y=>new sa(y.id,c,t.data.strokeThickness));g.push(...f)}const p=await this.changeInputTextWithRegion(t,t.data.size||ca,u,a.text||"",a,r,a?.customiseAllText??!1,h,s);p&&g.push(p);const m=new U(g);return A?{command:m,followup:async()=>{r.markUpdateCompleted(d),await r.setSelectionsAndElements(t.stepName,[e],i)}}:null}else{const g=await this.createTextboxRegions(t.stepName,e,t.data,u,a,r),p=await this.changeInputTextWithRegion(t,t.data.size||ca,u,g[0]?.newElement.input||a.text||t.data.defaultText||"",a,r,a?.customiseAllText??!1,h,s),m=g.flatMap(y=>y.commands);if(l){const y=g.map(w=>new oa(w.regionElement.id,l));m.push(...y)}if(c){const y=g.map(w=>new sa(w.newElement.id,c,t.data.strokeThickness));m.push(...y)}p&&m.push(p);const f=new U(m);return A?{command:f,followup:async()=>{r.markUpdateCompleted(d)}}:null}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,i,r,o){if(!a||!a.regions)throw new Error("Step data not supplied");const s=r.text||a.defaultText||"",l=Nt(s,o),c=this.getProcessedInput(l,a,!1),d=async(A,h)=>{const p=o.getLayouts().find(f=>f.panelId===A.panelId),m=N();try{if(!p)throw new Me("Failed to find layout for region: "+A.panelId);const f=await P.ensureFullOption(a.colorOption);let y;if(f&&f.variants){const k=await P.getDefaultVariant(f);k&&(y=this.createTextFillSpotColor(f,k),o.updateStorage(t,{colorProfileAssetKey:f.colorProfile?.key}))}const w=await this.getDefaultColor(a),F=w||"#000000",b={stepRegion:A,stepRegionIndex:h,stepName:t,align:this.textAlign(a),fill:r.color?r.color:F,fontSize:a.size||ca,fontData:i,id:m,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:c,input:s,type:D.Textbox,vertical:a.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:a.verticalAlign||"middle",curved:a.curved,paths:a.paths,fillSpotColorDefinition:y},v=[],I=new Map,M=new Map;if(!b.fontData)throw new O("Failed to resolve font data for text.");const[R,x]=Kt(b.fontSize,b.fontData,{left:b.x,top:b.y,width:b.width,height:b.height,rotation:b.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});I.set(b.id,R),M.set(b.id,x);const T=a.curved||a.vertical?c:(x||[]).join(`
|
|
1399
1407
|
`);v.push(this.generateTextChangeCommandsForRegion(R,a,b.id,T));const L=new G(b,p);return{regionElement:{id:m,region:A,regionIndex:h},commands:[L,...v],newElement:b,fontData:i}}catch(f){throw console.log(f),new ke("Error adding font to region")}},u=await Promise.all(a.regions.map(d)).catch(A=>{throw A instanceof ke?(ki.setLatestToast("Failed to load font.",he.Error),A):A instanceof Me?A:new Error(A)});return await o.setSelectionsAndElements(t,[e],u.map(A=>A.regionElement),async()=>{o.updateMetadata(t,{text:s}),o.updateStorage(t,{text:s})}),u}generateTextChangeCommandsForRegion(t,e,a,i){const r=[],o=new xi(a,i);if(r.push(o),!e.size){const l=new Bi(a,t);r.push(l)}return new U(r)}async changeInputTextWithRegion(t,e,a,i,r,o,s,l,c,d){const u=(i||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),A=Nt(u,o),h=this.getProcessedInput(A,t.data,s),g=o.getRegionElements(t.stepName),p=new Map,m=new Map;for(const b of g)if(b.region){const[v,I]=Kt(e,a,b.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});p.set(b.id,v),m.set(b.id,I)}const y=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const b=o.getWorkflowExperience().getProfanityList(),v=ma.split(h.toLowerCase());for(const I of v)for(const M in b){const R=b[M].toLowerCase().replace(/\s/g,"");if(I===R){const T="Blocked profanity.";return l(T),{error:T}}}if(!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
|
|
1400
1408
|
`)||h.includes("\r"))){const I="Text may not span multiple lines.";return l(I),{error:I}}if(!t.data.curved&&!Array.from(m.values()).every(M=>M)){const M="Text does not fit.";return l(M),{error:M}}return l(void 0),{info:(t.data.maxLength-h.length).toString()}})();if(y.error){c(y.error);return}if(c(`${y.info} characters remaining`||""),d)return;o.updateStorage(t.stepName,{text:u}),o.updateMetadata(t.stepName,{text:this.injectReplaceableText(u,t.data)}),(r.defaultCleared||!t.data.deleteDefaultOnFocus)&&u.trim()!==""&&o.setMandatoryFulfilled(t.stepName,!0);const w=[];for(const b of g){const v=t.data.curved?h:(m.get(b.id)||[]).join(`
|
|
1401
|
-
`);w.push(this.generateTextChangeCommandsForRegion(p.get(b.id)||1,t.data,b.id,v))}return new U(w)}}const j=new ll;class cl{}const dl="data:application/octet-stream;base64,AAEAAAAPAIAAAwBwRkZUTYdHeHoAAElcAAAAHEdERUYAJwBUAAAe2AAAAB5HUE9TkNtcVAAAHygAACoyR1NVQrj/uP4AAB74AAAAME9TLzJoWmUcAAABeAAAAGBjbWFwtkIacAAAAxAAAAJWZ2FzcP//AAMAAB7QAAAACGdseWY27KOUAAAGCAAAFcRoZWFkFPal0gAAAPwAAAA2aGhlYQU0Ar0AAAE0AAAAJGhtdHiADw6qAAAB2AAAAThsb2Nh5CzfJAAABWgAAACebWF4cACVAEwAAAFYAAAAIG5hbWXeIPPyAAAbzAAAAiJwb3N0ABeZTwAAHfAAAADdAAEAAAABAAAZ9vREXw889QALA+gAAAAA2ZexNAAAAADZl7E0ADL/yQJ2ArwAAAAIAAIAAAAAAAAAAQAAArz/wwAAAqsAAAAAAnYAAQAAAAAAAAAAAAAAAAAAAE4AAQAAAE4ASQAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAAEAbsBkAAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABYWFhYAEAACgCtArz/wwAAAqkANgAAAAMAAAAAAmQCZAAAACAAAgIPADIAAAAAAU0AAAAAAAAAAAAAALQAAAD3ADUCfQA1AcoANQKrADUCDQA1AX4ANQHYADUBNQA1AcgANQHUADUB8AA1AeEANQHpADUBqQA1AdAANQHpADUCqgA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUB3AA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUAtAAAAAAAAAAAAAMAA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v/bABP/4gAU/+IAFf/TABb/5wAg/+QAMf/nADL/3AAz//QANP/rADX/9AA2//IAN//4ADj/8AA5//QAOv/1ADv/7AA8/+oAPf/7AD7/9wA///IAQP/tAEH/+wBC/+IAQ//2AET/4wBF/7YARv/vAEf/pgBK/6MAS//yACYAB//TAAj/8QAK/84ADP/dAA3/9gAO//EAD//dABD/pgAR/8kAEv+6ABP/7AAU/90AFf/OADH/xAAy/5IAM//sADT/3QA1/+cANv/xADf/9gA4/90AO/9WADz/5wA9//EAPv/sAD//5wBA/84AQf/dAEL/0wBD/+cARP/nAEX/5wBG/+cAR//dAEj/2ABJ/7oASv/JAEv/4gAsAAb/+wAH//sACP/xAAn/zgAK/+cAC//dAAz/9gAN/9gADv/tAA//7AAQ/+kAEf/rABL/3QAT/90AFP/hABX/3QAW/90AMf/nADL/vwAz/+cANP/nADX/8QA2//EAN//sADj/5wA5//YAOv/2ADv/4gA8//EAPf/2AD7/+wA///sAQP/2AEH/+wBC/+wAQ//7AET/7ABF/9MARv/7AEf/yQBI/84ASf+wAEr/xABL/+cADgAG//sACf/xAAv/7AAN//sADv/7AA8AAAAR//EAEv/0ABP/9gAU//EAFf/xABb/7AAx//YAQP/2ACkABv/7AAf/9gAI//sACf/iAAr/5wAL/+wADP/vAA3/3QAO//sAD//qABD/8QAR/+wAEv/nABP/8QAU/+cAFf/iABb/7AAx/+cAMv/vADP//AA0/+cANf/7ADb//gA4//EAOf/8ADr//AA7/+kAPP/6AD3//QA+//4AP//7AEL/6gBD//0ARP/2AEX/7ABG//EAR//YAEj/4gBJ/+wASv/LAEv//AAsAAb/+wAH//EACP/2AAn/0wAK/+IAC//JAAz/5wAN/90ADv/iAA//7AAQ/+cAEf/sABL/3QAT/9MAFP/iABX/zgAW/+cAMf/YADL/xAAz/+wANP/dADX/6AA2//EAN//xADj/4wA5//EAOv/2ADv/7AA8/+wAPf/sAD7/9gA//+wAQP/iAEH/8QBC/90AQ//nAET/5wBF/8QARv/mAEf/xABI/8kASf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cARf/XAEb/6wBH/8kASP/JAEn/twBK/7cAS//nACAABv/7ACQAAgAl/+8AJ//5AC3//gAv//4AMv/oADP//QA0/+sANf/7ADb/+gA3//sAOP/jADn/9wA6//oAO//kADz//wA9//0APv/+AD8AAABA/+gAQf/7AEL/6ABD//sARP/sAEX/8QBG//sAR//qAEj/6wBJ/+cASv/qAEv/+QAbAAb/+wAl/+8AMv+5ADP/+wA0/+8ANf/7ADb/+wA3//0AOP/vADn/+wA6AAAAO/+7ADz//gA9//4APv/7AED/7ABB//4AQv/nAEP/+QBE//kARf/7AEb/+QBH//MASP/rAEn/4gBK/+8AS//7AB0ABv/2ABf/zgAl/+8AMv+3ADP/9wA0/+sANf/3ADb/8QA3//kAOP/uADn/8wA6//sAO//YADz/8wA9/+4APv/3AD//8wBA/+MAQf/3AEL/6QBD/+8ARP/nAEX/1ABG/+8AR//JAEj/zABJ/6YASv/JAEv/3AAcAAb/+wAX//MAJf/7ADL/6wAz//4ANP/uADX/+wA2//4AN//+ADj/8wA5//0AOv/+ADv/7gA8//4APf/+AD7/+wA///4AQP/uAEL/9wBD//4ARP/+AEX/+QBG//4AR//uAEj/9wBJ/+4ASv/zAEv//gAYAAb/+wAx//YAMv/rADP//wA0//MANf//ADYAAQA3//8AOP/zADv/6AA8//4APf/+AD4AAQBA/+4AQf//AEL/8wBD//4ARP/4AEX//QBH/+wASP/3AEn/7ABK//EASwABABwABv/2ABf/4QAy/8oAM//9ADT/+QA1//4ANv/7ADf//gA4//MAOf/+ADr//wA7/+EAPP/7AD3//gA+//4AP//+AED/7wBB//4AQv/zAEP//gBE//sARf/7AEb//gBH/+8ASP/5AEn/2gBK//oAS//+AB0ABv/nABf/5wAx/7AAMv/hADP/7gA0/7QANf/rADb/5wA3/+4AOP+sADn/6wA6//kAO/+3ADz/6gA9/+8APv/nAD//5wBA/6wAQf/uAEL/rgBD/+cARP+8AEX/3ABG/9oAR//cAEj/0QBJ/9oASv/RAEv/7wAeAAb/9gAX//cAI//9ADH/vwAy/+4AM//5ADT/2gA1//4ANv/3ADf/+wA4/9oAOf/3ADr/+wA7/+cAPP/7AD3/+QA+//cAP//5AED/1ABB//sAQv/cAEP/9wBE/+8ARf/JAEb/6wBH/8QASP++AEn/5wBK/8EAS//+ABwAF//7ADH/7AAy/+QAM//+ADT/7gA1//4ANgAAADf//QA4//cAOf/7ADr//gA7/+4APP/+AD3//gA+//0AP//7AED/7wBB//4AQv/uAEP//gBE//cARf/7AEb/+QBH/+gASP/vAEn/6wBK/+gAS//+AB4ABv/7ABf/8wAa//4AHf/3ACX/9wAq//4AMf/2ADL/5AAz//0ANP/zADX/+wA2//4AN//+ADj/+QA7/+4APf/+AD7/+wA///4AQP/2AEH/+gBC/+4AQ//7AET/+QBF//sARv/+AEf/8wBI/+8ASf/zAEr/6wBL//4AHQAG//EAJP/3ADH/7AAy/7sAM//sADT/4wA1/+8ANv/vADf/9wA4/+QAOf/qADr/9wA7/98APP/vAD3/9wA+/+sAP//uAED/4wBB/+4AQv/mAEP/7wBE/+IARf/VAEb/7gBH/8MASP/GAEn/uwBK/7oAS//fABwABv/sACT//gAy/54AM//rADT/6gA1//EANv/rADf/9wA4/+MAOf/oADr/9wA7/64APP/sAD3/8QA+/+wAP//sAED/4QBB//MAQv/oAEP/5ABE/9gARf/kAEb/7gBH/9EASP/QAEn/uwBK/8QAS//zADAAF//3ABj//wAZ/+kAGv//ABv//QAc//4AHf/pAB7/+wAf//8AIP/iACH//gAi//8AI//+ACT//wAl/+IAJ//uACj//gAp/+cAKv/hACv/+QAs/8MALf/QAC7/5AAv/8wAMP//ADL/4QAz//4ANP/jADX/9wA3//kAOP/fADn/9wA7/+IAPP/5AD3/+gA+//EAP//6AED/2gBB/+8AQv/aAET/7wBF/9cARv/qAEf/xgBI/7sASf/qAEr/tABL//sAHQAG/+cAF//oACT/+gAy/+IAM//xADT/zAA1/+8ANv/sADf/+gA4/8wAOf/3ADr/8wA7/8kAPP/uAD3/7wA+/+wAP//rAED/yQBB//cAQv/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/74AM//uADT/3wA1//oANv/xADj/5wA5/+8AOv/5ADv/2AA8/+0APf/9AD7/8wA///EAQP/rAEH/+ABC/+QAQ//3AET/5gBF/9AARv/zAEf/xgBI/80ASf++AEr/twBL/+gAKgAH//EACP/xAAn/0wAK/+YAC//YAAz/5wAN/9gADv/oAA//5wAQ/+IAEf/iABP/2AAU/90AFf/dACT/+wAx/+wAMv+7ADP/9wA0/+QANf/rADb/5wA3//EAOP/kADn/+QA6//YAO//aADz/9wA9//4APv/uAD//8QBA/+cAQf/vAEL/4wBD/+sARP/cAEX/0ABG/+sAR//CAEj/xABJ/7QASv+6AEv/6AAmAAf/9gAI//EACf/sAAr/9gAM/+cADv/6AA//8QAQ//EAEf/vABL/4QAT//EAFP/iABX/5wAy/+kAM//9ADT/5wA1//sANv/9ADf//gA4/+sAOf/+ADoAAQA7/+gAPP/9AD3/9wA+//0AP//9AED/6wBBAAEAQv/pAEP/+QBE/+wARgACAEf/6QBI/+8ASf/nAEr/6wBL//sAKQAH//sACP/xAAn/5wAK/+4AC//2AAz/4gAN//sADv/1AA//8QAQ/90AEf/kABL/4gAT/+wAFP/YABX/3QAx//YAMv+5ADP/+AA0/+MANf/3ADb/+AA3//kAOP/iADn/+gA6//0AO//OADz//QA9//4APv/5AD///ABA/+YAQv/jAEP/9wBE/+YARf/vAEb//gBH/+cASP/vAEn/0QBK/+YAS//9ACgAB//2AAj/4gAJ/90ACv/sAAv/4gAM/+gADf/iAA7/9QAP/+gAEP/dABH/4AAS/+YAE//OABT/4gAV/90AJP/7ADH/9gAy/8EAM//vADT/3wA2//QAN//4ADj/4wA5/+kAOv/6ADv/0QA8/+YAPf/zAD7/6QA///EAQP/qAEL/3ABD/+gARP/fAEb/+ABH/7sASP+7AEn/rwBK/68AS//jACcACP/xAAn/7AAK//gADP/2AA7/9wAP//YAEP/xABH/5wAS/+cAE//xABT/7AAV/+UAMf/2ADL/6AAz//kANP/qADX/+wA2//oAN//7ADj/6wA5//cAOv//ADv/4wA8//sAPf/+AD7/+wA///oAQP/sAEH/+gBC/+MAQ//5AET/7wBF/+oARv/7AEf/4wBI/+wASf/jAEr/6gBL//4AJgAH//sACP/7AAn/5wAK//oADP/2AA7/9gAP//YAEP/xABH/8QAS//IAE//xABT/5wAV//EAMv/nADP/+wA0//EANf/9ADb//gA3//4AOP/uADn/+wA6//4AO//oAD0AAAA+//sAP//+AED/7wBB//4AQv/qAEP//wBE//EARf/3AEb/+wBH/+YASP/3AEn/2gBK/+QAS//7ACkAB//2AAj/9gAJ/90ACv/yAAz/8QAO//EAD//wABD/6gAR/+wAEv/mABP/9AAU/+wAFf/rABf/zgAx//YAMv/OADP/7wA0/+oANf/5ADb//gA3//0AOP/oADn/+QA6//0AO//YADz//gA9//8APv/6AD//+QBA/+4AQf/5AEL/4wBD//gARP/qAEX/+QBG//oAR//pAEj/6QBJ/9UASv/rAEv/+gAqAAf/sgAI/8kACf+wAAr/ugAL/7UADP+1AA3/3QAO/+QAD/+6ABD/sgAR/7UAEv+xABP/4gAU/6sAFf+mADH/lwAy/9oAM//jADT/qwA1/+IANv/iADf/4wA4/5oAOf/XADr/7gA7/7QAPP/kAD3/6wA+/+4AP//mAED/rQBB/+8AQv+qAEP/6gBE/74ARf/XAEb/2gBH/9AASP/SAEn/1QBK/80AS//qACsAB//nAAj/8QAJ/6YACv/sAAv/nAAM/90ADf+6AA7/9gAP/+IAEP/sABH/3QAS/9oAE//sABT/3QAV/8QAJP/+ADH/pgAy/+sAM//vADT/ygA1//0ANv/zADf/+wA4/9MAOf/vADr/+wA7/9gAPP/3AD3/9wA+//EAP//7AED/1QBB//cAQv/PAEP/8wBE/+YARf+7AEb/5wBH/7UASP/JAEn/2gBK/6UAS//zACkAB//2AAn/7AAK//kAC//sAAz/9gAO//oAD//2ABD/7AAR/+cAEv/vABP/9gAU//EAFf/sABcAAQAx/+YAMv/pADP/+QA0/+oANf/zADb/+wA3//oAOP/nADn/9wA6//4AO//uADz/+QA9//oAPv/7AD//+QBA/+8AQf/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j/xgA5//sAOv/3ADv/pQA8/+8APf/+AD7/7gA//+oAQP/DAEH/7gBC/8QAQ//vAET/0ABF/+4ARv/uAEf/6QBI/+QASf/aAEr/5gBL//cAKgAH/8QACP/OAAn/pgAL/7oADP+rAA3/3QAO/+cAD/+5ABD/twAR/8QAEv+zABP/0wAU/7AAFf+cACT/+wAx/6EAMv/aADP/4wA0/7cANf/4ADb/4wA3//0AOP+3ADn/7gA6/+8AO/+7ADz/7gA9//EAPv/jAD//6ABA/7oAQf/zAEL/uQBD/+sARP/OAEX/3wBG/+EAR//aAEj/2ABJ/9gASv/MAEv/7gAsAAf/yQAI/84ACf/JAAr/wgAL/8kADP/JAA3//gAO/8kAD/+6ABD/jQAR/7oAEv+gABP/4gAU/7UAFf+6AB7/8QAk//sAMf+1ADL/lwAz/+8ANP+7ADX/5gA2/+4AN//uADj/uQA5/+gAOv/3ADv/hAA8/+8APf/sAD7/7AA//+oAQP+6AEH/7ABC/7kAQ//pAET/ygBF/+8ARv/vAEf/6ABI/+kASf/fAEr/5ABL//EAJgAH//YACf/iAAr/7AAL/+cADP/iAA3//wAO//UAD//nABD/7AAR/+IAEv/gABP/7AAU/90AFf/TADH/4gAy/+sAM//+ADT/6AA1//4ANgAEADf//wA4/9wAOf/6ADv/5gA8//8APf//AD///QBA/+MAQf//AEMAAABE/+8ARf/4AEb/+wBH//cASP/rAEn/6QBK/+kAS//9AAIAAQAGAEsAAAAAAAAAAQAAAADUGBYRAAAAANmXsTQAAAAA2ZexNA==",at=n=>Hr("http://www.w3.org/2000/svg",n),ul=(n,t)=>{const e=at("rect");return e.setAttribute("height",`${n}`),e.setAttribute("width",`${t}`),e},Al=(n,t,e,a)=>{const i=fe("filter");i.setAttribute("id",a),i.setAttribute("height","200%"),i.setAttribute("width","200%"),i.setAttribute("x","-50%"),i.setAttribute("y","-50%");const r=fe("feOffset");i.appendChild(r),r.setAttribute("result","offOut"),r.setAttribute("in","SourceAlpha"),r.setAttribute("dx",`${n}`),r.setAttribute("dy",`${t}`);const o=fe("feGaussianBlur");i.appendChild(o),o.setAttribute("result","blurOut"),o.setAttribute("in","offOut"),o.setAttribute("stdDeviation",`${e}`);const s=fe("feBlend");return i.appendChild(s),s.setAttribute("in","SourceGraphic"),s.setAttribute("in2","blurOut"),s.setAttribute("mode","normal"),i},hl=n=>{let t=n;return t=t.replace(/feoffset/gi,"feOffset"),t=t.replace(/fegaussianblur/gi,"feGaussianBlur"),t=t.replace(/feblend/gi,"feBlend"),t=t.replace(/lineargradient/gi,"linearGradient"),t=t.replace(/stddeviation/gi,"stdDeviation"),t};function gl(n,t,e,a,i,r){const o=i,s=r,l={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]};if(l.width<=0)return;const c=ml(l.height,l.width,e*o,a*s),d=(a-c*l.width)/2-c*l.x,u=(e-c*l.height)/2-c*l.y;n.setAttribute("transform",`translate(${d} ${u}) scale(${c} ${c})`)}function ml(n,t,e,a){const i=e/n,r=a/t;return i>1&&r>1?Math.min(i,r):i>1&&r<1?r:i<1&&r>1?i:Math.min(i,r)}const En={m:["x","y"],z:[],l:["x","y"],h:["x"],v:["y"],c:["x1","y1","x2","y2","x","y"],s:["x2","y2","x","y"],q:["x1","y1","x","y"],t:["x","y"],a:["rx","ry","xRotation","largeArc","sweep","x","y"]};class pl{constructor(t){const e=Array.from(t.querySelectorAll("path"));this.paths=e.map(a=>{const i=a.getAttribute("d")||"",r=this.parsePath(i);return{pathElement:a,pathData:r}})}transform(t){for(const e of this.paths)e.pathData=this.runTransformer(e.pathData,t);this.update()}encodePath(t){let e="";const i=r=>{const o=[],s=r.relative?r.type:r.type.toUpperCase();let l=e!==s;const c=En[r.type];l&&(o.push(s),e=s);for(const d of c){const u=r[d];let A;switch(typeof u){case"boolean":A=u|0;break;case"number":A=(u*100|0)/100;break;default:throw new It("Failed to encode path.")}l||o.push(" "),o.push(A),l=!1}return o.join("")};return t.map(i).join("")}parsePath(t){const e=/([mzlhvcsqta])([^mzlhvcsqta]*)/gi,a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,i=[];let r;for(e.lastIndex=0;r=e.exec(t);){const o=r[1].toLowerCase(),s=(r[2].match(a)||[]).map(parseFloat),l=o===r[1],c=En[o];if(s.length<c.length)throw new It(`Path type "${o}" given ${s.length} arguments, expected ${c.length}.`);if(c.length>0){if(s.length%c.length!==0)throw new It(`Path type "${o}" given ${s.length} arguments, not divisible by ${c.length}`);for(let d=0;d<s.length/c.length;d++){const u={type:o,relative:l};for(let A=0;A<c.length;A++)u[c[A]]=s[d*c.length+A];i.push(u)}}else i.push({type:o,relative:l})}return i}runTransformer(t,e){const a=[["x1","y1"],["x2","y2"],["x","y"]],i=r=>{for(let o=0;o<a.length;o++){const[s,l]=a[o];if(s in r&&l in r){const c=[r[s],r[l]],d=e(c);if(d.length<2)throw new It("Transformer must return at least 2 points.");r[s]=d[0],r[l]=d[1]}}return r};return this.transformPath(t,i)}transformPath(t,e){const a=[];for(let i=0;i<t.length;i++){const r=JSON.parse(JSON.stringify(t[i])),o=e(r);Array.isArray(o)?a.push(...o):o&&a.push(o)}return a}update(){for(const{pathElement:t,pathData:e}of this.paths){const a=this.encodePath(e);t.setAttribute("d",a)}}}class fl extends cl{constructor(){super(...arguments),this.moduleName="Vegemite"}svgPreview(t,e){return this.svgElement(t,e)}svgPrint(t,e){return this.svgElement(t,e)}svgElement(t,e){const a=Ps(dl),r=t!==""?(w=>w.charAt(0).toUpperCase()+w.substr(1).toLowerCase())(t):"",o=a.getPath(r,0,72,72),s=o.toSVG(2),l=o.getBoundingBox(),c=l.x2-l.x1,d=o.toPathData(3),u=()=>{const w=at("g");w.classList.add("module-text-group");const F=at("defs");w.appendChild(F),F.appendChild(Al(0,2,2,"shadow"));const b=at("path");b.setAttribute("d",d),b.setAttribute("stroke","black"),b.setAttribute("stroke-width","3"),F.appendChild(b);const v=at("g");v.classList.add("module-layer0"),w.appendChild(v),v.setAttribute("filter","url(#shadow)"),v.innerHTML=b.outerHTML;const I=at("g");I.classList.add("module-layer1"),w.appendChild(I),I.setAttribute("stroke-width","3"),I.setAttribute("stroke","rgb(45,41,38)"),I.setAttribute("fill","rgb(45,41,38)"),I.setAttribute("transform","translate(0.5,0)"),I.innerHTML=s;const M=at("g");M.classList.add("module-layer2"),w.appendChild(M),M.setAttribute("fill","rgb(255,209,0)"),M.setAttribute("transform","translate(1,-0.1)"),M.innerHTML=s;const R=at("g");return R.classList.add("module-layer3"),w.appendChild(R),R.setAttribute("fill","white"),R.innerHTML=s,new pl(w).transform(([T,L])=>[T,L+(c/2-T)**2/(c*6)]),w},A=at("g");A.classList.add("module-root");const h=at("defs");A.appendChild(h);const g=at("g");g.classList.add("module-bounds"),A.appendChild(g);const p=ul(e.height,e.width);p.setAttribute("opacity","0"),g.appendChild(p);const m=at("g");m.classList.add("module-text-enclosure"),A.appendChild(m);const f=u();m.appendChild(f);const y=Rr(d);return gl(m,y,e.height,e.width,.35,.65),hl(A.outerHTML)}}async function Mi(n){if(n==="Vegemite")return new fl;throw new O(`Failed to resolve Module, Module ${n} not found`)}const Cl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],wl=async(n,t,e)=>{const a=t.data,i=e.data.baseUrl,r=a.assetUrl.replace("localhost","localstack"),o=i.slice(0,4)==="http"?"":"https://",s=new URL(o+i);s.searchParams.append("video",An(JSON.stringify([{href:r}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${An(await Un.toString(l,{type:"svg"}))}`,u=h=>{const g=n.find(m=>m.panelId===h.panelId);if(!g)throw new Y(h);const p=N();return new G({id:p,src:d,type:D.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},A=e.data.regions;try{return A.map(u)}catch(h){return console.error(h),[]}},yl=async(n,t,e,a)=>{const i=e.data,r=i.assetUrl,o=await Ea(r);try{const s=await Us(i,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await Ei(c,s?.asset?.fileLink),u=await Ae(d),A=N(),h=n.find(p=>p.panelId===c.panelId);if(!h)throw new Y(c);const g=qa(o,u,{scale:i.scale,left:i.x,top:i.y},a.data.forceImageCover);return[new G({id:A,path:u.path,type:D.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/u.width,scaleY:c.height/u.height,pattern:{id:`${A}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},Sl=async(n,t,e,a)=>{const i=e.data,r=a.option;if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(b=>b.id===i.illustrationVariantId)||await P.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${i.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${i.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${i.illustrationVariantId}`),[];const l=await et(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],u=d?.length>0?d[0]:"",g=ct().parseFromString(u,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Le(g);const p={};Ut(g,b=>{Cl.includes(b.tagName)&&!b.attributes.getNamedItem("fill")&&b.setAttribute("fill","#000000");const v=b.attributes.getNamedItem("fill");if(v&&v.value!=="none"){const M=v.value,x=`spiff-fill-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}const I=b.attributes.getNamedItem("stroke");if(I&&I.value!=="none"){const M=I.value,x=`spiff-stroke-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}});const f=Et().serializeToString(g),y=i.colors;if(y){for(const[b,v]of Object.entries(p))for(const I of Object.keys(y))if(v.browserValue===I){p[b]={browserValue:y[I]};break}}const w=b=>{const v=n.find(M=>M.panelId===b.panelId);if(!v)throw new Y(b);const I=N();return new G({colors:p,id:I,svg:f,type:D.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},v)},F=a.data.regions;try{return F.map(w)}catch(b){return console.error(b),[]}},vl=async(n,t,e)=>{const a=await Mi(e.data.module),i=t.data,r=(s,l)=>{const c=n.find(u=>u.panelId===l.panelId);if(!c)throw new Y(l);const d=N();return new G({colors:{},id:d,svg:s,type:D.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>r(a.svgPrint(i.text,s),s))}catch(s){return console.error(s),[]}},El=async(n,t,e,a)=>{const i=e.data,r=a.option;if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(d=>d.id===i.pictureVariantId)||await P.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${i.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${i.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${i.pictureVariantId}`),[];const l=d=>{const u=n.find(h=>h.panelId===d.panelId);if(!u)throw new Y(d);const A=N();return new G({id:A,src:s,type:D.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},u)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},bl=async(n,t,e,a)=>{const i=e.data,r=a.option;if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(c=>c.id===i.colorVariantId)||await P.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${i.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(p=>p.panelId===c.panelId);if(!d)throw new Y(c);const u=`
|
|
1409
|
+
`);w.push(this.generateTextChangeCommandsForRegion(p.get(b.id)||1,t.data,b.id,v))}return new U(w)}}const j=new cl;class dl{}const ul="data:application/octet-stream;base64,AAEAAAAPAIAAAwBwRkZUTYdHeHoAAElcAAAAHEdERUYAJwBUAAAe2AAAAB5HUE9TkNtcVAAAHygAACoyR1NVQrj/uP4AAB74AAAAME9TLzJoWmUcAAABeAAAAGBjbWFwtkIacAAAAxAAAAJWZ2FzcP//AAMAAB7QAAAACGdseWY27KOUAAAGCAAAFcRoZWFkFPal0gAAAPwAAAA2aGhlYQU0Ar0AAAE0AAAAJGhtdHiADw6qAAAB2AAAAThsb2Nh5CzfJAAABWgAAACebWF4cACVAEwAAAFYAAAAIG5hbWXeIPPyAAAbzAAAAiJwb3N0ABeZTwAAHfAAAADdAAEAAAABAAAZ9vREXw889QALA+gAAAAA2ZexNAAAAADZl7E0ADL/yQJ2ArwAAAAIAAIAAAAAAAAAAQAAArz/wwAAAqsAAAAAAnYAAQAAAAAAAAAAAAAAAAAAAE4AAQAAAE4ASQAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAAEAbsBkAAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABYWFhYAEAACgCtArz/wwAAAqkANgAAAAMAAAAAAmQCZAAAACAAAgIPADIAAAAAAU0AAAAAAAAAAAAAALQAAAD3ADUCfQA1AcoANQKrADUCDQA1AX4ANQHYADUBNQA1AcgANQHUADUB8AA1AeEANQHpADUBqQA1AdAANQHpADUCqgA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUB3AA1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/+QBH/84ASP/JAEn/twBK/8EAS//rAB8ABv/7ABL/3wAX/8kAJf/5ACv/7wAy/7oAM//zADT/6wA1/+8ANv/uADf/8wA4/+oAOf/vADr/7wA7/9QAPP/5AD3//gA+//EAP//vAED/4wBB//MAQv/mAEP/7gBE/+cARf/XAEb/6wBH/8kASP/JAEn/twBK/7cAS//nACAABv/7ACQAAgAl/+8AJ//5AC3//gAv//4AMv/oADP//QA0/+sANf/7ADb/+gA3//sAOP/jADn/9wA6//oAO//kADz//wA9//0APv/+AD8AAABA/+gAQf/7AEL/6ABD//sARP/sAEX/8QBG//sAR//qAEj/6wBJ/+cASv/qAEv/+QAbAAb/+wAl/+8AMv+5ADP/+wA0/+8ANf/7ADb/+wA3//0AOP/vADn/+wA6AAAAO/+7ADz//gA9//4APv/7AED/7ABB//4AQv/nAEP/+QBE//kARf/7AEb/+QBH//MASP/rAEn/4gBK/+8AS//7AB0ABv/2ABf/zgAl/+8AMv+3ADP/9wA0/+sANf/3ADb/8QA3//kAOP/uADn/8wA6//sAO//YADz/8wA9/+4APv/3AD//8wBA/+MAQf/3AEL/6QBD/+8ARP/nAEX/1ABG/+8AR//JAEj/zABJ/6YASv/JAEv/3AAcAAb/+wAX//MAJf/7ADL/6wAz//4ANP/uADX/+wA2//4AN//+ADj/8wA5//0AOv/+ADv/7gA8//4APf/+AD7/+wA///4AQP/uAEL/9wBD//4ARP/+AEX/+QBG//4AR//uAEj/9wBJ/+4ASv/zAEv//gAYAAb/+wAx//YAMv/rADP//wA0//MANf//ADYAAQA3//8AOP/zADv/6AA8//4APf/+AD4AAQBA/+4AQf//AEL/8wBD//4ARP/4AEX//QBH/+wASP/3AEn/7ABK//EASwABABwABv/2ABf/4QAy/8oAM//9ADT/+QA1//4ANv/7ADf//gA4//MAOf/+ADr//wA7/+EAPP/7AD3//gA+//4AP//+AED/7wBB//4AQv/zAEP//gBE//sARf/7AEb//gBH/+8ASP/5AEn/2gBK//oAS//+AB0ABv/nABf/5wAx/7AAMv/hADP/7gA0/7QANf/rADb/5wA3/+4AOP+sADn/6wA6//kAO/+3ADz/6gA9/+8APv/nAD//5wBA/6wAQf/uAEL/rgBD/+cARP+8AEX/3ABG/9oAR//cAEj/0QBJ/9oASv/RAEv/7wAeAAb/9gAX//cAI//9ADH/vwAy/+4AM//5ADT/2gA1//4ANv/3ADf/+wA4/9oAOf/3ADr/+wA7/+cAPP/7AD3/+QA+//cAP//5AED/1ABB//sAQv/cAEP/9wBE/+8ARf/JAEb/6wBH/8QASP++AEn/5wBK/8EAS//+ABwAF//7ADH/7AAy/+QAM//+ADT/7gA1//4ANgAAADf//QA4//cAOf/7ADr//gA7/+4APP/+AD3//gA+//0AP//7AED/7wBB//4AQv/uAEP//gBE//cARf/7AEb/+QBH/+gASP/vAEn/6wBK/+gAS//+AB4ABv/7ABf/8wAa//4AHf/3ACX/9wAq//4AMf/2ADL/5AAz//0ANP/zADX/+wA2//4AN//+ADj/+QA7/+4APf/+AD7/+wA///4AQP/2AEH/+gBC/+4AQ//7AET/+QBF//sARv/+AEf/8wBI/+8ASf/zAEr/6wBL//4AHQAG//EAJP/3ADH/7AAy/7sAM//sADT/4wA1/+8ANv/vADf/9wA4/+QAOf/qADr/9wA7/98APP/vAD3/9wA+/+sAP//uAED/4wBB/+4AQv/mAEP/7wBE/+IARf/VAEb/7gBH/8MASP/GAEn/uwBK/7oAS//fABwABv/sACT//gAy/54AM//rADT/6gA1//EANv/rADf/9wA4/+MAOf/oADr/9wA7/64APP/sAD3/8QA+/+wAP//sAED/4QBB//MAQv/oAEP/5ABE/9gARf/kAEb/7gBH/9EASP/QAEn/uwBK/8QAS//zADAAF//3ABj//wAZ/+kAGv//ABv//QAc//4AHf/pAB7/+wAf//8AIP/iACH//gAi//8AI//+ACT//wAl/+IAJ//uACj//gAp/+cAKv/hACv/+QAs/8MALf/QAC7/5AAv/8wAMP//ADL/4QAz//4ANP/jADX/9wA3//kAOP/fADn/9wA7/+IAPP/5AD3/+gA+//EAP//6AED/2gB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P/fAEb/+ABH/7sASP+7AEn/rwBK/68AS//jACcACP/xAAn/7AAK//gADP/2AA7/9wAP//YAEP/xABH/5wAS/+cAE//xABT/7AAV/+UAMf/2ADL/6AAz//kANP/qADX/+wA2//oAN//7ADj/6wA5//cAOv//ADv/4wA8//sAPf/+AD7/+wA///oAQP/sAEH/+gBC/+MAQ//5AET/7wBF/+oARv/7AEf/4wBI/+wASf/jAEr/6gBL//4AJgAH//sACP/7AAn/5wAK//oADP/2AA7/9gAP//YAEP/xABH/8QAS//IAE//xABT/5wAV//EAMv/nADP/+wA0//EANf/9ADb//gA3//4AOP/uADn/+wA6//4AO//oAD0AAAA+//sAP//+AED/7wBB//4AQv/qAEP//wBE//EARf/3AEb/+wBH/+YASP/3AEn/2gBK/+QAS//7ACkAB//2AAj/9gAJ/90ACv/yAAz/8QAO//EAD//wABD/6gAR/+wAEv/mABP/9AAU/+wAFf/rABf/zgAx//YAMv/OADP/7wA0/+oANf/5ADb//gA3//0AOP/oADn/+QA6//0AO//YADz//gA9//8APv/6AD//+QBA/+4AQf/5AEL/4wBD//gARP/qAEX/+QBG//oAR//pAEj/6QBJ/9UASv/rAEv/+gAqAAf/sgAI/8kACf+wAAr/ugAL/7UADP+1AA3/3QAO/+QAD/+6ABD/sgAR/7UAEv+xABP/4gAU/6sAFf+mADH/lwAy/9oAM//jADT/qwA1/+IANv/iADf/4wA4/5oAOf/XADr/7gA7/7QAPP/kAD3/6wA+/+4AP//mAED/rQBB/+8AQv+qAEP/6gBE/74ARf/XAEb/2gBH/9AASP/SAEn/1QBK/80AS//qACsAB//nAAj/8QAJ/6YACv/sAAv/nAAM/90ADf+6AA7/9gAP/+IAEP/sABH/3QAS/9oAE//sABT/3QAV/8QAJP/+ADH/pgAy/+sAM//vADT/ygA1//0ANv/zADf/+wA4/9MAOf/vADr/+wA7/9gAPP/3AD3/9wA+//EAP//7AED/1QBB//cAQv/PAEP/8wBE/+YARf+7AEb/5wBH/7UASP/JAEn/2gBK/6UAS//zAC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+YARP/KAEX/6QBG/+8AR//jAEj/3wBJ/9MASv/hAEv/6wApAAf/zgAI/84ACf/TAAv/2AAM/84ADv/eAA//xAAQ/7AAEf/TABL/sQAT/+wAFP/FABX/yQAk//sAMf/JADL/lQAz//MANP/BADX/+QA2//MAN//3ADj/xgA5//sAOv/3ADv/pQA8/+8APf/+AD7/7gA//+oAQP/DAEH/7gBC/8QAQ//vAET/0ABF/+4ARv/uAEf/6QBI/+QASf/aAEr/5gBL//cAKgAH/8QACP/OAAn/pgAL/7oADP+rAA3/3QAO/+cAD/+5ABD/twAR/8QAEv+zABP/0wAU/7AAFf+cACT/+wAx/6EAMv/aADP/4wA0/7cANf/4ADb/4wA3//0AOP+3ADn/7gA6/+8AO/+7ADz/7gA9//EAPv/jAD//6ABA/7oAQf/zAEL/uQBD/+sARP/OAEX/3wBG/+EAR//aAEj/2ABJ/9gASv/MAEv/7gAsAAf/yQAI/84ACf/JAAr/wgAL/8kADP/JAA3//gAO/8kAD/+6ABD/jQAR/7oAEv+gABP/4gAU/7UAFf+6AB7/8QAk//sAMf+1ADL/lwAz/+8ANP+7ADX/5gA2/+4AN//uADj/uQA5/+gAOv/3ADv/hAA8/+8APf/sAD7/7AA//+oAQP+6AEH/7ABC/7kAQ//pAET/ygBF/+8ARv/vAEf/6ABI/+kASf/fAEr/5ABL//EAJgAH//YACf/iAAr/7AAL/+cADP/iAA3//wAO//UAD//nABD/7AAR/+IAEv/gABP/7AAU/90AFf/TADH/4gAy/+sAM//+ADT/6AA1//4ANgAEADf//wA4/9wAOf/6ADv/5gA8//8APf//AD///QBA/+MAQf//AEMAAABE/+8ARf/4AEb/+wBH//cASP/rAEn/6QBK/+kAS//9AAIAAQAGAEsAAAAAAAAAAQAAAADUGBYRAAAAANmXsTQAAAAA2ZexNA==",at=n=>Hr("http://www.w3.org/2000/svg",n),Al=(n,t)=>{const e=at("rect");return e.setAttribute("height",`${n}`),e.setAttribute("width",`${t}`),e},hl=(n,t,e,a)=>{const i=fe("filter");i.setAttribute("id",a),i.setAttribute("height","200%"),i.setAttribute("width","200%"),i.setAttribute("x","-50%"),i.setAttribute("y","-50%");const r=fe("feOffset");i.appendChild(r),r.setAttribute("result","offOut"),r.setAttribute("in","SourceAlpha"),r.setAttribute("dx",`${n}`),r.setAttribute("dy",`${t}`);const o=fe("feGaussianBlur");i.appendChild(o),o.setAttribute("result","blurOut"),o.setAttribute("in","offOut"),o.setAttribute("stdDeviation",`${e}`);const s=fe("feBlend");return i.appendChild(s),s.setAttribute("in","SourceGraphic"),s.setAttribute("in2","blurOut"),s.setAttribute("mode","normal"),i},gl=n=>{let t=n;return t=t.replace(/feoffset/gi,"feOffset"),t=t.replace(/fegaussianblur/gi,"feGaussianBlur"),t=t.replace(/feblend/gi,"feBlend"),t=t.replace(/lineargradient/gi,"linearGradient"),t=t.replace(/stddeviation/gi,"stdDeviation"),t};function ml(n,t,e,a,i,r){const o=i,s=r,l={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]};if(l.width<=0)return;const c=pl(l.height,l.width,e*o,a*s),d=(a-c*l.width)/2-c*l.x,u=(e-c*l.height)/2-c*l.y;n.setAttribute("transform",`translate(${d} ${u}) scale(${c} ${c})`)}function pl(n,t,e,a){const i=e/n,r=a/t;return i>1&&r>1?Math.min(i,r):i>1&&r<1?r:i<1&&r>1?i:Math.min(i,r)}const En={m:["x","y"],z:[],l:["x","y"],h:["x"],v:["y"],c:["x1","y1","x2","y2","x","y"],s:["x2","y2","x","y"],q:["x1","y1","x","y"],t:["x","y"],a:["rx","ry","xRotation","largeArc","sweep","x","y"]};class fl{constructor(t){const e=Array.from(t.querySelectorAll("path"));this.paths=e.map(a=>{const i=a.getAttribute("d")||"",r=this.parsePath(i);return{pathElement:a,pathData:r}})}transform(t){for(const e of this.paths)e.pathData=this.runTransformer(e.pathData,t);this.update()}encodePath(t){let e="";const i=r=>{const o=[],s=r.relative?r.type:r.type.toUpperCase();let l=e!==s;const c=En[r.type];l&&(o.push(s),e=s);for(const d of c){const u=r[d];let A;switch(typeof u){case"boolean":A=u|0;break;case"number":A=(u*100|0)/100;break;default:throw new It("Failed to encode path.")}l||o.push(" "),o.push(A),l=!1}return o.join("")};return t.map(i).join("")}parsePath(t){const e=/([mzlhvcsqta])([^mzlhvcsqta]*)/gi,a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,i=[];let r;for(e.lastIndex=0;r=e.exec(t);){const o=r[1].toLowerCase(),s=(r[2].match(a)||[]).map(parseFloat),l=o===r[1],c=En[o];if(s.length<c.length)throw new It(`Path type "${o}" given ${s.length} arguments, expected ${c.length}.`);if(c.length>0){if(s.length%c.length!==0)throw new It(`Path type "${o}" given ${s.length} arguments, not divisible by ${c.length}`);for(let d=0;d<s.length/c.length;d++){const u={type:o,relative:l};for(let A=0;A<c.length;A++)u[c[A]]=s[d*c.length+A];i.push(u)}}else i.push({type:o,relative:l})}return i}runTransformer(t,e){const a=[["x1","y1"],["x2","y2"],["x","y"]],i=r=>{for(let o=0;o<a.length;o++){const[s,l]=a[o];if(s in r&&l in r){const c=[r[s],r[l]],d=e(c);if(d.length<2)throw new It("Transformer must return at least 2 points.");r[s]=d[0],r[l]=d[1]}}return r};return this.transformPath(t,i)}transformPath(t,e){const a=[];for(let i=0;i<t.length;i++){const r=JSON.parse(JSON.stringify(t[i])),o=e(r);Array.isArray(o)?a.push(...o):o&&a.push(o)}return a}update(){for(const{pathElement:t,pathData:e}of this.paths){const a=this.encodePath(e);t.setAttribute("d",a)}}}class Cl extends dl{constructor(){super(...arguments),this.moduleName="Vegemite"}svgPreview(t,e){return this.svgElement(t,e)}svgPrint(t,e){return this.svgElement(t,e)}svgElement(t,e){const a=xs(ul),r=t!==""?(w=>w.charAt(0).toUpperCase()+w.substr(1).toLowerCase())(t):"",o=a.getPath(r,0,72,72),s=o.toSVG(2),l=o.getBoundingBox(),c=l.x2-l.x1,d=o.toPathData(3),u=()=>{const w=at("g");w.classList.add("module-text-group");const F=at("defs");w.appendChild(F),F.appendChild(hl(0,2,2,"shadow"));const b=at("path");b.setAttribute("d",d),b.setAttribute("stroke","black"),b.setAttribute("stroke-width","3"),F.appendChild(b);const v=at("g");v.classList.add("module-layer0"),w.appendChild(v),v.setAttribute("filter","url(#shadow)"),v.innerHTML=b.outerHTML;const I=at("g");I.classList.add("module-layer1"),w.appendChild(I),I.setAttribute("stroke-width","3"),I.setAttribute("stroke","rgb(45,41,38)"),I.setAttribute("fill","rgb(45,41,38)"),I.setAttribute("transform","translate(0.5,0)"),I.innerHTML=s;const M=at("g");M.classList.add("module-layer2"),w.appendChild(M),M.setAttribute("fill","rgb(255,209,0)"),M.setAttribute("transform","translate(1,-0.1)"),M.innerHTML=s;const R=at("g");return R.classList.add("module-layer3"),w.appendChild(R),R.setAttribute("fill","white"),R.innerHTML=s,new fl(w).transform(([T,L])=>[T,L+(c/2-T)**2/(c*6)]),w},A=at("g");A.classList.add("module-root");const h=at("defs");A.appendChild(h);const g=at("g");g.classList.add("module-bounds"),A.appendChild(g);const p=Al(e.height,e.width);p.setAttribute("opacity","0"),g.appendChild(p);const m=at("g");m.classList.add("module-text-enclosure"),A.appendChild(m);const f=u();m.appendChild(f);const y=Rr(d);return ml(m,y,e.height,e.width,.35,.65),gl(A.outerHTML)}}async function Mi(n){if(n==="Vegemite")return new Cl;throw new O(`Failed to resolve Module, Module ${n} not found`)}const wl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],yl=async(n,t,e)=>{const a=t.data,i=e.data.baseUrl,r=a.assetUrl.replace("localhost","localstack"),o=i.slice(0,4)==="http"?"":"https://",s=new URL(o+i);s.searchParams.append("video",An(JSON.stringify([{href:r}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${An(await Un.toString(l,{type:"svg"}))}`,u=h=>{const g=n.find(m=>m.panelId===h.panelId);if(!g)throw new Y(h);const p=N();return new G({id:p,src:d,type:D.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},A=e.data.regions;try{return A.map(u)}catch(h){return console.error(h),[]}},Sl=async(n,t,e,a)=>{const i=e.data,r=i.assetUrl,o=await Ea(r);try{const s=await Vs(i,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await Ei(c,s?.asset?.fileLink),u=await Ae(d),A=N(),h=n.find(p=>p.panelId===c.panelId);if(!h)throw new Y(c);const g=qa(o,u,{scale:i.scale,left:i.x,top:i.y},a.data.forceImageCover);return[new G({id:A,path:u.path,type:D.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/u.width,scaleY:c.height/u.height,pattern:{id:`${A}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},vl=async(n,t,e,a)=>{const i=e.data,r=a.option;if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(b=>b.id===i.illustrationVariantId)||await P.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${i.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${i.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${i.illustrationVariantId}`),[];const l=await et(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],u=d?.length>0?d[0]:"",g=ct().parseFromString(u,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Le(g);const p={};Ut(g,b=>{wl.includes(b.tagName)&&!b.attributes.getNamedItem("fill")&&b.setAttribute("fill","#000000");const v=b.attributes.getNamedItem("fill");if(v&&v.value!=="none"){const M=v.value,x=`spiff-fill-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}const I=b.attributes.getNamedItem("stroke");if(I&&I.value!=="none"){const M=I.value,x=`spiff-stroke-${M.replace(/\W/g,"")}`;b.classList.add(x),p[x]={browserValue:M}}});const f=Et().serializeToString(g),y=i.colors;if(y){for(const[b,v]of Object.entries(p))for(const I of Object.keys(y))if(v.browserValue===I){p[b]={browserValue:y[I]};break}}const w=b=>{const v=n.find(M=>M.panelId===b.panelId);if(!v)throw new Y(b);const I=N();return new G({colors:p,id:I,svg:f,type:D.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},v)},F=a.data.regions;try{return F.map(w)}catch(b){return console.error(b),[]}},El=async(n,t,e)=>{const a=await Mi(e.data.module),i=t.data,r=(s,l)=>{const c=n.find(u=>u.panelId===l.panelId);if(!c)throw new Y(l);const d=N();return new G({colors:{},id:d,svg:s,type:D.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>r(a.svgPrint(i.text,s),s))}catch(s){return console.error(s),[]}},bl=async(n,t,e,a)=>{const i=e.data,r=a.option;if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(d=>d.id===i.pictureVariantId)||await P.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${i.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${i.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${i.pictureVariantId}`),[];const l=d=>{const u=n.find(h=>h.panelId===d.panelId);if(!u)throw new Y(d);const A=N();return new G({id:A,src:s,type:D.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},u)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Il=async(n,t,e,a)=>{const i=e.data,r=a.option;if(!r)return console.error(`No option for step ${a.stepName}.`),[];const o=r.variants?.find(c=>c.id===i.colorVariantId)||await P.getDefaultVariant(r,a.overrideDefaultVariantId);if(!o)return console.error(`No variant with ID: ${i.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(p=>p.panelId===c.panelId);if(!d)throw new Y(c);const u=`
|
|
1402
1410
|
<svg
|
|
1403
1411
|
xmlns="http://www.w3.org/2000/svg"
|
|
1404
1412
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
|
@@ -1418,8 +1426,8 @@
|
|
|
1418
1426
|
fill="${o?.color}"
|
|
1419
1427
|
/>
|
|
1420
1428
|
</svg>
|
|
1421
|
-
`,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=N();return new G({colors:h,id:g,svg:u,type:D.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},
|
|
1422
|
-
`)},f))}else i.push(new G(y,f))}return i},
|
|
1429
|
+
`,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=N();return new G({colors:h,id:g,svg:u,type:D.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},Bl=async(n,t,e)=>{const a=[],r=t.type===E.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=r.endsWith(".jpeg")||r.endsWith(".jpg")||r.endsWith(".png")?D.Image:(r.endsWith(".svg"),D.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=n.find(A=>A.panelId===c.panelId);if(!d)throw new Y(c);const u={id:N(),src:r,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===E.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new G(u,d))})}catch(c){console.error(c)}else{const c=await et(r,!0),d=u=>{const A=/<svg.*?<\/svg>/s,h=u.match(A)||[],g=h?.length>0?h[0]:"",f=ct().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new It("Failed to read SVG.");return Le(f),Et().serializeToString(f)};l.forEach(u=>{const A=n.find(g=>g.panelId===u.panelId);if(!A)throw new Y(u);const h={id:N(),src:r,asset_key:r,svg:d(c),colors:{},type:s,y:u.top,x:u.left,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,scaleX:1,scaleY:1,rotation:u.rotation,productOverlay:t.type===E.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new G(h,A))})}return a},Pl=async(n,t,e,a)=>{const i=[],r=e.data,o=30,s=m=>m.vertical?"center":m.textAlign||"center",l=async()=>{const m=a.option;if(!m)return;const f=m.variants?.find(w=>w.id===r.fontVariantId)||await P.getDefaultVariant(m,a.overrideDefaultVariantId);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const y=f.asset.fileLink;if(y)return y},d=await(async()=>{const m=await l();if(!m)return;const f=await Ft(m);return{assetUrl:m,name:f.names.fullName.en}})(),u=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",r.text):r.text)||"",A=Fe(u,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async m=>{const f=m.colorOption;return f?(await P.getDefaultVariant(f))?.color:void 0},g=r.color||await h(a.data),p=a.data.regions;for(const m of p){const f=n.find(w=>w.panelId===m.panelId);if(!f)continue;const y={stepName:e.name,id:N(),align:s(a.data),curved:a.data.curved,fill:r.color||g||"#000000",fontData:d,fontSize:a.data.size||o,height:m.height,layer:m.layer,layerIndex:m.layerIndex,paths:a.data.paths,rotation:m.rotation,text:A,type:D.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:m.width,x:m.left,y:m.top};if(d){const[w,F]=Kt(a.data.size||o,d,m,[Fe(A,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});i.push(new G({...y,fontSize:w,text:y.curved?y.text:(F||[]).join(`
|
|
1430
|
+
`)},f))}else i.push(new G(y,f))}return i},xl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const i=a.selectedVariants;return e.requiredVariantSelections.some(r=>i.find(o=>o.id===r)!==void 0)}return!1}):!0,Ti=async(n,t,e,a)=>{const i=[],r={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case E.DigitalContent:i.push(...await yl(e,o,s));break;case E.Frame:case E.Photo:i.push(...await Sl(e,r,o,s));break;case E.Illustration:i.push(...await vl(e,r,o,s));break;case E.Module:i.push(...await El(e,o,s));break;case E.Picture:i.push(...await bl(e,r,o,s));break;case E.Shape:i.push(...await Il(e,r,o,s));break;case E.Text:i.push(...await Pl(e,r,o,s));break}}for(const o of t.steps)o.type!==E.SilentIllustration&&o.type!==E.ProductOverlay||xl(o,r)&&i.push(...await Bl(e,o,a));return i};class Fl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Ml(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),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}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Dl=()=>new Promise((n,t)=>{try{const a=yt().getContext("webgl2");n(!!a)}catch{n(!1)}}),kl=Dl();class Ml{constructor(t,e,a,i,r){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Va(2),this.id=t,this.name=e,this.service=a,this.panelSize=i,this.getWorkflowManager=r}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=Pt(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Tl(this.getID(),a,await kl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Tl extends Ua{constructor(t,e,a,i,r,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=i,this.layouts=r,this.getWorkflowManager=o}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,i=e/t.height,r=Math.min(a,i);return r>1?t:{width:t.width*r,height:t.height*r}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,i=t.layoutState.layout.height,r=a===1||i===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=r.width,s=r.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/i<g?(l=o,c=i*(o/a)):(l=a*(s/i),c=s);const m=this.resizeFit({width:l,height:c});l=m.width,c=m.height}else l=r.width,c=r.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),u=He(t.layoutState.layout,e,{renderingConfiguration:{purpose:Ot.ThreeD,templatingContext:d}}),A=Kn(u),h=await Ma.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const Nl=(n,t)=>{const e=[];return n.forEach(a=>{const i=t.steps.find(r=>r.stepName===a.stepName);i?.type===E.Text&&a.stepAspectType==="Text"&&e.push({name:i.stepName,data:{text:a.value}})}),e},Ql=async(n,t,e,a)=>{let i={serializableWorkflow:{steps:[]},layouts:{}};i=new U(e.map(l=>new ja(l))).apply(i);const o=await Ti(n,t,e,a);return new U(o).apply(i)},We=C.gql`
|
|
1423
1431
|
fragment GlobalPropertyStateAspectFields on GlobalPropertyStateAspect {
|
|
1424
1432
|
name
|
|
1425
1433
|
value
|
|
@@ -1441,7 +1449,7 @@
|
|
|
1441
1449
|
}
|
|
1442
1450
|
}
|
|
1443
1451
|
}
|
|
1444
|
-
`,
|
|
1452
|
+
`,Ol=C.gql`
|
|
1445
1453
|
${We}
|
|
1446
1454
|
mutation CreateGlobalPropertyState($bundleId: String!) {
|
|
1447
1455
|
globalPropertyStateCreate(bundleId: $bundleId) {
|
|
@@ -1451,7 +1459,7 @@
|
|
|
1451
1459
|
}
|
|
1452
1460
|
}
|
|
1453
1461
|
}
|
|
1454
|
-
`,
|
|
1462
|
+
`,Rl=C.gql`
|
|
1455
1463
|
${We}
|
|
1456
1464
|
mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
|
|
1457
1465
|
globalPropertyStateUpdate(id: $id, aspects: $aspects) {
|
|
@@ -1461,7 +1469,7 @@
|
|
|
1461
1469
|
}
|
|
1462
1470
|
}
|
|
1463
1471
|
}
|
|
1464
|
-
|
|
1472
|
+
`,$l=C.gql`
|
|
1465
1473
|
${We}
|
|
1466
1474
|
query GetGlobalPropertyState($bundleId: String!) {
|
|
1467
1475
|
globalPropertyState(bundleId: $bundleId) {
|
|
@@ -1471,7 +1479,7 @@
|
|
|
1471
1479
|
}
|
|
1472
1480
|
}
|
|
1473
1481
|
}
|
|
1474
|
-
|
|
1482
|
+
`,Ul=async n=>(await S.getShadowGraphqlClient().query({query:$l,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:n}})).data.globalPropertyState,Vl=n=>C.gql`
|
|
1475
1483
|
${Ge}
|
|
1476
1484
|
fragment ProductFields on Product {
|
|
1477
1485
|
id
|
|
@@ -1517,7 +1525,7 @@
|
|
|
1517
1525
|
}
|
|
1518
1526
|
}
|
|
1519
1527
|
`,Xa=n=>C.gql`
|
|
1520
|
-
${
|
|
1528
|
+
${Vl(n)}
|
|
1521
1529
|
fragment ProductCollectionProductFields on ProductCollectionProduct {
|
|
1522
1530
|
id
|
|
1523
1531
|
productId
|
|
@@ -1595,7 +1603,7 @@
|
|
|
1595
1603
|
workflowViewerLink
|
|
1596
1604
|
workflowViewerAmendLink
|
|
1597
1605
|
}
|
|
1598
|
-
`,
|
|
1606
|
+
`,Ll=n=>C.gql`
|
|
1599
1607
|
${We}
|
|
1600
1608
|
${Ye(n)}
|
|
1601
1609
|
${Ni}
|
|
@@ -1675,7 +1683,7 @@
|
|
|
1675
1683
|
}
|
|
1676
1684
|
}
|
|
1677
1685
|
}
|
|
1678
|
-
`,
|
|
1686
|
+
`,ql=C.gql`
|
|
1679
1687
|
query GetBundlesForCustomer($id: String!) {
|
|
1680
1688
|
customers(ids: [$id]) {
|
|
1681
1689
|
bundleStakeholders {
|
|
@@ -1704,7 +1712,7 @@
|
|
|
1704
1712
|
}
|
|
1705
1713
|
}
|
|
1706
1714
|
}
|
|
1707
|
-
`,
|
|
1715
|
+
`,zl=C.gql`
|
|
1708
1716
|
${Xa(!1)}
|
|
1709
1717
|
query GetProductCollectionProducts($id: String!, $productIds: [String!]) {
|
|
1710
1718
|
productCollections(ids: [$id], productIds: $productIds) {
|
|
@@ -1714,7 +1722,7 @@
|
|
|
1714
1722
|
}
|
|
1715
1723
|
}
|
|
1716
1724
|
}
|
|
1717
|
-
`,
|
|
1725
|
+
`,Gl=C.gql`
|
|
1718
1726
|
query GetProductCollectionForFilteredProducts(
|
|
1719
1727
|
$id: String!
|
|
1720
1728
|
$filters: ProductCollectionProductFilterInput
|
|
@@ -1737,7 +1745,7 @@
|
|
|
1737
1745
|
}
|
|
1738
1746
|
}
|
|
1739
1747
|
}
|
|
1740
|
-
`,
|
|
1748
|
+
`,jl=C.gql`
|
|
1741
1749
|
${Xa(!0)}
|
|
1742
1750
|
query GetProductCollectionForProductsFeed(
|
|
1743
1751
|
$id: String!
|
|
@@ -1769,7 +1777,7 @@
|
|
|
1769
1777
|
}
|
|
1770
1778
|
}
|
|
1771
1779
|
}
|
|
1772
|
-
`,
|
|
1780
|
+
`,Hl=n=>C.gql`
|
|
1773
1781
|
${Ye(n)}
|
|
1774
1782
|
mutation CreateBundle(
|
|
1775
1783
|
$collectionId: String
|
|
@@ -1798,7 +1806,7 @@
|
|
|
1798
1806
|
}
|
|
1799
1807
|
}
|
|
1800
1808
|
}
|
|
1801
|
-
`,
|
|
1809
|
+
`,Wl=()=>C.gql`
|
|
1802
1810
|
mutation DuplicateBundle(
|
|
1803
1811
|
$id: String!
|
|
1804
1812
|
$template: Boolean
|
|
@@ -1840,19 +1848,19 @@
|
|
|
1840
1848
|
id
|
|
1841
1849
|
}
|
|
1842
1850
|
}
|
|
1843
|
-
`,
|
|
1851
|
+
`,Yl=C.gql`
|
|
1844
1852
|
mutation BundleAddTransaction($id: String!, $transactionId: String!) {
|
|
1845
1853
|
bundleAddTransaction(id: $id, transactionId: $transactionId) {
|
|
1846
1854
|
id
|
|
1847
1855
|
}
|
|
1848
1856
|
}
|
|
1849
|
-
`,
|
|
1857
|
+
`,Jl=C.gql`
|
|
1850
1858
|
mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
|
|
1851
1859
|
bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
|
|
1852
1860
|
id
|
|
1853
1861
|
}
|
|
1854
1862
|
}
|
|
1855
|
-
`,
|
|
1863
|
+
`,Kl=C.gql`
|
|
1856
1864
|
mutation BundleRemoveTransaction(
|
|
1857
1865
|
$id: String!
|
|
1858
1866
|
$transactionId: String!
|
|
@@ -1867,7 +1875,7 @@
|
|
|
1867
1875
|
id
|
|
1868
1876
|
}
|
|
1869
1877
|
}
|
|
1870
|
-
`,
|
|
1878
|
+
`,_l=C.gql`
|
|
1871
1879
|
mutation BundleRemoveTransactions(
|
|
1872
1880
|
$id: String!
|
|
1873
1881
|
$transactionIds: [String!]!
|
|
@@ -1882,7 +1890,7 @@
|
|
|
1882
1890
|
id
|
|
1883
1891
|
}
|
|
1884
1892
|
}
|
|
1885
|
-
`,
|
|
1893
|
+
`,Xl=C.gql`
|
|
1886
1894
|
mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
|
|
1887
1895
|
bundleAddStakeholder(id: $id, details: $details, type: $type) {
|
|
1888
1896
|
id
|
|
@@ -1902,13 +1910,13 @@
|
|
|
1902
1910
|
}
|
|
1903
1911
|
}
|
|
1904
1912
|
}
|
|
1905
|
-
`,
|
|
1913
|
+
`,Zl=C.gql`
|
|
1906
1914
|
mutation BundleAddStakeholder($id: String!, $emailAddress: String!) {
|
|
1907
1915
|
bundleRemoveStakeholder(id: $id, emailAddress: $emailAddress) {
|
|
1908
1916
|
id
|
|
1909
1917
|
}
|
|
1910
1918
|
}
|
|
1911
|
-
`,
|
|
1919
|
+
`,tc=C.gql`
|
|
1912
1920
|
mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
|
|
1913
1921
|
bundleUpdateStakeholders(id: $id, input: $input) {
|
|
1914
1922
|
id
|
|
@@ -1928,13 +1936,13 @@
|
|
|
1928
1936
|
}
|
|
1929
1937
|
}
|
|
1930
1938
|
}
|
|
1931
|
-
`,
|
|
1939
|
+
`,ec=C.gql`
|
|
1932
1940
|
mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
|
|
1933
1941
|
bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
|
|
1934
1942
|
id
|
|
1935
1943
|
}
|
|
1936
1944
|
}
|
|
1937
|
-
`,
|
|
1945
|
+
`,ac=n=>C.gql`
|
|
1938
1946
|
${Ye(n)}
|
|
1939
1947
|
mutation BundleAssignProductCollection($id: String!, $productCollectionId: String!) {
|
|
1940
1948
|
bundleAssignProductCollection(id: $id, collectionId: $productCollectionId) {
|
|
@@ -1944,13 +1952,13 @@
|
|
|
1944
1952
|
}
|
|
1945
1953
|
}
|
|
1946
1954
|
}
|
|
1947
|
-
`,
|
|
1955
|
+
`,nc=C.gql`
|
|
1948
1956
|
mutation AssignGlobalPropertyConfiguration($bundleId: String!, $globalPropertyConfigurationId: String!) {
|
|
1949
1957
|
bundleUpdate(id: $bundleId, globalPropertyConfigurationId: $globalPropertyConfigurationId) {
|
|
1950
1958
|
id
|
|
1951
1959
|
}
|
|
1952
1960
|
}
|
|
1953
|
-
`,
|
|
1961
|
+
`,ic=n=>C.gql`
|
|
1954
1962
|
${Ni}
|
|
1955
1963
|
query CustomerBundlesFeed($id: String!, $limit: Int!, $offset: Int!, $template: Boolean, $templateStatus: BundleTemplateStatus, $ordered: Boolean) {
|
|
1956
1964
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: $template, templateStatus: $templateStatus, ordered: $ordered) {
|
|
@@ -1976,27 +1984,27 @@
|
|
|
1976
1984
|
total
|
|
1977
1985
|
}
|
|
1978
1986
|
}
|
|
1979
|
-
`,
|
|
1987
|
+
`,rc=C.gql`
|
|
1980
1988
|
mutation FinalizeUpdateBundle($bundleId: String!) {
|
|
1981
1989
|
bundleFinalizeUpdate(bundleId: $bundleId)
|
|
1982
1990
|
}
|
|
1983
|
-
`,
|
|
1991
|
+
`,oc=C.gql`
|
|
1984
1992
|
mutation ApproveBundle($id: String!, $note: String, $stakeholderId: String) {
|
|
1985
1993
|
bundleApprove(id: $id, note: $note, stakeholderId: $stakeholderId)
|
|
1986
1994
|
}
|
|
1987
|
-
`,
|
|
1995
|
+
`,sc=C.gql`
|
|
1988
1996
|
mutation RejectBundle($id: String!, $note: String, $stakeholderId: String) {
|
|
1989
1997
|
bundleReject(id: $id, note: $note, stakeholderId: $stakeholderId)
|
|
1990
1998
|
}
|
|
1991
|
-
`,
|
|
1999
|
+
`,lc=C.gql`
|
|
1992
2000
|
mutation ApproveTransaction($id: String!, $note: String) {
|
|
1993
2001
|
transactionApprove(id: $id, note: $note)
|
|
1994
2002
|
}
|
|
1995
|
-
`,
|
|
2003
|
+
`,cc=C.gql`
|
|
1996
2004
|
mutation RejectTransaction($id: String!, $note: String) {
|
|
1997
2005
|
transactionReject(id: $id, note: $note)
|
|
1998
2006
|
}
|
|
1999
|
-
`,
|
|
2007
|
+
`,dc=C.gql`
|
|
2000
2008
|
mutation CreateRecipient(
|
|
2001
2009
|
$firstName: String
|
|
2002
2010
|
$lastName: String
|
|
@@ -2038,7 +2046,7 @@
|
|
|
2038
2046
|
id
|
|
2039
2047
|
}
|
|
2040
2048
|
}
|
|
2041
|
-
`,
|
|
2049
|
+
`,uc=C.gql`
|
|
2042
2050
|
mutation UpdateRecipient(
|
|
2043
2051
|
$id: String!
|
|
2044
2052
|
$firstName: String
|
|
@@ -2084,17 +2092,17 @@
|
|
|
2084
2092
|
id
|
|
2085
2093
|
}
|
|
2086
2094
|
}
|
|
2087
|
-
`,
|
|
2095
|
+
`,Ac=C.gql`
|
|
2088
2096
|
mutation AtttachRecipient($id: String!, $recipientId: String!) {
|
|
2089
2097
|
transactionAttachRecipient(id: $id, recipientId: $recipientId) {
|
|
2090
2098
|
id
|
|
2091
2099
|
}
|
|
2092
2100
|
}
|
|
2093
|
-
`,
|
|
2101
|
+
`,hc=C.gql`
|
|
2094
2102
|
mutation DeleteBundle($id: String!) {
|
|
2095
2103
|
bundleDelete(id: $id)
|
|
2096
2104
|
}
|
|
2097
|
-
`,
|
|
2105
|
+
`,gc=C.gql`
|
|
2098
2106
|
query FindBundleForTransactions($ids: [String!]!) {
|
|
2099
2107
|
transactions(ids: $ids) {
|
|
2100
2108
|
id
|
|
@@ -2103,7 +2111,7 @@
|
|
|
2103
2111
|
}
|
|
2104
2112
|
}
|
|
2105
2113
|
}
|
|
2106
|
-
`,gc=(n,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,mc=n=>{for(const t of Object.values(n.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return Qi(n,"__typename"),n},Qi=(n,t)=>{if(!(typeof n!="object"||n===null))for(const e in n)e===t?delete n[e]:Qi(n[e],t)};var he=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(he||{});const pc=1e3;class In extends Ua{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},pc)})}}const fc=n=>n.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=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(i=>i.layout):fc(t.panels)},Xt=class Xt{constructor(t,e,a,i,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Va(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=Cc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new xl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=i,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new Si,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.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const i=a.uniqueIdentifier??a.title??"";a.type===_t.FirstName?e[i]=t?.firstName:a.type===_t.LastName?e[i]=t?.lastName:a.type===_t.Custom&&(a.customFieldIndex===1?e[i]=t?.customField1:a.customFieldIndex===2?e[i]=t?.customField2:a.customFieldIndex===3?e[i]=t?.customField3:a.customFieldIndex===4?e[i]=t?.customField4:a.customFieldIndex===5&&(e[i]=t?.customField5),a.option&&(e[i]=a.option.variants?.find(r=>r.id===e[i])?.name))}),e}async updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f,y){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:i??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},this.experience.callEvent(Ne.RecipientChanged),await this.graphQlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:i||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId,prevalidated:y}});else{const F=await this.graphQlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},this.experience.callEvent(Ne.RecipientChanged),await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=Xt.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const i=(async()=>(await this.graphQlClient().query({query:zo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();Xt.configurationPromiseMap.set(t.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),i=P.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([i,r]),this.allScenes=fn(t);const s=dt(this.allScenes,this.stepSelections).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new U(c),!0),this.stepElements={...this.stepElements,...l},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}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const i=fn(a),r={...t};let o=-1;for(;;){const c=dt(i,r).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return dt(i,r).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}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.experience.getTransaction().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}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}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))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.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())}getMandatoryUnfulfilledSteps(){return dt(this.allScenes,this.stepSelections).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let i=!1;if(!this.validationErrors.steps.has(t)&&a)i=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(i=!0,r.set(e,a)):a||(i=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}i&&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.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const i=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(i),dt(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await i.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(!te(a,this.storage)){this.storage=a;const i=new Sn(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const i={stepName:a.stepName};i.storage=this.storage[a.stepName],i.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(i)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new In(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new In(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new O("Attempted to serialize state before it was initialized.");const e=Pt(t.transaction),a=mc(e);return JSON.stringify(a,gc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}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,i)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return i.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])||[]}getInvalidModelVariants(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(e.type===E.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])||[]}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const i=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new vn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new vn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(i(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}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.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await S.getShadowGraphqlClient().query({query:Jo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,i){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,I)=>v+I.selectedVariants.map(M=>M.priceModifier||0).reduce((M,R)=>M+R,0),0),r.steps.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName])});const s=this.allScenes,l=dt(s,o),c=dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(I=>I.stepName===v.stepName));d.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1)});const h=this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(I=>I.id));const f=h.map(v=>new Dt(v.id)),y=new Sn(this.constructSerializableWorkflow()),w=[...p,...f,y];w.length>0&&this.commandContext.apply(new U(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(I=>b.applyModelVariant(I,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),i&&await i()}async ensureStepsAreLoaded(){const e=dt(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],i=e.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ha.init(l,this,this.reloadedState));break;case E.Frame:a.push(pt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case E.Material:a.push(Wa.init(l,this,this.reloadedState));break;case E.Model:a.push(Ya.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Mi(l.data.module)},a.push(Ja.init(l,this,this.reloadedState));break;case E.Picture:a.push(Ka.init(l,this,this.reloadedState));break;case E.Question:a.push(_a.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(j.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new U(o),!0);for(const l of s)await l();s.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 ds(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};Xt.configurationPromiseMap=new Map;let Pa=Xt;class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.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(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await P.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}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){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),i=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?i&&a.executeAnimation(i,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let Z=Zt;class Oi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=V(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const i=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?i.set(c,{browserValue:e,pmsValue:a}):i.set(c,e)}}):a?i.set(t,{browserValue:e,pmsValue:a}):i.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}}class Ri extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Wa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class $i extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ya.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Ui extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ka.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}}class Vi extends Z{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 _a.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Li extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.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 qi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await j.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?j.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return j.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return j.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);j.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,i=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:i,defaultCleared:!1}),this.setText(i)}setText(t){const e={input:t,helperData:{}},a=j.findLayoutElements(this.manager,this.step),i=j.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(i,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=i);const s=a.length<=0,l=s?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=j.getProcessedInput(i,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=j.updateInputText(i,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=j.findLayoutElements(this.manager,this.step);return j.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=Nt(this.getText(),this.manager);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.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?j.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeStrokeColor(this.step,t,e,this.manager)}}class zi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ha.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class ji extends Z{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=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Ja.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class ye{static get(t,e){switch(e.type){case E.DigitalContent:return new Gi(t,e,t.getStepTags(e.stepName));case E.Information:return new zi(t,e,t.getStepTags(e.stepName));case E.Question:return new Vi(t,e,t.getStepTags(e.stepName));case E.Text:return new qi(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Oi(t,e,t.getStepTags(e.stepName));case E.Picture:return new Ui(t,e,t.getStepTags(e.stepName));case E.Shape:return new Li(t,e,t.getStepTags(e.stepName));case E.Material:return new Ri(t,e,t.getStepTags(e.stepName));case E.Model:return new $i(t,e,t.getStepTags(e.stepName));case E.Frame:return new Ar(t,e,t.getStepTags(e.stepName));case E.Module:return new ji(t,e,t.getStepTags(e.stepName));default:throw new O(`Step type ${e.type} not yet supported in Core SDK`)}}}const wc=C.gql`
|
|
2114
|
+
`,mc=(n,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,pc=n=>{for(const t of Object.values(n.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return Qi(n,"__typename"),n},Qi=(n,t)=>{if(!(typeof n!="object"||n===null))for(const e in n)e===t?delete n[e]:Qi(n[e],t)};var he=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(he||{});const fc=1e3;class In extends Ua{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},fc)})}}const Cc=n=>n.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})),wc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(i=>i.layout):Cc(t.panels)},Xt=class Xt{constructor(t,e,a,i,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Va(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=wc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new Fl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=i,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new Si,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.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const i=a.uniqueIdentifier??a.title??"";a.type===_t.FirstName?e[i]=t?.firstName:a.type===_t.LastName?e[i]=t?.lastName:a.type===_t.Custom&&(a.customFieldIndex===1?e[i]=t?.customField1:a.customFieldIndex===2?e[i]=t?.customField2:a.customFieldIndex===3?e[i]=t?.customField3:a.customFieldIndex===4?e[i]=t?.customField4:a.customFieldIndex===5&&(e[i]=t?.customField5),a.option&&(e[i]=a.option.variants?.find(r=>r.id===e[i])?.name))}),e}async updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f,y){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:i??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},this.experience.callEvent(Ne.RecipientChanged),await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:i||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId,prevalidated:y}});else{const F=await this.graphQlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:i,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},this.experience.callEvent(Ne.RecipientChanged),await this.graphQlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=Xt.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const i=(async()=>(await this.graphQlClient().query({query:Go,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();Xt.configurationPromiseMap.set(t.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),i=P.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([i,r]),this.allScenes=fn(t);const s=dt(this.allScenes,this.stepSelections).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new U(c),!0),this.stepElements={...this.stepElements,...l},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}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const i=fn(a),r={...t};let o=-1;for(;;){const c=dt(i,r).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return dt(i,r).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}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.experience.getTransaction().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}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}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))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.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())}getMandatoryUnfulfilledSteps(){return dt(this.allScenes,this.stepSelections).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let i=!1;if(!this.validationErrors.steps.has(t)&&a)i=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(i=!0,r.set(e,a)):a||(i=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}i&&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.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const i=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(i),dt(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new O("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await i.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(!te(a,this.storage)){this.storage=a;const i=new Sn(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const i={stepName:a.stepName};i.storage=this.storage[a.stepName],i.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(i)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new In(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new In(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new O("Attempted to serialize state before it was initialized.");const e=Pt(t.transaction),a=pc(e);return JSON.stringify(a,mc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}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,i)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return i.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])||[]}getInvalidModelVariants(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(e.type===E.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])||[]}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const i=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new vn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new vn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(i(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}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.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await S.getShadowGraphqlClient().query({query:Ko,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await S.getShadowGraphqlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,i){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,I)=>v+I.selectedVariants.map(M=>M.priceModifier||0).reduce((M,R)=>M+R,0),0),r.steps.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName])});const s=this.allScenes,l=dt(s,o),c=dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(I=>I.stepName===v.stepName));d.forEach(v=>{Bt(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1)});const h=this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(I=>I.id));const f=h.map(v=>new Dt(v.id)),y=new Sn(this.constructSerializableWorkflow()),w=[...p,...f,y];w.length>0&&this.commandContext.apply(new U(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(I=>b.applyModelVariant(I,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),i&&await i()}async ensureStepsAreLoaded(){const e=dt(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],i=e.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ha.init(l,this,this.reloadedState));break;case E.Frame:a.push(pt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case E.Material:a.push(Wa.init(l,this,this.reloadedState));break;case E.Model:a.push(Ya.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Mi(l.data.module)},a.push(Ja.init(l,this,this.reloadedState));break;case E.Picture:a.push(Ka.init(l,this,this.reloadedState));break;case E.Question:a.push(_a.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(j.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new U(o),!0);for(const l of s)await l();s.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 us(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};Xt.configurationPromiseMap=new Map;let Pa=Xt;class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.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(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await P.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}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){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),i=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?i&&a.executeAnimation(i,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let Z=Zt;class Oi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=V(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const i=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?i.set(c,{browserValue:e,pmsValue:a}):i.set(c,e)}}):a?i.set(t,{browserValue:e,pmsValue:a}):i.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}}class Ri extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Wa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class $i extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ya.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Ui extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ka.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}}class Vi extends Z{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 _a.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Li extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.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 qi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await j.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?j.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return j.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return j.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);j.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,i=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:i,defaultCleared:!1}),this.setText(i)}setText(t){const e={input:t,helperData:{}},a=j.findLayoutElements(this.manager,this.step),i=j.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(i,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=i);const s=a.length<=0,l=s?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=j.getProcessedInput(i,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=j.updateInputText(i,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=j.findLayoutElements(this.manager,this.step);return j.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=Nt(this.getText(),this.manager);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.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?j.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await j.changeStrokeColor(this.step,t,e,this.manager)}}class zi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ha.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class ji extends Z{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=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Ja.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:he.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class ye{static get(t,e){switch(e.type){case E.DigitalContent:return new Gi(t,e,t.getStepTags(e.stepName));case E.Information:return new zi(t,e,t.getStepTags(e.stepName));case E.Question:return new Vi(t,e,t.getStepTags(e.stepName));case E.Text:return new qi(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Oi(t,e,t.getStepTags(e.stepName));case E.Picture:return new Ui(t,e,t.getStepTags(e.stepName));case E.Shape:return new Li(t,e,t.getStepTags(e.stepName));case E.Material:return new Ri(t,e,t.getStepTags(e.stepName));case E.Model:return new $i(t,e,t.getStepTags(e.stepName));case E.Frame:return new Ar(t,e,t.getStepTags(e.stepName));case E.Module:return new ji(t,e,t.getStepTags(e.stepName));default:throw new O(`Step type ${e.type} not yet supported in Core SDK`)}}}const yc=C.gql`
|
|
2107
2115
|
fragment CreateDesignTransaction on Transaction {
|
|
2108
2116
|
id
|
|
2109
2117
|
designName
|
|
@@ -2128,8 +2136,8 @@
|
|
|
2128
2136
|
externalProductVariantId
|
|
2129
2137
|
}
|
|
2130
2138
|
}
|
|
2131
|
-
`,
|
|
2132
|
-
${
|
|
2139
|
+
`,Sc=C.gql`
|
|
2140
|
+
${yc}
|
|
2133
2141
|
mutation CreateDesigns($inputs: [DesignCreateInput]!) {
|
|
2134
2142
|
designCreateMany(inputs: $inputs) {
|
|
2135
2143
|
id
|
|
@@ -2142,7 +2150,7 @@
|
|
|
2142
2150
|
}
|
|
2143
2151
|
}
|
|
2144
2152
|
}
|
|
2145
|
-
`;function Te(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const
|
|
2153
|
+
`;function Te(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const vc=async(n,t)=>{const e={};try{if(t){const i=await t.loggedInBearerToken();e.Authorization=`Bearer ${i}`}else throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!Te(s)&&(e.Authorization=`Bearer ${s}`)}return await t.getBetaEnabled()&&(e["X-Spiff-Beta"]="true"),(await S.getShadowGraphqlClient().mutate({mutation:Sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:n.map(i=>({name:i.name,layouts:i.layouts,workflowId:i.workflowId,transactionId:i.transactionId,previewImage:i.previewImage,useThreeDimPreview:i.useThreeDimPreview,metadata:i.metadata,selectedVariants:i.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},Bn=(n,t,e)=>{const a=r=>{const o={};if(r.type==="Frame"){const s=n[r.stepName],l=r.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${r.stepTitle} image`]=s.image}if(r.type==="Illustration"){const s=n[r.stepName],l=r.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${r.stepTitle} colors`]=c}}if(r.type==="Module"){const s=n[r.stepName],l=r.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${r.stepTitle} text`]=s.text}if(r.type==="Text"){const s=n[r.stepName];if(!s)return o;const l=r.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${r.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${r.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${r.stepTitle} stroke`]=s.strokeColor)}return o},i={};return t.steps.forEach(r=>{Object.assign(i,a(r))}),i},Ec=(n,t,e,a)=>{const i={};let r={};a&&(r=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(n).includes(l)){const c=n[l],d=t.steps.find(u=>u.stepTitle===l);i[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(r))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(i[c]={value:r[c],priceModifier:0})}return i},bc=(n,t,e,a,i,r,o,s)=>{const l=t.basePrice||0,c=n.priceModifierTotal||0,d=Ec(a,e,void 0,r),A=(Q.getMap("transactionOwnerIds")||new Map).get(n.id),h={additionalExternalProductId:n.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:n.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:n.designExternalVariants,designProductId:n.externalDesignProductId,designProductVariantId:n.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:n.externalCartProductId,externalCartProductVariantId:n.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:n.quantity,transactionId:n.id,transactionOwnerId:A,weight:t.weight,workflowViewerLink:n.workflowViewerLink||"",workflowViewerReadOnlyLink:n.workflowViewerReadOnlyLink||""};return r&&(h.metadata=r),a&&(h.selectedVariants=a),i&&(h.sku=i),h},Ic=async(n,t,e,a,i,r,o,s,l,c)=>{c&&(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await n.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const d=n.getPreviewService(),u=t?.finalizeStepConfig?.lookAtAnimation,A=d&&t.showModelOnFinishStep&&!!u,h=l&&Bn(l,t,!0),g=l&&Bn(l,t,!1),p=async v=>{const I={};let M=0;if(Object.keys(r).length>0)for(const R of Object.keys(r)){const x=r[R],T=t.steps.find(L=>L.stepName===R);for(let L=0;L<x.selections.length;++L){const k=x.selections[L];if(T){const X=await P.getOptionForStep(T);if(!v||X&&(X.variants||[]).length>1&&!T.data.hideSelectionInCart&&!T.data.hideSelectionsInCart){const bt=T.stepTitle;I[bt]?I[bt].push({id:k.id||"",name:k.name,priceModifier:k.priceModifier}):I[bt]=[{id:k.id||"",name:k.name,priceModifier:k.priceModifier}]}}M+=k.priceModifier}}return[I,M]},[m]=await p(!0),f=Object.fromEntries(Object.keys(m).map(v=>[v,m[v].map(I=>I.id)])),[y]=await p(!1),w=Object.fromEntries(Object.keys(y).map(v=>[v,y[v].map(I=>I.id)]));let F=await s(A,i.id);if(F){const v=await(await it(F)).blob();F=(await W.uploadAsset({name:`${i.id}-preview-image.png`,blob:v},ee.Image,!0,!1)).fileLink}return{designDetails:(()=>{const v={name:o,layouts:e.map(I=>({index:I.index,panelId:I.panelId})),workflowId:t.id,transactionId:i.id,useThreeDimPreview:!!A,previewImage:F};if(g){const I=[];for(const[M,R]of Object.entries(g))I.push({key:M,value:R});v.metadata=I}if(f){const I=[];for(const[M,R]of Object.entries(w))I.push({key:M,ids:R});v.selectedVariants=I}return v})(),cartSelectionsWithPrices:m,cartMetadata:h}},Hi=async(n,t)=>{await Promise.all(n.map(async s=>{await s.workflowManager.outstandingRequestsPromise()}));const a=await(async()=>{const s=S.getShadowGraphqlClient(),l=await Promise.all(n.map(async A=>({id:A.transaction.id,hash:await A.workflowManager.getStateHash()}))),d=ha(l,100),u=[];for(const A of d){const h=await s.query({query:Wo,variables:{transactions:A},fetchPolicy:"no-cache",errorPolicy:"all"});if(h.errors&&h.errors.length>0)return l.map(g=>g.id);u.push(...h.data?.transactionConfirmWorkflowStates??[])}return u})(),i=await Promise.all(n.map(async s=>await Ic(s.workflowManager,s.workflow,s.layouts,s.getReducerState,s.transaction,s.workflowSelections,s.designName,t??(()=>Promise.resolve(void 0)),s.workflowMetadata,a.includes(s.transaction.id)))),r=n[0].workflowManager.getClient(),o=await vc(i.map(s=>s.designDetails),r);if(!o)throw new Error("Failed to create designs");return o.map((s,l)=>{const c=n[l],d=i[l],u=s.transaction;return bc(u,c.product,c.workflow,d.cartSelectionsWithPrices,s.sku,d.cartMetadata,u.previewImageLink,s.processExecution?.id)})};class Bc{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=Q.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new O("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(i=>i.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(i=>i(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),i=a.find(r=>r.transactionId===t);if(!i)throw new Error(`No saved design for transaction ${t}.`);i.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"){Q.set(this.localPersistenceKey,JSON.stringify(t));return}throw new O("Unexpected storage method requested")}}const Ie=new Bc,Pc=C.gql`
|
|
2146
2154
|
mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
|
|
2147
2155
|
transactionAddStakeholder(id: $id, details: $details, type: $type) {
|
|
2148
2156
|
id
|
|
@@ -2156,7 +2164,7 @@
|
|
|
2156
2164
|
}
|
|
2157
2165
|
}
|
|
2158
2166
|
}
|
|
2159
|
-
`,
|
|
2167
|
+
`,xc=C.gql`
|
|
2160
2168
|
mutation AddAddressToTransaction(
|
|
2161
2169
|
$transactionId: String!
|
|
2162
2170
|
$streetAddress: String
|
|
@@ -2178,7 +2186,7 @@
|
|
|
2178
2186
|
id
|
|
2179
2187
|
}
|
|
2180
2188
|
}
|
|
2181
|
-
`,
|
|
2189
|
+
`,Fc=C.gql`
|
|
2182
2190
|
mutation AddOrganizationToTransaction($transactionId: String!, $organizationName: String!) {
|
|
2183
2191
|
organizationAttachToTransaction(transactionId: $transactionId, organizationName: $organizationName) {
|
|
2184
2192
|
id
|
|
@@ -2272,7 +2280,7 @@
|
|
|
2272
2280
|
}
|
|
2273
2281
|
}
|
|
2274
2282
|
}
|
|
2275
|
-
`;var Ne=(n=>(n.PriceBreakChanged="PriceBreakChanged",n.ProductChanged="ProductChanged",n.QuantityChanged="QuantityChanged",n.RecipientChanged="RecipientChanged",n.SelectionChanged="SelectionChanged",n))(Ne||{});class Wi{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=$n(async()=>{await Ie.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((i,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);i(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Pa(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const i=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(r=>r(i)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Pn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new O("Failed to set product. No product returned from server.");if(!this.bundle)throw new O("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const i=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=i?.getDefaultWorkflow();if(r){const o=await rr(r.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new O("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Pn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:qo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,i,r,o){await this.graphQlClient().mutate({mutation:Pc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:i||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:xc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),i=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!i)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,i)||""}let r=2048;e&&e<=2048&&(r=e);const o=yt(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=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},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Re("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=He(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Ot.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Kn(p);await(await Ma.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch})).render();const y=await this.getCanvasObjectURLAsync(o);return o.toDataURL(y)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const i=ye.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,i),i}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return(this.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(i=>{a+=i.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const i=this.getAdditionalProductPriceSubunits(e)||0;return a+i}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),i=t*a;return Math.ceil(i)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((i,r)=>-(i.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((i,r)=>i+r.getQuantity(),0);for(const i of t)if(i.minQty<=a)return i.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,i=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&i===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const i=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>i.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return ye.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>ye.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(i=>i.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(i=>e.steps.find(r=>r.stepName===i)).filter(i=>!!i&&this.stepHasHandle(i)).map(i=>ye.get(this.getWorkflowManager(),i))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Bc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(i=>i.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const i=Q.getMap("transactionCustomerIds")||new Map;i.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",i)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),i=this.getCommandContext().getState();if(!e)throw new O("Product undefined!");if(!a)throw new O("Workflow undefined!");if(!i)throw new O("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await Ie.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await Ie.addDesign(o),o}async copy(){const t=Pt(this.getCommandContext().getState());if(!t)throw new O("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new O("Workflow is undefined! Cannot copy experience!");const i=this.getTransaction().integrationProduct?.id;if(!i)throw new O("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:i,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),i=this.getWorkflow();if(!a)throw new O("Product undefined! Cannot finish an experience without a product.");if(!i)throw new O("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Hi([{workflowManager:this.workflowManager,workflow:i,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:i.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Ko,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),i=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await Dc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){i.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}i.push(c)}return i.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.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.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Lo,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(i=>i!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Fc=n=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Dc=async(n,t)=>{if(!Fc(n))return!1;const e=await P.getOptionForStep(n);if(e&&(e.variants||[]).length>1){const a=t[n.stepName];return!!(a&&a.selections.length>0)}return!1};class kc{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(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration;return t?Promise.all(t.aspects.map(e=>this.getHandle(e))):[]}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.conditionMode===Vn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(i=>{const r=e.aspects.find(o=>o.name===i.targetAspectName);return r?i.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case q.FileUpload:return new Yi(this.bundle,t).initialize();case q.ColorOption:return new xa(this.bundle,t,t.entityId?await P.getOption(t.entityId):void 0);case q.Option:{const e=t.entityId?await P.getOption(t.entityId):void 0;return e?.type==="Color"?new xa(this.bundle,t,e):new Za(this.bundle,t,e)}case q.Text:return new Ji(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Je{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}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(i=>i.getStepsConditionallyActive().filter(r=>r.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Yi extends Je{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await P.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),a=await za(t?.fileLink),i=a.width,r=a.height,o=await rt(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:i,height:r,aspect:i/r,svg:o.svg,colors:o.colors};At.set(t?.fileLink,l),this.imageData=l}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},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.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(),i=await W.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:i.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,i.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(i,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),i}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return W.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ve(qe(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return W.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return W.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.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(),i=a.getAspectStorage(this.property.name);if(i?.useOriginalAsset===t)return;const r={...i,useOriginalAsset:t},o=t?i?.originalAssetKey:i?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];if(t)s.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)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await W.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(i){if(this.updateSharedStepStorage({...i}),i.colors){const r=new Map(i.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all(this.getSharedSteps(t).map(async o=>{await o.changeColors(r)}))}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all(e.map(async r=>{await r.changeColors(a)}));const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...i,colors:Object.entries(t).map(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,i=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,i)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(i=>{if(i.getOverrideGlobalPropertyConfiguration(this.property.type))return;i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(i.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Ji extends Je{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),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 i=this.getSharedSteps(e).map(r=>{r.setText(t)});await Promise.all(i)}}class Za extends Je{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await P.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}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){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(i=>i.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const i=this.getSharedSteps(e).map(r=>r.selectVariant(t));await Promise.all(i)}}class xa extends Za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;i&&this.setCustomColor(i)}async applyColorVariant(t,e,a){const r=this.getSharedSteps(e).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&this.getSharedSteps().forEach(i=>i.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Mc=(n,t,e)=>{const a=n.getWorkflowExperiences(),i=n.getGlobalPropertyConfiguration();return i?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(i.id).includes(t)&&o.getType()===e):[]},Ki=(n,t)=>{const a=Mc(n,t,E.Illustration).map(i=>{if(!i.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=i.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Fa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Nc(a))return a;if(Array.isArray(a))return Fa(a,t);let i={};for(const[r,o]of Object.entries(a))i[r]=Tc(o)?o:Fa(o,t);return $r(i,t)}return Array.isArray(n)?n.map(e):e(n)}function Tc(n){return n==null}function Nc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function _i(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function Se(n){return Fa(n,["__typename"])}class Qc{constructor(t,e,a,i,r){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=Se(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=Se(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=i}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=_i(this.globalPropertyState)}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=Pt(this.globalPropertyState);this.globalPropertyState={...Se(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(i=>i.name===t&&i.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,i){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 r=this.configuration.aspects.find(l=>l.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Pt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(i){const l=s.find(c=>c.channel===i);if(l)l.value=e,l.type=r.type,l.channel=i,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(i===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:r.type,storage:a!==null?a:void 0,channel:i})}}else{const l=s[0];l.value=e,l.type=r.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:i});te(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,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 i=this.configuration.aspects.find(s=>s.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=Pt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=i.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=i.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:i.type,storage:e!==null?e:void 0,channel:a});te(r,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await S.getShadowGraphqlClient().mutate({mutation:Ol,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case q.FileUpload:{a.fileUpload=e.storage;break}case q.Option:{a.option=e.storage;break}case q.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=Se(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await S.getShadowGraphqlClient().mutate({mutation:Ql,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Oc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}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)}}const Rc=C.gql`
|
|
2283
|
+
`;var Ne=(n=>(n.PriceBreakChanged="PriceBreakChanged",n.ProductChanged="ProductChanged",n.QuantityChanged="QuantityChanged",n.RecipientChanged="RecipientChanged",n.SelectionChanged="SelectionChanged",n))(Ne||{});class Wi{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=$n(async()=>{await Ie.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((i,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);i(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Pa(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const i=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(r=>r(i)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Pn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new O("Failed to set product. No product returned from server.");if(!this.bundle)throw new O("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const i=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=i?.getDefaultWorkflow();if(r){const o=await rr(r.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new O("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Pn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:zo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,i,r,o){await this.graphQlClient().mutate({mutation:xc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:i||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Fc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),i=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!i)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,i)||""}let r=2048;e&&e<=2048&&(r=e);const o=yt(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=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},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Re("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=He(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Ot.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Kn(p);await(await Ma.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:yt,createImage:le,DOMParser:Ra(),fetch})).render();const y=await this.getCanvasObjectURLAsync(o);return o.toDataURL(y)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const i=ye.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,i),i}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return(this.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(i=>{a+=i.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const i=this.getAdditionalProductPriceSubunits(e)||0;return a+i}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),i=t*a;return Math.ceil(i)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((i,r)=>-(i.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((i,r)=>i+r.getQuantity(),0);for(const i of t)if(i.minQty<=a)return i.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,i=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&i===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const i=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>i.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return ye.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>ye.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(i=>i.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(i=>e.steps.find(r=>r.stepName===i)).filter(i=>!!i&&this.stepHasHandle(i)).map(i=>ye.get(this.getWorkflowManager(),i))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Pc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(i=>i.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const i=Q.getMap("transactionCustomerIds")||new Map;i.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",i)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),i=this.getCommandContext().getState();if(!e)throw new O("Product undefined!");if(!a)throw new O("Workflow undefined!");if(!i)throw new O("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await Ie.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await Ie.addDesign(o),o}async copy(){const t=Pt(this.getCommandContext().getState());if(!t)throw new O("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new O("Workflow is undefined! Cannot copy experience!");const i=this.getTransaction().integrationProduct?.id;if(!i)throw new O("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:i,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),i=this.getWorkflow();if(!a)throw new O("Product undefined! Cannot finish an experience without a product.");if(!i)throw new O("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Hi([{workflowManager:this.workflowManager,workflow:i,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:i.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:_o,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),i=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await kc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){i.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}i.push(c)}return i.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.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.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:qo,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(i=>i!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Dc=n=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},kc=async(n,t)=>{if(!Dc(n))return!1;const e=await P.getOptionForStep(n);if(e&&(e.variants||[]).length>1){const a=t[n.stepName];return!!(a&&a.selections.length>0)}return!1};class Mc{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(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration;return t?Promise.all(t.aspects.map(e=>this.getHandle(e))):[]}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.conditionMode===Vn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(i=>{const r=e.aspects.find(o=>o.name===i.targetAspectName);return r?i.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case q.FileUpload:return new Yi(this.bundle,t).initialize();case q.ColorOption:return new xa(this.bundle,t,t.entityId?await P.getOption(t.entityId):void 0);case q.Option:{const e=t.entityId?await P.getOption(t.entityId):void 0;return e?.type==="Color"?new xa(this.bundle,t,e):new Za(this.bundle,t,e)}case q.Text:return new Ji(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Je{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}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(i=>i.getStepsConditionallyActive().filter(r=>r.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Yi extends Je{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await P.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),a=await za(t?.fileLink),i=a.width,r=a.height,o=await rt(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:i,height:r,aspect:i/r,svg:o.svg,colors:o.colors};At.set(t?.fileLink,l),this.imageData=l}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},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.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(),i=await W.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:i.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,i.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(i,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),i}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return W.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ve(qe(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return W.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return W.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.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(),i=a.getAspectStorage(this.property.name);if(i?.useOriginalAsset===t)return;const r={...i,useOriginalAsset:t},o=t?i?.originalAssetKey:i?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];if(t)s.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)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await W.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(i){if(this.updateSharedStepStorage({...i}),i.colors){const r=new Map(i.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all(this.getSharedSteps(t).map(async o=>{await o.changeColors(r)}))}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all(e.map(async r=>{await r.changeColors(a)}));const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...i,colors:Object.entries(t).map(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,i=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,i)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(i=>{if(i.getOverrideGlobalPropertyConfiguration(this.property.type))return;i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(i.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Ji extends Je{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),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 i=this.getSharedSteps(e).map(r=>{r.setText(t)});await Promise.all(i)}}class Za extends Je{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await P.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}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){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(i=>i.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const i=this.getSharedSteps(e).map(r=>r.selectVariant(t));await Promise.all(i)}}class xa extends Za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const i=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;i&&this.setCustomColor(i)}async applyColorVariant(t,e,a){const r=this.getSharedSteps(e).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&this.getSharedSteps().forEach(i=>i.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Tc=(n,t,e)=>{const a=n.getWorkflowExperiences(),i=n.getGlobalPropertyConfiguration();return i?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(i.id).includes(t)&&o.getType()===e):[]},Ki=(n,t)=>{const a=Tc(n,t,E.Illustration).map(i=>{if(!i.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=i.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Fa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Qc(a))return a;if(Array.isArray(a))return Fa(a,t);let i={};for(const[r,o]of Object.entries(a))i[r]=Nc(o)?o:Fa(o,t);return $r(i,t)}return Array.isArray(n)?n.map(e):e(n)}function Nc(n){return n==null}function Qc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function _i(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function Se(n){return Fa(n,["__typename"])}class Oc{constructor(t,e,a,i,r){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=Se(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=Se(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=i}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=_i(this.globalPropertyState)}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=Pt(this.globalPropertyState);this.globalPropertyState={...Se(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(i=>i.name===t&&i.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,i){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 r=this.configuration.aspects.find(l=>l.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Pt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(i){const l=s.find(c=>c.channel===i);if(l)l.value=e,l.type=r.type,l.channel=i,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(i===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:r.type,storage:a!==null?a:void 0,channel:i})}}else{const l=s[0];l.value=e,l.type=r.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:i});te(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,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 i=this.configuration.aspects.find(s=>s.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=Pt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=i.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=i.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:i.type,storage:e!==null?e:void 0,channel:a});te(r,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await S.getShadowGraphqlClient().mutate({mutation:Rl,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case q.FileUpload:{a.fileUpload=e.storage;break}case q.Option:{a.option=e.storage;break}case q.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=Se(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await S.getShadowGraphqlClient().mutate({mutation:Ol,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class Rc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}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)}}const $c=C.gql`
|
|
2276
2284
|
query GetManyMetafields($entityIds: [String!]!) {
|
|
2277
2285
|
metafieldsMany(entityIds: $entityIds) {
|
|
2278
2286
|
id
|
|
@@ -2283,14 +2291,14 @@
|
|
|
2283
2291
|
}
|
|
2284
2292
|
}
|
|
2285
2293
|
}
|
|
2286
|
-
`;class
|
|
2294
|
+
`;class Uc{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(i=>{const r=this.requestKeyForEntityIfAvailable(t,i);r&&a.set(i,r)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await S.getShadowGraphqlClient().query({query:$c,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,i)=>{const r=e.data.metafieldsMany[i];this.internalMap.set(a,r.map(o=>({key:o.metafieldConfiguration.name,value:o.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const i=a.find(r=>r.key===e);return i||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),i?JSON.parse(i.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const i=this.internalMap.get(t).find(r=>r.key===e);if(i)return JSON.parse(i.value)}}const Xi=new Uc;var Zi=(n=>(n.Default="Default",n.Name="Name",n.Price="Price",n))(Zi||{});class tn{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||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}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 Wt(t))}async fetchProducts(t){if(this.fullFetched)return(this.collection.productCollectionProducts??[]).filter(a=>!!a.product).map(a=>new Wt(a));const e=await S.getShadowGraphqlClient().query({query:zl,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 Wt(a))}async filterProducts(t,e,a,i){const r=await S.getShadowGraphqlClient().query({query:Gl,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:i}});if(!r.data?.productCollections||r.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const o=this.getProducts(),s=r.data.productCollections[0].productCollectionProducts.map(l=>l.product.id);return o.filter(l=>s.includes(l.getId()))}async fetchProductsFeed(t,e,a,i,r,o,s,l){if(this.fullFetched){const A=await(a?this.filterProducts(a):this.fetchProducts());return{total:A.length,items:A.slice(t,t+e)}}const c=new AbortController,{signal:d}=c,u=S.getShadowGraphqlClient().watchQuery({query:jl,variables:{id:this.getId(),limit:e,offset:t,productFilters:a?{link:"And",metafields:a}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:i?{include:i.include??[],exclude:i.exclude??[]}:void 0,sortKey:r,sortDescending:o,quickSearch:s},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:d}}});return new Promise(A=>{let h=!1;const g=u.subscribe({next(p){if(h||p.partial&&(!p.data.productCollections||p.data.productCollections.length===0||!p.data.productCollections[0].productCollectionProductsFeed?.items||p.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),h=!0,g.unsubscribe();const m=p.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(f=>!!f.product).map(f=>new Wt(Pt(f)))||[];A({items:m,total:p.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){h||(h=!0,g.unsubscribe(),A({items:[],total:0}))}})})}getResource(){return this.collection}}class Wt{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const i=(this.product.integrationProducts||[]).find(r=>{const o=r.integration?.type,s=r.integration?.type===t,l=e?r.integration?.externalIntegrationId===e:!0;return o&&s&&l});if(!i)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return i}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>a.integration?.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 ft("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new ft("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(i=>i.workflowName===e);if(a)return new Qt(a)}if(t.length===1)return new Qt(t[0]);throw new ft("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 ft("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 Qt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){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=this.product.integrationProducts?.find(i=>i.integration?.id===t.integrationId):t.externalId?a=this.product.integrationProducts?.find(i=>i.integration?.externalIntegrationId===t.externalId):a=this.product.integrationProducts?.find(i=>i.integration?.type===t.integrationType),a?.additionalIntegrationProduct?.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return Xi.requestKeysForEntity(this.product.id,t)}}class Qt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}const Vc=C.gql`
|
|
2287
2295
|
${Ye(!1)}
|
|
2288
2296
|
query GetProductCollections($ids: [String!]!) {
|
|
2289
2297
|
productCollections(ids: $ids) {
|
|
2290
2298
|
...ProductCollectionFields
|
|
2291
2299
|
}
|
|
2292
2300
|
}
|
|
2293
|
-
`,
|
|
2301
|
+
`,Lc=async n=>(await S.getShadowGraphqlClient().query({query:Vc,errorPolicy:"all",variables:{ids:n}})).data?.productCollections?.map(e=>new tn(e));class qc{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 zc=C.gql`
|
|
2294
2302
|
mutation AddAddressToBundle(
|
|
2295
2303
|
$bundleId: String!
|
|
2296
2304
|
$streetAddress: String
|
|
@@ -2312,26 +2320,26 @@
|
|
|
2312
2320
|
id
|
|
2313
2321
|
}
|
|
2314
2322
|
}
|
|
2315
|
-
`,
|
|
2323
|
+
`,Gc=C.gql`
|
|
2316
2324
|
mutation AddOrganizationToBundle($bundleId: String!, $organizationName: String!) {
|
|
2317
2325
|
organizationAttachToBundle(bundleId: $bundleId, organizationName: $organizationName) {
|
|
2318
2326
|
id
|
|
2319
2327
|
}
|
|
2320
2328
|
}
|
|
2321
|
-
`,
|
|
2329
|
+
`,jc=C.gql`
|
|
2322
2330
|
mutation GenerateQuoteId($id: String!) {
|
|
2323
2331
|
bundleGenerateQuoteId(id: $id) {
|
|
2324
2332
|
id
|
|
2325
2333
|
quoteId
|
|
2326
2334
|
}
|
|
2327
2335
|
}
|
|
2328
|
-
`;class xn{constructor(t,e,a,i,r,o,s){this.workflowExperiences=[],this.eventEmitter=new Lc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=r,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Oc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new Qc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new kc(this),this.setPreviewService(a),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...i,bundleOwnerId:r},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const u=this.globalPropertyStateManager.getGlobalPropertyState();u?this.globalPropertyHandleService.getHandles().then(A=>{const h=A.map(async g=>{if(g.getType()===q.ColorOption||g.getType()===q.Option){const p=g;if(!u.aspects.find(f=>f.name===p.getName()))try{return await p.initDefaultVariant()}catch(f){console.error(`Failed to initialize default global variant - ${f}`)}}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))})),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getIntegrationProductIds(){return this.bundleStateManager.getState()?.integrationProductIds}async addIntegrationProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.integrationProductIds)e.integrationProductIds=[];else if(e.integrationProductIds.some(i=>i===t)){this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds});return}e.integrationProductIds=[...e.integrationProductIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds}),await S.getShadowGraphqlClient().mutate({mutation:da,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeIntegrationProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(r=>(e.integrationProductIds??[]).includes(r));if(a.length===0)return;e.integrationProductIds=(e.integrationProductIds??[]).filter(r=>!a.includes(r));const i=JSON.stringify(e);this.bundleStateManager.setState(i),this.fireEvent("bundle-integration-products-removed",{integrationProductIds:a}),await S.getShadowGraphqlClient().mutate({mutation:da,variables:{id:this.id,bundleStateData:i},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await S.getShadowGraphqlClient().mutate({mutation:Gc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,i,r,o){await S.getShadowGraphqlClient().mutate({mutation:qc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:i||void 0,state:r||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await S.getShadowGraphqlClient().mutate({mutation:zc,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(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const i=a?.name;await this.getGlobalPropertyStateManager().setAspect(i,a.value)}for(const a of t.aspects){const i=a?.name,r=e.find(o=>o.getName()===i);if(r)switch(a.type){case q.FileUpload:{const o=r,s=await Pe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case q.ColorOption:{const o=r,l=(await o.getAllVariants()).find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case q.Option:{const o=r,l=(await o.getAllVariants()).find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case q.Text:{await r.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===q.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,i)=>a+i,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new tn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const i of a){const r=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===i);if(r&&r.type===q.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=Ki(this,i),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===A);g&&await h.setAspect(i,g.variant.id||"",void 0,g.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 s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const i=Q.getMap("transactionOwnerIds")||new Map,r=e.map(s=>i.get(s));await S.getShadowGraphqlClient().mutate({mutation:Yl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:r},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(Q.getMap("transactionOwnerIds")||new Map).get(a);await S.getShadowGraphqlClient().mutate({mutation:Wl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.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 i=this.workflowExperiences.find(r=>r.getTransaction().id===e.id);if(i.setBundle(void 0),this.previewService&&i.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await S.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,o])=>({key:r,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const r=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),i.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:r})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(i=>this.workflowExperiences.findIndex(r=>r.getTransaction().id===i.id));if(e.some(i=>i===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((i,r)=>e[r]===-1).map(i=>i.id).join(", "));const a=t.map(i=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(r=>r.getTransaction().id===i.id),1)[0]);a.forEach(i=>i.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(i=>i.checkForPriceBreakChanges()),this.previewService&&a.forEach(i=>i.getWorkflowManager().ejectFromPreviewService()),t.forEach(i=>this.bundleStateManager.removeStateForTransaction(i.id)),await S.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,transactionIds:t.map(i=>i.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,r])=>({key:i,value:r})),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(i=>i.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.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const i=await this.getGlobalProperties();await Promise.all(i.map(r=>r.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){const a=await S.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,details:t,type:e||Na.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const i=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(i)}async removeStakeholder(t){if(!(await S.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await S.getShadowGraphqlClient().mutate({mutation:Zl,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await S.getShadowGraphqlClient().query({query:bn,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 S.getShadowGraphqlClient().query({query:bn,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){this.completed&&await S.getShadowGraphqlClient().mutate({mutation:ic,variables:{bundleId:this.id}});const a=await Hi(this.workflowExperiences.map(i=>{const r=i.getWorkflow();if(!r)throw new Error("Unable to create designs - Workflow not found!");const o=i.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:i.getWorkflowManager(),workflow:r,layouts:i.getWorkflowManager().getLayouts(),getReducerState:()=>i.getCommandContext().getState(),product:o,transaction:i.getTransaction(),workflowSelections:i.getWorkflowManager().getWorkflowSelections(),designName:r.name,workflowMetadata:i.getWorkflowManager().getWorkflowMetadata()}}),e?(i,r)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===r);return o?e(o,i):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+r),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.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}async assignGlobalPropertyConfiguration(t){await S.getShadowGraphqlClient().mutate({mutation:ac,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ec(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=a?.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 i=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),r=this.workflowExperiences.find(o=>o.getTransaction().id===i.id);r&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:r})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const i=await this.client.getWorkflowExperiences(t.map(s=>({type:"transaction",transactionId:s})),e,void 0,a);if(i.forEach(s=>s.setBundle(this)),i.forEach(s=>s.checkForPriceBreakChanges()),this.workflowExperiences=i,this.previewService)for(const s of i)await this.injectExperienceIntoPreviewService(s);const r=this.getIntegrationProductIds()||[],o=this.getProductCollection();if(o&&r.length>0){await o.fetchProducts();const s=o.getProducts();for(const l of r)if(!s.find(d=>d.getCurrentIntegration().id===l)){for(const d of i)d.getProduct()?.integrationProducts?.map(u=>u.id)?.includes(l)&&await d.clearProduct();await this.removeIntegrationProductIds([l])}}}async updateBundle(){if(!(await S.getShadowGraphqlClient().mutate({mutation:da,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await S.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),i=this.globalPropertyHandleService.applyConditionsFromState(a,t),r=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(i,r),this.checkMandatoryHandlesChanged(t,r);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)r.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=r.map(u=>{if(u.getType()===q.ColorOption||u.getType()===q.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(r.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(a,c);te(r.sort(),d.sort())||(this.checkConditionalHandlesChanged(r,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],i=[],r=[],o=_i(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?i.push(s):r.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:i,remaining:r})}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 S.getShadowGraphqlClient().mutate({mutation:rc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await S.getShadowGraphqlClient().mutate({mutation:oc,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 jc=C.gql`
|
|
2336
|
+
`;class xn{constructor(t,e,a,i,r,o,s){this.workflowExperiences=[],this.eventEmitter=new qc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=r,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Rc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new Oc(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Mc(this),this.setPreviewService(a),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...i,bundleOwnerId:r},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const u=this.globalPropertyStateManager.getGlobalPropertyState();u?this.globalPropertyHandleService.getHandles().then(A=>{const h=A.map(async g=>{if(g.getType()===q.ColorOption||g.getType()===q.Option){const p=g;if(!u.aspects.find(f=>f.name===p.getName()))try{return await p.initDefaultVariant()}catch(f){console.error(`Failed to initialize default global variant - ${f}`)}}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))})),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getIntegrationProductIds(){return this.bundleStateManager.getState()?.integrationProductIds}async addIntegrationProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.integrationProductIds)e.integrationProductIds=[];else if(e.integrationProductIds.some(i=>i===t)){this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds});return}e.integrationProductIds=[...e.integrationProductIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-integration-products-added",{integrationProductIds:e.integrationProductIds}),await S.getShadowGraphqlClient().mutate({mutation:da,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeIntegrationProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(r=>(e.integrationProductIds??[]).includes(r));if(a.length===0)return;e.integrationProductIds=(e.integrationProductIds??[]).filter(r=>!a.includes(r));const i=JSON.stringify(e);this.bundleStateManager.setState(i),this.fireEvent("bundle-integration-products-removed",{integrationProductIds:a}),await S.getShadowGraphqlClient().mutate({mutation:da,variables:{id:this.id,bundleStateData:i},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await S.getShadowGraphqlClient().mutate({mutation:jc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,i,r,o){await S.getShadowGraphqlClient().mutate({mutation:zc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:i||void 0,state:r||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await S.getShadowGraphqlClient().mutate({mutation:Gc,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(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const i=a?.name;await this.getGlobalPropertyStateManager().setAspect(i,a.value)}for(const a of t.aspects){const i=a?.name,r=e.find(o=>o.getName()===i);if(r)switch(a.type){case q.FileUpload:{const o=r,s=await Pe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case q.ColorOption:{const o=r,l=(await o.getAllVariants()).find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case q.Option:{const o=r,l=(await o.getAllVariants()).find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case q.Text:{await r.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===q.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,i)=>a+i,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new tn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const i of a){const r=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===i);if(r&&r.type===q.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=Ki(this,i),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===A);g&&await h.setAspect(i,g.variant.id||"",void 0,g.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 s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const i=Q.getMap("transactionOwnerIds")||new Map,r=e.map(s=>i.get(s));await S.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:r},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(Q.getMap("transactionOwnerIds")||new Map).get(a);await S.getShadowGraphqlClient().mutate({mutation:Yl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.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 i=this.workflowExperiences.find(r=>r.getTransaction().id===e.id);if(i.setBundle(void 0),this.previewService&&i.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await S.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,o])=>({key:r,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const r=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),i.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:r})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(i=>this.workflowExperiences.findIndex(r=>r.getTransaction().id===i.id));if(e.some(i=>i===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((i,r)=>e[r]===-1).map(i=>i.id).join(", "));const a=t.map(i=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(r=>r.getTransaction().id===i.id),1)[0]);a.forEach(i=>i.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(i=>i.checkForPriceBreakChanges()),this.previewService&&a.forEach(i=>i.getWorkflowManager().ejectFromPreviewService()),t.forEach(i=>this.bundleStateManager.removeStateForTransaction(i.id)),await S.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,transactionIds:t.map(i=>i.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,r])=>({key:i,value:r})),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(i=>i.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.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const i=await this.getGlobalProperties();await Promise.all(i.map(r=>r.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){const a=await S.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,details:t,type:e||Na.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const i=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(i)}async removeStakeholder(t){if(!(await S.getShadowGraphqlClient().mutate({mutation:Zl,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await S.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await S.getShadowGraphqlClient().query({query:bn,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 S.getShadowGraphqlClient().query({query:bn,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){this.completed&&await S.getShadowGraphqlClient().mutate({mutation:rc,variables:{bundleId:this.id}});const a=await Hi(this.workflowExperiences.map(i=>{const r=i.getWorkflow();if(!r)throw new Error("Unable to create designs - Workflow not found!");const o=i.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:i.getWorkflowManager(),workflow:r,layouts:i.getWorkflowManager().getLayouts(),getReducerState:()=>i.getCommandContext().getState(),product:o,transaction:i.getTransaction(),workflowSelections:i.getWorkflowManager().getWorkflowSelections(),designName:r.name,workflowMetadata:i.getWorkflowManager().getWorkflowMetadata()}}),e?(i,r)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===r);return o?e(o,i):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+r),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.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}async assignGlobalPropertyConfiguration(t){await S.getShadowGraphqlClient().mutate({mutation:nc,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ac(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=a?.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 i=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),r=this.workflowExperiences.find(o=>o.getTransaction().id===i.id);r&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:r})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const i=await this.client.getWorkflowExperiences(t.map(s=>({type:"transaction",transactionId:s})),e,void 0,a);if(i.forEach(s=>s.setBundle(this)),i.forEach(s=>s.checkForPriceBreakChanges()),this.workflowExperiences=i,this.previewService)for(const s of i)await this.injectExperienceIntoPreviewService(s);const r=this.getIntegrationProductIds()||[],o=this.getProductCollection();if(o&&r.length>0){await o.fetchProducts();const s=o.getProducts();for(const l of r)if(!s.find(d=>d.getCurrentIntegration().id===l)){for(const d of i)d.getProduct()?.integrationProducts?.map(u=>u.id)?.includes(l)&&await d.clearProduct();await this.removeIntegrationProductIds([l])}}}async updateBundle(){if(!(await S.getShadowGraphqlClient().mutate({mutation:da,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await S.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),i=this.globalPropertyHandleService.applyConditionsFromState(a,t),r=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(i,r),this.checkMandatoryHandlesChanged(t,r);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)r.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=r.map(u=>{if(u.getType()===q.ColorOption||u.getType()===q.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(r.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(a,c);te(r.sort(),d.sort())||(this.checkConditionalHandlesChanged(r,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],i=[],r=[],o=_i(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?i.push(s):r.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:i,remaining:r})}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 S.getShadowGraphqlClient().mutate({mutation:oc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await S.getShadowGraphqlClient().mutate({mutation:sc,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 Hc=C.gql`
|
|
2329
2337
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
2330
2338
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
2331
2339
|
id
|
|
2332
2340
|
}
|
|
2333
2341
|
}
|
|
2334
|
-
`;class tr{async execute(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:
|
|
2342
|
+
`;class tr{async execute(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:Hc,variables:{processFlowId:t,inputs:[...e.map(u=>u.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!r)throw new Error("Failed to create process execution.");function o(u){return new Promise(A=>{setTimeout(A,u)})}let s=!1,l=0,c,d;for(;!s;){c=await S.getShadowGraphqlClient().query({query:C.gql`
|
|
2335
2343
|
query getProcessFlowExecution($ids: [String]!) {
|
|
2336
2344
|
processExecutions(ids: $ids) {
|
|
2337
2345
|
id
|
|
@@ -2344,7 +2352,7 @@
|
|
|
2344
2352
|
}
|
|
2345
2353
|
}
|
|
2346
2354
|
}
|
|
2347
|
-
`,variables:{ids:[r]}});const u=c.data?.processExecutions[0];if(!c||!u)throw new Error("Failed to retrieve server response for execution.");if(u.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(u.completedAt){s=!0,d=new er(u);break}l+=1;const A=a?.repeats?a?.repeats:5;if(l>=A)throw new Error("Maximum wait time exceeded for execution result.");await o(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 er{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{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 en{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var ar=(n=>(n.Transaction="Transaction",n.Bundle="Bundle",n.Product="Product",n.Variant="Variant",n.Option="Option",n.LineItem="LineItem",n.Asset="Asset",n))(ar||{});class
|
|
2355
|
+
`,variables:{ids:[r]}});const u=c.data?.processExecutions[0];if(!c||!u)throw new Error("Failed to retrieve server response for execution.");if(u.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(u.completedAt){s=!0,d=new er(u);break}l+=1;const A=a?.repeats?a?.repeats:5;if(l>=A)throw new Error("Maximum wait time exceeded for execution result.");await o(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 er{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{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 en{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var ar=(n=>(n.Transaction="Transaction",n.Bundle="Bundle",n.Product="Product",n.Variant="Variant",n.Option="Option",n.LineItem="LineItem",n.Asset="Asset",n))(ar||{});class Wc extends en{constructor(t){super(`"${t}"`)}}class an extends en{constructor(t,e){if(e!=="Asset"&&!an.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 Yc extends en{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class Da{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=this.integrationProduct?.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 Qt(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 Qt(e))}}const ve=C.gql`
|
|
2348
2356
|
query GetCustomer($emailAddress: String!) {
|
|
2349
2357
|
customer(emailAddress: $emailAddress) {
|
|
2350
2358
|
id
|
|
@@ -2361,7 +2369,7 @@
|
|
|
2361
2369
|
}
|
|
2362
2370
|
}
|
|
2363
2371
|
}
|
|
2364
|
-
`,
|
|
2372
|
+
`,Jc=C.gql`
|
|
2365
2373
|
mutation CustomerCreate($details: CustomerDetailsInput!) {
|
|
2366
2374
|
customerCreate(details: $details) {
|
|
2367
2375
|
id
|
|
@@ -2401,7 +2409,7 @@
|
|
|
2401
2409
|
}
|
|
2402
2410
|
}
|
|
2403
2411
|
}
|
|
2404
|
-
`;const
|
|
2412
|
+
`;const Kc=C.gql`
|
|
2405
2413
|
mutation CustomerGenerateVerificationCode($emailAddress: String!) {
|
|
2406
2414
|
customerGenerateVerificationCode(emailAddress: $emailAddress)
|
|
2407
2415
|
}
|
|
@@ -2436,7 +2444,7 @@
|
|
|
2436
2444
|
}
|
|
2437
2445
|
}
|
|
2438
2446
|
}
|
|
2439
|
-
`;const
|
|
2447
|
+
`;const _c=C.gql`
|
|
2440
2448
|
query CustomerMetafields($id: String!) {
|
|
2441
2449
|
metafields(entityId: $id) {
|
|
2442
2450
|
id
|
|
@@ -2454,7 +2462,7 @@
|
|
|
2454
2462
|
}
|
|
2455
2463
|
}
|
|
2456
2464
|
}
|
|
2457
|
-
`;class _c{constructor(t,e=S.getShadowGraphqlClient.bind(S)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Xc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Xc;class nr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Qr(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new nr;class ir{constructor(t,e,a,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const Zc=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:es(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});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!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},td=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>ie.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=Zc(a,t),r=a.map(s=>ie.set({id:s,options:t},td(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},rr=async(n,t)=>(await nn([n],t))[0],ed=async n=>{const t=await S.getShadowGraphqlClient().query({query:$o,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class ad{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Vo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&to(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 36.0.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ht.setHubUrl(t.hubUrl),ht.setServerUrl(t.serverUrl),ht.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return W}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!eo())throw new Error("Application key required to use Flow Service.");return new tr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await S.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new ir(o,s,a,t)}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=or(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const i=(await S.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),i=(await e.query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Yc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(i);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const i=JSON.parse(e),r=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:Jc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await jt.verifyCode(t,e,a);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),i=new Date().getTime()/1e3,r=!a?.AccessToken||Te(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:Kc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:jl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new xn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,i,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([y,w])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Te(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Vl(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new xn(this,u,e,a,s,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:i?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,i){const o={...await lr(t),...i?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Hl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:nc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:Ll,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],i=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&i.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",i),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),i=a[0],r=i.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await i.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,i){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=ha(o,l),d=ha(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:Uo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,i&&i(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,bt)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(gt=>gt.option.transactionId===X.id)?.option.readOnly??!1,index:x[bt].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Ro,variables:{inputs:x.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,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,i&&i(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[y,w]=await Promise.all([(async()=>m.length>0?await ed(m):[])(),(async()=>f.length>0?await nn(f,e):[])()]),F=new Map(y.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,bt=L?b.get(L):void 0,gt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const ge=Q.getMap("transactionOwnerIds")||new Map;!ge.get(T.id)&&T.transactionOwnerId&&(ge.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",ge));const Ke=ge.get(T.id)||void 0,Cr=new _c({onMutate:()=>({context:{transactionOwnerId:Ke,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Ke,bundleOwnerId:e?.bundleOwnerId}})}),me={workflow:bt,transaction:T,singleVariantsRenderable:gt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Ke,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>Cr,readOnly:k,isReloadedTransaction:gt.type==="transaction"};if(gt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),me.reloadedState=ot}else if(!k&>.workflowState){const ot=JSON.parse(gt.workflowState);await ba(ot),me.reloadedState=ot}return me.delayWorkflowStateSync=!0,{experienceOptions:me,index:X,options:gt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Wi(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await S.getShadowGraphqlClient().query({query:Wo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Da(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Yo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Da(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,i=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return i.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:os,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 or=async(n,t)=>(await S.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,nd=async n=>{const e=await S.getShadowGraphqlClient().query({query:Go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},id=async(n,t)=>(await S.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,rd=async n=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,od=async n=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function sr(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(a);i&&!Te(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function lr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await sr();return{bundleOwnerId:e,...a}}async function sd(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await sr();return{transactionOwnerId:e,...a}}const ld=async n=>{const t=await lr(n),e=await S.getShadowGraphqlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},cd=async n=>{const t=await sd(n),e=await S.getShadowGraphqlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function cr(n,t,e,a){const i=e.width*n.zoom,r=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ee(n.x,t.width-c,0),s.y=Ee(n.y,t.height-d,0),s}const o=n;return o.x=Ee(o.x,-i,t.width),o.y=Ee(o.y,-r,t.height),o}function Ee(n,t,e){return Math.min(Math.max(n,t),e)}class dr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=$n(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 i=a;if(i.currentFrameSources){let r=!1;for(let o=0;o<i.currentFrameSources.length;o++){const s=i.currentFrameSources[o],l=await Ae(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(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 i=Mt.get(e);i&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=qe(this.imageData.svg,this.imageData.colors||{},!1);return Ve(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,i),this.onZoomChangeListeners.forEach(o=>o(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 i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=cr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,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,i,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new Gs(l,e,t[d]),new js(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}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,i)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[i]=r,this.maxZoomScale[i]=r*2.5):(this.minZoomScale[i]=r/10,this.maxZoomScale[i]=r*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]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class dd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f){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(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Set}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 ur=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(ur||{});class Ar extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new dr(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.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){if(await pt.selectImage(this.step,t,this.manager,a),e){const i=this.manager.getStepStorage(this.step.stepName)?.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(Qe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(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.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await W.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,i){return i&&i.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(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return W.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return W.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.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 ud=C.gql`
|
|
2465
|
+
`;class Xc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Zc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const i=await this.cognitoClient?.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Zc;class nr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Qr(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Fn=new nr;class ir{constructor(t,e,a,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,Fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Fn.getPrecisionForCurrency(e))}}const td=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:as(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});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!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},ed=async(n,t)=>{const a=(await t).find(i=>i.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>ie.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const i=td(a,t),r=a.map(s=>ie.set({id:s,options:t},ed(s,i))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},rr=async(n,t)=>(await nn([n],t))[0],ad=async n=>{const t=await S.getShadowGraphqlClient().query({query:Uo,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class nd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:Lo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&to(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 36.1.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ht.setHubUrl(t.hubUrl),ht.setServerUrl(t.serverUrl),ht.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Zn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return W}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!eo())throw new Error("Application key required to use Flow Service.");return new tr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await S.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new ir(o,s,a,t)}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=or(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const i=(await S.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),i=(await e.query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!i.id){const s=(await e.mutate({mutation:Jc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(i);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const i=JSON.parse(e),r=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<r-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:Kc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",i=await jt.verifyCode(t,e,a);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),i=new Date().getTime()/1e3,r=!a?.AccessToken||Te(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<i-parseInt(t)||r){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:_c,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await S.getShadowGraphqlClient().mutate({mutation:Hl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new xn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,i,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([y,w])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Te(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...i?.graphql?.additionalHeaders},d=await S.getShadowGraphqlClient().query({query:Ll(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new xn(this,u,e,a,s,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:i?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,i){const o={...await lr(t),...i?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Wl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:ic(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],i=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&i.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",i),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),i=a[0],r=i.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await i.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,i){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=ha(o,l),d=ha(s,l);let u=0;const A=S.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:Vo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,i&&i(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,bt)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(gt=>gt.option.transactionId===X.id)?.option.readOnly??!1,index:x[bt].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:$o,variables:{inputs:x.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,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,i&&i(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[y,w]=await Promise.all([(async()=>m.length>0?await ad(m):[])(),(async()=>f.length>0?await nn(f,e):[])()]),F=new Map(y.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,bt=L?b.get(L):void 0,gt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const ge=Q.getMap("transactionOwnerIds")||new Map;!ge.get(T.id)&&T.transactionOwnerId&&(ge.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",ge));const Ke=ge.get(T.id)||void 0,Cr=new Xc({onMutate:()=>({context:{transactionOwnerId:Ke,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Ke,bundleOwnerId:e?.bundleOwnerId}})}),me={workflow:bt,transaction:T,singleVariantsRenderable:gt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Ke,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>Cr,readOnly:k,isReloadedTransaction:gt.type==="transaction"};if(gt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),me.reloadedState=ot}else if(!k&>.workflowState){const ot=JSON.parse(gt.workflowState);await ba(ot),me.reloadedState=ot}return me.delayWorkflowStateSync=!0,{experienceOptions:me,index:X,options:gt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Wi(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await S.getShadowGraphqlClient().query({query:Yo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Da(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Jo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Da(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,i=await S.getShadowGraphqlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return i.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:ss,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 or=async(n,t)=>(await S.getShadowGraphqlClient().query({query:is,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,id=async n=>{const e=await S.getShadowGraphqlClient().query({query:jo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},rd=async(n,t)=>(await S.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,od=async n=>(await S.getShadowGraphqlClient().query({query:os,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,sd=async n=>(await S.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function sr(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(a);i&&!Te(i)&&(n.Authorization=`Bearer ${i}`)}return n}async function lr(n){const e=Q.getMap("bundleOwnerIds")?.get(n),a=await sr();return{bundleOwnerId:e,...a}}async function ld(n){const e=Q.getMap("transactionOwnerIds")?.get(n),a=await sr();return{transactionOwnerId:e,...a}}const cd=async n=>{const t=await lr(n),e=await S.getShadowGraphqlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},dd=async n=>{const t=await ld(n),e=await S.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function cr(n,t,e,a){const i=e.width*n.zoom,r=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ee(n.x,t.width-c,0),s.y=Ee(n.y,t.height-d,0),s}const o=n;return o.x=Ee(o.x,-i,t.width),o.y=Ee(o.y,-r,t.height),o}function Ee(n,t,e){return Math.min(Math.max(n,t),e)}class dr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=$n(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 i=a;if(i.currentFrameSources){let r=!1;for(let o=0;o<i.currentFrameSources.length;o++){const s=i.currentFrameSources[o],l=await Ae(s),c=this.frameData?this.frameData[o]:void 0;te(l,c)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(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 i=Mt.get(e);i&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=qe(this.imageData.svg,this.imageData.colors||{},!1);return Ve(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,i),this.onZoomChangeListeners.forEach(o=>o(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 i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=cr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,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,i,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new js(l,e,t[d]),new Hs(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}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,i)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[i]=r,this.maxZoomScale[i]=r*2.5):(this.minZoomScale[i]=r/10,this.maxZoomScale[i]=r*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]=qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class ud{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,i,r,o,s,l,c,d,u,A,h,g,p,m,f){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(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Set}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 ur=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(ur||{});class Ar extends Z{constructor(t,e,a){super(t,e,a);const i=e.data;this.frameService=new dr(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.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){if(await pt.selectImage(this.step,t,this.manager,a),e){const i=this.manager.getStepStorage(this.step.stepName)?.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(Qe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(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.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await W.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const i=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,i){return i&&i.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(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return W.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return W.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.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 Ad=C.gql`
|
|
2458
2466
|
query GetLoggedInCustomer($email: String!) {
|
|
2459
2467
|
customer(emailAddress: $email) {
|
|
2460
2468
|
id
|
|
@@ -2497,21 +2505,21 @@
|
|
|
2497
2505
|
total
|
|
2498
2506
|
}
|
|
2499
2507
|
}
|
|
2500
|
-
`,
|
|
2508
|
+
`,hd=C.gql`
|
|
2501
2509
|
mutation SetTransactionDesignName($id: String!, $name: String!) {
|
|
2502
2510
|
transactionUpdate(id: $id, designName: $name) {
|
|
2503
2511
|
id
|
|
2504
2512
|
designName
|
|
2505
2513
|
}
|
|
2506
2514
|
}
|
|
2507
|
-
`,
|
|
2515
|
+
`,gd=C.gql`
|
|
2508
2516
|
mutation DuplicateTransaction($id: String!, $template: Boolean!) {
|
|
2509
2517
|
transactionDuplicate(id: $id, template: $template) {
|
|
2510
2518
|
id
|
|
2511
2519
|
workflowViewerLink
|
|
2512
2520
|
}
|
|
2513
2521
|
}
|
|
2514
|
-
`,
|
|
2522
|
+
`,md=C.gql`
|
|
2515
2523
|
query GetCustomerBundles($id: String!, $limit: Int!, $offset: Int!) {
|
|
2516
2524
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset) {
|
|
2517
2525
|
items {
|
|
@@ -2526,7 +2534,7 @@
|
|
|
2526
2534
|
total
|
|
2527
2535
|
}
|
|
2528
2536
|
}
|
|
2529
|
-
`,
|
|
2537
|
+
`,pd=C.gql`
|
|
2530
2538
|
query GetTransactionsForBundle($id: String!) {
|
|
2531
2539
|
bundles(ids: [$id]) {
|
|
2532
2540
|
id
|
|
@@ -2547,21 +2555,21 @@
|
|
|
2547
2555
|
}
|
|
2548
2556
|
}
|
|
2549
2557
|
}
|
|
2550
|
-
`,
|
|
2558
|
+
`,fd=C.gql`
|
|
2551
2559
|
mutation SetBundleName($id: String!, $name: String!) {
|
|
2552
2560
|
bundleUpdate(id: $id, name: $name) {
|
|
2553
2561
|
id
|
|
2554
2562
|
name
|
|
2555
2563
|
}
|
|
2556
2564
|
}
|
|
2557
|
-
`,
|
|
2565
|
+
`,Cd=C.gql`
|
|
2558
2566
|
mutation DuplicateBundle($id: String!, $template: Boolean!) {
|
|
2559
2567
|
bundleDuplicate(id: $id, template: $template) {
|
|
2560
2568
|
id
|
|
2561
2569
|
workflowViewerLink
|
|
2562
2570
|
}
|
|
2563
2571
|
}
|
|
2564
|
-
`,
|
|
2572
|
+
`,wd=C.gql`
|
|
2565
2573
|
query GetBundleTemplates($id: String!, $limit: Int!, $offset: Int!) {
|
|
2566
2574
|
customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: true) {
|
|
2567
2575
|
items {
|
|
@@ -2574,7 +2582,7 @@
|
|
|
2574
2582
|
total
|
|
2575
2583
|
}
|
|
2576
2584
|
}
|
|
2577
|
-
`,
|
|
2585
|
+
`,yd=async(n,t,e)=>await S.getShadowGraphqlClient().mutate({mutation:fd,errorPolicy:"all",variables:{id:n,name:t},context:e}),Sd=async(n,t)=>await S.getShadowGraphqlClient().mutate({mutation:hd,errorPolicy:"all",variables:{id:n,name:t}}),vd=async(n,t)=>await S.getShadowGraphqlClient().mutate({mutation:Cd,errorPolicy:"all",variables:{id:n,template:t}}),Ed=async(n,t)=>await S.getShadowGraphqlClient().mutate({mutation:gd,errorPolicy:"all",variables:{id:n,template:t}}),bd=async n=>(await S.getShadowGraphqlClient().query({query:Ad,errorPolicy:"all",variables:{email:n}})).data.customer,Id=async(n,t,e)=>await S.getShadowGraphqlClient().query({query:md,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}),Bd=async(n,t)=>await S.getShadowGraphqlClient().query({query:pd,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:t}),Pd=async(n,t,e)=>(await S.getShadowGraphqlClient().query({query:rn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],xd=async(n,t,e)=>(await S.getShadowGraphqlClient().query({query:rn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Fd=async(n,t,e)=>(await S.getShadowGraphqlClient().query({query:rn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Dd=async(n,t,e)=>(await S.getShadowGraphqlClient().query({query:wd,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}))?.data.customerBundlesFeed?.items||[];(function(){try{if(typeof document<"u"){var n=document.createElement("style");n.appendChild(document.createTextNode("#spiffThemeWrapper{width:100%;height:100%}")),document.head.appendChild(n)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();var hr=(n=>(n.Manual="Manual",n.OnStart="OnStart",n.OnQuit="OnQuit",n.OnEnd="OnEnd",n))(hr||{}),_t=(n=>(n.Email="Email",n.FirstName="FirstName",n.LastName="LastName",n.Phone="Phone",n.Apartment="Apartment",n.City="City",n.Country="Country",n.OrganizationName="OrganizationName",n.PostCode="PostCode",n.State="State",n.StreetAddress="StreetAddress",n.Custom="Custom",n))(_t||{}),K;K={__e:function(n,t,e,a){for(var i,r,o;t=t.__;)if((i=t.__c)&&!i.__)try{if((r=i.constructor)&&r.getDerivedStateFromError!=null&&(i.setState(r.getDerivedStateFromError(n)),o=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,a||{}),o=i.__d),o)return i.__E=i}catch(s){n=s}throw n}},typeof Promise=="function"&&Promise.prototype.then.bind(Promise.resolve());var st,ua,Dn,gr=[],Aa=[],kn=K.__b,Mn=K.__r,Tn=K.diffed,Nn=K.__c,Qn=K.unmount;function kd(){for(var n;n=gr.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(Be),n.__H.__h.forEach(ka),n.__H.__h=[]}catch(t){n.__H.__h=[],K.__e(t,n.__v)}}K.__b=function(n){st=null,kn&&kn(n)},K.__r=function(n){Mn&&Mn(n);var t=(st=n.__c).__H;t&&(ua===st?(t.__h=[],st.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.__V=Aa,e.__N=e.i=void 0})):(t.__h.forEach(Be),t.__h.forEach(ka),t.__h=[])),ua=st},K.diffed=function(n){Tn&&Tn(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(gr.push(t)!==1&&Dn===K.requestAnimationFrame||((Dn=K.requestAnimationFrame)||Md)(kd)),t.__H.__.forEach(function(e){e.i&&(e.__H=e.i),e.__V!==Aa&&(e.__=e.__V),e.i=void 0,e.__V=Aa})),ua=st=null},K.__c=function(n,t){t.some(function(e){try{e.__h.forEach(Be),e.__h=e.__h.filter(function(a){return!a.__||ka(a)})}catch(a){t.some(function(i){i.__h&&(i.__h=[])}),t=[],K.__e(a,e.__v)}}),Nn&&Nn(n,t)},K.unmount=function(n){Qn&&Qn(n);var t,e=n.__c;e&&e.__H&&(e.__H.__.forEach(function(a){try{Be(a)}catch(i){t=i}}),e.__H=void 0,t&&K.__e(t,e.__v))};var On=typeof requestAnimationFrame=="function";function Md(n){var t,e=function(){clearTimeout(a),On&&cancelAnimationFrame(t),setTimeout(n)},a=setTimeout(e,100);On&&(t=requestAnimationFrame(e))}function Be(n){var t=st,e=n.__c;typeof e=="function"&&(n.__c=void 0,e()),st=t}function ka(n){var t=st;n.__c=n.__(),st=t}const mr=C.gql`
|
|
2578
2586
|
fragment AddressValidationResultFields on AddressValidationResult {
|
|
2579
2587
|
addressComplete
|
|
2580
2588
|
address {
|
|
@@ -2608,14 +2616,14 @@
|
|
|
2608
2616
|
...AddressValidationResultFields
|
|
2609
2617
|
}
|
|
2610
2618
|
}
|
|
2611
|
-
`,
|
|
2619
|
+
`,Td=C.gql`
|
|
2612
2620
|
${on}
|
|
2613
2621
|
query GetAddressValidationJobs($ids: [String!]!) {
|
|
2614
2622
|
addressValidationJobs(ids: $ids) {
|
|
2615
2623
|
...AddressValidationJobFields
|
|
2616
2624
|
}
|
|
2617
2625
|
}
|
|
2618
|
-
`,
|
|
2626
|
+
`,Nd=C.gql`
|
|
2619
2627
|
${on}
|
|
2620
2628
|
query GetRecipientsWithAddressValidationJobs($ids: [String!]!) {
|
|
2621
2629
|
recipients(ids: $ids) {
|
|
@@ -2625,27 +2633,27 @@
|
|
|
2625
2633
|
}
|
|
2626
2634
|
}
|
|
2627
2635
|
}
|
|
2628
|
-
`,
|
|
2636
|
+
`,Qd=C.gql`
|
|
2629
2637
|
${mr}
|
|
2630
2638
|
mutation ValidateRecipientAddress($id: String!) {
|
|
2631
2639
|
recipientValidate(id: $id) {
|
|
2632
2640
|
...AddressValidationResultFields
|
|
2633
2641
|
}
|
|
2634
2642
|
}
|
|
2635
|
-
`,
|
|
2643
|
+
`,Od=C.gql`
|
|
2636
2644
|
${on}
|
|
2637
2645
|
mutation BatchValidateRecipientAddress($ids: [String!]!) {
|
|
2638
2646
|
recipientValidateBatch(ids: $ids) {
|
|
2639
2647
|
...AddressValidationJobFields
|
|
2640
2648
|
}
|
|
2641
2649
|
}
|
|
2642
|
-
`,
|
|
2650
|
+
`,Rd=C.gql`
|
|
2643
2651
|
mutation OverrideRecipientAddress($id: String!) {
|
|
2644
2652
|
recipientOverrideAddress(id: $id) {
|
|
2645
2653
|
id
|
|
2646
2654
|
}
|
|
2647
2655
|
}
|
|
2648
|
-
`;var pr=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(pr||{}),fr=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(fr||{});const
|
|
2656
|
+
`;var pr=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(pr||{}),fr=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(fr||{});const $d=async n=>{const t=n.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await S.getShadowGraphqlClient().query({query:Nd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const i=a.getTransaction().recipient?.id;if(i)return e.data?.recipients?.find(r=>r.id===i)?.addressValidationJob})},Ud=async n=>(await S.getShadowGraphqlClient().query({query:Td,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:n}})).data?.addressValidationJobs,Vd=async n=>n.getTransaction().recipient?.id?(await S.getShadowGraphqlClient().mutate({mutation:Qd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n.getTransaction().recipient.id}})).data?.recipientValidate:void 0,Ld=async n=>{const t=n.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await S.getShadowGraphqlClient().mutate({mutation:Od,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const i=a.getTransaction().recipient?.id;if(i)return e.data?.recipientValidateBatch?.find(r=>r.entityId===i)})},qd=async n=>{const t=n.getTransaction().recipient?.id;if(!t)return;(await S.getShadowGraphqlClient().mutate({mutation:Rd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(n.getTransaction().addressValidationStatus=Ta.Overridden)},zd=C.gql`
|
|
2649
2657
|
query GetIntegrationProductsForIds($ids: [String!]!) {
|
|
2650
2658
|
integrationProducts(ids: $ids) {
|
|
2651
2659
|
id
|
|
@@ -2655,5 +2663,5 @@
|
|
|
2655
2663
|
}
|
|
2656
2664
|
}
|
|
2657
2665
|
}
|
|
2658
|
-
`,
|
|
2666
|
+
`,Gd=async n=>(await S.getShadowGraphqlClient().query({query:zd,variables:{ids:n}})).data.integrationProducts;exports.AddonHandle=Qe;exports.AddressValidationJobStatus=fr;exports.AddressValidationResultConfirmationLevel=pr;exports.AddressValidationStatus=Ta;exports.ArrayInput=Yc;exports.AspectType=q;exports.AssetNotFoundError=wt;exports.AssetType=ee;exports.BringForwardCommand=_s;exports.BringToBackCommand=Ks;exports.BringToFrontCommand=Js;exports.BundleDesignCreationCartAddMode=qn;exports.CanvasCommand=$;exports.CollectionProduct=Wt;exports.ColorOptionGlobalPropertyHandle=xa;exports.CommandContext=Si;exports.ConversionDataType=_t;exports.ConversionLocation=hr;exports.CreateElementCommand=G;exports.CreateLayoutCommand=ja;exports.CurrencyContext=ir;exports.CurrencyService=nr;exports.DeleteElementCommand=Dt;exports.DigitalContentStepHandle=Gi;exports.FileUploadGlobalPropertyHandle=Yi;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=er;exports.FlowService=tr;exports.FontAlignmentCommand=Pi;exports.FontColorCommand=Ii;exports.FontSizeCommand=Bi;exports.FontSourceCommand=Ia;exports.FrameService=dr;exports.FrameStep=ur;exports.FrameStepHandle=Ar;exports.GlobalPropertyHandle=Je;exports.GroupCommand=U;exports.IllustrationStepHandle=Oi;exports.InformationMessageType=he;exports.InformationStepHandle=zi;exports.IntegrationProduct=Da;exports.IntegrationType=Gn;exports.LayoutElementFactory=Ls;exports.LayoutElementType=D;exports.LayoutNotFoundError=Y;exports.LayoutRenderingPurpose=Ot;exports.MaterialStepHandle=Ri;exports.MisconfigurationError=lt;exports.MockWorkflowManager=ud;exports.ModelStepHandle=$i;exports.ModuleStepHandle=ji;exports.MoveCommand=qs;exports.ObjectInput=an;exports.ObjectInputType=ar;exports.OptionGlobalPropertyHandle=Za;exports.OptionNotFoundError=ae;exports.ParseError=It;exports.PictureStepHandle=Ui;exports.ProductCameraRig=jn;exports.ProductCollection=tn;exports.ProductCollectionProductSortKey=Zi;exports.ProductWorkflow=Qt;exports.PromiseCache=ie;exports.PromiseQueue=Va;exports.QuestionStepHandle=Vi;exports.QueueablePromise=Ua;exports.ResizeCommand=Gs;exports.ResourceNotFoundError=Rt;exports.RotateCommand=zs;exports.ScaleAxis=H;exports.SendBackwardsCommand=Xs;exports.ShapeStepHandle=Li;exports.ShareActionType=zn;exports.SpiffCommerceClient=nd;exports.StakeholderType=Na;exports.StepAspectType=Ln;exports.StepHandle=Z;exports.StepType=E;exports.TextAlgorithm=xt;exports.TextChangeCommand=xi;exports.TextGlobalPropertyHandle=Ji;exports.TextInput=Wc;exports.TextStepHandle=qi;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=Hn;exports.UpdateImageSourceCommand=Ws;exports.Variant=nt;exports.WorkflowExperienceEventType=Ne;exports.WorkflowExperienceImpl=Wi;exports.amtChannelsForAspect=Ki;exports.assetService=W;exports.browserColorToHex=ai;exports.cmPerPixel=bs;exports.currentDirection=Ss;exports.dataUrlFromExternalUrl=Jr;exports.deleteBundle=cd;exports.designService=Ie;exports.determineCorrectFontSizeAndLines=Kt;exports.digitalContentStepService=Ha;exports.domParser=ct;exports.duplicateBundle=vd;exports.duplicateTransaction=Ed;exports.fetchAsString=et;exports.findAngle=gs;exports.findElement=V;exports.findPmsColors=mo;exports.frameDataCache=Mt;exports.frameStepService=pt;exports.generate=N;exports.generateCommands=Ti;exports.generateSVGWithUnknownColors=rt;exports.generateStateFromDesignInputSteps=Ql;exports.getAddressValidationJobs=Ud;exports.getAttributesFromArrayBuffer=ce;exports.getAxisAlignedBoundingBox=hs;exports.getBoundedOffsets=cr;exports.getBundleIdForTransaction=dd;exports.getBundleThemeConfiguration=od;exports.getCustomer=bd;exports.getCustomerBundles=Id;exports.getElementVertices=vs;exports.getFrameData=Ae;exports.getGlobalPropertyStateForBundle=Ul;exports.getIntegration=or;exports.getIntegrationProducts=Gd;exports.getNEPoint=ws;exports.getNWPoint=Cs;exports.getOrderedTransactions=xd;exports.getOverrideThemeConfiguration=rd;exports.getPointOfRotation=fs;exports.getProductCollections=Lc;exports.getSEPoint=ys;exports.getSvgElement=He;exports.getTemplateBundles=Dd;exports.getTemplateTransactions=Fd;exports.getTransaction=id;exports.getTransactionThemeConfiguration=sd;exports.getTransactionsForBundle=Bd;exports.getTrueCoordinates=ps;exports.getUnorderedTransactions=Pd;exports.getValidationJobsForWorkflowExperiences=$d;exports.getWorkflow=rr;exports.getWorkflows=nn;exports.graphQlManager=S;exports.illustrationStepService=Jt;exports.isCloseToValue=ms;exports.loadFont=Ft;exports.matchHexToPms=Ao;exports.materialStepService=Wa;exports.metafieldManager=Xi;exports.mmPerPixel=Es;exports.modelStepService=Ya;exports.modifySVGColors=qe;exports.moduleStepService=Ja;exports.nameBundle=yd;exports.nameTransaction=Sd;exports.optionService=P;exports.outlineFontsInSvg=Fs;exports.overrideWorkflowExperienceRecipientAddress=qd;exports.patternImageDataCache=At;exports.persistenceService=Q;exports.pictureStepService=Ka;exports.pmsToRgb=uo;exports.questionStepService=_a;exports.registerFetchImplementation=Gr;exports.registerWindowImplementation=zr;exports.rehydrateSerializedLayout=ba;exports.rgbToPms=ei;exports.rotateAroundPoint=Ht;exports.sanitizeSvgTree=Le;exports.setBearerAuthenticationToken=Zn;exports.setCanvasModule=Oa;exports.shapeStepService=Tt;exports.shortenUrl=Fi;exports.spiffCoreConfiguration=ht;exports.stepAspectValuesToDesignInputSteps=Nl;exports.svgColorValueToDefinition=ya;exports.svgStringDimensions=Ga;exports.svgToDataUrl=Ve;exports.textStepService=j;exports.toast=ki;exports.validateWorkflowExperienceRecipient=Vd;exports.validateWorkflowExperienceRecipients=Ld;exports.xmlSerializer=Et;
|
|
2659
2667
|
//# sourceMappingURL=index.cjs.map
|