1 2!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f4b1ba88-5426-5f5a-8a3e-3a1944d220f7")}catch(e){}}(); 3import { o as __toESM } from "./rolldown-runtime.D1cXj70v.js"; 4import { n as require_createBrowserHistory, t as require_dist } from "./vendor~index~newNavigation~AccountTierManagementPage~AdminContainer~AISystemPromptManager~C~f6d7pve6.Df2s7yft.js"; 5import { $ as require_prop_types, X as require_jsx_runtime, dt as require_react, t as require_material } from "./vendor~index~newNavigation~AccountTierManagementPage~AdminContainer~AISystemPromptManager~C~h0mf93xb.B-8UGg7U.js"; 6import { Bn as require_dist$2, Cn as require_cjs, Dn as require_lib, En as require_sourcemapped_stacktrace, Er as captureException, Et as Button, Gn as v4, Hn as require_immutable, In as createStore, Jn as require_pnotify_confirm, Kn as require_pnotify_callbacks, Mn as require_redux_devtools_extension, Nn as init_es, Pn as applyMiddleware, Sn as Dropzone, St as Dropdown, Tn as require_browser, Un as require_toposort, Vn as require_md5, Wn as index, Xn as require_traverse, Yn as require_pnotify, Zn as require_dist$1, _ as require_lib$2, a as createClient, ar as init_moment, b as require_Components, bn as require_dist$4, c as import_createUploadLink, cr as matchPath, d as require_dist$6, er as require_escape_html, f as require_StreamSaver, g as require_query_string, gt as Tab, h as require_deep_diff, ht as require_dist$3, i as require_dist$5, ir as hooks, jt as Icon, l as onError, m as A, mr as matchPath$1, n as require_dist$7, nr as require_moment_timezone, o as GraphQLWsLink, p as require_jszip_min, qn as require_pnotify_buttons, s as require_timeoutLink, sr as require_number_to_letter, t as require_lib$3, tr as require_numeral, u as setContext, v as require_lib$1, wn as gBase64, xn as require_classnames, xt as Table, y as Rnd } from "./vendor~index~newNavigation~AccountTierManagementPage~AdminContainer~AISystemPromptManager~C~hh2h6ti1.DI0Ezgsb.js"; 7import { t as require_dist$8 } from "./dist.DzcutlwI.js"; 8import { A as DATA_ELEMENT_VALUE_OTHER_OR_MISSING, B as STATUS_REQUEST, D as DATA_ELEMENT_VALUE_EMPTY, E as DATA_ELEMENT_STATUS, Q as ERROR_ID_KEY, T as DATA_ELEMENT_ORIGIN, U as getGQLEditorProgramType, W as getGQLProgramType, X as ProgramType, Y as NotificationCopyToAnotherAccount, Z as TypesOfProjectSummary, _ as VideoAspectRatio, b as ALPHA_NUMERIC_MESSAGE, ct as toCapturableError, d as stableSort$1, it as getSskyErrorCodeFromGqlError, lt as toErrorMessage, nt as SskyErrorCode, ot as isOfflineError, p as valueExists, rt as getErrorIdFromRestError, st as isServerOriginError, tt as SSKY_ERROR_CODE_KEY, w as CANVAS_DIMENSIONS, y as VideoQualityProfile } from "./utils.GooH6I5k.js"; 9import { A as init_split, C as init_reactiveVars, F as Observable, I as init_module, M as ApolloLink, N as init_ApolloLink, P as init_utilities, S as init_inMemoryCache, V as cacheSizes, _ as ApolloClient, g as lib_default, h as init_lib, j as split, m as gql, v as init_ApolloClient, w as makeVar, x as InMemoryCache, z as getMainDefinition } from "./vendor~index~newNavigation~AccountTierManagementPage~AdminContainer~AISystemPromptManager~C~lx5ijrxx.Ds2KGt5R.js"; 10import { $ as CreateCustomAnalyticFieldDocument, $a as GqlClientPlaceholderType, $i as GqlClientDeletePresetResult, $l as UpdateProgramVersionSnapshotDocument, $s as MoveProgramToFolderDocument, Aa as GqlClientGettySortOrder, At as CreateRfrVersionDocument, B as CopySceneDocument, Ba as GqlClientLifecycleStage, Bl as UpdateNarrationDocument, Bt as DeleteAccountProgramFolderDocument, Ca as GqlClientFeedDataElementStatus, Cg as withCreateProgram, Cn as EditorAccountLevelDataBrandsDocument, Cr as GetProgramWithAssetsDocument, Ct as CreatePresetDocument, Dn as EditorAccountLevelDataNarratorsDocument, Dt as CreateProgramVersionSnapshotDocument, En as EditorAccountLevelDataMusicDocument, Et as CreateProgramVersionDraftFromSnapshotDocument, F as CopyDraftEditorProgramBetweenAccountsDocument, Fl as UpdateFeedDataElementDocument, G as CreateAssetRequestDocument, Gl as UpdateNarrationsDtaasPrefixKeyDocument, H as CopyStoryDocument, Il as UpdateMasterAnimationGuidelineDocument, Ja as GqlClientNarrationRecordingErrorReason, Ji as GqlClientDeleteDataElementResult, Jl as UpdatePrioritizedListLogicDocument, Jo as GqlClientUpdateAnimationResult, K as CreateAssetVersionDocument, Kg as withGetProgram, Kl as UpdatePlaceholderGroupLogicDocument, L as CopyEditorProgramDocument, Ll as UpdateMasterDataDocument, M as ConvertFeedDataElementToDerivedDocument, Mt as CreateSceneWithScenePartDocument, Pg as withDeleteProgram, Pt as CreateStoryWithDecisionPointAndBackgroun
10dAssetsDocument, Q as CreateCreativeNarrationRecordingVersionDocument, Qc as UpdateBuildersSceneDocument, Ql as UpdateProgramVersionDocument, R as CopyNarrationDocument, Ri as GqlClientCreateCreativeNarrationRecordingVersionResult, Sn as EditorAccountLevelDataAvatarsDocument, Sr as GetProgramVersionSnapshotsDocument, Ss as GqlClientUpdateNarrationsDtaasPrefixKeyResult, T as CcLibraryVersionDocument, Tt as CreateProgramVersionDraftDocument, Ul as UpdateNarrationRecordingDocument, V as CopyScenePartDocument, Vi as GqlClientCreatePresetResult, Vl as UpdateNarrationOrderDocument, W as CreateAccountProgramFolderDocument, Wi as GqlClientDataElementType, Wl as UpdateNarrationRecordingVersionDocument, Wt as DeleteCustomAnalyticFieldDocument, Xc as UpdateAssetDocument, Xl as UpdateProgramLastSnapshotNumberDocument, Yc as UpdateAnimationDocument, Yl as UpdateProgramDocument, Yo as GqlClientUpdateAssetResult, Ys as MoveAccountProgramFolderToFolderDocument, Z as CreateCreativeDataElementDocument, _r as GetProgramLifecycleHistoryDocument, _t as CreateNarrationRecordingVersionDocument, ai as GqlClientAnimationGuidelineType, an as DeletePrioritizedListLogicDocument, as as GqlClientUpdateCreativeNarrationRecordingVersionResult, br as GetProgramPresetsWithoutValuesDocument, cl as UpdateCustomAnalyticFieldDocument, cn as DeleteSceneEntityLogicDocument, co as GqlClientProgramType, cr as GetAllCreativesNarrationRecordingsDocument, cs as GqlClientUpdateEditorIsArchivedResult, ct as CreateEditorProgramDocument, cu as UpdateStoryWithDecisionPointsDocument, dc as RenameAccountProgramFolderDocument, dr as GetAnimationVersionsDocument, en as DeleteMasterAnimationGuidelineDocument, fi as GqlClientAssetLifecycleStage, fr as GetAssetVersionsDocument, gi as GqlClientBackgroundAssetType, gr as GetProgramDocument, gt as CreateNarrationDocument, hr as GetNarrationRecordingVersionsDocument, ht as CreateMasterAnimationGuidelineDocument, in as DeletePresetDocument, is as GqlClientUpdateCreativeNarrationRecordingResult, iu as UpdateScenePartWithAllPlaceholdersDocument, jt as CreateScenePartDocument, ki as GqlClientConvertFeedDataElementToDerivedResult, kt as CreateRecordingDocDocument, ll as UpdateDataTableDocument, ln as DeleteScenePartDocument, lu as UpdateStoryWithNewSceneDocument, ml as UpdateEditorIsArchivedDocument, mt as CreateFeedDataElementDocument, n as AccountCcLibraryVersionDocument, nn as DeletePlaceholderGroupLogicDocument, ns as GqlClientUpdateCreativeDataElementResult, nt as CreateDerivedDataElementDocument, nu as UpdateSceneEntityLogicDocument, ol as UpdateCreativeNarrationRecordingDocument, os as GqlClientUpdateDerivedDataElementResult, ot as CreateEditorLifecycleEntryDocument, pr as GetBuilderProgramDocument, q as CreateAssetWithVersionDocument, qg as withGetProgramMetadata, ql as UpdatePresetDocument, r_ as withUpdateProgramAndDraft, ra as GqlClientDynamoMigrationStatus, rl as UpdateCreativeDataElementDocument, ru as UpdateScenePartDocument, sl as UpdateCreativeNarrationRecordingVersionDocument, sn as DeleteSceneDocument, su as UpdateStoryForBuilderDocument, t_ as withUpdateFrameworkProgram, tn as DeleteNarrationDocument, tt as CreateDataTableDocument, u as AddLifecycleHistoryEntryDocument, ul as UpdateDerivedDataElementDocument, un as DeleteStoryDocument, vr as GetProgramPresetValuesDocument, vs as GqlClientUpdateFeedDataElementResult, wg as withCreateProgramAndDraft, wn as EditorAccountLevelDataFontsDocument, wr as GetProgramsDynamoMigrationStatusDocument, wt as CreateProgramAndBuilderDraftDocument, xr as GetProgramVersionSnapshotWithAssetsDocument, xs as GqlClientUpdateNarrationRecordingResult, yr as GetProgramPresetsDocument, z as CopyProgramDocument } from "./graphqlClient.B8mBnpI6.js"; 11import { Bn as require_dist$9, Dr as require_lodash, i as Sketch_default, r as init_es$1 } from "./vendor~index~newNavigation~AccountTierManagementPage~AdminContainer~AISystemPromptManager~C~e5v1w7z6.UinWi66V.js"; 12import { n as pagePathToName, t as isNewNav } from "./newNavUtils.BTMe6_zH.js"; 13import { t as FontAwesomeIcon } from "./dist.D6-c0JAy.js"; 14//#region common/rolesPermissionsConst.ts 15var import_dist$9 = require_dist$8(); 16var roles = /* @__PURE__ */ function(roles) { 17 roles["admin"] = "admin"; 18 roles["animator"] = "animator"; 19 roles["builderEditor"] = "builder editor"; 20 roles["builderOverview"] = "builder overview"; 21 roles["builderViewer"] = "builder viewer"; 22 roles["frameworkEditor"] = "framework editor"; 23 roles["adsUser"] = "ads user"; 24 roles["adsAdmin"] = "ads admin"; 25 roles["adsSundayskyViewer"] = "ads SundaySky viewer"; 26 roles["frameworkViewer"] = "framework viewer"; 27 roles["reportingServer"] = "reporting server"; 28 roles["builderReporting"] = "builder reporting"; 29 roles["resolver"] = "resolver"; 30 roles["bi"] = "bi"; 31 roles["sharedFrameworkViewer"] = "shared framework viewer"; 32 roles["productCreative"] = "product creative"; 33 roles["authoringServer"] = "authoring server"; 34 roles["platformEditor"] = "platform editor"; 35 roles["platformViewer"] = "platform viewer"; 36 roles["platformApprover"] = "platform approver"; 37 roles["reportsByInteractionAdmin"] = "reports by interaction admin"; 38 roles["shopifyServer"] = "shopify server"; 39 roles["accountOwner"] = "account owner";
40 roles["performanceToolResultUpdate"] = "performance tool result updater"; 41 roles["professionalServices"] = "professionalServices"; 42 roles["reviewer"] = "reviewer"; 43 roles["exportAccountData"] = "export account data"; 44 roles["cxEtlRole"] = "cx etl role"; 45 roles["allAccountsManager"] = "allAccountsManager"; 46 roles["internal"] = "internal"; 47 roles["external"] = "external"; 48 roles["storyTemplatesEditor"] = "storyTemplatesEditor"; 49 roles["promptTokenManager"] = "promptTokenManager"; 50 roles["helpCenterEditor"] = "helpCenterEditor"; 51 roles["contributor"] = "contributor"; 52 roles["aiSystemManager"] = "aiSystemManager"; 53 roles["adsSystemManager"] = "adsSystemManager"; 54 return roles; 55}({}); 56var permissions = { 57 getProjects: { 58 name: "GET_PROJECTS", 59 message: "You are not authorized to view projects" 60 }, 61 getBuilderProjectsInfo: { 62 name: "GET_BUILDER_PROJECTS_INFO", 63 message: "You are not authorized to view projects" 64 }, 65 editProjects: { 66 name: "EDIT_PROJECTS", 67 message: "You are not authorized to edit projects" 68 }, 69 getProjectsAssets: { 70 name: "GET_PROJECTS_ASSETS", 71 message: "You are not authorized to view projects assets" 72 }, 73 editProjectsAssets: { 74 name: "EDIT_PROJECTS_ASSETS", 75 message: "You are not authorized to edit projects assets" 76 }, 77 dashboards: { 78 name: "DASHBOARDS", 79 message: "You are not authorized to view dashboards" 80 }, 81 editUsers: { 82 name: "EDIT_USERS", 83 message: "You are not authorized to edit users" 84 }, 85 getUsers: { 86 name: "GET_USERS", 87 message: "You are not authorized to view users" 88 }, 89 editAccountUsers: { 90 name: "EDIT_ACCOUNT_USERS", 91 message: "You are not authorized to edit account users" 92 }, 93 syncProjectAssets: { 94 name: "SYNC_PROJECT_ASSETS", 95 message: "You are not authorized to sync project assets" 96 }, 97 editFeatureFlags: { 98 name: "EDIT_FEATURE_FLAGS", 99 message: "You are not authorized to edit feature flags" 100 }, 101 canvas: { 102 name: "CANVAS", 103 message: "You are not authorized to edit Framework" 104 }, 105 adsGetCampaignSettings: { 106 name: "ADS_GET_CAMPAIGN_SETTINGS", 107 message: "You are not authorized to view campaign settings" 108 }, 109 adsEditCampaignSettings: { 110 name: "ADS_EDIT_CAMPAIGN_SETTINGS", 111 message: "You are not authorized to edit campaign settings" 112 }, 113 adsSystemManagement: { 114 name: "ADS_SYSTEM_MANAGEMENT", 115 message: "You are not authorized to manage ads system settings" 116 }, 117 getProjectSummaries: { 118 name: "GET_PROJECTS_SUMMARIES", 119 message: "You are not authorized to view projects summaries" 120 }, 121 getFramework: { 122 name: "GET_FRAMEWORK", 123 message: "You are not authorized to view Framework" 124 }, 125 createProgram: { 126 name: "CREATE_PROGRAM", 127 message: "You are not authorized to create programs" 128 }, 129 deleteEntity: { 130 name: "DELETE_ENTITY", 131 message: "You are not authorized to delete" 132 }, 133 updateEntity: { 134 name: "UPDATE_ENTITY", 135 message: "You are not authorized to update" 136 }, 137 getSchedules: { 138 name: "GET_SCHEDULES", 139 message: "You are not authorized to get schedules" 140 }, 141 editReports: { 142 name: "EDIT_REPORTS", 143 message: "You are not authorized to edit reports" 144 }, 145 viewBuilderReports: { 146 name: "VIEW_BUILDER_REPORTS", 147 message: "You are not authorized to view builder reports" 148 }, 149 viewEditorReports: { 150 name: "VIEW_EDITOR_REPORTS", 151 message: "You are not authorized to view editor reports" 152 }, 153 viewReportsByInteraction: { 154 name: "VIEW_REPORTS_BY_INTERACTION", 155 message: "You are not authorized to view reports by interaction" 156 }, 157 adminOperations: { 158 name: "ADMIN_OPERATIONS", 159 message: "You are not authorized to perform admin operations" 160 }, 161 resolveQueries: { 162 name: "RESOLVE_QUERIES", 163 message: "You are not authorized to perform resolve queries" 164 }, 165 biQueries: { 166 name: "BI_QUERIES", 167 message: "You are not authorized to perform BI queries" 168 }, 169 raasRequests: { 170 name: "RAAS_REQUESTS", 171 message: "You are not authorized to perform RaaS requests" 172 }, 173 getExperiments: { 174 name: "GET_EXPERIMENTS", 175 message: "You are not authorized to get experiments" 176 }, 177 editExperiments: { 178 name: "EDIT_EXPERIMENTS", 179 message: "You are not authorized to edit experiments" 180 }, 181 getInputs: { 182 name: "GET_INPUTS", 183 message: "You are not authorized to get inputs" 184 }, 185 getCC: { 186 name: "GET_CC", 187 message: "You are not authorized to read configurable creatives" 188 }, 189 editCC: { 190 name: "EDIT_CC", 191 message: "You are not authorized to edit configurable creatives" 192 }, 193 editCCAnimatedWireframes: { 194 name: "EDIT_CC_ANIMATED_WIREFRAMES", 195 message: "You are not authorized to edit animated wireframes" 196 }, 197 createEditorPrograms: { 198 name: "CREATE_EDITOR_PROGRAMS", 199 message: "You are not authorized to create editor programs" 200 }, 201 getEditorPrograms: { 202 name: "GET_EDITOR_PROGRAMS", 203 message: "You are not authorized to view editor programs" 204 }, 205 editEditorPrograms: { 206 name: "EDIT_EDITOR_PROGRAMS", 207 message: "You are not authorized to edit editor programs" 208 }, 209 deleteEditorPrograms: { 210 name: "DELETE_EDITOR_PROGRAMS", 211 message: "You are not authorized to delete editor programs" 212 }, 213 getBrandConfigurations: { 214 name: "GET_BRAND_CONFIGURATIONS", 215 message: "You are not authorized to view brand configurations" 216 }, 217 editBrandConfigurations: { 218 name: "EDIT_BRAND_CONFIGURATIONS", 219 message: "You are not authorized to edit brand configurations" 220 }, 221 createBrandConfigurations: { 222 name: "CREATE_BRAND_CONFIGURATIONS", 223 message: "You are not authorized to create brand configurations" 224 }, 225 deleteBrandConfigurations: { 226 name: "DELETE_BRAND_CONFIGURATIONS", 227 message: "You are not authorized to delete brand configurations" 228 }, 229 archiveEditorPrograms: { 230 name: "ARCHIVE_EDITOR_PROGRAMS", 231 message: "You are not authorized to archive editor programs" 232 }, 233 uploadEditorAssetMedia: { 234 name: "UPLOAD_EDITOR_ASSET_MEDIA", 235 message: "You are not authorized to upload editor assets" 236 }, 237 copyEditorProgram: { 238 name: "COPY_EDITOR_PROGRAM", 239 message: "You are not authorized to copy editor programs" 240 }, 241 editViewerProfiles: { 242 name: "EDIT_VIEWER_PROFILES", 243 message: "You are not authorized to edit viewer profiles" 244 }, 245 generateVideoLinks: { 246 name: "GENERATE_VIDEO_LINKS", 247 message: "You are not authorized to generate video links" 248 }, 249 generateVideoLinksProd: { 250 name: "GENERATE_VIDEO_LINKS_PROD", 251 message: "You are not authorized to generate video links in prod" 252 }, 253 editStoryTemplates: { 254 name: "EDIT_STORY_TEMPLATES", 255 message: "You are not authorized to edit story templates" 256 }, 257 getStoryTemplatesData: { 258 name: "GET_STORY_TEMPLATES_DATA", 259 message: "You are not authorized to get story templates data" 260 }, 261 editLandingPageBuilderApiGateway: { 262 name: "EDIT_LANDING_PAGE_BUILDER_API_GATEWAY", 263 message: "You are not authorized to edit landing page builder api gateway" 264 }, 265 editStoryTemplatesGallery: { 266 name: "EDIT_STORY_TEMPLATES_GALLERY", 267 message: "You are not authorized to edit story templates gallery" 268 }, 269 reviewEditorPrograms: { 270 name: "REVIEW_EDITOR_PROGRAMS", 271 message: "You are not authorized to review editor videos" 272 }, 273 updatePerformanceToolResults: { 274 name: "UPDATE_PERFORMANCE_TOOL_RESULTS", 275 message: "You are not authorized to update performance tool results" 276 }, 277 getProgramSettings: { 278 name: "GET_PROGRAM_SETTINGS", 279 message: "You are not authorized to get program settings" 280 }, 281 editProgramSettings: { 282 name: "EDIT_PROGRAM_SETTINGS", 283 message: "You are not authorized to edit program settings" 284 }, 285 copyDraftEditorProgramBetweenAccounts: { 286 name: "COPY_DRAFT_EDITOR_PROGRAM_BETWEEN_ACCOUNTS", 287 message: "You are not authorized to copy programs between accounts" 288 }, 289 navigateToOldNavFromNewNav: { 290 name: "NAVIGATE_TO_OLD_NAVIGATION_FROM_NEW_NAVIGATION", 291 message: "You are not authorized to navigate to the older version" 292 }, 293 editAllAccountUsers: { 294 name: "EDIT_ALL_ACCOUNTS_USER", 295 message: "You are not authorized to edit all account users" 296 }, 297 getAllAccounts: { 298 name: "GET_ALL_ACCOUNTS", 299 message: "You are not authorized to view all accounts" 300 }, 301 accountTierManagement: { 302 name: "ACCOUNT_TIER_MANAGEMENT", 303 message: "You are not authorized to manage account tiers" 304 }, 305 createAuthThirdParty: { 306 name: "CREAT_AUTH_THIRD_PARTY", 307 message: "You are not authorized to create third part authentication" 308 }, 309 assumeS3Role: { 310 name: "ASSUME_S3_ROLE", 311 message: "You are not authorized to assume role to s3" 312 }, 313 editEditorCustomIntegrations: { 314 name: "EDIT_EDITOR_CUSTOM_INTEGRATIONS", 315 message: "You are not authorized to edit custom integrations" 316 }, 317 removeAllAccountExternalUsers: { 318 name: "REMOVE_ALL_ACCOUNT_EXTERNAL_USERS", 319 message: "You are not authorized to remove all account external users" 320 }, 321 createAdsEditorPrograms: { 322 name: "CREATE_ADS_EDITOR_PROGRAMS", 323 message: "You are not authorized to create ads programs" 324 }, 325 updateUseRecordedVoice: { 326 name: "UPDATE_USE_RECORDED_VOICE", 327 message: "You are not authorized to update program use of recorded voice" 328 },
329 exportAccountData: { 330 name: "EXPORT_ACCOUNT_DATA", 331 message: "You are not authorized to export account data" 332 }, 333 exportAnalyticsData: { 334 name: "EXPORT_ANALYTICS_DATA", 335 message: "You are not authorized to export analytics data" 336 }, 337 accountsSyncTrigger: { 338 name: "ACCOUNTS_SYNC_TRIGGER", 339 message: "You are not authorized to trigger accounts sync" 340 }, 341 editUserControlledFeatures: { 342 name: "EDIT_USER_CONTROLLED_FEATURES", 343 message: "You are not authorized to edit user-controlled features" 344 }, 345 editAccountTemplateFields: { 346 name: "EDIT_ACCOUNT_TEMPLATE_FIELDS", 347 message: "You are not authorized to edit account template fields" 348 }, 349 managePromptTokens: { 350 name: "MANAGE_PROMPT_TOKENS", 351 message: "You are not authorized to manage prompt tokens" 352 }, 353 editHelpCenter: { 354 name: "EDIT_HELP_CENTER", 355 message: "You are not authorized to edit help center" 356 }, 357 readContributorData: { 358 name: "READ_CONTRIBUTOR_DATA", 359 message: "You are not authorized to read contributor data" 360 }, 361 editContributorData: { 362 name: "EDIT_CONTRIBUTOR_DATA", 363 message: "You are not authorized to edit contributor data" 364 }, 365 readAiSystems: { 366 name: "READ_AI_SYSTEMS", 367 message: "You are not authorized to read AI systems" 368 }, 369 editAiSystems: { 370 name: "EDIT_AI_SYSTEMS", 371 message: "You are not authorized to edit AI systems" 372 }, 373 uploadContributorAssetMedia: { 374 name: "UPLOAD_CONTRIBUTOR_ASSET_MEDIA", 375 message: "You are not authorized to upload contributor asset media" 376 }, 377 reviewApprovalRequest: { 378 name: "REVIEW_APPROVAL_REQUEST", 379 message: "You are not authorized to review approval requests" 380 } 381}; 382Object.keys(roles).map((key) => roles[key]); 383var deprecatedRoles = [ 384 "framework viewer", 385 "framework editor", 386 "resolver", 387 "reports by interaction admin", 388 "shared framework viewer", 389 "bi", 390 "reporting server", 391 "authoring server", 392 "shopify server", 393 "performance tool result updater" 394]; 395var platformViewerPermissions = [ 396 permissions.getProjects.name, 397 permissions.getProjectSummaries.name, 398 permissions.getEditorPrograms.name, 399 permissions.getCC.name, 400 permissions.getBrandConfigurations.name, 401 permissions.raasRequests.name, 402 permissions.getStoryTemplatesData.name, 403 permissions.reviewEditorPrograms.name, 404 permissions.uploadContributorAssetMedia.name 405]; 406var rolesPermissions = { 407 ["admin"]: [ 408 permissions.adminOperations.name, 409 permissions.editFeatureFlags.name, 410 permissions.editAllAccountUsers.name, 411 permissions.getUsers.name, 412 permissions.editUsers.name, 413 permissions.getProgramSettings.name, 414 permissions.getProjects.name, 415 permissions.editProgramSettings.name, 416 permissions.exportAccountData.name, 417 permissions.exportAnalyticsData.name, 418 permissions.accountsSyncTrigger.name, 419 permissions.editUserControlledFeatures.name, 420 permissions.editAccountTemplateFields.name, 421 permissions.editHelpCenter.name, 422 permissions.accountTierManagement.name 423 ], 424 ["builder editor"]: [ 425 permissions.createProgram.name, 426 permissions.getBuilderProjectsInfo.name, 427 permissions.getProjects.name, 428 permissions.getProjectsAssets.name, 429 permissions.editProjects.name, 430 permissions.editProjectsAssets.name, 431 permissions.syncProjectAssets.name, 432 permissions.getProjectSummaries.name, 433 permissions.deleteEntity.name, 434 permissions.updateEntity.name, 435 permissions.getExperiments.name, 436 permissions.editExperiments.name, 437 permissions.generateVideoLinks.name, 438 permissions.generateVideoLinksProd.name, 439 permissions.editReports.name, 440 permissions.navigateToOldNavFromNewNav.name, 441 permissions.createAuthThirdParty.name 442 ], 443 ["animator"]: [ 444 permissions.getProjects.name, 445 permissions.getProjectSummaries.name, 446 permissions.getInputs.name, 447 permissions.assumeS3Role.name 448 ], 449 ["builder overview"]: [ 450 permissions.getProjects.name, 451 permissions.dashboards.name, 452 permissions.getProjectSummaries.name, 453 permissions.navigateToOldNavFromNewNav.name 454 ], 455 ["builder viewer"]: [ 456 permissions.getBuilderProjectsInfo.name, 457 permissions.getProjects.name, 458 permissions.getProjectsAssets.name, 459 permissions.syncProjectAssets.name, 460 permissions.getProjectSummaries.name,
461 permissions.navigateToOldNavFromNewNav.name 462 ], 463 ["framework editor"]: [ 464 permissions.createProgram.name, 465 permissions.getProjects.name, 466 permissions.getProjectsAssets.name, 467 permissions.syncProjectAssets.name, 468 permissions.canvas.name, 469 permissions.getProjectSummaries.name, 470 permissions.getFramework.name, 471 permissions.deleteEntity.name, 472 permissions.updateEntity.name, 473 permissions.editReports.name, 474 permissions.navigateToOldNavFromNewNav.name 475 ], 476 ["framework viewer"]: [ 477 permissions.getProjects.name, 478 permissions.getProjectsAssets.name, 479 permissions.syncProjectAssets.name, 480 permissions.getFramework.name, 481 permissions.getProjectSummaries.name, 482 permissions.navigateToOldNavFromNewNav.name 483 ], 484 ["ads user"]: [ 485 permissions.getBuilderProjectsInfo.name, 486 permissions.getProjects.name, 487 permissions.getProjectSummaries.name, 488 permissions.getProjectsAssets.name, 489 permissions.syncProjectAssets.name, 490 permissions.adsGetCampaignSettings.name, 491 permissions.navigateToOldNavFromNewNav.name 492 ], 493 ["ads admin"]: [ 494 permissions.getBuilderProjectsInfo.name, 495 permissions.getProjects.name, 496 permissions.getProjectSummaries.name, 497 permissions.getProjectsAssets.name, 498 permissions.syncProjectAssets.name, 499 permissions.adsGetCampaignSettings.name, 500 permissions.adsEditCampaignSettings.name, 501 permissions.navigateToOldNavFromNewNav.name 502 ], 503 ["ads SundaySky viewer"]: [ 504 permissions.getBuilderProjectsInfo.name, 505 permissions.getProjects.name, 506 permissions.getProjectSummaries.name, 507 permissions.getProjectsAssets.name, 508 permissions.syncProjectAssets.name, 509 permissions.adsGetCampaignSettings.name, 510 permissions.navigateToOldNavFromNewNav.name 511 ], 512 ["builder reporting"]: [ 513 permissions.getBuilderProjectsInfo.name, 514 permissions.getProjects.name, 515 permissions.getProjectsAssets.name, 516 permissions.syncProjectAssets.name, 517 permissions.getProjectSummaries.name, 518 permissions.getFramework.name, 519 permissions.dashboards.name, 520 permissions.editReports.name, 521 permissions.getExperiments.name, 522 permissions.viewBuilderReports.name, 523 permissions.viewEditorReports.name, 524 permissions.navigateToOldNavFromNewNav.name 525 ], 526 ["reporting server"]: [permissions.getSchedules.name], 527 ["resolver"]: [permissions.resolveQueries.name], 528 ["bi"]: [permissions.biQueries.name], 529 ["shared framework viewer"]: [ 530 permissions.getProjects.name, 531 permissions.getProjectsAssets.name, 532 permissions.syncProjectAssets.name, 533 permissions.getFramework.name, 534 permissions.getProjectSummaries.name 535 ], 536 ["product creative"]: [ 537 permissions.getProjects.name, 538 permissions.getCC.name, 539 permissions.editCC.name, 540 permissions.editStoryTemplatesGallery.name, 541 permissions.editReports.name, 542 permissions.copyDraftEditorProgramBetweenAccounts.name 543 ], 544 ["authoring server"]: [ 545 permissions.getProjects.name, 546 permissions.getCC.name, 547 permissions.editCCAnimatedWireframes.name 548 ], 549 ["platform viewer"]: platformViewerPermissions, 550 ["platform approver"]: [...platformViewerPermissions, permissions.reviewApprovalRequest.name], 551 ["platform editor"]: [ 552 permissions.getProjects.name, 553 permissions.getProjectSummaries.name, 554 permissions.createEditorPrograms.name, 555 permissions.getEditorPrograms.name, 556 permissions.getCC.name, 557 permissions.editEditorPrograms.name, 558 permissions.deleteEditorPrograms.name, 559 permissions.getBrandConfigurations.name, 560 permissions.editBrandConfigurations.name, 561 permissions.raasRequests.name, 562 permissions.archiveEditorPrograms.name, 563 permissions.uploadEditorAssetMedia.name, 564 permissions.copyEditorProgram.name, 565 permissions.editViewerProfiles.name, 566 permissions.generateVideoLinks.name, 567 permissions.generateVideoLinksProd.name, 568 permissions.getStoryTemplatesData.name, 569 permissions.editReports.name, 570 permissions.viewEditorReports.name, 571 permissions.reviewEditorPrograms.name, 572 permissions.createAuthThirdParty.name, 573 permissions.uploadContributorAssetMedia.name, 574 permissions.exportAnalyticsData.name 575 ], 576 ["professionalServices"]: [ 577 permissions.getProjects.name, 578 permissions.getProjectSummaries.name, 579 permissions.createEditorPrograms.name, 580 permissions.getEditorPrograms.name, 581 permissions.getCC.name, 582 permissions.editEditorPrograms.name, 583 permissions.deleteEditorPrograms.name, 584 permissions.getBrandConfigurations.name, 585 permissions.editBrandConfigurations.name, 586 permissions.raasRequests.name, 587 permissions.archiveEditorPrograms.name, 588 permissions.uploadEditorAssetMedia.name, 589 permissions.copyEditorProgram.name, 590 permissions.editViewerProfiles.name, 591 permissions.generateVideoLinks.name, 592 permissions.generateVideoLinksProd.name, 593 permissions.getStoryTemplatesData.name, 594 permissions.editReports.name, 595 permissions.viewEditorReports.name, 596 permissions.editEditorCustomIntegrations.name, 597 permissions.reviewEditorPrograms.name, 598 permissions.editLandingPageBuilderApiGateway.name, 599 permissions.createAdsEditorPrograms.name, 600 permissions.createAuthThirdParty.name 601 ], 602 ["shopify server"]: [ 603 permissions.getBuilderProjectsInfo.name, 604 permissions.getProjects.name, 605 permissions.getProjectsAssets.name, 606 permissions.getProjectSummaries.name, 607 permissions.getExperiments.name, 608 permissions.canvas.name, 609 permissions.getFramework.name, 610 permissions.getEditorPrograms.name, 611 permissions.getCC.name, 612 permissions.getBrandConfigurations.name, 613 permissions.raasRequests.name, 614 permissions.dashboards.name, 615 permissions.adsGetCampaignSettings.name, 616 permissions.adsEditCampaignSettings.name, 617 permissions.getStoryTemplatesData.name 618 ], 619 ["account owner"]: [ 620 permissions.getProjects.name, 621 permissions.getProjectSummaries.name, 622 permissions.getEditorPrograms.name, 623 permissions.getCC.name, 624 permissions.getBrandConfigurations.name, 625 permissions.raasRequests.name, 626 permissions.editAccountUsers.name, 627 permissions.editUserControlledFeatures.name, 628 permissions.editAccountTemplateFields.name, 629 permissions.getStoryTemplatesData.name, 630 permissions.editReports.name, 631 permissions.viewEditorReports.name, 632 permissions.reviewEditorPrograms.name, 633 permissions.createAuthThirdParty.name 634 ], 635 ["performance tool result updater"]: [permissions.updatePerformanceToolResults.name], 636 ["reports by interaction admin"]: [permissions.editReports.name, permissions.viewReportsByInteraction.name], 637 ["allAccountsManager"]: [ 638 permissions.editAccountUsers.name, 639 permissions.removeAllAccountExternalUsers.name, 640 permissions.accountTierManagement.name 641 ], 642 ["internal"]: [ 643 permissions.getBuilderProjectsInfo.name, 644 permissions.getProjects.name, 645 permissions.getEditorPrograms.name, 646 permissions.getCC.name, 647 permissions.getAllAccounts.name, 648 permissions.getBrandConfigurations.name, 649 permissions.raasRequests.name, 650 permissions.getProjectSummaries.name,
651 permissions.navigateToOldNavFromNewNav.name, 652 permissions.syncProjectAssets.name, 653 permissions.dashboards.name, 654 permissions.getFramework.name, 655 permissions.updateUseRecordedVoice.name 656 ], 657 ["external"]: [], 658 ["storyTemplatesEditor"]: [permissions.editStoryTemplatesGallery.name, permissions.editStoryTemplates.name], 659 ["reviewer"]: [permissions.reviewEditorPrograms.name], 660 ["export account data"]: [permissions.exportAccountData.name], 661 ["cx etl role"]: [permissions.getProjects.name, permissions.getAllAccounts.name], 662 ["promptTokenManager"]: [permissions.managePromptTokens.name], 663 ["helpCenterEditor"]: [permissions.editHelpCenter.name], 664 ["contributor"]: [ 665 permissions.readContributorData.name, 666 permissions.editContributorData.name, 667 permissions.getEditorPrograms.name, 668 permissions.raasRequests.name, 669 permissions.uploadContributorAssetMedia.name 670 ], 671 ["aiSystemManager"]: [permissions.readAiSystems.name, permissions.editAiSystems.name], 672 ["adsSystemManager"]: [permissions.adsSystemManagement.name, permissions.adsGetCampaignSettings.name] 673}; 674var getNavigationItemsByUserRoles = (userRoles) => { 675 let navigationItems = []; 676 userRoles.forEach((userRole) => { 677 navigationItems = navigationItems.concat(getNavigationItemsByUserRole(userRole)); 678 }); 679 navigationItems = Array.from(new Set(navigationItems)); 680 return navigationItems; 681}; 682var getNavigationItemsByUserRole = (userRole) => { 683 switch (userRole) { 684 case "admin": return Object.values(import_dist$9.StudioMainCategoriesPaths); 685 case "internal": return Object.values(import_dist$9.StudioMainCategoriesPaths); 686 case "builder editor": return [ 687 import_dist$9.StudioMainCategoriesPaths.Builder, 688 import_dist$9.StudioMainCategoriesPaths.Creative, 689 import_dist$9.StudioMainCategoriesPaths.Settings 690 ]; 691 case "animator": return []; 692 case "builder overview": return [import_dist$9.StudioMainCategoriesPaths.Overview]; 693 case "builder viewer": return [ 694 import_dist$9.StudioMainCategoriesPaths.Builder, 695 import_dist$9.StudioMainCategoriesPaths.Creative, 696 import_dist$9.StudioMainCategoriesPaths.Settings 697 ]; 698 case "framework editor": return [import_dist$9.StudioMainCategoriesPaths.Framework]; 699 case "ads user": return [ 700 import_dist$9.StudioMainCategoriesPaths.Builder, 701 import_dist$9.StudioMainCategoriesPaths.Settings, 702 import_dist$9.StudioMainCategoriesPaths.CampaignSettings 703 ]; 704 case "ads SundaySky viewer": return [ 705 import_dist$9.StudioMainCategoriesPaths.Builder, 706 import_dist$9.StudioMainCategoriesPaths.Settings, 707 import_dist$9.StudioMainCategoriesPaths.CampaignSettings 708 ]; 709 case "ads admin": return [ 710 import_dist$9.StudioMainCategoriesPaths.Builder, 711 import_dist$9.StudioMainCategoriesPaths.Settings, 712 import_dist$9.StudioMainCategoriesPaths.CampaignSettings 713 ]; 714 case "framework viewer": return [import_dist$9.StudioMainCategoriesPaths.Framework]; 715 case "shared framework viewer": return [import_dist$9.StudioMainCategoriesPaths.Framework]; 716 case "builder reporting": return [ 717 import_dist$9.StudioMainCategoriesPaths.Overview, 718 import_dist$9.StudioMainCategoriesPaths.Framework, 719 import_dist$9.StudioMainCategoriesPaths.Builder, 720 import_dist$9.StudioMainCategoriesPaths.Creative, 721 import_dist$9.StudioMainCategoriesPaths.Settings 722 ]; 723 case "platform editor": 724 case "platform viewer": 725 case "platform approver": 726 case "account owner": return [ 727 import_dist$9.StudioMainCategoriesPaths.Overview, 728 import_dist$9.StudioMainCategoriesPaths.Editor2, 729 import_dist$9.StudioMainCategoriesPaths.Editor 730 ]; 731 default: return []; 732 } 733}; 734var isPermitted = (userRoles, permission) => { 735 return Boolean(userRoles?.some((role) => rolesPermissions[role]?.includes(permission.name))); 736}; 737var dynamoDbRoles = { 738 "admin": "admin", 739 "ads SundaySky viewer": "ads SundaySky viewer", 740 "account owner": "account owner", 741 "ads admin": "ads admin", 742 "ads user": "ads user", 743 "animator": "animator", 744 "bi": "bi", 745 "authoring server": "authoring server", 746 "builder editor": "builder editor", 747 "builder overview": "builder overview", 748 "builder reporting": "builder reporting", 749 "builder viewer": "builder viewer", 750 "framework editor": "framework editor", 751 "framework viewer": "framework viewer",
752 "performance tool result updater": "performance tool result updater", 753 "platform editor": "platform editor", 754 "platform viewer": "platform viewer", 755 "platform approver": "platform approver", 756 "product creative": "product creative", 757 "reporting server": "reporting server", 758 "reports by interaction admin": "reports by interaction admin", 759 "resolver": "resolver", 760 "shared framework viewer": "shared framework viewer", 761 "shopify server": "shopify server", 762 "professionalServices": "professionalServices", 763 "reviewer": "reviewer" 764}; 765var dynamoDbRolesRemoved = ["button reporting configurer", "creative toolkit user"]; 766var ACCOUNT_LEVEL_ROLES = [ 767 "animator", 768 "builder editor", 769 "builder overview", 770 "builder viewer", 771 "framework editor", 772 "framework viewer", 773 "ads user", 774 "ads admin", 775 "ads SundaySky viewer", 776 "builder reporting", 777 "shared framework viewer", 778 "platform editor", 779 "platform viewer", 780 "platform approver", 781 "shopify server", 782 "account owner", 783 "storyTemplatesEditor", 784 "professionalServices", 785 "reviewer", 786 "contributor" 787]; 788var USER_LEVEL_ROLES = [ 789 "admin", 790 "bi", 791 "allAccountsManager", 792 "internal", 793 "external", 794 "reporting server", 795 "reports by interaction admin", 796 "performance tool result updater", 797 "authoring server", 798 "product creative", 799 "resolver", 800 "export account data", 801 "cx etl role", 802 "promptTokenManager", 803 "helpCenterEditor", 804 "aiSystemManager", 805 "adsSystemManager" 806]; 807var ROLE_BY_KEY_OR_VALUE = /* @__PURE__ */ new Map(); 808Object.keys(roles).forEach((k) => { 809 if (!ROLE_BY_KEY_OR_VALUE.has(k)) ROLE_BY_KEY_OR_VALUE.set(k, roles[k]); 810 if (!ROLE_BY_KEY_OR_VALUE.has(roles[k])) ROLE_BY_KEY_OR_VALUE.set(roles[k], roles[k]); 811}); 812/** 813* Translate a string which represents either an old (dynamodb) role, or a new role name/value 814* to a role enum. 815* @param role role string 816* @param validate if this is passed AND true, and there's no match for this role, an error will be thrown. 817* @returns matching role, or undefined if the input has no match (illegal input, dynamo was that was removed, etc.) 818* 819*/ 820function stringToRole(role, validate = false) { 821 const matchingEnumRole = ROLE_BY_KEY_OR_VALUE.get(role); 822 if (matchingEnumRole !== void 0) return matchingEnumRole; 823 if (dynamoDbRolesRemoved.includes(role)) return; 824 const matchingRole = dynamoDbRoles[role]; 825 if (matchingRole) return matchingRole; 826 else if (validate) throw new Error(`Cannot translate role input '${role}' to any existing role`); 827 else return; 828} 829//#endregion 830//#region common/types/commonTypes.ts 831var ReportEventType = /* @__PURE__ */ function(ReportEventType) { 832 ReportEventType["Error"] = "studio-error"; 833 ReportEventType["Info"] = "studio-info"; 834 ReportEventType["NonTransactionalError"] = "studio-non-transactional-error"; 835 ReportEventType["ImglyFailedToOpen"] = "imgly-failed-to-open"; 836 ReportEventType["ImglyActionError"] = "imgly-action-error"; 837 ReportEventType["ImglyLogMessage"] = "imgly-log-message"; 838 ReportEventType["RecorderError"] = "recorder-error"; 839 ReportEventType["PresentationParsingError"] = "presentation-parsing-error"; 840 return ReportEventType; 841}({}); 842//#endregion 843//#region client/logic/common/urlUtils.js 844var UrlUtils = class { 845 static append(from, to) { 846 if (from[from.length - 1] !== "/") from += "/"; 847 return new URL(to, from).href; 848 } 849 static getAccountAndProgramFromPath() { 850 const match = matchPath(window.location.pathname, { 851 path: import_dist$9.legacyProgramBasePath.pattern, 852 exact: false, 853 strict: false 854 }); 855 if (match) return { 856 accountId: match?.params?.accountId, 857 program: match?.params?.programId, 858 isLegacy: false 859 }; 860 const newNavMatch = matchPath(window.location.pathname, { 861 path: import_dist$9.newNavVideoPagePath.pattern, 862 exact: false, 863 strict: false 864 }); 865 if (newNavMatch) return { 866 accountId: newNavMatch?.params?.accountId, 867 program: newNavMatch?.params?.videoId, 868 isLegacy: false 869 }; 870 const legacyMatch = matchPath(window.location.pathname, { 871 path: import_dist$9.legacyAccountIdProjectsProjectNamePath.pattern, 872 exact: false, 873 strict: false 874 }); 875 return { 876 accountId: legacyMatch?.params?.accountId, 877 program: legacyMatch?.params?.projectName, 878 isLegacy: true 879 }; 880 } 881}; 882//#endregion 883//#region common/types/dataElement.ts 884var CompatibilityVersions = /* @__PURE__ */ function(CompatibilityVersions) { 885 CompatibilityVersions[CompatibilityVersions["Legacy"] = 0] = "Legacy"; 886 CompatibilityVersions[CompatibilityVersions["DisplayName"] = .1] = "DisplayName"; 887 CompatibilityVersions[CompatibilityVersions["RowForDataElement"] = .2] = "RowForDataElement"; 888 CompatibilityVersions[CompatibilityVersions["IdSupport"] = .3] = "IdSupport"; 889 return CompatibilityVersions; 890}({}); 891var DataElementContentTypes = /* @__PURE__ */ function(DataElementContentTypes) { 892 DataElementContentTypes["String"] = "string"; 893 DataElementContentTypes["Number"] = "number"; 894 DataElementContentTypes["Date"] = "datetime"; 895 DataElementContentTypes["Boolean"] = "boolean"; 896 DataElementContentTypes["Url"] = "url"; 897 return DataElementContentTypes; 898}({}); 899var CreativeDataElementContentTypes = /* @__PURE__ */ function(CreativeDataElementContentTypes) { 900 CreativeDataElementContentTypes["Image"] = "image";
901 CreativeDataElementContentTypes["Video"] = "video"; 902 CreativeDataElementContentTypes["Audio"] = "audio"; 903 CreativeDataElementContentTypes["Color"] = "color"; 904 CreativeDataElementContentTypes["Narration"] = "narration"; 905 return CreativeDataElementContentTypes; 906}({}); 907var DataElementOrigins = /* @__PURE__ */ function(DataElementOrigins) { 908 DataElementOrigins["Feed"] = "feed"; 909 DataElementOrigins["Derived"] = "derived"; 910 DataElementOrigins["System"] = "system"; 911 DataElementOrigins["Creative"] = "creative"; 912 return DataElementOrigins; 913}({}); 914var DataElementStatuses = /* @__PURE__ */ function(DataElementStatuses) { 915 DataElementStatuses["Approved"] = "approved"; 916 DataElementStatuses["Pending"] = "pending"; 917 DataElementStatuses["Missing"] = "missing"; 918 return DataElementStatuses; 919}({}); 920var TagNames = /* @__PURE__ */ function(TagNames) { 921 TagNames["PII"] = "PII"; 922 return TagNames; 923}({}); 924//#endregion 925//#region common/commonConst.ts 926/** 927* This is the studio API version. 928* If you want to force client update, advance this number 929*/ 930var studioApiVersionHeaderName = "studio-api-version"; 931var studioClientVersionHeaderName = "studio-client-version"; 932var X_SSKY_SERVER_TIMING_HEADER = "x-ssky-server-timing"; 933var X_SSKY_PAYLOAD_SIZE_HEADER = "x-ssky-payload-size"; 934var fileTypesWhiteListDef = [ 935 { 936 type: "audio", 937 ext: "mp3", 938 mime: "audio/mpeg" 939 }, 940 { 941 type: "audio", 942 ext: "m4a", 943 mime: "audio/x-m4a" 944 }, 945 { 946 type: "audio", 947 ext: "wav", 948 mime: "audio/vnd.wave" 949 }, 950 { 951 type: "image", 952 ext: "jpeg", 953 mime: "image/jpeg" 954 }, 955 { 956 type: "image", 957 ext: "jpg", 958 mime: "image/jpeg" 959 }, 960 { 961 type: "image", 962 ext: "exif", 963 mime: "image/jpeg" 964 }, 965 { 966 type: "image", 967 ext: "jfif", 968 mime: "image/jpeg" 969 }, 970 { 971 type: "image", 972 ext: "png", 973 mime: "image/png" 974 }, 975 { 976 type: "image", 977 ext: "gif", 978 mime: "image/gif" 979 }, 980 { 981 type: "video", 982 ext: "mov", 983 mime: "video/quicktime" 984 }, 985 { 986 type: "video", 987 ext: "flv", 988 mime: "video/x-flv" 989 }, 990 { 991 type: "video", 992 ext: "mp4", 993 mime: "video/mp4" 994 }, 995 { 996 type: "video", 997 ext: "webm", 998 mime: "video/webm" 999 }, 1000 { 1001 type: "video", 1002 ext: "m4v", 1003 mime: "video/x-m4v" 1004 }, 1005 { 1006 type: "text", 1007 ext: "txt", 1008 mime: "text/plain" 1009 }, 1010 { 1011 type: "text", 1012 ext: "json", 1013 mime: "application/json" 1014 }, 1015 { 1016 type: "zip", 1017 ext: "gz", 1018 mime: "application/gzip" 1019 }, 1020 { 1021 type: "font", 1022 ext: "ttf", 1023 mime: "font/ttf" 1024 }, 1025 { 1026 type: "font", 1027 ext: "otf", 1028 mime: "font/otf" 1029 }, 1030 { 1031 type: "font", 1032 ext: "woff", 1033 mime: "font/woff" 1034 }, 1035 { 1036 type: "email", 1037 ext: "msg", 1038 mime: "application/vnd.ms-outlook" 1039 }, 1040 { 1041 type: "email", 1042 ext: "eml", 1043 mime: "message/rfc822" 1044 }, 1045 { 1046 type: "slides", 1047 ext: "pptx", 1048 mime: "application/vnd.openxmlformats-officedocument.presentationml.presentation" 1049 }, 1050 { 1051 type: "text", 1052 ext: "docx", 1053 mime: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" 1054 }, 1055 { 1056 type: "text", 1057 ext: "pdf", 1058 mime: "application/pdf" 1059 }, 1060 { 1061 type: "spreadsheet", 1062 ext: "xlsx", 1063 mime: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 1064 } 1065]; 1066var fileTypesWhitelist = fileTypesWhiteListDef.map((def) => def.mime); 1067var fileTypesExcludeFromParse = fileTypesWhiteListDef.filter((def) => def.type === "text").map((def) => def.mime); 1068var mimeTypesByMediaType = fileTypesWhiteListDef.reduce((acc, typeDef) => { 1069 if (acc[typeDef.type]) acc[typeDef.type].push(typeDef.mime); 1070 else acc[typeDef.type] = [typeDef.mime]; 1071 return acc; 1072}, {}); 1073var audioExt = fileTypesWhiteListDef.filter((def) => def.type === "audio").map((def) => def.ext); 1074var imageExt = fileTypesWhiteListDef.filter((def) => def.type === "image").map((def) => def.ext); 1075var videoExt = fileTypesWhiteListDef.filter((def) => def.type === "video").map((def) => def.ext); 1076var supportedExtensions = fileTypesWhiteListDef.map((def) => def.ext); 1077var prependDot = (ext) => `.${ext}`; 1078var fileExtByMediaType = { 1079 audio: audioExt.map(prependDot), 1080 image: imageExt.map(prependDot), 1081 video: videoExt.map(prependDot), 1082 csv: [".csv"], 1083 email: [".eml", ".msg"], 1084 slides: [".pptx"], 1085 json: [".json"] 1086}; 1087var defaultNarratorId = "default_narrator"; 1088var urlPlaceHolderTypes = ["image", "video"]; 1089var adsDataElements = [{ 1090 name: "audience", 1091 displayName: "audience", 1092 type: DataElementContentTypes.String, 1093 description: "The audience to which the user belongs", 1094 origin: DataElementOrigins.Feed, 1095 compatibilityVersion: CompatibilityVersions.IdSupport, 1096 valueSet: [], 1097 useValueSet: true, 1098 status: DataElementStatuses.Pending 1099}]; 1100var sceneAssetType = "scene"; 1101var storyAssetType = "story"; 1102var storyInlineAssetType = "inlineStory";
1103var wireFramesAssetType = "wireframesUI"; 1104var recordingAssetType = "recording"; 1105var placeholderType = { 1106 onscreen: "placeholders", 1107 narration: "NarrationParts", 1108 parameter: "parameters" 1109}; 1110var onscreenTypes = { 1111 Image: "image", 1112 Video: "video", 1113 Text: "text", 1114 Hotspot: "hotspot" 1115}; 1116var entityType = { 1117 placeholders: "placeholders", 1118 groups: "groups", 1119 prioritizedLists: "prioritizedLists" 1120}; 1121var parameterType = { 1122 parameter: "parameter", 1123 color: "color" 1124}; 1125var LogicContainers = /* @__PURE__ */ function(LogicContainers) { 1126 LogicContainers["Master"] = "master"; 1127 LogicContainers["Analytics"] = "analytics"; 1128 LogicContainers["Derived"] = "derived"; 1129 LogicContainers["DecisionPoint"] = "decisionPoint"; 1130 LogicContainers["Story"] = "story"; 1131 LogicContainers["Soundtrack"] = "soundtrack"; 1132 LogicContainers["BackgroundAsset"] = "backgroundAsset"; 1133 LogicContainers["Program"] = "program"; 1134 LogicContainers["StorySelection"] = "storySelection"; 1135 LogicContainers["VideoSettings"] = "videoSettings"; 1136 return LogicContainers; 1137}({}); 1138var programTypes = { 1139 CRM: "CRM", 1140 ADS: "Ads" 1141}; 1142var legacyIllegalFileFormatMsg = `Illegal file format was uploaded. You may upload plain text, video (${videoExt.join(", ")}), audio (${audioExt.join(", ")}) or image (${imageExt.join(", ")}) files`; 1143var illegalFileFormatMsg = `Illegal file format was uploaded. You may upload video (${videoExt.join(", ")}), audio (${audioExt.join(", ")}) or image (${imageExt.join(", ")}) files`; 1144var fileTypeCheckRequiredBufferSize = 4100; 1145var programDefaultDynamoMigrationStatusFields = { 1146 most_entities: "done", 1147 assets: "done", 1148 recording_docs: "done", 1149 animations: "done", 1150 narrators: "done", 1151 lifecycle_history: "done", 1152 data_tables: "done" 1153}; 1154var CC_LIBRARY_ID = "ffffffff-ffff-ffff-ffff-ffffffff0000"; 1155var X_SSKY_ACCOUNT_DATA_VERSION_HEADER = "x-ssky-account-data-version"; 1156var EditorProjectIdsPrefix = /* @__PURE__ */ function(EditorProjectIdsPrefix) { 1157 EditorProjectIdsPrefix["LivePreview"] = "editor-live-preview"; 1158 EditorProjectIdsPrefix["Preview"] = "editor-preview"; 1159 return EditorProjectIdsPrefix; 1160}({}); 1161var ACCOUNT_LIBRARY_PROGRAM_NAME = "Account Library"; 1162var EDITOR_ACCOUNT_ID = "12345678901Editor"; 1163var CREATIVE_INFRA_ACCOUNT_ID = "12345678901CreativeInfra"; 1164var EXTERNAL_USER_TESTING_ACCOUNT_ID = "12345678901ExternalUserTesting"; 1165var CC_TEST_ACCOUNT_IDS = /* @__PURE__ */ new Set([ 1166 EDITOR_ACCOUNT_ID, 1167 CREATIVE_INFRA_ACCOUNT_ID, 1168 EXTERNAL_USER_TESTING_ACCOUNT_ID 1169]); 1170var CC_STAGING_ACCOUNT_IDS = [ 1171 EDITOR_ACCOUNT_ID, 1172 CREATIVE_INFRA_ACCOUNT_ID, 1173 EXTERNAL_USER_TESTING_ACCOUNT_ID 1174]; 1175[...CC_STAGING_ACCOUNT_IDS]; 1176var BUTTON_BORDER_COLOR_NAME = "buttonBorder_color"; 1177var BUTTON_TEXT_COLOR_NAME = "buttonText_color"; 1178var BUTTON_FILL_COLOR_NAME = "button_color"; 1179var NpsSurveyId = "4775168"; 1180var ANALYTICS_DEMO_ACCOUNTS = /* @__PURE__ */ new Set([ 1181 "0015a000037l1cjAAA", 1182 "0015a000037l1bqAAA", 1183 "0015a000037l1atAAA", 1184 "0015a000037l1aYAAQ", 1185 "0015a000037l1asAAA", 1186 "0015a000037l1bCAAQ", 1187 "0015a000037l1a5AAA", 1188 "0015a000037l1brAAA", 1189 "0015a000037l1aKAAQ", 1190 "0015a000037l1aJAAQ", 1191 "0015a000037l1bEAAQ", 1192 "0015a000037l1c5AAA", 1193 "0015a000037l1bsAAA", 1194 "0015a000037l1bDAAQ", 1195 "0015a000037l1bbAAA", 1196 "0015a000037l1cPAAQ", 1197 "0015a000031AWmKAAW", 1198 "0015a000037l1ZfAAI", 1199 "0015a000037kL9OAAU", 1200 "0015a000037l1a6AAA", 1201 "0015a000037kKyQAAU", 1202 "0015a000037l1a9AAA", 1203 "0015a000037kKykAAE", 1204 "0015a000037kAcHAAU", 1205 "0015a000037kL99AAE", 1206 "0015a0000344BmIAAU", 1207 "0015a0000343ht4AAA", 1208 "0015a000037l1ZVAAY", 1209 "0015a000037kL8kAAE", 1210 "0015a000037l1ToAAI", 1211 "0015a000037kKz4AAE", 1212 "0015a000037kL8BAAU", 1213 "0015a000037kLBeAAM", 1214 "0015a000037kL8VAAU" 1215]); 1216var M2_Logo_Aspect_Ratio_Value = { 1217 aspectRatio: 3, 1218 objectFit: "contain" 1219}; 1220var DEFAULT_NARRATOR_NAME = "Jessica"; 1221var DEPRECATED_ELEVENLABS_NARRATOR_NAMES = ["Aria", "Charlotte"]; 1222var MEDIA_OVERLAY_UNSUPPORTED_LAYOUT_NAME = "X4_Layout7_M2"; 1223var AVATAR_SILENCE_DURATION = .2;
1224var STATIC_DEFAULT_PROFILE_NAME = "Untitled"; 1225var APPS = /* @__PURE__ */ function(APPS) { 1226 APPS["SUNDAYSKY"] = "sundaysky"; 1227 APPS["AMPLIFY"] = "amplify"; 1228 return APPS; 1229}({}); 1230//#endregion 1231//#region client/logic/vlx/consts.ts 1232var import_dist$8 = require_dist$1(); 1233var import_prop_types = /* @__PURE__ */ __toESM(require_prop_types()); 1234var VLX_PARAMTYPE = import_dist$8.paramType; 1235var VLX_SCOPE = import_dist$8.scope; 1236var VLX_FUNCTION_TAGS = import_dist$8.tag; 1237var ADAVarName = import_dist$8.DESCRIPTIVE_TRANSCRIPT; 1238var SCENES_REPOSITORY = "scene"; 1239var CURATED_REPOSITORY = "curated"; 1240var ANIMATION_REPOSITORY = "animation"; 1241var LOGIC_DATA_TYPES = Object.freeze({ 1242 Const: "const", 1243 ValueSetValue: "valueSetValue", 1244 DataElement: "dataElement", 1245 Asset: "asset", 1246 Animation: "animation", 1247 MappingTable: "mappingTable", 1248 Variable: "variable" 1249}); 1250var LOGIC_MEDIA_TYPES = Object.freeze({ 1251 String: "string", 1252 Number: "number", 1253 Date: "datetime", 1254 URL: "url", 1255 Boolean: "boolean" 1256}); 1257var LogicMediaTypeValues = Object.keys(LOGIC_MEDIA_TYPES).map((key) => LOGIC_MEDIA_TYPES[key]); 1258var CURATED_ASSETS_MEDIA_TYPES = Object.freeze({ 1259 Text: "text", 1260 Image: "image", 1261 Video: "video", 1262 Audio: "audio" 1263}); 1264var ASSET_TYPES = Object.freeze({ 1265 decisionTable: "decision_table", 1266 mappingTable: "mapping_table", 1267 animation: "animation", 1268 narrator: "narrator", 1269 curated: "curated", 1270 recording: "recording", 1271 story: "story", 1272 inlineStory: "inlineStory", 1273 scene: "scene" 1274}); 1275var LOGIC_TYPE = Object.freeze({ 1276 SceneValidation: "boolean", 1277 NextScene: "scene", 1278 Story: "Story", 1279 Quality: "quality", 1280 Ratio: "ratio", 1281 Animation: "animation", 1282 Image: "image", 1283 Video: "video", 1284 Text: "text", 1285 Audio: "audio", 1286 BackgroundAsset: "backgroundAsset", 1287 DataElementString: "string", 1288 DataElementNumber: "number", 1289 DataElementDate: "datetime", 1290 DataElementBoolean: "de_boolean", 1291 AnalyticCustomField: "analyticsField", 1292 Compound: "compound", 1293 Prioritized: "prioritized", 1294 PrioritizedSlot: "prioritized-slot", 1295 Color: "color" 1296}); 1297var LogicTypeValues = Object.keys(LOGIC_TYPE).map((key) => LOGIC_TYPE[key]); 1298var LOGIC_CONTEXT = Object.freeze({ 1299 Scene: "scene", 1300 Derived: "derived", 1301 Placeholder: "placeholder", 1302 Story: "story", 1303 StoryRatioAndQuality: "storyRatioAndQuality", 1304 Narration: "narration", 1305 Prioritized: "prioritized", 1306 Soundtrack: "soundtrack", 1307 BackgroundAsset: "backgroundAsset", 1308 Program: "program" 1309}); 1310var LogicContextValues = Object.keys(LOGIC_CONTEXT).map((key) => LOGIC_CONTEXT[key]); 1311var VALIDATION_STATUS = Object.freeze({ 1312 Valid: "valid", 1313 Partial: "partial", 1314 Invalid: "invalid" 1315}); 1316var VALIDATION_TEXT = Object.freeze({ 1317 ValueIsEmpty: "Value is empty", 1318 ValueCanBeComplexStringOnlyForStringPlaceholders: "Value can be complex string only for string placeholders", 1319 SelectedMediaTypeDoesNotMatchPlaceholderType: "Selected media type does not match placeholder type", 1320 DataElementsOrAssetsNotValid: "Data elements / Assets not valid", 1321 DataTableNotValid: "Data table is not valid", 1322 DataElementValueSetNotValid: "Data element value set is not valid", 1323 AssetIsRequestWaitingForFulfilment: "Asset is Request waiting for fulfilment", 1324 DerivedDataElementIsNotValid: "Derived Data Element is not valid", 1325 DerivedDataElementLogicIsNotValid: "Derived Data Element logic is not valid", 1326 InvalidOperatorForLeftHandSideOperand: "Invalid operator for left-hand side operand", 1327 OperationMustBeComplete: "Operation must be complete", 1328 RightHandSideOperandTypeMismatch: "Right-hand side operand type does not match operator", 1329 OperandFunctionOrFormatterTypeMismatch: "Operand type does not match function or formatter", 1330 ValueFunctionOrFormatterTypeMismatch: "Value type does not match function or formatter", 1331 SelectedDataElementIsMissingOrPending: "Selected data element is missing/pending", 1332 RuleMustHaveValidCondition: "Rule must have valid condition", 1333 RuleMustHaveAtLeastOneCondition: "Rule must have at least one condition", 1334 CaseMustHaveAValue: "Case must have a value", 1335 RuleValueMustBeValid: "Rule value must be valid", 1336 PlaceholderMustHaveAName: "Placeholder must have a name", 1337 PrioritizedListIsMissing: "List does not exist",
1338 PrioritizedListLogicIsInvalid: "List logic is not valid", 1339 PrioritizedListSlotIsMissing: "List Slot does not exist", 1340 InputMustHaveADefaultValue: "Input must have a default value", 1341 PleaseChooseAnElement: "Please choose an element", 1342 InvalidDataElementSelected: "Invalid data element selected", 1343 OperatorMustBeValid: "Operator must be valid", 1344 ShownRuleValueMustBeValid: "Shown rule value must be valid", 1345 DefaultValueShouldBeValid: "Default value should be valid", 1346 RuleOperatorsMustBeValid: "Rule Operators must be valid", 1347 AllCasesMustBeValid: "All Cases must be valid", 1348 CompoundValuesMustBeValid: "Compound values must be valid", 1349 HotspotValuesMustBeValid: "Hotspot values must be valid", 1350 SingleValueMustBeValid: "Single value must be valid", 1351 CandidateNameMustBeValid: "Candidate name must be valid", 1352 StoryIsMissing: "Selected story is missing" 1353}); 1354var DATA_TABLE_OUTPUT_TYPES = Object.freeze({ 1355 String: "string", 1356 Url: "external", 1357 Color: "color", 1358 Media: "url" 1359}); 1360var TEXT_ELEMENTS = [{ 1361 name: "\n", 1362 title: "Line Break", 1363 value: "\n", 1364 iconClass: "line-break", 1365 defaultValue: "\n" 1366}]; 1367var CYCLIC_ERROR_MESSAGE = "Cyclic Dependency!"; 1368var HOTSPOT_TYPES = Object.freeze({ URL: "URL" }); 1369var HOTSPOT_DISPLAY_MAPPERS = Object.freeze({ [HOTSPOT_TYPES.URL]: { 1370 url: "Destination URL", 1371 label: "Label", 1372 operation: "Reports operation", 1373 code: "Reports code", 1374 id: "id", 1375 type: "type" 1376} }); 1377var EXCLUDED_HOTSPOT_KEYS = [ 1378 "id", 1379 "type", 1380 "name", 1381 "code" 1382]; 1383import_prop_types.default.shape({ 1384 status: import_prop_types.default.string, 1385 report: import_prop_types.default.arrayOf(import_prop_types.default.object), 1386 message: import_prop_types.default.string 1387}); 1388//#endregion 1389//#region client/logic/Logics/ActionableDataUtils.ts 1390var actionableDataObjectType = Symbol("_OBJECT_LOGIC_ACTIONABLE_DATA"); 1391var ActionableDataPropType = import_prop_types.default.shape({ 1392 mediaType: import_prop_types.default.oneOf(Object.values(LOGIC_MEDIA_TYPES)), 1393 displayName: import_prop_types.default.string, 1394 id: import_prop_types.default.string, 1395 type: import_prop_types.default.oneOf(Object.values(LOGIC_DATA_TYPES)), 1396 name: import_prop_types.default.string, 1397 actions: import_prop_types.default.array 1398}); 1399function buildActionableData(args, mediaType, dataType) { 1400 if (typeof args !== "object") { 1401 args = { value: args }; 1402 if (mediaType) args.mediaType = mediaType; 1403 if (dataType) args.dataType = dataType; 1404 } 1405 const defaults = { 1406 mediaType: LOGIC_MEDIA_TYPES.String, 1407 dataType: LOGIC_DATA_TYPES.Const, 1408 displayName: args.value, 1409 actions: [] 1410 }; 1411 args = Object.assign({}, defaults, args); 1412 const { id, value, displayName, dataType: effectiveDataType, mediaType: effectiveMediaType, actions } = args; 1413 return { 1414 id, 1415 name: value, 1416 value, 1417 displayName, 1418 mediaType: effectiveMediaType, 1419 type: effectiveDataType, 1420 actions, 1421 _objectType: actionableDataObjectType 1422 }; 1423} 1424/*** 1425* Extracts the value stored in the actionable data of an object 1426* (used to be name, for old objects, and has value/id for newer ones 1427* @param actionableDataObj - An object representing data in logic (which has actions that can be aplied on it) created with buildAcitonableData functions (see above) 1428*/ 1429function getValueFromActionableData(actionableDataObj) { 1430 if (!actionableDataObj) return null; 1431 if (valueExists(actionableDataObj.value)) return actionableDataObj.value.toString(); 1432 if (valueExists(actionableDataObj.id)) return actionableDataObj.id; 1433 if (valueExists(actionableDataObj.name)) return actionableDataObj.name.toString(); 1434} 1435//#endregion 1436//#region common/types/dataTable.ts 1437var DataTableOutputTypes = /* @__PURE__ */ function(DataTableOutputTypes) { 1438 DataTableOutputTypes["String"] = "string"; 1439 DataTableOutputTypes["URL"] = "url"; 1440 DataTableOutputTypes["Color"] = "color"; 1441 return DataTableOutputTypes; 1442}({}); 1443//#endregion 1444//#region common/types/logic.ts 1445function t(o) { 1446 return o; 1447} 1448var LogicMediaType = t({ 1449 ...DataElementContentTypes, 1450 ...DataTableOutputTypes, 1451 List: "prioritized", 1452 ListSlot: "prioritized-slot" 1453}); 1454var LogicType = /* @__PURE__ */ function(LogicType) { 1455 LogicType["SceneValidation"] = "boolean"; 1456 LogicType["Story"] = "Story"; 1457 LogicType["Quality"] = "quality"; 1458 LogicType["Ratio"] = "ratio"; 1459 LogicType["NextScene"] = "scene"; 1460 LogicType["Animation"] = "animation"; 1461 LogicType["Image"] = "image";
1462 LogicType["Video"] = "video"; 1463 LogicType["Text"] = "text"; 1464 LogicType["Audio"] = "audio"; 1465 LogicType["BackgroundAsset"] = "backgroundAsset"; 1466 LogicType["DataElementString"] = "string"; 1467 LogicType["DataElementNumber"] = "number"; 1468 LogicType["DataElementDate"] = "datetime"; 1469 LogicType["DataElementBoolean"] = "de_boolean"; 1470 LogicType["AnalyticCustomField"] = "analyticsField"; 1471 LogicType["Compound"] = "compound"; 1472 LogicType["Prioritized"] = "prioritized"; 1473 LogicType["PrioritizedSlot"] = "prioritized-slot"; 1474 LogicType["Color"] = "color"; 1475 return LogicType; 1476}({}); 1477var LogicContext = /* @__PURE__ */ function(LogicContext) { 1478 LogicContext["Scene"] = "scene"; 1479 LogicContext["Derived"] = "derived"; 1480 LogicContext["Placeholder"] = "placeholder"; 1481 LogicContext["Story"] = "story"; 1482 LogicContext["StoryRatioAndQuality"] = "storyRatioAndQuality"; 1483 LogicContext["Narration"] = "narration"; 1484 LogicContext["Prioritized"] = "prioritized"; 1485 LogicContext["Soundtrack"] = "soundtrack"; 1486 LogicContext["BackgroundAsset"] = "backgroundAsset"; 1487 LogicContext["Program"] = "program"; 1488 return LogicContext; 1489}({}); 1490var ActionableDataValueType = /* @__PURE__ */ function(ActionableDataValueType) { 1491 ActionableDataValueType["Const"] = "const"; 1492 ActionableDataValueType["ValueSetValue"] = "valueSetValue"; 1493 ActionableDataValueType["DataElement"] = "dataElement"; 1494 ActionableDataValueType["Asset"] = "asset"; 1495 ActionableDataValueType["Animation"] = "animation"; 1496 ActionableDataValueType["MappingTable"] = "mappingTable"; 1497 ActionableDataValueType["Variable"] = "variable"; 1498 ActionableDataValueType["Prioritized"] = "prioritized"; 1499 ActionableDataValueType["PrioritizedSlot"] = "prioritized-slot"; 1500 return ActionableDataValueType; 1501}({}); 1502//#endregion 1503//#region client/logic/common/hubNotifications.js 1504var import_pnotify = /* @__PURE__ */ __toESM(require_pnotify()); 1505var import_escape_html = /* @__PURE__ */ __toESM(require_escape_html()); 1506require_pnotify_confirm(); 1507require_pnotify_buttons(); 1508require_pnotify_callbacks(); 1509var HubNotifications = class { 1510 static error(errorMessage) { 1511 new import_pnotify.default({ 1512 title: "Error", 1513 text: (0, import_escape_html.default)(errorMessage), 1514 hide: false, 1515 type: "error", 1516 buttons: { sticker: false } 1517 }); 1518 } 1519 static confirm(title, confirmMsg, confirmCB, cancelCB, confirmButtonText, cancelButtonText) { 1520 new import_pnotify.default({ 1521 width: "450px", 1522 title: (0, import_escape_html.default)(title), 1523 text: (0, import_escape_html.default)(confirmMsg), 1524 hide: false, 1525 icon: "brighttheme-question-icon", 1526 addclass: "stack-modal input-popup-notification", 1527 stack: { 1528 dir1: "down", 1529 dir2: "right", 1530 modal: true, 1531 firstpos1: 200 1532 }, 1533 buttons: { 1534 closer: false, 1535 sticker: false 1536 }, 1537 confirm: { 1538 confirm: true, 1539 buttons: [{ 1540 text: cancelButtonText ? cancelButtonText : "No", 1541 addClass: "whiteBTN", 1542 click: function(notice) { 1543 notice.remove(); 1544 if (typeof cancelCB === "function") cancelCB(); 1545 } 1546 }, { 1547 text: confirmButtonText ? confirmButtonText : "Yes", 1548 click: function(notice) { 1549 notice.remove(); 1550 confirmCB(); 1551 } 1552 }] 1553 } 1554 }); 1555 } 1556 static confirmWithCancel(title, confirmMsg, confirmCB, cancelCB, closeCB) { 1557 new import_pnotify.default({ 1558 width: "450px", 1559 height: "260px", 1560 title: (0, import_escape_html.default)(title), 1561 text: (0, import_escape_html.default)(confirmMsg), 1562 hide: false, 1563 icon: "brighttheme-question-icon", 1564 addclass: "stack-modal input-popup-notification", 1565 stack: { 1566 dir1: "down", 1567 dir2: "right", 1568 modal: true, 1569 firstpos1: 200 1570 }, 1571 buttons: { 1572 closer: false, 1573 sticker: false 1574 }, 1575 confirm: { 1576 confirm: true, 1577 buttons: [ 1578 { 1579 text: "Cancel", 1580 addClass: "whiteBTN", 1581 click: function(notice) { 1582 notice.remove(); 1583 if (typeof closeCB === "function") closeCB(); 1584 } 1585 }, 1586 { 1587 text: "No", 1588 addClass: "whiteBTN", 1589 click: function(notice) { 1590 notice.remove(); 1591 if (typeof cancelCB === "function") cancelCB(); 1592 } 1593 }, 1594 { 1595 text: "Yes", 1596 click: function(notice) { 1597 notice.remove(); 1598 confirmCB(); 1599 } 1600 } 1601 ] 1602 } 1603 }); 1604 } 1605 static sorry(title, confirmMsg, confirmCB) { 1606 new import_pnotify.default({ 1607 width: "450px", 1608 height: "260px", 1609 title: (0, import_escape_html.default)(title), 1610 text: (0, import_escape_html.default)(confirmMsg), 1611 hide: false, 1612 icon: "brighttheme-error-icon", 1613 addclass: "stack-modal input-popup-notification", 1614 stack: { 1615 dir1: "down", 1616 dir2: "right", 1617 modal: true, 1618 firstpos1: 200 1619 }, 1620 buttons: { 1621 closer: false, 1622 sticker: false 1623 },
1624 confirm: { 1625 confirm: true, 1626 buttons: [{ 1627 text: "Got it!", 1628 click: function(notice) { 1629 notice.remove(); 1630 confirmCB(); 1631 } 1632 }, null] 1633 } 1634 }); 1635 } 1636 static inputPopup(title, confirmMsg, confirmCB, cancelCB, confirmButtonText, cancelButtonText, validateFunction, initialValue, emptyPromptMessage) { 1637 let encodedTitle = (0, import_escape_html.default)(title); 1638 let encodedConfirmMsg = (0, import_escape_html.default)(confirmMsg); 1639 let promptValue = initialValue ? initialValue : ""; 1640 let emptyFieldValue = emptyPromptMessage ? encodedConfirmMsg(emptyPromptMessage) : "Enter name"; 1641 let getValidationResult = (value) => { 1642 if (typeof validateFunction !== "function") return { result: true }; 1643 return validateFunction(value); 1644 }; 1645 let buttons = function() { 1646 return [{ 1647 text: cancelButtonText ? cancelButtonText : "No", 1648 addClass: "whiteBTN reject-button", 1649 promptTrigger: false, 1650 click: (notice) => { 1651 notice.remove(); 1652 if (typeof cancelCB === "function") cancelCB(); 1653 } 1654 }, { 1655 text: confirmButtonText ? confirmButtonText : "Yes", 1656 addClass: "confirm-button", 1657 promptTrigger: false, 1658 click: (notice, value) => { 1659 if (typeof confirmCB === "function" && value !== initialValue && getValidationResult(value).result) { 1660 notice.remove(); 1661 confirmCB(value); 1662 } 1663 } 1664 }]; 1665 }; 1666 let getConfirm = function(value) { 1667 return { 1668 prompt: true, 1669 prompt_class: "input-popup", 1670 prompt_default: value, 1671 confirm: true, 1672 buttons: buttons() 1673 }; 1674 }; 1675 let setValidateFunction = function(notice, value, emptyFieldValue) { 1676 notice.get().find(".input-popup").attr("placeholder", emptyFieldValue); 1677 const toggleConfirmButtonState = (status) => { 1678 const confirmButton = notice.get().find(".confirm-button"); 1679 if (status) confirmButton.removeClass("invalid"); 1680 else confirmButton.addClass("invalid"); 1681 }; 1682 const toggleValidationMessage = (status, value) => { 1683 const inputPopup = notice.get().find(".input-popup"); 1684 const invalidMessage = inputPopup.siblings(".input-popup-invalid-message").get(0); 1685 const validFunctionResult = getValidationResult(value); 1686 if (invalidMessage) { 1687 invalidMessage.remove(); 1688 inputPopup.removeClass("invalid"); 1689 } 1690 if (status && validFunctionResult.result === false) { 1691 inputPopup.after(`<div class="input-popup-invalid-message">${validFunctionResult.message}</div>`); 1692 inputPopup.addClass("invalid"); 1693 } 1694 }; 1695 toggleValidationMessage(false, value); 1696 if (!value) toggleConfirmButtonState(false); 1697 notice.get().find(".input-popup").focus().keyup(({ keyCode }) => { 1698 if (keyCode === 27) notice.get().find(".reject-button").get(0).click(); 1699 else if (keyCode === 13) { 1700 const confirmButton = notice.get().find(".confirm-button"); 1701 const confirmButtonClass = confirmButton.attr("class"); 1702 if (confirmButton && confirmButtonClass ? !confirmButtonClass.includes("invalid") : false) confirmButton.get(0).click(); 1703 } else { 1704 const newValue = notice.get().find(".input-popup").get(0).value; 1705 if (newValue !== "" && getValidationResult(newValue).result) { 1706 toggleConfirmButtonState(true);
1707 toggleValidationMessage(false); 1708 } else { 1709 toggleConfirmButtonState(false); 1710 toggleValidationMessage(true, newValue); 1711 } 1712 } 1713 }); 1714 }; 1715 new import_pnotify.default({ 1716 width: "450px", 1717 height: "260px", 1718 title: encodedTitle, 1719 text: encodedConfirmMsg, 1720 hide: false, 1721 icon: "", 1722 addclass: "stack-modal input-popup-notification", 1723 stack: { 1724 dir1: "down", 1725 dir2: "right", 1726 modal: true, 1727 firstpos1: 200 1728 }, 1729 buttons: { 1730 closer: false, 1731 sticker: false 1732 }, 1733 confirm: getConfirm(promptValue), 1734 before_open: (notice) => { 1735 setValidateFunction(notice, promptValue, emptyFieldValue); 1736 notice.get().find(".input-popup").get(0).select(); 1737 } 1738 }); 1739 } 1740}; 1741//#endregion 1742//#region client/logic/common/types.ts 1743var Order = /* @__PURE__ */ function(Order) { 1744 Order["Asc"] = "asc"; 1745 Order["Desc"] = "desc"; 1746 return Order; 1747}({}); 1748var BulkId = /* @__PURE__ */ function(BulkId) { 1749 BulkId["MostEntities"] = "mostEntities"; 1750 BulkId["Assets"] = "assets"; 1751 BulkId["RecordingDocs"] = "recordingDocs"; 1752 BulkId["Animations"] = "animations"; 1753 BulkId["Narrators"] = "narrators"; 1754 BulkId["LifecycleHistory"] = "lifecycleHistory"; 1755 BulkId["DataTables"] = "dataTables"; 1756 return BulkId; 1757}({}); 1758//#endregion 1759//#region client/logic/common/timeUtils.ts 1760init_moment(); 1761var durationToDisplayTimeFromNow = 2880 * 60 * 1e3; 1762var timeDateFormat = "YYYY MM DD hh:mm:ss a"; 1763var readableDateFormat = "DD/MM/YYYY"; 1764var readableTimeFormat = "HH:mm:ss"; 1765var readableTimeDateFormat = "DD/MM/YYYY \xA0 HH:mm:ss"; 1766var readableEditorTimeFormat = "HH:mm"; 1767var readableEditorTimeDateFormat = "MM/DD/YYYY HH:mm"; 1768var secondsDurationFormat = "ss:SS"; 1769var minutesDurationFormat = "mm:ss:SS"; 1770var minutesDurationNoMiliFormat = "mm:ss"; 1771var designSystemReadableTimeFormat = "h:mm A"; 1772var designSystemReadableDateAndYearFormat = "MMM D, YYYY"; 1773var designSystemReadableDateFormat = "MMM D"; 1774var reportsPageDateFormat = "DD-MMM-yyyy \xA0 HH:mm:ss"; 1775var DETAILED_REPORTS_DATE_FORMAT = "YYYY-MM-DD"; 1776var TODAY = "Today"; 1777var YESTERDAY = "Yesterday"; 1778var TOMORROW = "Tomorrow"; 1779var TimeUtils = class TimeUtils { 1780 static getTimeDate(timestamp, disableFromNow) { 1781 if (!disableFromNow && hooks().format("x") - timestamp < durationToDisplayTimeFromNow) return hooks(timestamp).fromNow(); 1782 else return hooks(timestamp).format(timeDateFormat); 1783 } 1784 static { 1785 this.getReadableDuration = (milliseconds, format) => { 1786 const duration = hooks.duration(milliseconds); 1787 return hooks.utc(duration.as("milliseconds")).format(format).toString(); 1788 }; 1789 } 1790 static getReadableTime(timestamp) { 1791 return hooks(timestamp).format(readableTimeFormat); 1792 } 1793 static getReadableDate(timestamp) { 1794 return hooks(timestamp).format(readableDateFormat); 1795 } 1796 static getReadableTimeDate(timestamp) { 1797 return hooks(timestamp).format(readableTimeDateFormat); 1798 } 1799 static getReportsPageDateFormats(timestamp) { 1800 return hooks(timestamp).format(reportsPageDateFormat); 1801 } 1802 static getEditorReadableTime(timestamp) { 1803 return hooks(timestamp).format(readableEditorTimeFormat); 1804 } 1805 static getEditorReadableTimeDate(timestamp) { 1806 return hooks(timestamp).format(readableEditorTimeDateFormat); 1807 } 1808 static getReadableTimeDateWithTodayText(timestamp) { 1809 if (hooks(timestamp).isSame(hooks(), "day")) return `Today at ${hooks(timestamp).format(readableEditorTimeFormat)}`; 1810 return hooks(timestamp).format(readableEditorTimeDateFormat); 1811 } 1812 static { 1813 this.getReadableSecondsDuration = (milliseconds) => { 1814 return TimeUtils.getReadableDuration(milliseconds, secondsDurationFormat); 1815 }; 1816 } 1817 static { 1818 this.getReadableMinutesDuration = (milliseconds) => { 1819 return TimeUtils.getReadableDuration(milliseconds, minutesDurationFormat); 1820 }; 1821 } 1822 static { 1823 this.getReadableMinutesNoMiliDuration = (milliseconds) => { 1824 return TimeUtils.getReadableDuration(milliseconds, minutesDurationNoMiliFormat); 1825 }; 1826 } 1827 static compare(timeStampA, timeStampB, format) { 1828 const compareFormat = format ? format : readableTimeDateFormat; 1829 return hooks(timeStampA, compareFormat).valueOf() - hooks(timeStampB, compareFormat).valueOf(); 1830 } 1831 static getDesignSystemReadableTime(timestamp) { 1832 if (!timestamp) return ""; 1833 return hooks(timestamp).format(designSystemReadableTimeFormat); 1834 } 1835 static getDesignSystemReadableDate(timestamp) { 1836 if (!timestamp) return ""; 1837 const momentFromStamp = hooks(timestamp); 1838 let readableDate; 1839 if (momentFromStamp.isSame(hooks(), "day")) readableDate = TODAY; 1840 else if (momentFromStamp.isSame(hooks().subtract(1, "days").startOf("day"), "day")) readableDate = YESTERDAY; 1841 else if (momentFromStamp.isSame(hooks().add(1, "days").startOf("day"), "day")) readableDate = TOMORROW; 1842 else if (momentFromStamp.isSame(hooks(), "year")) readableDate = momentFromStamp.format(designSystemReadableDateFormat); 1843 else readableDate = momentFromStamp.format(designSystemReadableDateAndYearFormat); 1844 return readableDate; 1845 } 1846 static isDateRelative(readtableDate) { 1847 if (!readtableDate) return false;
1848 if (readtableDate.includes(TODAY) || readtableDate.includes(YESTERDAY) || readtableDate.includes(TOMORROW)) return true; 1849 return false; 1850 } 1851 static getMillisecondsSinceTime(timestamp) { 1852 if (!timestamp) return 0; 1853 const momentFromStamp = hooks(timestamp); 1854 return hooks().diff(momentFromStamp, "milliseconds"); 1855 } 1856 static getDesignSystemReadableTimeDate(timestamp, ignoreTime = false) { 1857 if (!timestamp) return ""; 1858 const readableDate = this.getDesignSystemReadableDate(timestamp); 1859 if (ignoreTime) return readableDate; 1860 return `${readableDate}, ${this.getDesignSystemReadableTime(timestamp)}`; 1861 } 1862}; 1863//#endregion 1864//#region common/compareUtils.ts 1865function is(x, y) { 1866 if (x === y) return x !== 0 || y !== 0 || 1 / x === 1 / y; 1867 else return x !== x && y !== y; 1868} 1869function shallowEqual(objA, objB) { 1870 if (is(objA, objB)) return true; 1871 if (typeof objA !== "object" || objA === null || typeof objB !== "object" || objB === null) return false; 1872 const keysA = Object.keys(objA); 1873 const keysB = Object.keys(objB); 1874 if (keysA.length !== keysB.length) return false; 1875 for (let i = 0; i < keysA.length; i++) if (!Object.hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) return false; 1876 return true; 1877} 1878function sameArrays(array1, array2, equals) { 1879 if (!array1 || !array2) return false; 1880 const defaultEquals = (a, b) => a === b; 1881 const equalsFn = equals || defaultEquals; 1882 return array1.length === array2.length && array1.reduce((acc, item, index) => acc && equalsFn(item, array2[index]), true); 1883} 1884//#endregion 1885//#region client/logic/common/generalUtils.ts 1886function deepCloneObj(obj, notifyUser = true) { 1887 if (obj === void 0) return; 1888 try { 1889 return JSON.parse(JSON.stringify(obj)); 1890 } catch (err) { 1891 if (notifyUser) HubNotifications.error(err); 1892 } 1893} 1894function removeMasterFromScenes(scenes) { 1895 let scenesCopy = deepCloneObj(scenes); 1896 if (Array.isArray(scenesCopy)) { 1897 const masterIndex = scenesCopy.findIndex((scene) => (scene.id || scene) === LogicContainers.Master); 1898 masterIndex > -1 && scenesCopy.splice(masterIndex, 1); 1899 } else if (typeof scenesCopy === "object") delete scenesCopy[LogicContainers.Master]; 1900 return scenesCopy; 1901} 1902function sortByPropName(cellA, cellB, orderBy, order, propName) { 1903 const nameA = cellA.value.props[propName]; 1904 const nameB = cellB.value.props[propName]; 1905 return order === "desc" ? nameB.localeCompare(nameA) : nameA.localeCompare(nameB); 1906} 1907function sortByString(cellA, cellB, orderBy, order) { 1908 const valA = cellA.value; 1909 const valB = cellB.value; 1910 return order === "desc" ? valB.localeCompare(valA) : valA.localeCompare(valB); 1911} 1912function sortByDisplayText(cellA, cellB, orderBy, order) { 1913 const nameA = cellA.value.props.textValue; 1914 const nameB = cellB.value.props.textValue; 1915 return order === "desc" ? nameB.localeCompare(nameA) : nameA.localeCompare(nameB); 1916} 1917function extractDateFromVersionString(cell) { 1918 return cell.value.split(",")[0]; 1919} 1920function sortByVersionString(cellA, cellB, orderBy, order) { 1921 if (typeof cellA.value !== "string") return order === Order.Desc ? 1 : -1; 1922 else if (typeof cellB.value !== "string") return order === Order.Desc ? -1 : 1; 1923 return sortByDate({ value: extractDateFromVersionString(cellA) }, { value: extractDateFromVersionString(cellB) }, orderBy, order); 1924} 1925function getSortByDisplayDateFunc(format) { 1926 return (cellA, cellB, orderBy, order) => sortByDate(cellA, cellB, orderBy, order, format); 1927} 1928function sortByDate(cellA, cellB, orderBy, order, format) { 1929 const dateA = typeof cellA.value === "string" ? cellA.value : cellA.value.props.textValue; 1930 const dateB = typeof cellB.value === "string" ? cellB.value : cellB.value.props.textValue; 1931 return order === Order.Desc ? TimeUtils.compare(dateB, dateA, format) : TimeUtils.compare(dateA, dateB, format); 1932} 1933var memoizeThunkAction = (thunkAction) => { 1934 let lastArgs; 1935 return (...args) => { 1936 if (sameArrays(lastArgs, args)) return () => {}; 1937 else { 1938 lastArgs = Array.from(args); 1939 return thunkAction(...args); 1940 } 1941 }; 1942}; 1943//#endregion 1944//#region common/generalUtils.ts 1945function mapNumToLetter(int) { 1946 return String.fromCharCode("A".charCodeAt(0) + int); 1947} 1948function mapLetterToNum(c) {
1949 return c && c.charCodeAt(0) - "A".charCodeAt(0); 1950} 1951function toSentenceCase(string) { 1952 return typeof string === "string" ? string.charAt(0).toUpperCase() + string.slice(1).toLowerCase() : string; 1953} 1954function isUuid(string) { 1955 if (typeof string !== "string") return false; 1956 return /^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$/i.test(string); 1957} 1958function excludeKeysFromObject(keysToExclude, object) { 1959 let objectKeys = Object.keys(object); 1960 if (objectKeys) return objectKeys.filter((ok) => !keysToExclude.includes(ok)).reduce((acc, newObjectKeys) => { 1961 return { 1962 ...acc, 1963 [newObjectKeys]: object[newObjectKeys] 1964 }; 1965 }, {}); 1966} 1967function mapRange(x, in_min, in_max, out_min, out_max) { 1968 return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 1969} 1970var convertMapToPlainObject = (map) => { 1971 return Object.assign({}, ...[...map.entries()].map(([k, v]) => ({ [k]: v }))); 1972}; 1973var removeEmptyEntriesFromObject = (obj, strictMode = false) => { 1974 if (obj === void 0) return; 1975 return JSON.parse(JSON.stringify(obj), (_, value) => { 1976 return value === null || value === void 0 || !strictMode && value === "" || !strictMode && Array.isArray(value) && value.length === 0 ? void 0 : value; 1977 }); 1978}; 1979var unionSets = (...iterables) => { 1980 const set = /* @__PURE__ */ new Set(); 1981 for (let iterable of iterables) for (let item of iterable) set.add(item); 1982 return set; 1983}; 1984var reAlpha = /[^a-zA-Z]+/g; 1985var reNumeric = /[^0-9]+/g; 1986function sortAlphaNum(a, b) { 1987 const aA = a.replace(reAlpha, "-").toLocaleLowerCase(); 1988 const bA = b.replace(reAlpha, "-").toLocaleLowerCase(); 1989 if (aA === bA) { 1990 const aN = parseInt(a.replace(reNumeric, ""), 10); 1991 const bN = parseInt(b.replace(reNumeric, ""), 10); 1992 return aN === bN ? 0 : aN > bN ? 1 : -1; 1993 } else return aA > bA ? 1 : -1; 1994} 1995var isObject = (value) => { 1996 return value && typeof value === "object" && !Array.isArray(value); 1997}; 1998var isAnEmptyObject = (value) => { 1999 return isObject(value) && Object.entries(value).length === 0; 2000}; 2001function immutablyReplaceValue(obj, path, value, merge) { 2002 obj = obj && typeof obj === "object" ? obj : void 0; 2003 if (path.length === 0) { 2004 if (merge && typeof value === "object") return { 2005 ...obj, 2006 ...value 2007 }; 2008 return value; 2009 } 2010 const part = path.shift(); 2011 return { 2012 ...obj, 2013 [part]: immutablyReplaceValue(obj && obj[part], path, value, merge) 2014 }; 2015} 2016var clearObj = (obj) => { 2017 return Object.keys(obj).reduce((acc, key) => { 2018 if (obj[key] !== void 0) acc[key] = obj[key]; 2019 return acc; 2020 }, {}); 2021}; 2022var replaceSpecialChar = (value, charToReplaceWith) => { 2023 return value?.replace(/[^A-Za-z0-9]+/g, charToReplaceWith) ?? ""; 2024}; 2025var escapeRegExp = (str) => { 2026 return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); 2027}; 2028var getUniqueNameWithRunningSuffix = (newName, allNames) => { 2029 const suffixes = allNames.map((name) => { 2030 const matches = name.toLowerCase().match(new RegExp(escapeRegExp(newName.toLowerCase()) + "(\\d*)$")); 2031 const suffix = Number(matches?.[1]); 2032 return !Number.isNaN(suffix) ? suffix : null; 2033 }).filter((suffix) => suffix != null); 2034 return suffixes.length > 0 ? newName + (Math.max(...suffixes) + 1).toString() : newName; 2035}; 2036var areAllObjectPropertiesEmpty = (obj) => { 2037 if (!obj) return true; 2038 return !Object.keys(obj).some((key) => { 2039 if (obj[key]) return true; 2040 }); 2041}; 2042var isNumber = (value) => { 2043 return Number.isFinite(value); 2044}; 2045var stableSort = (array, compareFn) => { 2046 const indexedArray = array.map((value, index) => ({ 2047 value, 2048 index 2049 })); 2050 indexedArray.sort((a, b) => { 2051 const cmpResult = compareFn(a.value, b.value); 2052 return cmpResult === 0 ? a.index - b.index : cmpResult; 2053 }); 2054 return indexedArray.map((item) => item.value); 2055}; 2056var escapeHTML = (value) => String(value).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); 2057//#endregion 2058//#region client/logic/validations/validationTable.ts 2059var ValidationTable = class { 2060 constructor() { 2061 this.getById = (id) => { 2062 return this.table[id]; 2063 }; 2064 this.putById = (id, record) => { 2065 this.table[id] = record; 2066 }; 2067 this.getAllRecords = () => { 2068 return Object.values(this.table); 2069 }; 2070 this.table = {}; 2071 } 2072 static getTableKey(type, id) {
2073 return type + "/" + id; 2074 } 2075}; 2076//#endregion 2077//#region client/logic/entities/definitions.ts 2078var EntityTypes = /* @__PURE__ */ function(EntityTypes) { 2079 EntityTypes["ANIMATION"] = "Animation"; 2080 EntityTypes["ASSET"] = "Asset"; 2081 EntityTypes["ANALYTICS"] = "Analytics"; 2082 EntityTypes["DATA_ELEMENT"] = "DataElement"; 2083 EntityTypes["CREATIVE_DATA_ELEMENT"] = "ContentSetData"; 2084 EntityTypes["DATA_TABLE"] = "DataTable"; 2085 EntityTypes["DERIVED_DATA_ELEMENT"] = "StudioDataElement"; 2086 EntityTypes["GROUP"] = "Group"; 2087 EntityTypes["MEDIA"] = "Media"; 2088 EntityTypes["NARRATION"] = "Narration"; 2089 EntityTypes["PARAMETER"] = "Parameter"; 2090 EntityTypes["PLACEHOLDER"] = "Placeholder"; 2091 EntityTypes["PRIORITIZED_LIST"] = "List"; 2092 EntityTypes["PRIORITIZED_LIST_CANDIDATE"] = "PrioritizedListCandidate"; 2093 EntityTypes["PROGRAM"] = "Program"; 2094 EntityTypes["RECORDING"] = "Recording"; 2095 EntityTypes["SCENE"] = "Scene"; 2096 EntityTypes["SCENE_VALIDATION"] = "SceneValidation"; 2097 EntityTypes["SCENE_ANIMATION"] = "SceneAnimation"; 2098 EntityTypes["SCENE_PART"] = "ScenePart"; 2099 EntityTypes["LOGIC"] = "Logic"; 2100 EntityTypes["STORY"] = "Story"; 2101 EntityTypes["OVERVIEW"] = "Overview"; 2102 EntityTypes["SETTINGS"] = "Settings"; 2103 return EntityTypes; 2104}({}); 2105var RecordStatus = /* @__PURE__ */ function(RecordStatus) { 2106 RecordStatus["PENDING"] = "PENDING"; 2107 RecordStatus["CALCULATING"] = "CALCULATING"; 2108 RecordStatus["DONE"] = "DONE"; 2109 return RecordStatus; 2110}({}); 2111//#endregion 2112//#region client/logic/validations/validationTableRecord.ts 2113var ValidationTableRecord = class { 2114 constructor(prevValidationResult, validate) { 2115 this.prevValidationResult = prevValidationResult; 2116 this.validate = validate; 2117 this.validationResult = null; 2118 this.status = RecordStatus.PENDING; 2119 } 2120}; 2121//#endregion 2122//#region client/logic/validations/validationManager.ts 2123var IssueCodes = /* @__PURE__ */ function(IssueCodes) { 2124 IssueCodes["MISSING"] = "MISSING"; 2125 IssueCodes["CYCLIC_DEPENDENCY"] = "CYCLIC_DEPENDENCY"; 2126 IssueCodes["DATA_ELEMENT_VALUE_SET"] = "DATA_ELEMENT_VALUE_SET"; 2127 IssueCodes["DERIVED_DATA_ELEMENT_CYCLIC_DEPENDENCY"] = "DERIVED_DATA_ELEMENT_CYCLIC_DEPENDENCY"; 2128 IssueCodes["DATA_TABLE_SCHEME_ERROR"] = "DATA_TABLE_SCHEME_ERROR"; 2129 IssueCodes["NARRATION_ORPHANED_DIMENSIONS"] = "NARRATION_ORPHANED_DIMENSIONS"; 2130 IssueCodes["NARRATION_ORPHANED_VARIATIONS"] = "NARRATION_ORPHANED_VARIATIONS"; 2131 IssueCodes["NARRATION_EMPTY_LINES"] = "NARRATION_EMPTY_LINES"; 2132 IssueCodes["NARRATION_DATA_ELEMENTS_ERROR"] = "NARRATION_DATA_ELEMENTS_ERROR"; 2133 IssueCodes["NARRATION_DERIVED_DATA_ELEMENTS_ERROR"] = "NARRATION_DERIVED_DATA_ELEMENTS_ERROR"; 2134 IssueCodes["NARRATION_CREATIVE_OVERRIDE_ERROR"] = "NARRATION_CREATIVE_OVERRIDE_ERROR"; 2135 IssueCodes["PRIORITIZED_LIST_EMPTY_CANDIDATE_NAME"] = "PRIORITIZED_LIST_EMPTY_CANDIDATE_NAME"; 2136 IssueCodes["PRIORITIZED_LIST_INVALID_CANDIDATE_NAME"] = "PRIORITIZED_LIST_INVALID_CANDIDATE_NAME"; 2137 IssueCodes["PRIORITIZED_LIST_DUPLICATE_CANDIDATE_NAME"] = "PRIORITIZED_LIST_DUPLICATE_CANDIDATE_NAME"; 2138 IssueCodes["PRIORITIZED_LIST_CANDIDATES_ERROR"] = "PRIORITIZED_LIST_CANDIDATES_ERROR"; 2139 IssueCodes["INVALID_LOGIC"] = "INVALID_LOGIC"; 2140 IssueCodes["ANALYTICS_LOGIC_ERROR"] = "ANALYTICS_LOGIC_ERROR"; 2141 IssueCodes["ANALYTICS_NAME_ERROR"] = "ANALYTICS_NAME_ERROR"; 2142 IssueCodes["DERIVED_LOGIC_ERROR"] = "DERIVED_LOGIC_ERROR"; 2143 IssueCodes["GROUP_LOGIC_ERROR"] = "GROUP_LOGIC_ERROR"; 2144 IssueCodes["PARAMETER_LOGIC_ERROR"] = "PARAMETER_LOGIC_ERROR"; 2145 IssueCodes["PARAMETER_LOGIC_MISSING"] = "PARAMETER_LOGIC_MISSING"; 2146 IssueCodes["PLACEHOLDER_LOGIC_ERROR"] = "PLACEHOLDER_LOGIC_ERROR"; 2147 IssueCodes["PLACEHOLDER_LOGIC_MISSING"] = "PLACEHOLDER_LOGIC_MISSING"; 2148 IssueCodes["PRIORITIZED_LIST_LOGIC_ERROR"] = "PRIORITIZED_LIST_LOGIC_ERROR"; 2149 IssueCodes["SCENE_ANIMATION_LOGIC_ERROR"] = "SCENE_ANIMATION_LOGIC_ERROR"; 2150 IssueCodes["SCENE_VALIDATION_LOGIC_ERROR"] = "SCENE_VALIDATION_LOGIC_ERROR"; 2151 IssueCodes["STORY_LOGIC_ERROR"] = "STORY_LOGIC_ERROR"; 2152 IssueCodes["STORY_SOUNDTRACK_LOGIC_ERROR"] = "STORY_SOUNDTRACK_LOGIC_ERROR"; 2153 IssueCodes["STORY_BACKGROUND_ASSET_LOGIC_ERROR"] = "STORY_BACKGROUND_ASSET_LOGIC_ERROR"; 2154 IssueCodes["STORY_VIDEO_RATIO_QUALITY_LOGIC_ERROR"] = "STORY_VIDEO_RATIO_QUALITY_LOGIC_ERROR"; 2155 IssueCodes["STORY_VIDEO_DURATION_OPTIONS_ERROR"] = "STORY_VIDEO_DURATION_OPTIONS_ERROR"; 2156 IssueCodes["STORY_VIDEO_NUM_OF_PRODUCT_ERROR"] = "STORY_VIDEO_NUM_OF_PRODUCT_ERROR"; 2157 IssueCodes["STORY_VIDEO_RATIO_QUALITY_OPTIONS_ERROR"] = "STORY_VIDEO_RATIO_QUALITY_OPTIONS_ERROR"; 2158 IssueCodes["PROGRAM_SETTINGS_ERROR"] = "PROGRAM_SETTINGS_ERROR"; 2159 IssueCodes["PROGRAM_ANALYTICS_ERROR"] = "PROGRAM_ANALYTICS_ERROR"; 2160 IssueCodes["PROGRAM_SCENES_ERROR"] = "PROGRAM_SCENES_ERROR"; 2161 IssueCodes["PROGRAM_STORY_ERROR"] = "PROGRAM_STORY_ERROR"; 2162 IssueCodes["PROGRAM_STORY_SELECTION_LOGIC_ERROR"] = "PROGRAM_STORY_SELECTION_LOGIC_ERROR"; 2163 IssueCodes["SCENE_PART_ERROR"] = "SCENE_PART_ERROR"; 2164 IssueCodes["SCENE_PART_PLACEHOLDER_ERROR"] = "SCENE_PART_PLACEHOLDER_ERROR"; 2165 IssueCodes["SCENE_PART_NARRATION_ERROR"] = "SCENE_PART_NARRATION_ERROR"; 2166 IssueCodes["SCENE_PART_PARAMETER_ERROR"] = "SCENE_PART_PARAMETER_ERROR"; 2167 IssueCodes["SCENE_PART_GROUP_ERROR"] = "SCENE_PART_GROUP_ERROR"; 2168 IssueCodes["SCENE_PART_PRIORITIZED_LIST_ERROR"] = "SCENE_PART_PRIORITIZED_LIST_ERROR"; 2169 IssueCodes["SCENE_PART_RECORDING_ERROR"] = "SCENE_PART_RECORDING_ERROR"; 2170 IssueCodes["STORY_SCENE_ERROR"] = "STORY_SCENE_ERROR"; 2171 IssueCodes["DERIVED_LOGIC_MISSING"] = "DERIVED_LOGIC_MISSING"; 2172 IssueCodes["RECORDING_IS_PENDING"] = "RECORDING_IS_PENDING"; 2173 IssueCodes["RECORDING_IS_REJECTED"] = "RECORDING_IS_REJECTED"; 2174 IssueCodes["RECORDING_IS_PENDING_APPROVAL"] = "RECORDING_IS_PENDING_APPROVAL"; 2175 return IssueCodes; 2176}({}); 2177var IssueSeverity = /* @__PURE__ */ function(IssueSeverity) { 2178 IssueSeverity["ERROR"] = "ERROR"; 2179 IssueSeverity["WARNING"] = "WARNING"; 2180 return IssueSeverity; 2181}({}); 2182var ValidationManager = class { 2183 constructor(entities) { 2184 this.init = (prevTable, context) => { 2185 let table = new ValidationTable();
2186 this.entities && this.entities.forEach((entity) => { 2187 let entityInstances = entity.collector({ context }); 2188 entityInstances && entityInstances.forEach((entityInstance) => { 2189 const tableKey = ValidationTable.getTableKey(entity.getType(), entityInstance.id); 2190 const prevRecord = prevTable.getById(tableKey); 2191 const record = new ValidationTableRecord(prevRecord && prevRecord.prevValidationResult, entityInstance.validate); 2192 table.putById(tableKey, record); 2193 }); 2194 }); 2195 let allRecords = table.getAllRecords(); 2196 if (allRecords) allRecords.forEach((record) => { 2197 if (!record.validationResult) record.validationResult = this.fulfillRecord(table, record); 2198 }); 2199 return table; 2200 }; 2201 this.fulfillRecord = (table, record) => { 2202 record.status = RecordStatus.CALCULATING; 2203 let result = record.validate(record.prevValidationResult, (type, id) => { 2204 return this.resolveValidationResultById(table, type, id); 2205 }); 2206 record.status = RecordStatus.DONE; 2207 return result; 2208 }; 2209 this.resolveValidationResultById = (table, type, id) => { 2210 let record = table.getById(ValidationTable.getTableKey(type, id)); 2211 if (!record) return { 2212 type, 2213 id, 2214 issues: [{ 2215 code: "MISSING", 2216 severity: "ERROR", 2217 details: {} 2218 }], 2219 severity: "ERROR" 2220 }; 2221 let validationResult = record.validationResult; 2222 if (record.status === RecordStatus.CALCULATING) { 2223 validationResult = { 2224 type, 2225 id, 2226 issues: [{ 2227 code: "CYCLIC_DEPENDENCY", 2228 severity: "ERROR", 2229 details: {} 2230 }], 2231 severity: "ERROR" 2232 }; 2233 return validationResult; 2234 } 2235 if (!validationResult) { 2236 validationResult = this.fulfillRecord(table, record); 2237 record.validationResult = validationResult; 2238 } 2239 return validationResult; 2240 }; 2241 this.readValidationResultById = (table, type, id) => { 2242 let record = table.getById(ValidationTable.getTableKey(type, id)); 2243 if (record) return record.validationResult; 2244 }; 2245 this.entities = entities; 2246 } 2247 static getHighestSeverity(severities) { 2248 for (const severity of severities) if (severity === "ERROR") return "ERROR"; 2249 return "WARNING"; 2250 } 2251}; 2252//#endregion 2253//#region common/types/asset.ts 2254var MediaTypes = /* @__PURE__ */ function(MediaTypes) { 2255 MediaTypes["Video"] = "video"; 2256 MediaTypes["Image"] = "image"; 2257 MediaTypes["Audio"] = "audio"; 2258 MediaTypes["Text"] = "text"; 2259 MediaTypes["Application"] = "application"; 2260 return MediaTypes; 2261}({}); 2262var AssetTypes = /* @__PURE__ */ function(AssetTypes) { 2263 AssetTypes["animation"] = "animation"; 2264 AssetTypes["curated"] = "curated"; 2265 AssetTypes["decisionTable"] = "decision_table"; 2266 AssetTypes["inlineStory"] = "inlineStory"; 2267 AssetTypes["mappingTable"] = "mapping_table"; 2268 AssetTypes["narrator"] = "narrator"; 2269 AssetTypes["program"] = "program"; 2270 AssetTypes["recording"] = "recording"; 2271 AssetTypes["story"] = "story"; 2272 AssetTypes["scene"] = "scene"; 2273 AssetTypes["wireframesUI"] = "wireframesUI"; 2274 return AssetTypes; 2275}({}); 2276var RecordingOrigin = /* @__PURE__ */ function(RecordingOrigin) { 2277 RecordingOrigin["Builder"] = "builder"; 2278 RecordingOrigin["Creative"] = "creative"; 2279 return RecordingOrigin; 2280}({}); 2281var NarrationRecordingErrorReason = /* @__PURE__ */ function(NarrationRecordingErrorReason) { 2282 NarrationRecordingErrorReason["BADINTONATION"] = "Bad Intonation"; 2283 NarrationRecordingErrorReason["CORRUPTED"] = "Corrupted"; 2284 NarrationRecordingErrorReason["TEXTDOESNOTMATCH"] = "Text does not match"; 2285 NarrationRecordingErrorReason["OTHER"] = "Other"; 2286 return NarrationRecordingErrorReason; 2287}({}); 2288var EditorLibraryMediaType = /* @__PURE__ */ function(EditorLibraryMediaType) { 2289 EditorLibraryMediaType["Video"] = "video"; 2290 EditorLibraryMediaType["Image"] = "image"; 2291 return EditorLibraryMediaType; 2292}({}); 2293//#endregion 2294//#region client/components/HubEditor/HubEditorsUtils.jsx 2295var jsVariableRegExp = /^(?!(?:do|if|in|for|let|new|try|var|symbol|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$)
vendor: 10,923 bytes, line 2295
2295[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/
2295; 2296var alphaNumericRegExp = /^[a-z0-9]+$/i; 2297var HubEditorUtils = class { 2298 static isAlphaNumeric(input) { 2299 return alphaNumericRegExp.test(input); 2300 } 2301 static isValidJsVariable(input) { 2302 return jsVariableRegExp.test(input); 2303 } 2304 static isValidJsObjAndProperty(input) { 2305 return input && input.split(".").every((exp) => jsVariableRegExp.test(exp)); 2306 } 2307}; 2308//#endregion 2309//#region client/logic/builder/editorsContainerLogic/groupUtils.js 2310function getGroupX(placeholders) { 2311 const x = placeholders.map((p) => p.x).sort((a, b) => a - b)[0]; 2312 return x <= 6 ? 0 : x - 6; 2313} 2314function getGroupWidth(groupX, placeholders) { 2315 const grpWidth = placeholders.map((p) => p.x + p.width).sort((a, b) => b - a)[0] - groupX + 5; 2316 return grpWidth + groupX <= CANVAS_DIMENSIONS.width ? grpWidth : CANVAS_DIMENSIONS.width - groupX; 2317} 2318function getGroupY(placeholders) { 2319 const y = placeholders.map((p) => p.y).sort((a, b) => a - b)[0]; 2320 return y <= 5 ? 0 : y - 5; 2321} 2322function getGroupHeight(groupY, placeholders) { 2323 const grpHeight = placeholders.map((p) => p.y + p.height).sort((a, b) => b - a)[0] - groupY + 5; 2324 return grpHeight + groupY <= CANVAS_DIMENSIONS.height ? grpHeight : CANVAS_DIMENSIONS.height - groupY; 2325} 2326function calcGroupCoords(placeholders) { 2327 const x = getGroupX(placeholders); 2328 const y = getGroupY(placeholders); 2329 return { 2330 x, 2331 y, 2332 width: getGroupWidth(x, placeholders), 2333 height: getGroupHeight(y, placeholders) 2334 }; 2335} 2336//#endregion 2337//#region client/logic/builder/editorsContainerLogic/prioritizedListUtils.ts 2338function validatePrioritizedListNameFromScenes(scene, value, listId) { 2339 if (!value) return { 2340 result: false, 2341 message: "Enter a list name" 2342 }; 2343 if (!HubEditorUtils.isAlphaNumeric(value)) return { 2344 result: false, 2345 message: ALPHA_NUMERIC_MESSAGE 2346 }; 2347 if (scene && scene.sceneParts) { 2348 for (let scenePart of scene.sceneParts) if (scenePart.prioritizedLists && scenePart.prioritizedLists.some((pl) => pl.name === value && pl.id !== listId)) return { 2349 result: false, 2350 message: "Name already exists" 2351 }; 2352 } 2353 return { result: true }; 2354} 2355function calcOriginPos(val, padding) { 2356 return val <= padding ? 0 : val - padding; 2357} 2358/*** 2359* calculate the size of prioritized list in canvas 2360* 1 - if multiplying height by slot number (with padding) fits in canvas, use that. 2361* 2 - else, push PL to top of canvas (y=0) and check if fits. 2362* 3 - if all else fails, push to top of canvas and apply scale down factor to make group or placeholder smaller. 2363* in that case height should be as close to canvas width as possible but never larger. 2364* 2365* @param itemRect - object representing placeholder or group dimensions - { x, y, width, height } 2366* @param numSlots - number of slots 2367* @param padding - the space between slots and border, default 5 2368* @param canvasDim - object representing width and height of scene part canvas, default { width: 480, height: 270 } 2369* @return position object { 2370* x, 2371* y, 2372* width, 2373* height, 2374* maxItemHeight 2375* scaleFactor 2376* } 2377*/ 2378function calcPrioritizedListSize(itemRect, numSlots, padding = 5, canvasDim = CANVAS_DIMENSIONS) { 2379 const _floorTwoDecimals = (num) => Math.floor(num * 100) / 100; 2380 let plRect = { 2381 x: calcOriginPos(itemRect.x, padding), 2382 y: calcOriginPos(itemRect.y, padding), 2383 width: itemRect.width + padding * 2, 2384 height: padding + (itemRect.height + padding) * numSlots, 2385 maxItemHeight: itemRect.height, 2386 scaleFactor: 1 2387 }; 2388 if (plRect.y + plRect.height <= canvasDim.height) return plRect; 2389 else if (plRect.height <= canvasDim.height) return { 2390 ...plRect, 2391 y: 0 2392 }; 2393 else { 2394 const maxItemHeight = (canvasDim.height - padding) / numSlots - padding; 2395 const scaleFactor = _floorTwoDecimals(maxItemHeight / itemRect.height); 2396 return { 2397 x: plRect.x, 2398 y: 0, 2399 width: Math.round(itemRect.width * scaleFactor) + padding * 2, 2400 height: padding + (Math.round(itemRect.height * scaleFactor) + padding) * numSlots, 2401 maxItemHeight: Math.round(maxItemHeight), 2402 scaleFactor 2403 }; 2404 } 2405} 2406function findPrioritizedListFromScenes(scenes, sceneId, scenePartIndex, prioritizedListId) { 2407 let scene = scenes[sceneId]; 2408 return scene.sceneParts[scenePartIndex].prioritizedLists && scene.sceneParts[scenePartIndex].prioritizedLists.find((pl) => pl.id === prioritizedListId); 2409} 2410function resizeByFactor(itemRect, scaleFactor) { 2411 return { 2412 ...itemRect, 2413 x: itemRect.x, 2414 y: Math.floor(itemRect.y * scaleFactor), 2415 width: Math.floor(itemRect.width * scaleFactor), 2416 height: Math.floor(itemRect.height * scaleFactor) 2417 }; 2418} 2419/*** 2420* calculate the y position of a placeholder in prioritized list 2421* @param baseY - object representing prioritized list dimensions - { x, y, width, height, scaleFactor } 2422* @param relativeY - the y value of placeholder that's in a group, relative to the group y value. 0 for non grouped placeholders 2423* @param slotHeight - the height of each slot 2424* @param slotIndex - slot index 2425* @param padding - the space between slots and border, default 5 2426* @return slots array with positions modified 2427*/ 2428function calcCascadeYValue(baseY, relativeY = 0, slotHeight, slotIndex, padding = 5) { 2429 return baseY + padding + relativeY + slotIndex * (slotHeight + padding); 2430} 2431/*** 2432* change the position of groups and placeholders inside prioritized list. 2433* @param prioritizedListRect - object representing prioritized list dimensions - { x, y, width, height, scaleFactor } 2434* @param slotsOrig - array of groups or placeholders 2435* @param padding - the space between slots and border, default 5 2436* @return slots array with positions modified 2437*/ 2438function cascadePrioritizedListSlots(prioritizedListRect, slotsOrig, padding = 5) { 2439 return deepCloneObj(slotsOrig).map((slotContent, slotIndex) => { 2440 if (slotContent.placeholders) { 2441 const slotY = getGroupY(slotContent.placeholders); 2442 const grpHeight = getGroupHeight(slotY, slotContent.placeholders); 2443 const slotHeight = Math.min(prioritizedListRect.maxItemHeight, grpHeight); 2444 const slotX = getGroupX(slotContent.placeholders); 2445 const updatePlaceholders = slotContent.placeholders.map((ph) => { 2446 const relativeX = Math.floor((ph.x - slotX) * prioritizedListRect.scaleFactor); 2447 const placeholderX = slotX + relativeX; 2448 const relativeY = Math.floor((ph.y - slotY) * prioritizedListRect.scaleFactor); 2449 const placeholderY = calcCascadeYValue(prioritizedListRect.y, relativeY, slotHeight, slotIndex, padding); 2450 return { 2451 ...resizeByFactor(ph, prioritizedListRect.scaleFactor), 2452 x: placeholderX, 2453 y: placeholderY 2454 }; 2455 }); 2456 return { 2457 ...slotContent, 2458 placeholders: updatePlaceholders 2459 }; 2460 } else {
2461 const slotHeight = Math.min(prioritizedListRect.maxItemHeight, slotContent.height); 2462 const slotIndexYValue = calcCascadeYValue(prioritizedListRect.y, 0, slotHeight, slotIndex, padding); 2463 return { 2464 ...resizeByFactor(slotContent, prioritizedListRect.scaleFactor), 2465 y: slotIndexYValue 2466 }; 2467 } 2468 }); 2469} 2470function findPrioritizedListNameFromId(scenes, scenePartIndex, prioritizedListId) { 2471 const scenePart = scenes.sceneParts[scenePartIndex]; 2472 if (scenePart && scenePart.prioritizedLists) { 2473 const prioritizedList = scenePart.prioritizedLists.find((pl) => pl.id === prioritizedListId); 2474 if (prioritizedList) return prioritizedList.name; 2475 } 2476} 2477function getMaxSlotsForPrioritizedList(sceneEditorData, prioritizedListId) { 2478 let maxSlotsNumber = 0; 2479 sceneEditorData.sceneParts.forEach((scenePart) => { 2480 if (scenePart.prioritizedLists && scenePart.prioritizedLists.length) { 2481 const pl = scenePart.prioritizedLists.find((pl) => pl.id === prioritizedListId); 2482 maxSlotsNumber = pl ? Math.max(pl.slots.length, maxSlotsNumber) : maxSlotsNumber; 2483 } 2484 }); 2485 return maxSlotsNumber; 2486} 2487function calcSlotsCoords(prioritizedListSlots) { 2488 if (prioritizedListSlots.some((slot) => slot.placeholders)) return calcGroupCoords(prioritizedListSlots.map((slot) => calcGroupCoords(slot.placeholders))); 2489 else return calcGroupCoords(prioritizedListSlots); 2490} 2491/*** 2492* adds a slot to prioritized list. Duplicates the _last_ slot and then adjusts slots sizes by 2493* 1 - adding slot in bottom 2494* 2 - pushing to top and adding slot in bottom 2495* 3 - making list smaller, pushing to top and adding slot in bottom. FML 2496* @param prioritizedListSlots - array of prioritized list slots 2497* @param padding - the space between slots and border, default 5 2498* @param canvasDim - object representing width and height of scene part canvas, default { width: 480, height: 270 } 2499* @return array of prioritized list slots 2500*/ 2501function addSlot(prioritizedListSlots, padding, canvasDim) { 2502 let newPrioritizedListSlots = deepCloneObj(prioritizedListSlots); 2503 const slotIsAGroup = newPrioritizedListSlots.some((slot) => slot.placeholders); 2504 let newSlot = deepCloneObj(newPrioritizedListSlots[newPrioritizedListSlots.length - 1]); 2505 const newSlotHeight = slotIsAGroup ? calcSlotsCoords([newSlot]).height : newSlot.height; 2506 const currentSlotsCoords = calcSlotsCoords(newPrioritizedListSlots); 2507 let currentSlotsBottom = currentSlotsCoords.y + currentSlotsCoords.height; 2508 if (currentSlotsBottom + newSlotHeight - padding < canvasDim.height) { 2509 if (slotIsAGroup) newSlot.placeholders.forEach((ph) => { 2510 ph.y = currentSlotsBottom + padding; 2511 }); 2512 else newSlot.y = currentSlotsBottom; 2513 newPrioritizedListSlots.push(newSlot); 2514 } else if (currentSlotsCoords.height - currentSlotsCoords.y + newSlotHeight - padding < canvasDim.height) { 2515 newPrioritizedListSlots.forEach((slot) => { 2516 if (slotIsAGroup) slot.placeholders.forEach((ph) => { 2517 ph.y = ph.y - currentSlotsCoords.y + padding; 2518 }); 2519 else slot.y = slot.y - currentSlotsCoords.y; 2520 }); 2521 const newSlotsCoords = calcSlotsCoords(newPrioritizedListSlots); 2522 if (slotIsAGroup) newSlot.placeholders.forEach((ph) => { 2523 ph.y = newSlotsCoords.height + padding; 2524 }); 2525 else newSlot.y = newSlotsCoords.height; 2526 newPrioritizedListSlots.push(newSlot); 2527 } else { 2528 const _floorTwoDecimals = (num) => Math.floor(num * 100) / 100; 2529 const scaleFactor = _floorTwoDecimals(canvasDim.height / (currentSlotsCoords.height + currentSlotsCoords.y + newSlotHeight + padding * 2)); 2530 newPrioritizedListSlots = newPrioritizedListSlots.map((slot) => { 2531 if (slotIsAGroup) { 2532 slot.placeholders = slot.placeholders.map((ph) => resizeByFactor(ph, scaleFactor)); 2533 return slot; 2534 } else return resizeByFactor(slot, scaleFactor); 2535 }); 2536 const newSlotsCoords = calcSlotsCoords(newPrioritizedListSlots); 2537 if (slotIsAGroup) newSlot.placeholders = newSlot.placeholders.map((ph) => { 2538 let newPh = resizeByFactor(ph, scaleFactor); 2539 newPh = { 2540 ...newPh, 2541 y: newSlotsCoords.y + newSlotsCoords.height + padding 2542 }; 2543 return newPh; 2544 }); 2545 else { 2546 newSlot = resizeByFactor(newSlot, scaleFactor); 2547 newSlot = { 2548 ...newSlot, 2549 y: newSlotsCoords.y + newSlotsCoords.height 2550 }; 2551 } 2552 newPrioritizedListSlots.push(newSlot); 2553 } 2554 return newPrioritizedListSlots; 2555} 2556function updatePrioritizedListSlotNumber(prioritizedList, newNumberOfSlots) { 2557 const currentNumberOfSlots = prioritizedList.slots.length; 2558 if (newNumberOfSlots < currentNumberOfSlots) { 2559 prioritizedList.slots = prioritizedList.slots.slice(0, newNumberOfSlots); 2560 return prioritizedList; 2561 } else if (newNumberOfSlots > currentNumberOfSlots) { 2562 const slotsToAdd = newNumberOfSlots - currentNumberOfSlots; 2563 for (let i = 0; i < slotsToAdd; i++) prioritizedList.slots = addSlot(prioritizedList.slots, 5, CANVAS_DIMENSIONS); 2564 return prioritizedList; 2565 } 2566 return prioritizedList; 2567} 2568function updatePrioritizedListWireFrames(prioritizedListData, { newPrioritizedListName, newNumberOfSlots, newId }) { 2569 let newPrioritizedListData = deepCloneObj(prioritizedListData); 2570 newPrioritizedListData.name = newPrioritizedListName ? newPrioritizedListName : newPrioritizedListData.name; 2571 newPrioritizedListData.id = newId || newPrioritizedListData.id;
2572 if (typeof newNumberOfSlots === "number") newPrioritizedListData = updatePrioritizedListSlotNumber(newPrioritizedListData, newNumberOfSlots); 2573 return newPrioritizedListData; 2574} 2575function checkIfPrioritizedListSlotIsGroup(slotObj) { 2576 return slotObj.placeholders ? true : false; 2577} 2578function isUniquePlaceholderInSlot(pListSlot, uniquePlaceholderName) { 2579 let numOfPlaceholders = 0; 2580 pListSlot.placeholders.forEach((ph) => { 2581 if (ph.name === uniquePlaceholderName) numOfPlaceholders++; 2582 }); 2583 return numOfPlaceholders === 1; 2584} 2585/*** 2586* Deletes a placeholder from prioritized list slot 2587* @param scene - scene object as presented on wireframes 2588* @param pListlogic - prioritized list logic as presented on wireframes 2589* @param prioritizedListId - the prioritized list id that we delete the placeholder from 2590* @param slotIndex - the prioritized list slot index that we delete the placeholder from 2591* @param phNameToDelete - placeholder name to delete 2592* @param phIndexToDelete - placeholder index to delete 2593* @param isUnique - whether it's the last instance of the placeholder in slot 2594* @param setSecenePart - scene part modification function 2595* @param setInputLogic - logic modification function 2596*/ 2597function deletePlaceholderFromPrioritizedList(scene, pListLogic, prioritizedListId, slotIndex, phNameToDelete, phIndexToDelete, isUnique, setScenePart, setInputLogic) { 2598 scene.sceneParts.forEach((modifiedScenePart, scenePartIndex) => { 2599 if (modifiedScenePart[entityType.prioritizedLists]) { 2600 modifiedScenePart[entityType.prioritizedLists].forEach((pList) => { 2601 if (pList.id === prioritizedListId) if (isUnique) { 2602 pList.slots.forEach((slot) => { 2603 slot.placeholders = slot.placeholders.filter((ph) => ph.name !== phNameToDelete); 2604 });
2605 pListLogic.rules.forEach((rule) => { 2606 rule.value = rule.value.filter((ph) => ph.id !== phNameToDelete); 2607 }); 2608 } else pList.slots[slotIndex].placeholders.splice(phIndexToDelete, 1); 2609 }); 2610 setScenePart(scene.id, scenePartIndex, modifiedScenePart, false); 2611 } 2612 }); 2613 if (isUnique) setInputLogic(scene.id, prioritizedListId, pListLogic); 2614} 2615/** 2616* Finds the rule key from candidate name 2617* @param candidateName - candidate name (with quotes) 2618* @param prioritizedListId - prioritized list Id. can also be slot id (plid suffix ---slotXYZ) 2619* @param prioritizedListLogic - list of prioritized list logic. 2620* @return string - rule key (with quotes) 2621*/ 2622function resolveCandidateKeyFromName(candidateName, prioritizedListId, prioritizedListLogic) { 2623 const rhsWithoutQuotes = candidateName.substring(1, candidateName.length - 1); 2624 const id = prioritizedListId.includes("---slot") ? prioritizedListId.substr(0, prioritizedListId.indexOf("---slot")) : prioritizedListId; 2625 const PrioritizedListLogic = (prioritizedListLogic || []).find((item) => item.id === id); 2626 if (!PrioritizedListLogic) return candidateName; 2627 const candidate = PrioritizedListLogic.rules.find((rule) => rule.name === rhsWithoutQuotes); 2628 if (candidate && candidate.key) return `'${candidate.key}'`; 2629 return candidateName; 2630} 2631/** 2632* get list of candidate names 2633* @param prioritizedList logic object 2634* @return list of objects - rule (candidate) names as 'dn' (display name) and keys as 'id' 2635*/ 2636function listCandidateNames(prioritizedList) { 2637 return prioritizedList.rules.map((rule) => ({ 2638 dn: rule.name || "", 2639 id: rule.key 2640 })); 2641} 2642function addPlaceHolderToSlots(scene, listId, placeholder) { 2643 scene.sceneParts.forEach((scenePart) => { 2644 if (scenePart.prioritizedLists) scenePart.prioritizedLists.forEach((pList) => { 2645 if (pList.id === listId) { 2646 if (pList.slots) pList.slots.forEach((slot) => { 2647 let clonePlaceholder = deepCloneObj(placeholder); 2648 if (checkIfPrioritizedListSlotIsGroup(slot)) { 2649 clonePlaceholder.height = slot.placeholders[0].height; 2650 clonePlaceholder.y = slot.placeholders[0].y; 2651 slot.placeholders.push(clonePlaceholder); 2652 } else { 2653 clonePlaceholder.height = slot.height; 2654 clonePlaceholder.y = slot.y; 2655 slot.placeholders = []; 2656 const existingPH = deepCloneObj(slot); 2657 slot.placeholders.push(existingPH, clonePlaceholder); 2658 } 2659 }); 2660 } 2661 }); 2662 }); 2663} 2664function addNewPlaceholderLogicToList(scene, listId, placeholder, placeholderType, logicObject) { 2665 let listLogicClone = deepCloneObj(StateReaderUtils.getInputLogicFromStateProjectLogic(logicObject, scene.id, listId));
2666 listLogicClone.rules.forEach((rule) => { 2667 rule.value.push(createEmptyCompoundValue([{ 2668 name: placeholder.name, 2669 type: placeholderType 2670 }])[0]); 2671 }); 2672 return listLogicClone; 2673} 2674function renamePlaceholderInList(prioritizedList, oldName, newName) { 2675 if (prioritizedList.slots) prioritizedList.slots.forEach((slot) => { 2676 if (checkIfPrioritizedListSlotIsGroup(slot)) slot.placeholders.forEach((ph) => { 2677 if (ph.name === oldName) ph.name = newName; 2678 }); 2679 else if (slot.name === oldName) slot.name = newName; 2680 }); 2681} 2682function renamePlaceholderInListLogic(listLogic, oldName, newName) { 2683 return { 2684 ...listLogic, 2685 rules: listLogic.rules.map((rule) => ({ 2686 ...rule, 2687 value: rule.value.map((ph) => { 2688 return ph.id === oldName || ph.displayName === oldName ? { 2689 ...ph, 2690 id: newName, 2691 displayName: newName 2692 } : ph; 2693 }) 2694 })) 2695 }; 2696} 2697var generateActionableData = (prioritizedList, slotIndex) => { 2698 const slotCharacter = mapNumToLetter(slotIndex); 2699 return { 2700 id: `${prioritizedList.id}---slot${slotCharacter}`, 2701 slotIdx: slotIndex, 2702 type: ActionableDataValueType.PrioritizedSlot 2703 }; 2704}; 2705var getPrioritizedListIdFromActionableDataId = (actionableDataId) => { 2706 return actionableDataId.split("---")[0]; 2707}; 2708//#endregion 2709//#region client/logic/builder/editorsContainerLogic/styleUtils.ts 2710var FULL_CHANNEL_INTENSITY = 255; 2711var MIN_CHANNEL_INTENSITY = 0; 2712var getRedFromColorInt = (colorInt) => colorInt >> 24 & 255; 2713var getGreenFromColorInt = (colorInt) => colorInt >> 16 & 255; 2714var getBlueFromColorInt = (colorInt) => colorInt >> 8 & 255; 2715var getAlphaFromColorInt = (colorInt) => colorInt & 255; 2716var hexToRgb = (hex) => { 2717 const colorInt = parseInt(hex.replace("#", "") + "FF", 16); 2718 return { 2719 r: getRedFromColorInt(colorInt), 2720 g: getGreenFromColorInt(colorInt), 2721 b: getBlueFromColorInt(colorInt) 2722 }; 2723}; 2724var hexToRgba = (hex) => { 2725 const colorInt = parseInt(hex.replace("#", ""), 16); 2726 return { 2727 r: getRedFromColorInt(colorInt), 2728 g: getGreenFromColorInt(colorInt), 2729 b: getBlueFromColorInt(colorInt), 2730 a: getAlphaFromColorInt(colorInt) 2731 }; 2732}; 2733var hexToColorChannels = (hex) => { 2734 if (hex.length == 9) return hexToRgba(hex); 2735 else return hexToRgb(hex); 2736}; 2737var colorChannelsToHex = (channels) => { 2738 const handleSingleChannel = (channel) => { 2739 return channel.toString(16).padStart(2, "0"); 2740 }; 2741 return `#${handleSingleChannel(channels.r)}${handleSingleChannel(channels.g)}${handleSingleChannel(channels.b)}${channels.a !== void 0 ? handleSingleChannel(channels.a) : ""}`; 2742}; 2743var averageAlpha = (colorA, colorB) => { 2744 if (colorA.a === void 0 && colorB.a === void 0) return; 2745 return Math.round((colorA.a !== void 0 ? colorA.a : FULL_CHANNEL_INTENSITY) + (colorB.a !== void 0 ? colorB.a : FULL_CHANNEL_INTENSITY) / 2); 2746}; 2747var averageRGBA = (colorA, colorB) => { 2748 return { 2749 r: Math.round((colorA.r + colorB.r) / 2), 2750 g: Math.round((colorA.g + colorB.g) / 2), 2751 b: Math.round((colorA.b + colorB.b) / 2), 2752 a: averageAlpha(colorA, colorB) 2753 }; 2754}; 2755var calcMiddleTint = (Tint1, Tint2) => { 2756 return colorChannelsToHex(averageRGBA(hexToColorChannels(Tint1), hexToColorChannels(Tint2))); 2757}; 2758var styleIsEmpty = (style) => !style || typeof style === "object" && !style.Tint1; 2759/** 2760* render linear gradient for use in inline CSS. 2761* @param style 2762* @returns a color or gradient 2763*/ 2764var inlineColor = (style) => { 2765 if (!style) return ""; 2766 if (!isValidColor(style)) return ""; 2767 if (typeof style === "string") return style; 2768 if (typeof style === "object" && style.IsOneTint) return `${style.Tint1}`; 2769 else { 2770 const middleTint = calcMiddleTint(style.Tint1, style.Tint2); 2771 return `linear-gradient(to right, ${style.Tint1}, ${middleTint} ${style.Ratio * 100}%, ${style.Tint2})`; 2772 } 2773}; 2774var isFullyTransparentColor = (hex) => { 2775 return hexToColorChannels(hex).a === MIN_CHANNEL_INTENSITY; 2776}; 2777var toggleTransparency = (color) => { 2778 const channels = hexToColorChannels(color); 2779 if (channels.a != void 0 && channels.a !== MIN_CHANNEL_INTENSITY && channels.a !== FULL_CHANNEL_INTENSITY) return color; 2780 channels.a = channels.a === MIN_CHANNEL_INTENSITY ? FULL_CHANNEL_INTENSITY : MIN_CHANNEL_INTENSITY; 2781 return colorChannelsToHex(channels); 2782}; 2783//#endregion 2784//#region client/logic/vlx/editorLogicUtils.ts 2785var import_traverse = /* @__PURE__ */ __toESM(require_traverse()); 2786var import_lodash = require_lodash(); 2787var VALIDATION_PROGRAM_SETTINGS_LABEL = "Program Settings"; 2788var VALIDATION_ANIMATED_WIREFRAMES_COMPATIBILITY_LABEL = "Animated Wireframes Compatibility";
2789var VALIDATION_SEVERITY_LABEL = "severity"; 2790function valueCanBeFromValueSet(value) { 2791 if (typeof value === "string") return true; 2792 else if (Array.isArray(value) && value.length === 1) return true; 2793 else if (!Array.isArray(value) && typeof value === "object") return true; 2794 return false; 2795} 2796function getMediaTypeByValue(value) { 2797 if (Array.isArray(value) || typeof value === "string") return LOGIC_MEDIA_TYPES.String; 2798 else if (typeof value === "object") return value.mediaType; 2799 else return; 2800} 2801var functions = import_dist$8.definitions ?? []; 2802function getAvailableFunctions() { 2803 return functions; 2804} 2805function getLhsMediaType(lhs, context) { 2806 if (!lhs) return null; 2807 if (lhs.actions?.length) return convertVlxParamTypeToLogicMediaType(lhs.actions[lhs.actions.length - 1].output); 2808 else return getElementInfoFromActionableData(lhs, context).mediaType || lhs.mediaType; 2809} 2810function getAvailableOperatorsForObject(lhsMediaType) { 2811 if (!functions || !functions.length) return null; 2812 let mediaType = convertLogicMediaTypToVlxParamType(lhsMediaType); 2813 let actions = functions.filter((func) => func.input.some((input) => input === mediaType) && func.tag.some((tag) => tag === VLX_FUNCTION_TAGS.Operator) && (!func.params || func.params.length < 2)); 2814 if (actions.length === 0) return []; 2815 let booleanOps = actions.filter((act) => act.output === VLX_PARAMTYPE.Boolean); 2816 let numericOps = actions.filter((act) => act.output === VLX_PARAMTYPE.Numeric); 2817 let stringOps = booleanOps.map((act) => act.text); 2818 stringOps = numericOps.reduce((opsArray, act) => { 2819 return opsArray.concat([ 2820 `${act.text} =`, 2821 `${act.text} >`, 2822 `${act.text} <` 2823 ]); 2824 }, []).concat(stringOps); 2825 if (mediaType === VLX_PARAMTYPE.Numeric) stringOps = stringOps.concat([ 2826 "smaller than", 2827 "greater than", 2828 "small or equal than", 2829 "great or equal than" 2830 ]); 2831 return stringOps; 2832} 2833function capitalizeFirstLetter(str) { 2834 return str.charAt(0).toUpperCase() + str.slice(1); 2835} 2836function filterDataElementsByMediaType(dataElements, inputType) { 2837 if (!dataElements) return dataElements; 2838 else if (!inputType || inputType === LOGIC_TYPE.Text) return dataElements.filter((de) => de.type !== "mappingTable"); 2839 else return dataElements.filter((de) => de.type === convertLogicTypeToDataElementType(inputType) || de.type === getCreativeDataElementType(inputType)); 2840} 2841function getCreativeDataElementType(logicType) { 2842 switch (logicType) { 2843 case LOGIC_TYPE.Image: return CreativeDataElementContentTypes.Image; 2844 case LOGIC_TYPE.Video: return CreativeDataElementContentTypes.Video; 2845 case LOGIC_TYPE.Audio: return CreativeDataElementContentTypes.Audio; 2846 case LOGIC_TYPE.Color: return CreativeDataElementContentTypes.Color; 2847 } 2848} 2849function convertLogicTypeToDataElementType(logicType) { 2850 switch (logicType) { 2851 case LOGIC_TYPE.Compound: 2852 case LOGIC_TYPE.Text: return LOGIC_MEDIA_TYPES.String; 2853 case LOGIC_TYPE.DataElementNumber: return LOGIC_MEDIA_TYPES.Number; 2854 case LOGIC_TYPE.DataElementDate: return LOGIC_MEDIA_TYPES.Date; 2855 case LOGIC_MEDIA_TYPES.Boolean: 2856 case LOGIC_TYPE.DataElementBoolean: return LOGIC_MEDIA_TYPES.Boolean; 2857 case LOGIC_TYPE.Audio: 2858 case LOGIC_TYPE.Image: 2859 case LOGIC_TYPE.Video: 2860 case LOGIC_MEDIA_TYPES.URL: return LOGIC_MEDIA_TYPES.URL; 2861 } 2862 return LOGIC_TYPE.Text; 2863} 2864function convertVlxParamTypeToLogicMediaType(type) { 2865 switch (type) { 2866 case VLX_PARAMTYPE.Boolean: return LogicMediaType.Boolean; 2867 case VLX_PARAMTYPE.Date: return LogicMediaType.Date; 2868 case VLX_PARAMTYPE.Numeric: return LogicMediaType.Number; 2869 case VLX_PARAMTYPE.String: 2870 default: return LogicMediaType.String; 2871 } 2872} 2873function convertLogicMediaTypToVlxParamType(type) { 2874 switch (type) { 2875 case LogicMediaType.Number: return VLX_PARAMTYPE.Numeric; 2876 case LogicMediaType.String: return VLX_PARAMTYPE.String; 2877 case LogicMediaType.Date: return VLX_PARAMTYPE.Date; 2878 case LogicMediaType.Boolean: return VLX_PARAMTYPE.Boolean; 2879 case LogicMediaType.Url: return VLX_PARAMTYPE.URL; 2880 case LogicMediaType.Color: return VLX_PARAMTYPE.Color; 2881 case LogicMediaType.List: return VLX_PARAMTYPE.List; 2882 case LogicMediaType.ListSlot: return VLX_PARAMTYPE.ListItem; 2883 } 2884} 2885function hasRhs(op) { 2886 return op && ![ 2887 "is empty", 2888 "is filled", 2889 "exists", 2890 "does not exist", 2891 "is true", 2892 "is false", 2893 "is false or empty", 2894 "then" 2895 ].some((unary) => unary.toUpperCase() === op.toUpperCase()); 2896} 2897function getRhsMediaType(operator, lhsMediaType) { 2898 if (!hasRhs(operator)) return null; 2899 let op = functions.find((op) => op.text === operator); 2900 if (!op) { 2901 if (operator.endsWith("in")) return LOGIC_MEDIA_TYPES.String; 2902 return LOGIC_MEDIA_TYPES.Number; 2903 } 2904 if (op.params && op.params.length > 0) if (op.params[0].type === VLX_PARAMTYPE.Any) return lhsMediaType || LogicMediaType.String; 2905 else return convertVlxParamTypeToLogicMediaType(op.params[0].type); 2906 return convertVlxParamTypeToLogicMediaType(op.output); 2907} 2908function getRhsValueSet(operator, lhs, dataElements) { 2909 if ((operator === "equals" || operator === "not equals") && lhs && (!lhs.actions || !lhs.actions.length)) return getValueSetForOperand(lhs, dataElements); 2910 return null; 2911} 2912/** 2913* Gets value set from operand if it is a data element. 2914* Value set of derived data element is retrieved from its logic, and value set from feed data element is saved as a field on it. 2915* @param operand operand object 2916* @param dataElements list of data elements 2917* @returns {Array} Value set of the data element if exists and if prop useValueSet is true, or null. 2918*/ 2919function getValueSetForOperand(operand, dataElements) { 2920 if (operand.type === LOGIC_DATA_TYPES.DataElement) { 2921 let dataElement = findDataElementByLogicValue(operand, dataElements); 2922 let values = dataElement && dataElement.getValueSet ? dataElement.getValueSet() : null; 2923 if (values) { 2924 let dataElementId = getDataElementId(dataElement); 2925 let mediaType = convertDataElementTypeToLogicMeidaType(dataElement.type); 2926 return values.filter((value) => value).map((value) => { 2927 return buildActionableData({ 2928 id: dataElementId, 2929 value: value.id, 2930 displayName: value.dn, 2931 dataType: LOGIC_DATA_TYPES.ValueSetValue, 2932 mediaType 2933 }); 2934 }); 2935 } 2936 return null; 2937 } 2938} 2939function cleanInputLogic(logicObject) { 2940 if (logicObject) { 2941 let modified = false;
2942 let cleanLogicObject = Object.assign({}, logicObject); 2943 if (cleanLogicObject.rules && cleanLogicObject.rules.length > 0) cleanLogicObject.rules.forEach((rule) => { 2944 if (rule.whens && rule.whens.length > 0) rule.whens.forEach((when) => { 2945 if (valueExists(when.lhs) && when.operator && valueExists(when.rhs)) if (!hasRhs(when.operator)) { 2946 when.rhs = void 0; 2947 modified = true; 2948 } else { 2949 let rhsMediaType = getRhsMediaType(when.operator, when.lhs?.mediaType); 2950 if (rhsMediaType === LOGIC_MEDIA_TYPES.Number && typeof when.rhs === "string") { 2951 let rhs = Number(when.rhs); 2952 if (!isNaN(rhs)) { 2953 when.rhs = buildActionableData(rhs, LogicMediaType.Number); 2954 modified = true; 2955 } 2956 } else if (rhsMediaType === LOGIC_MEDIA_TYPES.String && typeof when.rhs === "number") { 2957 when.rhs = buildActionableData(when.rhs.toString(), LogicMediaType.String); 2958 modified = true; 2959 } 2960 } 2961 }); 2962 }); 2963 if (cleanLogicObject.outputType === "parameter") { 2964 cleanLogicObject.outputType = LogicType.Text; 2965 modified = true; 2966 } 2967 return modified ? cleanLogicObject : logicObject; 2968 } 2969 return logicObject; 2970} 2971function getLogicValueFromValueSetValue(value, logicType) { 2972 switch (logicType) { 2973 case LOGIC_TYPE.Text: return [value]; 2974 case LOGIC_TYPE.DataElementNumber: return buildActionableData({ 2975 dataType: LOGIC_DATA_TYPES.Const, 2976 value: Number(value), 2977 mediaType: LOGIC_MEDIA_TYPES.Number 2978 }); 2979 case LOGIC_TYPE.DataElementBoolean: return buildActionableData({ 2980 dataType: LOGIC_DATA_TYPES.Const, 2981 value: value === "true", 2982 mediaType: LOGIC_MEDIA_TYPES.Boolean 2983 }); 2984 default: return value; 2985 } 2986} 2987function createLogic$1(outputType, defaultValue, defaultValueShow, isLast, rules) { 2988 return { 2989 rules: rules || [], 2990 defaultValue, 2991 defaultValueShow: defaultValueShow || true, 2992 outputType 2993 }; 2994} 2995function createLogicFromValueSet(valueSet, logicType) { 2996 let rulesArr = []; 2997 valueSet.forEach((value) => { 2998 rulesArr.push({ 2999 key: v4(), 3000 convertedKey: value.id, 3001 whens: [], 3002 value: getLogicValueFromValueSetValue(value.dn, logicType) 3003 }); 3004 }); 3005 return { 3006 rules: rulesArr, 3007 defaultValue: logicType === LOGIC_TYPE.DataElementBoolean ? false : null, 3008 defaultValueShow: logicType === LOGIC_TYPE.DataElementBoolean, 3009 outputType: logicType 3010 }; 3011} 3012function createLogicWithDerived(derived, outputType) { 3013 let mediaType = convertLogicTypeToDataElementType(outputType); 3014 let shouldDefaultValueBeAnArray = !(mediaType === LOGIC_MEDIA_TYPES.URL); 3015 let defaultValueValue = { 3016 id: derived.id, 3017 mediaType, 3018 type: LOGIC_DATA_TYPES.DataElement, 3019 actions: [] 3020 }; 3021 let logicObj = { 3022 rules: [], 3023 defaultValue: defaultValueValue, 3024 defaultValueShow: true, 3025 outputType 3026 }; 3027 if (shouldDefaultValueBeAnArray) logicObj.defaultValue = [defaultValueValue]; 3028 return logicObj; 3029} 3030function validationStatusToString(status) { 3031 switch (status) { 3032 case VALIDATION_STATUS.Invalid: return "invalid"; 3033 case VALIDATION_STATUS.Partial: return "partial"; 3034 case VALIDATION_STATUS.Valid: 3035 default: return "valid"; 3036 } 3037} 3038/*** 3039* Returns the name of a mapping table if a value is defined in a mapping table 3040* @param valueItem a valid logic's actionable data element 3041* @return the name of the mapping table 3042*/ 3043function getMappingTableNameFromValue(valueItem) { 3044 if (!valueItem || !valueItem.type || valueItem.type !== LOGIC_DATA_TYPES.MappingTable) return null; 3045 const value = getValueFromActionableData(valueItem); 3046 if (!value) return null; 3047 if (!value || !value.includes(".")) return value; 3048 return value.split(".")[0]; 3049} 3050function getMappingTablePropertyFromValue(valueItem) { 3051 if (!valueItem || !valueItem.type || valueItem.type !== LOGIC_DATA_TYPES.MappingTable) return null; 3052 else if (valueItem.id && valueItem.id.includes(".") && valueItem.id.split(".").length > 1) return valueItem.id.split(".")[1]; 3053 else if (valueItem.name && valueItem.name.includes(".") && valueItem.name.split(".").length > 1) return valueItem.name.split(".")[1]; 3054 else return null; 3055} 3056/** 3057* Returns a list of data element ids which are used as inputs to a given mapping table 3058*/ 3059function getDataElementIdsFromMappingTable(mappingTable) { 3060 let dataElementIds = []; 3061 if (mappingTable && mappingTable.mappingTableScheme) { 3062 let inputs = mappingTable.mappingTableScheme.inputs;
3063 if (inputs) inputs.forEach((input) => { 3064 let dataElementId = input.id || input.name; 3065 dataElementIds.push(dataElementId); 3066 }); 3067 } 3068 return dataElementIds; 3069} 3070/** 3071* This function will return an array from a validation object (containing a report) 3072* about the given object 3073* @param validationObject { 3074* status: <VALIDATION_STATUS>, 3075* message: <VALIDATION_MESSAGE>, 3076* report: <NESTED_REPORT_ARRAY>, 3077* item: <WHICH ITEM THE REPORT IS ABOUT> 3078* } 3079*/ 3080function getValidationReportOnObject(validationObject, item) { 3081 if (!validationObject || !validationObject.report) return validationObject; 3082 return validationObject.report.filter((vObj) => vObj && (vObj.item === item || !vObj.item && !item || !vObj.item && Array.isArray(item) && item.length === 0 || vObj.item && vObj.item.length === 0 && item && item.length === 0)).reduce((acc, item) => acc.concat(item.report ? item.report : item), []); 3083} 3084function convertDataElementTypeToLogicMeidaType(deType) { 3085 switch (deType) { 3086 case DataElementContentTypes.Number: return LOGIC_MEDIA_TYPES.Number; 3087 case DataElementContentTypes.Date: return LOGIC_MEDIA_TYPES.Date; 3088 case DataElementContentTypes.Boolean: return LOGIC_MEDIA_TYPES.Boolean; 3089 case CreativeDataElementContentTypes.Video: 3090 case CreativeDataElementContentTypes.Image: 3091 case CreativeDataElementContentTypes.Audio: 3092 case DataElementContentTypes.Url: return LOGIC_MEDIA_TYPES.URL; 3093 case CreativeDataElementContentTypes.Color: return LOGIC_TYPE.Color; 3094 case DataElementContentTypes.String: 3095 default: return LOGIC_MEDIA_TYPES.String; 3096 } 3097} 3098function convertDataTblOutputTypeToLogicMediaType(outputType) { 3099 switch (outputType) { 3100 case DATA_TABLE_OUTPUT_TYPES.Media: return LOGIC_MEDIA_TYPES.URL; 3101 case DATA_TABLE_OUTPUT_TYPES.Color: return LOGIC_TYPE.Color; 3102 case DATA_TABLE_OUTPUT_TYPES.Url: 3103 case DATA_TABLE_OUTPUT_TYPES.String: 3104 default: return LOGIC_MEDIA_TYPES.String; 3105 } 3106} 3107function convertAssetMediaTypeToLogicMediaType(assetMediaType) { 3108 switch (assetMediaType) { 3109 case CURATED_ASSETS_MEDIA_TYPES.Text: return LOGIC_MEDIA_TYPES.String; 3110 case CURATED_ASSETS_MEDIA_TYPES.Image: 3111 case CURATED_ASSETS_MEDIA_TYPES.Video: 3112 case CURATED_ASSETS_MEDIA_TYPES.Audio: return LOGIC_MEDIA_TYPES.URL; 3113 default: return assetMediaType; 3114 } 3115} 3116function getAssetTitleFromName(name, assets) { 3117 return getElementInfoFromActionableData(buildActionableData({ 3118 dataType: LOGIC_DATA_TYPES.Asset, 3119 value: name 3120 }), { assets }).displayName || name; 3121} 3122/** 3123* Gets an array of all the data element IDs within a logic, including those which are "hidden" within mapping tables. 3124* Note: Some of the returned Ids may be of DELETED data elements! This function doesn't check if they exist. 3125* Note #2: The returned IDs are the IDs as they appear in the LOGIC. In old projects, theses IDs may be the names of data elements. 3126* @param logic the logic object 3127* @param mappingTables a list of all the mapping tables 3128*/ 3129function extractDataElementIdsFromLogic(logic, mappingTables) { 3130 let set = (0, import_traverse.default)(logic).reduce((acc, node) => { 3131 if (node && node.type === LOGIC_DATA_TYPES.DataElement) { 3132 let dataElementId = getValueFromActionableData(node); 3133 acc.add(dataElementId); 3134 } else if (mappingTables && node && node.type === LOGIC_DATA_TYPES.MappingTable) { 3135 let mappingTableName = getMappingTableNameFromValue(node); 3136 getDataElementIdsFromMappingTable(mappingTables.find((mappingTable) => mappingTable.name === mappingTableName)).forEach((dataElementId) => acc.add(dataElementId)); 3137 } 3138 return acc; 3139 }, /* @__PURE__ */ new Set()); 3140 return Array.from(set); 3141} 3142/** 3143* This function extracts data field meta data (such as media type, refName, and displayName) 3144* from logic actionable data representing the element 3145* @param actionableDataObject - The actionable data object (representing DataElement / Asset / Mapping Table in the logic) 3146* @param dataFields: { assets: Array<Asset>, dataElements: Array<DataElement> } - An Object data fields of the project (dataElements, assets) 3147* @returns object: { 3148* displayName: string - representing the user displayed name of the field, 3149* refName: string - representing the id OR s3-reference-name of the field 3150* mediaType: <LogicMediaType> - representing the LOGIC_MEDIA_TYPE of the output element 3151* } 3152*/ 3153function getElementInfoFromActionableData(actionableDataObject, dataFields) { 3154 const error = { 3155 displayName: actionableDataObject.name, 3156 mediaType: actionableDataObject.mediaType 3157 }; 3158 switch (actionableDataObject.type) { 3159 case LOGIC_DATA_TYPES.DataElement: { 3160 const currentItem = findDataElementByLogicValue(actionableDataObject, dataFields.dataElements); 3161 if (!currentItem) return error; 3162 const displayName = getDataElementDisplayName(currentItem); 3163 const origin = getDataElementOrigin(currentItem); 3164 return { 3165 displayName, 3166 refName: displayName, 3167 mediaType: convertDataElementTypeToLogicMeidaType(currentItem.type), 3168 origin 3169 }; 3170 } 3171 case LOGIC_DATA_TYPES.ValueSetValue: { 3172 const currentItem = findDataElementById(actionableDataObject.id, dataFields.dataElements); 3173 if (currentItem) { 3174 let valueSet = currentItem.getValueSet(); 3175 let value = valueSet && valueSet.find((value) => value && value.id === actionableDataObject.name); 3176 if (value) return { 3177 displayName: value.dn, 3178 refName: value.dn, 3179 mediaType: currentItem.type 3180 }; 3181 } 3182 return { 3183 displayName: actionableDataObject.displayName, 3184 refName: actionableDataObject.displayName, 3185 mediaType: actionableDataObject.mediaType 3186 }; 3187 } 3188 case LOGIC_DATA_TYPES.MappingTable: { 3189 const dataTable = (dataFields.assets || []).find((asset) => asset.name === getMappingTableNameFromValue(actionableDataObject) && asset.type === AssetTypes.mappingTable && !asset.archived && !asset.deleted); 3190 if (!dataTable) return error; 3191 if (!getMappingTablePropertyFromValue(actionableDataObject)) return { 3192 displayName: dataTable.title, 3193 refName: dataTable.name 3194 }; 3195 const output = dataTable && Array.isArray(dataTable.mappingTableScheme.outputs) && dataTable.mappingTableScheme.outputs.find((output) => (output.id && actionableDataObject.id ? output.id : output.name) === getMappingTablePropertyFromValue(actionableDataObject)); 3196 if (!output) return error; 3197 return { 3198 displayName: `${dataTable.title} - ${output.name}`, 3199 refName: `${dataTable.name}.${output.id ? output.id : output.name}`, 3200 mediaType: convertDataTblOutputTypeToLogicMediaType(output.type) 3201 }; 3202 } 3203 case LOGIC_TYPE.Prioritized: { 3204 const prioritizedList = (dataFields.prioritizedLists || []).find((list) => list.id === actionableDataObject.id); 3205 return { 3206 displayName: prioritizedList?.name || "UNKNOWN LIST", 3207 refName: prioritizedList?.name, 3208 mediaType: actionableDataObject.mediaType 3209 }; 3210 } 3211 case LOGIC_TYPE.PrioritizedSlot: { 3212 const listActionableData = actionableDataObject; 3213 const listId = getPrioritizedListIdFromActionableDataId(listActionableData.id); 3214 const prioritizedList = (dataFields.prioritizedLists || []).find((list) => list.id === listId); 3215 return { 3216 displayName: `${prioritizedList?.name || "UNKNOWN LIST"} - ${mapNumToLetter(listActionableData.slotIdx)}`, 3217 refName: prioritizedList?.name, 3218 mediaType: listActionableData.type 3219 }; 3220 } 3221 case ActionableDataValueType.Variable: return { 3222 displayName: actionableDataObject.name, 3223 refName: actionableDataObject.path, 3224 mediaType: actionableDataObject.mediaType 3225 }; 3226 case LOGIC_DATA_TYPES.Asset: 3227 case LOGIC_DATA_TYPES.Animation: { 3228 const element = (dataFields.assets || []).find((asset) => asset.name === actionableDataObject.name && !asset.archived && !asset.deleted); 3229 if (!element) return error; 3230 return { 3231 displayName: element.title, 3232 refName: element.name, 3233 mediaType: convertAssetMediaTypeToLogicMediaType(element.mediaType) 3234 }; 3235 } 3236 case LOGIC_DATA_TYPES.Const: 3237 default: { 3238 const { mediaType, name } = actionableDataObject; 3239 return { 3240 displayName: name, 3241 refName: name, 3242 mediaType 3243 }; 3244 } 3245 } 3246} 3247/** 3248* Find the asset the actionable data is representing 3249* @param actionableDataObj - An <ActionableData> object 3250* @param assetsArr - An array of all system assets 3251*/ 3252function getAssetFromActionableData(actionableDataObj, assetsArr) { 3253 const assetName = getValueFromActionableData(actionableDataObj); 3254 if (!assetName) return null; 3255 return (assetsArr || []).find((asset) => asset.name === assetName); 3256} 3257function compareCompoundValues(v, u) { 3258 if (Array.isArray(u)) return -1; 3259 else if (Array.isArray(v)) return 1; 3260 else return v.displayName.localeCompare(u.displayName); 3261} 3262/*** 3263* returns true if testee has characteristics of compound value 3264* testee.show can be undefined so it isn't checked. 3265* @param testee - item to test if it's compound value 3266*/ 3267function isCompoundValue(testee) { 3268 return testee.id && testee.displayName && testee.value !== void 0 && testee.outputType; 3269} 3270/*** 3271* returns true if testee is array and has characteristics of compound value, recursively 3272* @param testee - item to test if it's array of compound values 3273*/ 3274function isArrayOfCompoundValues(testee) { 3275 return testee && Array.isArray(testee) && testee.length > 0 && testee.every((value) => isCompoundValue(value) || isArrayOfCompoundValues(value)); 3276} 3277/*** 3278* Creates empty compound value 3279* @param phArray - [{ "name": "placeHolderName--abc", "type": "text", "id": "phId" }, ...}] 3280* id is optional 3281* @returns emptyCompoundValue - array of compound values 3282* [{ "id": "xx", 3283"displayName": "placeHolderName--abc", 3284"outputType": "text", 3285"value": null 3286}] 3287*/ 3288function createEmptyCompoundValue(phArray) { 3289 return phArray.map((ph) => { 3290 if (ph.type === onscreenTypes.Hotspot) return { 3291 id: ph.id || ph.name, 3292 displayName: ph.name, 3293 value: createEmptyCompoundValue(createHotspotInputArray(HOTSPOT_TYPES.URL)), 3294 outputType: LOGIC_TYPE.Compound, 3295 show: true 3296 }; 3297 return { 3298 id: ph.id || ph.name, 3299 displayName: ph.name, 3300 outputType: ph.type, 3301 value: getDefaultValue(ph.id), 3302 show: true 3303 }; 3304 }); 3305} 3306function getDefaultValue(itemKey) { 3307 if (itemKey === "id") return v4(); 3308 if (itemKey === "type") return HOTSPOT_TYPES.URL; 3309 return null; 3310} 3311/***
3312* finds a value in a recursive compound value 3313* return a _ref_ to the value for future change 3314* @param compoundValue - the compound value 3315* @param phId - the id of the value we're looking for 3316* @returns value object who's id matches phId or undefined 3317*/ 3318function findInCompoundValue(compoundValue, phId) { 3319 let ref = void 0; 3320 (0, import_traverse.default)(compoundValue).forEach((value) => { 3321 if (value && value.id === phId) ref = value; 3322 }); 3323 return ref; 3324} 3325/*** 3326* Creates LogicData for group. 3327* If inheritLogicDataFromThis is supplied, the logic will populate rules and values in the logic object 3328* @param sceneLogic (required)- the scene's logic 3329* @param phArray (required) - [{ "name": "placeHolderName--abc", "type": "text"}, ...}] 3330* @param inheritLogicDataFromThis - string, name of placeholder. 3331* @returns LogicData - logic object 3332*/ 3333function createInitialCompoundLogic(sceneLogic, phArray, inheritLogicDataFromThis = "") { 3334 const emptyCompoundValue = createEmptyCompoundValue(phArray); 3335 let newRules = sceneLogic[inheritLogicDataFromThis] && sceneLogic[inheritLogicDataFromThis].rules ? deepCloneObj(sceneLogic[inheritLogicDataFromThis].rules) : []; 3336 newRules.forEach((rule) => { 3337 const valueToPreserve = deepCloneObj(rule.value); 3338 rule.value = deepCloneObj(emptyCompoundValue); 3339 if (inheritLogicDataFromThis && sceneLogic[inheritLogicDataFromThis]) { 3340 rule.key = v4(); 3341 rule.value.forEach((vl) => { 3342 if (vl.id === inheritLogicDataFromThis) { 3343 vl.value = valueToPreserve; 3344 vl.show = rule.show; 3345 } 3346 }); 3347 } 3348 }); 3349 let newDefaultValue = deepCloneObj(emptyCompoundValue); 3350 if (sceneLogic[inheritLogicDataFromThis] && sceneLogic[inheritLogicDataFromThis].defaultValue) { 3351 let defValueRef = newDefaultValue.find((val) => val.id === inheritLogicDataFromThis); 3352 defValueRef.value = deepCloneObj(sceneLogic[inheritLogicDataFromThis].defaultValue); 3353 } 3354 const newDefaultValueShow = sceneLogic[inheritLogicDataFromThis] && sceneLogic[inheritLogicDataFromThis].defaultValueShow ? sceneLogic[inheritLogicDataFromThis].defaultValueShow : true; 3355 return { 3356 outputType: LogicType.Compound, 3357 defaultValueShow: newDefaultValueShow, 3358 defaultValue: newDefaultValue, 3359 rules: newRules 3360 }; 3361} 3362/*** 3363* Add placeholder(s) to group logic. 3364* @param groupLogicData 3365* @param phArray - [{ "name": "placeHolderName--abc", "type": "text"}, ...}] 3366* @return updatedGroupLogicData 3367*/ 3368function addPlaceholdersToGroup(groupLogicData, phArray) { 3369 const emptyCompoundValue = createEmptyCompoundValue(phArray); 3370 let updatedGroupLogicData = deepCloneObj(groupLogicData); 3371 if (Array.isArray(updatedGroupLogicData.rules) && updatedGroupLogicData.rules.length >
3371 0) updatedGroupLogicData.rules.forEach((rule) => { 3372 rule.value = rule.value.concat(emptyCompoundValue); 3373 }); 3374 if (isArrayOfCompoundValues(updatedGroupLogicData.defaultValue)) updatedGroupLogicData.defaultValue = updatedGroupLogicData.defaultValue.concat(emptyCompoundValue); 3375 delete updatedGroupLogicData.validation; 3376 return updatedGroupLogicData; 3377} 3378/*** 3379* Search wireframes for entity by ID and entityType and extract the placeholders' name and type. 3380* useful when adding rules' value or defaultValue for groups, prioritized lists or hotspots. (see createEmptyCompoundValue) 3381* @param sceneWireFramesData - WireFramesData.scenes[sceneId] 3382* @param entityId - the relevant entityId or placeholder name 3383* @param typeOfEntity - one of entityType - placeholders, groups, prioritizedLists 3384* @return nameAndTypeArr - [{ "name": "placeHolderName--abc", "type": "text"}, ...}] 3385*/ 3386function extractPlaceholderNamesAndTypesFromWireframes(sceneWireFramesData, entityId, typeOfEntity) { 3387 let placeholdersNamesSet = /* @__PURE__ */ new Set([]); 3388 let nameAndTypeArr = []; 3389 sceneWireFramesData.sceneParts.forEach((scenePart) => { 3390 if (typeOfEntity === entityType.groups && scenePart.groups) { 3391 const group = scenePart.groups.find((grp) => grp.id === entityId); 3392 if (group) group.placeholders.forEach((ph) => { 3393 if (!placeholdersNamesSet.has(ph.name)) { 3394 placeholdersNamesSet.add(ph.name); 3395 nameAndTypeArr.push({ 3396 name: ph.name, 3397 type: ph.type 3398 }); 3399 } 3400 }); 3401 } else if (typeOfEntity === entityType.prioritizedLists && scenePart.prioritizedLists) { 3402 const pList = scenePart.prioritizedLists.find((list) => list.id === entityId); 3403 if (pList && pList.slots) pList.slots.forEach((slot) => { 3404 if (slot.placeholders) slot.placeholders.forEach((ph) => { 3405 if (!placeholdersNamesSet.has(ph.name)) { 3406 placeholdersNamesSet.add(ph.name); 3407 nameAndTypeArr.push({ 3408 name: ph.name, 3409 type: ph.type 3410 }); 3411 } 3412 }); 3413 else if (!placeholdersNamesSet.has(slot.name)) { 3414 placeholdersNamesSet.add(slot.name); 3415 nameAndTypeArr.push({ 3416 name: slot.name, 3417 type: slot.type 3418 }); 3419 } 3420 }); 3421 } else if (typeOfEntity === entityType.placeholders && scenePart.placeholders && scenePart.placeholders.find((ph) => ph.name === entityId && ph.type === onscreenTypes.Hotspot)) nameAndTypeArr = createHotspotInputArray(HOTSPOT_TYPES.URL); 3422 }); 3423 return nameAndTypeArr; 3424} 3425/*** 3426* Rename a placeholder in compound value 3427* @param compoundValue - array of compound value objects 3428* @param phId - Id of placeholder to replace 3429* @param newName - name of placeholder 3430* @return newCompoundValue - newCompoundValue duplicate with changes 3431*/ 3432function renamePlaceholderInCompoundValue(compoundValue, phId, newName) { 3433 let newCompoundValue = deepCloneObj(compoundValue); 3434 newCompoundValue.forEach((val) => { 3435 if (val.id === phId) { 3436 val.displayName = newName; 3437 val.id = newName; 3438 } 3439 }); 3440 return newCompoundValue; 3441} 3442/*** 3443* Rename placeholder in group logic (rules and defaultValue) 3444* @param groupLogicData - The groups' logicData 3445* @param phId - Id of placeholder to delete 3446* @param newName - name of placeholder 3447* @param renameAll - should we keep the old name and logic once too or rename all 3448* @param isDuplicated - whether the placeholder has more than a signle instance in scene part 3449* @return newGroupLogicData - logicData duplicate 3450*/ 3451function renamePlaceholderInGroup(groupLogicData, phId, newName, renameAll, isDuplicated) { 3452 let newGroupLogicData = deepCloneObj(groupLogicData); 3453 if (renameAll) newGroupLogicData.defaultValue = renamePlaceholderInCompoundValue(newGroupLogicData.defaultValue, phId, newName); 3454 else { 3455 const oldPlaceholderValue = newGroupLogicData.defaultValue.find((item) => item.id === phId); 3456 newGroupLogicData.defaultValue = renamePlaceholderInCompoundValue(newGroupLogicData.defaultValue, phId, newName); 3457 if (oldPlaceholderValue && isDuplicated) newGroupLogicData.defaultValue.push(oldPlaceholderValue); 3458 }
3459 newGroupLogicData.rules.forEach((rule) => { 3460 if (renameAll) rule.value = renamePlaceholderInCompoundValue(rule.value, phId, newName); 3461 else { 3462 const oldVal = deepCloneObj(rule.value.find((item) => item.id === phId)); 3463 rule.value = renamePlaceholderInCompoundValue(rule.value, phId, newName); 3464 oldVal && isDuplicated && rule.value.push(oldVal); 3465 } 3466 }); 3467 delete newGroupLogicData.validation; 3468 return newGroupLogicData; 3469} 3470/*** 3471* Delete placeholder from compoundValue 3472* @param compoundValue - array of compound value objects 3473* @param phId - Id of placeholder to delete 3474* @return newCompoundValue - newCompoundValue duplicate with changes 3475*/ 3476function removePlaceHolderFromCompoundValue(compoundValue, phId) { 3477 return deepCloneObj(compoundValue).filter((val) => val.id !== phId); 3478} 3479/*** 3480* Delete placeholder from group logic (rules and defaultValue) 3481* @param groupLogicData - The groups' logicData 3482* @param phId - Id of placeholder to delete 3483* @return newGroupLogicData - logicData duplicate 3484*/ 3485function removePlaceHolderFromGroup(groupLogicData, phId) { 3486 let newGroupLogicData = deepCloneObj(groupLogicData); 3487 newGroupLogicData.defaultValue = removePlaceHolderFromCompoundValue(newGroupLogicData.defaultValue, phId);
3488 newGroupLogicData.rules.forEach((rule) => { 3489 rule.value = removePlaceHolderFromCompoundValue(rule.value, phId); 3490 }); 3491 delete newGroupLogicData.validation; 3492 return newGroupLogicData; 3493} 3494/*** 3495* Generate placeholder logic data object from group logic 3496* Useful when breaking group to separate placeholders 3497* @param groupLogicData - The groups' logicData 3498* @param phId - Id of placeholder to delete 3499* @return placeholderLogicData - logicData object for single placeholder. has rules from group and relevant value 3500*/ 3501function generatePlaceholderLogicDataFromGroup(groupLogicData, phId) { 3502 if (!groupLogicData) return; 3503 let outputType; 3504 if (Array.isArray(groupLogicData.rules) && groupLogicData.rules.length > 0 && isArrayOfCompoundValues(groupLogicData.rules[0].value)) outputType = groupLogicData.rules[0].value.find((ph) => ph.id === phId).outputType; 3505 else if (isArrayOfCompoundValues(groupLogicData.defaultValue)) outputType = groupLogicData.defaultValue.find((ph) => ph.id === phId).outputType; 3506 else throw `Error: failed to find placeholder '${phId}' outputType in group`; 3507 const defaultValueShow = groupLogicData.defaultValueShow; 3508 const defaultValue = groupLogicData.defaultValue.find((ph) => ph.id === phId).value; 3509 let phRules = deepCloneObj(groupLogicData.rules); 3510 phRules.forEach((rule) => { 3511 rule.value = rule.value.find((ph) => ph.id === phId).value; 3512 rule.key = v4(); 3513 }); 3514 return { 3515 outputType, 3516 defaultValueShow, 3517 defaultValue, 3518 rules: phRules 3519 }; 3520} 3521/*** 3522* Find the validation for value. 3523* @param validation (required) - validation object, see validationShape in consts for shape 3524* @param value - the value who's report we're looking for 3525* @returns the last validation object who's item matches the value 3526*/ 3527function getValueValidationForCompoundValue(validation, value) { 3528 let allNonValidResults = []; 3529 (0, import_traverse.default)(validation).forEach(function(node) { 3530 if (node && node.item !== void 0 && node.message && node.status !== VALIDATION_STATUS.Valid) allNonValidResults.push(node); 3531 }); 3532 return allNonValidResults.filter((x) => x.item === value).pop(); 3533} 3534/*** 3535* Creates LogicData for Prioritized List. It is empty at the beginning. 3536* @param phArray (required) - [{ "name": "placeHolderName--abc", "type": "text"}, ...}] 3537* returns a logic object 3538*/ 3539function createInitialPrioritizedListLogic(phArray) { 3540 const firstRule = { 3541 value: deepCloneObj(createEmptyCompoundValue(phArray)), 3542 key: v4(), 3543 name: "", 3544 whens: [] 3545 }; 3546 return { 3547 outputType: LogicType.Prioritized, 3548 rules: [firstRule], 3549 defaultValue: null 3550 }; 3551} 3552function filterTransformTextPlaceholders(placeholderList) { 3553 return placeholderList.filter((ph) => ph.type === LOGIC_TYPE.Text || ph.source === placeholderType.parameter).map((ph) => { 3554 let out = { 3555 name: ph.name, 3556 type: LOGIC_DATA_TYPES.Variable, 3557 mediaType: LOGIC_MEDIA_TYPES.String, 3558 source: ph.source 3559 }; 3560 if (ph.groupId) out.groupId = ph.groupId; 3561 return out; 3562 }); 3563} 3564function isPlaceholderOfType(scene, name, type) { 3565 if (scene && Array.isArray(scene.sceneParts)) { 3566 for (let scenePart of scene.sceneParts) if (scenePart[placeholderType.onscreen]) { 3567 for (let ph of scenePart[placeholderType.onscreen]) if (ph.name === name && ph.type === type) return true; 3568 } 3569 } 3570 return false; 3571} 3572/** 3573* HOTSPOT START 3574*/ 3575function createHotspotInputArray(hotspotType) { 3576 let hotspotDisplayMapper = HOTSPOT_DISPLAY_MAPPERS[hotspotType]; 3577 return Object.keys(hotspotDisplayMapper).map((key) => ({ 3578 id: key, 3579 name: hotspotDisplayMapper[key], 3580 type: LOGIC_TYPE.Text 3581 })); 3582} 3583function createHotspotLogicObject(hotspotType) { 3584 return createInitialCompoundLogic({}, createHotspotInputArray(hotspotType)); 3585} 3586function isLogicValueHotspot(logicValue) { 3587 if (Array.isArray(logicValue) && logicValue.length) return Object.keys(HOTSPOT_DISPLAY_MAPPERS).some((hotspotType) => { 3588 const hotspotMap = HOTSPOT_DISPLAY_MAPPERS[hotspotType]; 3589 return logicValue.every((val) => { 3590 return !!hotspotMap[val.id]; 3591 }); 3592 }); 3593 return false; 3594} 3595function getHotspotDefaultLogicObj(inputName, defaultValue, defaultValueShow) { 3596 let compoundValue = createEmptyCompoundValue([{ 3597 name: inputName, 3598 type: onscreenTypes.Hotspot 3599 }])[0]; 3600 compoundValue.value = defaultValue; 3601 if (defaultValueShow !== void 0) compoundValue.show = defaultValueShow; 3602 return compoundValue; 3603} 3604index((logicItems) => { 3605 return logicItems.map((logicItem) =>
3605 findHotspotValuesInLogicItem(logicItem)).filter((valueArray) => !!valueArray).flat(); 3606}); 3607/*** 3608* Finds all hotspots values in logic object 3609* @param logicObjc 3610* @return array includes all Hotspot Values In Logic Object 3611*/ 3612var findHotspotValuesInLogicItem = index((logicObjc) => { 3613 return parseLogicObject(logicObjc).getValues().map((value) => findHotspotValuesInValue(value)).filter((valuesArray) => !!valuesArray).flat(); 3614}); 3615var findHotspotValuesInValue = (value) => { 3616 if (isLogicValueHotspot(value)) return [value]; 3617 return Array.isArray(value) && value.filter((v) => isLogicValueHotspot(v.value)).map((item) => item.value); 3618}; 3619function findHotspotValuesInRule(rule) { 3620 return rule && findHotspotValuesInValue(rule.value); 3621} 3622function excludeHotspotKeys(hotspot) { 3623 let modifiedHotspot = deepCloneObj(hotspot); 3624 EXCLUDED_HOTSPOT_KEYS.forEach((key) => { 3625 delete modifiedHotspot[key]; 3626 }); 3627 return modifiedHotspot; 3628} 3629/** 3630* HOTSPOT END 3631*/ 3632var getProgramValidationContent = (programValidations) => { 3633 let validations = {}; 3634 let issues = programValidations && programValidations.issues; 3635 issues && issues.forEach((issue) => { 3636 switch (issue.code) { 3637 case IssueCodes.PROGRAM_ANALYTICS_ERROR: 3638 validations["Analytics Settings"] = { 3639 errors: [], 3640 warnings: [] 3641 }; 3642 issue.children && issue.children.forEach((analytics) => { 3643 let analyticsName = analytics.name; 3644 analytics.issues && analytics.issues.forEach((analyticsIssue) => { 3645 if (analyticsIssue.code === IssueCodes.ANALYTICS_NAME_ERROR) validations["Analytics Settings"].errors.push(`Error - Missing field name in ${analyticsName}`); 3646 else if (analyticsIssue.severity === IssueSeverity.ERROR) validations["Analytics Settings"].errors.push(`Error in ${analyticsName} logic`); 3647 else validations["Analytics Settings"].warnings.push(`Warning in ${analyticsName} logic`); 3648 }); 3649 }); 3650 break; 3651 case IssueCodes.PROGRAM_SETTINGS_ERROR: 3652 validations["Program Settings"] = { 3653 errors: [], 3654 warnings: [] 3655 }; 3656 validations["Program Settings"].errors.push("Missing program SalesForce ID"); 3657 break; 3658 case IssueCodes.PROGRAM_STORY_ERROR: 3659 validations["Stories"] = { 3660 errors: [], 3661 warnings: [] 3662 }; 3663 issue.children && issue.children.forEach((story) => { 3664 let storyName = story.name; 3665 story.issues && story.issues.forEach((storyIssue) => { 3666 if (storyIssue.code === IssueCodes.STORY_LOGIC_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} logic`); 3667 else validations["Stories"].warnings.push(`Warning in ${storyName} logic`); 3668 if (storyIssue.code === IssueCodes.STORY_SOUNDTRACK_LOGIC_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} soundtrack logic`); 3669 else validations["Stories"].warnings.push(`Warning in ${storyName} soundtrack logic`); 3670 if (storyIssue.code === IssueCodes.STORY_BACKGROUND_ASSET_LOGIC_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} background asset logic`); 3671 else validations["Stories"].warnings.push(`Warning in ${storyName} background asset logic`); 3672 if (storyIssue.code === IssueCodes.STORY_VIDEO_RATIO_QUALITY_LOGIC_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} ratio and quality logic`); 3673 else validations["Stories"].warnings.push(`Warning in ${storyName} ratio and quality logic`); 3674 if (storyIssue.code === IssueCodes.STORY_VIDEO_DURATION_OPTIONS_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} duration options definition`); 3675 else validations["Stories"].warnings.push(`Warning in ${storyName} duration options definition`); 3676 if (storyIssue.code === IssueCodes.STORY_VIDEO_NUM_OF_PRODUCT_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} number of products definition`); 3677 else validations["Stories"].warnings.push(`Warning in ${storyName} number of products definition`); 3678 if (storyIssue.code === IssueCodes.STORY_VIDEO_RATIO_QUALITY_OPTIONS_ERROR) if (storyIssue.severity === IssueSeverity.ERROR) validations["Stories"].errors.push(`Error in ${storyName} ratio and quality options definition`); 3679 else validations["Stories"].warnings.push(`Warning in ${storyName} ratio and quality options definition`); 3680 }); 3681 }); 3682 if (validations["Stories"].errors.length === 0 && validations["Stories"].warnings.length === 0) delete val
3682idations["Stories"]; 3683 break; 3684 case IssueCodes.PROGRAM_SCENES_ERROR: 3685 issue.children && issue.children.forEach((scene) => { 3686 validations[scene.name] = getSceneValidationContent(scene.issues, scene.id); 3687 }); 3688 break; 3689 case IssueCodes.PROGRAM_STORY_SELECTION_LOGIC_ERROR: 3690 validations["Stories"] = validations["Stories"] || { 3691 errors: [], 3692 warnings: [] 3693 }; 3694 if (issue.severity === IssueSeverity.ERROR && issue.children) validations["Stories"].errors.push("Error in story selection logic"); 3695 else if (issue.severity === IssueSeverity.WARNING && issue.children) validations["Stories"].warnings.push("Warning in story selection logic"); 3696 else validations["Stories"].errors.push("Error - Missing story selection logic"); 3697 break; 3698 } 3699 }); 3700 if (Object.keys(validations).length > 0) validations[VALIDATION_SEVERITY_LABEL] = programValidations.severity; 3701 return validations; 3702}; 3703var getSceneValidationContent = (issues, sceneId) => { 3704 let errors = []; 3705 let warnings = []; 3706 let recordingErrors = 0; 3707 let recordingWarnings = 0; 3708 issues && issues.forEach((issue) => { 3709 if (issue.code === IssueCodes.SCENE_ANIMATION_LOGIC_ERROR) if (issue.severity === IssueSeverity.ERROR) errors.push("Error in scene animation logic"); 3710 else warnings.push("Warning in scene animation logic"); 3711 else if (issue.code === IssueCodes.SCENE_VALIDATION_LOGIC_ERROR) if (issue.severity === IssueSeverity.ERROR) errors.push("Error in scene validation logic"); 3712 else warnings.push("Warning in scene validation logic"); 3713 else if (issue.code === IssueCodes.SCENE_PART_ERROR) issue.children && issue.children.forEach((scenePart) => { 3714 let scenePartName = scenePart.name; 3715 scenePart.issues && scenePart.issues.forEach((scenePartIssue) => { 3716 scenePartIssue.children && scenePartIssue.children.forEach((entity) => { 3717 const isMaster = sceneId === LogicContainers.Master; 3718 if (entity.type === EntityTypes.RECORDING) if (entity.severity === IssueSeverity.ERROR) recordingErrors++; 3719 else recordingWarnings++; 3720 else if (entity.severity === IssueSeverity.ERROR) errors.push(`Error${isMaster ? "" : ` in ${scenePartName}`} with ${entity.type} ${entity.name} logic`); 3721 else warnings.push(`Warning ${isMaster ? "" : ` in ${scenePartName}`} with ${entity.type} ${entity.name} logic`); 3722 }); 3723 }); 3724 }); 3725 }); 3726 if (recordingWarnings > 0) warnings.unshift(`${recordingWarnings} narration recording file${recordingWarnings > 1 ? "s are" : " is"} missing`); 3727 if (recordingErrors > 0) errors.unshift(`${recordingErrors} narration recording file${recordingErrors > 1 ? "s are" : " is"} missing`); 3728 return { 3729 errors, 3730 warnings 3731 }; 3732}; 3733var stringIsHexColor = (str) => /^(#[0-9A-F]{6})$|(#[0-9A-F]{8})$/i.test(str); 3734var objectIsColor = (potentialColor) => potentialColor && typeof potentialColor === "object" && Object.keys(potentialColor).length === 4 && potentialColor.hasOwnProperty("IsOneTint") && potentialColor.hasOwnProperty("Tint1") && potentialColor.hasOwnProperty("Tint2") && potentialColor.hasOwnProperty("Ratio") && typeof potentialColor.IsOneTint === "boolean" && typeof potentialColor.Tint1 === "string" && stringIsHexColor(potentialColor.Tint1) && typeof potentialColor.Tint2 === "string" && stringIsHexColor(potentialColor.Tint2) && typeof potentialColor.Ratio === "number" && potentialColor.Ratio >= 0 && potentialColor.Ratio <= 1; 3735var isValidColor = (potentialColor) => typeof potentialColor === "string" && stringIsHexColor(potentialColor) || objectIsColor(potentialColor); 3736var isTransparentColor = (potentialColor) => typeof potentialColor === "string" && stringIsHexColor(potentialColor) && isFullyTransparentColor(potentialColor); 3737var getCreativeDataElementsUsedInNarrationsOverrides = (wireframes, dataElementIdsMap = {}, shallowUsage = false) => { 3738 if (!wireframes || !wireframes.narrations) return dataElementIdsMap; 3739 function addDataElement(deId, sceneId, narrationId, sceneName, narrationLetter) { 3740 dataElementIdsMap[deId] = dataElementIdsMap[deId] || []; 3741 if (shallowUsage) dataElementIdsMap[deId].push(sceneId); 3742 else dataElementIdsMap[deId].push({ 3743 sceneId, 3744 narrationId, 3745 sceneName, 3746 narrationLetter 3747 }); 3748 }
3749 Object.values(wireframes.scenes).forEach((scene) => { 3750 scene.sceneParts.forEach((scenePart) => { 3751 scenePart.NarrationParts && scenePart.NarrationParts.forEach((narrationPart) => { 3752 let dataElementsIdsInUse = StateReaderUtils.getNarrationTableCreativeOverride(wireframes, narrationPart.id) && StateReaderUtils.getNarrationTableOverrideIds(wireframes, narrationPart.id); 3753 if (dataElementsIdsInUse) { 3754 let narrationLetter = StateReaderUtils.getNarrationLetterInScene(scene, narrationPart.id); 3755 dataElementsIdsInUse.forEach((deId) => { 3756 addDataElement(deId, scene.id, narrationPart.id, scene.name, narrationLetter); 3757 }); 3758 } 3759 }); 3760 }); 3761 }); 3762 for (let deId in dataElementIdsMap) dataElementIdsMap[deId] = (0, import_lodash.uniqWith)(dataElementIdsMap[deId], import_lodash.isEqual); 3763 return dataElementIdsMap; 3764}; 3765var getNarrationPartInvalidCreativeOverrides = index((narrationCDEsUsage, narrationId) => { 3766 return Object.keys(narrationCDEsUsage).reduce((acc, deId) => { 3767 if (narrationCDEsUsage && narrationCDEsUsage[deId] && narrationCDEsUsage[deId].length > 1) narrationCDEsUsage[deId].map((usage) => usage.narrationId).includes(narrationId) && acc.push(deId); 3768 return acc; 3769 }, []); 3770}); 3771/** 3772* Normalizes a logic - deleting validation, and any itemData that was previously saved on the logic object. 3773* In addition, fixes all references to data elements by their names to ids 3774* @param logic 3775* @param dataElements 3776*/ 3777var normalizeLogic = (logic, dataElements) => { 3778 if (!logic) return logic; 3779 if (logic.validation) delete logic.validation; 3780 (0, import_traverse.default)(logic).forEach((node) => { 3781 if (node && node.type && node.itemData) delete node.itemData; 3782 if (node && node.type === ActionableDataValueType.DataElement) { 3783 if (!node.id) { 3784 let dataElement = dataElements.find((de) => de.id === node.name || de.name === node.name); 3785 if (dataElement) { 3786 node.id = dataElement.id; 3787 delete node.name; 3788 } 3789 } 3790 } 3791 }); 3792 return logic; 3793}; 3794function getAllActionableDataFromValue(value) { 3795 if (Array.isArray(value)) return value.filter((exp) => exp.type); 3796 else if (value?.type) return [value]; 3797 return []; 3798} 3799//#endregion 3800//#region client/logic/Logics/Logic.ts 3801function parseLogicObject(logic) { 3802 return createLogic(logic); 3803} 3804function createNewStorySelectionLogic() { 3805 return createLogic({ 3806 outputType: LogicType.Story, 3807 defaultValue: null, 3808 defaultValueShow: true, 3809 rules: [] 3810 }); 3811} 3812function createNewDecisionPointLogic() { 3813 return createLogic({ 3814 outputType: LogicType.NextScene, 3815 defaultValue: null, 3816 isLast: true, 3817 rules: [] 3818 }); 3819} 3820function createNewSoundtrackLogic() { 3821 return createLogic({ 3822 outputType: LogicType.Audio, 3823 defaultValue: null, 3824 defaultValueShow: false, 3825 rules: [] 3826 }); 3827} 3828function createNewBackgroundVideoLogic() { 3829 return createLogic({ 3830 outputType: LogicType.Video, 3831 defaultValue: null, 3832 defaultValueShow: false, 3833 rules: [] 3834 }); 3835} 3836function createNewBackgroundImageLogic() { 3837 return createLogic({ 3838 outputType: LogicType.Image, 3839 defaultValue: null, 3840 defaultValueShow: false, 3841 rules: [] 3842 }); 3843} 3844function createLogic(logicObj) { 3845 let outputType = logicObj.outputType; 3846 let defaultValue = logicObj.defaultValue; 3847 let defaultValueShow = logicObj.defaultValueShow; 3848 let last = logicObj.isLast; 3849 let rules = logicObj.rules || []; 3850 return { 3851 getOutputType: function() { 3852 return outputType; 3853 }, 3854 getDefaultValue: function() { 3855 return defaultValue; 3856 }, 3857 isDefaultValueShow: function() { 3858 return this.defaultValueShow; 3859 }, 3860 isLast: function() { 3861 return last; 3862 }, 3863 isRuleExists: function(ruleKey) { 3864 return rules.some((rule) => rule.key === ruleKey); 3865 }, 3866 getValueSet: (context) => { 3867 return getValueSet(logicObj, convertLogicTypeToDataElementType(outputType), context); 3868 }, 3869 getRules: function() { 3870 return rules; 3871 }, 3872 getRule: function(ruleKey) { 3873 return rules.find((rule) => rule.key === ruleKey); 3874 }, 3875 /** 3876 * Gets all logic values (including default value) 3877 * @return {any[]} array of values 3878 */ 3879 getValues: function() { 3880 let values = rules.map((rule) => rule.value); 3881 values.push(defaultValue); 3882 return values; 3883 }, 3884 /** 3885 * Gets all logic pairs of rule keys and values (including default value) 3886 * @return {any[]}
3886 array of object containing rule.key and value 3887 */ 3888 getAllKeysAndValues: function() { 3889 let keysAndValues = rules.map((rule) => { 3890 return { ...rule }; 3891 }); 3892 keysAndValues.push({ 3893 key: void 0, 3894 isLast: last, 3895 show: defaultValueShow, 3896 value: defaultValue, 3897 whens: [] 3898 }); 3899 return keysAndValues; 3900 }, 3901 setOutputType: function(outputTypeArg) { 3902 outputType = outputTypeArg; 3903 }, 3904 setDefaultValue: function(defaultValueArg) { 3905 defaultValue = defaultValueArg; 3906 }, 3907 setDefaultValueShow: function(defaultValueShowArg) { 3908 defaultValueShow = defaultValueShowArg; 3909 }, 3910 setLast: function(lastArg) { 3911 last = lastArg; 3912 }, 3913 setRules: function(rulesArg) { 3914 rules = rulesArg; 3915 }, 3916 addRuleWithValue: function(valueArg) { 3917 let newRules = [...rules]; 3918 newRules.push({ 3919 key: v4(), 3920 whens: [], 3921 value: valueArg 3922 }); 3923 rules = newRules; 3924 }, 3925 updateRule: function(ruleId, ruleData) {}, 3926 updateRuleValue: function(ruleKey, ruleNewValue) { 3927 let ruleIndex = rules.findIndex((rule) => { 3928 return rule.key === ruleKey; 3929 }); 3930 if (ruleIndex > -1) { 3931 let newRule = { ...rules[ruleIndex] }; 3932 newRule.value = ruleNewValue; 3933 let newRules = [...rules]; 3934 newRules.splice(ruleIndex, 1, newRule); 3935 rules = newRules; 3936 } 3937 }, 3938 removeRule: function(ruleKey) { 3939 let ruleIndex = rules.findIndex((rule) => { 3940 return rule.key === ruleKey; 3941 }); 3942 if (ruleIndex > -1) { 3943 let newRules = [...rules]; 3944 newRules.splice(ruleIndex, 1); 3945 rules = newRules; 3946 } 3947 }, 3948 serializeLogicData: function() { 3949 return { 3950 outputType, 3951 rules, 3952 defaultValueShow, 3953 defaultValue, 3954 isLast: last 3955 }; 3956 } 3957 }; 3958} 3959/** 3960* Gets the values from all the possible cases + default value 3961* @param {LogicJSON} logicObj a logic object 3962*/ 3963function getAllValues(logicObj) { 3964 let logic = parseLogicObject(logicObj); 3965 let values = logic.getRules().map((rule) => rule.value); 3966 values.push(logic.getDefaultValue()); 3967 return values; 3968} 3969function isLogicEmpty(logicObject, isOptionalDefaultValueFlag) { 3970 if (!logicObject) return true; 3971 const noDefaultValue = logicObject.defaultValue === void 0 || logicObject.defaultValue === null || Array.isArray(logicObject.defaultValue) && logicObject.defaultValue.length === 0; 3972 if (isOptionalDefaultValueFlag) return !logicObject.rules && noDefaultValue && logicObject.defaultValueShow || logicObject.rules && logicObject.rules.length === 0 && noDefaultValue && logicObject.defaultValueShow; 3973 return !logicObject.rules && noDefaultValue || logicObject.rules && logicObject.rules.length === 0 && noDefaultValue; 3974} 3975//#endregion 3976//#region common/Graph.ts 3977var import_toposort = /* @__PURE__ */ __toESM(require_toposort()); 3978var Graph = class Graph { 3979 constructor() { 3980 this.graph = /* @__PURE__ */ new Map(); 3981 } 3982 hasVertex(vertex) { 3983 return this.graph.has(vertex); 3984 } 3985 addVertex(vertex) { 3986 if (!this.graph.has(vertex)) this.graph.set(vertex, []); 3987 } 3988 removeVertex(vertex) { 3989 this.graph.delete(vertex); 3990 } 3991 addEdge(vertex1, vertex2) { 3992 if (!this.graph.get(vertex1).includes(vertex2)) this.graph.get(vertex1).push(vertex2); 3993 } 3994 detectCycles() { 3995 const graphNodes = Array.from(this.graph.keys()); 3996 const visited = {}; 3997 const recStack = {}; 3998 for (let i = 0; i < graphNodes.length; i++) { 3999 const node = graphNodes[i]; 4000 if (this.detectCycleUtil(node, visited, recStack)) { 4001 let cycleElements = []; 4002 Object.keys(recStack).forEach((rec) => { 4003 recStack[rec] && cycleElements.push(rec); 4004 }); 4005 return cycleElements; 4006 } 4007 } 4008 return []; 4009 } 4010 getReversedGraph() { 4011 let newGraph = new Graph(); 4012 const vertices = Array.from(this.graph.keys()); 4013 vertices.forEach((vertex) => newGraph.addVertex(vertex)); 4014 vertices.forEach((vertex) => { 4015 this.graph.get(vertex).forEach((neighbour) => { 4016 newGraph.addEdge(neighbour, vertex); 4017 }); 4018 }); 4019 return newGraph; 4020 } 4021 getLinkedVertices(vertex) { 4022 let linkedVertices = /* @__PURE__ */ new Set(); 4023 let queue = []; 4024 queue.push(vertex); 4025 while (queue.length > 0) { 4026 let currentNode = queue[0]; 4027 this.graph.get(currentNode).forEach((neighbour) => { 4028 if (!linkedVertices.has(neighbour)) { 4029 queue.push(neighbour); 4030 linkedVertices.add(neighbour); 4031 } 4032 }); 4033 queue.shift(); 4034 } 4035 return Array.from(linkedVertices); 4036 } 4037 detectCycleUtil(node, visited, recStack) { 4038 if (!visited[node]) { 4039 visited[node] = true; 4040 recStack[node] = true; 4041 const nodeNeighbors = this.graph.get(node); 4042 for (let i = 0; nodeNeighbors && i < nodeNeighbors.length; i++) { 4043 const currNode = nodeNeighbors[i]; 4044 if (!visited[currNode] && this.detectCycleUtil(currNode, visited, recStack)) return true; 4045 else if (recStack[currNode]) return true; 4046 } 4047 } 4048 recStack[node] = false;
4049 return false; 4050 } 4051 sortByDependencies() { 4052 const vertices = Array.from(this.graph.keys()); 4053 const edges = vertices.reduce((acc, vertex) => { 4054 this.graph.get(vertex).forEach((neighbour) => { 4055 acc.push([vertex, neighbour]); 4056 }); 4057 return acc; 4058 }, []); 4059 return import_toposort.default.array(vertices, edges).reverse(); 4060 } 4061}; 4062//#endregion 4063//#region common/arrayUtils.ts 4064function removeDuplicatesFromArrayByPropName(inputArr, prop) { 4065 return inputArr.filter((obj, pos, arr) => { 4066 return arr.map((mapObj) => mapObj[prop]).indexOf(obj[prop]) === pos; 4067 }); 4068} 4069/** 4070* Takes in an array and splits to two arrays using toFilter and optional ident function 4071* Returns an array of items that meet the filter criteria, and an array of the ones that don't. 4072* @param origArray 4073* @param toFilter 4074* @param ident 4075* @returns { 4076* filteredArray: array of the filtered items 4077* remainingArray: array of the remaining items (unfiltered) 4078* } 4079*/ 4080var getFilteredAndRemainingItems = (origArray, toFilter, ident = (x) => x) => { 4081 let remainingArray = []; 4082 return { 4083 remainingArray, 4084 filteredArray: origArray.filter((item) => { 4085 if (toFilter.includes(ident(item))) return true; 4086 else { 4087 remainingArray.push(item); 4088 return false; 4089 } 4090 }) 4091 }; 4092}; 4093function convertArrayOfObjectsToObject(arr, representativeField) { 4094 if (arr === void 0) return; 4095 return arr.reduce((acc, item) => { 4096 acc[item[representativeField]] = item; 4097 return acc; 4098 }, {}); 4099} 4100function convertArrayOfObjectsToObjectWithKeys(arr, representativeFields, keyGenerator) { 4101 if (arr === void 0) return; 4102 return arr.reduce((acc, item) => { 4103 const key = keyGenerator(...representativeFields.map((fieldName) => item[fieldName])); 4104 acc[key] = item; 4105 return acc; 4106 }, {}); 4107} 4108function convertArrayOfObjectsToObjectWithDuplicates(arr, representativeField) { 4109 return arr.reduce((acc, item) => { 4110 const val = item[representativeField]; 4111 if (typeof val === "string") { 4112 if (!acc[val]) acc[val] = []; 4113 acc[val].push(item); 4114 } 4115 return acc; 4116 }, {}); 4117} 4118/** 4119* Compare arrays (must have the exact same items in the exact same place) using <code>===</code> to compare items 4120* @param a array 1 4121* @param b array 2 4122*/ 4123var compareArrays = (a, b) => { 4124 if (a.length != b.length) return false; 4125 for (let i = 0; i < a.length; i++) if (a[i] != b[i]) return false; 4126 return true; 4127}; 4128//#endregion 4129//#region client/logic/DataElements/StudioDataManager.ts 4130var getDataElementIdsFromLogic = function(derivedLogic, shouldEnterGraph, mappingTables) { 4131 if (!derivedLogic) return []; 4132 return extractDataElementIdsFromLogic(derivedLogic, mappingTables).filter((deId) => shouldEnterGraph(deId)); 4133}; 4134var StudioDataManager = class { 4135 constructor(context) { 4136 this._graph = new Graph(); 4137 this._derivedLogic = context && context.derivedLogic || {}; 4138 this._mappingTables = context && context.mappingTables || []; 4139 this._dataElements = context && context.dataElements || []; 4140 this._dataElementsByName = convertArrayOfObjectsToObject(this._dataElements, "name"); 4141 } 4142 getLogic(idOrName) { 4143 let dataElement = findDataElementById(idOrName, this._dataElements); 4144 dataElement = dataElement || findDataElementByName(idOrName, this._dataElements); 4145 if (!dataElement) return null; 4146 let logicId = getDerivedDataElementLogicId(dataElement); 4147 return this._derivedLogic[logicId]; 4148 } 4149 buildDerivedGraphFromLogic(logic, includeNonDerived) { 4150 let _shouldEnterGraph = (dataElementIdFromLogic) => { 4151 if (includeNonDerived) return true; 4152 return !!this.getLogic(dataElementIdFromLogic); 4153 }; 4154 this._graph = new Graph(); 4155 let dataElementIDs = getDataElementIdsFromLogic(logic, _shouldEnterGraph, this._mappingTables); 4156 dataElementIDs.forEach((deId) => this._graph.addVertex(deId)); 4157 this._enhanceGraphFromVertices(dataElementIDs, _shouldEnterGraph); 4158 } 4159 buildDerivedGraph(dataElements) { 4160 let _shouldEnterGraph = (dataElementIdFromLogic) => { 4161 let dataElement = findDataElementById(dataElementIdFromLogic, dataElements); 4162 dataElement = dataElement || findDataElementByName(dataElementIdFromLogic, dataElements); 4163 return !!dataElement; 4164 }; 4165 this._graph = new Graph(); 4166 let vertices = [];
4167 dataElements.forEach((dataElement) => { 4168 let dataElementId = getDataElementId(dataElement); 4169 this._graph.addVertex(dataElementId); 4170 vertices.push(dataElementId); 4171 }); 4172 this._enhanceGraphFromVertices(vertices, _shouldEnterGraph); 4173 } 4174 _enhanceGraphFromVertices(vertices, shouldEnterGraph) { 4175 let newVertices = []; 4176 vertices.forEach((vertex) => { 4177 getDataElementIdsFromLogic(this.getLogic(vertex), shouldEnterGraph, this._mappingTables).forEach((dataElementIdOrName) => { 4178 let dataElementId = this._dataElementsByName[dataElementIdOrName] ? this._dataElementsByName[dataElementIdOrName].id : dataElementIdOrName; 4179 this._graph.addEdge(vertex, dataElementId); 4180 if (!this._graph.hasVertex(dataElementId)) { 4181 this._graph.addVertex(dataElementId); 4182 newVertices.push(dataElementId); 4183 } 4184 }); 4185 }); 4186 if (newVertices.length === 0) return; 4187 this._enhanceGraphFromVertices(newVertices, shouldEnterGraph); 4188 } 4189 detectCycles() { 4190 return this._graph.detectCycles(); 4191 } 4192 getDependentDerivedDataElementIds(dataElementId) { 4193 let deIDs = Array.isArray(dataElementId) ? dataElementId : [dataElementId]; 4194 let reversedGraph = this._graph.getReversedGraph(); 4195 return this._getDependentDerivedDataElementIds(deIDs, reversedGraph); 4196 } 4197 _getDependentDerivedDataElementIds(dataElementIds, graph) { 4198 let set = /* @__PURE__ */ new Set(); 4199 dataElementIds.forEach((id) => { 4200 graph.getLinkedVertices(id).forEach((v) => set.add(v)); 4201 }); 4202 return Array.from(set); 4203 } 4204 sortDerivedByDependencies() { 4205 return this._graph.sortByDependencies(); 4206 } 4207}; 4208//#endregion 4209//#region client/logic/Logics/ValueSetUtils.ts 4210var NULL_KEY = "~~~null_key~~~"; 4211var NULL_ID = "~~~null_id~~~"; 4212var generateValueId = () => { 4213 let chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; 4214 let result = ""; 4215 for (let i = 0; i < 8; ++i) { 4216 let idx = Math.floor(Math.random() * 62); 4217 result += chars.charAt(idx); 4218 } 4219 return result; 4220}; 4221function ruleValuePartIsConst(value) { 4222 return typeof value === "string" || typeof value === "object" && value.type === LOGIC_DATA_TYPES.Const; 4223} 4224function addValueToValueSet(value, type, valueSet) { 4225 let key = normalizeValueSetValueDisplayName(value.dn, type); 4226 if (!valueSet.has(key)) valueSet.set(key, value); 4227} 4228function concatValueSets(addedValueSet, mainValueSet) { 4229 addedValueSet.forEach((value, key) => { 4230 if (!mainValueSet.has(key)) mainValueSet.set(key, value); 4231 }); 4232 return mainValueSet; 4233} 4234function join$1(valueSet1, valueSet2) { 4235 let joined = /* @__PURE__ */ new Map(); 4236 valueSet1.forEach((value1, key1) => { 4237 valueSet2.forEach((value2, key2) => { 4238 if (value1 || value2) { 4239 let key = (key1 != NULL_KEY ? key1 : "") + (key2 != NULL_KEY ? key2 : ""); 4240 let displayName = (value1 ? value1.dn : "") + (value2 ? value2.dn : ""); 4241 let value1Id = value1 ? value1.id : NULL_ID; 4242 let value2Id = value2 ? value2.id : NULL_ID; 4243 let id = value1Id && value2Id ? value1Id + "^" + value2Id : value1Id + value2Id; 4244 joined.set(key, { 4245 dn: displayName, 4246 id 4247 }); 4248 } 4249 }); 4250 }); 4251 return joined; 4252} 4253function normalizeValueSetValueDisplayName(dn, type) { 4254 if (type === LOGIC_MEDIA_TYPES.Number && !isNaN(Number(dn))) return Number(dn).toString(); 4255 return dn.toLowerCase(); 4256} 4257function getDisplayNameForValuePart(ruleValue) { 4258 if (typeof ruleValue === "string") return ruleValue; 4259 else if (ruleValue.mediaType === LOGIC_MEDIA_TYPES.String) return ruleValue.name; 4260 else if (ruleValue.mediaType === LOGIC_MEDIA_TYPES.Number) return ruleValue.name.toString(); 4261 else if (ruleValue.mediaType === LOGIC_MEDIA_TYPES.Boolean) return ruleValue.name.toString(); 4262 else if (ruleValue.mediaType === LOGIC_MEDIA_TYPES.Date) return ruleValue.name.toString(); 4263} 4264function getIDForValuePart(ruleValue) { 4265 if (typeof ruleValue === "object" && ruleValue.mediaType === LOGIC_MEDIA_TYPES.Boolean) return ruleValue.name ? "true" : "false"; 4266 else return ""; 4267} 4268function getValueSetFromValuePart(valuePart, logicMediaType, context) { 4269 if (valuePart === void 0 || valuePart === null) return null; 4270 if (ruleValuePartIsConst(valuePart)) { 4271 let valueSetSizeOne = /* @__PURE__ */ new Map(); 4272 addValueToValueSet({ 4273 dn: getDisplayNameForValuePart(valuePart), 4274 id: getIDForValuePart(valuePart) 4275 }, logicMediaType, valueSetSizeOne); 4276 return valueSetSizeOne; 4277 } else if (typeof valuePart === "object" && valuePart.type === ActionableDataValueType.MappingTable) return null; 4278 else if (typeof valuePart === "object" && valuePart.type === ActionableDataValueType.Prioritized) return null; 4279 else if (typeof valuePart === "object" && valuePart.type === ActionableDataValueType.DataElement) { 4280 if (valuePart.actions && valuePart.actions.length > 0) return null; 4281 let dataElement = findDataElementByLogicValue(valuePart, context && context.dataElements); 4282 if (!dataElement) return null; 4283 let deValueSet = dataElement.getValueSet(); 4284 if (!deValueSet) return null; 4285 let deValueSetMap = /* @__PURE__ */ new Map(); 4286 deValueSet.forEach((value) => { 4287 if (value === null) deValueSetMap.set(NULL_KEY, null); 4288 else { 4289 getDataElementId(dataElement); 4290 addValueToValueSet({ ...value }, logicMediaType, deValueSetMap); 4291 } 4292 }); 4293 return deValueSetMap; 4294 } 4295} 4296function getValueSetFromArrayLogicRule(ruleValue, logicMediaType, context) { 4297 return ruleValue.reduce((accVS, valuePart, index) => { 4298 if (!accVS) return null; 4299 let valueSetOfValuePart = getValueSetFromValuePart(valuePart, logicMediaType, context); 4300 if (!valueSetOfValuePart) return null; 4301 else if (index === 0) return valueSetOfValuePart; 4302 else return join$1(accVS, valueSetOfValuePart); 4303 }
4303, /* @__PURE__ */ new Map()); 4304} 4305/** 4306* Gets a wrapped value from a rule, and returns weather or not the value is literal, and the value itself. 4307* A value is considered a literal if it an actionable data with type 'const', or a string. 4308* @param ruleValue The value that a rule returns. 4309* @param showValue boolean from the logic that determines weather or not the value is shown. 4310* @returns {object} An object with fields: isLiteral - weather or not the value is literal. value: the literal value. 4311*/ 4312function getValueSetFromLogicRule(ruleValue, showValue, logicMediaType, context) { 4313 let valueSetMap = /* @__PURE__ */ new Map(); 4314 if (showValue === false) valueSetMap.set(NULL_KEY, null); 4315 else if (ruleValue && Array.isArray(ruleValue)) valueSetMap = getValueSetFromArrayLogicRule(ruleValue, logicMediaType, context); 4316 else valueSetMap = getValueSetFromArrayLogicRule([ruleValue], logicMediaType, context); 4317 return valueSetMap; 4318} 4319function addRuleKeyPrefixToIDs(valueSet, keyPrefix) { 4320 valueSet.forEach((value) => { 4321 if (value) value.id = keyPrefix + (value.id ? "_" + value.id : ""); 4322 }); 4323} 4324/** 4325* Gets the value set from logic if it has a closed set, or null if it hasn't. 4326* A value set of logic is all the possible values it can return, and it is considered closed set if all of them are literals. 4327* We consider the character 'line-feed' as non-literal. 4328* @param logicObj a logic of a derived element 4329* @param type the type of the derived element 4330* @param context context includes derivedLogic, mappingTables, dataElements 4331* @param withConstructingIds determines weather to return for each value an array of the value ids that constructed that value. 4332* @returns {array} An array of all possible values that the logic can return, or null if it isn't a closed set. 4333*/ 4334function getValueSet(logicObj, type, context) { 4335 return memoizeGetValueSet(logicObj, type, false, context); 4336} 4337var memoizeGetValueSet = index((logicObj, type, withConstructingIds, context) => { 4338 let manager = new StudioDataManager(context); 4339 manager.buildDerivedGraphFromLogic(logicObj, false); 4340 if (manager.detectCycles().length > 0) return null; 4341 let valueSet = /* @__PURE__ */ new Map(); 4342 let rules = createLogic(logicObj).getAllKeysAndValues(); 4343 for (let i = 0; i < rules.length; ++i) { 4344 let ruleValueSet = getValueSetFromLogicRule(rules[i].value, rules[i].show, type, context); 4345 if (!ruleValueSet) return null; 4346 let prefix; 4347 if (rules[i].convertedKey) prefix = rules[i].convertedKey; 4348 else prefix = rules[i].key ? "_derived_rule_" + rules[i].key : "_derived_default"; 4349 addRuleKeyPrefixToIDs(ruleValueSet, prefix); 4350 concatValueSets(ruleValueSet, valueSet); 4351 } 4352 if (valueSet.has(NULL_KEY)) { 4353 valueSet.delete(NULL_KEY); 4354 valueSet.set(NULL_KEY, null); 4355 } 4356 let valuesArr = Array.from(valueSet.values()); 4357 if (!withConstructingIds) return valuesArr.map((value) => value && { 4358 dn: value.dn, 4359 id: value.id 4360 }); 4361 return Array.from(valueSet.values()); 4362}); 4363//#endregion 4364//#region client/logic/DataElements/DataElementsManager.ts 4365var CurrentCompatibilityVersion = CompatibilityVersions.IdSupport; 4366var DataElementTags = { PII: { 4367 tag: TagNames.PII, 4368 name: "Personal Identifiable Information", 4369 origins: [DataElementOrigins.Feed, DataElementOrigins.Derived], 4370 types: Object.values(DataElementContentTypes) 4371} }; 4372var dataElementObjectType = Symbol("_OBJECT_DATA_ELEMENT"); 4373var ASSIGN_TO_ALL_STORIES_LABEL = "All Stories"; 4374function buildDataElement(args) { 4375 const displayName = args.displayName || args.name || null; 4376 const id = args.id || null; 4377 let status = args.status || DataElementStatuses.Pending; 4378 if (args.origin && args.origin !== DataElementOrigins.Feed || adsDataElements.find((de) => de.displayName === displayName)) status = void 0; 4379 let dataElement = { 4380 id, 4381 name: args.name || null, 4382 displayName, 4383 compatibilityVersion: args.compatibilityVersion || CurrentCompatibilityVersion, 4384 type: args.type || DataElementContentTypes.String, 4385 description: args.description || null, 4386 origin: args.origin || DataElementOrigins.Feed, 4387 tags: [...args.tags || []], 4388 updatedTime: args.updatedTime || null, 4389 _objectType: dataElementObjectType 4390 }; 4391 if (args.graphQLId) dataElement.graphQLId = args.graphQLId; 4392 if (args.graphQLUpdated) dataElement.graphQLUpdated = args.graphQLUpdated; 4393 if (dataElement.origin === DataElementOrigins.Feed) return { 4394 ...dataElement, 4395 origin: DataElementOrigins.Feed, 4396 status, 4397 valueSet: args.valueSet ? Object.freeze(args.valueSet.map((val) => Object.freeze(val))) : null, 4398 useValueSet: args.useValueSet || false 4399 }; 4400 else if (dataElement.origin === DataElementOrigins.Derived) return { ...dataElement }; 4401 else if (args.origin === DataElementOrigins.Creative) return { 4402 ...dataElement, 4403 origin: DataElementOrigins.Creative, 4404 valueSet: args.valueSet ? Object.freeze(args.valueSet.map((val) => Object.freeze(val))) : null, 4405 useValueSet: args.useValueSet || false, 4406 assignedStories: args.assignedStories || [], 4407 assignedToAllStories: args.assignedToAllStories || false 4408 }; 4409 else if (args.origin === DataElementOrigins.System) return { 4410 ...dataElement, 4411 origin: DataElementOrigins.System, 4412 valueSet: args.valueSet ? Object.freeze(args.valueSet.map((val) => Object.freeze(val))) : null, 4413 useValueSet: args.useValueSet || false 4414 }; 4415} 4416/*** 4417* Finds a data Element by it's unique id 4418* @param dataElementId- the id by which to search for data elements 4419* @param dataElementsArray - Array<DataElement> - The list of all available data elements 4420*/ 4421function findDataElementById(dataElementId, dataElementsArray) { 4422 return (dataElementsArray || []).find((de) => { 4423 if (!de.compatibilityVersion || de.compatibilityVersion === CompatibilityVersions.DisplayName || de.compatibilityVersion < CompatibilityVersions.RowForDataElement) return de.name === dataElementId; 4424 return de.id === dataElementId; 4425 }); 4426} 4427/*** 4428* Finds a data Element by it's name attribute 4429* @param dataElementName - the name by which to search for data element 4430* @param dataElementsArray - Array<DataElement> - The list of all available data elements 4431*/
4432function findDataElementByName(dataElementName, dataElementsArray) { 4433 return (dataElementsArray || []).find((de) => de.name === dataElementName); 4434} 4435/** 4436* Update the name of an existing data element, returns a shallow copy of the provided data element 4437* with updated filed 4438* @param dataElement The data element to be updated 4439* @param id - The ID to be stored in the data element 4440* @return data element with new id 4441*/ 4442function changeID(dataElement, id) { 4443 return Object.freeze({ 4444 ...dataElement, 4445 id 4446 }); 4447} 4448/** 4449* Update the name of an existing data element, returns a shallow copy of the provided data element 4450* with updated filed 4451* @param dataElement The data element to be updated 4452* @param name - The new name to be stored in the data element 4453* @return {{name: string, id?: string, displayName: string, compatibilityVersion: CompatibilityVersion, contentType: DataElementContentTypes, description?: string, origin: DataElementOrigin}} 4454*/ 4455function changeName(dataElement, name) { 4456 return Object.freeze({ 4457 ...dataElement, 4458 displayName: name.trim() 4459 }); 4460} 4461/** 4462* Updates the description of an existing data element, returns a shallow copy of the provided data element 4463* @param dataElement - The data element to be updated 4464* @param desc - The new value of description to be stored in the data element 4465* @return {{name: string, id?: string, displayName: string, compatibilityVersion: CompatibilityVersion, contentType: DataElementContentTypes, description?: string, origin: DataElementOrigin}} 4466*/ 4467function changeDescription(dataElement, desc) { 4468 return Object.freeze({ 4469 ...dataElement, 4470 description: desc 4471 }); 4472} 4473/** 4474* Updates the type of an existing data element 4475* returns a copy of the data element with the change of the type 4476* @param dataElement - The data element to be updated 4477* @param newType - The new value of type to be updated for the data element 4478* @return DataElement 4479*/ 4480function changeContentType(dataElement, newType) { 4481 return Object.freeze({ 4482 ...dataElement, 4483 type: newType 4484 }); 4485} 4486/** 4487* Change the assigned to all stories indicator 4488* @param dataElement - The data element to be updated with the new assigned to all stories indicator 4489* @param assignedToAllStories - true/false - the new indicator 4490* @return {Readonly<{name: string, id?: string, displayName: string, compatibilityVersion: CompatibilityVersions, type: DataElementContentTypes, description?: string, origin: DataElementOrigins}>} 4491*/ 4492function changeAssignedToAllStories(dataElement, assignedToAllStories) { 4493 return Object.freeze({ 4494 ...dataElement, 4495 assignedToAllStories 4496 }); 4497} 4498/** 4499* Change the assigned stories ids array 4500* @param dataElement - The data element to be updated with the new assigned stories 4501* @param storiesIds - The new stories ids array 4502* @return {Readonly<{name: string, id?: string, displayName: string, compatibilityVersion: CompatibilityVersions, type: DataElementContentTypes, description?: string, origin: DataElementOrigins}>} 4503*/ 4504function changeAssignedStories(dataElement, storiesIds) { 4505 return Object.freeze({ 4506 ...dataElement, 4507 assignedStories: storiesIds 4508 }); 4509} 4510/*** 4511* Adds a story Id to the assigned stories array on a data element 4512* @param dataElement - The data element to assign to the story 4513* @param storyId - The story id to add 4514* @return {Readonly<{}>} 4515*/ 4516function addAssignedStory(dataElement, storyId) { 4517 if (dataElement.origin !== DataElementOrigins.Creative) throw `Cannot assign story to data element originating from "${dataElement.origin}"`; 4518 if ((dataElement.assignedStories || []).find((sId) => sId === storyId)) throw `Cannot assign story ${storyId} more than once`; 4519 return Object.freeze({ 4520 ...dataElement, 4521 assignedStories: [...dataElement.assignedStories || [], storyId] 4522 }); 4523} 4524/*** 4525* Removes a story Id from the assigned stories array on a data element 4526* @param dataElement - The data element to un-assign to the story 4527* @param storyId - The story id to remove 4528* @return {Readonly<{}>} 4529*/ 4530function removeAssignedStory(dataElement, storyId) { 4531 let assignedStories = dataElement.assignedStories; 4532 if ((assignedStories || []).find((sId) => sId === storyId)) { 4533 let index = assignedStories.indexOf(storyId); 4534 assignedStories.splice(index, 1); 4535 } else throw `Cannot find assign story ${storyId}`; 4536 return Object.freeze({ 4537 ...dataElement, 4538 assignedStories 4539 }); 4540} 4541/** 4542* Updates the status of an existing data element object, returns a new data element with the new status. 4543* @param dataElement - Existing data element to be updated 4544* @param newStatus - The new status to which update the data element 4545* @return {Readonly<{name: string, id?: string, displayName: string, compatibilityVersion: CompatibilityVersion, type: DataElementContentTypes, description?: string, origin: DataElementOrigin}>} 4546*/ 4547function changeStatus(dataElement, newStatus) { 4548 return Object.freeze({ 4549 ...dataElement, 4550 status: newStatus 4551 }); 4552} 4553/** 4554* Updates the string array of places an existing data element object is used in, returns a new data element with the new list of items as string. 4555* @param dataElement - Existing data element to be updates 4556* @param usedInString - Ths string containing the used scenes in which this data element is used 4557* @return {Readonly<{ 4558id?: string, 4559name: string, 4560type: DataElementContentType, 4561origin: DataElementOrigin, 4562displayName: string, 4563compatibilityVersion: CompatibilityVersion, 4564description?: string, 4565status?: DataElementStatus, 4566usedIn: string 4567} 4568*/ 4569function changeAndSetUsedInScene(dataElement, usedInString) { 4570 return Object.freeze({ 4571 ...dataElement, 4572 usedInScenes: usedInString 4573 }); 4574} 4575/** 4576* Updates a value set for data element 4577* @param dataElement - Existing data element to be updates 4578* @param valueSet - The new value set 4579* @return {Readonly<{ 4580* id?: string, 4581* name: string, 4582* type: DataElementContentType, 4583* origin: DataElementOrigin, 4584* displayName: string, 4585* compatibilityVersion: CompatibilityVersion, 4586* description?: string, 4587* status?: DataElementStatus, 4588* usedIn: string}> 4589* } 4590*/ 4591function changeValueSet(dataElement, valueSet) { 4592 Object.freeze(valueSet); 4593 return Object.freeze({ 4594 ...dataElement, 4595 valueSet 4596 }); 4597} 4598/** 4599* Updates an indicator of weather to use the value set of this data element, or ignore it 4600* @param dataElement - Existing data element to be updates 4601* @param useValueSet - an indicator of weather to use the value set or ignore it 4602* @return {Readonly<{ 4603* id?: string, 4604* name: string, 4605* type: DataElementContentType, 4606* origin: DataElementOrigin, 4607* displayName: string, 4608* compatibilityVersion: CompatibilityVersion, 4609* description?: string, 4610* status?: DataElementStatus, 4611* usedIn: string}> 4612* } 4613* 4614*/ 4615function changeUseValueSet(dataElement, useValueSet) { 4616 return Object.freeze({ 4617 ...dataElement, 4618 useValueSet 4619 }); 4620} 4621/** 4622* Updates a getter for value set. This getter should not be saved on the redux state! 4623* @param dataElement - Existing data element to be updates 4624* @param valueSetGetter - an indicator of weather to use the value set or ignore it 4625* @return {Readonly<{ 4626* id?: string, 4627* name: string, 4628* type: DataElementContentType, 4629* origin: DataElementOrigin, 4630* displayName: string, 4631* compatibilityVersion: CompatibilityVersion, 4632* description?: string, 4633* status?: DataElementStatus, 4634* usedIn: string}> 4635* } 4636*/ 4637function changeGetterForValueSet(dataElement, valueSetGetter) { 4638 return Object.freeze({ 4639 ...dataElement, 4640 getValueSet: valueSetGetter 4641 }); 4642} 4643/*** 4644* Returns the displayName of a data element 4645* @param dataElement 4646* @return {string} 4647*/ 4648function getDataElementDisplayName(dataElement) { 4649 if (!dataElement) return ""; 4650 return dataElement.displayName || ""; 4651} 4652/*** 4653* Returns the name of an origin 4654* @param origin an origin 4655* @param isFullDemoFlowBuilder - boolean 4656* @return {string} 4657*/ 4658function getOriginDisplayName(origin, isFullDemoFlowBuilder) { 4659 return getOriginDisplayNameAndIndefiniteArticle(origin, isFullDemoFlowBuilder).displayName; 4660} 4661/*** 4662* Returns the name and indefinite article of an origin 4663* @param origin an origin 4664* @param isFullDemoFlowBuilder - boolean 4665* @return {{ 4666* displayName: string,
4667* indefiniteArticle: string} 4668* } 4669*/ 4670function getOriginDisplayNameAndIndefiniteArticle(origin, isFullDemoFlowBuilder) { 4671 switch (origin) { 4672 case DataElementOrigins.Creative: return { 4673 displayName: "Content Set Data Element", 4674 indefiniteArticle: "a" 4675 }; 4676 case DataElementOrigins.Derived: return isFullDemoFlowBuilder ? { 4677 displayName: "Audience", 4678 indefiniteArticle: "an" 4679 } : { 4680 displayName: "Studio Data Element", 4681 indefiniteArticle: "a" 4682 }; 4683 case DataElementOrigins.Feed: 4684 case DataElementOrigins.System: 4685 default: return { 4686 displayName: "Data Element", 4687 indefiniteArticle: "a" 4688 }; 4689 } 4690} 4691/*** 4692* Returns the type of a data element 4693* @param dataElement 4694* @return {string} 4695*/ 4696function getDataElementType(dataElement) { 4697 if (!dataElement) return ""; 4698 return dataElement.type || ""; 4699} 4700/*** 4701* Returns the stories' ids which the data element is assigned to 4702* @param dataElement 4703* @return {string[]} 4704*/ 4705function getDataElementAssignedStories(dataElement) { 4706 if (!dataElement) return []; 4707 return dataElement.assignedStories || []; 4708} 4709/*** 4710* Returns whether the data element is assigned to all stories 4711* @param dataElement 4712* @return {boolean} 4713*/ 4714function getDataElementAssignedToAllStories(dataElement) { 4715 if (!dataElement) return false; 4716 return dataElement.assignedToAllStories || false; 4717} 4718/*** 4719* Returns whether the data element is assigned to a story ("all stories" included) 4720* @param dataElement 4721* @param storyId 4722* @return {boolean} 4723*/ 4724function isDataElementAssignedToStory(dataElement, storyId) { 4725 const assignedStories = getDataElementAssignedStories(dataElement); 4726 return getDataElementAssignedToAllStories(dataElement) || assignedStories.includes(storyId); 4727} 4728/*** 4729* Returns the origin of a data element 4730* @param dataElement 4731* @return {string} 4732*/ 4733function getDataElementOrigin(dataElement) { 4734 if (!dataElement) return ""; 4735 return dataElement.origin || ""; 4736} 4737/*** 4738* Returns the usedInScenes of a data element 4739* @param dataElement 4740* @return {string} 4741*/ 4742function getDataElementUsedInScene(dataElement) { 4743 if (!dataElement) return ""; 4744 return dataElement.usedInScenes || ""; 4745} 4746/*** 4747* Returns the description of a data element 4748* @param dataElement 4749* @return {string} 4750*/ 4751function getDataElementDescription(dataElement) { 4752 if (!dataElement) return ""; 4753 return dataElement.description || ""; 4754} 4755/*** 4756* Returns the status of a data element 4757* @param dataElement 4758* @return {string} 4759*/ 4760function getDataElementStatus(dataElement) { 4761 if (!dataElement) return ""; 4762 return dataElement.status || ""; 4763} 4764/*** 4765* Returns the updatedTime of a data element 4766* @param dataElement 4767* @return {string} 4768*/ 4769function getDataElementUpdatedTime(dataElement) { 4770 if (!dataElement) return 0; 4771 return dataElement.updatedTime || 0; 4772} 4773/** 4774* For backward compatibility this functions looks for the right data element 4775* based on the value stored in the logic, either by name or by id, 4776* depending on what is stored in the logic value 4777* @param logicValue - actionable data value, of type = DataElement 4778* @param dataElementsArray - Array<DataElement> - The list of all available data elements 4779* in the project 4780*/ 4781function findDataElementByLogicValue(logicValue, dataElementsArray) { 4782 if (typeof logicValue !== "object" || !logicValue.type || logicValue.type !== LOGIC_DATA_TYPES.DataElement) return null; 4783 if (logicValue.hasOwnProperty("id") && logicValue.id) return findDataElementById(logicValue.id, dataElementsArray); 4784 return findDataElementById(logicValue.name, dataElementsArray) || findDataElementByName(logicValue.name, dataElementsArray); 4785} 4786/*** 4787* Returns a unique identifier of the data element (based on it's computability version) 4788* @param dataElement 4789* @return {string} 4790*/ 4791function getDataElementId(dataElement) { 4792 if (!dataElement.compatibilityVersion || typeof dataElement.compatibilityVersion === "string" || dataElement.compatibilityVersion < CompatibilityVersions.RowForDataElement || !dataElement.id) return dataElement.name; 4793 return dataElement.id; 4794} 4795/** 4796* Returns the identifier of the logic object of associated with this derived data element 4797* covers all older versions of data elements, and starts using ids for v0.3+ 4798* @param dataElement - A derived data element object 4799* @return {string} The id of the logic obeject stored under /derived/{id} 4800*/ 4801function getDerivedDataElementLogicId(dataElement) { 4802 if (!dataElement.compatibilityVersion || typeof dataElement.compatibilityVersion === "string" || dataElement.compatibilityVersion < CompatibilityVersions.IdSupport || !dataElement.id) return dataElement.name; 4803 return dataElement.id; 4804} 4805/** 4806* Returns the derived data element for a derived data element key 4807* @param derivedKey - derived data element key 4808* @param dataElementsArray - Array<DataElement> - The list of all available data elements 4809*/ 4810function getDataElementFromDerivedKey(derivedKey, dataElementsArray) { 4811 if (dataElementsArray) return dataElementsArray.find((de) => getDerivedDataElementLogicId(de) === derivedKey); 4812} 4813/** 4814* Returns whether the data element type supported by valueSet 4815* @param dataElement - A data element object 4816* @return {boolean} whether the data element type supported by valueSet 4817*/ 4818function isValueSetSupportedForDataElementType(dataElement) { 4819 return dataElement.type === DataElementContentTypes.String || dataElement.type === DataElementContentTypes.Number || dataElement.type === DataElementContentTypes.Boolean; 4820} 4821/*** 4822* Check whether or not a tag can be applied to a data element based on it's origins and types 4823* @param dataElement - The data element to be checked for appliance 4824* @param tag - The tage to be checked 4825* @return {boolean} True if this tag is allowed to be added to this data element; false otherwise 4826*/ 4827function supportsTag(dataElement, tag) { 4828 if (!dataElement || !tag) return false;
4829 if (!(DataElementTags[tag].origins || []).some((o) => o === dataElement.origin)) return false; 4830 if (!(DataElementTags[tag].types || []).some((t) => t === dataElement.type)) return false; 4831 return true; 4832} 4833/*** 4834* Adds a tag to a data element 4835* @param dataElement - The data element on which the tag will be added 4836* @param tag - The tag to added on the 4837* @return {Readonly<{}>} 4838*/ 4839function addTag(dataElement, tag) { 4840 if (!(DataElementTags[tag].origins || []).some((o) => o === dataElement.origin)) throw `Cannot apply tag: ${tag}, 4841 on data element originating from "${dataElement.origin}"`; 4842 if (!(DataElementTags[tag].types || []).some((t) => t === dataElement.type)) throw `Cannot apply tag: ${tag}, 4843 on data element of type "${dataElement.type}"`; 4844 if ((dataElement.tags || []).findIndex((deTag) => deTag == tag) >= 0) throw `Cannot apply tag ${tag} more than once`; 4845 return Object.freeze({ 4846 ...dataElement, 4847 tags: [...dataElement.tags || [], tag] 4848 }); 4849} 4850/*** 4851* Returns a new data element without the tag to be removed 4852* @param dataElement - A data element object 4853* @param tag - The tag to be removed 4854* @return {*} a new data element without the tag, or the same data element if the tag does not exist 4855*/ 4856function removeTag(dataElement, tag) { 4857 let index = (dataElement.tags || []).findIndex((deTag) => deTag == tag); 4858 while (index >= 0) { 4859 if (index < 0) return dataElement; 4860 const tags = [...dataElement.tags.slice(0, index), ...dataElement.tags.slice(index + 1)]; 4861 dataElement = Object.freeze({ 4862 ...dataElement, 4863 tags 4864 }); 4865 index = (dataElement.tags || []).findIndex((deTag) => deTag == tag); 4866 } 4867 return dataElement; 4868} 4869/*** 4870* Returns true if the provided data element has a certain tag in the list of its tags 4871* @param dataElement - 4872* @param tag - On of the DataElementTagKeys 4873* @return {boolean} - True if the data elements was assigned with this tag, false otherwise 4874*/ 4875function hasTag(dataElement, tag) { 4876 return (dataElement.tags || []).findIndex((deTag) => deTag == tag) >= 0; 4877} 4878/** 4879* Returns an array with all tags (and their meta data) this data element 4880* @param dataElement 4881*/ 4882function getDataElementTags(dataElement) { 4883 if (!dataElement.tags || !dataElement.tags.length) return []; 4884 return dataElement.tags.map((tagKey) => DataElementTags[tagKey]); 4885} 4886/** 4887* Extracts the display name of the tag object 4888* @param dataElementTag - A tag meta object (@see: getDataElementTags) 4889* @return {*} A human readable text explaining the tag 4890*/ 4891function getDataElementTagDisplayName(dataElementTag) { 4892 return dataElementTag.name; 4893} 4894/** 4895* Extracts the key identifying this tag (EX: PII) 4896* @param dataElementTag - A tag meta object (@see: getDataElementTags) 4897* @return {*} A string used as the key to extract the tag meta object and the string stored in the tags array of the data element 4898*/ 4899function getDataElementTagKey(dataElementTag) { 4900 return dataElementTag.tag; 4901} 4902/*** 4903* Filter data elements by it's origin 4904* @param dataElementsArray - Array<DataElement> - The list of all available data elements 4905* @param originArray- Array<string> - The list of wanted origins 4906*/ 4907function filterDataElementsArrayByOrigin(dataElementsArray, originArray) { 4908 return (dataElementsArray || []).filter((de) => { 4909 return originArray.includes(getDataElementOrigin(de)); 4910 }); 4911} 4912/*** 4913* Filter data elements by it's type 4914* @param dataElementsArray - Array<DataElement> - The list of all available data elements 4915* @param typeArray- Array<string> - The list of wanted types 4916*/ 4917function filterDataElementsArrayByType(dataElementsArray, typeArray) { 4918 return (dataElementsArray || []).filter((de) => { 4919 return typeArray.includes(getDataElementType(de)); 4920 }); 4921} 4922function convertDataElementToStudioData(dataElement) { 4923 return buildDataElement({ 4924 origin: DataElementOrigins.Derived, 4925 id: dataElement.id, 4926 name: dataElement.name, 4927 displayName: dataElement.displayName, 4928 type: dataElement.type, 4929 description: dataElement.description, 4930 compatibilityVersion: dataElement.compatibilityVersion, 4931 updatedTime: dataElement.updatedTime, 4932 tags: dataElement.tags 4933 }); 4934} 4935/** 4936* Normalizes the data element from legacy structures to the newest structure. 4937* Currently only the value set is normalized 4938* @param dataElement a new data element with the newest structure 4939*/ 4940var normalizeDataElement = (dataElement) => { 4941 let normalizedDataElement = { ...dataElement }; 4942 if (dataElement.origin === DataElementOrigins.Feed) { 4943 if (dataElement.valueSet && dataElement.valueSet.length > 0 && typeof dataElement.valueSet[0] === "string") normalizedDataElement.valueSet = dataElement.valueSet.map((value) => ({ 4944 dn: value, 4945 id: generateValueId() 4946 })); 4947 } 4948 return normalizedDataElement; 4949}; 4950//#endregion 4951//#region client/logic/projects/projectWireframes/projectNarrations/NarrationsModelUtils.js 4952var import_immutable = /* @__PURE__ */ __toESM(require_immutable()); 4953var import_md5 = /* @__PURE__ */ __toESM(require_md5()); 4954var Structure = import_immutable.default.Record({ 4955 stack: void 0, 4956 representativeKey: void 0, 4957 creativeOverride: void 0 4958}); 4959var Layer = import_immutable.default.Record({ 4960 valueSetSource: void 0, 4961 valueSetId: void 0, 4962 name: "", 4963 type: void 0, 4964 valueSet: void 0, 4965 merges: void 0 4966}); 4967var Dimension = import_immutable.default.Record({ 4968 id: "", 4969 name: "", 4970 type: void 0, 4971 valueSet: void 0, 4972 indexMap: import_immutable.default.Map(),
4973 orphaned: false, 4974 removed: false, 4975 hasOrphanedValues: false 4976}); 4977var Variation = import_immutable.default.Record({ 4978 points: void 0, 4979 rp: void 0, 4980 orphaned: false, 4981 dataOrphaned: false, 4982 variationData: void 0 4983}); 4984var VariationData = import_immutable.default.Record({ 4985 text: "", 4986 comment: "", 4987 muted: false, 4988 overrideId: "" 4989}); 4990var defaultStructure = () => { 4991 return new Structure({ 4992 stack: import_immutable.default.List(), 4993 representativeKey: generateKey(emptyPointSet()) 4994 }); 4995}; 4996var defaultVariationDataMap = () => { 4997 return import_immutable.default.Map(); 4998}; 4999var buildDimensions = (structure, valueSetProviders) => { 5000 return buildDimensionsFromStack(structure.stack, valueSetProviders); 5001}; 5002var buildVariations = (structure, variationDataMap, dimensions, valueSetProviders) => { 5003 return buildVariationsFromStack(structure.stack, variationDataMap, dimensions, valueSetProviders); 5004}; 5005var setRepresentativeKey = (representativeKey) => { 5006 return { structureUpdate: { representativeKey } }; 5007}; 5008var setText = (variationKey, variationDataMap, defaultVariationData, text) => { 5009 if (variationDataMap.has(variationKey)) return { variationDataUpdates: { [variationKey]: { text } } }; 5010 return { variationDataUpdates: { [variationKey]: { 5011 text, 5012 comment: defaultVariationData.comment, 5013 muted: defaultVariationData.muted, 5014 overrideId: defaultVariationData.overrideId 5015 } } }; 5016}; 5017var setComment = (variationKey, variationDataMap, defaultVariationData, comment) => { 5018 if (variationDataMap.has(variationKey)) return { variationDataUpdates: { [variationKey]: { comment } } }; 5019 return { variationDataUpdates: { [variationKey]: { 5020 text: defaultVariationData.text, 5021 comment, 5022 muted: defaultVariationData.muted, 5023 overrideId: defaultVariationData.overrideId 5024 } } }; 5025}; 5026var mute = (variationKey, variationDataMap, defaultVariationData) => { 5027 if (variationDataMap.has(variationKey)) return { variationDataUpdates: { [variationKey]: { muted: true } } }; 5028 return { variationDataUpdates: { [variationKey]: { 5029 text: defaultVariationData.text, 5030 comment: defaultVariationData.comment, 5031 muted: true, 5032 overrideId: defaultVariationData.overrideId 5033 } } }; 5034}; 5035var unmute = (variationKey, variationDataMap, defaultVariationData) => { 5036 if (variationDataMap.has(variationKey)) return { variationDataUpdates: { [variationKey]: { muted: false } } }; 5037 return { variationDataUpdates: { [variationKey]: { 5038 text: defaultVariationData.text, 5039 comment: defaultVariationData.comment, 5040 muted: false, 5041 overrideId: defaultVariationData.overrideId 5042 } } }; 5043}; 5044var setOverrideId = (variationKey, variationDataMap, defaultVariationData, overrideId) => { 5045 if (variationDataMap.has(variationKey)) return { variationDataUpdates: { [variationKey]: { overrideId } } }; 5046 return { variationDataUpdates: { [variationKey]: { 5047 text: defaultVariationData.text, 5048 comment: defaultVariationData.comment, 5049 muted: defaultVariationData.muted, 5050 overrideId 5051 } } }; 5052}; 5053var addDimension = (structure, valueSetProviders, valueSetProvider) => { 5054 if (findDimensionIndex(structure.stack, valueSetProvider) >= 0) return {}; 5055 let valueSet = valueSetProvider.getValueSet(); 5056 let merges = import_immutable.default.OrderedSet(); 5057 let layer = structure.stack.last(); 5058 if (layer) merges = join(layer.merges, valueSet); 5059 let stack = structure.stack.push(new Layer({ 5060 valueSetSource: valueSetProvider.getSource(), 5061 valueSetId: valueSetProvider.getId(), 5062 name: valueSetProvider.getName(), 5063 type: valueSetProvider.getType(), 5064 valueSet, 5065 merges 5066 })); 5067 let representativePoints = getPointsForKey(structure.stack, valueSetProviders, structure.representativeKey); 5068 return { structureUpdate: { 5069 stack, 5070 representativeKey: generateKey(join(import_immutable.default.OrderedSet.of(representativePoints), valueSet).first()) 5071 } }; 5072}; 5073var removeDimension = (dimensions, index) => { 5074 let dimension = dimensions.get(index); 5075 return dimensions.set(index, new Dimension({ 5076 id: dimension.id, 5077 name: dimension.name, 5078 type: dimension.type, 5079 valueSet: dimension.valueSet, 5080 indexMap: dimension.indexMap, 5081 orphaned: dimension.orphaned, 5082 removed: true, 5083 hasOrphanedValues: dimension.hasOrphanedValues 5084 })); 5085}; 5086var setSupportCreativeOverride = (structure, variations, variationDataMap, supportCreativeOverride) => {
5087 if (structure.creativeOverride === supportCreativeOverride) return {}; 5088 let finalVariationDataUpdates = {}; 5089 if (!supportCreativeOverride) variations.forEach((variation, variationKey) => { 5090 if (variation && variation.variationData && variation.variationData.overrideId) { 5091 let { variationDataUpdates } = setOverrideId(variationKey, variationDataMap, variation.variationData, ""); 5092 if (variationDataUpdates) Object.assign(finalVariationDataUpdates, variationDataUpdates); 5093 } 5094 }); 5095 return { 5096 structureUpdate: { creativeOverride: supportCreativeOverride }, 5097 variationDataUpdates: finalVariationDataUpdates 5098 }; 5099}; 5100var merge = (structure, variations, variationKeySets) => { 5101 let layer = structure.stack.last(); 5102 let variationDataUpdates = {}; 5103 let updatedRepresentativeKey; 5104 let merges = layer.merges.withMutations((mutableMerges) => { 5105 variationKeySets.forEach((variationKeys) => { 5106 variationKeys.forEach((variationKey) => { 5107 let variation = variations.get(variationKey); 5108 if (mutableMerges.has(variation.points)) mutableMerges.delete(variation.points); 5109 }); 5110 }); 5111 variationKeySets.forEach((variationKeys) => { 5112 let mergedPoints = import_immutable.default.OrderedSet().withMutations((mutableMerge) => { 5113 variationKeys.forEach((variationKey) => { 5114 variations.get(variationKey).points.forEach((point) => mutableMerge.add(point)); 5115 }); 5116 }); 5117 mutableMerges.add(mergedPoints); 5118 let mergedKey = generateKey(mergedPoints); 5119 if (variationKeys.some((variationKey) => variationKey === structure.representativeKey)) updatedRepresentativeKey = mergedKey; 5120 let survivingVariationData = variations.get(variationKeys[0]).variationData; 5121 variationDataUpdates[mergedKey] = { 5122 text: survivingVariationData.text, 5123 comment: survivingVariationData.comment, 5124 muted: survivingVariationData.muted, 5125 overrideId: survivingVariationData.overrideId 5126 }; 5127 }); 5128 }); 5129 layer = new Layer({ 5130 valueSetSource: layer.valueSetSource, 5131 valueSetId: layer.valueSetId, 5132 name: layer.name, 5133 type: layer.type, 5134 valueSet: layer.valueSet, 5135 merges 5136 }); 5137 return { 5138 structureUpdate: { 5139 stack: structure.stack.set(structure.stack.size - 1, layer), 5140 representativeKey: updatedRepresentativeKey || structure.representativeKey 5141 }, 5142 variationDataUpdates 5143 }; 5144}; 5145var unmerge = (structure, variations, points) => { 5146 let layer = structure.stack.last(); 5147 let variationDataUpdates = {}; 5148 let updatedRepresentativeKey; 5149 let merges = import_immutable.default.OrderedSet().withMutations((mutableMerges) => { 5150 layer.merges.forEach((mergedPoints) => { 5151 let variationKey = generateKey(mergedPoints); 5152 let updatedMergedPoints = mergedPoints.subtract(points); 5153 if (updatedMergedPoints.size > 1) { 5154 if (updatedMergedPoints.size < mergedPoints.size) { 5155 let survivingVariationData = variations.get(variationKey).variationData; 5156 let updatedKey = generateKey(updatedMergedPoints); 5157 variationDataUpdates[updatedKey] = { 5158 text: survivingVariationData.text, 5159 comment: survivingVariationData.comment, 5160 muted: survivingVariationData.muted, 5161 overrideId: survivingVariationData.overrideId 5162 }; 5163 if (variationKey === structure.representativeKey) updatedRepresentativeKey = updatedKey; 5164 } 5165 mutableMerges.add(updatedMergedPoints); 5166 } else if (variationKey === structure.representativeKey) updatedRepresentativeKey = generateKey(import_immutable.default.OrderedSet.of(mergedPoints.first())); 5167 }); 5168 }); 5169 layer = new Layer({ 5170 valueSetSource: layer.valueSetSource, 5171 valueSetId: layer.valueSetId, 5172 name: layer.name, 5173 type: layer.type, 5174 valueSet: layer.valueSet, 5175 merges 5176 }); 5177 return { 5178 structureUpdate: { 5179 stack: structure.stack.set(structure.stack.size - 1, layer), 5180 representativeKey: updatedRepresentativeKey || structure.representativeKey 5181 }, 5182 variationDataUpdates 5183 }; 5184}; 5185var acceptOrphansAndRemoved = (structure, variationDataMap, dimensions, valueSetProviders) => { 5186 let orphanedOrRemovedDimFound = false; 5187 let stack = import_immutable.default.List().withMutations((mutableStack) => { 5188 let valueSets = import_immutable.default.List(); 5189 structure.stack.forEach((layer, index) => { 5190 let dimension = dimensions.get(index); 5191 if (!dimension.orphaned && !dimension.removed) { 5192 let valueSetProvider = valueSetProviders.find((valueSetProvider) => valueSetProvider.getSource() === layer.valueSetSource && valueSetProvider.getId() === layer.valueSetId); 5193 let name = valueSetProvider.getName(); 5194 let type = valueSetProvider.getType(); 5195 let valueSet = valueSetProvider.getValueSet(); 5196 valueSets = valueSets.push(valueSet); 5197 let merges = !orphanedOrRemovedDimFound ? updateSetOfPointsPerValueSet(layer.merges, valueSets) : import_immutable.default.OrderedSet(); 5198 mutableStack.push(new Layer({ 5199 valueSetSource: layer.valueSetSource, 5200 valueSetId: layer.valueSetId, 5201 name, 5202 type, 5203 valueSet, 5204 merges 5205 })); 5206 } else orphanedOrRemovedDimFound = true; 5207 }); 5208 }); 5209 let variationDataUpdates = {}; 5210 if (orphanedOrRemovedDimFound) { 5211 let variations = buildVariationsEx(structure.stack, import_immutable.default.Map(), dimensions, false); 5212 variationDataUpdates = variationDataMap.reduce((variationDataUpdates, value, key) => { 5213 return variations.has(key) ? Object.assign(variationDataUpdates, { [key]: null }) : variationDataUpdates; 5214 }, variationDataUpdates); 5215 } 5216 let representativePoints = getPointsForKey(structure.stack, valueSetProviders, structure.representativeKey); 5217 return { 5218 structureUpdate: { 5219 stack, 5220 representativeKey: generateVerifiedKey(stack, valueSetProviders, representativePoints && removeOrphanedAndRemovedDimensions(representativePoints, dimensions)) 5221 }, 5222 variationDataUpdates 5223 }; 5224}; 5225var isValueSetProviderUsed = (structure, valueSetSource, valueSetId) => { 5226 return isValueSetProviderUsedEx(structure, (usedValueSetSource, usedValueSetId) => usedValueSetSource === valueSetSource && usedValueSetId === valueSetId); 5227}; 5228var isValueSetProviderUsedEx = (structure, predicate, ...args) => { 5229 return structure.stack.some((layer) => predicate(layer.valueSetSource, layer.valueSetId, ...args)); 5230}; 5231var handleValueSetProviderChange = (structure, valueSetProviders) => { 5232 return { structureUpdate: { stack: structure.stack.withMutations((mutableStack) => {
5233 valueSetProviders.forEach((valueSetProvider) => { 5234 structure.stack.forEach((layer, index) => { 5235 if (layer.valueSetSource === valueSetProvider.getSource() && layer.valueSetId === valueSetProvider.getId()) { 5236 let name = valueSetProvider.getName(); 5237 let type = valueSetProvider.getType(); 5238 let valueSet = valueSetProvider.getValueSet(); 5239 layer.valueSet.forEach((value) => { 5240 if (!valueSetIncludes(valueSet, value.id)) valueSet = valueSet.push(value); 5241 }); 5242 mutableStack.set(index, new Layer({ 5243 valueSetSource: layer.valueSetSource, 5244 valueSetId: layer.valueSetId, 5245 name, 5246 type, 5247 valueSet, 5248 merges: layer.merges 5249 })); 5250 } 5251 }); 5252 }); 5253 }) } }; 5254}; 5255var generateKeyForExpandedPoint = (variationKey, point) => { 5256 return variationKey + "^" + JSON.stringify(point.toJSON()); 5257}; 5258var isExpandedPoint = (key) => { 5259 return key.includes("^"); 5260}; 5261var getExpandedPoint = (key) => { 5262 if (key.includes("^")) { 5263 let pieces = key.split("^"); 5264 return import_immutable.default.List(JSON.parse(pieces[1])); 5265 } 5266}; 5267var updateStructure = (structure, structureUpdate) => { 5268 return new Structure({ 5269 stack: structureUpdate.stack !== void 0 ? structureUpdate.stack : structure.stack, 5270 representativeKey: structureUpdate.representativeKey !== void 0 ? structureUpdate.representativeKey : structure.representativeKey, 5271 creativeOverride: structureUpdate.creativeOverride !== void 0 ? structureUpdate.creativeOverride : structure.creativeOverride 5272 }); 5273}; 5274var updateVariationDataMap = (variationDataMap, variationKey, variationDataUpdate) => { 5275 let variationData = null; 5276 if (variationDataUpdate) { 5277 let { text, comment, muted, overrideId } = variationDataUpdate; 5278 let existingVariationData = variationDataMap.get(variationKey); 5279 variationData = new VariationData({
5280 text: text !== void 0 ? text : existingVariationData ? existingVariationData.text : "", 5281 comment: comment !== void 0 ? comment : existingVariationData ? existingVariationData.comment : "", 5282 muted: muted !== void 0 ? muted : existingVariationData ? existingVariationData.muted : false, 5283 overrideId: overrideId !== void 0 ? overrideId : existingVariationData ? existingVariationData.overrideId : "" 5284 }); 5285 } 5286 return applyVariationDataToVariationDataMap(variationDataMap, variationKey, variationData); 5287}; 5288var applyVariationDataToVariations = (variations, variationKey, variationData) => { 5289 let variation = variations.get(variationKey); 5290 return variation ? variations.set(variationKey, new Variation({ 5291 points: variation.points, 5292 rp: variation.rp, 5293 orphaned: variation.orphaned, 5294 dataOrphaned: variation.dataOrphaned, 5295 variationData 5296 })) : variations; 5297}; 5298var applyVariationDataToVariationDataMap = (variationDataMap, variationKey, variationData) => { 5299 if (variationData) return variationDataMap.set(variationKey, variationData); 5300 else return variationDataMap.delete(variationKey); 5301}; 5302var valueSetToIndexMap = (valueSet) => { 5303 return import_immutable.default.Map().withMutations((mutableIndexMap) => { 5304 let index = 0; 5305 valueSet.forEach((value) => { 5306 mutableIndexMap.set(value.id, index++); 5307 }); 5308 }); 5309}; 5310var dbExtractDimensionDataFromStructure = (structure) => { 5311 return structure.stack.toArray().map((layer) => { 5312 return { 5313 valueSetSource: layer.valueSetSource, 5314 valueSetId: layer.valueSetId, 5315 name: layer.name, 5316 type: layer.type, 5317 valueSet: layer.valueSet.toArray() 5318 }; 5319 }); 5320}; 5321var dbExtractMergeDataFromStructure = (structure) => { 5322 let indexMaps = []; 5323 return structure.stack.toArray().map((layer) => { 5324 indexMaps.push(valueSetToIndexMap(layer.valueSet)); 5325 return { merges: layer.merges.toArray().map((points) => { 5326 return points.toArray().map((point) => { 5327 return pointToNumber(point, indexMaps); 5328 }); 5329 }) }; 5330 }); 5331}; 5332var dbExtractRepresentativeKeyFromStructure = (structure) => { 5333 return structure.representativeKey; 5334}; 5335var dbExtractCreativeOverrideFromStructure = (structure) => { 5336 return structure.creativeOverride; 5337}; 5338var dbBuildStructureFromDBData = (dbDimensionData, dbMergeData, dbRepresentativeKey, dbCreativeOverride) => { 5339 let valueSets = []; 5340 return new Structure({ 5341 stack: import_immutable.default.List().withMutations((mutableStack) => { 5342 dbDimensionData.forEach((dbDimensionLayer, index) => { 5343 valueSets.push(import_immutable.default.List(dbDimensionLayer.valueSet)); 5344 let dbMergeLayer = dbMergeData[index]; 5345 let valueSetSource = dbDimensionLayer.dataElementId ? "DataElements" : dbDimensionLayer.valueSetSource; 5346 let valueSetId = dbDimensionLayer.dataElementId ? dbDimensionLayer.dataElementId : dbDimensionLayer.valueSetId; 5347 let type = dbDimensionLayer.type ? dbDimensionLayer.type : DataElementContentTypes.String; 5348 let layer = new Layer({ 5349 valueSetSource, 5350 valueSetId, 5351 name: dbDimensionLayer.name, 5352 type, 5353 valueSet: import_immutable.default.List(dbDimensionLayer.valueSet), 5354 merges: import_immutable.default.OrderedSet(dbMergeLayer.merges.map((dbPoints) => import_immutable.default.OrderedSet(dbPoints.map((dbPoint) => { 5355 if (Array.isArray(dbPoint)) return import_immutable.default.List(dbPoint); 5356 return numberToPoint(dbPoint, valueSets); 5357 })))) 5358 }); 5359 mutableStack.push(layer); 5360 }); 5361 }), 5362 representativeKey: dbRepresentativeKey, 5363 creativeOverride: dbCreativeOverride 5364 }); 5365}; 5366var dbExtractVariationDataUpdates = (variationDataUpdates) => { 5367 let result = {}; 5368 Object.keys(variationDataUpdates).forEach((key) => { 5369 let variationDataUpdate = variationDataUpdates[key]; 5370 if (variationDataUpdate) { 5371 let update = {}; 5372 let textUpdate = variationDataUpdate.text; 5373 if (textUpdate !== void 0) update.text = textUpdate ? textUpdate : null; 5374 let commentUpdate = variationDataUpdate.comment; 5375 if (commentUpdate !== void 0) update.comment = commentUpdate ? commentUpdate : null; 5376 let mutedUpdate = variationDataUpdate.muted; 5377 if (mutedUpdate !== void 0) update.muted = !!mutedUpdate; 5378 let overrideIdUpdate = variationDataUpdate.overrideId; 5379 if (overrideIdUpdate !== void 0) update.overrideId = overrideIdUpdate ? overrideIdUpdate : null; 5380 result[key] = update; 5381 } else result[key] = null; 5382 }); 5383 return result; 5384}; 5385var dbBuildVariationDataMapFromVariationData = (dbVariationData) => { 5386 return import_immutable.default.Map().withMutations((mutableMap) => {
5387 Object.keys(dbVariationData).forEach((variationKey) => { 5388 let { text, comment, muted, overrideId } = dbVariationData[variationKey]; 5389 mutableMap.set(variationKey, new VariationData({ 5390 text: text ? text : "", 5391 comment: comment ? comment : "", 5392 muted: muted ? muted : false, 5393 overrideId: overrideId ? overrideId : "" 5394 })); 5395 }); 5396 }); 5397}; 5398var pointToNumber = (point, indexMaps) => { 5399 return indexMaps.reduce((acc, cur, idx) => { 5400 acc *= indexMaps[idx].size; 5401 acc += indexMaps[idx].get(point.get(idx)); 5402 return acc; 5403 }, 0); 5404}; 5405var numberToPoint = (number, valueSets) => { 5406 return import_immutable.default.List(valueSets.reduce((acc, cur, idx) => { 5407 let revIdx = valueSets.length - 1 - idx; 5408 let index = number % valueSets[revIdx].size; 5409 acc[revIdx] = valueSets[revIdx].get(index).id; 5410 number /= valueSets[revIdx].size; 5411 return acc; 5412 }, [])); 5413}; 5414var serializeStructure = (structure) => { 5415 return { 5416 stack: structure.stack.toArray().map((layer) => { 5417 return { 5418 valueSetSource: layer.valueSetSource, 5419 valueSetId: layer.valueSetId, 5420 name: layer.name, 5421 type: layer.type, 5422 valueSet: layer.valueSet.toArray(), 5423 merges: layer.merges.toArray().map((points) => { 5424 return points.toArray().map((point) => { 5425 return point.toArray(); 5426 }); 5427 }) 5428 }; 5429 }), 5430 representativeKey: structure.representativeKey, 5431 creativeOverride: structure.creativeOverride 5432 }; 5433}; 5434var unserializeStructure = (jsStructure) => { 5435 let stack = import_immutable.default.List().withMutations((mutableStack) => { 5436 jsStructure.stack.forEach((jsLayer) => { 5437 let valueSetSource = jsLayer.dataElementId ? "DataElements" : jsLayer.valueSetSource; 5438 let valueSetId = jsLayer.dataElementId || jsLayer.valueSetId; 5439 let type = jsLayer.type || DataElementContentTypes.String; 5440 let layer = new Layer({ 5441 valueSetSource, 5442 valueSetId, 5443 name: jsLayer.name, 5444 type, 5445 valueSet: import_immutable.default.List(updgradeValueSet(jsLayer.valueSet)), 5446 merges: import_immutable.default.OrderedSet(jsLayer.merges.map((jsPoints) => import_immutable.default.OrderedSet(jsPoints.map((jsPoint) => import_immutable.default.List(jsPoint))))) 5447 }); 5448 mutableStack.push(layer); 5449 }); 5450 }); 5451 let representativeKey = jsStructure.representativeKey; 5452 let creativeOverride = jsStructure.creativeOverride; 5453 return new Structure({ 5454 stack, 5455 representativeKey, 5456 creativeOverride 5457 }); 5458}; 5459var updgradeValueSet = (valueSet) => { 5460 return valueSet.map((value) => { 5461 if (typeof value === "string") if (value === "~~~OTHER~OR~MISSING~~~") return { 5462 id: "_vs_other_or_missing", 5463 dn: DATA_ELEMENT_VALUE_OTHER_OR_MISSING 5464 }; 5465 else return { 5466 id: "_bc_" + value.toLowerCase(), 5467 dn: value 5468 }; 5469 return value; 5470 }); 5471}; 5472var serializeVariationDataMap = (variationDataMap) => { 5473 let result = {}; 5474 variationDataMap.forEach((variationData, variationKey) => { 5475 result[variationKey] = { 5476 text: variationData.text, 5477 comment: variationData.comment, 5478 muted: variationData.muted, 5479 overrideId: variationData.overrideId 5480 }; 5481 }); 5482 return result; 5483}; 5484var unserializeVariationDataMap = (jsVariationDataMap) => { 5485 return import_immutable.default.Map().withMutations((mutableMap) => { 5486 Object.keys(jsVariationDataMap).forEach((variationKey) => { 5487 let { text, comment, muted, overrideId } = jsVariationDataMap[variationKey]; 5488 mutableMap.set(variationKey, new VariationData({ 5489 text, 5490 comment, 5491 muted, 5492 overrideId 5493 })); 5494 }); 5495 }); 5496}; 5497var emptyPointSet = () => { 5498 return import_immutable.default.OrderedSet.of(import_immutable.default.List()); 5499}; 5500var generateKey = (points) => { 5501 return (0, import_md5.default)(pointsToCompactString(points)); 5502}; 5503var pointsToCompactString = (points) => { 5504 let result = ""; 5505 points.forEach((point) => { 5506 point.forEach((valueId) => { 5507 result += valueId + String.fromCharCode(1); 5508 }); 5509 result += String.fromCharCode(2); 5510 }); 5511 return result; 5512}; 5513var findDimensionIndex = (stack, valueSetProvider) => { 5514 return stack.findIndex((layer) => layer.valueSetSource === valueSetProvider.getSource() && layer.valueSetId === valueSetProvider.getId()); 5515}; 5516var getPointsForKey = (stack, valueSetProviders, key) => { 5517 let dimensions = buildDimensionsFromStack(stack, valueSetProviders); 5518 let variation = buildVariationsEx(stack, import_immutable.default.Map(), dimensions, false).get(key); 5519 if (variation) return variation.points; 5520}; 5521var generateVerifiedKey = (stack, valueSetProviders, points) => { 5522 let dimensions = buildDimensionsFromStack(stack, valueSetProviders); 5523 let variations = buildVariationsEx(stack, import_immutable.default.Map(), dimensions, false); 5524 if (points) { 5525 let key = generateKey(points); 5526 if (variations.get(key)) return key; 5527 } 5528 return generateKey(variations.sort(variationComparator(dimensions)).first().points); 5529}; 5530var buildDimensionsFromStack = (stack, valueSetProviders) => { 5531 return import_immutable.default.List().withMutations((mutableDimensions) => { 5532 stack.forEach((layer) => { 5533 let valueSetProvider = valueSetProviders.find((valueSetProvider) => valueSetProvider.getSource() === layer.valueSetSource && valueSetProvider.getId() === layer.valueSetId); 5534 let id = generateDimensionId(layer.valueSetSource, layer.valueSetId); 5535 let name = layer.name; 5536 let type = layer.type; 5537 let valueSet = layer.valueSet; 5538 let indexMap = valueSetToIndexMap(valueSet); 5539 let orphaned = !valueSetProvider || valueSetProvider.getValueSet().size === 0; 5540 let removed = false;
5541 let hasOrphanedValues = !orphaned && valueSet.size > valueSetProvider.getValueSet().size; 5542 mutableDimensions.push(new Dimension({ 5543 id, 5544 name, 5545 type, 5546 valueSet, 5547 indexMap, 5548 orphaned, 5549 removed, 5550 hasOrphanedValues 5551 })); 5552 }); 5553 }); 5554}; 5555var buildVariationsFromStack = (stack, variationDataMap, dimensions, valueSetProviders) => { 5556 let variations = buildVariationsEx(stack, variationDataMap, dimensions, false); 5557 if (dimensions.some((dimension) => dimension.orphaned || dimension.removed)) { 5558 let reducedVariations = buildVariationsEx(stack, variationDataMap, dimensions, true); 5559 let sortedVariations = variations.sort(variationComparator(dimensions)); 5560 let usedKeys = import_immutable.default.Set(); 5561 let emptyPointSetKey = generateKey(emptyPointSet()); 5562 variations = variations.withMutations((mutableVariations) => { 5563 sortedVariations.forEach((variation, variationKey) => { 5564 let key = generateKey(removeOrphanedAndRemovedDimensions(variation.points, dimensions)); 5565 if (key !== emptyPointSetKey && reducedVariations.has(key) && !usedKeys.has(key)) { 5566 usedKeys = usedKeys.add(key); 5567 mutableVariations.set(variationKey, new Variation({ 5568 points: variation.points, 5569 rp: variation.rp, 5570 orphaned: false, 5571 dataOrphaned: true, 5572 variationData: variation.variationData 5573 })); 5574 } else mutableVariations.set(variationKey, new Variation({ 5575 points: variation.points, 5576 rp: variation.rp, 5577 orphaned: true, 5578 dataOrphaned: true, 5579 variationData: variation.variationData 5580 })); 5581 }); 5582 }); 5583 } 5584 if (dimensions.some((dimension) => dimension.hasOrphanedValues)) variations = variations.withMutations((mutableVariations) => { 5585 variations.forEach((variation, variationKey) => { 5586 if (!variation.orphaned) { 5587 if (variation.points.some((point) => point.some((valueId, index) => { 5588 let dimension = dimensions.get(index); 5589 if (dimension.orphaned || dimension.removed) return false; 5590 return !valueSetIncludes(valueSetProviders.find((valueSetProvider) => valueSetProvider.getSource() === stack.get(index).valueSetSource && valueSetProvider.getId() === stack.get(index).valueSetId).getValueSet(), valueId); 5591 }))) mutableVariations.set(variationKey, new Variation({ 5592 points: variation.points, 5593 rp: variation.rp, 5594 orphaned: true, 5595 dataOrphaned: true, 5596 variationData: variation.variationData 5597 })); 5598 } 5599 }); 5600 }); 5601 return variations.sort(variationComparator(dimensions)); 5602}; 5603var buildVariationsEx = (stack, variationDataMap, dimensions, withoutOrphanedAndRemoved) => { 5604 let masterSet = import_immutable.default.OrderedSet.of(emptyPointSet()); 5605 let orphanedOrRemovedDimFound = false; 5606 let indexToMerge = -1; 5607 stack.forEach((layer, index) => { 5608 let dimension = dimensions.get(index); 5609 if (withoutOrphanedAndRemoved && (dimension.orphaned || dimension.removed)) orphanedOrRemovedDimFound = true; 5610 else { 5611 masterSet = join(masterSet, dimension.valueSet); 5612 if (!orphanedOrRemovedDimFound) indexToMerge = index; 5613 } 5614 }); 5615 if (indexToMerge >= 0) { 5616 let layer = stack.get(indexToMerge); 5617 masterSet = applyMerges(masterSet, layer.merges); 5618 } 5619 return import_immutable.default.Map().withMutations((mutableVariations) => { 5620 masterSet.forEach((points) => { 5621 let key = generateKey(points); 5622 let rp = extractRepresentativePoint(dimensions, points); 5623 let variationData = findVariationDataForPoints(dimensions, points, variationDataMap); 5624 mutableVariations.set(key, new Variation({ 5625 points, 5626 rp, 5627 orphaned: false, 5628 dataOrphaned: false, 5629 variationData: variationData || new VariationData() 5630 })); 5631 }); 5632 }); 5633}; 5634var removeOrphanedAndRemovedDimensions = (points, dimensions) => { 5635 return import_immutable.default.OrderedSet().withMutations((mutablePoints) => { 5636 points.forEach((point) => { 5637 let reducedPoint = import_immutable.default.List().withMutations((mutableReducedPoint) => { 5638 dimensions.forEach((dimension, index) => { 5639 if (!dimension.orphaned && !dimension.removed) mutableReducedPoint.push(point.get(index)); 5640 }); 5641 }); 5642 mutablePoints.add(reducedPoint); 5643 }); 5644 }); 5645}; 5646function generateDimensionId(source, id) { 5647 return `${source}__${id}`; 5648} 5649var findVariationDataForPoints = (dimensions, points, variationDataMap) => { 5650 let key = findBestKeyForPoints(dimensions, points, (key) => variationDataMap.has(key)); 5651 return variationDataMap.get(key); 5652}; 5653var findBestKeyForPoints = (dimensions, points, predicate) => { 5654 let bestKey; 5655 let key = generateKey(points); 5656 if (predicate(key)) bestKey = key; 5657 if (!bestKey && points.size > 0) for (let dim = 0; dim < dimensions.size && !bestKey; ++dim) {
5658 key = generateKey(points.map((point) => point.skipLast(dim + 1))); 5659 if (predicate(key)) bestKey = key; 5660 } 5661 return bestKey; 5662}; 5663var valueSetIncludes = (valueSet, valueId) => { 5664 return valueSet.some((valueSetValue) => valueSetValue.id === valueId); 5665}; 5666var updateSetOfPointsPerValueSet = (setOfPoints, valueSets) => { 5667 return import_immutable.default.OrderedSet().withMutations((mutableSet) => { 5668 setOfPoints.forEach((points) => { 5669 let updatedPoints = updatePointsPerValueSet(points, valueSets); 5670 if (updatedPoints.size > 0) mutableSet.add(updatedPoints); 5671 }); 5672 }); 5673}; 5674var updatePointsPerValueSet = (points, valueSets) => { 5675 return import_immutable.default.OrderedSet().withMutations((mutablePoints) => { 5676 points.forEach((point) => { 5677 if (point.every((valueId, index) => valueSetIncludes(valueSets.get(index), valueId))) mutablePoints.add(point); 5678 }); 5679 }); 5680}; 5681var join = (masterSet, valueSet) => { 5682 return import_immutable.default.OrderedSet().withMutations((mutableSet) => { 5683 masterSet.forEach((points) => { 5684 valueSet.forEach((value) => { 5685 let expandedPoints = import_immutable.default.OrderedSet().withMutations((mutablePoints) => { 5686 points.forEach((point) => { 5687 mutablePoints.add(point.concat(value.id)); 5688 }); 5689 }); 5690 mutableSet.add(expandedPoints); 5691 }); 5692 }); 5693 }); 5694}; 5695var applyMerges = (masterSet, merges) => { 5696 let mergedMasterSet = null; 5697 import_immutable.default.Map().withMutations((mutableExistingPointMap) => { 5698 masterSet.forEach((masterPoints) => { 5699 updatePointMap(mutableExistingPointMap, masterPoints); 5700 }); 5701 mergedMasterSet = masterSet.withMutations((mutableSet) => { 5702 merges.forEach((points) => { 5703 points.forEach((point) => { 5704 let existingPoints = mutableExistingPointMap.get(point); 5705 if (existingPoints) { 5706 mutableSet.delete(existingPoints); 5707 mutableExistingPointMap.delete(point); 5708 if (existingPoints.size > 1) { 5709 existingPoints = existingPoints.delete(point); 5710 mutableSet.add(existingPoints); 5711 updatePointMap(mutableExistingPointMap, existingPoints); 5712 } 5713 } 5714 }); 5715 mutableSet.add(points); 5716 updatePointMap(mutableExistingPointMap, points); 5717 }); 5718 }); 5719 }); 5720 return mergedMasterSet; 5721}; 5722var updatePointMap = (mutableMap, points) => { 5723 points.forEach((point) => { 5724 mutableMap.set(point, points); 5725 }); 5726}; 5727var extractRepresentativePoint = (dimensions, points) => { 5728 return points.first(); 5729}; 5730var variationComparator = (dimensions) => { 5731 let comparator = pointComparator(dimensions); 5732 return (entryA, entryB) => { 5733 return comparator(entryA.rp, entryB.rp); 5734 }; 5735}; 5736var pointComparator = (dimensions) => { 5737 return (pointA, pointB) => { 5738 let result = 0; 5739 dimensions.forEach((dimension, index) => { 5740 let valueA = pointA.get(index); 5741 let valueB = pointB.get(index); 5742 result = dimension.indexMap.get(valueA) - dimension.indexMap.get(valueB); 5743 if (result !== 0) return false; 5744 }); 5745 return result; 5746 }; 5747}; 5748var NarrationsModelUtils = { 5749 defaultStructure, 5750 defaultVariationDataMap, 5751 buildDimensions, 5752 buildVariations, 5753 setRepresentativeKey, 5754 setText, 5755 setComment, 5756 mute, 5757 unmute, 5758 setOverrideId, 5759 addDimension, 5760 removeDimension, 5761 setSupportCreativeOverride, 5762 merge, 5763 unmerge, 5764 acceptOrphansAndRemoved, 5765 isValueSetProviderUsed, 5766 isValueSetProviderUsedEx, 5767 handleValueSetProviderChange, 5768 generateKey, 5769 generateKeyForExpandedPoint, 5770 isExpandedPoint, 5771 getExpandedPoint, 5772 updateStructure, 5773 updateVariationDataMap, 5774 applyVariationDataToVariations, 5775 applyVariationDataToVariationDataMap, 5776 valueSetToIndexMap, 5777 dbExtractDimensionDataFromStructure, 5778 dbExtractMergeDataFromStructure, 5779 dbExtractRepresentativeKeyFromStructure, 5780 dbExtractCreativeOverrideFromStructure, 5781 dbBuildStructureFromDBData, 5782 dbExtractVariationDataUpdates, 5783 dbBuildVariationDataMapFromVariationData, 5784 pointToNumber, 5785 numberToPoint, 5786 serializeStructure, 5787 unserializeStructure, 5788 serializeVariationDataMap, 5789 unserializeVariationDataMap, 5790 generateDimensionId 5791}; 5792//#endregion 5793//#region common/SystemDataElementsUtils.ts 5794var import_dist$7 = require_dist$2(); 5795var SYSTEM_DATA_STORY_ID = "HubSystem:Story"; 5796var getDynamicSystemDataElements = () => { 5797 return import_dist$7.systemDataElementsArr.filter((sde) => sde.id === SYSTEM_DATA_STORY_ID); 5798}; 5799/** 5800* Gets the concatenated array of system data elements and dynamic system data elements 5801* @param programType - the program type we want to get the data elements for 5802* @param isEditorAccountLibraryProgram - the editor's Account Library program should include both ads and cx system data elements 5803*/ 5804var getAllSystemDataElements = (programType, isEditorAccountLibraryProgram = false) => { 5805 let sysDEArray = import_dist$7.systemDataElementsArr; 5806 if (isEditorAccountLibraryProgram || programType?.toLowerCase() === ProgramType.Ads.toLocaleLowerCase()) sysDEArray = sysDEArray.concat(import_dist$7.adsSystemDataElementsArr); 5807 if (isEditorAccountLibraryProgram || programType?.toLowerCase() === ProgramType.CRM.toLocaleLowerCase()) sysDEArray = sysDEArray.concat(import_dist$7.cxSystemDataElementsArr); 5808 return sysDEArray; 5809}; 5810//#endregion 5811//#region client/logic/common/DynamicValueSetSelector.js 5812var DynamicValueSetSelector = class DynamicValueSetSelector { 5813 static buildDynamicValueSetData = index((wireframes, getStoriesAsArray) => { 5814 let sysDataElements = getDynamicSystemDataElements(); 5815 let dynamicDataForValueSet = {};
5816 sysDataElements.forEach(function(sde) { 5817 dynamicDataForValueSet[sde.id] = DynamicValueSetSelector.getDynamicValueSet(sde, wireframes, getStoriesAsArray); 5818 }); 5819 return dynamicDataForValueSet; 5820 }); 5821 static getDynamicValueSet(dataElement, wireframes, getStoriesAsArray) { 5822 let valueSet = []; 5823 switch (dataElement.id) { 5824 case SYSTEM_DATA_STORY_ID: return DynamicValueSetSelector.getStoriesValueSet(wireframes, getStoriesAsArray); 5825 } 5826 return valueSet; 5827 } 5828 static getStoriesValueSet(wireframes, getStoriesAsArray) { 5829 return getStoriesAsArray(wireframes).map((story) => ({ 5830 dn: story.name, 5831 id: "_system_" + story.id 5832 })); 5833 } 5834}; 5835//#endregion 5836//#region client/logic/common/routingUtils.ts 5837var RouterPropType = { 5838 match: import_prop_types.default.object.isRequired, 5839 location: import_prop_types.default.object.isRequired, 5840 history: import_prop_types.default.object.isRequired 5841}; 5842var removeLastSlash = (str) => { 5843 return str.replace(/\/$/, ""); 5844}; 5845var setProgramAndNavigationItemToUrl = (accountId, programId, navigationItem) => { 5846 return (0, import_dist$9.legacyAccountAccountIdProgramProgramIdNavigationItemTypePath)({ 5847 accountId, 5848 programId, 5849 navigationItemType: navigationItem 5850 }); 5851}; 5852var getEditorUrlPartWithQueryParams = (industry, storyName) => { 5853 return industry && storyName ? `${encodeURI(`${import_dist$9.StudioMainCategoriesPaths.Editor}?industry=${industry}&useCase=${storyName}`)}` : import_dist$9.StudioMainCategoriesPaths.Editor; 5854}; 5855var navigateToEditorPath = (accountId, programId, step) => { 5856 return isNewNav ? (0, import_dist$9.newNavEditorRootPath)({ 5857 accountId, 5858 videoId: programId, 5859 editorType: step 5860 }) : (0, import_dist$9.legacyEditorSteps)({ 5861 accountId, 5862 programId, 5863 navigationItem: import_dist$9.StudioMainCategoriesPaths.Editor, 5864 editorType: step 5865 }); 5866}; 5867var getEditorUrl = (accountId, programId, industry, storyName) => { 5868 return (0, import_dist$9.legacyAccountAccountIdProgramProgramIdNavigationItemTypePath)({ 5869 accountId, 5870 programId, 5871 navigationItemType: import_dist$9.StudioMainCategoriesPaths.Editor 5872 }) + (industry && storyName ? `${encodeURI(`?industry=${industry}&useCase=${storyName}`)}` : ""); 5873}; 5874var addVersionToUrl = (url, version, isItemExist) => { 5875 return setToUrl(url, 7, 2, "version/" + version, isItemExist); 5876}; 5877var removeVersionFromUrl = (url) => { 5878 return setToUrl(url, 7, 2, void 0, true); 5879}; 5880var legacyBuilderVersionPath = import_dist$9.legacyBuilderBuilderTypePath.slash("version/:versionNumber"); 5881var addBuilderTypeToUrl = (accountId, programId, storiesVersion) => { 5882 const builderType = storiesVersion ? import_dist$9.BuilderTypePaths.Story : import_dist$9.BuilderTypePaths.Scene; 5883 const version = getVersionFromPathname(window.location.pathname); 5884 return version ? legacyBuilderVersionPath({ 5885 accountId, 5886 programId, 5887 navigationItemType: import_dist$9.StudioMainCategoriesPaths.Builder, 5888 builderType, 5889 versionNumber: version 5890 }) : (0, import_dist$9.legacyBuilderBuilderTypePath)({ 5891 accountId, 5892 programId, 5893 navigationItemType: import_dist$9.StudioMainCategoriesPaths.Builder, 5894 builderType 5895 }); 5896}; 5897var getHomePageByUserRoles = (userRoles, accountId) => { 5898 if (userRoles) { 5899 if (isSharedFrameworkViewerUser(userRoles)) return import_dist$9.legacyRootPath.slash(`account/${accountId}/notfound`)(); 5900 if (userRoles.length === 1 && userRoles.includes(roles.animator)) return (0, import_dist$9.legacyPreviewPath)(); 5901 if (accountId) return getUserHomePageUrl(accountId); 5902 } 5903 return (0, import_dist$9.legacyRootPath)(); 5904}; 5905var getUserHomePageUrl = (accountId) => { 5906 return isNewNav ? (0, import_dist$9.newNavYourVideosPath)({ accountId }) : (0, import_dist$9.legacyAllProgramsOverviewPath)({ accountId }); 5907}; 5908var getStoryBuilderPageUrl = (accountId, projectName, stage, version) => { 5909 let url = import_dist$9.legacyRootPath.slash(`account/${accountId}/program/${projectName}/${import_dist$9.StudioMainCategoriesPaths.Builder}/${import_dist$9.BuilderTypePaths.Story}`)(); 5910 if (stage) url += "/stage/" + stage; 5911 else if (version) url += "/version/" + version; 5912 return url; 5913}; 5914var startIndex = import_dist$9.legacyRoot === "/" ? 0 : import_dist$9.legacyRoot.split("/").length - 1; 5915var setToUrl = (url, index, indexesToDelete, item, isExists) => { 5916 const adjustedIndex = startIndex + index; 5917 let urlArray = url.split("/"); 5918 item ? urlArray.splice(adjustedIndex, isExists ? indexesToDelete : 0, item) : urlArray.splice(adjustedIndex, isExists ? indexesToDelete : 0); 5919 return urlArray.join("/"); 5920}; 5921var dashboardsPaths = [import_dist$9.legacyRootPath.slash("dashboards").pattern, import_dist$9.legacyRootPath.slash(":accountId/dashboards").pattern]; 5922var dashboardPaths = [import_dist$9.legacyRootPath.pattern, import_dist$9.legacyAccountIdPath.pattern]; 5923var mainContainerPathByUserRoles = index((userRoles) => { 5924 if (isSharedFrameworkViewerUser(userRoles)) return [{ 5925 path: sharedFrameworkViewerPath, 5926 isExact: true 5927 }]; 5928 return [{ 5929 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName(${import_dist$9.programIdForAllPrograms})/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Overview})`).pattern, 5930 isExact: true 5931 }, { 5932 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem${getEnumStr
5932ingForPath(getNavigationItemsByUserRoles(userRoles))}`).pattern, 5933 isExact: false 5934 }]; 5935}); 5936var getEnumStringForPath = (urlPathParameterOptions) => { 5937 let enumString = ""; 5938 urlPathParameterOptions.forEach((urlPathParameterOption, index) => { 5939 if (index < urlPathParameterOptions.length - 1) enumString = enumString + urlPathParameterOption + "|"; 5940 else enumString = enumString + urlPathParameterOption; 5941 }); 5942 return `(${enumString})`; 5943}; 5944var studioPath = import_dist$9.legacyRootPath.slash("account/:accountId/program/:programName/:navigationItem").pattern; 5945import_dist$9.legacyRootPath.slash("account/:accountId/program/:programName/:navigationItem/:navigationItemType/version/:version").pattern; 5946var studioStageBasePath = import_dist$9.legacyRootPath.slash("account/:accountId/program/:programName/:navigationItem/:navigationItemType/stage/:stage").pattern; 5947import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem${getEnumStringForPath(Object.values(import_dist$9.StudioMainCategoriesPaths))}/:navigationItemType`).pattern; 5948var buildersBasePath = import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})`).pattern; 5949var builderPaths = (version, stage) => [ 5950 { 5951 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/version/:version`).pattern, 5952 key: version 5953 }, 5954 { 5955 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/stage/:stage`).pattern, 5956 key: stage 5957 }, 5958 { 5959 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/:builderType(${import_dist$9.BuilderTypePaths.Scene}|${import_dist$9.BuilderTypePaths.Story}|${import_dist$9.BuilderTypePaths.Narrations}|${import_dist$9.BuilderTypePaths.VersionManager})`).pattern, 5960 key: "draft" 5961 }, 5962 { 5963 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/:builderType(${import_dist$9.BuilderTypePaths.Scene}|${import_dist$9.BuilderTypePaths.Story}|${import_dist$9.BuilderTypePaths.Narrations}|${import_dist$9.BuilderTypePaths.VersionManager})/stage/:stage`).pattern, 5964 key: stage 5965 }, 5966 { 5967 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/:builderType(${import_dist$9.BuilderTypePaths.Scene}|${import_dist$9.BuilderTypePaths.Story}|${import_dist$9.BuilderTypePaths.Narrations}|${import_dist$9.BuilderTypePaths.VersionManager})/version/:version`).pattern, 5968 key: version 5969 } 5970]; 5971var creativePaths = [import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Creative})`).pattern, import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Creative})/:creativeTab(${import_dist$9.CreativeTypePaths.CreativeTable}|${import_dist$9.CreativeTypePaths.CreativeVersionManager})`).pattern]; 5972var settingsPathsForOwnedMedia = [import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Settings})`).pattern, import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Settings})/:settingsType(${import_dist$9.SettingsTypePaths.AnalyticsSettings}|${import_dist$9.SettingsTypePaths.GeneralSettings}|${import_dist$9.SettingsTypePaths.StoryTemplateSettings})`).pattern]; 5973var settingsPathsForPaidMedia = [import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Settings})`).pattern, import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Settings})/:settingsType(${import_dist$9.SettingsTypePaths.GeneralSettings}|${import_dist$9.SettingsTypePaths.StoryTemplateSettings})`).pattern]; 5974var frameworkLegacyPaths = { 5975 Base: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})`).pattern, 5976 Canvas: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.LegacyCanvas})`).pattern, 5977 Overview: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.LegacyOverview})`).pattern, 5978 Strategy: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.Strategy})`).pattern, 5979 StoryMap: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.StoryMap})`).pattern 5980}; 5981var getFrameworkTab = (tabId, accountId, programName) => import_dist$9.legacyRootPath.slash(`account/${accountId}/program/${programName}/${import_dist$9.StudioMainCategoriesPaths.Framework}/${tabId}`).pattern; 5982var sharedFrameworkViewerPath = import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.Strategy}|${import_dist$9.FrameworkTypePaths.StoryMap})/draft/:draftId`).pattern; 5983var getEditorPaths = () => import_dist$9.legacyEditorSteps.pattern; 5984var editorLegacyPaths = { 5985 base: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Editor2})`).pattern, 5986 content: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Editor2})/:editorType(${import_dist$9.EditorTypePaths.Content})`).pattern 5987}; 5988var getFrameworkPaths = (sharedFrameworkViewerUser) => { 5989 if (sharedFrameworkViewerUser) return [sharedFrameworkViewerPath]; 5990 else return [import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.Drafts})`).pattern, import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Framework})/:frameworkType(${import_dist$9.FrameworkTypePaths.Strategy}|${import_dist$9.FrameworkTypePaths.StoryMap})/draft/:draftId`).pattern]; 5991}; 5992var isSharedFrameworkViewerUser = (userRoles) => (userRoles || []).length === 1 && userRoles[0] === roles.sharedFrameworkViewer; 5993var previewPaths = (version, stage) => [ 5994 { 5995 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/${import_dist$9.BuilderTypePaths.Preview}`).pattern, 5996 key: "draft" 5997 }, 5998 { 5999 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/${import_dist$9.BuilderTypePaths.Preview}/stage/:stage`).pattern, 6000 key: stage 6001 }, 6002 { 6003 path: import_dist$9.legacyRootPath.slash(`account/:accountId/program/:programName/:navigationItem(${import_dist$9.StudioMainCategoriesPaths.Builder})/${import_dist$9.BuilderTypePaths.Preview}/version/:version`).pattern, 6004 key: version 6005 } 6006]; 6007var urlsToSupportForLegacyPrograms = [ 6008 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName").pattern, 6009 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/curated").pattern, 6010 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/:stage/preview").pattern 6011]; 6012var urlsToRedirectToHomePage = [ 6013 import_dist$9.legacyRootPath.pattern, 6014 import_dist$9.legacyRootPath.slash("dashboards").pattern, 6015 import_dist$9.legacyAccountIdDashboardsPath.pattern, 6016 import_dist$9.legacyRootPath.slash(":accountId/dashboards/accountOverview/:programName").pattern, 6017 import_dist$9.legacyRootPath.slash(":accountId/dashboards/accountOverview").pattern, 6018 import_dist$9.legacyRootPath.slash(":accountId/dashboards/accountOverview/:programName/sideBySide").pattern, 6019 import_dist$9.legacyRootPath.slash(":accountId/dashboards/accountDashboard/:programName/sideBySide").pattern, 6020 import_dist$9.legacyAccountIdDashboardsAccountDashboardPath.pattern, 6021 import_dist$9.legacyRootPath.slash(":accountId/dashboards/accountDashboard/:programName").pattern, 6022 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/wireframes").pattern, 6023 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/wireframes/narrations").pattern, 6024 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/wireframes/stage/:stage").pattern, 6025 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/wireframes/version/:version").pattern, 6026 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/wireframes/storyPreview/version/:version").pattern, 6027 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/wireframes/storyPreview/:stage").pattern, 6028 import_dist$9.legacyRootPath.slash(":accountId/framework").pattern, 6029 import_dist$9.legacyRootPath.slash(":accountId/projects/:projectName/version-manager").pattern, 6030 import_dist$9.legacyRootPath.slash(":accountId/projects/:programName/analytics").pattern 6031]; 6032var NOT_ACCOUNT_IDS = /* @__PURE__ */ new Set([ 6033 "login", 6034 "preview", 6035 "admin", 6036 "accounts", 6037 "account-tier-restriction-management", 6038 "ads-management", 6039 "cc-library-tool", 6040 "manage-ai-systems", 6041 "review-gallery", 6042 "creative-toolkit", 6043 "editor", 6044 "dashboards", 6045 "projects" 6046]); 6047var getAccountIdFromPath = () => { 6048 const match = matchPath$1(window.location.pathname, { 6049 path: import_dist$9.legacyRootPath.slash("account/:accountId").pattern, 6050 strict: false, 6051 exact: false 6052 }); 6053 if (match) return match.params.accountId; 6054 const legacyMatch = matchPath$1(window.location.pathname, { 6055 path: import_dist$9.legacyAccountIdPath.pattern, 6056 strict: false, 6057 exact: false 6058 }); 6059 if (legacyMatch && !NOT_ACCOUNT_IDS.has(legacyMatch.params.accountId)) return legacyMatch.params.accountId; 6060 const newNavMatch = matchPath$1(window.location.pathname, { 6061 path: import_dist$9.newNavAccountPath.pattern, 6062 strict: false, 6063 exact: false 6064 }); 6065 if (newNavMatch) return newNavMatch.params.accountId; 6066}; 6067//#endregion 6068//#region client/components/main/mainContainerUtils.ts 6069var DrawerFilters = /* @__PURE__ */ function(DrawerFilters) { 6070 DrawerFilters["AllButArchive"] = "notArchived"; 6071 DrawerFilters["Archive"] = "archived"; 6072 return DrawerFilters; 6073}({}); 6074var findProgramSummaryForProgramId = index((programSummaries, programId) => { 6075 return programSummaries.find((program) => { 6076 const { id, projectIds: { builders, canvas, dashboards } } = program; 6077 return [ 6078 id, 6079 builders, 6080 canvas, 6081 dashboards 6082 ].includes(programId); 6083 }); 6084}); 6085var findProgramSummaryIndexForProgramId = index((programSummaries, programId) => { 6086 return programSummaries.findIndex((program) => { 6087 const { id, projectIds: { builders, canvas, dashboards } } = program; 6088 return [ 6089 id, 6090 builders, 6091 canvas, 6092 dashboards 6093 ].includes(programId); 6094 }); 6095}); 6096var getBuildersProgramsSummariesWithoutCanvas = index((programSummaries) => programSummaries.filter((program) => program.projectIds.builders)); 6097var getBuildersProgramsToCombine = index((programSummaries) => { 6098 let buildersPrograms = getBuildersProgramsSummariesWithoutCanvas(programSummaries).reduce((acc, p) => { 6099 acc.push({ 6100 key: p.projectIds.builders, 6101 value: p.projectIds.builders, 6102 text: p.displayName 6103 }); 6104 return acc; 6105 }, []); 6106 return [{ 6107 key: "none", 6108 value: "", 6109 text: "None" 6110 }].concat(buildersPrograms); 6111}); 6112var shouldShowAddBuilderProgramButton = index((userRoles) => { 6113 return userRoles.includes(roles.admin) || userRoles.includes(roles.builderEditor); 6114}); 6115var shouldShowAddFrameWorkProgramButton = index((userRoles) => { 6116 return userRoles.includes(roles.admin) || userRoles.includes(roles.frameworkEditor); 6117}); 6118var shouldShowAddEditorProgramButton = index((userRoles) => { 6119 return isPermitted(userRoles, permissions.createEditorPrograms); 6120}); 6121var shouldShowAddProgramButton = index((userRoles) => { 6122 return shouldShowAddBuilderProgramButton(userRoles) || shouldShowAddFrameWorkProgramButton(userRoles) || shouldShowAddEditorProgramButton(userRoles); 6123}); 6124var getDashboardsProgramIds = index((programSummaries, drawerFilter) => { 6125 let ids = /* @__PURE__ */ new Set();
6126 programSummaries.forEach((programSummary) => { 6127 if (isProgramBelongToFilter(programSummary, drawerFilter) && !!programSummary.projectIds[TypesOfProjectSummary.dashboards]) ids.add(programSummary.projectIds.sfId.toLowerCase()); 6128 }); 6129 return ids; 6130}); 6131var isProgramBelongToFilter = (programSummary, drawerFilter) => { 6132 return !drawerFilter || drawerFilter === "notArchived" && !programSummary.isArchive || drawerFilter === "archived" && programSummary.isArchive; 6133}; 6134var getNumOfDashboardsPrograms = index((programSummaries) => { 6135 return getNumOfProgramsByType(programSummaries, TypesOfProjectSummary.dashboards); 6136}); 6137index((programSummaries) => { 6138 return getNumOfProgramsByType(programSummaries, TypesOfProjectSummary.builders); 6139}); 6140index((programSummaries) => { 6141 return getNumOfProgramsByType(programSummaries, TypesOfProjectSummary.canvas); 6142}); 6143var getNumOfProgramsByType = (programSummaries, type) => { 6144 return programSummaries.filter((program) => !!program.projectIds[type]).length; 6145}; 6146var getStageFromPathname = (pathname) => { 6147 const match = matchPath$1(pathname, { 6148 path: studioStageBasePath, 6149 exact: false, 6150 strict: false 6151 }); 6152 const params = match && match.params; 6153 return params && params.stage; 6154}; 6155var builderVersionPaths = [import_dist$9.legacyRootPath.slash("account/:accountId/program/:programName/:navigationItem/:navigationItemType/version/:version"), import_dist$9.legacyRootPath.slash("account/:accountId/program/:programName/:navigationItem/version/:version")]; 6156var getVersionFromPathname = (pathname) => { 6157 for (const path of builderVersionPaths) { 6158 const match = matchPath$1(pathname, { 6159 path: path.pattern, 6160 exact: false, 6161 strict: false 6162 }); 6163 if (match) return match.params.version; 6164 } 6165 return null; 6166}; 6167var getProgramNameFromPathname = (pathname, template = studioPath) => { 6168 const match = matchPath$1(pathname, { 6169 path: template, 6170 exact: false, 6171 strict: false 6172 }); 6173 const params = match && match.params; 6174 return params && params.programName; 6175}; 6176var getAccountIdFromPathname = (pathname, template = studioPath) => { 6177 const match = matchPath$1(pathname, { 6178 path: template, 6179 exact: false, 6180 strict: false 6181 }); 6182 const params = match && match.params; 6183 return params && params.accountId; 6184}; 6185var isFrameworkRoute = (pathname) => { 6186 const match = matchPath$1(pathname, { 6187 path: getFrameworkPaths()[0], 6188 exact: false, 6189 strict: false 6190 }); 6191 return match && match.params && match.params.navigationItem === import_dist$9.StudioMainCategoriesPaths.Framework; 6192}; 6193var isEditorRoute = (pathname) => { 6194 if (isNewNav) return !!matchPath$1(pathname, { 6195 path: import_dist$9.newNavEditorPath.pattern, 6196 exact: false, 6197 strict: false 6198 }); 6199 else return matchPath$1(pathname, { 6200 path: getEditorPaths(), 6201 exact: false, 6202 strict: false 6203 })?.params?.navigationItem === import_dist$9.StudioMainCategoriesPaths.Editor; 6204}; 6205//#endregion 6206//#region client/logic/common/Consts.ts 6207var EDITING_MODE = "edit"; 6208var STAGE_MODE = "stage"; 6209var POSTGRES_CREATIVES_PRESET_ID = "2269852e-f11f-4d6a-90b4-d725901cf52a"; 6210var IGNORE_UPDATED = "$IGNORE$"; 6211var IGNORE_SERVER_ERRORS = "ignoreServerErrors"; 6212var MOCK_SCENE_ENTITY_LOGIC_ID = "SCENE_ENTITY_LOGIC_TEMP_POSTGRES_ID"; 6213var CREATIVES_PRESET_ID = "creatives_preset_id"; 6214//#endregion 6215//#region client/logic/common/StateReaderUtils.js 6216var import_number_to_letter = /* @__PURE__ */ __toESM(require_number_to_letter()); 6217var StateReaderUtils = class StateReaderUtils { 6218 static getTasksStartingTime(state) { 6219 return state.tasksStartingTime; 6220 } 6221 static getTaskStartingTime(state, taskId) { 6222 return state.tasksStartingTime[taskId]; 6223 } 6224 static getBrowserHistory(state) { 6225 return state.browserHistory.allLinks; 6226 } 6227 static getBrowserHistoryctiveId(state) { 6228 return state.browserHistory.activeId; 6229 } 6230 static getShouldTurnOffMergeDPSession(state) { 6231 return state.shouldTurnOffMergeDPSession; 6232 } 6233 static objectComparator(field, reverse) { 6234 return function(a, b) { 6235 a = a[field]; 6236 b = b[field]; 6237 if (typeof a === "string") { 6238 a = a.toLowerCase(); 6239 b = b.toLowerCase(); 6240 } 6241 return reverse * ((a > b) - (b > a)); 6242 }; 6243 } 6244 static isFeatureFlagsLoad(state) { 6245 return state.enableAllFeatureFlags !== void 0 || state.featureFlags !== void 0; 6246 } 6247 static isProgramsDynamoMigrationStatusLoaded(state) { 6248 return state.programsDynamoMigrationStatus !== void 0; 6249 } 6250 static isFeatureEnable(state, featureFlagId, overridingProgramId) { 6251 if (state.enableAllFeatureFlags !== void 0) return !!state.enableAllFeatureFlags; 6252 const featureFlagObj = state.featureFlags && state.featureFlags[featureFlagId]; 6253 if (!featureFlagObj) return false;
6254 const accountId = getAccountIdFromPath(); 6255 if (StateReaderUtils.isAccountExcludedFromFeatureFlag(accountId, featureFlagObj.excludedAccounts)) return !featureFlagObj.defaultValue; 6256 const { program: programFromUrl } = UrlUtils.getAccountAndProgramFromPath(); 6257 const programIdOrDashboardName = overridingProgramId ?? programFromUrl; 6258 if (programIdOrDashboardName && StateReaderUtils.isProgramExcludedFromFeatureFlag(accountId, programIdOrDashboardName, featureFlagObj.excludedPrograms, state.projectSummaries)) return !featureFlagObj.defaultValue; 6259 return featureFlagObj.defaultValue; 6260 } 6261 static isFeatureEnableIgnoreExcludedPrograms(state, featureFlagId) { 6262 if (state.enableAllFeatureFlags !== void 0) return !!state.enableAllFeatureFlags; 6263 return state.featureFlags && state.featureFlags[featureFlagId] && state.featureFlags[featureFlagId].defaultValue; 6264 } 6265 static isAccountExcludedFromFeatureFlag(accountId, excludedAccounts) { 6266 return excludedAccounts.some((account) => account.accountId === accountId); 6267 } 6268 static isProgramExcludedFromFeatureFlag(accountId, programIdOrDashboardName, excludedPrograms, projectSummaries = []) { 6269 const isProgramExcluded = (programKey) => excludedPrograms.some((program) => program === programKey || program.dynamoUniqueId === programKey || program.postgresUniqueId === programKey); 6270 const result = isProgramExcluded(`${accountId}/${programIdOrDashboardName}`); 6271 if (result) return result; 6272 const projectSummary = projectSummaries.find((ps) => ps.projectIds.dashboards === programIdOrDashboardName); 6273 if (projectSummary) return isProgramExcluded(`${accountId}/${projectSummary.id}`); 6274 return false; 6275 } 6276 static getFeatureFlags(state) { 6277 return state.featureFlags; 6278 } 6279 static getProgramDynamoMigrationStatus(state, programId) { 6280 return state.programsDynamoMigrationStatus && state.programsDynamoMigrationStatus[programId]; 6281 } 6282 static isProgramBulkDynamoMigrationDone(state, programId, bulkId) { 6283 return true; 6284 } 6285 static isProgramBulkDynamoMigrationDoneByLegacyId(state, projectName, bulkId) { 6286 return true; 6287 } 6288 static getForceLoad(state) { 6289 return state.forceLoad; 6290 } 6291 static getReportConfigurationJSON(state) { 6292 return import_dist$7.reportConfigurationTemplate; 6293 } 6294 static getDashboardScenes(state) { 6295 let arr = []; 6296 state.dashboardScenes.allIds.forEach((id) => { 6297 arr.push(state.dashboardScenes.byId[id]); 6298 }); 6299 arr = arr.sort(this.objectComparator("name", 1)); 6300 return arr; 6301 } 6302 static getDashboardProgramsScenes(programIds, statePrograms) { 6303 let selectedScenesObj = {}; 6304 programIds.forEach((programId) => { 6305 if (statePrograms.byId[programId]) statePrograms.byId[programId].scenes.forEach((sceneId) => { 6306 selectedScenesObj[sceneId] = true; 6307 }); 6308 }); 6309 return Object.keys(selectedScenesObj); 6310 } 6311 static getDashboardSelectedProgramDetails(state) { 6312 if (state.dashboardPrograms && state.selectedProgramId) return { 6313 id: state.selectedProgramId, 6314 details: state.dashboardPrograms.byId[state.selectedProgramId].details 6315 }; 6316 } 6317 static getDashboardPrograms(state, drawerFilter) { 6318 let arr = []; 6319 const filteredProgramIds = getDashboardsProgramIds(StateReaderUtils.getProgramSummaries(state), drawerFilter); 6320 state.dashboardPrograms.allIds.forEach((id) => { 6321 filteredProgramIds.has(id.toLowerCase()) && arr.push(state.dashboardPrograms.byId[id]); 6322 }); 6323 return arr; 6324 } 6325 static getDashboardAccountInfo(state) { 6326 return state.accountInfo; 6327 } 6328 static getPreviewDashboardSessionObj(state) { 6329 return state.previewDashboardSessionObj; 6330 } 6331 static getSecondPreviewSessionObject(state) { 6332 return state.secondPreviewDashboardSessionObj; 6333 } 6334 static getSharePreviewSessionObject(state) { 6335 return state.shareDashboardSessionObj; 6336 } 6337 static getShareUrl(state) { 6338 return state.shareUrl; 6339 } 6340 static getImageUrl(state) { 6341 return state.imageUrl; 6342 } 6343 static getProjects(stateProjects) { 6344 let projects = []; 6345 if (stateProjects.allNames) stateProjects.allNames.forEach(function(projectName) { 6346 projects.push(stateProjects.byName[projectName]); 6347 }); 6348 return projects; 6349 } 6350 static getProject(state, projectName) { 6351 return state.projects.byName[projectName]; 6352 } 6353 static getProjectType(state, projectName) { 6354 const project = StateReaderUtils.getProject(state, projectName); 6355 return project && project.programType; 6356 } 6357 static getProjectId(state, projectName) { 6358 return StateReaderUtils.getProject(state, projectName).programId; 6359 } 6360 static getNewPrograms(state) { 6361 return state.newPrograms; 6362 } 6363 static getProgramWithNoBuilders(state) { 6364 const allAccountPrograms = StateReaderUtils.getNewPrograms(state); 6365 const existingPrograms = StateReaderUtils.getBuildersProgramsSummariesWithSfIds(state) || []; 6366 return allAccountPrograms && allAccountPrograms.filter((program) => program.programId && !existingPrograms.find((bProg) => bProg.projectIds.sfId === program.programId)); 6367 } 6368 static getBuildersProgramsSummariesWithSfIds = (state) => { 6369 const programSummaries = StateReaderUtils.getProgramSummaries(state); 6370 return programSummaries && programSummaries.filter((program) => { 6371 return program.projectIds.builders && program.projectIds.sfId; 6372 }); 6373 }; 6374 static getProgramRFR(state, programName, stage, version) { 6375 let wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6376 return wireframes && wireframes.programRFR || 0; 6377 } 6378 static getProgramRFRTimestamp(state, programName, stage, version) { 6379 let wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6380 return wireframes && wireframes.programRFRTimestamp; 6381 } 6382 static getStoriesVersion(state, programName, stage, version) { 6383 let wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6384 return StateReaderUtils.getStoriesVersionFromWireframes(wireframes); 6385 } 6386 static getStoriesVersionFromWireframes(wireframes) { 6387 return wireframes && wireframes.storiesVersion; 6388 } 6389 static getTransition(wireframes) { 6390 if (!wireframes) return; 6391 if (wireframes.transition) return wireframes.transition; 6392 if (!wireframes.stories) return; 6393 const firstStoryId = Object.keys(wireframes.stories)[0]; 6394 if (!firstStoryId) return; 6395 return wireframes.stories[firstStoryId].transition; 6396 } 6397 static getCreativeVersion(state, programName, stage, version) { 6398 let wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6399 return StateReaderUtils.getCreativeVersionFromWireframes(wireframes); 6400 } 6401 static getCreativeVersionFromWireframes(wireframes) { 6402 return wireframes && wireframes.creativeVersion; 6403 } 6404 static getCreativeDDE(state, programName, stage, version) { 6405 let wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6406 return StateReaderUtils.getCreativeDDEFromWireframes(wireframes); 6407 } 6408 static getCreativeDDEFromWireframes(wireframes) { 6409 return wireframes && wireframes.creativeDDE; 6410 } 6411 static getCreativeNameLabel(state, programName, stage, version) { 6412 let wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6413 return StateReaderUtils.getCreativeNameLabelFromWireframes(wireframes); 6414 } 6415 static getCreativeNameLabelFromWireframes(wireframes) { 6416 return wireframes && wireframes.creativeNameLabel; 6417 } 6418 static getCustomAnalyticFields(wireframes) { 6419 return wireframes && wireframes.customAnalyticFields; 6420 } 6421 static getSnapshot(state, snapshot) { 6422 if (state.snapshots) return state.snapshots.byId[snapshot.snapshotId]; 6423 } 6424 static getSnapshotByNumber(state, projectName, snapshotNumber) { 6425 const snapshotId = StateReaderUtils.getSnapshotIdByNumber(projectName, snapshotNumber); 6426 return state.snapshots && state.snapshots.byId && state.snapshots.byId[snapshotId]; 6427 } 6428 static getSnapshotsFromState(state) { 6429 return state.snapshots; 6430 } 6431 static getSnapshots(snapshotsById, stageSnapshots) { 6432 let snapshots = [];
6433 if (stageSnapshots) stageSnapshots.forEach(function(stageSnapshot) { 6434 snapshots.push(snapshotsById[stageSnapshot.snapshotId]); 6435 }); 6436 return snapshots; 6437 } 6438 static getIsStageView(stage, version) { 6439 return !!(stage && stage !== "draft" || version); 6440 } 6441 static getIsViewOnly(state, stage, version) { 6442 return this.getIsStageView(stage, version) || this.getIsEditorsViewer(state); 6443 } 6444 static getSnapshotNumber(stageSnapshot) { 6445 return stageSnapshot.snapshotNumber; 6446 } 6447 static getSnapshotDate(stageSnapshot) { 6448 return stageSnapshot.promotedDate; 6449 } 6450 static getSnapshotName(stageSnapshot) { 6451 return stageSnapshot.snapshotName; 6452 } 6453 static getPromoteStatus(state) { 6454 if (state.versionManager) return state.versionManager.promoteStatus; 6455 return false; 6456 } 6457 static getRevertToVersion(state) { 6458 return state.revertToVersion; 6459 } 6460 static getSnapshotIdByNumber(projectName, snapshotNumber) { 6461 if (snapshotNumber && snapshotNumber > -1) return projectName + "/" + snapshotNumber; 6462 return ""; 6463 } 6464 static getSnapshotAssetsBySnapshotStage(assets, snapshots, project, stage) { 6465 let projectStageSnapshots = project && project[stage + "Snapshots"]; 6466 if (assets && projectStageSnapshots && projectStageSnapshots[0] && projectStageSnapshots[0].snapshotId && snapshots.byId[projectStageSnapshots[0].snapshotId] && snapshots.byId[projectStageSnapshots[0].snapshotId].assets) return snapshots.byId[projectStageSnapshots[0].snapshotId].assets.map((snapshotAsset) => { 6467 let assetId = StateReaderUtils.getAssetUniqueId(project.accountId, project.projectName, snapshotAsset.type, snapshotAsset.name); 6468 if (assets.byId[assetId]) snapshotAsset.title = assets.byId[assetId].title; 6469 return snapshotAsset; 6470 }); 6471 return []; 6472 } 6473 static getSnapshotAssetsBySnapshotVersion(assets, snapshots, project, version) { 6474 const versionSnapshotId = this.getSnapshotIdByNumber(project.projectName, version); 6475 if (assets && snapshots.byId[versionSnapshotId] && snapshots.byId[versionSnapshotId].assets) return snapshots.byId[versionSnapshotId].assets.map((snapshotAsset) => { 6476 let assetId = StateReaderUtils.getAssetUniqueId(project.accountId, project.projectName, snapshotAsset.type, snapshotAsset.name); 6477 if (assets.byId[assetId]) snapshotAsset.title = assets.byId[assetId].title; 6478 return snapshotAsset; 6479 }); 6480 return []; 6481 } 6482 static getLatestSnapshotIdForStage(project, stage) { 6483 const stageSnapshot = `${stage}Snapshots`; 6484 return project && project[stageSnapshot] && project[stageSnapshot][0] && project[stageSnapshot][0].snapshotId; 6485 } 6486 static getLatestSnapshotNumberForStage(state, projectName, stage) { 6487 return StateReaderUtils.getProject(state, projectName)?.[stage + "Snapshots"]?.[0]?.snapshotNumber; 6488 } 6489 static getWireframesUIVersionFromSnapshot({ state, projectName, version, stage }) { 6490 let snapshotId; 6491 if (version) snapshotId = StateReaderUtils.getSnapshotIdByNumber(projectName, version); 6492 else if (stage) { 6493 const project = StateReaderUtils.getProject(state, projectName); 6494 snapshotId = StateReaderUtils.getLatestSnapshotIdForStage(project, stage); 6495 } 6496 const snapshotAssets = StateReaderUtils.getSnapshotAssets(state, snapshotId); 6497 const wireframesUIAsset = snapshotAssets && snapshotAssets.find((asset) => asset.type === "wireframesUI"); 6498 return wireframesUIAsset && wireframesUIAsset.version; 6499 } 6500 static getSnapshotDetails(state, snapshotNumber) { 6501 return state.versions && state.versions.find((snapshot) => snapshot.snapshotNumber === snapshotNumber); 6502 } 6503 static getAllVersions(state) { 6504 return state.versions; 6505 } 6506 static getLatestVersionNumber(state, projectName) { 6507 if (state.versions && state.versions.length) { 6508 let versionNumbers = state.versions.map((version) => { 6509 return version.snapshotNumber; 6510 }); 6511 return Math.max(...versionNumbers); 6512 } else if (state.snapshots && state.snapshots.byId) { 6513 let versionNumbers = Object.values(state.snapshots.byId).reduce((acc, snapshot) => { 6514 if (snapshot.snapshotId.split("/")[0] === projectName) acc.push(snapshot.snapshotNumber); 6515 return acc; 6516 }, []); 6517 if (versionNumbers.length) return Math.max(...versionNumbers); 6518 } 6519 } 6520 static getSnapshotAssets(state, snapshotId) { 6521 return snapshotId ? state.snapshots.byId[snapshotId] && state.snapshots.byId[snapshotId].assets : []; 6522 } 6523 static getProjectStageSnapshots(state, projectName, stage) { 6524 let project = StateReaderUtils.getProject(state, projectName); 6525 if (project) { 6526 let stageSnapshots = project[stage + "Snapshots"]; 6527 if (stageSnapshots && stageSnapshots.length > 0) {
6528 const versionToNameMap = state.versions?.reduce((acc, version) => { 6529 acc[version.snapshotNumber] = version.snapshotName; 6530 return acc; 6531 }, {}) ?? {}; 6532 return stageSnapshots.map((stageSnapshot) => { 6533 return { 6534 ...stageSnapshot, 6535 snapshotName: versionToNameMap[stageSnapshot.snapshotNumber] 6536 }; 6537 }); 6538 } 6539 } 6540 return []; 6541 } 6542 static getDiffWireframes(state, projectName, version) { 6543 const projectDiffWireframes = state["diffwireframes"].byName[projectName]; 6544 return projectDiffWireframes && version ? projectDiffWireframes[version] : projectDiffWireframes; 6545 } 6546 static getDiffModel(state) { 6547 return state.diffModel; 6548 } 6549 static getAssetUniqueId(accountId, projectName, assetType, assetName) { 6550 return accountId + "/" + projectName + "/" + assetType + "/" + assetName; 6551 } 6552 static getAssetId(assetType, assetName) { 6553 return assetType + "/" + assetName; 6554 } 6555 static getAssets(state) { 6556 return state.assets; 6557 } 6558 static memoizeGetProjectAssets = index((stateProject, stateAssets) => { 6559 let assets = []; 6560 if (stateProject && stateProject.assets && stateAssets) stateProject.assets.forEach((assetId) => assets.push(stateAssets.byId[assetId])); 6561 return assets; 6562 }); 6563 static getProjectAssetsValidAsBackgroundAsset(stateProject, stateAssets) { 6564 return StateReaderUtils.memoizeGetProjectAssetsValidAsBackgroundAsset(stateProject, stateAssets); 6565 } 6566 static memoizeGetProjectAssetsValidAsBackgroundAsset = index((stateProject, stateAssets) => { 6567 return StateReaderUtils.memoizeGetLiveProjectAssetsByType(stateProject, stateAssets, ASSET_TYPES.curated).filter((asset) => asset.width === 640 && (asset.height === 360 || asset.height === 640)); 6568 }); 6569 static getLiveProjectAssetsByType(stateProject, stateAssets, assetType) { 6570 return StateReaderUtils.memoizeGetLiveProjectAssetsByType(stateProject, stateAssets, assetType); 6571 } 6572 static memoizeGetLiveProjectAssetsByType = index((stateProject, stateAssets, assetType) => { 6573 return StateReaderUtils.memoizeGetProjectAssetsByType(stateProject, stateAssets, assetType).filter((asset) => !asset.archived && !asset.deleted); 6574 }); 6575 static getProjectAssets(stateProject, stateAssets) { 6576 return StateReaderUtils.memoizeGetProjectAssets(stateProject, stateAssets); 6577 } 6578 static memoizeGetProjectAssetsByType = index((stateProject, stateAssets, assetType) => { 6579 let assets = []; 6580 if (stateProject && stateProject.assets && stateAssets) stateProject.assets.forEach(function(assetId) { 6581 if (stateAssets.byId[assetId].type === assetType) assets.push(stateAssets.byId[assetId]); 6582 }); 6583 return assets; 6584 }); 6585 static getProjectAssetsByType(stateProject, stateAssets, assetType) { 6586 return StateReaderUtils.memoizeGetProjectAssetsByType(stateProject, stateAssets, assetType); 6587 } 6588 static getProjectAssetsCount(stateProject, assetType) { 6589 assetType = assetType ? assetType : "all"; 6590 return stateProject && stateProject.totalAssetCount && stateProject.totalAssetCount[assetType] ? stateProject.totalAssetCount[assetType] : 0; 6591 } 6592 static getAssetsFromSnapshotOrDraft(program, stateAssets, stateSnapshots, stage, version, assetType) { 6593 if (version) return StateReaderUtils.getAssetsInVersionMode(program, stateAssets, stateSnapshots, version, assetType); 6594 else if (stage) return StateReaderUtils.getAssetsInStageMode(program, stateAssets, stateSnapshots, stage, assetType); 6595 else if (assetType) return StateReaderUtils.getProjectAssetsByType(program, stateAssets, assetType); 6596 else return StateReaderUtils.getProjectAssets(program, stateAssets); 6597 } 6598 static getAssetsInVersionMode(program, stateAssets, stateSnapshots, version, assetType) { 6599 let snapshotId = StateReaderUtils.getSnapshotIdByNumber(program.projectName, version); 6600 return StateReaderUtils._getAssetsAdjustedToSnapshot(program, stateAssets, stateSnapshots, snapshotId, assetType); 6601 } 6602 static getAssetsInStageMode(program, stateAssets, stateSnapshots, stage, assetType) { 6603 const stageSnapshots = program && program[stage + "Snapshots"]; 6604 const snapshotId = stageSnapshots && stageSnapshots[0] && stageSnapshots[0].snapshotId; 6605 return StateReaderUtils._getAssetsAdjustedToSnapshot(program, stateAssets, stateSnapshots, snapshotId, assetType); 6606 } 6607 static memoizeGetAssetsAdjustedToSnapshot = index((accountId, projectName, stateAssets, stateSnapshots, snapshotId, assetType) => { 6608 const snapshot = stateSnapshots.byId[snapshotId]; 6609 if (stateAssets && snapshot && snapshot.assets) { 6610 let assets = snapshot.assets.map((snapshotAsset) => { 6611 let assetId = StateReaderUtils.getAssetUniqueId(accountId, projectName, snapshotAsset.type, snapshotAsset.name); 6612 let asset = stateAssets.byId[assetId]; 6613 if (asset) return { 6614 ...asset, 6615 stageVersion: snapshotAsset.version, 6616 stageAssetItem: { ...snapshotAsset } 6617 }; 6618 return { 6619 ...snapshotAsset, 6620 stageAssetItem: snapshotAsset 6621 }; 6622 }); 6623 if (assetType) assets = assets.filter((asset) => asset.type === assetType); 6624 return assets; 6625 } 6626 return []; 6627 }); 6628 static _getAssetsAdjustedToSnapshot(program, stateAssets, stateSnapshots, snapshotId, assetType) { 6629 const { accountId, projectName } = program; 6630 return StateReaderUtils.memoizeGetAssetsAdjustedToSnapshot(accountId, projectName, stateAssets, stateSnapshots, snapshotId, assetType); 6631 } 6632 static getAsset(state, accountId, projectName, assetType, dynamoAssetName) { 6633 const assetUniqueId = StateReaderUtils.getAssetUniqueId(accountId, projectName, assetType, dynamoAssetName); 6634 const stateAsset = StateReaderUtils.getAssets(state).byId[assetUniqueId]; 6635 return stateAsset && { ...stateAsset }; 6636 } 6637 static getProjectMasterData(state, project, stage, version) { 6638 const wireframes = this.getWireFrame(state, project, stage, version); 6639 const masterScene = this.getProjectWireframesScene(wireframes, LogicContainers.Master); 6640 return masterScene && masterScene.sceneParts[0]; 6641 } 6642 static getProjectMasterAnimationGuidelineByName(state, project, name, stage, version) { 6643 const masterData = this.getProjectMasterData(state, project, stage, version); 6644 return (masterData && masterData.parameters || []).find((parameter) => parameter.name === name); 6645 } 6646 static getProjectWireframesScene(wireframe, sceneId) { 6647 return wireframe && wireframe.scenes[sceneId]; 6648 } 6649 static getProjectWireframesScenePart(wireframe, sceneId, scenePartIndex) { 6650 return wireframe && wireframe.scenes && wireframe.scenes[sceneId] && wireframe.scenes[sceneId].sceneParts && wireframe.scenes[sceneId].sceneParts[scenePartIndex]; 6651 } 6652 static getProjectWireframesScenePartById(wireframe, sceneId, scenePartId) { 6653 let scenePart; 6654 if (wireframe && wireframe.scenes && wireframe.scenes[sceneId] && wireframe.scenes[sceneId].sceneParts) scenePart = wireframe.scenes[sceneId].sceneParts.find((part) => part.scenePart === scenePartId); 6655 return scenePart; 6656 } 6657 static getProjectWireframesStories(state, projectName, stage, version) { 6658 let wireframes = this.getWireFrame(state, projectName, stage, version); 6659 if (!wireframes || !wireframes.stories) return; 6660 return wireframes.stories; 6661 } 6662 static getProjectWireframesStoriesArray(state, project, stage, version) { 6663 let storiesObj = this.getProjectWireframesStories(state, project, stage, version); 6664 if (!storiesObj) return; 6665 return Object.keys(storiesObj).map((storyId) => { 6666 return storiesObj[storyId]; 6667 }); 6668 } 6669 static getProjectWireframeScenes(state, project, stage, version) { 6670 let wireframes = this.getWireFrame(state, project, stage, version); 6671 return wireframes && wireframes.scenes ? wireframes.scenes : void 0; 6672 } 6673 static getProjectWireframeScenesArray(state, project, stage, version) { 6674 let scenesObj = this.getProjectWireframeScenes(state, project, stage, version); 6675 if (!scenesObj) return; 6676 return Object.keys(scenesObj).map((sceneId) => { 6677 return scenesObj[sceneId]; 6678 }); 6679 } 6680 static getProjectWireframeScenesIdsArray(state, project, stage, version) { 6681 let wireframes = this.getWireFrame(state, project, stage, version); 6682 if (!wireframes || !wireframes.scenes) return; 6683 return Object.keys(wireframes.scenes); 6684 } 6685 static getProjectWireframeNarrations(state, project, stage, version) { 6686 const wireframes = this.getWireFrame(state, project, stage, version); 6687 return wireframes && wireframes.narrations ? wireframes.narrations : void 0; 6688 }
6689 static getWireframesPathOnState(projectName, stage, version) { 6690 if (stage && stage !== "draft") { 6691 if (stage === "diff" && version) return [ 6692 "diffwireframes", 6693 "byName", 6694 projectName, 6695 version 6696 ]; 6697 return [ 6698 `${stage}wireframes`, 6699 "byName", 6700 projectName 6701 ]; 6702 } else if (version) return [ 6703 "versionwireframes", 6704 "byName", 6705 projectName 6706 ]; 6707 else return [ 6708 "wireframes", 6709 "byName", 6710 projectName 6711 ]; 6712 } 6713 static getWireFrame(state, programName, stage, version) { 6714 if (stage && stage !== "draft") { 6715 if (stage === "diff" && version) return StateReaderUtils.getDiffWireframes(state, programName, version); 6716 return state[`${stage}wireframes`].byName[programName]; 6717 } else if (version) return state["versionwireframes"].byName[programName]; 6718 else return state["wireframes"].byName[programName]; 6719 } 6720 static getWireframesGraphQLParentProgramVersionId(state, projectName) { 6721 if (state.wireframes.byName[projectName]) return state.wireframes.byName[projectName].graphQLParentProgramVersionId; 6722 } 6723 static serializeWireFrame(state, project, stage, version) { 6724 let serializedWireframe = { ...this.getWireFrame(state, project, stage, version) }; 6725 if (serializedWireframe.narrations) { 6726 serializedWireframe.narrations = { ...serializedWireframe.narrations }; 6727 serializedWireframe.narrations.byId = { ...serializedWireframe.narrations.byId }; 6728 Object.keys(serializedWireframe.narrations.byId).forEach((narrationId) => { 6729 let narrationState = serializedWireframe.narrations.byId[narrationId]; 6730 serializedWireframe.narrations.byId[narrationId] = { 6731 structure: NarrationsModelUtils.serializeStructure(narrationState.structure), 6732 variationDataMap: NarrationsModelUtils.serializeVariationDataMap(narrationState.variationDataMap) 6733 }; 6734 }); 6735 } 6736 return serializedWireframe; 6737 } 6738 static getProjectLogicItemsThatMayContainHotspot(state, programName, stage, version) { 6739 const wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 6740 return StateReaderUtils.getProjectLogicItemsThatMayContainHotspotInternal(wireframes.scenes, wireframes.logic); 6741 } 6742 static getProjectLogicItemsThatMayContainHotspotInternal = index((scenes, logicItems) => { 6743 return Object.keys(scenes).map((sceneId) => StateReaderUtils.getSceneLogicItemsThatMayContainHotspot(scenes[sceneId], logicItems[sceneId])).filter((logicItemsArray) => !!logicItemsArray).flat(); 6744 }); 6745 static getSceneLogicItemsThatMayContainHotspot = index((scene, sceneLogicItems) => { 6746 let logicItemsIds = /* @__PURE__ */ new Set(); 6747 scene.sceneParts.forEach((scenePart) => { 6748 scenePart[entityType.groups] && scenePart[entityType.groups].forEach((group) => logicItemsIds.add(group.id)); 6749 scenePart[entityType.prioritizedLists] && scenePart[entityType.prioritizedLists].forEach((list) => logicItemsIds.add(list.id)); 6750 scenePart[entityType.placeholders] && scenePart[entityType.placeholders].forEach((ph) => logicItemsIds.add(ph.name)); 6751 }); 6752 return Array.from(logicItemsIds).map((logicId) => sceneLogicItems[logicId]).filter((logicItem) => !!logicItem); 6753 }); 6754 static getPlaceHoldersTypes(scene, pHName) { 6755 let phTypes = []; 6756 if (scene) scene.sceneParts.forEach((scenePart) => { 6757 scenePart[placeholderType.onscreen].forEach((ph) => { 6758 if (ph.name === pHName) phTypes.push(ph.type); 6759 }); 6760 if (scenePart.groups) scenePart.groups.forEach((group) => { 6761 group.placeholders.forEach((ph) => { 6762 if (ph.name === pHName) phTypes.push(ph.type); 6763 }); 6764 }); 6765 if (scenePart[placeholderType.narration] && scenePart[placeholderType.narration].find((narration) => narration.name === pHName)) phTypes.push(placeholderType.narration); 6766 if (scenePart[placeholderType.parameter].find((parameter) => parameter.name === pHName)) phTypes.push(placeholderType.parameter); 6767 }); 6768 return phTypes; 6769 } 6770 static getScenePrioritizedList(wireframes, sceneId) { 6771 if (!wireframes || !wireframes.logic || !wireframes.logic[sceneId] || !wireframes.scenes[sceneId] || !wireframes.scenes[sceneId].sceneParts || !wireframes.scenes[sceneId].sceneParts.length) return []; 6772 const prioritizedListWireframesArray = wireframes.scenes[sceneId].sceneParts.reduce((acc, scenePart) => scenePart.prioritizedLists ? acc.concat(...scenePart.prioritizedLists) : acc, []); 6773 return Object.keys(wireframes.logic[sceneId]).map((id) => ({ 6774 ...wireframes.logic[sceneId][id], 6775 id 6776 })).filter((obj) => obj.outputType === LogicType.Prioritized).map((plLogic) => { 6777 const matchPl = prioritizedListWireframesArray.find((plWireFrames) => plWireFrames.id === plLogic.id); 6778 if (!matchPl) return; 6779 return { 6780 ...plLogic, 6781 name: matchPl.name, 6782 maxSlots: matchPl.slots.length, 6783 slots: matchPl.slots 6784 }; 6785 }).filter((item) => item !== void 0); 6786 } 6787 static getProjectPrioritizedLists(wireframes) { 6788 let prioritizedList = []; 6789 if (wireframes && wireframes.scenes) Object.keys(wireframes.scenes).forEac
6789h((sceneId) => { 6790 prioritizedList = prioritizedList.concat(StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 6791 }); 6792 return prioritizedList; 6793 } 6794 static getScenePlaceholders = index((wireframes, sceneId) => { 6795 const sceneParts = wireframes.scenes[sceneId] && wireframes.scenes[sceneId].sceneParts; 6796 if (!sceneParts || !Array.isArray(sceneParts)) return []; 6797 let placeholders = {}; 6798 sceneParts.forEach((scenePart) => { 6799 if (scenePart[placeholderType.onscreen] && scenePart[placeholderType.onscreen].length) scenePart[placeholderType.onscreen].forEach((ph) => { 6800 placeholders[ph.name] = { 6801 ...ph, 6802 source: placeholderType.onscreen 6803 }; 6804 }); 6805 if (scenePart[placeholderType.parameter] && scenePart[placeholderType.parameter].length) scenePart[placeholderType.parameter].forEach((pr) => { 6806 placeholders[pr.name] = { 6807 ...pr, 6808 source: placeholderType.parameter 6809 }; 6810 }); 6811 if (scenePart[entityType.groups] && scenePart[entityType.groups].length) scenePart[entityType.groups].forEach((grp) => { 6812 grp[entityType.placeholders].forEach((ph) => { 6813 placeholders[ph.name] = { 6814 ...ph, 6815 source: placeholderType.onscreen, 6816 groupId: grp.id 6817 }; 6818 }); 6819 }); 6820 }); 6821 return Object.values(placeholders); 6822 }); 6823 static getProjectPlaceholdersFromWireframes(wireframes) { 6824 const sceneIds = Object.keys(wireframes.scenes); 6825 let placeholders = []; 6826 sceneIds.forEach((sceneId) => { 6827 placeholders = placeholders.concat(StateReaderUtils.getScenePlaceholders(wireframes, sceneId)); 6828 }); 6829 return placeholders; 6830 } 6831 static getProjectNarrationParts = (wireframes) => { 6832 let narrationParts = []; 6833 if (wireframes && wireframes.scenes) Object.values(wireframes.scenes).forEach((scene) => { 6834 if (scene && scene.sceneParts) scene.sceneParts.forEach((scenePart) => { 6835 if (scenePart && scenePart.NarrationParts) scenePart.NarrationParts.forEach((narrationPart) => { 6836 if (narrationPart) narrationParts.push({ 6837 ...narrationPart, 6838 sceneId: scene.id, 6839 scenePartId: scenePart.scenePart 6840 }); 6841 }); 6842 }); 6843 }); 6844 return narrationParts; 6845 }; 6846 static getNarrationsVersion = (wireframes) => { 6847 return wireframes && typeof wireframes.narrationsVersion === "number" ? wireframes.narrationsVersion : 0; 6848 }; 6849 static getNarrationsVersionFromState = (state, projectName, stage, version) => { 6850 const wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 6851 return StateReaderUtils.getNarrationsVersion(wireframes); 6852 }; 6853 static memoizeAddGetterForValueSet = index((dataElements, derivedLogic, dynamicValueSetData) => { 6854 let effectiveDerivedLogic = derivedLogic || {}; 6855 let effectiveDataElements = dataElements || []; 6856 let getDataElementsWithGetter; 6857 let dataElementsWithGetter = effectiveDataElements.map((dataElement) => { 6858 return changeGetterForValueSet(dataElement, () => { 6859 if (dataElement.origin === DataElementOrigins.Derived) { 6860 let logicID = getDerivedDataElementLogicId(dataElement); 6861 return createLogic(effectiveDerivedLogic[logicID] || {}).getValueSet({ 6862 dataElements: getDataElementsWithGetter(), 6863 derivedLogic 6864 }); 6865 } else if (dataElement.origin === DataElementOrigins.System) if (dataElement.valueSet) { 6866 let staticValueSet = dataElement.valueSet; 6867 let dynamicValueSet = dynamicValueSetData[dataElement.id]; 6868 if (dynamicValueSet) staticValueSet = staticValueSet.concat(dynamicValueSet); 6869 return staticValueSet.map((value) => typeof value === "string" ? { 6870 id: "_bc_system_" + value.toLowerCase(), 6871 dn: value 6872 } : value); 6873 } else return null; 6874 else if (dataElement.type === DataElementContentTypes.Boolean) return [{ 6875 id: "_boolean_false", 6876 dn: "false" 6877 }, { 6878 id: "_boolean_true", 6879 dn: "true" 6880 }]; 6881 else { 6882 if (isValueSetSupportedForDataElementType(dataElement) && dataElement.useValueSet && dataElement.valueSet) return dataElement.valueSet.map((value) => typeof value === "string" ? { 6883 id: "_bc_" + value.toLowerCase(), 6884 dn: value 6885 } : value); 6886 return null; 6887 } 6888 }); 6889 }); 6890 getDataElementsWithGetter = () => dataElementsWithGetter; 6891 return dataElementsWithGetter; 6892 }); 6893 static getProjectDataElements(state, projectName, stage, version) { 6894 let wireFrames = StateReaderUtils.getWireFrame(state, projectName, stage, version); 6895 return StateReaderUtils.getProjectDataElementsFromWireframes(wireFrames); 6896 } 6897 static getProjectPrioritizedListsFromWireframes(wireframes) { 6898 if (!wireframes || !wireframes.logic || !wireframes.scenes) return []; 6899 const scenesLogicById = Object.keys(wireframes.scenes).map((sceneId) => wireframes.logic[sceneId]).reduce((acc, item) => Object.assign(acc, item), {}); 6900 return Object.keys(scenesLogicById).filter((key) => scenesLogicById[key].outputType === LOGIC_CONTEXT.Prioritized).map((plId) => ({ 6901 ...scenesLogicById[plId], 6902 id: plId 6903 })); 6904 } 6905 static getProjectDataElementsFromWireframes(wireframes) { 6906 let dataElements = wireframes && wireframes.dataElements; 6907 let derivedLogic = StateReaderUtils.getAllProgramLogicFromWireframes(wireframes, LogicContainers.Derived); 6908 let dynamicValueSetData = DynamicValueSetSelector.buildDynamicValueSetData(wireframes, StateReaderUtils.getStoriesAsArray); 6909 return StateReaderUtils.memoizeAddGetterForValueSet(dataElements, derivedLogic, dynamicValueSetData); 6910 } 6911 static getProjectWireframesSceneInputLogic(state, project, sceneId, inputName, stage, version) { 6912 let wireframes = this.getWireFrame(state, project, stage, version); 6913 return wireframes && wireframes.logic && wireframes.logic[sceneId] ? wireframes.logic[sceneId][inputName] : void 0; 6914 } 6915 static getDecisionPointLogicItemsForStory(state, projectName, storyId, stage, version) { 6916 let wireframes = this.getWireFrame(state, projectName, stage, version); 6917 return StateReaderUtils.getDecisionPointLogicItemsForStoryFromWireframes(wireframes, storyId); 6918 } 6919 static getDecisionPointLogicItemsForStoryFromWireframes(wireframes, storyId) { 6920 return wireframes && wireframes.logic && wireframes.logic[LogicContainers.Story] && wireframes.logic[LogicContainers.Story][storyId] && wireframes.logic[LogicContainers.Story][storyId][LogicContainers.DecisionPoint] || {}; 6921 } 6922 static getStoryLogicItems(state, projectName, storyId, stage, version) { 6923 let wireframes = this.getWireFrame(state, projectName, stage, version); 6924 return wireframes && wireframes.logic && wireframes.logic[LogicContainers.Story] && wireframes.logic[LogicContainers.Story][storyId] || {}; 6925 }
6926 static getStoryBackgroundAssetLogic(state, projectName, storyId, stage, version) { 6927 let wireframes = this.getWireFrame(state, projectName, stage, version); 6928 return this.getStoryBackgroundAssetLogicFromWireframe(wireframes, storyId); 6929 } 6930 static getStoryBackgroundAssetLogicFromWireframe(wireframes, storyId) { 6931 let story = this.getStoryById(wireframes, storyId); 6932 if (!story || !story.backgroundAssetType) return {}; 6933 return this.getStoryLogicItemFromWireframeByType(wireframes, storyId, LogicContainers.BackgroundAsset, story.backgroundAssetType); 6934 } 6935 static getStorySoundtrackLogic(state, projectName, storyId, stage, version) { 6936 let wireframes = this.getWireFrame(state, projectName, stage, version); 6937 return this.getStorySoundtrackLogicFromWireframe(wireframes, storyId); 6938 } 6939 static getStoryVideoRatioQualityLogic(state, projectName, storyId, stage, version) { 6940 let wireframes = this.getWireFrame(state, projectName, stage, version); 6941 return this.getStoryVideoRatioQualityLogicWireframe(wireframes, storyId); 6942 } 6943 static getStorySoundtrackLogicFromWireframe(wireframes, storyId) { 6944 return this.getStoryLogicItemFromWireframeByType(wireframes, storyId, LogicContainers.Soundtrack, MediaTypes.Audio); 6945 } 6946 static getStoryVideoRatioQualityLogicWireframe(wireframes, storyId) { 6947 return this.getStoryLogicItemFromWireframeByType(wireframes, storyId, LogicContainers.VideoSettings, LogicContext.StoryRatioAndQuality); 6948 } 6949 static getStoryLogicItemFromWireframeByType(wireframes, storyId, logicType, logicId) { 6950 return wireframes && wireframes.logic && wireframes.logic[LogicContainers.Story] && wireframes.logic[LogicContainers.Story][storyId] && wireframes.logic[LogicContainers.Story][storyId][logicType] && wireframes.logic[LogicContainers.Story][storyId][logicType][logicId] || {}; 6951 } 6952 static getDecisionPointsLogic(state, projectName, storyId, decisionPointId, stage, version) { 6953 return StateReaderUtils.getDecisionPointLogicItemsForStory(state, projectName, storyId, stage, version)[decisionPointId]; 6954 } 6955 static getInputLogicFromStateProjectLogic(project, sceneId, inputName) { 6956 return project && project[sceneId] ? project[sceneId][inputName] : void 0; 6957 } 6958 static getProgramStorySelectionLogic(state, projectName, stage, version) { 6959 let wireframes = this.getWireFrame(state, projectName, stage, version); 6960 return StateReaderUtils.getProgramLogicItemFromWireframeByType(wireframes, LogicContainers.StorySelection, LogicContainers.StorySelection); 6961 } 6962 static getAllProgramLogicItemsFromWireframeByType(wireframes, logicType) { 6963 return wireframes && wireframes.logic && wireframes.logic[LogicContainers.Program] && wireframes.logic[LogicContainers.Program][logicType]; 6964 } 6965 static getProgramLogicItemFromWireframeByType(wireframes, logicType, logicId) { 6966 return wireframes && wireframes.logic && wireframes.logic[LogicContainers.Program] && wireframes.logic[LogicContainers.Program][logicType] && wireframes.logic[LogicContainers.Program][logicType][logicId]; 6967 } 6968 static getProgramLogicItems(state, projectName, stage, version) { 6969 let wireframes = this.getWireFrame(state, projectName, stage, version); 6970 return wireframes && wireframes.logic && wireframes.logic[LogicContainers.Program]; 6971 } 6972 static getProjectWireframesLogic(state, projectName, stage, version) { 6973 let wireframes = this.getWireFrame(state, projectName, stage, version); 6974 return wireframes && wireframes.logic ? wireframes.logic : void 0; 6975 } 6976 static getAllProgramLogic(state, programName, container, stage, version) { 6977 let wireframes = this.getWireFrame(state, programName, stage, version); 6978 return StateReaderUtils.getAllProgramLogicFromWireframes(wireframes, container); 6979 } 6980 static getAllProgramLogicFromWireframes(wireframes, container) { 6981 if (!wireframes || !wireframes.logic || !wireframes.logic[container]) return; 6982 return wireframes.logic[container]; 6983 } 6984 static getCustomAnalyticsFieldData(programWireframes, fieldName) { 6985 if (!programWireframes || !programWireframes.logic || !programWireframes.logic[LogicContainers.Analytics]) return; 6986 return programWireframes.logic[LogicContainers.Analytics][fieldName]; 6987 } 6988 static getCustomAnalyticsParticipatingDataElements(programWireframes, dataElements) { 6989 const analyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(programWireframes); 6990 if (!analyticsFieldsArray || !programWireframes || !programWireframes.logic || !programWireframes.logic[LogicContainers.Analytics]) return; 6991 let analyticsDataElements = []; 6992 analyticsFieldsArray.forEach((analyticFieldKey) => { 6993 let analyticFieldData = StateReaderUtils.getCustomAnalyticsFieldData(programWireframes, analyticFieldKey); 6994 const dataElement = analyticFieldData && findDataElementByLogicValue(analyticFieldData.defaultValue, dataElements); 6995 const dataElementId = dataElement && getDataElementId(dataElement); 6996 if (dataElementId && !analyticsDataElements.includes(dataElementId)) analyticsDataElements.push(dataElementId); 6997 }); 6998 return analyticsDataElements; 6999 } 7000 static getCustomAnalyticsFieldsArray(programWireframes) { 7001 if (!programWireframes) return; 7002 if (programWireframes.customAnalyticsOrder) return programWireframes.customAnalyticsOrder; 7003 if (!programWireframes.stories) return; 7004 const firstStoryId = Object.keys(programWireframes.stories)[0]; 7005 if (!firstStoryId) return; 7006 return programWireframes.stories[firstStoryId].customAnalyticsOrder; 7007 } 7008 static getElementTypeFromElement(element) { 7009 if (element.endsWith("_animation")) return "animation"; 7010 else if (element.endsWith("_nextScene")) return "next scene"; 7011 else if (element.endsWith("_validation")) return "validation"; 7012 else return "placeholder"; 7013 } 7014 static getDerivedLogicCycles(wireframes) { 7015 return wireframes && wireframes.derivedLogicCycles || []; 7016 } 7017 static getDerivedLogicCyclesFromWireframes(state, programName, stage, version) { 7018 const wireframes = StateReaderUtils.getWireFrame(state, programName, stage, version); 7019 return wireframes && wireframes.derivedLogicCycles || []; 7020 } 7021 static isLogicContainerAScene(logicContainer) { 7022 return /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/.test(logicContainer); 7023 } 7024 static getImageThumbnail(state) { 7025 return state.imageThumbnail; 7026 } 7027 static getSecondImageUrl(state) { 7028 return state.secondImageUrl; 7029 } 7030 static getSecondImageThumbnail(state) { 7031 return state.secondImageThumbnail; 7032 } 7033 static getAnalyticsEmbedContainerChartUrl(state) { 7034 return state.analyticsEmbedContainerChartUrl; 7035 } 7036 static getdtaasEndPoint(state) { 7037 return state.dtaasEndPoint; 7038 } 7039 static getResolverEndPoint(state) { 7040 return state.resolverEndPoint; 7041 } 7042 static getNarrationServerEndpoint(state) { 7043 return state.narrationServerEndpoint; 7044 } 7045 static getMockNarrationServerEndpoint(state) { 7046 return state.mockNarrationServerEndpoint; 7047 } 7048 static getActivePresetId(state, projectName) { 7049 if (state.activePresetId && state.activePresetId !== "creatives_preset_id") return state.activePresetId; 7050 const presets = state.presets && state.presets.byName[projectName] || {}; 7051 return Object.keys(presets).reduce((acc, presetId) => { 7052 if (presetId !== "creatives_preset_id" && (!acc || presets[presetId].name < presets[acc].name)) return presetId; 7053 return acc; 7054 }, void 0); 7055 } 7056 static getPresets(state, projectName) { 7057 return StateReaderUtils.memoizeFilterPresets(state.presets.byName[projectName]); 7058 } 7059 static memoizeFilterPresets(statePresets) { 7060 return (0, import_lodash.pickBy)(statePresets, (presetValue) => presetValue.id !== CREATIVES_PRESET_ID); 7061 } 7062 static getPresetById(state, project, id) { 7063 return state.presets.byName[project]?.[id]; 7064 } 7065 static getCreativePreset(state, project) { 7066 return state.presets.byName[project]?.[CREATIVES_PRESET_ID]; 7067 } 7068 static getActiveAccount(state) { 7069 return state.accounts && state.accounts.byId[state.activeAccountId]; 7070 } 7071 static isEditorAccount(state) { 7072 return state.activeAccountId === EDITOR_ACCOUNT_ID; 7073 } 7074 static getActiveAccountId(state) { 7075 return state.activeAccountId; 7076 } 7077 static getUserName(state) { 7078 return state.userName; 7079 } 7080 static getUserRoles(state) { 7081 return state.userRoles; 7082 } 7083 static memoizeGetAccountsFromState = index((stateAccounts) => { 7084 return stateAccounts.allIds.map((accountId) => stateAccounts.byId[accountId]); 7085 }); 7086 static getAccountsFromState(state) { 7087 return StateReaderUtils.memoizeGetAccountsFromState(state.accounts); 7088 } 7089 static memoizeGetAccountsNames = index((stateAccounts) => { 7090 return stateAccounts.allIds.map((accountId) => stateAccounts.byId[accountId].displayName); 7091 }); 7092 static getAccountsNames(state) { 7093 return StateReaderUtils.memoizeGetAccountsNames(state.accounts); 7094 } 7095 static memoizeGetAccounts = index((stateAccounts) => { 7096 return stateAccounts.allIds.map((accountId) => stateAccounts.byId[accountId]); 7097 }); 7098 static getAccounts(stateAccounts) { 7099 return StateReaderUtils.memoizeGetAccounts(stateAccounts); 7100 } 7101 static getAccountVideoViews(state) { 7102 return state.accountVideoViews; 7103 } 7104 static getUsers(state) { 7105 return state.users.allNames; 7106 } 7107 static getAvailableRoles(state) { 7108 return state.users.roles; 7109 } 7110 static getSelectedUser(state) { 7111 return state.users.selectedUser; 7112 } 7113 static getAccountDisplayName(stateAccount) { 7114 return stateAccount.displayName; 7115 } 7116 static getAccountId(stateAccount) { 7117 return stateAccount.accountId; 7118 } 7119 static getTableauBaseURL(state) { 7120 return state.tableauBaseURL; 7121 } 7122 static getTableauWorkbookName(state) { 7123 return state.tableauWorkbookName; 7124 } 7125 static isFetchingUser(state) { 7126 return state.admin.isFetchingUser; 7127 } 7128 static isSettingFeatureFlag(state) { 7129 return state.admin.isSettingFeatureFlag; 7130 } 7131 static isLoadingUsers(state) { 7132 return state.admin.isLoadingUsers; 7133 } 7134 static isLoadingAllProjects(state) { 7135 return state.admin.isLoadingAllProjects; 7136 } 7137 static getSuccessMessage(state) { 7138 return state.users.successMessage; 7139 } 7140 static getWarningMessage(state) { 7141 return state.users.warningMessage; 7142 } 7143 static getIsEditorsViewer(state) { 7144 let userRoles = StateReaderUtils.getUserRoles(state); 7145 return isPermitted(userRoles, permissions.getProjects) && !isPermitted(userRoles, permissions.editProjects); 7146 } 7147 static isCampaignViewOnly(state) { 7148 let userRoles = StateReaderUtils.getUserRoles(state); 7149 return isPermitted(userRoles, permissions.adsGetCampaignSettings) && !isPermitted(userRoles, permissions.adsEditCampaignSettings); 7150 } 7151 static isExperimentManagerViewOnly(state) { 7152 let userRoles = StateReaderUtils.getUserRoles(state); 7153 return isPermitted(userRoles, permissions.viewBuilderReports) && isPermitted(userRoles, permissions.editReports) && !isPermitted(userRoles, permissions.editProjects); 7154 } 7155 static isAllowedCampaignSetting(state) { 7156 let userRoles = StateReaderUtils.getUserRoles(state) || []; 7157 return isPermitted(userRoles, permissions.adsGetCampaignSettings) || isPermitted(userRoles, permissions.adsEditCampaignSettings); 7158 } 7159 static isAllowedDetailedReport(state) { 7160 let userRoles = StateReaderUtils.getUserRoles(state) || []; 7161 return isPermitted(userRoles, permissions.viewBuilderReports) || isPermitted(userRoles, permissions.viewEditorReports); 7162 } 7163 static isAllowedExperiments(state) { 7164 return isPermitted(StateReaderUtils.getUserRoles(state) || [], permissions.getExperiments); 7165 } 7166 static getNarrationPostgresId(wireframes, narrationId) { 7167 return wireframes.narrations.byId[narrationId] && (wireframes.narrations.byId[narrationId].postgresNarrationId || narrationId); 7168 } 7169 static getNarrationTableUpdating(wireframes, narrationId) { 7170 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].updating; 7171 } 7172 static getNarrationTableDimensions(wireframes, narrationId) { 7173 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].dimensions; 7174 } 7175 static getNarrationTableVariations(wireframes, narrationId) { 7176 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].variations; 7177 } 7178 static getNarrationTableRepresentativeKey(wireframes, narrationId) { 7179 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].structure.representativeKey; 7180 } 7181 static getNarrationTableCreativeOverride(wireframes, narrationId) { 7182 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].structure.creativeOverride; 7183 } 7184 static getNarrationTableDataElements(wireframes, narrationId) { 7185 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].structure.stack.filter((layer) => layer.valueSetSource === "DataElements").map((layer) => layer.valueSetId); 7186 } 7187 static getNarrationTablePrioritizedListProviders(wireframes, narrationId) { 7188 return wireframes.narrations.byId[narrationId] && wireframes.narrations.byId[narrationId].structure.stack.filter((layer) => layer.valueSetSource === "candidateNames" || layer.valueSetSource === "numberOfValidSlots").map((layer) => layer.valueSetId); 7189 } 7190 static getNarrationTableOverrideIds(wireframes, narrationId) { 7191 let overrideIds = /* @__PURE__ */ new Set(); 7192 StateReaderUtils.getNarrationTableVariations(wireframes, narrationId).forEac
7192h((variation) => { 7193 if (variation && variation.variationData && variation.variationData.overrideId) overrideIds.add(variation.variationData.overrideId); 7194 }); 7195 return Array.from(overrideIds); 7196 } 7197 static getNarrationDefaultText(wireframes, narrationId) { 7198 let entry = StateReaderUtils.getNarrationDefaultTextEntry(wireframes, narrationId); 7199 if (entry) return entry[1].variationData.text; 7200 return ""; 7201 } 7202 static getNarrationDefaultTextKey(wireframes, narrationId) { 7203 let entry = StateReaderUtils.getNarrationDefaultTextEntry(wireframes, narrationId); 7204 if (entry) return entry[0]; 7205 } 7206 static getNarrationDefaultTextEntry(wireframes, narrationId) { 7207 let variations = StateReaderUtils.getNarrationTableVariations(wireframes, narrationId); 7208 if (variations) return variations.findEntry((variation) => variation.variationData.text && !variation.variationData.muted) || variations.entrySeq().first(); 7209 } 7210 static getNarrationName(wireframes, sceneId, narrationId) { 7211 let scene = StateReaderUtils.getProjectWireframesScene(wireframes, sceneId); 7212 return StateReaderUtils.getNarrationNameInScene(scene, narrationId); 7213 } 7214 static getNarrationIndexInScene(scene, narrationId) { 7215 let scenePartIndex = 0; 7216 let narrationIndex = -1; 7217 let scenePart = scene.sceneParts && scene.sceneParts[scenePartIndex]; 7218 while (scenePart) scenePart = scenePart[placeholderType.narration].some((narrationPart) => { 7219 ++narrationIndex; 7220 return narrationPart.id === narrationId; 7221 }) ? void 0 : scene.sceneParts && scene.sceneParts[++scenePartIndex]; 7222 return narrationIndex; 7223 } 7224 static getNarrationNameInScene(scene, narrationId) { 7225 let narrationIndex = this.getNarrationIndexInScene(scene, narrationId); 7226 if (narrationIndex > -1) return "Narrations." + (0, import_number_to_letter.default)(narrationIndex); 7227 else return; 7228 } 7229 static getNarrationLetterInScene(scene, narrationId) { 7230 let narrationIndex = this.getNarrationIndexInScene(scene, narrationId); 7231 if (narrationIndex > -1) return (0, import_number_to_letter.default)(narrationIndex); 7232 else return; 7233 } 7234 static getLastRelevantNarrationUpdateTimeStamp(state) { 7235 return state.lastRelevantNarrationUpdateTimeStamp; 7236 } 7237 static getShowMutedNarrationRows(state) { 7238 return state.showMutedNarrationRows; 7239 } 7240 static getShowNarrationNoteColumn(state) { 7241 return state.showNarrationNoteColumn; 7242 } 7243 static getShowNarrationStatusColumn(state) { 7244 return state.showNarrationStatusColumn; 7245 } 7246 static getNarrator(wireframes, storyId) { 7247 if (storyId) return wireframes.stories[storyId] && wireframes.stories[storyId].narrator; 7248 else if (!StateReaderUtils.getStoriesVersionFromWireframes(wireframes)) { 7249 let defaultStoryId = Object.keys(wireframes.stories)[0]; 7250 return wireframes.stories[defaultStoryId].narrator; 7251 } else return null; 7252 } 7253 static getAllNarrationIds(wireframes) { 7254 return wireframes.narration.allIds; 7255 } 7256 static getSceneIdOfNarration(wireframes, narrationId) { 7257 return Object.keys(wireframes.scenes).find((sceneId) => { 7258 return wireframes.scenes[sceneId].sceneParts.some((scenePart) => { 7259 return scenePart.NarrationParts?.some((narration) => narration.id === narrationId); 7260 }); 7261 }); 7262 } 7263 static getStories(wireframes) { 7264 return wireframes && wireframes.stories; 7265 } 7266 static getStoriesAsArray(wireframes) { 7267 let stories = StateReaderUtils.getStories(wireframes); 7268 let storiesArray = []; 7269 if (stories) for (let storyField in stories) storiesArray.push(stories[storyField]); 7270 return storiesArray; 7271 } 7272 static getStoryById(wireframes, storyId) { 7273 return wireframes && wireframes["stories"] && wireframes["stories"][storyId]; 7274 } 7275 static getStoryGqlId = (state, projectName, storyId) => { 7276 return StateReaderUtils.getStoryById(StateReaderUtils.getWireFrame(state, projectName), storyId).graphQLId; 7277 }; 7278 static getProjectRecordingDocs(state) { 7279 return state.recordingDocs || []; 7280 } 7281 static enableHubStickyBarLogoMenu(state) { 7282 return state.enableHubStickyBarLogoMenu; 7283 } 7284 static getBreadCrumbsArray(state) { 7285 return state.breadCrumbsArray; 7286 } 7287 static getHubStickyBarLogoMenuItemsArray(state) { 7288 return state.hubStickyBarLogoMenuItemsArray; 7289 } 7290 static getStudioProgramsDrawerFilter(state) { 7291 return state.studioProgramsDrawerFilter; 7292 } 7293 static getMiddlePanelCollapsed(state) { 7294 return state.middlePanelCollapsed; 7295 } 7296 static isStateError(state) { 7297 return state.error; 7298 } 7299 static getStateError(state) { 7300 return state.errorMessage; 7301 } 7302 static getStateErrorStack(state) { 7303 return state.errorStackMessage; 7304 } 7305 static getStateErrorRest(state) { 7306 return state.errorRestUrl; 7307 } 7308 static getPageTitle(state) { 7309 return state.pageTitle; 7310 } 7311 static getLoadingCount(state) { 7312 return state.loadingCount; 7313 } 7314 static isSoftLoading(state) { 7315 return state.softLoading; 7316 } 7317 static getLoadingProgress(state) { 7318 return state.loadingProgress; 7319 } 7320 static getLoadingUpdateNarrationLibrary(state) { 7321 return state.loadingUpdateNarrationLibrary; 7322 } 7323 static getDataLibrarySelectedTabId(state) { 7324 return state.dataLibrarySelectedTabId || 0; 7325 }
7326 static memoizeGetLogicErrorsAndWarnings = index((wireframes, projectAssets, currentRFR) => { 7327 let errors = []; 7328 let warnings = []; 7329 if (wireframes) { 7330 let { logic, stories, scenes } = wireframes; 7331 let storiesScenes = stories ? Object.keys(Object.values(stories).reduce((acc, story) => { 7332 if (story.lineup) story.lineup.forEach((sceneId) => acc[sceneId] = sceneId); 7333 return acc; 7334 }, {})) : []; 7335 if (logic) { 7336 if (scenes) { 7337 const updateErrors = ({ sceneName, scenePartIndex, wireframesEntity, sceneLogic, entitySelector = "id", entityType }) => { 7338 if (wireframesEntity) { 7339 let entityLogic = sceneLogic[wireframesEntity[entitySelector]]; 7340 let entityLogicValidation = entityLogic && entityLogic.validation; 7341 if (entityLogicValidation) { 7342 if (entityLogicValidation.status === VALIDATION_STATUS.Invalid) errors.push(`Error in scene ${sceneName} Part #${scenePartIndex} with ${entityType} ${wireframesEntity.name} logic`); 7343 else if (entityLogicValidation.status === VALIDATION_STATUS.Partial) warnings.push(`Warning in scene ${sceneName} Part #${scenePartIndex} with ${entityType} ${wireframesEntity.name} logic`); 7344 } 7345 } 7346 }; 7347 storiesScenes.forEach((sceneId) => { 7348 let scene = scenes[sceneId]; 7349 let sceneLogic = logic[sceneId]; 7350 if (storiesScenes.includes(sceneId) && sceneLogic) { 7351 if (scene.sceneParts) scene.sceneParts.forEach((scenePart, index) => { 7352 if (scenePart.placeholders) scenePart.placeholders.forEach((placeholder) => { 7353 updateErrors({ 7354 sceneName: scene.name, 7355 scenePartIndex: index + 1, 7356 wireframesEntity: placeholder, 7357 entityType: "placeholder", 7358 entitySelector: "name", 7359 sceneLogic 7360 }); 7361 }); 7362 if (scenePart.groups) scenePart.groups.forEach((group) => { 7363 updateErrors({ 7364 sceneName: scene.name, 7365 scenePartIndex: index + 1, 7366 wireframesEntity: group, 7367 entityType: "group", 7368 sceneLogic 7369 }); 7370 }); 7371 if (scenePart.prioritizedLists) scenePart.prioritizedLists.forEach((prioritizedList) => { 7372 updateErrors({ 7373 sceneName: scene.name, 7374 scenePartIndex: index + 1, 7375 wireframesEntity: prioritizedList, 7376 entityType: "prioritized list", 7377 sceneLogic 7378 }); 7379 }); 7380 });
7381 Object.keys(sceneLogic).forEach((element) => { 7382 let scenePartValidation = sceneLogic[element].validation; 7383 if (scenePartValidation && scenePartValidation.status !== VALIDATION_STATUS.valid) { 7384 let elementType = StateReaderUtils.getElementTypeFromElement(element); 7385 if (["animation", "validation"].includes(elementType)) { 7386 if (scenePartValidation.status === VALIDATION_STATUS.Invalid && elementType !== "animation") errors.push(`Error in scene ${scene.name} with ${elementType} logic`); 7387 else if (scenePartValidation.status === VALIDATION_STATUS.Partial || scenePartValidation.status === VALIDATION_STATUS.Invalid && elementType === "animation") warnings.push(`Warning in scene ${scene.name} with ${elementType} logic`); 7388 } 7389 } 7390 }); 7391 } 7392 }); 7393 } 7394 const analyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(wireframes); 7395 if (analyticsFieldsArray) analyticsFieldsArray.forEach((analyticFieldKey, index) => { 7396 let analyticFieldData = StateReaderUtils.getCustomAnalyticsFieldData(wireframes, analyticFieldKey); 7397 if (analyticFieldData && analyticFieldData.isNew) errors.push(`Error - Missing field name in custom field #${index + 1} in Analytics Settings`); 7398 let analyticsFieldValidation = analyticFieldData && analyticFieldData.validation; 7399 if (analyticsFieldValidation && analyticsFieldValidation.status !== VALIDATION_STATUS.valid) { 7400 if (analyticsFieldValidation.status === VALIDATION_STATUS.Invalid) errors.push(`Error in custom field #${index + 1} in Analytics Settings`); 7401 else if (analyticsFieldValidation.status === VALIDATION_STATUS.Partial) warnings.push(`Warning in custom field #${index + 1} in Analytics Settings`); 7402 } 7403 }); 7404 let derivedLogic = logic[LogicContainers.Derived]; 7405 let dataElements = wireframes && wireframes.dataElements || [];
7406 if (derivedLogic) Object.keys(derivedLogic).forEach((derivedDataElementKey) => { 7407 let derivedDataElement = getDataElementFromDerivedKey(derivedDataElementKey, dataElements); 7408 if (derivedDataElement) { 7409 let derivedValidation = derivedLogic[derivedDataElementKey].validation; 7410 if (derivedValidation && derivedValidation.status !== VALIDATION_STATUS.valid) { 7411 let derivedDataElementDisplayName = getDataElementDisplayName(derivedDataElement); 7412 if (derivedValidation.status === VALIDATION_STATUS.Invalid) errors.push(`Error in Studio Data Element ${derivedDataElementDisplayName} logic`); 7413 else if (derivedValidation.status === VALIDATION_STATUS.Partial) warnings.push(`Warning in Studio Data Element ${derivedDataElementDisplayName} logic`); 7414 } 7415 } 7416 }); 7417 } 7418 } 7419 if (projectAssets) { 7420 let excludedTypes = [ 7421 sceneAssetType, 7422 storyAssetType, 7423 wireFramesAssetType 7424 ]; 7425 let pendingAssets = projectAssets.filter((asset) => !excludedTypes.includes(asset.type.toLowerCase()) && !asset.archived && asset.version === 0 && (asset.type !== ASSET_TYPES.recording || asset.RFR >= currentRFR)).map((asset) => asset.title || asset.filename); 7426 let pendingCount = pendingAssets.length; 7427 if (pendingCount > 0) if (pendingCount === 1) warnings.push(`There is 1 asset request: ${pendingAssets[0]}`); 7428 else warnings.push(`There are ${pendingCount} asset requests${pendingCount > 3 ? ", including" : ""}: ${pendingAssets.slice(0, 3).join(", ")}${pendingCount > 3 ? ", ..." : ""}`); 7429 } 7430 return { 7431 errors, 7432 warnings 7433 }; 7434 }); 7435 static getLogicErrorsAndWarnings(wireframes, projectAssets, currentRFR) { 7436 return StateReaderUtils.memoizeGetLogicErrorsAndWarnings(wireframes, projectAssets, currentRFR); 7437 } 7438 static getProjectsForAllAccounts(state) { 7439 return state.admin.allProjects; 7440 } 7441 static getFrameworkProgram(state, programId) { 7442 return state.frameworkEditor.byId[programId] || null; 7443 } 7444 static getProgramSummaries(state) { 7445 return state.projectSummaries; 7446 } 7447 static getUsedProgramNames(state) { 7448 return StateReaderUtils.getProgramSummaries(state).reduce((usedProgramNames, programSummary) => { 7449 usedProgramNames.add(programSummary.displayName.toLocaleLowerCase()); 7450 programSummary.projectIds.builders && usedProgramNames.add(programSummary.projectIds.builders.toLocaleLowerCase()); 7451 programSummary.postgresName && usedProgramNames.add(programSummary.postgresName.toLocaleLowerCase()); 7452 return usedProgramNames; 7453 }, /* @__PURE__ */ new Set()); 7454 } 7455 static getIsFrameworkViewer(state) { 7456 let userRoles = StateReaderUtils.getUserRoles(state); 7457 return isPermitted(userRoles, permissions.getFramework) && !isPermitted(userRoles, permissions.deleteEntity) && !isPermitted(userRoles, permissions.updateEntity); 7458 } 7459 static getIsEditorViewer(state) { 7460 return !isPermitted(StateReaderUtils.getUserRoles(state), permissions.editEditorPrograms); 7461 } 7462 static getProgramId(state, programName) { 7463 if (state.projectSummaries) { 7464 const selectedProgramSummary = state.projectSummaries.find((ps) => ps.projectIds && ps.projectIds.builders === programName); 7465 return selectedProgramSummary && selectedProgramSummary.id; 7466 } 7467 } 7468 static getBuilderProgramAndDraftVersionIds = (state, projectName) => { 7469 const programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(state), projectName); 7470 return { 7471 programId: programSummary && programSummary.id, 7472 programVersionId: programSummary && programSummary.projectIds && programSummary.projectIds.builderDraftVersionId 7473 }; 7474 }; 7475 static isEditorProgram = (state, projectName) => { 7476 const programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(state), projectName); 7477 return programSummary && programSummary.isEditor; 7478 }; 7479 static getCreativeRecordingAssets(state, programId) { 7480 return state.creativeRecordingAssets.byId[programId]; 7481 } 7482 static getSurveys(state, projectName, stage, version) { 7483 return StateReaderUtils.getWireFrame(state, projectName, stage, version).surveys; 7484 } 7485}; 7486//#endregion 7487//#region client/components/model.ts 7488init_reactiveVars(); 7489var errorMessageVar = makeVar(null); 7490var userDataVar = makeVar(null); 7491var activeAccountIdVar = makeVar(null); 7492var activeAccountNameVar = makeVar(null); 7493var featureFlagsVar = makeVar(null); 7494var accessDeniedVar = makeVar(false); 7495var scrollToBottomVar = makeVar(false); 7496var isBreadCrumbsVisibleVar = makeVar(false); 7497var mainContainerRefVar = makeVar(void 0); 7498var helpCenterDataVar = makeVar(null); 7499var helpCenterOpenVar = makeVar(false); 7500var editHelpCenterEnabled = makeVar(false); 7501var editHelpCenterDataVar = makeVar(null); 7502var editHelpCenterOpenVar = makeVar(false); 7503var localRecordingToolSession = makeVar(null); 7504var localRecordingToolPermissionsDeniedState = makeVar(null); 7505var localRecordingToolMenuAnchorVar = makeVar(null); 7506var localRecordingToolState = makeVar(null); 7507var videosAndFoldersVar = makeVar({ 7508 loading: true, 7509 videoItemsById: /* @__PURE__ */ new Map(), 7510 videosByParentFolderId: /* @__PURE__ */ new Map(), 7511 rootFolder: null, 7512 foldersById: /* @__PURE__ */ new Map(), 7513 foldersByParentFolderId: /* @__PURE__ */ new Map(),
7514 accountHasPreviewLifecycleStageVideos: false 7515}); 7516var templatesVar = makeVar({ 7517 loading: true, 7518 templates: [] 7519}); 7520var programAccessVar = makeVar({ 7521 videosLoading: true, 7522 templatesLoading: true, 7523 accessByProgramId: /* @__PURE__ */ new Map() 7524}); 7525var assetMediaVar = makeVar({ 7526 loading: true, 7527 assetLibraryMedia: [], 7528 assetLibraryMediaByGqlMediaId: {}, 7529 assetLibraryMediaByLocalMediaId: {}, 7530 surrogateAssetMediaByMediaId: {}, 7531 surrogateAssetMediaByName: {}, 7532 availableAssetsInYourLibraryById: {}, 7533 availableAssetsForSaveAsById: {}, 7534 hiddenGettyPremiumExpiredMedia: [], 7535 assetLibraryId: null, 7536 mediaFolders: [], 7537 rootFolder: null, 7538 foldersById: /* @__PURE__ */ new Map(), 7539 foldersByParentFolderId: /* @__PURE__ */ new Map(), 7540 pathFromRootToFoldersById: /* @__PURE__ */ new Map(), 7541 mediaByFolderId: /* @__PURE__ */ new Map() 7542}); 7543var deleteEditorVideoVar = makeVar(null); 7544var duplicateEditorVideoIdVar = makeVar(null); 7545var duplicateTemplateIdVar = makeVar(null); 7546var updateTemplateDetailsIdVar = makeVar(null); 7547var saveVideoAsTemplateIdVar = makeVar(null); 7548var aiVideoGeneratedSnackbarVar = makeVar({ 7549 show: false, 7550 errorMessage: null, 7551 assetId: null, 7552 thumbnailUrl: null, 7553 creditsUsed: 0, 7554 savedFolderName: null 7555}); 7556//#endregion 7557//#region client/logic/common/sentryReporting.ts 7558var captureExceptionToSentry = (error, sskyCode, extra) => { 7559 if (isServerOriginError(error)) return; 7560 captureException(toCapturableError(error?.networkError ?? error?.graphQLErrors?.[0] ?? error), { 7561 tags: { sskyCode }, 7562 extra: extra && Object.keys(extra).length > 0 ? extra : void 0 7563 }); 7564}; 7565//#endregion 7566//#region client/logic/common/silentErrorCodes.ts 7567var silentErrorCodes = /* @__PURE__ */ new Set([ 7568 SskyErrorCode.AssetFontUploadError, 7569 SskyErrorCode.UnsupportedAssetFontType, 7570 SskyErrorCode.LivePreviewError, 7571 SskyErrorCode.Unauthorized, 7572 SskyErrorCode.LandingPageOutOfAppPreviewError, 7573 SskyErrorCode.LandingPageOutOfAppPreviewOpenNewTabError, 7574 SskyErrorCode.EmbedVideoPageOutOfAppPreviewError, 7575 SskyErrorCode.EmbedVideoPageOutOfAppPreviewOpenNewTabError, 7576 SskyErrorCode.MediaCropHintsError, 7577 SskyErrorCode.ShareToSocialPreviewError 7578]); 7579//#endregion 7580//#region client/logic/common/errorHandlingUtils.ts 7581var import_createBrowserHistory = /* @__PURE__ */ __toESM(require_createBrowserHistory()); 7582var import_sourcemapped_stacktrace = /* @__PURE__ */ __toESM(require_sourcemapped_stacktrace()); 7583var import_dist$6 = require_dist(); 7584var isOwnClientFrame = (line) => line.includes("/client/") && !line.includes("node_modules"); 7585var getErrorStackMessage = (stack) => { 7586 return (stack && stack.filter(isOwnClientFrame).map((line) => { 7587 let regexArr = /(at \w+)(?:.+\/)*(.+\..+)(?::\d+\))/gm.exec(line); 7588 return regexArr && regexArr.length > 2 ? `${regexArr[1]} (${regexArr[2]})` : ""; 7589 })).slice(0, 5).join(" < "); 7590}; 7591var getComponentStackMessage = (stack) => { 7592 let stackArr = stack && stack.map((line) => { 7593 let regexArr = /(?:\(created by )(.*?)(?:\))/gm.exec(line); 7594 return regexArr && regexArr.length > 1 ? regexArr[1] : ""; 7595 }); 7596 return [...new Set(stackArr)].filter((elem) => elem && !elem.includes("Connect")).slice(0, 10).join(" < "); 7597}; 7598var mapStackTracePromise = (err) => { 7599 return new Promise((resolve) => { 7600 if (typeof err === "object" && err.stack) import_sourcemapped_stacktrace.mapStackTrace(err.stack, function(mappedStack) { 7601 let stackMessage = getErrorStackMessage(mappedStack) || getComponentStackMessage(mappedStack) || mappedStack; 7602 if (stackMessage) err.stack = stackMessage; 7603 resolve(err); 7604 }); 7605 else resolve(err); 7606 }); 7607}; 7608var parseErrorForReport = async (err, crashed) => { 7609 const firstGqlError = err?.graphQLErrors?.[0]; 7610 const gqlServerErrorMessage = firstGqlError?.message || ""; 7611 const gqlNetworkErrorMessage = err?.networkError?.message; 7612 err = await mapStackTracePromise(err); 7613 if (!err["errorId"]) { 7614 if (firstGqlError?.["errorId"]) err[ERROR_ID_KEY] = firstGqlError[ERROR_ID_KEY]; 7615 else if (firstGqlError?.extensions?.["errorId"]) err[ERROR_ID_KEY] = firstGqlError.extensions[ERROR_ID_KEY]; 7616 } 7617 const errorIdFromRestError = getErrorIdFromRestError(err); 7618 let errorMessage; 7619 if (gqlServerErrorMessage) errorMessage = "[GraphQL error]: " + gqlServerErrorMessage; 7620 else if (gqlNetworkErrorMessage) errorMessage = "[GraphQL Network error]: " + gqlNetworkErrorMessage; 7621 else if (errorIdFromRestError) { 7622 err[ERROR_ID_KEY] = errorIdFromRestError; 7623 const responseData = err.response.data; 7624 errorMessage = "Error ID:" + responseData.errorId + "\n\nDescription:" + (responseData.message || responseData.error) + "\n\nDetails:" + responseData.metadata; 7625 } else errorMessage = err.message || String(err).toString(); 7626 let requestUrl = ""; 7627 if (err.details?.method && err.details?.url) requestUrl = `${err.details.method} : ${err.details.url}`; 7628 else if (err.config) requestUrl = `${err.config.method} : ${err.config.url}`; 7629 const metadataObj = { 7630 errorStackMessage: err.stack, 7631 requestUrl, 7632 error: err, 7633 crashed 7634 }; 7635 return { 7636 errorMessage, 7637 metadataObj 7638 }; 7639}; 7640var deriveSentryContext = (error, defaultSskyCode) => {
7641 let sskyCode = error?.getSskyErrorCode?.(); 7642 if (!sskyCode && error?.graphQLErrors?.[0]) sskyCode = getSskyErrorCodeFromGqlError(error.graphQLErrors[0]); 7643 return { 7644 sskyCode: sskyCode ?? defaultSskyCode, 7645 errorId: error?.getErrorId?.() ?? error?.["errorId"] 7646 }; 7647}; 7648var handleError = async ({ error, skipSentryCapture }) => { 7649 const originalStack = error?.stack; 7650 const { errorMessage, metadataObj } = await parseErrorForReport(error, false); 7651 reportErrorToSplunk(errorMessage, metadataObj); 7652 let isRedirected = false; 7653 const response = error.response; 7654 const gqlError = error.graphQLErrors?.[0]; 7655 const gqlServerErrorMessage = gqlError?.message || ""; 7656 const history = (0, import_createBrowserHistory.default)(); 7657 const isAuthOrOutdatedClientError = gqlServerErrorMessage === "Error: Client is outdated" || error === import_dist$6.errors.userNotLoggedIn || response === import_dist$6.errors.userNotLoggedIn || response?.status === 401 || getSskyErrorCodeFromGqlError(gqlError) === SskyErrorCode.Unauthorized || error.getSskyErrorCode?.() === SskyErrorCode.Unauthorized; 7658 if (!(removeLastSlash(window.location.pathname) === (0, import_dist$9.legacyLoginPath)() || removeLastSlash(window.location.pathname) === (0, import_dist$9.newNavLoginPath)()) && isAuthOrOutdatedClientError) { 7659 history.push(isNewNav ? (0, import_dist$9.newNavLoginPath)() : (0, import_dist$9.legacyLoginPath)()); 7660 window.location.reload(); 7661 isRedirected = true; 7662 } else if (response?.status === 403) { 7663 const redirect = getHomePageByUserRoles(StateReaderUtils.getUserRoles(getReduxState()), StateReaderUtils.getActiveAccountId(getReduxState())); 7664 if (redirect) { 7665 history.push(redirect); 7666 window.location.reload(); 7667 isRedirected = true; 7668 } 7669 } 7670 const { sskyCode, errorId } = deriveSentryContext(error, SskyErrorCode.UnexpectedClientError); 7671 if (!skipSentryCapture && !isAuthOrOutdatedClientError && !isRedirected && !isOfflineError(error) && !silentErrorCodes.has(sskyCode)) { 7672 if (error && typeof error === "object" && originalStack !== void 0) error.stack = originalStack; 7673 captureExceptionToSentry(error, sskyCode, errorId ? { errorId } : void 0); 7674 } 7675 return isRedirected; 7676}; 7677var handleUnexpectedError = async ({ error }) => { 7678 const { sskyCode, errorId } = deriveSentryContext(error, SskyErrorCode.ClientRuntimeError); 7679 captureExceptionToSentry(error, sskyCode, errorId ? { errorId } : void 0); 7680 const errorMessage = error?.message?.split("\n")[0]; 7681 error = await mapStackTracePromise(error); 7682 reportErrorToSplunk(errorMessage, { 7683 stackMessage: error.stack, 7684 crashed: true 7685 }); 7686}; 7687//#endregion 7688//#region client/logic/common/commonActions.ts 7689var import_lib$3 = require_lib(); 7690var ERROR = "ERROR"; 7691var CLEAR_ERROR = "CLEAR_ERROR"; 7692var PUSH_HISTORY = "PUSH_HISTORY"; 7693var SET_PAGE_TITLE = "SET_PAGE_TITLE"; 7694var SET_LOADING = "SET_LOADING"; 7695var SET_SOFT_LOADING = "SET_SOFT_LOADING"; 7696var SET_LOADING_FOR_UPDATE_NARRATION_LIBRARY = "SET_LOADING_FOR_UPDATE_NARRATION_LIBRARY"; 7697var SET_BREADCRUMBS_ARRAY = "SET_BREADCRUMBS_ARRAY"; 7698var SET_REVERT_TO_VERSION = "SET_REVERT_TO_VERSION"; 7699var ENABLE_HUB_STICKY_BAR_LOGO_MENU = "ENABLE_HUB_STICKY_BAR_LOGO_MENU"; 7700var SET_HUB_STICKY_BAR_LOGO_MENU_ITEMS_ARRAY = "SET_HUB_STICKY_BAR_LOGO_MENU_ITEMS_ARRAY"; 7701var TOGGLE_MIDDLE_PANEL_COLLAPSE = "TOGGLE_MIDDLE_PANEL_COLLAPSE"; 7702var DATA_LIBRARY_SELECTED_TAB = "DATA_LIBRARY_SELECTED_TAB"; 7703var SET_FORCE_LOAD = "SET_FORCE_LOAD"; 7704var REPORT_ESCAPE_CLICK = "REPORT_ESCAPE_CLICK"; 7705var SET_DRAWER_FILTER = "SET_DRAWER_FILTER"; 7706var setDrawerFilter = (0, import_lib$3.createAction)(SET_DRAWER_FILTER, (drawerFilter) => ({ drawerFilter })); 7707var reportErrorSuccess = (0, import_lib$3.createAction)(ERROR, (userErrorMessage) => ({ userErrorMessage })); 7708var clearError = (0, import_lib$3.createAction)(CLEAR_ERROR, () => {}); 7709var pushHistory = (0, import_lib$3.createAction)(PUSH_HISTORY, (title, link, context) => ({ 7710 context, 7711 title, 7712 link 7713})); 7714var setPageTitle = (0, import_lib$3.createAction)(SET_PAGE_TITLE, (pageTitle) => ({ pageTitle })); 7715var setLoading = (0, import_lib$3.createAction)(SET_LOADING, (isLoading, accountId, projectName, stage, version) => ({ 7716 isLoading, 7717 loadingProgress: void 0, 7718 accountId, 7719 projectName, 7720 stage, 7721 version 7722}), void 0); 7723var setSoftLoading = (0, import_lib$3.createAction)(SET_SOFT_LOADING,
7723(isLoading) => ({ isLoading })); 7724var setLoadingForUpdateNarrationLibrary = (0, import_lib$3.createAction)(SET_LOADING_FOR_UPDATE_NARRATION_LIBRARY, (isLoading, accountId, projectName) => ({ isLoading })); 7725var setBreadcrumbsArray = (0, import_lib$3.createAction)(SET_BREADCRUMBS_ARRAY, (breadCrumbsArray) => ({ breadCrumbsArray })); 7726var setHubStickyBarLogoMenuItemsArray = (0, import_lib$3.createAction)(SET_HUB_STICKY_BAR_LOGO_MENU_ITEMS_ARRAY, (hubStickyBarLogoMenuItemsArray) => ({ hubStickyBarLogoMenuItemsArray })); 7727var enableHubStickyBarLogoMenu = (0, import_lib$3.createAction)(ENABLE_HUB_STICKY_BAR_LOGO_MENU, (isEnableHubStickyBarLogoMenu) => ({ isEnableHubStickyBarLogoMenu })); 7728var toggleMiddlePanelCollapse = (0, import_lib$3.createAction)(TOGGLE_MIDDLE_PANEL_COLLAPSE); 7729var setDataLibrarySelectedTabId = (0, import_lib$3.createAction)(DATA_LIBRARY_SELECTED_TAB, (selectedTabId) => selectedTabId); 7730var setForceLoad = (0, import_lib$3.createAction)(SET_FORCE_LOAD, (forceLoad) => forceLoad); 7731(0, import_lib$3.createAction)(SET_REVERT_TO_VERSION, (versionNumber) => versionNumber); 7732var reportEscapeClick = (0, import_lib$3.createAction)(REPORT_ESCAPE_CLICK, (isEscapeClick) => ({ isEscapeClick })); 7733var onEscapeClick = function(isEscapeClick, cb) { 7734 return function(dispatch) { 7735 if (isEscapeClick) { 7736 dispatch(reportEscapeClick(true)); 7737 cb(); 7738 } 7739 }; 7740}; 7741var _reportError = async ({ error, reportErrorToUser = true, userErrorMessage, reportErrorSuccess }) => { 7742 if (!await handleError({ error }) && reportErrorToUser) { 7743 const response = error.response; 7744 let errorMessageForUser; 7745 if (userErrorMessage) errorMessageForUser = userErrorMessage; 7746 else if (error?.response?.data?.errorId) errorMessageForUser = "Error ID:" + response.data.errorId + "\n\nDescription:" + (response.data.message || response.data.error) + "\n\nDetails:" + response.data.metadata; 7747 else errorMessageForUser = String(error).toString(); 7748 reportErrorSuccess(errorMessageForUser); 7749 } 7750}; 7751var reportError = function(error, reportErrorToUser = true, userErrorMessage) { 7752 return async function(dispatch) { 7753 return _reportError({ 7754 error, 7755 reportErrorToUser, 7756 userErrorMessage, 7757 reportErrorSuccess: (message) => dispatch(reportErrorSuccess(message)) 7758 }); 7759 }; 7760}; 7761var reportErrorRV = function(error, reportErrorToUser = true, userErrorMessage) { 7762 return _reportError({ 7763 error, 7764 reportErrorToUser, 7765 userErrorMessage, 7766 reportErrorSuccess: (message) => errorMessageVar(message) 7767 }); 7768}; 7769var reportUnhandledError = function(error) { 7770 return async function() { 7771 await handleUnexpectedError({ error }); 7772 }; 7773}; 7774//#endregion 7775//#region client/logic/common/commonReducer.ts 7776function commonReducer(state, action) { 7777 switch (action.type) { 7778 case ERROR: { 7779 const userErrorMessage = action.payload.userErrorMessage; 7780 return Object.assign({}, state, { 7781 error: true, 7782 errorMessage: userErrorMessage 7783 }); 7784 } 7785 case CLEAR_ERROR: return Object.assign({}, state, { 7786 error: false, 7787 errorMessage: "" 7788 }); 7789 case PUSH_HISTORY: { 7790 let link = action.payload.link; 7791 let title = action.payload.title; 7792 let byLink = state.browserHistory.byLink; 7793 let allLinks = state.browserHistory.allLinks; 7794 let activeId = state.browserHistory.activeId; 7795 let context = state.browserHistory.context; 7796 if (!context) context = action.payload.context; 7797 else if (action.payload.context && context !== action.payload.context) { 7798 allLinks = [allLinks[activeId]]; 7799 context = action.payload.context; 7800 byLink = {}; 7801 byLink[allLinks[0].link] = 0; 7802 } 7803 if (byLink[link] >= 0) { 7804 activeId = byLink[link]; 7805 allLinks = [ 7806 ...allLinks.slice(0, activeId), 7807 { 7808 title, 7809 link 7810 }, 7811 ...allLinks.slice(activeId + 1) 7812 ]; 7813 } else { 7814 allLinks = [...allLinks, { 7815 title, 7816 link 7817 }]; 7818 if (allLinks.length > 10) { 7819 byLink = { 7820 ...byLink, 7821 [allLinks[0].link]: void 0 7822 }; 7823 allLinks = allLinks.slice(1); 7824 } 7825 activeId = allLinks.length - 1; 7826 byLink = { 7827 ...byLink, 7828 [link]: activeId 7829 }; 7830 } 7831 return Object.assign({}, state, { browserHistory: { 7832 byLink, 7833 allLinks, 7834 activeId, 7835 context 7836 } }); 7837 } 7838 case SET_FORCE_LOAD: return { 7839 ...state, 7840 forceLoad: action.payload 7841 }; 7842 case SET_PAGE_TITLE: return Object.assign({}, state, { pageTitle: action.payload.pageTitle }); 7843 case SET_LOADING: 7844 var count = action.payload.isLoading ? state.loadingCount + 1 : state.loadingCount - 1; 7845 return Object.assign({}, state, { loadingCount: count }); 7846 case SET_SOFT_LOADING: return { 7847 ...state, 7848 softLoading: action.payload.isLoading 7849 }; 7850 case SET_LOADING_FOR_UPDATE_NARRATION_LIBRARY: if (state.loadingUpdateNarrationLibrary === action.payload.isLoading) return state; 7851 else return { 7852 ...state, 7853 loadingUpdateNarrationLibrary: action.payload.isLoading 7854 }; 7855 case SET_BREADCRUMBS_ARRAY: return { 7856 ...state, 7857 breadCrumbsArray: action.payload.breadCrumbsArray 7858 }; 7859 case ENABLE_HUB_STICKY_BAR_LOGO_MENU: return { 7860 ...state, 7861 enableHubStickyBarLogoMenu: action.payload.isEnableHubStickyBarLogoMenu 7862 }; 7863 case SET_HUB_STICKY_BAR_LOGO_MENU_ITEMS_ARRAY: return { 7864 ...state, 7865 hubStickyBarLogoMenuItemsArray: action.payload.hubStickyBarLogoMenuItemsArray 7866 }; 7867 case SET_REVERT_TO_VERSION: return { 7868 ...state, 7869 revertToVersion: action.payload 7870 }; 7871 case TOGGLE_MIDDLE_PANEL_COLLAPSE: return { 7872 ...state, 7873 middlePanelCollapsed: !state.middlePanelCollapsed 7874 }; 7875 case DATA_LIBRARY_SELECTED_TAB: return { 7876 ...state, 7877 dataLibrarySelectedTabId: action.payload 7878 }; 7879 case REPORT_ESCAPE_CLICK: { 7880 let isEscapeClick = action.payload.isEscapeClick; 7881 return Object.assign({}, state, { shouldTurnOffMergeDPSession: isEscapeClick }); 7882 } 7883 case SET_DRAWER_FILTER: return { 7884 ...state, 7885 studioProgramsDrawerFilter: action.payload.drawerFilter 7886 }; 7887 default: return state; 7888 } 7889} 7890//#endregion 7891//#region common/types/documentToVideo.ts 7892var MAX_FILE_SIZE = 50 * 1024 * 1024; 7893var ACCEPTED_FILE_TYPES = [ 7894 "text/plain", 7895 "application/pdf", 7896 "application/msword", 7897 "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 7898 "application/json" 7899]; 7900var RefineValidationErrorType = /* @__PURE__ */ function(RefineValidationErrorType) { 7901 RefineValidationErrorType["REQUIRES_REGENERATION"] = "requiresRegeneration"; 7902 RefineValidationErrorType["MULTIPLE_ACTIONS"] = "multipleActions"; 7903 RefineValidationErrorType["MISSING_INFORMATION"] = "missingInformation"; 7904 RefineValidationErrorType["UNSUPPORTED_ACTION"] = "unsupportedAction"; 7905 return RefineValidationErrorType; 7906}({}); 7907//#endregion 7908//#region common/assetSizeLimitUtils.ts 7909var AcceptedFileTypes = /* @__PURE__ */ function(AcceptedFileTypes) { 7910 AcceptedFileTypes["Image"] = "Image";
7911 AcceptedFileTypes["Video"] = "Video"; 7912 AcceptedFileTypes["Audio"] = "Audio"; 7913 AcceptedFileTypes["CSV"] = "CSV"; 7914 AcceptedFileTypes["EML"] = "EML"; 7915 AcceptedFileTypes["PPTX"] = "PPTX"; 7916 AcceptedFileTypes["JSON"] = "JSON"; 7917 AcceptedFileTypes["TXT"] = "TXT"; 7918 AcceptedFileTypes["PDF"] = "PDF"; 7919 AcceptedFileTypes["DOC"] = "DOC"; 7920 AcceptedFileTypes["DOCX"] = "DOCX"; 7921 return AcceptedFileTypes; 7922}({}); 7923var audioMaxUploadSizeMB = 25; 7924var imageMaxUploadSizeMB = 40; 7925var videoMaxUploadSizeMB = 250; 7926var customAvatarInputMaxUploadSizeMB = 500; 7927var csvMaxUploadSizeMB = 100; 7928var emlMaxUploadSizeMB = 25; 7929var pptxMaxUploadSizeMB = 25; 7930var jsonMaxUploadSizeMB = 25; 7931var documentMaxUploadSizeMB = 40; 7932var MEGA = 1024 * 1024; 7933var audioMaxUploadSize = audioMaxUploadSizeMB * MEGA; 7934var imageMaxUploadSize = imageMaxUploadSizeMB * MEGA; 7935var videoMaxUploadSize = videoMaxUploadSizeMB * MEGA; 7936customAvatarInputMaxUploadSizeMB * MEGA; 7937var csvMaxUploadSize = csvMaxUploadSizeMB * MEGA; 7938documentMaxUploadSizeMB * MEGA; 7939var audioSizeExceededMsg = `Audio size limit exceeded. You may upload audio files up to ${audioMaxUploadSizeMB}MB`; 7940var imageSizeExceededMsg = `Image size limit exceeded. You may upload image files up to ${imageMaxUploadSizeMB}MB`; 7941var videoSizeExceededMsg = `Video size limit exceeded. You may upload video files up to ${videoMaxUploadSizeMB}MB`; 7942var documentSizeExceededMsg = `file size limit exceeded. You may upload DOC files up to ${documentMaxUploadSizeMB}MB`; 7943var getImageMaxUploadFileSizeMB = () => { 7944 return imageMaxUploadSizeMB; 7945}; 7946var getVideoMaxUploadFileSizeMB = () => { 7947 return videoMaxUploadSizeMB; 7948}; 7949var getMaxUploadFileSizeMbByType = (type) => { 7950 switch (type) { 7951 case "Image": return getImageMaxUploadFileSizeMB(); 7952 case "Video": return getVideoMaxUploadFileSizeMB(); 7953 case "Audio": return audioMaxUploadSizeMB; 7954 case "CSV": return csvMaxUploadSizeMB; 7955 case "EML": return emlMaxUploadSizeMB; 7956 case "PPTX": return pptxMaxUploadSizeMB; 7957 case "JSON": return jsonMaxUploadSizeMB; 7958 case "TXT": 7959 case "PDF": 7960 case "DOC": 7961 case "DOCX": return documentMaxUploadSizeMB; 7962 default: throw new Error("Unsupported file type"); 7963 } 7964}; 7965var validateAssetFileSize = (fileSize, fileType) => { 7966 if (fileType.startsWith("image") && fileSize > imageMaxUploadSize) throw Error(imageSizeExceededMsg); 7967 if (fileType.startsWith("video") && fileSize > videoMaxUploadSize) throw Error(videoSizeExceededMsg); 7968 if (fileType.startsWith("audio") && fileSize > audioMaxUploadSize) throw Error(audioSizeExceededMsg); 7969 if (ACCEPTED_FILE_TYPES.includes(fileType)) { 7970 if (fileSize > 41943040) throw Error(documentSizeExceededMsg); 7971 } 7972}; 7973//#endregion 7974//#region client/logic/common/assetUtils.ts 7975var import_browser = /* @__PURE__ */ __toESM(require_browser()); 7976var AssetUtils = class AssetUtils { 7977 static { 7978 this.recordingStatuses = { 7979 APPROVED: "approved", 7980 REJECTED: "rejected", 7981 PENDING_APPROVAL: "pendingApproval" 7982 }; 7983 } 7984 static { 7985 this.AssetPropType = import_prop_types.default.shape({ 7986 activeVersion: import_prop_types.default.number.isRequired, 7987 assetId: import_prop_types.default.string.isRequired, 7988 filename: import_prop_types.default.string, 7989 name: import_prop_types.default.string.isRequired, 7990 version: import_prop_types.default.number 7991 }); 7992 } 7993 static getRecordingStatusText(asset) { 7994 if (asset.status === "request") return "Pending Recording"; 7995 switch (asset.recordingStatus) { 7996 case AssetUtils.recordingStatuses.PENDING_APPROVAL: return "Pending Approval"; 7997 case AssetUtils.recordingStatuses.REJECTED: return asset.recordingErrorReason; 7998 case AssetUtils.recordingStatuses.APPROVED: return "Approved"; 7999 default: return ""; 8000 } 8001 } 8002 static getRecordingStatusClassName(asset) { 8003 if (asset.status === "request") return "pending"; 8004 switch (asset.recordingStatus) { 8005 case AssetUtils.recordingStatuses.PENDING_APPROVAL: return "pending-approval"; 8006 case AssetUtils.recordingStatuses.REJECTED: return "rejected"; 8007 case AssetUtils.recordingStatuses.APPROVED: return "approved"; 8008 default: return ""; 8009 } 8010 } 8011 static deconstructRecordingAssetName(assetName) { 8012 const deconstructed = assetName.split("~"); 8013 return { 8014 narrationId: deconstructed[0], 8015 narratorId: deconstructed[1], 8016 key: deconstructed[2] 8017 }; 8018 } 8019 static { 8020 this.getVersion = (asset, stageView) => { 8021 if (stageView && valueExists(asset.stageVersion)) return asset.stageVersion; 8022 else if (valueExists(asset.activeVersion)) return asset.activeVersion; 8023 else return asset.version; 8024 }; 8025 } 8026 static { 8027 this.getDownloadUrl = (asset, stageView, preview) => { 8028 if (asset.isPostgresAsset) if (stageView && asset.stageAssetItem) { 8029 const { url, thumbnailUrl } = asset.stageAssetItem; 8030 return preview ? thumbnailUrl : url; 8031 } else { 8032 const { url, thumbnailUrl } = asset; 8033 return preview ? thumbnailUrl : url; 8034 } 8035 const parameters = preview ? "?preview=true" : ""; 8036 return AssetUtils.getAssetField(asset, "downloadSelf", stageView, parameters); 8037 }; 8038 } 8039 static { 8040 this.getLocation = (asset, stageView) => { 8041 return AssetUtils.getAssetField(asset, "location", stageView); 8042 }; 8043 } 8044 static { 8045 this.getFormat = (asset, stageView) => { 8046 return AssetUtils.getAssetField(asset, "format", stageView); 8047 }; 8048 } 8049 static { 8050 this.getAssetField = (asset, fieldName, stageView, parameters = "") => { 8051 if (stageView && asset.stageAssetItem && asset.stageAssetItem[fieldName]) return asset.stageAssetItem[fieldName] + parameters; 8052 if (asset.version !== asset.activeVersion) { 8053 if (asset.activeVersionItem && asset.activeVersionItem[fieldName]) return asset.activeVersionItem[fieldName] + parameters; 8054 if (asset.history && asset.history.Items) { 8055 const assetVersion = asset.history.Items.find((assetVersionItem) => assetVersionItem.version === asset.activeVersion); 8056 if (assetVersion) return assetVersion[fieldName] + parameters; 8057 } 8058 } 8059 return asset[fieldName] ? asset[fieldName] + parameters : void 0; 8060 }; 8061 } 8062 static { 8063 this.getAssetTypeFromId = (projectAssetId) => { 8064 return projectAssetId.split("/")[2]; 8065 }; 8066 } 8067 static { 8068 this.getFileType = async (file) => { 8069 let reader; 8070 return new Promise((resolve, reject) => { 8071 reader = new FileReader(); 8072 reader.onload = resolve; 8073 reader.onerror = reject; 8074 reader.readAsArrayBuffer(file.slice(0, fileTypeCheckRequiredBufferSize)); 8075 }).then(() => { 8076 let buffer = reader && reader.result; 8077 return import_browser.default.fromBuffer(buffer); 8078 }).then((type) => { 8079 return type && type.mime; 8080 }); 8081 }; 8082 } 8083 static { 8084 this.getAssetNameNoFileExtension = (filename) => { 8085 return filename.substr(0, filename.lastIndexOf(".")); 8086 }; 8087 } 8088 static { 8089 this.getMockNarrationUrl = (narrator, text, mockNarrationServerEndpoint) => { 8090 return `${mockNarrationServerEndpoint}tts-service/play?narrator=${narrator}&text=${gBase64.encode(text)}&filename=any.mp3`; 8091 }; 8092 } 8093 static { 8094 this.convertGraphQLRecordingDocForRedux = (recordingDoc) => { 8095 return { 8096 createdTime: recordingDoc.created,
8097 createdBy: recordingDoc.createdBy, 8098 audioFileName: recordingDoc.audioFilename, 8099 scriptFileName: recordingDoc.scriptFilename, 8100 totalRecordingFiles: recordingDoc.totalRecordingFiles, 8101 folderLocation: recordingDoc.folderLocation, 8102 audioFileUrl: recordingDoc.audioFileUrl, 8103 scriptFileUrl: recordingDoc.scriptFileUrl, 8104 id: recordingDoc.id, 8105 isPostgresAsset: true 8106 }; 8107 }; 8108 } 8109 static validateFileType(fileMimeType, requiredMediaType, isLegacyProject) { 8110 if (!fileMimeType) throw illegalFileFormatMsg; 8111 if (!fileTypesWhitelist.includes(fileMimeType)) throw isLegacyProject ? legacyIllegalFileFormatMsg : illegalFileFormatMsg; 8112 if (requiredMediaType) { 8113 let allowedTypes = mimeTypesByMediaType[requiredMediaType]; 8114 if (allowedTypes && !allowedTypes.includes(fileMimeType)) throw `File of type: "${fileMimeType}" isn't compatible for ${requiredMediaType} media type`; 8115 } 8116 } 8117 static validateMediaFileType(filename, fileMimeType, requiredMediaType) { 8118 if (!AssetUtils.isFileExtensionValid(filename, supportedExtensions).isValid) throw illegalFileFormatMsg; 8119 if (!fileMimeType) throw illegalFileFormatMsg; 8120 if (!fileTypesWhitelist.includes(fileMimeType)) throw illegalFileFormatMsg; 8121 if (requiredMediaType) { 8122 let allowedTypes = []; 8123 requiredMediaType.forEach((requiredType) => { 8124 if (mimeTypesByMediaType[requiredType]) allowedTypes.push(...mimeTypesByMediaType[requiredType]); 8125 }); 8126 if (allowedTypes && !allowedTypes.includes(fileMimeType)) throw illegalFileFormatMsg; 8127 } 8128 } 8129 static { 8130 this.isFileExtensionValid = (filename, allowedExtensions) => { 8131 const fileExtension = filename.substr(filename.lastIndexOf(".") + 1).toLowerCase(); 8132 return { 8133 isValid: allowedExtensions.includes(fileExtension), 8134 fileExtension 8135 }; 8136 }; 8137 } 8138 static { 8139 this.getCrossVersionId = (graphQLId) => { 8140 if (graphQLId.includes("|")) return graphQLId.split("|").slice(2).join("|"); 8141 else return graphQLId; 8142 }; 8143 } 8144}; 8145//#endregion 8146//#region client/logic/projects/projectWireframes/projectNarrations/DataElementValueSetAdapter.ts 8147var createDataElementValueSetAdapter = (dataElement) => { 8148 const getSource = () => { 8149 return "DataElements"; 8150 }; 8151 const getId = () => { 8152 return getDataElementId(dataElement); 8153 }; 8154 const getName = () => { 8155 return getDataElementDisplayName(dataElement); 8156 }; 8157 const getType = () => { 8158 return dataElement.type; 8159 }; 8160 const getValueSet = () => { 8161 let valueSet = dataElement.getValueSet() || []; 8162 let supportsMissing = false; 8163 let supportsOther = false; 8164 if (dataElement.origin === DataElementOrigins.Derived) { 8165 let valueSetWithoutNull = valueSet.filter((value) => value !== null); 8166 if (valueSetWithoutNull.length < valueSet.length) { 8167 valueSet = valueSetWithoutNull; 8168 supportsMissing = true; 8169 } 8170 } else if (dataElement.origin === DataElementOrigins.System) {} else if (dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative) { 8171 if (valueSet.length > 0) { 8172 supportsMissing = true; 8173 supportsOther = true; 8174 } 8175 } 8176 return import_immutable.default.List(valueSet).withMutations((mutableValueSet) => { 8177 if (supportsOther || supportsMissing) mutableValueSet.push({ 8178 id: "_vs_other_or_missing", 8179 dn: DATA_ELEMENT_VALUE_OTHER_OR_MISSING 8180 }); 8181 }); 8182 }; 8183 return { 8184 getSource, 8185 getId, 8186 getName, 8187 getType, 8188 getValueSet 8189 }; 8190}; 8191//#endregion 8192//#region client/logic/projects/projectWireframes/projectNarrations/PrioritizedListValueSetAdapter.js 8193var PRIORITIZED_LIST_VALUE_SET_SOURCES = Object.freeze({ 8194 CandidateNames: "candidateNames", 8195 NumberOfValidSlots: "numberOfValidSlots" 8196}); 8197var createPrioritizedListCandidatesValueSetAdapter = (prioritizedList, slotName) => { 8198 const getSource = () => { 8199 return PRIORITIZED_LIST_VALUE_SET_SOURCES.CandidateNames; 8200 }; 8201 const getId = () => { 8202 return `${prioritizedList.id}^${slotName}`; 8203 }; 8204 const getName = () => { 8205 return `${prioritizedList.name} - ${slotName}`; 8206 }; 8207 const getType = () => { 8208 return LOGIC_TYPE.DataElementString; 8209 }; 8210 const getValueSet = () => { 8211 const candidateNames = listCandidateNames(prioritizedList); 8212 return import_immutable.default.List(candidateNames).withMutations((mutableValueSet) => { 8213 mutableValueSet.push({ 8214 id: "_vs_empty", 8215 dn: DATA_ELEMENT_VALUE_EMPTY 8216 }); 8217 }); 8218 }; 8219 return { 8220 getSource, 8221 getId, 8222 getName, 8223 getType, 8224 getValueSet 8225 }; 8226}; 8227var createPrioritizedListValidSlotsValueSetAdapter = (prioritizedList) => { 8228 const name = "# of valid slots"; 8229 const getSource = () => { 8230 return PRIORITIZED_LIST_VALUE_SET_SOURCES.NumberOfValidSlots; 8231 }; 8232 const getId = () => { 8233 return `${prioritizedList.id}^${name}`; 8234 }; 8235 const getName = () => { 8236 return `${prioritizedList.name} - ${name}`; 8237 }; 8238 const getType = () => { 8239 return LOGIC_TYPE.DataElementNumber; 8240 }; 8241 const getValueSet = () => { 8242 const slotNumbers = Array.from({ length: prioritizedList.maxSlots + 1 }).map((_, idx) => ({ 8243 id: `validSlotNum${idx}`, 8244 dn: `${idx}` 8245 })); 8246 return import_immutable.default.List(slotNumbers); 8247 }; 8248 return { 8249 getSource, 8250 getId, 8251 getName, 8252 getType, 8253 getValueSet 8254 }; 8255}; 8256//#endregion 8257//#region client/logic/projects/projectWireframes/projectNarrations/ValueSetAdapterUtils.ts 8258var generatePrioritizedListCandidateNamesValueSetProviders = (prioritizedList) => { 8259 let prioritizedListValueSetProviders = [];
8260 Array.from(Array(prioritizedList.maxSlots).keys()).forEach((num) => { 8261 const slotCharacter = mapNumToLetter(num); 8262 prioritizedListValueSetProviders.push(createPrioritizedListCandidatesValueSetAdapter(prioritizedList, `Slot ${slotCharacter}`)); 8263 }); 8264 return prioritizedListValueSetProviders; 8265}; 8266var generatePrioritizedListValueSetProviders = (prioritizedList) => { 8267 let prioritizedListValueSetProviders = []; 8268 prioritizedListValueSetProviders.push(...generatePrioritizedListCandidateNamesValueSetProviders(prioritizedList)); 8269 prioritizedListValueSetProviders.push(createPrioritizedListValidSlotsValueSetAdapter(prioritizedList)); 8270 return prioritizedListValueSetProviders; 8271}; 8272var generateValueSetProviders = (dataElements, prioritizedLists) => { 8273 let valueSetProviders = []; 8274 dataElements.forEach((dataElement) => { 8275 valueSetProviders.push(createDataElementValueSetAdapter(dataElement)); 8276 }); 8277 prioritizedLists.forEach((prioritizedList) => { 8278 valueSetProviders.push(...generatePrioritizedListValueSetProviders(prioritizedList)); 8279 }); 8280 return valueSetProviders; 8281}; 8282var logicOperatos_default = { 8283 "# of chars >": ">", 8284 "# of chars <": "<", 8285 "# of chars =": "===", 8286 And: "&&", 8287 Or: "||", 8288 "smaller than": "<", 8289 "greater than": ">", 8290 "small or equal than": "<=", 8291 "great or equal than": ">=", 8292 "is true": "=== true", 8293 "is false": "=== false", 8294 "# of valid slots =": "===", 8295 "# of valid slots >": ">", 8296 "# of valid slots <": "<" 8297}; 8298var logicFunctions_default = { 8299 "# of chars >": { 8300 "name": "length", 8301 "expectsRhs": true, 8302 "handleRhsAsArg": false 8303 }, 8304 "# of chars <": { 8305 "name": "length", 8306 "expectsRhs": true, 8307 "handleRhsAsArg": false 8308 }, 8309 "# of chars =": { 8310 "name": "length", 8311 "expectsRhs": true, 8312 "handleRhsAsArg": false 8313 }, 8314 exists: { 8315 "name": "exists", 8316 "expectsRhs": false 8317 }, 8318 "does not exist": { 8319 "name": "!exists", 8320 "expectsRhs": false 8321 }, 8322 equals: { 8323 "name": "equals", 8324 "expectsRhs": true, 8325 "handleRhsAsArg": true 8326 }, 8327 "not equals": { 8328 "name": "notEquals", 8329 "expectsRhs": true, 8330 "handleRhsAsArg": true 8331 }, 8332 contains: { 8333 "name": "contains", 8334 "expectsRhs": true, 8335 "handleRhsAsArg": true 8336 }, 8337 "is before": { 8338 "name": "isDateBefore", 8339 "expectsRhs": true, 8340 "handleRhsAsArg": true 8341 }, 8342 "is after": { 8343 "name": "isDateAfter", 8344 "expectsRhs": true, 8345 "handleRhsAsArg": true 8346 }, 8347 "is true": { 8348 "name": "istrue", 8349 "expectsRhs": false 8350 }, 8351 "is false": { 8352 "name": "isfalse", 8353 "expectsRhs": false 8354 }, 8355 "# of valid slots =": { 8356 "name": "listLength", 8357 "expectsRhs": true, 8358 "handleRhsAsArg": false 8359 }, 8360 "# of valid slots >": { 8361 "name": "listLength", 8362 "expectsRhs": true, 8363 "handleRhsAsArg": false 8364 }, 8365 "# of valid slots <": { 8366 "name": "listLength", 8367 "expectsRhs": true, 8368 "handleRhsAsArg": false 8369 }, 8370 includes: { 8371 "name": "listIncludes", 8372 "expectsRhs": true, 8373 "handleRhsAsArg": true, 8374 "replaceCandidateName": true 8375 }, 8376 "does not include": { 8377 "name": "listDoesntInclude", 8378 "expectsRhs": true, 8379 "handleRhsAsArg": true, 8380 "replaceCandidateName": true 8381 }, 8382 "is filled": { 8383 "name": "slotExists", 8384 "expectsRhs": false 8385 }, 8386 "is empty": { 8387 "name": "slotDoesntExist", 8388 "expectsRhs": false 8389 }, 8390 "is filled with": { 8391 "name": "equals", 8392 "expectsRhs": true, 8393 "handleRhsAsArg": true, 8394 "replaceCandidateName": true 8395 } 8396}; 8397//#endregion 8398//#region client/logic/vlx/logixBuilder.ts 8399function stringify(val) { 8400 return `'${val.replace(/'/g, "\\'")}'`; 8401} 8402function getInputLogicType(inputLogic) { 8403 return inputLogic?.outputType || "string"; 8404} 8405var wrapParamValue = function(param) { 8406 if (param.value === void 0 || param.value === null || param.value === true || param.value === false || typeof param.value === "number" || param.type === "number") return `${param.value}`; 8407 return `"${param.value}"`; 8408}; 8409/** 8410* Builds a string, which the VLX would know to resolve, and read the data element value 8411* in the following format: De(<dataElement.displayName>) 8412* @param logicElement - the *DataElement* object (as stored in data elements table)
8413* @param programDataFields - an object containing { dataElements: Array<DataElements> and assets: Array<Asset> } 8414* containing arrays of data fields used in the logic 8415* @return {string} - The string the VLX is expecting to properly resolve a data element` 8416*/ 8417function wrapDataElement(logicElement, programDataFields) { 8418 const extractedMetadata = getElementInfoFromActionableData(logicElement, programDataFields); 8419 let mediaType = extractedMetadata.mediaType || logicElement.mediaType; 8420 let dataElementName = extractedMetadata.refName || logicElement.name; 8421 let currentValue = `${`${mediaType}De`}('${dataElementName}') `; 8422 if (logicElement.actions && logicElement.actions.length > 0) currentValue = wrapActions(currentValue, logicElement.actions, programDataFields); 8423 return currentValue; 8424} 8425function evalScopeVariable(variableName, scope) { 8426 return { eval: wrapScopeVariable(variableName, scope) }; 8427} 8428function wrapScopeVariable(variableName, scope) { 8429 return scope ? `de('${scope}.${variableName}')` : `de('${variableName}')`; 8430} 8431function wrapPrioritizedList(plName, scope) { 8432 return `deConditionKeys('${scope}.${plName}')`; 8433} 8434function wrapPrioritizedListSlot(plName, slotIdx, scope) { 8435 return `${wrapPrioritizedList(plName, scope)}[${slotIdx}]`; 8436} 8437function wrapPrioritizedListNumberOfSlots(plName, scope) { 8438 let prioritizedList = wrapPrioritizedList(plName, scope); 8439 return macro(wrapFunction(logicFunctions_default["# of valid slots ="].name, prioritizedList)); 8440} 8441function wrapPrioritizedListSlotName(plName, slotIdx, scope) { 8442 return { eval: wrapPrioritizedListSlot(plName, slotIdx, scope) }; 8443} 8444function wrapPrioritizedListSlotPath(plName, slotIdx) { 8445 return `${plName}.slot${mapNumToLetter(slotIdx)}`; 8446} 8447function wrapActions(currentValue, actions, programDataFields) { 8448 let wrappedValue = currentValue; 8449 actions.forEach((action) => { 8450 let params = action.params ? action.params.map((param) => { 8451 if (param.type === VLX_PARAMTYPE.TimeZone) return "stringDe('TimeZone') "; 8452 else if (param.type === LOGIC_DATA_TYPES.DataElement) return wrapDataElement(param, programDataFields); 8453 else return wrapParamValue(param); 8454 }) : []; 8455 wrappedValue = wrapFunction(action.name, [wrappedValue, ...params]); 8456 }); 8457 return wrappedValue; 8458} 8459function macro(variable) { 8460 return `[[${variable}]]`; 8461} 8462function wrapFunction(func, ...args) { 8463 return `${func}(${args})`; 8464} 8465function getLhs(lhs, func, rhs, dataFields) { 8466 if (!lhs) return ""; 8467 let variable; 8468 const extractedMetadata = getElementInfoFromActionableData(lhs, dataFields); 8469 if (lhs && (lhs.type === LOGIC_DATA_TYPES.DataElement || lhs.type === LOGIC_DATA_TYPES.MappingTable)) variable = wrapDataElement(lhs, dataFields); 8470 else if (lhs.type === ActionableDataValueType.Prioritized) variable = wrapPrioritizedList(extractedMetadata.refName, VLX_SCOPE.Scene); 8471 else if (lhs.type === ActionableDataValueType.PrioritizedSlot && func.replaceCandidateName) variable = wrapPrioritizedListSlot(extractedMetadata.refName, lhs.slotIdx, VLX_SCOPE.Scene); 8472 else if (lhs.type === ActionableDataValueType.PrioritizedSlot) variable = wrapScopeVariable(wrapPrioritizedListSlotPath(extractedMetadata.refName, lhs.slotIdx), VLX_SCOPE.Scene); 8473 if (typeof func === "object") if (func.handleRhsAsArg) return wrapFunction(func.name, [variable, rhs]); 8474 else return wrapFunction(func.name, [variable]); 8475 return variable; 8476} 8477function getRhs(lhs, rhs, dataFields) { 8478 if (rhs instanceof Array) return rhs.reduce((acc, item) => { 8479 if (acc) acc += "+"; 8480 acc += getRhs(lhs, item, dataFields); 8481 return acc; 8482 }, ""); 8483 if (rhs && typeof rhs === "object") { 8484 if (rhs.type === LOGIC_DATA_TYPES.DataElement || rhs.type === LOGIC_DATA_TYPES.MappingTable) return wrapDataElement(rhs, dataFields); 8485 else if (rhs.type === LOGIC_DATA_TYPES.Const) if (rhs.mediaType === LOGIC_MEDIA_TYPES.Number) return Number(rhs.name); 8486 else return stringify(rhs.name); 8487 else if (rhs.type === LOGIC_DATA_TYPES.ValueSetValue) { 8488 let elementInfo = getElementInfoFromActionableData(rhs, dataFields); 8489 if (elementInfo) if (elementInfo.mediaType === LOGIC_MEDIA_TYPES.Number) return Number(elementInfo.displayName); 8490 else return stringify(elementInfo.displayName); 8491 } 8492 return; 8493 } 8494 if (typeof rhs === "string") if (lhs && lhs.mediaType === LOGIC_MEDIA_TYPES.Number && (Number(rhs) || Number(rhs) === 0)) return Number(rhs); 8495 else return stringify(rhs); 8496 else return rhs; 8497} 8498function buildRuleWhen(whens, dataFields) { 8499 return whens.reduce((acc, whenItem) => { 8500 if (typeof whenItem === "object") { 8501 let rhs = getRhs(whenItem.lhs, whenItem.rhs, dataFields); 8502 const operator = logicOperatos_default[whenItem.operator]; 8503 const func = logicFunctions_default[whenItem.operator]; 8504 if (func && func.replaceCandidateName && typeof rhs === "string" && whenItem.lhs.mediaType === LOGIC_TYPE.Prioritized) rhs = resolve
8504CandidateKeyFromName(rhs, whenItem.lhs.id, dataFields.prioritizedListLogic); 8505 const lhs = getLhs(whenItem.lhs, func, rhs, dataFields); 8506 acc += lhs; 8507 if (!logicFunctions_default[whenItem.operator] || logicFunctions_default[whenItem.operator].expectsRhs && !logicFunctions_default[whenItem.operator].handleRhsAsArg) acc += " " + operator + " " + rhs; 8508 } else if (typeof whenItem === "string") acc += " " + logicOperatos_default[whenItem] + " "; 8509 return acc; 8510 }, ""); 8511} 8512function valueIsDerived(value, dataElements) { 8513 return Boolean(dataElements && Array.isArray(dataElements) && dataElements.find((de) => de.id === value.id && de.origin === DATA_ELEMENT_ORIGIN.DERIVED)); 8514} 8515function valueIsOfOrigin(value, dataElements, origin) { 8516 return Boolean(dataElements && Array.isArray(dataElements) && dataElements.find((de) => de.id === value.id && de.origin === origin)); 8517} 8518function isOfAssetType(type) { 8519 return Boolean(type === LogicType.Image || type === LogicType.Video || type === LogicType.Audio); 8520} 8521function buildValue(value, phType, useAbsolutePath = false, programDataFields, supportMultipleStories = false, breakHotspotValue = false, isValueOfBackgroundAsset = false) { 8522 if (typeof value === "undefined" || value === null) return isValueOfBackgroundAsset ? null : ""; 8523 if (breakHotspotValue && isLogicValueHotspot(value)) return { actionRef: buildValue(getHotspotId(value), LogicType.Text, useAbsolutePath, programDataFields, supportMultipleStories) }; 8524 if (phType === LogicType.Compound) { 8525 let compoundItemValue = {}; 8526 value.forEach((item) => { 8527 let outputType = item.outputType; 8528 if (isLogicValueHotspot(item.value)) outputType = breakHotspotValue ? LogicType.Text : onscreenTypes.Hotspot; 8529 if (item.outputType === LogicType.Ratio || item.outputType === LogicType.Quality) outputType = LogicType.Text; 8530 compoundItemValue[item.id] = { 8531 type: outputType, 8532 value: buildValue(item.value, item.outputType, useAbsolutePath, programDataFields, supportMultipleStories, breakHotspotValue) 8533 }; 8534 }); 8535 return compoundItemValue; 8536 } 8537 if (phType === LogicType.Prioritized) { 8538 let slotContentValue = {}; 8539 value.forEach((item) => { 8540 const outputType = isLogicValueHotspot(item.value) ? onscreenTypes.Hotspot : item.outputType; 8541 slotContentValue[item.displayName] = { 8542 type: outputType, 8543 value: buildValue(item.value, item.outputType, useAbsolutePath, programDataFields) 8544 }; 8545 }); 8546 return slotContentValue; 8547 } 8548 if (phType === LogicType.NextScene && supportMultipleStories) return (0, import_md5.default)(JSON.stringify(value)); 8549 if (phType === LogicType.Story) return buildStoryValue(value, programDataFields.storyIdToStoryAssetName); 8550 if (value instanceof Array) return value.reduce((acc, item) => { 8551 acc += buildValue(item, phType, useAbsolutePath, programDataFields); 8552 return acc; 8553 }, ""); 8554 const dataType = valueIsDerived(value, programDataFields.dataElements) ? DATA_ELEMENT_ORIGIN.DERIVED : value.type; 8555 const isUrlThatRepresentsMediaAsset = value.mediaType === LOGIC_MEDIA_TYPES.URL && isOfAssetType(phType); 8556 const isCreativeAssetDE = isOfAssetType(value.mediaType) && isOfAssetType(phType) && dataType === LOGIC_DATA_TYPES.DataElement && valueIsOfOrigin(value, programDataFields.dataElements, DataElementOrigins.Creative); 8557 if (dataType === DATA_ELEMENT_ORIGIN.DERIVED && isUrlThatRepresentsMediaAsset) return { eval: wrapDataElement(value, programDataFields) }; 8558 else if (dataType === LOGIC_DATA_TYPES.DataElement || dataType === LOGIC_DATA_TYPES.MappingTable || dataType === DATA_ELEMENT_ORIGIN.DERIVED) { 8559 let currentValue = wrapDataElement(value, programDataFields); 8560 if (isUrlThatRepresentsMediaAsset || isCreativeAssetDE) return isValueOfBackgroundAsset ? { eval: `({ href: ${currentValue}})` } : { eval: `({ source: ${currentValue}})` }; 8561 else if (value.mediaType === LOGIC_TYPE.Color) return { eval: currentValue }; 8562 else if (value.mediaType === DATA_TABLE_OUTPUT_TYPES.Url) return { eval: `({ source: ${currentValue}})` }; 8563 else return macro(currentValue); 8564 } else if (dataType === LOGIC_DATA_TYPES.Asset) { 8565 const assetRef = { 8566 "repo-url": value.name, 8567 repository: CURATED_REPOSITORY 8568 };
8569 return isValueOfBackgroundAsset ? { href: assetRef } : { source: assetRef }; 8570 } else if (dataType === LOGIC_DATA_TYPES.Animation) { 8571 const animationAsset = getAssetFromActionableData(value, programDataFields.assets); 8572 return { href: { 8573 "repo-url": useAbsolutePath && animationAsset ? animationAsset.self : getValueFromActionableData(value) + "/", 8574 repository: ANIMATION_REPOSITORY 8575 } }; 8576 } else if (dataType === LOGIC_DATA_TYPES.Variable) return macro(wrapScopeVariable(value.path || value.name, VLX_SCOPE.Scene)); 8577 else if (value.slotPath) return macro(wrapScopeVariable(value.slotPath, VLX_SCOPE.Scene)); 8578 else return value.name !== void 0 && value.name !== null ? value.name : value; 8579} 8580function buildStoryValue(value, storyIdToStoryAssetName) { 8581 return storyIdToStoryAssetName[value]; 8582} 8583function getHotspotId(value) { 8584 const idIndex = value.findIndex((item) => item.id === "id"); 8585 return value.slice(idIndex, idIndex + 1)[0].value; 8586} 8587/*** 8588* 8589* @param inputLogic - The logic object to be converted in the VLX structure 8590* @param useAbsolutePath - Should animation path be absulote, usually false, true only for animatic previews (As they are created by the "Studio" (hub :]) app 8591* @param programDataFields : { dataElements: Array<DataElements>, assets: <Assets> } 8592* @param supportMultipleStories Does the project support the new feature of multiple stories 8593* @param isValueOfBackgroundAsset: are the rules being build belong to background asset (audio/ video/ image) 8594* @return {*} 8595*/ 8596function buildInputRules(inputLogic, programDataFields = {}, useAbsolutePath = false, supportMultipleStories = false, breakHotspotValue = false, isValueOfBackgroundAsset = false) { 8597 if (!inputLogic) return [{ value: "" }]; 8598 let rules = []; 8599 if (inputLogic.rules) rules = inputLogic.rules.map((rule) => { 8600 return { 8601 when: rule.always === true ? "true" : buildRuleWhen(rule.whens, programDataFields), 8602 value: buildValue(rule.value, inputLogic.outputType, useAbsolutePath, programDataFields, supportMultipleStories, breakHotspotValue, isValueOfBackgroundAsset), 8603 key: rule.key 8604 }; 8605 }); 8606 if (inputLogic.outputType !== LOGIC_TYPE.Prioritized) rules.push({ value: buildValue(inputLogic.defaultValue, inputLogic.outputType, useAbsolutePath, programDataFields, supportMultipleStories, breakHotspotValue, isValueOfBackgroundAsset) }); 8607 return rules; 8608} 8609function wrapAnalyticsValue(analyticsKey, value) { 8610 if (Array.isArray(value)) return [`${analyticsKey}=`, ...value]; 8611 if (!value) return `${analyticsKey}=`; 8612 return [`${analyticsKey}=`, value]; 8613} 8614function buildAnalyticsRules(inputAnalyticsLogic, analyticsKey, programDataFields) { 8615 if (!inputAnalyticsLogic) return [{ value: wrapAnalyticsValue(analyticsKey, "") }]; 8616 let rules = []; 8617 if (inputAnalyticsLogic.rules) rules = inputAnalyticsLogic.rules.map((rule) => { 8618 return { 8619 when: buildRuleWhen(rule.whens, programDataFields), 8620 value: buildValue(wrapAnalyticsValue(analyticsKey, rule.value), LogicType.AnalyticCustomField, false, programDataFields), 8621 key: rule.key 8622 }; 8623 }); 8624 rules.push({ value: buildValue(wrapAnalyticsValue(analyticsKey, inputAnalyticsLogic.defaultValue), LogicType.AnalyticCustomField, false, programDataFields) }); 8625 return rules; 8626} 8627//#endregion 8628//#region client/logic/vlx/utils.js 8629function createJsonHierarchyForVar(json, variable, value) { 8630 variable.toString().split(".").reduce((acc, jsonNode, index, array) => { 8631 if (!acc[jsonNode]) acc[jsonNode] = {}; 8632 if (index === array.length - 1) acc[jsonNode] = value; 8633 return acc[jsonNode]; 8634 }, json); 8635 return json; 8636} 8637/** 8638* Parse a string value to the value of a relevant mediaType 8639* @param strValue 8640* @param mediaType 8641*/ 8642function parseStringToRelevantMediaType(strValue, mediaType) { 8643 switch (mediaType) { 8644 case LOGIC_MEDIA_TYPES.Number: return Number(strValue); 8645 case LOGIC_MEDIA_TYPES.Boolean: 8646 if (strValue === "true") return true; 8647 else if (strValue === "false") return false; 8648 return; 8649 default: return strValue; 8650 } 8651} 8652/** 8653* Gets a logic data, and returns a map of objects according to type -> list of scene ids in which it is used 8654* @param logicData logic object, where the first layer must be scene ids 8655* @type the type of the objects to be extracted 8656*/ 8657function extractScenesByType(logicData, type) { 8658 let elementToScenesMap = (0, import_traverse.default)(logicData).reduce(function(acc, node) { 8659 if (node && node.type === type) { 8660 let dataElementName; 8661 if (type === LOGIC_DATA_TYPES.MappingTable) dataElementName = getMappingTableNameFromValue(node); 8662 else dataElementName = getValueFromActionableData(node); 8663 acc[dataElementName] = acc[dataElementName] || {}; 8664 let sceneId = this.path[0]; 8665 if (sceneId !== "derived") acc[dataElementName][sceneId] = sceneId; 8666 } 8667 return acc; 8668 }, {}); 8669 for (let de in elementToScenesMap) if (elementToScenesMap.hasOwnProperty(de)) elementToScenesMap[de] = Object.keys(elementToScenesMap[de]); 8670 return elementToScenesMap; 8671} 8672//#endregion 8673//#region client/logic/vlx/dataElements.js 8674var import_moment_timezone = /* @__PURE__ */ __toESM(require_moment_timezone()); 8675/** 8676* This function constructs a set of feed values, coherent with the stracture 8677* @param dataElementsNamesAndValues Array<nameAndValue>: and object describing a data element display name and the value it should get 8678* ex: [{ name: "de1", value: "1"}, { name: "dateDe", value: "27/11/91" }] 8679* @return {{dataElements: an object simulating a data feed with deeply nested object and their values 8680* ex: { userDevice: { type: "mac", location: "" } } 8681* }} 8682*/ 8683function createDataFeed(dataElementsNamesAndValues) { 8684 let dataElementsJson = {}; 8685 if (dataElementsNamesAndValues) dataElementsJson = dataElementsNamesAndValues.reduce((acc, dePresetValue) => { 8686 createJsonHierarchyForVar(acc, dePresetValue.name, dePresetValue.value); 8687 return acc; 8688 }, {}); 8689 return { dataElements: dataElementsJson }; 8690} 8691/** 8692* Gets logic object, and returns all the data elements in which it depends. 8693* Data elements of type 'derived' should NOT be returned, instead, THEIR depen
8693dent data elements should be returned. 8694* @param input an object that includes logic. 8695* @param derivedLogic the logic of the derived data elements 8696* @param mappingTables a list of the project's mapping table 8697* @param dataElements an array of all the data elements 8698* @returns an array of objects, containing data elements ids, of the data elements which appear in the logic. 8699*/ 8700function extractDataElementsFromLogic(input, derivedLogic, mappingTables, dataElements) { 8701 let manager = new StudioDataManager({ 8702 derivedLogic, 8703 dataElements, 8704 mappingTables 8705 }); 8706 manager.buildDerivedGraphFromLogic(input); 8707 if (manager.detectCycles().length > 0) throw CYCLIC_ERROR_MESSAGE; 8708 let participatingDataElementMap = extractDataElementsFromLogicStep(input, /* @__PURE__ */ new Map(), derivedLogic, mappingTables, dataElements); 8709 addTimeZoneDataElement(participatingDataElementMap, dataElements); 8710 return Array.from(participatingDataElementMap.values()); 8711} 8712function extractDataElementsFromLogicStep(input, accumulatedParticipatingDataElementMap, derivedLogic, mappingTables, dataElements) { 8713 let { derivedDataElementMap, nonDerivedDataElementMap } = splitToDerivedAndNonDerivedMaps(extractDataElementIdsFromLogic(input, mappingTables).reduce((acc, deId) => { 8714 let dataElement = findDataElementById(deId, dataElements); 8715 dataElement = dataElement || findDataElementByName(deId, dataElements); 8716 if (dataElement) acc.set(deId, dataElement); 8717 return acc; 8718 }, /* @__PURE__ */ new Map())); 8719 accumulatedParticipatingDataElementMap.forEach((val, key) => nonDerivedDataElementMap.set(key, val)); 8720 if (derivedDataElementMap.size === 0) return nonDerivedDataElementMap; 8721 let participatingDerivedLogics = []; 8722 derivedDataElementMap.forEach((derivedDE) => { 8723 const derivedLogicId = getDerivedDataElementLogicId(derivedDE); 8724 participatingDerivedLogics.push(derivedLogic[derivedLogicId]); 8725 }); 8726 return extractDataElementsFromLogicStep(participatingDerivedLogics, nonDerivedDataElementMap, derivedLogic, mappingTables, dataElements); 8727} 8728function splitToDerivedAndNonDerivedMaps(dataElementMap) { 8729 let derivedDataElementMap = /* @__PURE__ */ new Map(); 8730 let nonDerivedDataElementMap = /* @__PURE__ */ new Map(); 8731 dataElementMap.forEach((dataElement, dataElementId) => { 8732 if (getDataElementOrigin(dataElement) === DataElementOrigins.Derived) derivedDataElementMap.set(dataElementId, dataElement); 8733 else nonDerivedDataElementMap.set(dataElementId, dataElement); 8734 }); 8735 return { 8736 derivedDataElementMap, 8737 nonDerivedDataElementMap 8738 }; 8739} 8740function extractMappingTableNames(input, mappingTables) { 8741 let tableData = {}; 8742 if (mappingTables) { 8743 let tables = (0, import_traverse.default)(input).reduce((acc, node) => { 8744 if (mappingTables && node && node.type === LOGIC_DATA_TYPES.MappingTable) { 8745 let mappingTableName = getMappingTableNameFromValue(node); 8746 if (mappingTables.find((mappingTable) => mappingTable.name === mappingTableName)) acc[mappingTableName] = mappingTableName; 8747 } 8748 return acc; 8749 }, {}); 8750 tableData.tables = Object.keys(tables); 8751 } 8752 return tableData; 8753} 8754function createTablesObject(mappingTables) { 8755 let tables = {}; 8756 if (mappingTables) mappingTables.forEach((table) => { 8757 tables[table.name] = { dtKey: table.decisionTablesLocation }; 8758 }); 8759 return tables; 8760} 8761function addTimeZoneDataElement(dataElementMap, dataElements) { 8762 let hasDateType = false;
8763 dataElementMap.forEach((de) => hasDateType = hasDateType || de.type === LOGIC_MEDIA_TYPES.Date); 8764 if (hasDateType) { 8765 const timeZoneDe = dataElements.find((de) => getDataElementId(de) === "HubSystem:TimeZone"); 8766 if (timeZoneDe) dataElementMap.set("HubSystem:TimeZone", timeZoneDe); 8767 } 8768} 8769function getDefaultValueForSystemDataElement(dataElementId) { 8770 switch (dataElementId) { 8771 case "HubSystem:now": return (0, import_moment_timezone.default)().format(); 8772 case "HubSystem:TimeZone": return "America/New_York"; 8773 default: return; 8774 } 8775} 8776function buildDerivedDataElements(context) { 8777 return buildDerivedDataElementsFromLogic(null, context); 8778} 8779function buildDerivedDataElementsFromLogic(logic, context) { 8780 let { derivedLogic, assets, dataElements } = context; 8781 const mappingTables = assets ? assets.filter((asset) => asset.type === ASSET_TYPES.mappingTable) : []; 8782 const derivedDataElements = dataElements ? dataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Derived) : []; 8783 context.mappingTables = mappingTables; 8784 let manager = new StudioDataManager(context); 8785 logic ? manager.buildDerivedGraphFromLogic(logic) : manager.buildDerivedGraph(derivedDataElements); 8786 return manager.sortDerivedByDependencies().map((dataElementId) => { 8787 let dataElement = findDataElementById(dataElementId, derivedDataElements); 8788 dataElement = dataElement || findDataElementByName(dataElementId, derivedDataElements); 8789 const logicId = getDerivedDataElementLogicId(dataElement); 8790 return { 8791 name: getDataElementDisplayName(dataElement), 8792 value: { 8793 rules: buildInputRules(derivedLogic[logicId], context), 8794 type: getInputLogicType(derivedLogic[logicId]) 8795 } 8796 }; 8797 }); 8798} 8799/** 8800*The function gets the params bellow and return object that for each scene contains all the logics that are being used in it (including derived Logic). 8801* @param logicData logic object, where the first layer must be scene ids 8802* @param dataElementsArr array of data Elements objects 8803* @param derivedLogic the logic of the derived data elements 8804** @return ByScene - logic Data included in each scene logic object, where the first layer must be scene ids 8805*/ 8806function addDerivedLogicToAllLogicsPerSceneObject(logicData, dataElementsArr, derivedLogic) { 8807 let logicsByScene = {}; 8808 for (let sceneId in logicData) { 8809 let derivedLogicsForSceneId = (0, import_traverse.default)(logicData[sceneId]).reduce(function(acc, node) { 8810 if (node && node.type === LOGIC_DATA_TYPES.DataElement) { 8811 const dataElement = findDataElementByLogicValue(node, dataElementsArr); 8812 if (dataElement && dataElement.origin === DataElementOrigins.Derived) { 8813 let derivedLogicId; 8814 let participatingDerivedLogic; 8815 let derivedDataElementId; 8816 if ((derivedLogicId = getDerivedDataElementLogicId(dataElement)) && (participatingDerivedLogic = derivedLogic[derivedLogicId]) && (derivedDataElementId = getDataElementId(dataElement))) acc[derivedDataElementId] = Object.assign({}, participatingDerivedLogic); 8817 } 8818 } 8819 return acc; 8820 }, {}); 8821 logicsByScene[sceneId] = Object.assign(logicData[sceneId], derivedLogicsForSceneId); 8822 } 8823 return logicsByScene; 8824} 8825/** 8826*The function returns for each data element id the array of scene that use it. 8827* @param object args = { 8828* logicData: logic object, where the first layer must be scene ids 8829* dataElementsArr: array of data Elements objects 8830* derivedLogic: the logic of the derived data elements 8831* mappingTables: a list of the project's mapping table 8832* } 8833* @return a map of data element -> list of scene ids in which it is used 8834*/ 8835function extractScenes(args) { 8836 let { wireframes, logicData, dataElementsArr, derivedLogic, mappingTables } = args; 8837 let logicsByScene = addDerivedLogicToAllLogicsPerSceneObject(logicData, dataElementsArr, derivedLogic); 8838 let dataElementIdsMappedToScenesId = {}; 8839 for (let sceneId in logicsByScene) { 8840 let deToScenesMap = (0, import_traverse.default)(logicsByScene[sceneId]).reduce(function(acc, node) { 8841 if (node) { 8842 if (node.type === LOGIC_DATA_TYPES.DataElement) { 8843 const dataElement = findDataElementByLogicValue(node, dataElementsArr); 8844 if (dataElement) { 8845 let dataElementId = getDataElementId(dataElement); 8846 acc[dataElementId] = sceneId; 8847 } 8848 } else if (mappingTables && node.type === LOGIC_DATA_TYPES.MappingTable) { 8849 let mappingTableName = getMappingTableNameFromValue(node); 8850 let mappingTable = mappingTables.find((mappingTable) => mappingTable.name === mappingTableName); 8851 if (mappingTable && mappingTable.mappingTableScheme) { 8852 let inputs = mappingTable.mappingTableScheme.inputs;
8853 if (inputs) inputs.forEach((input) => { 8854 const dataElement = (dataElementsArr || []).find((de) => input.id === getDataElementId(de) || input.name === getDataElementId(de)); 8855 if (dataElement) { 8856 let dataElementId = getDataElementId(dataElement); 8857 acc[dataElementId] = sceneId; 8858 } 8859 }); 8860 } 8861 } 8862 } 8863 return acc; 8864 }, {}); 8865 for (let dataElementId in deToScenesMap) { 8866 let sceneArr = dataElementIdsMappedToScenesId[dataElementId] || []; 8867 sceneArr.push(sceneId); 8868 dataElementIdsMappedToScenesId[dataElementId] = sceneArr; 8869 } 8870 } 8871 dataElementIdsMappedToScenesId = getDataElementsUsedInNarrations(wireframes, wireframes.scenes, dataElementIdsMappedToScenesId); 8872 dataElementIdsMappedToScenesId = getCreativeDataElementsUsedInNarrationsOverrides(wireframes, dataElementIdsMappedToScenesId, true); 8873 return dataElementIdsMappedToScenesId; 8874} 8875function getDataElementsUsedInNarrations(wireframes, wireframeScenes, dataElementIdsMappedToScenesId) { 8876 function addDataElement(deId, sceneId) { 8877 if (!dataElementIdsMappedToScenesId[deId]) dataElementIdsMappedToScenesId[deId] = []; 8878 dataElementIdsMappedToScenesId[deId].push(sceneId); 8879 } 8880 Object.values(wireframeScenes).forEach((scene) => { 8881 scene.sceneParts.forEach((scenePart) => { 8882 scenePart.NarrationParts && scenePart.NarrationParts.forEach((narrationPart) => { 8883 let dataElementsIdsInUse = wireframes.narrations && StateReaderUtils.getNarrationTableDataElements(wireframes, narrationPart.id); 8884 if (dataElementsIdsInUse) { 8885 dataElementsIdsInUse = dataElementsIdsInUse.toArray(); 8886 dataElementsIdsInUse.forEach((deId) => { 8887 const dataElement = findDataElementById(deId, wireframes.dataElements); 8888 if (dataElement.origin === DataElementOrigins.Derived) getDataElementsUsedInDerived(wireframes.dataElements, dataElement, wireframes.logic.derived[dataElement.id]).forEach((id) => { 8889 addDataElement(id, scene.id); 8890 }); 8891 addDataElement(deId, scene.id); 8892 }); 8893 } 8894 }); 8895 }); 8896 }); 8897 for (let deId in dataElementIdsMappedToScenesId) dataElementIdsMappedToScenesId[deId] = (0, import_lodash.uniq)(dataElementIdsMappedToScenesId[deId]); 8898 return dataElementIdsMappedToScenesId; 8899} 8900function getDataElementsUsedInDerived(allDataElements, derivedDataElement, derivedLogic) { 8901 return (0, import_traverse.default)(derivedLogic).reduce(function(acc, node) { 8902 if (node) { 8903 if (node.type === LOGIC_DATA_TYPES.DataElement) { 8904 const dataElement = findDataElementByLogicValue(node, allDataElements); 8905 if (dataElement) { 8906 let dataElementId = getDataElementId(dataElement); 8907 acc.push(dataElementId); 8908 } 8909 } 8910 } 8911 return acc; 8912 }, []); 8913} 8914//#endregion 8915//#region client/logic/vlx/tester.ts 8916var import_cjs = /* @__PURE__ */ __toESM(require_cjs()); 8917function testSingleInputLogic(inputLogic, dataElementsValues, derivedLogic, mappingTables, dtaasEndPoint, programDataFields, prioritizedLists, inputName) { 8918 const rules = buildInputRules(inputLogic, programDataFields); 8919 let data = createDataFeed(dataElementsValues.map((deVal) => { 8920 return { 8921 name: deVal.name, 8922 value: deVal.value 8923 }; 8924 })); 8925 let tables = createTablesObject(mappingTables); 8926 let tableData = extractMappingTableNames({ 8927 inputLogic, 8928 derivedLogic 8929 }, mappingTables); 8930 let variableLogic; 8931 if (inputLogic && inputLogic.outputType === LOGIC_CONTEXT.Prioritized) { 8932 const pList = prioritizedLists.find((pl) => pl.id === inputName); 8933 variableLogic = { 8934 type: "object", 8935 cardinality: { 8936 multiple: true, 8937 transform: "slots", 8938 limit: pList ? pList.maxSlots : void 0 8939 }, 8940 rules 8941 }; 8942 } else if (inputLogic && inputLogic.outputType === LOGIC_TYPE.Color) variableLogic = { 8943 type: LOGIC_TYPE.Color, 8944 rules 8945 }; 8946 else variableLogic = { 8947 type: "text", 8948 rules 8949 }; 8950 let promise; 8951 if (tableData.tables && tableData.tables.length > 0) promise = (0, import_dist$8.resolveMappingTables)({ tables }, { tableData }, data.dataElements, dtaasEndPoint); 8952 else promise = Promise.resolve({}); 8953 return promise.then((resolvedMappingTables) => { 8954 data.dataElements = (0, import_cjs.default)(data.dataElements, resolvedMappingTables); 8955 if (derivedLogic) (0, import_dist$8.addVariablesToContext)(buildDerivedDataElementsFromLogic(inputLogic, {
8956 ...programDataFields, 8957 derivedLogic 8958 }), data); 8959 const resolved = (0, import_dist$8.resolveVar)(variableLogic, data); 8960 return { 8961 result: resolved.value, 8962 case: resolved.case 8963 }; 8964 }); 8965} 8966//#endregion 8967//#region client/logic/common/exportNarrationsUtils.ts 8968var styles = { 8969 headerDark: { 8970 fill: { fgColor: { rgb: "FFCFE2F3" } }, 8971 font: { bold: true }, 8972 alignment: { 8973 vertical: "center", 8974 horizontal: "center" 8975 } 8976 }, 8977 cellGreen: { 8978 fill: { fgColor: { rgb: "FF38761d" } }, 8979 font: { size: 11 } 8980 }, 8981 cellRed: { fill: { fgColor: { rgb: "FFa61c00" } } } 8982}; 8983function getRecordingAssetName(narrationId, narratorId, text) { 8984 return narrationId + "~" + narratorId + "~" + (0, import_md5.default)(text); 8985} 8986function getRecordingAssetNameByKey(narrationId, narratorId, key) { 8987 return `${narrationId}~${narratorId}~${key}`; 8988} 8989function getRecordingNarrationId(assetName) { 8990 if (assetName) { 8991 const indexOf = assetName.indexOf("~"); 8992 return indexOf > 0 && indexOf + 1 < assetName.length ? assetName.substring(0, indexOf) : void 0; 8993 } 8994} 8995function getColumnSpecifications(wireframes, storyId, narrationId) { 8996 let dimensions = StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId); 8997 let narrator = StateReaderUtils.getNarrator(wireframes, storyId); 8998 let getSpecification = (columnName, width) => ({ 8999 displayName: columnName, 9000 headerStyle: styles.headerDark, 9001 cellStyle: function(value, row) { 9002 return styles.cellGreen; 9003 }, 9004 width 9005 }); 9006 let dataElementsColumns = dimensions.reduce((specifications, dimension) => { 9007 specifications[dimension.name] = getSpecification("DataElement_" + dimension.name, 220); 9008 return specifications; 9009 }, {}); 9010 dataElementsColumns["approved_narration"] = getSpecification("Approved N
9010arration", 260); 9011 dataElementsColumns["comment"] = getSpecification("SSky Comments", 120); 9012 dataElementsColumns["dynamic_ost"] = getSpecification("Dynamic OST", 120); 9013 dataElementsColumns["narrator_mock"] = getSpecification("Narrator\nMock", 70); 9014 if (narrator) dataElementsColumns["narrator_" + narrator] = getSpecification("Narrator\n" + narrator, 70); 9015 dataElementsColumns["audio_file"] = getSpecification("Audio\nFile", 70); 9016 return dataElementsColumns; 9017} 9018function getData(wireframes, assets, program, storyId, narrationId) { 9019 let dimensions = StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId); 9020 let variations = StateReaderUtils.getNarrationTableVariations(wireframes, narrationId); 9021 let narrator = StateReaderUtils.getNarrator(wireframes, storyId); 9022 let data = []; 9023 let i = 0; 9024 let variationKeys = {}; 9025 variations.forEach((variation, variationKey) => { 9026 if (!variation.variationData.muted) { 9027 variationKeys[variationKey] = 0; 9028 let first = true; 9029 variation.points.forEach((point) => { 9030 data[i] = {}; 9031 point.forEach((valueId, coordinate) => { 9032 let dimensionName = dimensions.get(coordinate).name; 9033 let value = dimensions.get(coordinate).valueSet.find((valueSetValue) => valueSetValue.id === valueId); 9034 data[i][dimensionName] = value.dn; 9035 }); 9036 data[i].comment = variation.variationData.comment; 9037 data[i].approved_narration = variation.variationData.text; 9038 data[i].variationKey = variationKey; 9039 data[i].narrator_mock = first ? "TBR" : "Yes"; 9040 if (narrator) data[i]["narrator_" + narrator] = first ? "TBR" : "Yes"; 9041 let { accountId, projectName } = program; 9042 let assetName = getRecordingAssetName(narrationId, defaultNarratorId, variation.variationData.text); 9043 let assetId = StateReaderUtils.getAssetUniqueId(accountId, projectName, ASSET_TYPES.recording, assetName); 9044 let asset = assets.byId[assetId]; 9045 if (asset) data[i].audio_file = asset.filename; 9046 i++; 9047 first = false; 9048 }); 9049 } 9050 }); 9051 data.sort((row1, row2) => { 9052 for (let i = 0; i < dimensions.size; ++i) { 9053 let indexMap = dimensions.get(i).indexMap; 9054 let dimensionName = dimensions.get(i).name; 9055 let result = indexMap.get(row1[dimensionName]) - indexMap.get(row2[dimensionName]); 9056 if (result !== 0 || i === dimensions.size - 1) return result; 9057 } 9058 }); 9059 data.forEach((row) => { 9060 dimensions.forEach((dimension) => { 9061 if (row[dimension.name].startsWith("~~~")) row[dimension.name] = null; 9062 else if (dimension.type === DataElementContentTypes.Number) row[dimension.name] = Number(row[dimension.name]).toString(); 9063 }); 9064 }); 9065 stableSort$1(data, (row1, row2) => { 9066 return row1.audio_file - row2.audio_file; 9067 }); 9068 return data; 9069} 9070var getAllNarrations = function(scenes) { 9071 return scenes.reduce((allNarrations, scene) => { 9072 let count = 0; 9073 let sceneNarrations = scene.sceneParts.reduce((sceneNarrations, scenePart) => { 9074 let narrations = scenePart.NarrationParts && scenePart.NarrationParts.map((nar) => { 9075 let letter = String.fromCharCode("A".charCodeAt(0) + count++); 9076 return { 9077 name: scene.name + "-" + letter, 9078 sceneId: scene.id, 9079 scenePartId: scenePart.scenePart, 9080 id: nar.id 9081 }; 9082 }); 9083 if (narrations) sceneNarrations = sceneNarrations.concat(narrations); 9084 return sceneNarrations; 9085 }, []); 9086 allNarrations = allNarrations.concat(sceneNarrations); 9087 return allNarrations; 9088 }, []); 9089}; 9090function getDtaasSchemaInputs(wireframes, narrationId) { 9091 return StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId).map((dim) => ({ 9092 id: dim.id, 9093 displayName: dim.name, 9094 name: dim.id, 9095 type: dim.type 9096 })); 9097} 9098function cachedGetRecording(recordings) { 9099 let cache = recordings.reduce((acc, asset) => { 9100 acc[asset.name] = asset; 9101 return acc; 9102 }, {}); 9103 return (narrationId, narratorId, text) => { 9104 if (!text || !narrationId || !narratorId) return; 9105 let recordingAssetName = getRecordingAssetName(narrationId, narratorId, text); 9106 let recording = cache[recordingAssetName]; 9107 return recording && AssetUtils.getLocation(recording, false); 9108 }; 9109} 9110function getDataForDtaas(wireframes, narrationId, narratorId, recordings) { 9111 let dimensions = StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId); 9112 let variations = StateReaderUtils.getNarrationTableVariations(wireframes, narrationId); 9113 let dataElements = StateReaderUtils.getProjectDataElementsFromWireframes(wireframes); 9114 const getRecording = cachedGetRecording(recordings); 9115 const uniqueCoordinateValueSetFetchId = (coordinate, valueId) => coordinate + "/" + valueId; 9116 const valueFetchMap = dimensions.reduce((acc, dimension, coordinate) => { 9117 dimension.valueSet.forEach((valueSetValue) => { 9118 acc[uniqueCoordinateValueSetFetchId(coordinate, valueSetValue.id)] = valueSetValue; 9119 }); 9120 return acc; 9121 }, {}); 9122 let data = []; 9123 let i = 0; 9124 let variationKeys = {}; 9125 variations.forEach((variation, variationKey) => { 9126 variationKeys[variationKey] = 0;
9127 variation.points.forEach((point) => { 9128 data[i] = {}; 9129 point.forEach((valueId, coordinate) => { 9130 let dimensionId = dimensions.get(coordinate).id; 9131 let isCandidateName = dimensionId.startsWith(PRIORITIZED_LIST_VALUE_SET_SOURCES.CandidateNames); 9132 let value = valueFetchMap[uniqueCoordinateValueSetFetchId(coordinate, valueId)]; 9133 let isSpecialValue = value.dn.startsWith("~~~"); 9134 data[i][dimensionId] = isCandidateName && !isSpecialValue ? value.id : value.dn; 9135 }); 9136 data[i].comment = variation.variationData.muted ? null : variation.variationData.text; 9137 data[i].value = getRecording(narrationId, narratorId, data[i].comment); 9138 if (!variation.variationData.muted && variation.variationData.overrideId) { 9139 const overrideCDE = findDataElementById(variation.variationData.overrideId, dataElements); 9140 if (overrideCDE && overrideCDE.displayName) data[i].overrideCDEName = overrideCDE.displayName; 9141 } 9142 i++; 9143 }); 9144 }); 9145 data.forEach((row) => { 9146 dimensions.forEach((dimension) => { 9147 if (row[dimension.id].startsWith("~~~")) row[dimension.id] = null; 9148 else if (dimension.type === DataElementContentTypes.String) row[dimension.id] = row[dimension.id].toLowerCase(); 9149 else if (dimension.type === DataElementContentTypes.Number) row[dimension.id] = Number(row[dimension.id]).toString(); 9150 }); 9151 }); 9152 return data; 9153} 9154function createDtaasObj(wireframes, narratorId, recordings) { 9155 return getAllNarrations(Object.values(wireframes.scenes)).map((narration) => { 9156 return { 9157 id: narration.id, 9158 sceneId: narration.sceneId, 9159 scenePartId: narration.scenePartId, 9160 scheme: { 9161 inputs: getDtaasSchemaInputs(wireframes, narration.id), 9162 outputs: [{ 9163 name: "comment", 9164 id: "comment", 9165 type: "string" 9166 }, { 9167 name: "value", 9168 id: "value", 9169 type: "string" 9170 }] 9171 }, 9172 data: getDataForDtaas(wireframes, narration.id, narratorId, recordings) 9173 }; 9174 }); 9175} 9176function createExcelObj(wireframes, scenes, assets, program, storyId) { 9177 let narrations = getAllNarrations(scenes); 9178 const MAX_CHAR = 31; 9179 function cutSceneName(narrationName) { 9180 const narrationNameArr = narrationName.split("-"); 9181 let narrationPartName = narrationNameArr[narrationNameArr.length - 1]; 9182 let sceneName; 9183 if (narrationNameArr.length > 2) sceneName = narrationNameArr.slice(0, -1).join("-"); 9184 else sceneName = narrationNameArr[0]; 9185 const endIndex = MAX_CHAR - 1 - narrationPartName.length - 1; 9186 return sceneName.slice(0, endIndex) + "-" + narrationPartName; 9187 } 9188 return narrations.map((narration) => { 9189 return { 9190 name: narration.name.length > MAX_CHAR ? cutSceneName(narration.name) : narration.name, 9191 merges: [], 9192 specification: getColumnSpecifications(wireframes, storyId, narration.id), 9193 data: getData(wireframes, assets, program, storyId, narration.id) 9194 }; 9195 }); 9196} 9197//#endregion 9198//#region client/logic/projects/projectWireframes/projectNarrations/projectNarrationsActions.ts 9199var AddOrRemove = /* @__PURE__ */ function(AddOrRemove) { 9200 AddOrRemove["ADD"] = "add"; 9201 AddOrRemove["REMOVE"] = "remove"; 9202 return AddOrRemove; 9203}({}); 9204var LOAD_NARRATIONS_SUCCESS = "LOAD_NARRATIONS_SUCCESS"; 9205var loadNarrationsSuccess = (0, import_lib$3.createAction)(LOAD_NARRATIONS_SUCCESS, (accountId, projectName, narrations) => { 9206 return { 9207 accountId, 9208 projectName, 9209 narrations 9210 }; 9211}, void 0); 9212var UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_PENDING = "UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_PENDING"; 9213var updateNarrationStructureAndVariationDataPending = (0, import_lib$3.createAction)(UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_PENDING, (accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates) => { 9214 return { 9215 accountId, 9216 projectName, 9217 sceneId, 9218 narrationId, 9219 structureUpdate, 9220 variationDataUpdates 9221 }; 9222}, void 0); 9223var UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_SUCCESS = "UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_SUCCESS"; 9224var updateNarrationStructureAndVariationDataSuccess = (0, import_lib$3.createAction)(UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_SUCCESS, (accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, mayCauseChangeInAssetLibrary, graphQLUpdated) => { 9225 return { 9226 accountId, 9227 projectName, 9228 sceneId, 9229 narrationId, 9230 structureUpdate, 9231 variationDataUpdates, 9232 mayCauseChangeInAssetLibrary, 9233 graphQLUpdated 9234 }; 9235}, void 0); 9236var UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_FAILURE = "UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_FAILURE"; 9237var updateNarrationStructureAndVariationDataFailure = (0, import_lib$3.createAction)(UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_FAILURE, (accountId, projectName, sceneId, narrationId, structureUpdate, variationReverts, variationDataMapReverts) => { 9238 return { 9239 accountId, 9240 projectName, 9241 sceneId, 9242 narrationId, 9243 structureUpdate, 9244 variationReverts, 9245 variationDataMapReverts 9246 }; 9247}, void 0); 9248var NARRATION_USED_VALUE_SET_PROVIDER_CHANGED = "NARRATION_USED_VALUE_SET_PROVIDER_CHANGED"; 9249var narrationUsedValueSetProviderChanged = (0, import_lib$3.createAction)(NARRATION_USED_VALUE_SET_PROVIDER_CHANGED, (accountId, projectName, sceneId, narrationId) => { 9250 return { 9251 accountId, 9252 projectName, 9253 sceneId, 9254 narrationId 9255 }; 9256}); 9257var REMOVE_NARRATION_DIMENSION = "REMOVE_NARRATION_DIMENSION"; 9258var removeNarrationDimension = (0, import_lib$3.createAction)(REMOVE_NARRATION_DIMENSION, (accountId, projectName, sceneId, narrationId, index) => { 9259 return { 9260 accountId, 9261 projectName, 9262 sceneId, 9263 narrationId, 9264 index 9265 }; 9266}, void 0); 9267var CANCEL_REMOVE_NARRATION_DIMENSION = "CANCEL_REMOVE_NARRATION_DIMENSION"; 9268var cancelRemoveNarrationDimension = (0, import_lib$3.createAction)(CANCEL_REMOVE_NARRATION_DIMENSION, (accountId, projectName, sceneId, narrationId) => { 9269 return { 9270 accountId, 9271 projectName, 9272 sceneId, 9273 narrationId 9274 }; 9275}); 9276var ADD_NARRATION_SUCCESS = "ADD_NARRATION_SUCCESS"; 9277var addNarrationSuccess = (0, import_lib$3.createAction)(ADD_NARRATION_SUCCESS, (accountId, projectName, sceneId, narrationId, structure, variationDataMap, postgresNarrationId, graphQLUpdated) => { 9278 return { 9279 accountId, 9280 projectName, 9281 sceneId, 9282 narrationId, 9283 structure, 9284 variationDataMap, 9285 postgresNarrationId, 9286 graphQLUpdated 9287 }; 9288}, void 0); 9289var DELETE_NARRATION_SUCCESS = "DELETE_NARRATION_SUCCESS"; 9290var deleteNarrationSuccess = (0, import_lib$3.createAction)(DELETE_NARRATION_SUCCESS, (accountId, projectName, sceneId, narrationId) => { 9291 return { 9292 accountId, 9293 projectName, 9294 sceneId, 9295 narrationId 9296 }; 9297}); 9298var SET_SHOW_MUTED_ROWS = "SET_SHOW_MUTED_ROWS"; 9299var setShowMutedRows = (0, import_lib$3.createAction)(SET_SHOW_MUTED_ROWS, (show) => { 9300 return { show }; 9301}); 9302var SET_SHOW_NOTE_COLUMN = "SET_SHOW_NOTE_COLUMN"; 9303var setShowNoteColumn = (0, import_lib$3.createAction)(SET_SHOW_NOTE_COLUMN, (show) => { 9304 return { show }; 9305}); 9306var SET_SHOW_STATUS_COLUMN = "SET_SHOW_STATUS_COLUMN"; 9307var setShowStatusColumn = (0, import_lib$3.createAction)(SET_SHOW_STATUS_COLUMN, (show) => { 9308 return { show }; 9309}); 9310var updateNarrationStructureAndVariationData = (accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, mayCauseChangeInAssetLibrary) => { 9311 return (dispatch, getState, services) => { 9312 let variationReverts = {}; 9313 let variationDataMapReverts = {}; 9314 if (variationDataUpdates) { 9315 let state = getState(); 9316 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9317 let variations = wireframes.narrations.byId[narrationId].variations; 9318 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap;
9319 Object.keys(variationDataUpdates).forEach((variationKey) => { 9320 if (variations.has(variationKey)) variationReverts[variationKey] = variations.get(variationKey).variationData; 9321 variationDataMapReverts[variationKey] = variationDataMap.get(variationKey); 9322 }); 9323 } 9324 dispatch(updateNarrationStructureAndVariationDataPending(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates)); 9325 let dbStructure = {}; 9326 let dbVariationDataUpdates = {}; 9327 Promise.resolve().then(() => { 9328 if (structureUpdate && Object.keys(structureUpdate).length > 0) { 9329 if (structureUpdate.stack) { 9330 dbStructure.dimensionData = NarrationsModelUtils.dbExtractDimensionDataFromStructure(structureUpdate); 9331 dbStructure.mergeData = NarrationsModelUtils.dbExtractMergeDataFromStructure(structureUpdate); 9332 } 9333 if (structureUpdate.representativeKey) dbStructure.representativeKey = NarrationsModelUtils.dbExtractRepresentativeKeyFromStructure(structureUpdate); 9334 if (structureUpdate.creativeOverride !== void 0) dbStructure.creativeOverride = NarrationsModelUtils.dbExtractCreativeOverrideFromStructure(structureUpdate); 9335 if (variationDataUpdates && Object.keys(variationDataUpdates).length > 0) dbVariationDataUpdates = NarrationsModelUtils.dbExtractVariationDataUpdates(variationDataUpdates); 9336 } 9337 if (variationDataUpdates && Object.keys(variationDataUpdates).length > 0) dbVariationDataUpdates = NarrationsModelUtils.dbExtractVariationDataUpdates(variationDataUpdates); 9338 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 9339 let variationsToUpsert = []; 9340 let variationsToDelete = []; 9341 Object.keys(dbVariationDataUpdates).forEach((variationKey) => { 9342 let variationUpdate = dbVariationDataUpdates[variationKey]; 9343 if (variationUpdate) variationsToUpsert.push({ 9344 variationKey, 9345 sentence: variationUpdate.text, 9346 note: variationUpdate.comment, 9347 muted: variationUpdate.muted, 9348 overridingCreativeDataElementId: variationUpdate.overrideId ? `${programVersionId}|${variationUpdate.overrideId}` : variationUpdate.overrideId 9349 }); 9350 else variationsToDelete.push({ variationKey }); 9351 }); 9352 let input = { 9353 id: narrationId, 9354 updated: IGNORE_UPDATED, 9355 representativeKey: dbStructure.representativeKey, 9356 supportsCreativeDataElementOverride: dbStructure.creativeOverride, 9357 dimensionData: dbStructure.dimensionData, 9358 mergeData: dbStructure.mergeData, 9359 variationsToUpsert, 9360 variationsToDelete 9361 }; 9362 return services.graphQlClient.mutate({ 9363 mutation: UpdateNarrationDocument, 9364 variables: { 9365 input, 9366 dryRun: false 9367 } 9368 }); 9369 }).then((gqlOutput) => { 9370 if (gqlOutput.data.updateNarration.__typename === "UpdateNarrationOutputSuccess") { 9371 let graphQLUpdated = gqlOutput.data.updateNarration.narration.updated; 9372 dispatch(updateNarrationStructureAndVariationDataSuccess(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, mayCauseChangeInAssetLibrary, graphQLUpdated)); 9373 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9374 } 9375 }).catch(() => { 9376 dispatch(updateNarrationStructureAndVariationDataFailure(accountId, projectName, sceneId, narrationId, structureUpdate, variationReverts, variationDataMapReverts)); 9377 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9378 }); 9379 }; 9380}; 9381var addNarrationDimension = (accountId, projectName, sceneId, narrationId, valueSetProvider) => { 9382 return (dispatch, getState) => { 9383 let state = getState(); 9384 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 9385 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 9386 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.addDimension(wireframes.narrations.byId[narrationId].structure, valueSetProviders, valueSetProvider); 9387 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9388 }; 9389}; 9390var mergeNarrationVariations = (accountId, projectName, sceneId, narrationId, variationKeySets) => { 9391 return (dispatch, getState) => { 9392 let state = getState(); 9393 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9394 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.merge(wireframes.narrations.byId[narrationId].structure, wireframes.narrations.byId[narrationId].variations, variationKeySets); 9395 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9396 }; 9397}; 9398var unmergeNarrationPoints = (accountId, projectName, sceneId, narrationId, points) => { 9399 return (dispatch, getState) => { 9400 let state = getState(); 9401 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9402 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.unmerge(wireframes.narrations.byId[narrationId].structure, wireframes.narrations.byId[narrationId].variations, points); 9403 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9404 }; 9405}; 9406var acceptNarrationOrphansAndRemoved = (accountId, projectName, sceneId, narrationId) => { 9407 return (dispatch, getState) => { 9408 let state = getState(); 9409 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 9410 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 9411 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.acceptOrphansAndRemoved(wireframes.narrations.byId[narrationId].structure, wireframes.narrations.byId[narrationId].variationDataMap, wireframes.narrations.byId[narrationId].dimensions, valueSetProviders); 9412 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9413 }; 9414}; 9415var setNarrationDefaultText = (accountId, projectName, sceneId, scenePartIndex, narrationPartIndex, text) => { 9416 return (dispatch, getState) => { 9417 let state = getState(); 9418 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9419 let scenePart = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 9420 let narrationPart = scenePart.NarrationParts && scenePart.NarrationParts[narrationPartIndex]; 9421 if (StateReaderUtils.getNarrationsVersion(wireframes) > 0) { 9422 let defaultTextKey = StateReaderUtils.getNarrationDefaultTextKey(wireframes, narrationPart.id);
9423 if (defaultTextKey) dispatch(setNarrationText(accountId, projectName, sceneId, narrationPart.id, defaultTextKey, text)); 9424 } else { 9425 scenePart.NarrationParts[narrationPartIndex] = { 9426 ...narrationPart, 9427 mockValue: text 9428 }; 9429 dispatch(setProjectWireframesScenePart(accountId, projectName, sceneId, scenePart.scenePart, scenePart, scenePartIndex, true)); 9430 } 9431 }; 9432}; 9433var setNarrationRepresentative = (accountId, projectName, sceneId, narrationId, representativeKey) => { 9434 return (dispatch, getState) => { 9435 let state = getState(); 9436 if (StateReaderUtils.getWireFrame(state, projectName).narrations.byId[narrationId].variations.has(representativeKey)) { 9437 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.setRepresentativeKey(representativeKey); 9438 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, false)); 9439 } 9440 }; 9441}; 9442var setNarrationText = (accountId, projectName, sceneId, narrationId, variationKey, text) => { 9443 return (dispatch, getState) => { 9444 let state = getState(); 9445 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9446 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9447 let variation = wireframes.narrations.byId[narrationId].variations.get(variationKey); 9448 if (variation) { 9449 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.setText(variationKey, variationDataMap, variation.variationData, text); 9450 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9451 } 9452 }; 9453}; 9454var setNarrationComment = (accountId, projectName, sceneId, narrationId, variationKey, comment) => { 9455 return (dispatch, getState) => { 9456 let state = getState(); 9457 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9458 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9459 let variation = wireframes.narrations.byId[narrationId].variations.get(variationKey); 9460 if (variation) { 9461 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.setComment(variationKey, variationDataMap, variation.variationData, comment); 9462 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, false)); 9463 } 9464 }; 9465}; 9466var muteNarration = (accountId, projectName, sceneId, narrationId, variationKey) => { 9467 return (dispatch, getState) => { 9468 let state = getState(); 9469 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9470 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9471 let variation = wireframes.narrations.byId[narrationId].variations.get(variationKey); 9472 if (variation) { 9473 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.mute(variationKey, variationDataMap, variation.variationData); 9474 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9475 } 9476 }; 9477}; 9478var unmuteNarration = (accountId, projectName, sceneId, narrationId, variationKey) => { 9479 return (dispatch, getState) => { 9480 let state = getState(); 9481 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 9482 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9483 let variation = wireframes.narrations.byId[narrationId].variations.get(variationKey); 9484 if (variation) { 9485 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.unmute(variationKey, variationDataMap, variation.variationData); 9486 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, true)); 9487 } 9488 }; 9489}; 9490var addNarration = (accountId, projectName, sceneId, scenePartIndex) => { 9491 return (dispatch, getState, services) => { 9492 let structure = NarrationsModelUtils.defaultStructure(); 9493 let variationDataMap = NarrationsModelUtils.defaultVariationDataMap(); 9494 let dbStructure = { 9495 dimensionData: NarrationsModelUtils.dbExtractDimensionDataFromStructure(structure), 9496 mergeData: NarrationsModelUtils.dbExtractMergeDataFromStructure(structure), 9497 representativeKey: NarrationsModelUtils.dbExtractRepresentativeKeyFromStructure(structure), 9498 creativeOverride: false 9499 }; 9500 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 9501 let scenePart = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 9502 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.projectNarrationsServices.addNarration(accountId, projectName, sceneId, dbStructure).then((narrationId) => { 9503 dispatch(addNarrationSuccess(accountId, projectName, sceneId, narrationId, structure, variationDataMap)); 9504 let newNarrationPart = { id: narrationId }; 9505 let newNarrationParts = [...scenePart.NarrationParts, newNarrationPart]; 9506 let newScenePart = { 9507 ...scenePart, 9508 NarrationParts: newNarrationParts 9509 }; 9510 dispatch(setProjectWireframesScenePart(accountId, projectName, sceneId, newScenePart.scenePart, newScenePart, scenePartIndex, true)); 9511 return narrationId; 9512 }).then((narrationId) => { 9513 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 9514 let input = { 9515 scenePartId: `${programVersionId}|${sceneId}|${scenePart.postgresScenePartId || scenePart.scenePart}`, 9516 representativeKey: dbStructure.representativeKey, 9517 supportsCreativeDataElementOverride: dbStructure.creativeOverride, 9518 dimensionData: dbStructure.dimensionData, 9519 mergeData: dbStructure.mergeData 9520 }; 9521 services.graphQlClient.mutate({ 9522 mutation: CreateNarrationDocument, 9523 variables: { 9524 input, 9525 legacyId: narrationId, 9526 [IGNORE_SERVER_ERRORS]: true 9527 } 9528 }).catch((err) => {}); 9529 }).catch((err) => dispatch(reportError(err))); 9530 else { 9531 let input = { 9532 scenePartId: scenePart.graphQLId, 9533 representativeKey: dbStructure.representativeKey, 9534 supportsCreativeDataElementOverride: dbStructure.creativeOverride, 9535 dimensionData: dbStructure.dimensionData, 9536 mergeData: dbStructure.mergeData 9537 }; 9538 services.graphQlClient.mutate({ 9539 mutation: CreateNarrationDocument, 9540 variables: { input } 9541 }).then((gqlOutput) => { 9542 let { updated, id } = gqlOutput.data.createNarration.narration; 9543 dispatch(addNarrationSuccess(accountId, projectName, sceneId, id, structure, variationDataMap, void 0, updated)); 9544 let newNarrationParts = [...scenePart.NarrationParts, { id }]; 9545 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, { 9546 ...scenePart, 9547 NarrationParts: newNarrationParts 9548 }, scenePartIndex)); 9549 }).catch(() => {}); 9550 } 9551 }; 9552}; 9553var deleteNarration = (accountId, projectName, sceneId, scenePartIndex, narrationId) => { 9554 return (dispatch, getState, services) => { 9555 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 9556 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 9557 let scenePart = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 9558 if (!isPostgresOnly) { 9559 services.projectNarrationsServices.deleteNarration(accountId, projectName, sceneId, narrationId).then(() => { 9560 let newNarrationParts = scenePart.NarrationParts.filter((narrationPart) => narrationPart.id !== narrationId); 9561 let newScenePart = { 9562 ...scenePart, 9563 NarrationParts: newNarrationParts 9564 }; 9565 return services.wireframes.setProjectWireframesScenePart(accountId, projectName, sceneId, newScenePart.scenePart, newScenePart); 9566 }).then((scenePart) => { 9567 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, scenePart, scenePartIndex)); 9568 dispatch(deleteNarrationSuccess(accountId, projectName, sceneId, narrationId)); 9569 }).catch((err) => dispatch(reportError(err))); 9570 let programSummary = StateReaderUtils.getProgramSummaries(getState()).find((ps) => ps.projectIds.builders === projectName); 9571 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 9572 let scenePart = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 9573 const postgresNarrationId = StateReaderUtils.getNarrationPostgresId(wireframes, narrationId) || narrationId; 9574 const postgresScenePartId = scenePart.postgresScenePartId || scenePart.scenePart; 9575 let input = { id: `${programSummary.projectIds.builderDraftVersionId}|${sceneId}|${postgresScenePartId}|${postgresNarrationId}` }; 9576 services.graphQlClient.mutate({ 9577 mutation: DeleteNarrationDocument, 9578 variables: { 9579 input, 9580 [IGNORE_SERVER_ERRORS]: true 9581 } 9582 }).catch(() => {}); 9583 } else { 9584 let input = { id: narrationId }; 9585 services.graphQlClient.mutate({ 9586 mutation: DeleteNarrationDocument, 9587 variables: { input } 9588 }).then(() => { 9589 let newNarrationParts = scenePart.NarrationParts.filter((narrationPart) => narrationPart.id !== narrationId); 9590 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, { 9591 ...scenePart, 9592 NarrationParts: newNarrationParts 9593 }, scenePartIndex)); 9594 dispatch(deleteNarrationSuccess(accountId, projectName, sceneId, narrationId)); 9595 }).catch(() => {}); 9596 } 9597 }; 9598}; 9599var updateNarrationLibrary = (accountId, projectName, bulkAssetUpdates, bulkScenePartUpdates, bulkNarrationUpdates, programUpdates, assetToVariationKeyMap) => { 9600 return (dispatch, getState, services) => { 9601 dispatch(setLoadingForUpdateNarrationLibrary(true, accountId, projectName)); 9602 if (assetToVariationKeyMap) { 9603 let mergeData = Object.keys(assetToVariationKeyMap).reduce((acc, key) => { 9604 if (assetToVariationKeyMap[key].length > 1) { 9605 let splittedKey = key.split("/"); 9606 let sceneId = splittedKey[0]; 9607 let narrationId = splittedKey[1]; 9608 acc[sceneId + "/" + narrationId] = acc[sceneId + "/" + narrationId] || []; 9609 acc[sceneId + "/" + narrationId].push(assetToVariationKeyMap[key]); 9610 } 9611 return acc; 9612 }, {});
9613 Object.keys(mergeData).forEach((key) => { 9614 let splittedKey = key.split("/"); 9615 let sceneId = splittedKey[0]; 9616 let narrationId = splittedKey[1]; 9617 dispatch(mergeNarrationVariations(accountId, projectName, sceneId, narrationId, mergeData[key])); 9618 }); 9619 } 9620 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.bulkUpdateProjectWireframesSceneParts(accountId, projectName, bulkScenePartUpdates).then((responseBody) => { 9621 if (Object.keys(responseBody).every((scenePartId) => responseBody[scenePartId].status === 200)) { 9622 dispatch(ChangingBulkScenePartsSuccess(accountId, projectName, bulkScenePartUpdates)); 9623 return services.projectAssetsServices.updateRecordingAssets(accountId, projectName, bulkAssetUpdates); 9624 } else throw "Failed updating sceneParts"; 9625 }).then((response) => { 9626 const responseBody = response.response; 9627 dispatch(updateBulkAssetsSuccess(projectName, responseBody, recordingAssetType)); 9628 if (Object.keys(responseBody).every((assetName) => responseBody[assetName].status === 200)) return services.projectServices.updateProject(accountId, projectName, { 9629 RFR: programUpdates.RFR, 9630 RFRUpdateTimestamp: Date.now() 9631 }); 9632 }).then((updatedProgram) => { 9633 dispatch(updateProjectComplete(updatedProgram)); 9634 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9635 }).then(() => { 9636 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 9637 let input = { 9638 programVersionId, 9639 updated: IGNORE_UPDATED, 9640 RFR: programUpdates.RFR, 9641 narrationUpdates: [], 9642 narrationRecordingsToUpsert: [] 9643 }; 9644 services.graphQlClient.mutate({ 9645 mutation: CreateRfrVersionDocument, 9646 variables: { 9647 input, 9648 [IGNORE_SERVER_ERRORS]: true 9649 } 9650 }).catch(() => {}); 9651 }).catch((err) => { 9652 dispatch(reportError(err)); 9653 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9654 }); 9655 else { 9656 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 9657 const narrationUpdates = Object.keys(bulkNarrationUpdates).map((id) => { 9658 return { 9659 narrationId: id, 9660 updated: IGNORE_UPDATED, 9661 lastUsedRecordingFileName: bulkNarrationUpdates[id].lastUsedRecordingFileName 9662 }; 9663 }); 9664 const narrationRecordingsToUpsert = Object.keys(bulkAssetUpdates).map((assetName) => { 9665 const recordingAsset = StateReaderUtils.getAsset(getState(), accountId, projectName, AssetTypes.recording, assetName); 9666 const recordingAssetUpdates = bulkAssetUpdates[assetName]; 9667 const { narrationId, key } = AssetUtils.deconstructRecordingAssetName(assetName); 9668 return { 9669 narrationRecordingId: recordingAsset && recordingAsset.graphQLId, 9670 updated: IGNORE_UPDATED, 9671 narrationId, 9672 key, 9673 filename: recordingAssetUpdates.filename, 9674 text: recordingAssetUpdates.narrationMetadata?.text, 9675 rfr: recordingAssetUpdates.RFR, 9676 metadata: recordingAssetUpdates.narrationMetadata 9677 }; 9678 }); 9679 let input = { 9680 programVersionId, 9681 updated: IGNORE_UPDATED, 9682 RFR: programUpdates.RFR, 9683 narrationUpdates, 9684 narrationRecordingsToUpsert 9685 }; 9686 services.graphQlClient.mutate({ 9687 mutation: CreateRfrVersionDocument, 9688 variables: { input } 9689 }).then((result) => { 9690 if (result.data.createRFRVersion.__typename === "CreateRFRVersionOutputSuccess") { 9691 dispatch(ChangingBulkScenePartsSuccess(accountId, projectName, bulkScenePartUpdates)); 9692 const programVersion = result.data.createRFRVersion.programVersion; 9693 dispatch(updateProjectComplete({ 9694 ...programUpdates, 9695 projectName, 9696 RFRUpdateTimestamp: Date.now(), 9697 graphQLUpdated: programVersion.updated 9698 })); 9699 const bulkResponse = {}; 9700 const recordingsByAssetName = convertArrayOfObjectsToObjectWithKeys(programVersion.narrationRecordings, ["narrationId", "key"], (narrationId, key) => getRecordingAssetNameByKey(narrationId, defaultNarratorId, key)); 9701 Object.keys(bulkAssetUpdates).forEach((assetName) => { 9702 const asset = StateReaderUtils.getAsset(getState(), accountId, projectName, AssetTypes.recording, assetName); 9703 const gqlNarrationRecording = recordingsByAssetName[assetName]; 9704 const assetUpdates = asset ? { 9705 ...bulkAssetUpdates[assetName], 9706 graphQLUpdated: programVersion.updated 9707 } : { 9708 ...bulkAssetUpdates[assetName], 9709 version: 0, 9710 activeVersion: 0, 9711 status: STATUS_REQUEST, 9712 type: AssetTypes.recording, 9713 assetId: StateReaderUtils.getAssetId(AssetTypes.recording, assetName), 9714 name: assetName, 9715 mediaType: MediaTypes.Audio, 9716 graphQLUpdated: gqlNarrationRecording.updated, 9717 graphQLId: gqlNarrationRecording.id, 9718 isPostgresAsset: true, 9719 createdTime: Date.now(), 9720 updatedTime: Date.now() 9721 }; 9722 bulkResponse[assetName] = { 9723 status: 200, 9724 response: assetUpdates 9725 }; 9726 }); 9727 dispatch(updateBulkAssetsSuccess(projectName, bulkResponse, recordingAssetType)); 9728 } 9729 }).catch(() => {}).finally(() => { 9730 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9731 }); 9732 } 9733 }; 9734}; 9735var DE_COLUMN_PREFIX = "DataElement_";
9736var TEXT_COLUMN_NAME = "Approved Narration"; 9737var validateColumns = (csvColumns, dimensions) => { 9738 if (!csvColumns.includes(TEXT_COLUMN_NAME)) return false; 9739 return csvColumns.filter((column) => column.startsWith(DE_COLUMN_PREFIX)).every((deColumn) => { 9740 let deName = deColumn.slice(12); 9741 return dimensions.some((dim) => dim.name === deName); 9742 }); 9743}; 9744var getValueId = index((valueName, dimension) => { 9745 let normalize = normalizeValueSetValueDisplayName; 9746 let type = dimension.type; 9747 let value = dimension.valueSet.find((value) => normalize(value.dn, type) === normalize(valueName, type) || !valueName && value.dn.startsWith("~~~")); 9748 return value ? value.id : null; 9749}); 9750var buildVariationDataUpdateFromCSVRow = (csvRow, dimensions, variations, textColumnIndex) => { 9751 let valueIds = csvRow.slice(0, dimensions.size).map((valueName, index) => { 9752 return getValueId(valueName, dimensions.get(index)); 9753 }); 9754 if (valueIds.includes(null)) return null; 9755 let key = NarrationsModelUtils.generateKey([valueIds]); 9756 if (!variations.has(key)) return {}; 9757 return { [key]: { text: csvRow[textColumnIndex] } }; 9758}; 9759var buildVariationDataUpdatesFromCSVData = (csvData, dimensions, variations, textColumnIndex) => { 9760 let variationDataUpdates = {}; 9761 for (let i = 0; i < csvData.length; ++i) { 9762 let row = csvData[i]; 9763 let rowUpdates = buildVariationDataUpdateFromCSVRow(row, dimensions, variations, textColumnIndex); 9764 if (rowUpdates !== null) Object.assign(variationDataUpdates, rowUpdates); 9765 else return { 9766 errorLine: i + 2, 9767 result: null 9768 }; 9769 } 9770 return { 9771 errorLine: -1, 9772 result: variationDataUpdates 9773 }; 9774}; 9775var updateNarrationFromCSVData = (accountId, projectName, sceneId, narrationId, csvData) => { 9776 return (dispatch, getState) => { 9777 dispatch(setLoadingForUpdateNarrationLibrary(true, accountId, projectName)); 9778 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 9779 let csvColumns = csvData[0]; 9780 let dimensions = StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId); 9781 let variations = StateReaderUtils.getNarrationTableVariations(wireframes, narrationId); 9782 if (!validateColumns(csvColumns, dimensions)) { 9783 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9784 dispatch(reportErrorSuccess("One or more of the column names in the file do not match the data elements defined for this narration, please fix accordingly.")); 9785 return null; 9786 } 9787 csvData.splice(0, 1); 9788 let result = buildVariationDataUpdatesFromCSVData(csvData, dimensions, variations, csvColumns.findIndex((col) => col === TEXT_COLUMN_NAME)); 9789 if (result.result) dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, null, result.result, true)); 9790 else { 9791 dispatch(setLoadingForUpdateNarrationLibrary(false, accountId, projectName)); 9792 dispatch(reportErrorSuccess("There is an invalid input in row " + result.errorLine + ". Please check that the input matches the narration's values.")); 9793 } 9794 }; 9795}; 9796var removeDimensionsFromDerivedLogic = (dimensions, context) => { 9797 if (!context.derivedLogic) return; 9798 context.derivedLogic = Object.keys(context.derivedLogic).reduce((acc, deId) => { 9799 if (!dimensions.find((dimension) => { 9800 return dimension.id.includes(deId); 9801 })) acc[deId] = context.derivedLogic[deId]; 9802 return acc; 9803 }, {}); 9804}; 9805var createDataElementsFromDimensions = (dimensions) => { 9806 return dimensions.map((dim) => { 9807 return buildDataElement({ 9808 id: dim.id, 9809 name: dim.name, 9810 type: DataElementContentTypes.String, 9811 origin: DataElementOrigins.Feed, 9812 displayName: dim.name 9813 }); 9814 }).toArray(); 9815}; 9816var _calcValueForVariation = (variation, dimensions, logic, context, dtaasEndPoint) => { 9817 let dataElementsValues = dimensions.map((dimension, index) => { 9818 let dimensionName = dimension.name; 9819 let variationCoord = variation.points.first().get(index); 9820 return { 9821 name: dimensionName, 9822 value: dimension.valueSet.find((value) => value.id === variationCoord).dn 9823 }; 9824 }).toArray(); 9825 removeDimensionsFromDerivedLogic(dimensions, context); 9826 return testSingleInputLogic(logic, dataElementsValues, context.derivedLogic, [], dtaasEndPoint, { dataElements: context.dataElements }).then((testResult) => { 9827 let result = testResult.result && testResult.result.toString(); 9828 if (result && result.includes("~~~")) result = ""; 9829 return result; 9830 }); 9831}; 9832var updateNarrationFromLogic = (accountId, projectName, sceneId, narrationId, logic, affectedKeys) => { 9833 return (dispatch, getState) => { 9834 dispatch(setLoadingForUpdateNarrationLibrary(true, accountId, projectName)); 9835 const state = getState(); 9836 let project = StateReaderUtils.getProject(state, projectName); 9837 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 9838 let dataElements = StateReaderUtils.getProjectDataElements(state, projectName); 9839 let mappingTables = StateReaderUtils.getProjectAssetsByType(project, state.assets, ASSET_TYPES.mappingTable); 9840 let derivedLogic = StateReaderUtils.getAllProgramLogic(state, projectName, LOGIC_CONTEXT.Derived); 9841 let variations = StateReaderUtils.getNarrationTableVariations(wireframes, narrationId); 9842 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9843 let dimensions = StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId); 9844 const dtaasEndPoint = StateReaderUtils.getdtaasEndPoint(state); 9845 let tempDataElements = createDataElementsFromDimensions(dimensions); 9846 let effectiveDataElements = [...dataElements, ...tempDataElements]; 9847 let finalVariationDataUpdates = {}; 9848 let promises = affectedKeys.map((key) => { 9849 if (NarrationsModelUtils.isExpandedPoint(key)) return Promise.resolve(); 9850 let variation = variations.get(key); 9851 return _calcValueForVariation(variation, dimensions, logic, { 9852 derivedLogic, 9853 dataElements: effectiveDataElements, 9854 mappingTables 9855 }, dtaasEndPoint).then((result) => { 9856 let { variationDataUpdates } = NarrationsModelUtils.setText(key, variationDataMap, variation.variationData, result); 9857 if (variationDataUpdates) Object.assign(finalVariationDataUpdates, variationDataUpdates); 9858 }); 9859 }); 9860 Promise.all(promises).then(() => { 9861 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, null, finalVariationDataUpdates, true)); 9862 }); 9863 }; 9864}; 9865var addOrRemoveCreative = (accountId, projectName, sceneId, narrationId, addOrRemove) => { 9866 return (dispatch, getState) => { 9867 let state = getState(); 9868 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 9869 const structure = wireframes.narrations.byId[narrationId].structure; 9870 const variations = wireframes.narrations.byId[narrationId].variations;
9871 const variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9872 const supportCreativeOverride = addOrRemove === "add"; 9873 const { structureUpdate, variationDataUpdates } = NarrationsModelUtils.setSupportCreativeOverride(structure, variations, variationDataMap, supportCreativeOverride); 9874 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, false)); 9875 }; 9876}; 9877var overrideWithCreative = (accountId, projectName, sceneId, narrationId, variationKey, overrideId) => { 9878 return (dispatch, getState) => { 9879 let state = getState(); 9880 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 9881 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 9882 let variation = wireframes.narrations.byId[narrationId].variations.get(variationKey); 9883 if (variation) { 9884 let { structureUpdate, variationDataUpdates } = NarrationsModelUtils.setOverrideId(variationKey, variationDataMap, variation.variationData, overrideId); 9885 dispatch(updateNarrationStructureAndVariationData(accountId, projectName, sceneId, narrationId, structureUpdate, variationDataUpdates, false)); 9886 } 9887 }; 9888}; 9889//#endregion 9890//#region common/types/scene.ts 9891var ParameterTypes = /* @__PURE__ */ function(ParameterTypes) { 9892 ParameterTypes["parameter"] = "parameter"; 9893 ParameterTypes["color"] = "color"; 9894 return ParameterTypes; 9895}({}); 9896var PlaceholderType = /* @__PURE__ */ function(PlaceholderType) { 9897 PlaceholderType["HOTSPOT"] = "hotspot"; 9898 PlaceholderType["TEXT"] = "text"; 9899 PlaceholderType["IMAGE"] = "image"; 9900 PlaceholderType["VIDEO"] = "video"; 9901 return PlaceholderType; 9902}({}); 9903//#endregion 9904//#region common/types/lifecycle.ts 9905var Stages = /* @__PURE__ */ function(Stages) { 9906 Stages["dev"] = "dev"; 9907 Stages["UAT"] = "uat"; 9908 Stages["prod"] = "prod"; 9909 return Stages; 9910}({}); 9911//#endregion 9912//#region client/logic/builder/graphql/convertTypes.ts 9913var convertDataElementType = (type) => { 9914 switch (type) { 9915 case DataElementContentTypes.Boolean: return GqlClientDataElementType.BOOLEAN; 9916 case DataElementContentTypes.String: return GqlClientDataElementType.STRING; 9917 case DataElementContentTypes.Number: return GqlClientDataElementType.NUMBER; 9918 case DataElementContentTypes.Date: return GqlClientDataElementType.DATETIME; 9919 case DataElementContentTypes.Url: return GqlClientDataElementType.URL; 9920 case CreativeDataElementContentTypes.Audio: return GqlClientDataElementType.AUDIO; 9921 case CreativeDataElementContentTypes.Image: return GqlClientDataElementType.IMAGE; 9922 case CreativeDataElementContentTypes.Video: return GqlClientDataElementType.VIDEO; 9923 case CreativeDataElementContentTypes.Color: return GqlClientDataElementType.COLOR; 9924 case CreativeDataElementContentTypes.Narration: return GqlClientDataElementType.NARRATION; 9925 default: return; 9926 } 9927}; 9928var convertDataElementTypeReverse = (type) => { 9929 switch (type) { 9930 case GqlClientDataElementType.BOOLEAN: return DataElementContentTypes.Boolean; 9931 case GqlClientDataElementType.STRING: return DataElementContentTypes.String; 9932 case GqlClientDataElementType.NUMBER: return DataElementContentTypes.Number; 9933 case GqlClientDataElementType.DATETIME: return DataElementContentTypes.Date; 9934 case GqlClientDataElementType.URL: return DataElementContentTypes.Url; 9935 case GqlClientDataElementType.AUDIO: return CreativeDataElementContentTypes.Audio; 9936 case GqlClientDataElementType.IMAGE: return CreativeDataElementContentTypes.Image; 9937 case GqlClientDataElementType.VIDEO: return CreativeDataElementContentTypes.Video; 9938 case GqlClientDataElementType.COLOR: return CreativeDataElementContentTypes.Color; 9939 case GqlClientDataElementType.NARRATION: return CreativeDataElementContentTypes.Narration; 9940 default: return; 9941 } 9942}; 9943var convertDataElementStatus = (status) => { 9944 switch (status) { 9945 case DataElementStatuses.Approved: return GqlClientFeedDataElementStatus.APPROVED; 9946 case DataElementStatuses.Pending: return GqlClientFeedDataElementStatus.PENDING; 9947 case DataElementStatuses.Missing: return GqlClientFeedDataElementStatus.MISSING; 9948 default: return; 9949 } 9950}; 9951var convertDataElementStatusReverse = (status) => { 9952 switch (status) { 9953 case GqlClientFeedDataElementStatus.APPROVED: return DataElementStatuses.Approved; 9954 case GqlClientFeedDataElementStatus.PENDING: return DataElementStatuses.Pending; 9955 case GqlClientFeedDataElementStatus.MISSING: return DataElementStatuses.Missing; 9956 default: return; 9957 } 9958}; 9959var convertPlaceholderTypeReverse = (type) => { 9960 switch (type) { 9961 case GqlClientPlaceholderType.HOTSPOT: return PlaceholderType.HOTSPOT; 9962 case GqlClientPlaceholderType.IMAGE: return PlaceholderType.IMAGE; 9963 case GqlClientPlaceholderType.TEXT: return PlaceholderType.TEXT; 9964 case GqlClientPlaceholderType.VIDEO: return PlaceholderType.VIDEO; 9965 default: return; 9966 } 9967}; 9968var convertAnimationGuidelineType = (type) => { 9969 switch (type) { 9970 case ParameterTypes.color: return GqlClientAnimationGuidelineType.COLOR; 9971 case ParameterTypes.parameter: return GqlClientAnimationGuidelineType.TEXT; 9972 default: return; 9973 } 9974}; 9975var convertAnimationGuidelineTypeReverse = (type) => { 9976 switch (type) { 9977 case GqlClientAnimationGuidelineType.COLOR: return ParameterTypes.color; 9978 case GqlClientAnimationGuidelineType.TEXT: return ParameterTypes.parameter; 9979 default: return; 9980 } 9981};
9982var convertBackgroundAssetTypeReverse = (type) => { 9983 switch (type) { 9984 case GqlClientBackgroundAssetType.VIDEO: return MediaTypes.Video; 9985 case GqlClientBackgroundAssetType.IMAGE: return MediaTypes.Image; 9986 default: return; 9987 } 9988}; 9989var convertStoryRationAndQualityOptionsTypeReverse = (ratioAndQualityOption) => { 9990 const convertRatio = (ratio) => { 9991 switch (ratio) { 9992 case VideoAspectRatio.SQUARE: return VideoAspectRatio.SQUARE; 9993 case VideoAspectRatio.FULL_LANDSCAPE: return VideoAspectRatio.FULL_LANDSCAPE; 9994 case VideoAspectRatio.FULL_PORTRAIT: return VideoAspectRatio.FULL_PORTRAIT; 9995 default: return; 9996 } 9997 }; 9998 const convertQuality = (quality) => { 9999 switch (quality) { 10000 case VideoQualityProfile.SD: return VideoQualityProfile.SD; 10001 case VideoQualityProfile.SD_INTERMEDIATE: return VideoQualityProfile.SD_INTERMEDIATE; 10002 case VideoQualityProfile.SD_HIGH: return VideoQualityProfile.SD_HIGH; 10003 case VideoQualityProfile.HD: return VideoQualityProfile.HD; 10004 case VideoQualityProfile.HD_READY: return VideoQualityProfile.HD_READY; 10005 case VideoQualityProfile.HD_READY_INTERMEDIATE: return VideoQualityProfile.HD_READY_INTERMEDIATE; 10006 case VideoQualityProfile.HD_READY_HIGH: return VideoQualityProfile.HD_READY_HIGH; 10007 default: return; 10008 } 10009 }; 10010 return { 10011 ratio: convertRatio(ratioAndQualityOption?.ratio), 10012 quality: convertQuality(ratioAndQualityOption?.quality) 10013 }; 10014}; 10015var convertProgramTypeReverse = (programType) => { 10016 switch (programType) { 10017 case GqlClientProgramType.CRM: return ProgramType.CRM; 10018 case GqlClientProgramType.ADS: return ProgramType.Ads; 10019 default: return; 10020 } 10021}; 10022var convertStageType = (stage) => { 10023 switch (stage) { 10024 case Stages.dev: return GqlClientLifecycleStage.DEV; 10025 case Stages.UAT: return GqlClientLifecycleStage.UAT; 10026 case Stages.prod: return GqlClientLifecycleStage.PROD; 10027 default: return; 10028 } 10029}; 10030var convertStageTypeReverse = (stage) => { 10031 switch (stage) { 10032 case GqlClientLifecycleStage.DEV: return Stages.dev; 10033 case GqlClientLifecycleStage.UAT: return Stages.UAT; 10034 case GqlClientLifecycleStage.PROD: return Stages.prod; 10035 default: return; 10036 } 10037}; 10038var convertNarrationRecordingErrorReason = (errorReason) => { 10039 switch (errorReason) { 10040 case GqlClientNarrationRecordingErrorReason.BADINTONATION: return NarrationRecordingErrorReason.BADINTONATION; 10041 case GqlClientNarrationRecordingErrorReason.CORRUPTED: return NarrationRecordingErrorReason.CORRUPTED; 10042 case GqlClientNarrationRecordingErrorReason.OTHER: return NarrationRecordingErrorReason.OTHER; 10043 case GqlClientNarrationRecordingErrorReason.TEXTDOESNOTMATCH: return NarrationRecordingErrorReason.TEXTDOESNOTMATCH; 10044 default: return; 10045 } 10046}; 10047//#endregion 10048//#region client/logic/common/convertGqlPresetUtils.ts 10049var convertGqlPresetsResult = (gqlResult) => { 10050 return (gqlResult?.data?.program?.programVersion?.presets)?.reduce((acc, preset) => { 10051 const presetId = getIdFromGqlId(preset.id); 10052 let presetData = {}; 10053 if (!preset.isCreative) { 10054 presetData = [...preset.systemElementValues, ...preset.dataElementValues].reduce((data, dataElement) => { 10055 const elementId = dataElement?.systemElementId || getIdFromGqlId(dataElement?.id); 10056 data[elementId] = { 10057 id: elementId, 10058 type: dataElement?.type, 10059 value: parseDataElementValue(dataElement) 10060 }; 10061 if (dataElement?.valueId !== null && dataElement?.valueId !== void 0) data[elementId].valueId = dataElement?.valueId; 10062 return data; 10063 }, {}); 10064 acc[presetId] = { 10065 id: presetId, 10066 name: preset.name, 10067 data: presetData, 10068 graphQLId: preset.id, 10069 graphQLUpdated: preset.updated 10070 }; 10071 } else acc[CREATIVES_PRESET_ID] = { 10072 id: CREATIVES_PRESET_ID, 10073 name: "Creatives Preset", 10074 data: preset.dataElementValues?.reduce((data, dataElement) => { 10075 const dataElementId = getIdFromGqlId(dataElement?.id); 10076 data[dataElementId] = parseDataElementValue(dataElement); 10077 return data; 10078 }, {}), 10079 graphQLId: preset.id, 10080 graphQLUpdated: preset.updated 10081 }; 10082 return acc; 10083 }, {}); 10084}; 10085var parseDataElementValue = (dataElement) => { 10086 return dataElement?.value !== null && dataElement?.value !== void 0 ? JSON.parse(dataElement.value) : dataElement.value; 10087}; 10088var convertGqlPresetsWithoutValuesResult = (gqlResult, existingPresets) => { 10089 return (gqlResult?.data?.program?.programVersion?.presets)?.reduce((acc, preset) => { 10090 const presetId = getIdFromGqlId(preset.id); 10091 if (!preset.isCreative) { 10092 const existingPreset = existingPresets?.[presetId]; 10093 acc[presetId] = { 10094 id: presetId, 10095 name: preset.name, 10096 data: existingPreset?.graphQLId === preset.id ? existingPreset.data : {}, 10097 graphQLId: preset.id, 10098 graphQLUpdated: preset.updated 10099 }; 10100 } else {
10101 const existingPreset = existingPresets?.[CREATIVES_PRESET_ID]; 10102 acc[CREATIVES_PRESET_ID] = { 10103 id: CREATIVES_PRESET_ID, 10104 name: "Creatives Preset", 10105 data: existingPreset?.graphQLId === preset.id ? existingPreset.data : {}, 10106 graphQLId: preset.id, 10107 graphQLUpdated: preset.updated 10108 }; 10109 } 10110 return acc; 10111 }, {}); 10112}; 10113var convertGqlPresetValuesResultAndAddToPresetMap = (gqlResult, presets) => { 10114 const preset = gqlResult?.data?.program?.programVersion?.preset; 10115 let existingPreset; 10116 let presetData; 10117 if (!preset.isCreative) { 10118 const presetId = getIdFromGqlId(preset.id); 10119 presetData = [...preset.systemElementValues, ...preset.dataElementValues].reduce((data, dataElement) => { 10120 const elementId = dataElement?.systemElementId || getIdFromGqlId(dataElement?.id); 10121 data[elementId] = { 10122 id: elementId, 10123 type: dataElement?.type, 10124 value: parseDataElementValue(dataElement) 10125 }; 10126 if (dataElement?.valueId !== null && dataElement?.valueId !== void 0) data[elementId].valueId = dataElement?.valueId; 10127 return data; 10128 }, {}); 10129 existingPreset = presets[presetId]; 10130 } else { 10131 presetData = preset.dataElementValues?.reduce((data, dataElement) => { 10132 const dataElementId = getIdFromGqlId(dataElement?.id); 10133 data[dataElementId] = parseDataElementValue(dataElement); 10134 return data; 10135 }, {}); 10136 existingPreset = presets[CREATIVES_PRESET_ID]; 10137 } 10138 return { 10139 ...presets, 10140 [existingPreset.id]: { 10141 ...existingPreset, 10142 data: presetData 10143 } 10144 }; 10145}; 10146//#endregion 10147//#region common/types/snapshot.ts 10148var SnapshotSource = /* @__PURE__ */ function(SnapshotSource) { 10149 SnapshotSource["DYNAMO"] = "Dynamo"; 10150 SnapshotSource["POSTGRES"] = "Postgres"; 10151 return SnapshotSource; 10152}({}); 10153//#endregion 10154//#region client/logic/projects/projectWireframes/projectsWireframesActions.ts 10155var LOADING_PROJECT_WIREFRAMES_FROM_UIASSET = "LOADING_PROJECT_WIREFRAMES_FROM_UIASSET"; 10156var loadingProjectWireframesFromUIAsset = (0, import_lib$3.createAction)(LOADING_PROJECT_WIREFRAMES_FROM_UIASSET, (accountId, projectName, data, stage, version) => { 10157 return { 10158 accountId, 10159 projectName, 10160 data, 10161 stage, 10162 version 10163 }; 10164}, void 0); 10165var ADDING_PROJECT_WIREFRAMES_SCENE_SUCCESS = "ADDING_PROJECT_WIREFRAMES_SCENE_SUCCESS"; 10166var addingProjectWireframesSceneSuccess = (0, import_lib$3.createAction)(ADDING_PROJECT_WIREFRAMES_SCENE_SUCCESS, function(accountId, projectName, sceneId, sceneData) { 10167 return { 10168 accountId, 10169 projectName, 10170 sceneId, 10171 sceneData 10172 }; 10173}); 10174var ADDING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS = "ADDING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS"; 10175var AddingProjectWireframesScenePartsSuccess = (0, import_lib$3.createAction)(ADDING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS, function(accountId, projectName, sceneId, scenePart) { 10176 return { 10177 accountId, 10178 projectName, 10179 sceneId, 10180 scenePart 10181 }; 10182}); 10183var CHANGING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS = "CHANGING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS"; 10184var ChangingProjectWireframesScenePartsSuccess = (0, import_lib$3.createAction)(CHANGING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS, function(accountId, projectName, sceneId, scenePart, scenePartIndex) { 10185 return { 10186 accountId, 10187 projectName, 10188 sceneId, 10189 scenePart, 10190 scenePartIndex 10191 }; 10192}, void 0); 10193var CHANGING_BULK_SCENE_PARTS_SUCCESS = "CHANGING_BULK_SCENE_PARTS_SUCCESS"; 10194var ChangingBulkScenePartsSuccess = (0, import_lib$3.createAction)(CHANGING_BULK_SCENE_PARTS_SUCCESS, function(accountId, projectName, bulkSceneParts) { 10195 return { 10196 accountId, 10197 projectName, 10198 bulkSceneParts 10199 }; 10200}); 10201var CHANGING_PROJECT_WIREFRAMES_SCENE_SUCCESS = "CHANGING_PROJECT_WIREFRAMES_SCENE_SUCCESS"; 10202var changingProjectWireframesSceneSuccess = (0, import_lib$3.createAction)(CHANGING_PROJECT_WIREFRAMES_SCENE_SUCCESS, function(accountId, projectName, sceneId, sceneData) { 10203 return { 10204 accountId, 10205 projectName, 10206 sceneId, 10207 sceneData 10208 }; 10209}); 10210var CHANGING_PROJECT_WIREFRAMES_STORY_SUCCESS = "CHANGING_PROJECT_WIREFRAMES_STORY_SUCCESS"; 10211var DELETING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS = "DELETING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS"; 10212var deletingProjectWireframesScenePartsSuccess = (0, import_lib$3.createAction)(DELETING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS, function(accountId, projectName, sceneId, scenePartIndex) { 10213 return { 10214 accountId, 10215 projectName, 10216 sceneId, 10217 scenePartIndex 10218 }; 10219}); 10220var DELETING_PROJECT_WIREFRAMES_SCENE_SUCCESS = "DELETING_PROJECT_WIREFRAMES_SCENE_SUCCESS"; 10221var deletingProjectWireframesSceneSuccess = (0, import_lib$3.createAction)(DELETING_PROJECT_WIREFRAMES_SCENE_SUCCESS, function(accountId, projectName, sceneId) { 10222 return { 10223 accountId, 10224 projectName, 10225 sceneId 10226 }; 10227}); 10228var UPDATING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC_SUCCESS = "UPDATING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC_SUCCESS"; 10229var updatingProjectWireFramesSceneInputLogicSuccess = (0, import_lib$3.createAction)(UPDATING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC_SUCCESS, function(accountId, projectName, sceneId, inputName, logicData, stage, version) { 10230 return { 10231 accountId, 10232 projectName, 10233 sceneId, 10234 inputName, 10235 logicData, 10236 stage, 10237 version 10238 }; 10239}, void 0); 10240var VALUE_SETS_CHANGED = "VALUE_SETS_CHANGED"; 10241var valueSetsChanged = (0, import_lib$3.createAction)(VALUE_SETS_CHANGED, function(accountId, projectName, dataElementIds) { 10242 return { 10243 accountId, 10244 projectName, 10245 dataElementIds 10246 }; 10247}); 10248var LOADING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC = "LOADING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC"; 10249var loadingProjectWireFramesSceneInputLogic = (0, import_lib$3.createAction)(LOADING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC, function(accountId, projectName, sceneId, inputName, stage, version) { 10250 return { 10251 accountId, 10252 projectName, 10253 sceneId, 10254 inputName, 10255 stage, 10256 version 10257 }; 10258}, void 0); 10259var ADDING_PROJECT_WIREFRAMES_SCENE_PART_STORYBOARD_FRAME_SUCCESS = "ADDING_PROJECT_WIREFRAMES_SCENE_PART_STORYBOARD_FRAME_SUCCESS"; 10260var addingProjectWireframesScenePartStoryboardFrameSuccess = (0, import_lib$3.createAction)(ADDING_PROJECT_WIREFRAMES_SCENE_PART_STORYBOARD_FRAME_SUCCESS, function(accountId, projectName, sceneId, scenePartId, scenePartData, scenePartIndex) { 10261 return { 10262 accountId, 10263 projectName, 10264 sceneId, 10265 scenePartId, 10266 scenePartData, 10267 scenePartIndex 10268 }; 10269}, void 0); 10270var LOADING_PROGRAM_WIREFRAMES_SUCCESS = "LOADING_PROGRAM_WIREFRAMES_SUCCESS"; 10271var loadingProgramWireframeSuccess = (0, import_lib$3.createAction)(LOADING_PROGRAM_WIREFRAMES_SUCCESS, function(accountId, projectName, initialWireframes, dataElements, logicData, programLogic, storiesLogic, narrations, stage, version, calculateDeriveCycles) { 10272 return { 10273 accountId, 10274 projectName, 10275 initialWireframes, 10276 dataElements, 10277 logicData, 10278 programLogic, 10279 storiesLogic, 10280 narrations, 10281 stage, 10282 version, 10283 calculateDeriveCycles 10284 }; 10285}, void 0); 10286var DELETING_PROJECT_WIREFRAMES_INPUT_LOGICS_SUCCESS = "DELETING_PROJECT_WIREFRAMES_INPUT_LOGICS_SUCCESS"; 10287var deletingProjectWireFramesInputLogicSuccess = (0, import_lib$3.createAction)(DELETING_PROJECT_WIREFRAMES_INPUT_LOGICS_SUCCESS, function(accountId, projectName, sceneId, logicName) { 10288 return { 10289 accountId, 10290 projectName, 10291 sceneId, 10292 logicName
10293 }; 10294}); 10295var DELETING_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS = "DELETING_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS"; 10296var deleteMasterAnimationGuidelineSuccess = (0, import_lib$3.createAction)(DELETING_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS, function(projectName, animationName) { 10297 return { 10298 projectName, 10299 animationName 10300 }; 10301}); 10302var CREATE_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS = "CREATE_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS"; 10303var createMasterAnimationGuidelineSuccess = (0, import_lib$3.createAction)(CREATE_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS, function(projectName, animationGuideline) { 10304 return { 10305 projectName, 10306 animationGuideline 10307 }; 10308}); 10309var RENAME_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS = "RENAME_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS"; 10310var renameMasterAnimationGuidelineSuccess = (0, import_lib$3.createAction)(RENAME_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS, function(projectName, updatedAnimationGuidelineIndex, updatedAnimationGuideline) { 10311 return { 10312 projectName, 10313 updatedAnimationGuidelineIndex, 10314 updatedAnimationGuideline 10315 }; 10316}); 10317var ADDING_PROJECT_WIREFRAMES_PRESET_SUCCESS = "ADDING_PROJECT_WIREFRAMES_PRESET_SUCCESS"; 10318var AddingProjectWireframesPresetSuccess = (0, import_lib$3.createAction)(ADDING_PROJECT_WIREFRAMES_PRESET_SUCCESS, function(accountId, projectName, preset) { 10319 return { 10320 accountId, 10321 projectName, 10322 preset 10323 }; 10324}); 10325var CHANGING_PROJECT_WIREFRAMES_PRESET_SUCCESS = "CHANGING_PROJECT_WIREFRAMES_PRESET_SUCCESS"; 10326var changingProjectWireframesPresetSuccess = (0, import_lib$3.createAction)(CHANGING_PROJECT_WIREFRAMES_PRESET_SUCCESS, function(accountId, projectName, presetId, presetData) { 10327 return { 10328 accountId, 10329 projectName, 10330 presetId, 10331 presetData 10332 }; 10333}); 10334var DELETING_PROJECT_WIREFRAMES_PRESET_SUCCESS = "DELETING_PROJECT_WIREFRAMES_PRESET_SUCCESS"; 10335var deletingProjectWireFramesPresetSuccess = (0, import_lib$3.createAction)(DELETING_PROJECT_WIREFRAMES_PRESET_SUCCESS, function(accountId, projectName, presetId) { 10336 return { 10337 accountId, 10338 projectName, 10339 presetId 10340 }; 10341}); 10342var LOADING_PROJECT_WIREFRAMES_PRESETS_SUCCESS = "LOADING_PROJECT_WIREFRAMES_PRESETS_SUCCESS"; 10343var loadingProjectWireframesPresetsSuccess = (0, import_lib$3.createAction)(LOADING_PROJECT_WIREFRAMES_PRESETS_SUCCESS, function(accountId, projectName, presets) { 10344 return { 10345 accountId, 10346 projectName, 10347 presets 10348 }; 10349}); 10350var SET_CUSTOM_ANALYTICS_ORDER_SUCCESS = "SET_CUSTOM_ANALYTICS_ORDER_SUCCESS"; 10351var setCustomAnalyticsOrderSuccess = (0, import_lib$3.createAction)(SET_CUSTOM_ANALYTICS_ORDER_SUCCESS, function(accountId, projectName, analyticsOrder, updated) { 10352 return { 10353 accountId, 10354 projectName, 10355 analyticsOrder, 10356 updated 10357 }; 10358}); 10359var SET_CUSTOM_ANALYTIC_FIELD_SUCCESS = "SET_CUSTOM_ANALYTIC_FIELD_SUCCESS"; 10360var setCustomAnalyticFieldSuccess = (0, import_lib$3.createAction)(SET_CUSTOM_ANALYTIC_FIELD_SUCCESS, function(accountId, projectName, analyticFieldUpdates) { 10361 return { 10362 accountId, 10363 projectName, 10364 analyticFieldUpdates 10365 }; 10366}); 10367var ADD_CUSTOM_ANALYTIC_FIELD_SUCCESS = "ADD_CUSTOM_ANALYTIC_FIELD_SUCCESS"; 10368var addCustomAnalyticFieldSuccess = (0, import_lib$3.createAction)(ADD_CUSTOM_ANALYTIC_FIELD_SUCCESS, function(accountId, projectName, analyticField) { 10369 return { 10370 accountId, 10371 projectName, 10372 analyticField 10373 }; 10374}); 10375var DELETE_CUSTOM_ANALYTIC_FIELD_SUCCESS = "DELETE_CUSTOM_ANALYTIC_FIELD_SUCCESS"; 10376var deleteCustomAnalyticFieldSuccess = (0, import_lib$3.createAction)(DELETE_CUSTOM_ANALYTIC_FIELD_SUCCESS, function(accountId, projectName, analyticFieldId) { 10377 return { 10378 accountId, 10379 projectName, 10380 analyticFieldId 10381 }; 10382}); 10383var CHANGE_ACTIVE_PRESET = "CHANGE_ACTIVE_PRESET"; 10384var changeActivePreset = (0, import_lib$3.createAction)(CHANGE_ACTIVE_PRESET, function(presetId) { 10385 return { presetId }; 10386}); 10387var UPDATE_PROJECT_MASTER_SUCCESS = "UPDATE_PROJECT_MASTER_SUCCESS"; 10388var updateProjectMasterDataSuccess = (0, import_lib$3.createAction)(UPDATE_PROJECT_MASTER_SUCCESS, (projectName, masterData) => ({ 10389 projectName, 10390 masterData 10391})); 10392var ADDING_SURVEY_SUCCESS = "ADDING_SURVEY_SUCCESS"; 10393(0, import_lib$3.createAction)(ADDING_SURVEY_SUCCESS, function(accountId, projectName, surveyId, surveyData) { 10394 return { 10395 accountId, 10396 projectName, 10397 surveyId, 10398 surveyData 10399 }; 10400}); 10401var UPDATING_SURVEY_SUCCESS = "UPDATING_SURVEY_SUCCESS"; 10402(0, import_lib$3.createAction)(UPDATING_SURVEY_SUCCESS, function(accountId, projectName, surveyId, surveyData) { 10403 return { 10404 accountId, 10405 projectName, 10406 surveyId, 10407 surveyData 10408 }; 10409}); 10410var DELETING_SURVEY_SUCCESS = "DELETING_SURVEY_SUCCESS"; 10411(0, import_lib$3.createAction)(DELETING_SURVEY_SUCCESS, function(accountId, projectName, surveyId) { 10412 return { 10413 accountId, 10414 projectName, 10415 surveyId 10416 }; 10417}); 10418var LOADING_SURVEYS_SUCCESS = "LOADING_SURVEYS_SUCCESS"; 10419(0, import_lib$3.createAction)(LOADING_SURVEYS_SUCCESS, function(accountId, projectName, surveys) { 10420 return { 10421 accountId, 10422 projectName, 10423 surveys 10424 }; 10425}); 10426var UPDATE_NARRATION_POSTGRES_ID_SUCCESS = "UPDATE_NARRATION_POSTGRES_ID_SUCCESS"; 10427var updateNarrationPostgresIdSuccess = (0, import_lib$3.createAction)(UPDATE_NARRATION_POSTGRES_ID_SUCCESS, (accountId, projectName, narrationId, postgresId, isPostgresOnly) => { 10428 return { 10429 accountId, 10430 projectName, 10431 narrationId, 10432 postgresId, 10433 isPostgresOnly 10434 }; 10435}, void 0); 10436var UPDATE_WIREFRAME_GRAPHQL_PARENT_PROGRAM_VERSION_ID = "UPDATE_WIREFRAME_GRAPHQL_PARENT_PROGRAM_VERSION_ID"; 10437var updateWireframeGraphQLParentProgramVersionId = (0, import_lib$3.createAction)(UPDATE_WIREFRAME_GRAPHQL_PARENT_PROGRAM_VERSION_ID, function(projectName, graphQLParentProgramVersionId) { 10438 return { 10439 projectName, 10440 graphQLParentProgramVersionId 10441 }; 10442}); 10443/**
10444* validates a scene part. 10445* We are interested only in prioritized lists with no slots slots that are groups with no placeholders. 10446* @param scenePart 10447*/ 10448var invalidScenePart = function(scenePart) { 10449 return (scenePart.prioritizedLists || []).some((pl) => { 10450 return !pl.slots || pl.slots.length === 0 || pl.slots.some((slot) => { 10451 return slot.placeholders && slot.placeholders.length === 0; 10452 }); 10453 }); 10454}; 10455var addNarrationWithBody = function(dispatch, getState, services, accountId, projectName, sceneId, scenePartIndex, structure, variationDataMap, postgresNarrationId) { 10456 let narrationId; 10457 let dbStructure = { 10458 dimensionData: NarrationsModelUtils.dbExtractDimensionDataFromStructure(structure), 10459 mergeData: NarrationsModelUtils.dbExtractMergeDataFromStructure(structure), 10460 representativeKey: NarrationsModelUtils.dbExtractRepresentativeKeyFromStructure(structure), 10461 creativeOverride: NarrationsModelUtils.dbExtractCreativeOverrideFromStructure(structure) 10462 }; 10463 return services.projectNarrationsServices.addNarration(accountId, projectName, sceneId, dbStructure, postgresNarrationId).then((narrId) => { 10464 let dbVariationDataUpdates = NarrationsModelUtils.dbExtractVariationDataUpdates(variationDataMap.toJSON()); 10465 narrationId = narrId; 10466 return services.projectNarrationsServices.storeVariationData(accountId, projectName, sceneId, narrationId, dbVariationDataUpdates); 10467 }).then(() => { 10468 dispatch(addNarrationSuccess(accountId, projectName, sceneId, narrationId, structure, variationDataMap, postgresNarrationId)); 10469 return { 10470 narrationId, 10471 sceneId, 10472 scenePartIndex 10473 }; 10474 }); 10475}; 10476var getNarrationPostgresId = (projectName, state, narrationId) => { 10477 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 10478 return StateReaderUtils.getNarrationPostgresId(wireframes, narrationId); 10479}; 10480var initMasterObj = () => ({ 10481 id: LogicContainers.Master, 10482 name: "Master", 10483 sceneParts: [] 10484}); 10485var initMasterDataObj = () => ({ 10486 placeholders: [], 10487 parameters: [] 10488}); 10489var loadProjectWireframesVersionPromise = (services, dispatch, accountId, projectName, wireframesVersion, stage, version) => { 10490 return services.projectAssetsServices.getAssetContent(accountId, projectName, wireFramesAssetType, "draft", wireframesVersion).then((wireframeUIAsset) => { 10491 if (!wireframeUIAsset.scenes[LogicContainers.Master]) { 10492 wireframeUIAsset.scenes[LogicContainers.Master] = initMasterObj(); 10493 wireframeUIAsset.scenes[LogicContainers.Master].sceneParts[0] = initMasterDataObj(); 10494 } 10495 if (!wireframeUIAsset.logic[LogicContainers.Master]) wireframeUIAsset.logic[LogicContainers.Master] = {}; 10496 dispatch(loadingProjectWireframesFromUIAsset(accountId, projectName, wireframeUIAsset, stage, version)); 10497 }); 10498}; 10499var loadProjectWireframesVersionTheOldWay = memoizeThunkAction((accountId, projectName, stage, version, withNarrationRecordings, showLoadingSpinner) => { 10500 return (dispatch, getState, services) => { 10501 if (showLoadingSpinner) dispatch(setLoading(true, accountId, projectName)); 10502 return loadProjectWireframesVersionPromise(services, dispatch, accountId, projectName, StateReaderUtils.getWireframesUIVersionFromSnapshot({ 10503 state: getState(), 10504 projectName, 10505 version, 10506 stage 10507 }), stage, version).then(() => { 10508 const wireframes = StateReaderUtils.getWireFrame(getState(), projectName, stage, version); 10509 if (wireframes.narrationsVersion > 0 && withNarrationRecordings) { 10510 if (!(wireframes.programDynamoMigrationStatus?.mostEntities === GqlClientDynamoMigrationStatus.DONE)) return services.projectAssetsServices.getAllAssets(accountId, projectName, AssetTypes.recording, void 0, void 0, true); 10511 } 10512 }).then((recordingAssets) => { 10513 if (recordingAssets) dispatch(loadingProjectAssetsSuccess(projectName, recordingAssets, !!version)); 10514 }).catch((err) => { 10515 dispatch(reportError(err)); 10516 }).finally(() => { 10517 if (showLoadingSpinner) dispatch(setLoading(false, accountId, projectName, stage, version)); 10518 }); 10519 }; 10520}); 10521var loadProjectWireframesTheNewWay = memoizeThunkAction((accountId, projectName, versionId, stage, version, showLoadingSpinner) => { 10522 return async (dispatch, getState, services) => { 10523 if (showLoadingSpinner) dispatch(setLoading(true, accountId, projectName)); 10524 const { programId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10525 return services.graphQlClient.query({ 10526 fetchPolicy: "no-cache", 10527 query: GetBuilderProgramDocument, 10528 variables: { 10529 id: programId, 10530 versionId 10531 } 10532 }).then((gqlResult) => { 10533 const program = gqlResult && gqlResult.data && gqlResult.data.program;
10534 const wireframes = buildWireframesFromGql(program); 10535 const dataElements = buildDataElementsFromGql(program); 10536 const derivedLogic = buildDerivedLogicFromGql(program); 10537 const analyticsLogic = buildAnalyticsLogicFromGql(program); 10538 const masterLogic = buildMasterLogicFromGql(program); 10539 const scenesLogicItems = buildScenesLogicFromGql(program); 10540 const storyLogic = buildStoriesLogicFromGql(program); 10541 const programLogic = buildProgramLogicFromGql(program); 10542 const narrations = buildWireframesNarrationsFromGql(program, false, [], {}); 10543 dispatch(loadingProgramWireframeSuccess(accountId, projectName, wireframes, dataElements, { 10544 [LogicContainers.Derived]: derivedLogic, 10545 [LogicContainers.Analytics]: analyticsLogic, 10546 [LogicContainers.Master]: masterLogic, 10547 ...scenesLogicItems 10548 }, programLogic, storyLogic, narrations, stage, version, !!Object.keys(derivedLogic).length)); 10549 }).then(() => { 10550 dispatch(setForceLoad(false)); 10551 }).catch((err) => { 10552 dispatch(reportError(err)); 10553 }).finally(() => { 10554 if (showLoadingSpinner) dispatch(setLoading(false, accountId, projectName, stage, version)); 10555 }); 10556 }; 10557}); 10558var loadProjectWireframes = (accountId, projectName, stage, version, triggeredWithForceLoad, showLoadingSpinner = true) => { 10559 return async (dispatch, getState) => { 10560 let forceLoad = triggeredWithForceLoad || StateReaderUtils.getForceLoad(getState()); 10561 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName, stage, version); 10562 if (!forceLoad && wireframes && wireframes.snapshotNumber === version) return Promise.resolve(); 10563 if (!stage && !version) { 10564 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10565 return dispatch(loadProjectWireframesTheNewWay(accountId, projectName, programVersionId, void 0, void 0, showLoadingSpinner)); 10566 } 10567 const project = StateReaderUtils.getProject(getState(), projectName); 10568 const snapshotId = version ? StateReaderUtils.getSnapshotIdByNumber(projectName, version) : StateReaderUtils.getLatestSnapshotIdForStage(project, stage); 10569 const versionDetails = StateReaderUtils.getSnapshot(getState(), { snapshotId }); 10570 if (versionDetails) if (versionDetails.snapshotSource === SnapshotSource.POSTGRES) return dispatch(loadProjectWireframesTheNewWay(accountId, projectName, versionDetails.graphQLId, stage, version, showLoadingSpinner)); 10571 else { 10572 if (!StateReaderUtils.getWireframesUIVersionFromSnapshot({ 10573 state: getState(), 10574 projectName, 10575 version, 10576 stage 10577 })) return Promise.resolve(); 10578 return dispatch(loadProjectWireframesVersionTheOldWay(accountId, projectName, stage, version, true, showLoadingSpinner)); 10579 } 10580 }; 10581}; 10582var getDuplicatedSceneName = function(wireframes, sceneName) { 10583 return getUniqueNameWithRunningSuffix(sceneName + "Copy", Object.keys(wireframes.scenes).map((key) => wireframes.scenes[key].name)); 10584}; 10585var duplicateScene = function(accountId, projectName, sceneData) { 10586 return (dispatch, getState, services) => { 10587 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 10588 let newScene; 10589 const narrationsVersion = StateReaderUtils.getNarrationsVersion(wireframes); 10590 services.graphQlClient.mutate({ 10591 mutation: CopySceneDocument, 10592 variables: { input: { 10593 sourceId: sceneData.graphQLId, 10594 targetName: getDuplicatedSceneName(wireframes, sceneData.name) 10595 } } 10596 }).then((gqlOutput) => { 10597 const gqlScene = gqlOutput.data.copyScene.targetScene; 10598 newScene = buildWireframesSceneFromGql(narrationsVersion, gqlScene); 10599 if (narrationsVersion > 0) { 10600 let loadedNarrations = []; 10601 gqlScene.sceneParts.forEach((part) => { 10602 if (part.narrations.length > 0) part.narrations.forEach((narr) => { 10603 loadedNarrations.push(buildWireframesNarrationFromGql(narr)); 10604 }); 10605 }); 10606 if (loadedNarrations.length > 0) dispatch(loadNarrationsSuccess(accountId, projectName, loadedNarrations)); 10607 } 10608 dispatch(addingProjectWireframesSceneSuccess(accountId, projectName, newScene.id, newScene)); 10609 const newSceneLogicItems = buildSceneLogicFromGql(gqlScene);
10610 Object.keys(newSceneLogicItems).forEach((inputName) => { 10611 dispatch(updatingProjectWireFramesSceneInputLogicSuccess(accountId, projectName, newScene.id, inputName, newSceneLogicItems[inputName])); 10612 }); 10613 }).catch((err) => {}); 10614 }; 10615}; 10616var addProjectWireframesScene = function(accountId, projectName, sceneName, cb) { 10617 return (dispatch, getState, services) => { 10618 services.graphQlClient.mutate({ 10619 mutation: CreateSceneWithScenePartDocument, 10620 variables: { input: { 10621 name: sceneName, 10622 programVersionId: StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName).programVersionId 10623 } } 10624 }).then((gqlOutput) => { 10625 const gqlScene = gqlOutput.data.createSceneWithScenePart.scene; 10626 const gqlScenePart = gqlScene.sceneParts[0]; 10627 const sceneLocalId = getIdFromGqlId(gqlScene.id); 10628 const sceneData = { 10629 name: gqlScene.name, 10630 creationTime: gqlScene.created, 10631 id: sceneLocalId, 10632 sceneParts: [{ 10633 scenePart: getIdFromGqlId(gqlScenePart.id), 10634 placeholders: [], 10635 parameters: [], 10636 NarrationParts: [], 10637 graphQLId: gqlScenePart.id, 10638 graphQLUpdated: gqlScenePart.updated 10639 }], 10640 graphQLId: gqlScene.id, 10641 graphQLUpdated: gqlScene.updated 10642 }; 10643 dispatch(addingProjectWireframesSceneSuccess(accountId, projectName, sceneData.id, sceneData)); 10644 if (cb) cb(sceneLocalId); 10645 }).catch(() => {}); 10646 }; 10647}; 10648var editProjectWireframesScene = function(accountId, projectName, sceneId, scene) { 10649 return (dispatch, getState, services) => { 10650 let sceneData = Object.assign({}, scene, { sceneParts: scene.sceneParts.map((scenePartItem) => scenePartItem.scenePart) }); 10651 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) services.wireframes.editProjectWireframesScene(accountId, projectName, sceneId, sceneData).then(() => { 10652 dispatch(changingProjectWireframesSceneSuccess(accountId, projectName, sceneId, scene)); 10653 }).then(() => { 10654 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10655 services.graphQlClient.mutate({ 10656 mutation: UpdateBuildersSceneDocument, 10657 variables: { 10658 input: { 10659 id: `${programVersionId}|${sceneId}`, 10660 updated: IGNORE_UPDATED, 10661 name: scene.name, 10662 scenePartOrder: scene.sceneParts.map((scenePart) => `${programVersionId}|${sceneId}|${scenePart.postgresScenePartId || scenePart.scenePart}`) 10663 }, 10664 dryRun: false, 10665 [IGNORE_SERVER_ERRORS]: true 10666 } 10667 }).catch((err) => {}); 10668 }).catch((err) => dispatch(reportError(err))); 10669 else services.graphQlClient.mutate({ 10670 mutation: UpdateBuildersSceneDocument, 10671 variables: { 10672 input: { 10673 id: scene.graphQLId, 10674 updated: IGNORE_UPDATED, 10675 name: scene.name, 10676 scenePartOrder: scene.sceneParts.map((scenePart) => scenePart.graphQLId) 10677 }, 10678 dryRun: false 10679 } 10680 }).then((gqlOutput) => { 10681 if (gqlOutput.data.updateScene.__typename === "UpdateSceneOutputSuccess") { 10682 const gqlScene = gqlOutput.data.updateScene.scene; 10683 dispatch(changingProjectWireframesSceneSuccess(accountId, projectName, sceneId, { 10684 ...scene, 10685 graphQLId: gqlScene.id, 10686 graphQLUpdated: gqlScene.updated 10687 })); 10688 } 10689 }).catch((err) => {}); 10690 }; 10691}; 10692var setProjectWireframesScenePart = function(accountId, projectName, sceneId, scenePartId, scenePartData, scenePartIndex, isUpdateRelevantToNarrationPart, cb) { 10693 return (dispatch, getState, services) => { 10694 if (invalidScenePart(scenePartData)) reportErrorToSplunk("Trying to update invalid scene part", { 10695 metadata: { 10696 scenePartId, 10697 scenePartData, 10698 scenePartBeforeUpdate: StateReaderUtils.getProjectWireframesScenePart(StateReaderUtils.getWireFrame(getState(), projectName), sceneId, scenePartIndex) 10699 }, 10700 crashed: false 10701 }); 10702 const wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 10703 const narrationsVersion = StateReaderUtils.getNarrationsVersion(wireframes); 10704 const dispatchChangingProjectWireframesScenePartsSuccess = (scenePart) => { 10705 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, scenePart, scenePartIndex)); 10706 if (typeof cb === "function") cb(); 10707 }; 10708 if (!isUpdateRelevantToNarrationPart) return services.graphQlClient.mutate({ 10709 mutation: UpdateScenePartWithAllPlaceholdersDocument, 10710 variables: { 10711 input: { 10712 id: scenePartData.graphQLId, 10713 updated: IGNORE_UPDATED, 10714 scenePartData 10715 }, 10716 dryRun: false 10717 } 10718 }).then((gqlOutput) => { 10719 if (gqlOutput.data.updateScenePartWithAllPlaceholders.__typename === "UpdateScenePartWithAllPlaceholdersOutputSuccess") { 10720 const gqlScenePart = gqlOutput.data.updateScenePartWithAllPlaceholders.scenePart; 10721 dispatchChangingProjectWireframesScenePartsSuccess({ 10722 ...scenePartData, 10723 graphQLUpdated: gqlScenePart.updated 10724 }); 10725 } 10726 }).catch(() => {}); 10727 else if (narrationsVersion <= 0) return services.graphQlClient.mutate({ 10728 mutation: UpdateScenePartDocument, 10729 variables: { 10730 input: { 10731 id: scenePartData.graphQLId, 10732 updated: IGNORE_UPDATED,
10733 oldNarrationData: scenePartData.NarrationParts 10734 }, 10735 dryRun: false 10736 } 10737 }).then((gqlOutput) => { 10738 if (gqlOutput.data.updateScenePart.__typename === "UpdateScenePartOutputSuccess") { 10739 const gqlScenePart = gqlOutput.data.updateScenePart.scenePart; 10740 dispatchChangingProjectWireframesScenePartsSuccess({ 10741 ...scenePartData, 10742 graphQLUpdated: gqlScenePart.updated 10743 }); 10744 } 10745 }).catch(() => {}); 10746 }; 10747}; 10748var moveNarrationPartUpOrDown = function(accountId, projectName, sceneId, scenePartIndex, narrationPartIndex, direction) { 10749 return (dispatch, getState, services) => { 10750 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 10751 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 10752 let scene = StateReaderUtils.getProjectWireframesScene(wireframes, sceneId); 10753 let scenePart = scene.sceneParts[scenePartIndex]; 10754 let narrationPartData = scenePart.NarrationParts[narrationPartIndex]; 10755 let isUp = direction === "UP"; 10756 let narrationIndexIsOnTheEdge = isUp ? narrationPartIndex === 0 : narrationPartIndex === scenePart.NarrationParts.length - 1; 10757 let scenePartIndexIsOnTheEdge = isUp ? scenePartIndex === 0 : scenePartIndex === scene.sceneParts.length - 1; 10758 let linkedNarrationIndex = isUp ? narrationPartIndex - 1 : narrationPartIndex + 1; 10759 let linkedScenePartIndex = isUp ? scenePartIndex - 1 : scenePartIndex + 1; 10760 let addNarrationToArr = (scenePart, narrationPart) => { 10761 return isUp ? [...scenePart.NarrationParts, narrationPart] : [narrationPart, ...scenePart.NarrationParts]; 10762 }; 10763 let removeNarrationFromArr = (scenePart) => { 10764 return isUp ? scenePart.NarrationParts.slice(1) : scenePart.NarrationParts.slice(0, scenePart.NarrationParts.length - 1); 10765 }; 10766 if (!narrationIndexIsOnTheEdge) { 10767 let newNarArr = [...scenePart.NarrationParts]; 10768 const linkedNarrationData = newNarArr[linkedNarrationIndex]; 10769 newNarArr[linkedNarrationIndex] = narrationPartData; 10770 newNarArr[narrationPartIndex] = linkedNarrationData; 10771 let newScenePart = { 10772 ...scenePart, 10773 NarrationParts: newNarArr 10774 }; 10775 if (!isPostgresOnly) dispatch(setProjectWireframesScenePart(accountId, projectName, sceneId, scenePart.scenePart, newScenePart, scenePartIndex, true, () => { 10776 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10777 const postgresNarrationId = StateReaderUtils.getNarrationPostgresId(wireframes, narrationPartData.id); 10778 const postgresScenePartId = scenePart.postgresScenePartId || scenePart.scenePart; 10779 services.graphQlClient.mutate({ 10780 mutation: UpdateNarrationOrderDocument, 10781 variables: { 10782 input: { 10783 id: `${programVersionId}|${sceneId}|${postgresScenePartId}|${postgresNarrationId}`, 10784 updated: IGNORE_UPDATED, 10785 sourceScenePartNarrationOrder: newNarArr.map((n) => getNarrationPostgresId(projectName, getState(), n.id)) 10786 }, 10787 dryRun: false, 10788 [IGNORE_SERVER_ERRORS]: true 10789 } 10790 }).catch((err) => {}); 10791 })); 10792 else services.graphQlClient.mutate({ 10793 mutation: UpdateNarrationOrderDocument, 10794 variables: { 10795 input: { 10796 id: narrationPartData.id, 10797 updated: IGNORE_UPDATED, 10798 sourceScenePartNarrationOrder: newNarArr.map((n) => getIdFromGqlId(n.id)) 10799 }, 10800 dryRun: false 10801 } 10802 }).then((gqlOutput) => { 10803 if (gqlOutput.data.updateNarrationOrder.__typename === "UpdateNarrationOrderSuccess") { 10804 let graphQLUpdated = gqlOutput.data.updateNarrationOrder.originalScenePart.updated; 10805 newScenePart = { 10806 ...newScenePart, 10807 graphQLUpdated 10808 }; 10809 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, newScenePart, scenePartIndex)); 10810 } 10811 }).catch((err) => {}); 10812 } else if (!scenePartIndexIsOnTheEdge) if (!isPostgresOnly) { 10813 let linkedScenePart = scene.sceneParts[linkedScenePartIndex]; 10814 let newLinkedNarArr = addNarrationToArr(linkedScenePart, narrationPartData); 10815 let newLinkedScenePart = { 10816 ...linkedScenePart, 10817 NarrationParts: newLinkedNarArr 10818 }; 10819 let newOriginalArr; 10820 let updatedLinkedScenePart; 10821 services.wireframes.setProjectWireframesScenePart(accountId, projectName, sceneId, linkedScenePart.scenePart, newLinkedScenePart).then((updatedScenePart) => { 10822 updatedLinkedScenePart = updatedScenePart; 10823 newOriginalArr = removeNarrationFromArr(scenePart); 10824 let newScenePart = { 10825 ...scenePart, 10826 NarrationParts: newOriginalArr 10827 }; 10828 return services.wireframes.setProjectWireframesScenePart(accountId, projectName, sceneId, scenePart.scenePart, newScenePart); 10829 }).then((updatedScenePart) => { 10830 dispatch(ChangingBulkScenePartsSuccess(accountId, projectName, { 10831 [sceneId + "/" + scenePart.scenePart]: updatedScenePart, 10832 [sceneId + "/" + linkedScenePart.scenePart]: updatedLinkedScenePart 10833 })); 10834 }).then(() => { 10835 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10836 const postgresNarrationId = StateReaderUtils.getNarrationPostgresId(wireframes, narrationPartData.id); 10837 const postgresScenePartId = scenePart.postgresScenePartId || scenePart.scenePart; 10838 services.projectNarrationsServices.updateNarrationPostgresId(accountId, projectName, sceneId, narrationPartData.id, v4()).then((narr) => { 10839 dispatch(updateNarrationPostgresIdSuccess(accountId, projectName, narrationPartData.id, narr.postgresNarrationId, false)); 10840 services.graphQlClient.mutate({ 10841 mutation: UpdateNarrationOrderDocument, 10842 variables: { 10843 input: { 10844 id: `${programVersionId}|${sceneId}|${postgresScenePartId}|${postgresNarrationId}`, 10845 updated: IGNORE_UPDATED,
10846 sourceScenePartNarrationOrder: newOriginalArr.map((n) => getNarrationPostgresId(projectName, getState(), n.id)), 10847 targetScenePartNarrationOrder: newLinkedNarArr.map((n) => getNarrationPostgresId(projectName, getState(), n.id)), 10848 targetScenePartId: updatedLinkedScenePart.postgresScenePartId || updatedLinkedScenePart.scenePart, 10849 newNarrationId: narr.postgresNarrationId 10850 }, 10851 dryRun: false, 10852 [IGNORE_SERVER_ERRORS]: true 10853 } 10854 }).catch((err) => {}); 10855 }); 10856 }).catch((err) => { 10857 dispatch(reportError(err)); 10858 }); 10859 } else { 10860 const newNarrationId = v4(); 10861 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10862 let linkedScenePart = scene.sceneParts[linkedScenePartIndex]; 10863 let newNarrationPartData = { 10864 ...narrationPartData, 10865 id: `${programVersionId}|${sceneId}|${linkedScenePart.scenePart}|${newNarrationId}` 10866 }; 10867 let newLinkedNarArr = addNarrationToArr(linkedScenePart, newNarrationPartData); 10868 let newOriginalArr = removeNarrationFromArr(scenePart); 10869 services.graphQlClient.mutate({ 10870 mutation: UpdateNarrationOrderDocument, 10871 variables: { 10872 input: { 10873 id: narrationPartData.id, 10874 updated: IGNORE_UPDATED, 10875 sourceScenePartNarrationOrder: newOriginalArr.map((n) => getIdFromGqlId(n.id)), 10876 targetScenePartNarrationOrder: newLinkedNarArr.map((n) => getIdFromGqlId(n.id)), 10877 targetScenePartId: linkedScenePart.scenePart, 10878 newNarrationId 10879 }, 10880 dryRun: false 10881 } 10882 }).then((gqlOutput) => { 10883 if (gqlOutput.data.updateNarrationOrder.__typename === "UpdateNarrationOrderSuccess") { 10884 let originalUpdated = gqlOutput.data.updateNarrationOrder.originalScenePart.updated; 10885 let linkedUpdated = gqlOutput.data.updateNarrationOrder.targetScenePart.updated; 10886 let newScenePart = { 10887 ...scenePart, 10888 NarrationParts: newOriginalArr, 10889 graphQLUpdated: originalUpdated 10890 }; 10891 let newLinkedScenePart = { 10892 ...linkedScenePart, 10893 NarrationParts: newLinkedNarArr, 10894 graphQLUpdated: linkedUpdated 10895 }; 10896 let bulkUpdates = { 10897 [sceneId + "/" + newScenePart.scenePart]: newScenePart, 10898 [sceneId + "/" + newLinkedScenePart.scenePart]: newLinkedScenePart 10899 }; 10900 dispatch(updateNarrationPostgresIdSuccess(accountId, projectName, narrationPartData.id, newNarrationPartData.id, true)); 10901 dispatch(ChangingBulkScenePartsSuccess(accountId, projectName, bulkUpdates)); 10902 } 10903 }).catch(() => {}); 10904 } 10905 }; 10906}; 10907var addProjectWireframesScenePart = function(accountId, projectName, sceneId, scenePartData, duplication, cb) { 10908 return (dispatch, getState, services) => { 10909 let dynamoScenePart; 10910 const dispatchAddScenePart = (scenePart) => { 10911 dispatch(AddingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, scenePart)); 10912 if (typeof cb === "function") cb(scenePart); 10913 }; 10914 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10915 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) services.wireframes.addProjectWireframesScenePart(accountId, projectName, sceneId, scenePartData).then((scenePart) => { 10916 dynamoScenePart = scenePart; 10917 dispatchAddScenePart(scenePart); 10918 }).then(() => { 10919 if (!duplication) services.graphQlClient.mutate({ 10920 mutation: CreateScenePartDocument, 10921 variables: { 10922 input: { 10923 sceneId: `${programVersionId}|${sceneId}`, 10924 legacyId: dynamoScenePart.scenePart 10925 }, 10926 [IGNORE_SERVER_ERRORS]: true 10927 } 10928 }).catch((err) => {}); 10929 }).catch((err) => { 10930 dispatch(reportError(err)); 10931 }); 10932 else if (duplication) dispatchAddScenePart(scenePartData); 10933 else services.graphQlClient.mutate({ 10934 mutation: CreateScenePartDocument, 10935 variables: { input: { sceneId: `${programVersionId}|${sceneId}` } } 10936 }).then((gqlOutput) => { 10937 const gqlScenePart = gqlOutput.data.createScenePart.scenePart; 10938 const scenePartLocalId = getIdFromGqlId(gqlScenePart.id); 10939 dispatchAddScenePart({ 10940 graphQLId: gqlScenePart.id, 10941 graphQLUpdated: gqlScenePart.updated, 10942 NarrationParts: [], 10943 placeholders: [], 10944 parameters: [], 10945 scenePart: scenePartLocalId 10946 }); 10947 }).catch((err) => {}); 10948 }; 10949}; 10950var duplicateProjectWireframesScenePart = function(accountId, projectName, sceneId, scenePartIndex, scenePartId) { 10951 return (dispatch, getState, services) => { 10952 const wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 10953 const narrationsVersion = StateReaderUtils.getNarrationsVersion(wireframes); 10954 const scenePartData = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 10955 let newScenePartData = deepCloneObj(scenePartData); 10956 let newNarrationIds = [];
10957 delete newScenePartData.storyboardFrameThumbnailLocation; 10958 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) { 10959 let promiseChain = Promise.resolve(); 10960 if (narrationsVersion > 0) { 10961 promiseChain = scenePartData.NarrationParts.reduce((promiseChain, narrationPart) => { 10962 let narrations = wireframes.narrations; 10963 let structure = narrations.byId[narrationPart.id].structure; 10964 let variationDataMap = narrations.byId[narrationPart.id].variationDataMap; 10965 let postgresNarrationId = StateReaderUtils.getNarrationPostgresId(wireframes, narrationPart.id) || narrationPart.id; 10966 return promiseChain.then((answer) => { 10967 if (answer) newNarrationIds.push(answer.narrationId); 10968 return addNarrationWithBody(dispatch, getState, services, accountId, projectName, sceneId, void 0, structure, variationDataMap, postgresNarrationId); 10969 }); 10970 }, Promise.resolve(null)); 10971 promiseChain.then((lastAnswer) => { 10972 if (lastAnswer) { 10973 newNarrationIds.push(lastAnswer.narrationId); 10974 newScenePartData.NarrationParts = newNarrationIds.map((narrationId) => ({ id: narrationId })); 10975 } 10976 }); 10977 } 10978 promiseChain.then(() => { 10979 dispatch(addProjectWireframesScenePart(accountId, projectName, sceneId, newScenePartData, true, (newScenePart) => { 10980 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 10981 const postgresScenePartId = scenePartData.postgresScenePartId || scenePartId; 10982 services.graphQlClient.mutate({ 10983 mutation: CopyScenePartDocument, 10984 variables: { 10985 input: { sourceId: `${programVersionId}|${sceneId}|${postgresScenePartId}` }, 10986 legacyId: newScenePart.scenePart, 10987 [IGNORE_SERVER_ERRORS]: true 10988 } 10989 }).catch((err) => {}); 10990 })); 10991 }).catch((err) => dispatch(reportError(err))); 10992 } else services.graphQlClient.mutate({ 10993 mutation: CopyScenePartDocument, 10994 variables: { input: { sourceId: scenePartData.graphQLId } } 10995 }).then((gqlOutput) => { 10996 const gqlScenePart = gqlOutput.data.copyScenePart.targetScenePart; 10997 const scenePartData = { 10998 ...newScenePartData, 10999 scenePart: getIdFromGqlId(gqlScenePart.id), 11000 graphQLId: gqlScenePart.id, 11001 graphQLUpdated: gqlScenePart.updated 11002 }; 11003 if (narrationsVersion >
11003 0 && gqlScenePart.narrations.length > 0) { 11004 let loadedNarrations = []; 11005 scenePartData.NarrationParts = buildWireframesNarrationsPartFromGql(gqlScenePart.narrations, gqlScenePart.narrationPartOrder); 11006 gqlScenePart.narrations.forEach((narr) => { 11007 loadedNarrations.push(buildWireframesNarrationFromGql(narr)); 11008 }); 11009 if (loadedNarrations.length > 0) dispatch(loadNarrationsSuccess(accountId, projectName, loadedNarrations)); 11010 } 11011 dispatch(addProjectWireframesScenePart(accountId, projectName, sceneId, scenePartData, true)); 11012 }).catch((err) => {}); 11013 }; 11014}; 11015var deleteProjectWireframesScenePart = function(accountId, projectName, sceneId, scenePartId) { 11016 return (dispatch, getState, services) => { 11017 const wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 11018 const narrationsVersion = StateReaderUtils.getNarrationsVersion(wireframes); 11019 let scenePart = StateReaderUtils.getProjectWireframesScenePartById(wireframes, sceneId, scenePartId); 11020 let narrationIds = []; 11021 if (narrationsVersion > 0) scenePart[placeholderType.narration].forEach((narration) => narrationIds.push(narration.id)); 11022 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) services.wireframes.deleteProjectWireframesScenePart(accountId, projectName, sceneId, scenePartId).then(() => { 11023 dispatch(deletingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, scenePartId)); 11024 }).then(() => { 11025 let deleteNarrationPromises = narrationIds.map((id) => services.projectNarrationsServices.deleteNarration(accountId, projectName, sceneId, id)); 11026 return Promise.all(deleteNarrationPromises); 11027 }).then(() => { 11028 narrationIds.forEach((id) => { 11029 dispatch(deleteNarrationSuccess(accountId, projectName, sceneId, id)); 11030 }); 11031 }).then(() => { 11032 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11033 const postgresScenePartId = scenePart.postgresScenePartId || scenePartId; 11034 services.graphQlClient.mutate({ 11035 mutation: DeleteScenePartDocument, 11036 variables: { 11037 input: { id: `${programVersionId}|${sceneId}|${postgresScenePartId}` }, 11038 [IGNORE_SERVER_ERRORS]: true 11039 } 11040 }).catch((err) => {}); 11041 }).catch((err) => dispatch(reportError(err))); 11042 else services.graphQlClient.mutate({ 11043 mutation: DeleteScenePartDocument, 11044 variables: { input: { id: scenePart.graphQLId } } 11045 }).then(() => { 11046 dispatch(deletingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, scenePartId)); 11047 narrationIds.forEach((id) => { 11048 dispatch(deleteNarrationSuccess(accountId, projectName, sceneId, id)); 11049 }); 11050 }).catch((err) => {}); 11051 }; 11052}; 11053var deleteProjectWireframesScene = function(accountId, projectName, sceneId) { 11054 return (dispatch, getState, services) => { 11055 const wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 11056 const narrationsVersion = StateReaderUtils.getNarrationsVersion(wireframes); 11057 let scene = StateReaderUtils.getProjectWireframesScene(wireframes, sceneId); 11058 let narrationIds = []; 11059 if (narrationsVersion > 0) scene.sceneParts.forEach((part) => { 11060 part[placeholderType.narration].forEach((narration) => { 11061 narrationIds.push(narration.id); 11062 }); 11063 }); 11064 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) services.wireframes.deleteProjectWireframesScene(accountId, projectName, sceneId).then(() => { 11065 dispatch(deletingProjectWireframesSceneSuccess(accountId, projectName, sceneId)); 11066 }).then(() => { 11067 let deleteNarrationPromises = narrationIds.map((id) => services.projectNarrationsServices.deleteNarration(accountId, projectName, sceneId, id)); 11068 return Promise.all(deleteNarrationPromises); 11069 }).then(() => { 11070 narrationIds.forEach((id) => { 11071 dispatch(deleteNarrationSuccess(accountId, projectName, sceneId, id)); 11072 }); 11073 }).then(() => { 11074 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11075 services.graphQlClient.mutate({ 11076 mutation: DeleteSceneDocument, 11077 variables: { 11078 input: { id: `${programVersionId}|${sceneId}` }, 11079 [IGNORE_SERVER_ERRORS]: true 11080 } 11081 }).catch((err) => {}); 11082 }).catch((err) => dispatch(reportError(err))); 11083 else services.graphQlClient.mutate({ 11084 mutation: DeleteSceneDocument, 11085 variables: { input: { id: scene.graphQLId } } 11086 }).then(() => { 11087 dispatch(deletingProjectWireframesSceneSuccess(accountId, projectName, sceneId)); 11088 narrationIds.forEach((id) => { 11089 dispatch(deleteNarrationSuccess(accountId, projectName, sceneId, id)); 11090 }); 11091 }).catch((err) => {}); 11092 }; 11093}; 11094var setProjectWireframesSceneInputLogic = function(accountId, projectName, logicContainer, logicOwner, logicData) { 11095 return (dispatch, getState, services) => { 11096 dispatch(loadingProjectWireFramesSceneInputLogic(accountId, projectName, logicContainer, logicOwner)); 11097 const sceneGqlId = StateReaderUtils.getProjectWireframesScene(StateReaderUtils.getWireFrame(getState(), projectName), logicContainer)?.graphQLId; 11098 let mutation; 11099 let input = { 11100 id: sceneGqlId, 11101 updated: IGNORE_UPDATED 11102 }; 11103 if (logicOwner.endsWith("_animation")) { 11104 mutation = UpdateBuildersSceneDocument; 11105 input = { 11106 ...input, 11107 animationLogic: logicData 11108 }; 11109 } else if (logicOwner.endsWith("_validation")) { 11110 mutation = UpdateBuildersSceneDocument; 11111 input = { 11112 ...input, 11113 validationLogic: logicData 11114 }; 11115 } else if (logicOwner.endsWith("_nextScene")) {} else if (logicOwner === "descriptive-transcript") { 11116 mutation = UpdateBuildersSceneDocument; 11117 input = { 11118 ...input, 11119 descriptiveTranscriptLogic: logicData 11120 }; 11121 } else if (logicContainer === LogicContainers.Derived) {} else if (logicContainer === LogicContainers.Analytics) {} else if (logicContainer === LogicContainers.Master) { 11122 mutation = UpdateMasterAnimationGuidelineDocument; 11123 const masterAnimationGuideline = StateReaderUtils.getProjectMasterAnimationGuidelineByName(getState(), projectName, logicOwner); 11124 input = { 11125 ...input, 11126 id: masterAnimationGuideline.graphQLId, 11127 logic: logicData 11128 }; 11129 }
11129 else if (isUuid(logicOwner)) { 11130 input = { 11131 ...input, 11132 id: `${sceneGqlId}|${logicOwner}`, 11133 logic: logicData 11134 }; 11135 if (logicData.outputType === LogicType.Prioritized) mutation = UpdatePrioritizedListLogicDocument; 11136 else mutation = UpdatePlaceholderGroupLogicDocument; 11137 } else { 11138 mutation = UpdateSceneEntityLogicDocument; 11139 input = { 11140 ...input, 11141 id: `${sceneGqlId}|${MOCK_SCENE_ENTITY_LOGIC_ID}`, 11142 name: logicOwner, 11143 logic: logicData 11144 }; 11145 } 11146 if (mutation) services.graphQlClient.mutate({ 11147 mutation, 11148 variables: { 11149 input, 11150 dryRun: false 11151 } 11152 }).then(() => { 11153 dispatch(updatingProjectWireFramesSceneInputLogicSuccess(accountId, projectName, logicContainer, logicOwner, logicData)); 11154 }).catch((err) => {}); 11155 }; 11156}; 11157var deleteProjectWireframesSceneInputLogic = function(accountId, projectName, sceneId, inputName) { 11158 return (dispatch, getState, services) => { 11159 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 11160 const logicData = StateReaderUtils.getProjectWireframesSceneInputLogic(getState(), projectName, sceneId, inputName, null, null); 11161 if (!isPostgresOnly) services.wireframes.deleteProjectWireFramesInputLogic(accountId, projectName, sceneId, inputName).then(() => { 11162 dispatch(deletingProjectWireFramesInputLogicSuccess(accountId, projectName, sceneId, inputName)); 11163 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11164 let mutation; 11165 let input; 11166 if (inputName.endsWith("_animation") || inputName.endsWith("_validation") || inputName.endsWith("_nextScene") || inputName === "descriptive-transcript" || sceneId === LogicContainers.Derived || sceneId === LogicContainers.Master || sceneId === LogicContainers.Analytics) {} else if (isUuid(inputName)) { 11167 input = { id: `${programVersionId}|${sceneId}|${inputName}` }; 11168 if (logicData.outputType === LogicType.Prioritized) mutation = DeletePrioritizedListLogicDocument; 11169 else mutation = DeletePlaceholderGroupLogicDocument; 11170 } else { 11171 mutation = DeleteSceneEntityLogicDocument; 11172 input = { 11173 id: `${programVersionId}|${sceneId}|${MOCK_SCENE_ENTITY_LOGIC_ID}`, 11174 name: inputName 11175 }; 11176 } 11177 if (mutation) services.graphQlClient.mutate({ 11178 mutation, 11179 variables: { 11180 input, 11181 [IGNORE_SERVER_ERRORS]: true 11182 } 11183 }).catch((err) => {}); 11184 }).catch((err) => { 11185 dispatch(reportError(err)); 11186 }); 11187 else { 11188 let mutation; 11189 let input; 11190 const scene = StateReaderUtils.getProjectWireframesScene(StateReaderUtils.getWireFrame(getState(), projectName), sceneId); 11191 if (!(inputName.endsWith("_animation") || inputName.endsWith("_validation") || inputName.endsWith("_nextScene") || inputName === "descriptive-transcript" || sceneId === LogicContainers.Derived || sceneId === LogicContainers.Master || sceneId === LogicContainers.Analytics)) if (isUuid(inputName)) { 11192 input = { id: `${scene.graphQLId}|${inputName}` }; 11193 if (logicData.outputType === LogicType.Prioritized) mutation = DeletePrioritizedListLogicDocument; 11194 else mutation = DeletePlaceholderGroupLogicDocument; 11195 } else { 11196 mutation = DeleteSceneEntityLogicDocument; 11197 input = { 11198 id: `${scene.graphQLId}`, 11199 name: inputName 11200 }; 11201 } 11202 if (mutation) services.graphQlClient.mutate({ 11203 mutation, 11204 variables: { input } 11205 }).then((gqlOutput) => { 11206 dispatch(deletingProjectWireFramesInputLogicSuccess(accountId, projectName, sceneId, inputName)); 11207 }).catch((err) => {}); 11208 } 11209 }; 11210}; 11211var deleteScenePartStoryboardFrame = function(accountId, projectName, sceneId, scenePartId, scenePartIndex) { 11212 return function(dispatch, state, services) { 11213 const wireframes = StateReaderUtils.getWireFrame(state(), projectName); 11214 const scenePartData = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 11215 const gqlScenePartId = scenePartData.graphQLId; 11216 return services.graphQlClient.mutate({ 11217 mutation: UpdateScenePartDocument, 11218 variables: { 11219 input: { 11220 id: gqlScenePartId, 11221 updated: IGNORE_UPDATED, 11222 thumbnailLocation: null 11223 }, 11224 dryRun: false 11225 } 11226 }).then((gqlOutput) => { 11227 if (gqlOutput.data.updateScenePart.__typename === "UpdateScenePartOutputSuccess") { 11228 const gqlScenePart = gqlOutput.data.updateScenePart.scenePart; 11229 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, { 11230 ...scenePartData, 11231 graphQLUpdated: gqlScenePart.updated 11232 }, scenePartIndex)); 11233 } 11234 }).catch((err) => {}); 11235 }; 11236}; 11237var addProjectWireframesScenePartStoryboardFrame = function(accountId, projectName, sceneId, scenePartId, scenePartData, scenePartIndex, storyboardFrameFile) { 11238 return async function(dispatch, getState, services) { 11239 let thumbnailLocation; 11240 const wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 11241 const postgresScenePartId = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex).postgresScenePartId || scenePartId; 11242 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11243 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 11244 if (!isPostgresOnly) services.wireframes.addProjectWireframesScenePartStoryboardFrame(accountId, projectName, sceneId, scenePartId, storyboardFrameFile, isPostgresOnly).then((scenePart) => {
11245 thumbnailLocation = scenePart.storyboardFrameThumbnailLocation; 11246 dispatch(addingProjectWireframesScenePartStoryboardFrameSuccess(accountId, projectName, sceneId, scenePartId, scenePart, scenePartIndex)); 11247 }).then(() => { 11248 services.graphQlClient.mutate({ 11249 mutation: UpdateScenePartDocument, 11250 variables: { 11251 input: { 11252 id: `${programVersionId}|${sceneId}|${postgresScenePartId}`, 11253 updated: IGNORE_UPDATED, 11254 thumbnailLocation 11255 }, 11256 dryRun: false, 11257 [IGNORE_SERVER_ERRORS]: true 11258 } 11259 }).catch(() => {}); 11260 }).catch((err) => dispatch(reportError(err))); 11261 else { 11262 const thumbnailLocation = await services.wireframes.addProjectWireframesScenePartStoryboardFrame(accountId, projectName, sceneId, scenePartId, storyboardFrameFile, isPostgresOnly); 11263 services.graphQlClient.mutate({ 11264 mutation: UpdateScenePartDocument, 11265 variables: { 11266 input: { 11267 id: scenePartData.graphQLId, 11268 updated: IGNORE_UPDATED, 11269 thumbnailLocation 11270 }, 11271 dryRun: false 11272 } 11273 }).then((gqlOutput) => { 11274 if (gqlOutput.data.updateScenePart.__typename === "UpdateScenePartOutputSuccess") { 11275 const gqlScenePart = gqlOutput.data.updateScenePart.scenePart; 11276 dispatch(addingProjectWireframesScenePartStoryboardFrameSuccess(accountId, projectName, sceneId, scenePartId, { 11277 ...scenePartData, 11278 storyboardFrameThumbnailLocation: thumbnailLocation, 11279 graphQLUpdated: gqlScenePart.updated 11280 }, scenePartIndex)); 11281 } 11282 }).catch((err) => {}); 11283 } 11284 }; 11285}; 11286var addProjectWireframesPreset = (accountId, projectName, presetData, cb, isCreative) => { 11287 return async (dispatch, getState, services) => { 11288 let pgsMutationSuccess; 11289 let postgresPreset; 11290 try { 11291 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11292 const programDataElements = StateReaderUtils.getProjectDataElements(getState(), projectName); 11293 const { systemElementValues, dataElementValues } = getPresetValuesFromData(presetData.data, programVersionId, programDataElements); 11294 let mutationVariables = { 11295 programVersionId, 11296 input: { 11297 name: presetData.name, 11298 isCreative: Boolean(isCreative), 11299 dataElementValues, 11300 systemElementValues 11301 } 11302 }; 11303 if (isCreative) mutationVariables.legacyId = POSTGRES_CREATIVES_PRESET_ID; 11304 const createPresetOutput = (await services.graphQlClient.mutate({ 11305 mutation: CreatePresetDocument, 11306 variables: mutationVariables 11307 }).catch(() => {})).data.createPreset; 11308 pgsMutationSuccess = createPresetOutput.result === GqlClientCreatePresetResult.SUCCESS; 11309 if (pgsMutationSuccess) postgresPreset = { 11310 ...presetData, 11311 id: isCreative ? CREATIVES_PRESET_ID : getIdFromGqlId(createPresetOutput.preset.id), 11312 graphQLId: createPresetOutput.preset.id, 11313 graphQLUpdated: createPresetOutput.preset.updated 11314 }; 11315 } catch (err) {} 11316 if (pgsMutationSuccess) { 11317 dispatch(AddingProjectWireframesPresetSuccess(accountId, projectName, postgresPreset)); 11318 if (typeof cb === "function") cb(); 11319 } 11320 }; 11321}; 11322var editProjectWireframesPreset = (accountId, projectName, presetId, presetData, cb) => { 11323 return async (dispatch, getState, services) => { 11324 try { 11325 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11326 const programDataElements = StateReaderUtils.getProjectDataElements(getState(), projectName); 11327 const { systemElementValues, dataElementValues } = getPresetValuesFromData(presetData.data, programVersionId, programDataElements); 11328 const mutationVariables = { input: { 11329 id: StateReaderUtils.getPresetById(getState(), projectName, presetId).graphQLId, 11330 updated: IGNORE_UPDATED, 11331 name: presetData.name, 11332 dataElementValues, 11333 systemElementValues 11334 } }; 11335 const gqlResult = await services.graphQlClient.mutate({ 11336 mutation: UpdatePresetDocument, 11337 variables: mutationVariables 11338 }); 11339 if (gqlResult.data.updatePreset.__typename === "UpdatePresetOutputSuccess") { 11340 dispatch(changingProjectWireframesPresetSuccess(accountId, projectName, presetId, clearObj({ 11341 ...presetData, 11342 graphQLId: gqlResult.data.updatePreset.preset.id, 11343 graphQLUpdated: gqlResult.data.updatePreset.preset.updated 11344 }))); 11345 if (typeof cb === "function") cb(); 11346 } 11347 } catch (err) {} 11348 }; 11349}; 11350var deleteProjectWireframesPreset = (accountId, projectName, presetId) => { 11351 return async (dispatch, getState, services) => { 11352 let programId = StateReaderUtils.getProgramId(getState(), projectName); 11353 if (!programId) { 11354 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 11355 programId = StateReaderUtils.getProgramId({ projectSummaries }, projectName); 11356 } 11357 const writeBuilderEntitiesPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), programId, BulkId.MostEntities); 11358 if (!writeBuilderEntitiesPostgresOnly) try { 11359 await services.wireframes.deleteProjectWireFramesPreset(accountId, projectName, presetId); 11360 } catch (err) { 11361 dispatch(reportError(err)); 11362 } 11363 let pgsMutationSuccess; 11364 try { 11365 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11366 const mutationVariables = { 11367 input: { id: writeBuilderEntitiesPostgresOnly ? StateReaderUtils.getPresetById(getState(), projectName, presetId).graphQLId : `${programVersionId}|${presetId}` }, 11368 [IGNORE_SERVER_ERRORS]: !writeBuilderEntitiesPostgresOnly 11369 }; 11370 pgsMutationSuccess = (await services.graphQlClient.mutate({ 11371 mutation: DeletePresetDocument, 11372 variables: mutationVariables 11373 }).catch(() => {})).data.deletePreset.result === GqlClientDeletePresetResult.SUCCESS; 11374 } catch (err) {} 11375 if (pgsMutationSuccess || !writeBuilderEntitiesPostgresOnly) dis
11375patch(deletingProjectWireFramesPresetSuccess(accountId, projectName, presetId)); 11376 }; 11377}; 11378var getProjectWireframesPresets = (accountId, projectName, version, stage) => { 11379 return async (dispatch, state, services) => { 11380 try { 11381 const { programId, programVersionId: programDraftVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(state(), projectName); 11382 let programVersionId; 11383 if (version || stage) { 11384 const project = StateReaderUtils.getProject(state(), projectName); 11385 const snapshotId = version ? StateReaderUtils.getSnapshotIdByNumber(projectName, version) : StateReaderUtils.getLatestSnapshotIdForStage(project, stage); 11386 const versionDetails = StateReaderUtils.getSnapshot(state(), { snapshotId }); 11387 if (versionDetails) programVersionId = versionDetails.snapshotSource === SnapshotSource.POSTGRES ? versionDetails.graphQLId : programDraftVersionId; 11388 } else programVersionId = programDraftVersionId; 11389 const readBuilderEntitiesFromPostgres = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.MostEntities); 11390 let dynamoPresets; 11391 let gqlPresets; 11392 if (!readBuilderEntitiesFromPostgres) dynamoPresets = await services.wireframes.getProjectWireframesPreset(accountId, projectName); 11393 if (readBuilderEntitiesFromPostgres && programVersionId) gqlPresets = convertGqlPresetsResult(await services.graphQlClient.query({ 11394 fetchPolicy: "no-cache", 11395 query: GetProgramPresetsDocument, 11396 variables: { 11397 programId, 11398 programVersionId 11399 } 11400 }).catch(() => null)); 11401 dispatch(loadingProjectWireframesPresetsSuccess(accountId, projectName, readBuilderEntitiesFromPostgres ? gqlPresets : dynamoPresets)); 11402 } catch (err) { 11403 dispatch(reportError(err)); 11404 } 11405 }; 11406}; 11407var getProjectWireframesPresetsWithoutValues = (accountId, projectName, version, stage) => { 11408 return async (dispatch, state, services) => { 11409 try { 11410 const { programId, programVersionId: programDraftVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(state(), projectName); 11411 let programVersionId; 11412 if (version || stage) { 11413 const project = StateReaderUtils.getProject(state(), projectName); 11414 const snapshotId = version ? StateReaderUtils.getSnapshotIdByNumber(projectName, version) : StateReaderUtils.getLatestSnapshotIdForStage(project, stage); 11415 const versionDetails = StateReaderUtils.getSnapshot(state(), { snapshotId }); 11416 if (versionDetails) programVersionId = versionDetails.snapshotSource === SnapshotSource.POSTGRES ? versionDetails.graphQLId : programDraftVersionId; 11417 } else programVersionId = programDraftVersionId; 11418 const getGqlPresetsResponse = await services.graphQlClient.query({ 11419 fetchPolicy: "no-cache", 11420 query: GetProgramPresetsWithoutValuesDocument, 11421 variables: { 11422 programId, 11423 programVersionId 11424 } 11425 }).catch(() => null); 11426 const existingPresets = state().presets.byName[projectName]; 11427 dispatch(loadingProjectWireframesPresetsSuccess(accountId, projectName, convertGqlPresetsWithoutValuesResult(getGqlPresetsResponse, existingPresets))); 11428 } catch (err) { 11429 dispatch(reportError(err)); 11430 } 11431 }; 11432}; 11433var getProjectWireframesPresetValues = (accountId, projectName, version, stage, presetId) => { 11434 return async (dispatch, state, services) => { 11435 try { 11436 const { programId, programVersionId: programDraftVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(state(), projectName); 11437 let programVersionId; 11438 if (version || stage) { 11439 const project = StateReaderUtils.getProject(state(), projectName); 11440 const snapshotId = version ? StateReaderUtils.getSnapshotIdByNumber(projectName, version) : StateReaderUtils.getLatestSnapshotIdForStage(project, stage); 11441 const versionDetails = StateReaderUtils.getSnapshot(state(), { snapshotId }); 11442 if (versionDetails) programVersionId = versionDetails.snapshotSource === SnapshotSource.POSTGRES ? versionDetails.graphQLId : programDraftVersionId; 11443 } else programVersionId = programDraftVersionId; 11444 const getGqlPresetValuesResponse = await services.graphQlClient.query({ 11445 fetchPolicy: "no-cache", 11446 query: GetProgramPresetValuesDocument, 11447 variables: { 11448 programId, 11449 programVersionId, 11450 presetId 11451 } 11452 }).catch(() => null); 11453 const existingPresets = state().presets.byName[projectName]; 11454 dispatch(loadingProjectWireframesPresetsSuccess(accountId, projectName, convertGqlPresetValuesResultAndAddToPresetMap(getGqlPresetValuesResponse, existingPresets))); 11455 } catch (err) { 11456 dispatch(reportError(err)); 11457 } 11458 }; 11459}; 11460var updateCustomAnalyticsOrder = function(accountId, projectName, analyticsOrder) { 11461 return function(dispatch, getState, services) { 11462 let input = { 11463 id: StateReaderUtils.getProgramId(getState(), projectName), 11464 updated: IGNORE_UPDATED,
11465 customAnalyticsOrder: analyticsOrder 11466 }; 11467 services.graphQlClient.mutate({ 11468 mutation: UpdateProgramDocument, 11469 variables: { 11470 input, 11471 [IGNORE_SERVER_ERRORS]: true 11472 } 11473 }).then((res) => { 11474 if (res.data.updateProgram.__typename === "UpdateProgramOutputSuccess") dispatch(setCustomAnalyticsOrderSuccess(accountId, projectName, analyticsOrder, res.data.updateProgram.program.updated)); 11475 }).catch((err) => { 11476 dispatch(reportError(err)); 11477 }); 11478 }; 11479}; 11480var addCustomField = (accountId, projectName, fieldName, fieldData) => { 11481 return function(dispatch, getState, services) { 11482 let input = { 11483 name: fieldName, 11484 logic: fieldData, 11485 programId: StateReaderUtils.getProgramId(getState(), projectName) 11486 }; 11487 services.graphQlClient.mutate({ 11488 mutation: CreateCustomAnalyticFieldDocument, 11489 variables: { 11490 input, 11491 [IGNORE_SERVER_ERRORS]: true 11492 } 11493 }).then((result) => { 11494 dispatch(addCustomAnalyticFieldSuccess(accountId, projectName, { 11495 id: result.data.createCustomAnalyticField.customAnalyticField.id, 11496 name: fieldName, 11497 data: fieldData, 11498 graphQLUpdated: result.data.createCustomAnalyticField.customAnalyticField.updated 11499 })); 11500 }).catch((err) => { 11501 dispatch(reportError(err)); 11502 }); 11503 }; 11504}; 11505var updateCustomField = (accountId, projectName, fieldId, newName, newData) => { 11506 return async function(dispatch, getState, services) { 11507 const program = StateReaderUtils.getProject(getState(), projectName); 11508 const isProgramPermanentlyMigratedToPostgres = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), program.graphQLId, BulkId.MostEntities); 11509 let gqlAnalyticFieldId; 11510 if (isProgramPermanentlyMigratedToPostgres) gqlAnalyticFieldId = fieldId; 11511 else gqlAnalyticFieldId = getState().activeGqlProgram.customAnalyticFields.find((field) => field.name === fieldId).id; 11512 let input = { 11513 id: gqlAnalyticFieldId, 11514 updated: IGNORE_UPDATED, 11515 logic: newData, 11516 name: newName 11517 }; 11518 try { 11519 const gqlResult = await services.graphQlClient.mutate({ 11520 mutation: UpdateCustomAnalyticFieldDocument, 11521 variables: { 11522 input, 11523 [IGNORE_SERVER_ERRORS]: true 11524 } 11525 }); 11526 if (gqlResult.data.updateCustomAnalyticField.__typename === "UpdateCustomAnalyticFieldOutputSuccess") if (isProgramPermanentlyMigratedToPostgres) { 11527 const analyticFieldUpdates = { 11528 id: fieldId, 11529 name: newName, 11530 data: newData, 11531 graphQLUpdated: gqlResult.data.updateCustomAnalyticField.customAnalyticField.updated 11532 }; 11533 Object.keys(analyticFieldUpdates).forEach((key) => analyticFieldUpdates[key] === void 0 && delete analyticFieldUpdates[key]); 11534 dispatch(setCustomAnalyticFieldSuccess(accountId, projectName, analyticFieldUpdates)); 11535 } else dispatch(loadingGqlProgramSuccess(gqlResult.data.updateCustomAnalyticField.customAnalyticField.program)); 11536 } catch (err) { 11537 if (isProgramPermanentlyMigratedToPostgres) dispatch(reportError(err)); 11538 } 11539 }; 11540}; 11541var deleteCustomField = (accountId, projectName, fieldId) => { 11542 return function(dispatch, getState, services) { 11543 const program = StateReaderUtils.getProject(getState(), projectName); 11544 const isProgramPermanentlyMigratedToPostgres = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), program.graphQLId, BulkId.MostEntities); 11545 let gqlAnalyticFieldId; 11546 if (isProgramPermanentlyMigratedToPostgres) gqlAnalyticFieldId = fieldId; 11547 else gqlAnalyticFieldId = getState().activeGqlProgram.customAnalyticFields.find((field) => field.name === fieldId).id; 11548 let input = { id: gqlAnalyticFieldId }; 11549 services.graphQlClient.mutate({ 11550 mutation: DeleteCustomAnalyticFieldDocument, 11551 variables: { 11552 input, 11553 [IGNORE_SERVER_ERRORS]: true 11554 } 11555 }).then((result) => { 11556 if (isProgramPermanentlyMigratedToPostgres) dispatch(deleteCustomAnalyticFieldSuccess(accountId, projectName, fieldId)); 11557 else dispatch(loadingGqlProgramSuccess(result.data.deleteCustomAnalyticField.program)); 11558 }).catch((err) => { 11559 if (isProgramPermanentlyMigratedToPostgres) dispatch(reportError(err)); 11560 }); 11561 }; 11562}; 11563var duplicateNarration = (accountId, projectName, sceneId, scenePartIndex, narrationPartIndex) => { 11564 return (dispatch, getState, services) => { 11565 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 11566 let scenePart = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 11567 if (StateReaderUtils.getNarrationsVersion(wireframes) > 0) { 11568 let narrationId = scenePart.NarrationParts[narrationPartIndex].id; 11569 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 11570 let structure = wireframes.narrations.byId[narrationId].structure; 11571 let variationDataMap = wireframes.narrations.byId[narrationId].variationDataMap; 11572 if (!isPostgresOnly) addNarrationWithBody(dispatch, getState, services, accountId, projectName, sceneId, scenePartIndex, structure, variationDataMap).then((answer) => { 11573 let newScenePart = { ...scenePart }; 11574 newScenePart.NarrationParts.push({ id: answer.narrationId }); 11575 dispatch(setProjectWireframesScenePart(accountId, projectName, sceneId, newScenePart.scenePart, newScenePart, scenePartIndex, true)); 11576 return answer.narrationId; 11577 }).then((newNarrationId) => { 11578 let programSummary = StateReaderUtils.getProgramSummaries(getState()).find((ps) => ps.projectIds.builders === projectName); 11579 let wireframes = StateReaderUtils.getWireFrame(getState(), projectName); 11580 let scenePart = StateReaderUtils.getProjectWireframesScenePart(wireframes, sceneId, scenePartIndex); 11581 const postgresNarrationId = StateReaderUtils.getNarrationPostgresId(wireframes, narrationId) || narrationId; 11582 let input = { sourceId: `${programSummary.projectIds.builderDraftVersionId}|${sceneId}|${scenePart.scenePart}|${postgresNarrationId}` }; 11583 services.graphQlClient.mutate({ 11584 mutation: CopyNarrationDocument, 11585 variables: { 11586 input, 11587 legacyId: newNarrationId, 11588 [IGNORE_SERVER_ERRORS]: true 11589 } 11590 }).catch(() => {}); 11591 }); 11592 else services.graphQlClient.mutate({ 11593 mutation: CopyNarrationDocument, 11594 variables: { input: { sourceId: narrationId } } 11595 }).then((gqlOutput) => { 11596 let { updated, id } = gqlOutput.data.copyNarration.targetNarration; 11597 dispatch(addNarrationSuccess(accountId, projectName, sceneId, id, structure, variationDataMap, void 0, updated)); 11598 let newNarrationParts = [...scenePart.NarrationParts, { id }]; 11599 dispatch(ChangingProjectWireframesScenePartsSuccess(accountId, projectName, sceneId, { 11600 ...scenePart, 11601 NarrationParts: newNarrationParts 11602 }, scenePartIndex)); 11603 }).catch(() => {}); 11604 } else { 11605 let newScenePart = { ...scenePart }; 11606 let newNarration = newScenePart.NarrationParts[narrationPartIndex]; 11607 newScenePart.NarrationParts = [...scenePart.NarrationParts, newNarration]; 11608 dispatch(setProjectWireframesScenePart(accountId, projectName, sceneId, newScenePart.scenePart, newScenePart, scenePartIndex, true)); 11609 } 11610 }; 11611}; 11612var updateProjectMasterData = (accountId, projectName, master) => { 11613 return (dispatch, state, services) => { 11614 const masterData = master.sceneParts[0]; 11615 services.wireframes.updateProjectMasterData(accountId, projectName, masterData).then((master) => { 11616 dispatch(updateProjectMasterDataSuccess(projectName, master.masterData)); 11617 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(state(), projectName); 11618 const input = { 11619 programVersionId, 11620 masterData 11621 }; 11622 services.graphQlClient.mutate({ 11623 mutation: UpdateMasterDataDocument, 11624 variables: { 11625 input, 11626 dryRun: false, 11627 [IGNORE_SERVER_ERRORS]: true 11628 } 11629 }).catch((err) => {}); 11630 }).catch((error) => { 11631 dispatch(reportError(error)); 11632 }); 11633 }; 11634}; 11635var createMasterAnimationGuideline = (accountId, projectName, name, type, cb) => { 11636 return (dispatch, getState, services) => { 11637 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 11638 services.graphQlClient.mutate({ 11639 mutation: CreateMasterAnimationGuidelineDocument, 11640 variables: { 11641 input: { 11642 programVersionId, 11643 name, 11644 type: convertAnimationGuidelineType(type) 11645 }, 11646 dryRun: false 11647 } 11648 }).then((gqlOutput) => { 11649 const gqlMasterAnimationGuideline = gqlOutput.data.createMasterAnimationGuideline.masterAnimationGuideline; 11650 dispatch(createMasterAnimationGuidelineSuccess(projectName, { 11651 graphQLId: gqlMasterAnimationGuideline.id, 11652 graphQLUpdated: gqlMasterAnimationGuideline.updated, 11653 type, 11654 name 11655 })); 11656 cb(); 11657 }).catch((err) => {}); 11658 }; 11659}; 11660var renameMasterAnimationGuideline = (accountId, projectName, updatedAnimationGuidelineIndex, newName, cb) => { 11661 return (dispatch, getState, services) => { 11662 const animationGuideline = StateReaderUtils.getProjectMasterData(getState(), projectName).parameters[updatedAnimationGuidelineIndex]; 11663 services.graphQlClient.mutate({ 11664 mutation: UpdateMasterAnimationGuidelineDocument, 11665 variables: { 11666 input: { 11667 id: animationGuideline.graphQLId, 11668 name: newName, 11669 updated: IGNORE_UPDATED 11670 }, 11671 dryRun: false 11672 } 11673 }).then((gqlOutput) => { 11674 if (gqlOutput.data.updateMasterAnimationGuideline.__typename === "UpdateMasterAnimationGuidelineOutputSuccess") { 11675 dispatch(renameMasterAnimationGuidelineSuccess(projectName, updatedAnimationGuidelineIndex, { 11676 graphQLUpdated: gqlOutput.data.updateMasterAnimationGuideline.masterAnimationGuideline.updated, 11677 name: newName 11678 })); 11679 cb(); 11680 } 11681 }).catch((err) => {}); 11682 }; 11683}; 11684var deleteMasterAnimationGuideline = (accountId, projectName, deletedAnimationGuidelineIndex, cb) => { 11685 return (dispatch, state, services) => { 11686 const animationGuideline = StateReaderUtils.getProjectMasterData(state(), projectName).parameters[deletedAnimationGuidelineIndex]; 11687 services.graphQlClient.mutate({ 11688 mutation: DeleteMasterAnimationGuidelineDocument, 11689 variables: { 11690 input: { id: animationGuideline.graphQLId }, 11691 dryRun: false 11692 } 11693 }).then((gqlOutput) => { 11694 dispatch(deleteMasterAnimationGuidelineSuccess(projectName, animationGuideline.name)); 11695 cb(); 11696 }).catch((err) => {}); 11697 }; 11698}; 11699var getPresetValuesFromData = (presetData, programVersionId, dataElements) => { 11700 const systemElementValues = presetData ? [] : void 0; 11701 const dataElementValues = presetData ? [] : void 0;
11702 presetData && Object.keys(presetData).forEach((presetValueId) => { 11703 const dataElement = dataElements.find((de) => de.id === presetValueId || de.name === presetValueId || de.displayName === presetValueId); 11704 if (!dataElement) return; 11705 const { type, value, valueId } = getDynamoPresetValueFields(presetData[presetValueId]); 11706 const nullableFields = { 11707 type, 11708 value: value !== null && value !== void 0 ? JSON.stringify(value) : null, 11709 valueId 11710 }; 11711 if (dataElement.origin === DataElementOrigins.System) systemElementValues.push({ 11712 systemElementId: presetValueId, 11713 ...nullableFields 11714 }); 11715 else dataElementValues.push({ 11716 dataElementId: `${programVersionId}|${dataElement.id}`, 11717 ...nullableFields 11718 }); 11719 }); 11720 return { 11721 systemElementValues, 11722 dataElementValues 11723 }; 11724}; 11725var getDynamoPresetValueFields = (dynamoPresetValue) => { 11726 const isPrimitivePresetValue = dynamoPresetValue === null || dynamoPresetValue === void 0 || !dynamoPresetValue.hasOwnProperty("value") && !dynamoPresetValue.hasOwnProperty("type"); 11727 return { 11728 type: isPrimitivePresetValue ? null : getPresetValueType(dynamoPresetValue), 11729 value: isPrimitivePresetValue ? dynamoPresetValue : dynamoPresetValue.value, 11730 valueId: isPrimitivePresetValue ? null : dynamoPresetValue.valueId || null 11731 }; 11732}; 11733var getPresetValueType = (presetValue) => { 11734 return isObject(presetValue.type) ? presetValue.type.type : presetValue.type; 11735}; 11736//#endregion 11737//#region common/types/editorPlaceholder.ts 11738var Adjustment = /* @__PURE__ */ function(Adjustment) { 11739 Adjustment["ScaleToFit"] = "scaleToFit"; 11740 Adjustment["ScaleToFill"] = "scaleToFill"; 11741 Adjustment["Stretch"] = "stretch"; 11742 return Adjustment; 11743}({}); 11744var VerticalAlignment = /* @__PURE__ */ function(VerticalAlignment) { 11745 VerticalAlignment["Top"] = "top"; 11746 VerticalAlignment["Center"] = "center"; 11747 VerticalAlignment["Bottom"] = "bottom"; 11748 return VerticalAlignment; 11749}({}); 11750var HorizontalAlignment = /* @__PURE__ */ function(HorizontalAlignment) { 11751 HorizontalAlignment["Left"] = "left"; 11752 HorizontalAlignment["Center"] = "center"; 11753 HorizontalAlignment["Right"] = "right"; 11754 return HorizontalAlignment; 11755}({}); 11756var TextFit = /* @__PURE__ */ function(TextFit) { 11757 TextFit["ResizeFont"] = "resize-font"; 11758 TextFit["ScrollDown"] = "scroll-down"; 11759 TextFit["SplitIntoSections"] = "split-into-sections"; 11760 return TextFit; 11761}({}); 11762var TextHorizontalLinePaddingMode = /* @__PURE__ */ function(TextHorizontalLinePaddingMode) { 11763 TextHorizontalLinePaddingMode["On"] = "on"; 11764 TextHorizontalLinePaddingMode["Off"] = "off"; 11765 TextHorizontalLinePaddingMode["Auto"] = "auto"; 11766 return TextHorizontalLinePaddingMode; 11767}({}); 11768var BreathingType = /* @__PURE__ */ function(BreathingType) { 11769 BreathingType["In"] = "In"; 11770 BreathingType["Out"] = "Out"; 11771 BreathingType["None"] = "None"; 11772 return BreathingType; 11773}({}); 11774var DurationType = /* @__PURE__ */ function(DurationType) { 11775 DurationType["TruncateContentAtSceneEnd"] = "TruncateContentAtSceneEnd"; 11776 DurationType["PlayToEndOfContent"] = "PlayToEndOfContent"; 11777 DurationType["LoopContent"] = "LoopContent"; 11778 return DurationType; 11779}({}); 11780var SoundUnit = /* @__PURE__ */ function(SoundUnit) { 11781 SoundUnit["Percent"] = "%"; 11782 return SoundUnit; 11783}({}); 11784var PlaceholderShowType = /* @__PURE__ */ function(PlaceholderShowType) { 11785 PlaceholderShowType["Static"] = "static"; 11786 PlaceholderShowType["Dynamic"] = "dynamic"; 11787 return PlaceholderShowType; 11788}({}); 11789/** version 5 **/ 11790var ButtonActions = { OpenUrl: "openUrl" }; 11791var CommonPlaceholderType = /* @__PURE__ */ function(CommonPlaceholderType) { 11792 CommonPlaceholderType["TEXT"] = "text"; 11793 CommonPlaceholderType["MEDIA"] = "media"; 11794 CommonPlaceholderType["NARRATION"] = "narration"; 11795 CommonPlaceholderType["BUTTON"] = "button"; 11796 CommonPlaceholderType["AVATAR"] = "avatar"; 11797 CommonPlaceholderType["BULLET"] = "bullet"; 11798 return CommonPlaceholderType; 11799}({}); 11800/** version 9 - support for rich text **/ 11801/** also in version 9 - support for Avatars **/ 11802var RichTextStyleSetting = /* @__PURE__ */ function(RichTextStyleSetting) { 11803 RichTextStyleSetting["TRUE"] = "true"; 11804 RichTextStyleSetting["FALSE"] = "false"; 11805 RichTextStyleSetting["UNSET"] = "unset"; 11806 return RichTextStyleSetting; 11807}({}); 11808var ORIGIN_LANGUAGE = "origin"; 11809var ButtonShowContentItemElement = /* @__PURE__ */ function(ButtonShowContentItemElement) { 11810 ButtonShowContentItemElement["Text"] = "text"; 11811 ButtonShowContentItemElement["URL"] = "url"; 11812 ButtonShowContentItemElement["Report"] = "report"; 11813 return ButtonShowContentItemElement; 11814}({}); 11815var AvatarSource = /* @__PURE__ */ function(AvatarSource) { 11816 AvatarSource["CC"] = "cc"; 11817 AvatarSource["ACCOUNT"] = "account"; 11818 return AvatarSource; 11819}({}); 11820var BulletIconSize = /* @__PURE__ */ function(BulletIconSize) { 11821 BulletIconSize["S"] = "S"; 11822 BulletIconSize["M"] = "M"; 11823 BulletIconSize["L"] = "L"; 11824 BulletIconSize["XL"] = "XL"; 11825 return BulletIconSize; 11826}({}); 11827var BulletOrientation = /* @__PURE__ */ function(BulletOrientation) { 11828 BulletOrientation["Horizontal"] = "horizontal"; 11829 BulletOrientation["Vertical"] = "vertical"; 11830 return BulletOrientation; 11831}({});
11832var DEFAULT_BULLET_ICON_SIZE_BY_ORIENTATION = { 11833 ["horizontal"]: "M", 11834 ["vertical"]: "M" 11835}; 11836var BULLET_ICON_SIZE_FRACTION_BY_ORIENTATION = { 11837 ["horizontal"]: { 11838 ["S"]: .05, 11839 ["M"]: .1, 11840 ["L"]: .15, 11841 ["XL"]: .2 11842 }, 11843 ["vertical"]: { 11844 ["S"]: .1, 11845 ["M"]: .17, 11846 ["L"]: .24, 11847 ["XL"]: .31 11848 } 11849}; 11850var BULLET_ICON_TEXT_GAP_FACTOR = .15; 11851var BULLET_TEXT_PART_NAME = "text"; 11852var BULLET_ICON_PART_NAME = "icon"; 11853/** version 2 **/ 11854var ContentType = /* @__PURE__ */ function(ContentType) { 11855 ContentType["Text"] = "text"; 11856 ContentType["Media"] = "media"; 11857 ContentType["Button"] = "button"; 11858 ContentType["Avatar"] = "avatar"; 11859 ContentType["Narration"] = "narration"; 11860 ContentType["Bullet"] = "bullet"; 11861 return ContentType; 11862}({}); 11863var MediaSettingKey = /* @__PURE__ */ function(MediaSettingKey) { 11864 MediaSettingKey["Adjustment"] = "Adjustment"; 11865 MediaSettingKey["Alignment"] = "Alignment"; 11866 MediaSettingKey["Color"] = "Color"; 11867 MediaSettingKey["Breathing"] = "Breathing"; 11868 MediaSettingKey["PlayToEnd"] = "PlayToEnd"; 11869 MediaSettingKey["Sound"] = "Sound"; 11870 MediaSettingKey["OverrideLogo"] = "OverrideLogo"; 11871 MediaSettingKey["Duration"] = "Duration"; 11872 return MediaSettingKey; 11873}({}); 11874var TextSettingKey = /* @__PURE__ */ function(TextSettingKey) { 11875 TextSettingKey["Color"] = "Color"; 11876 TextSettingKey["FontSize"] = "FontSize"; 11877 TextSettingKey["BackgroundColor"] = "BackgroundColor"; 11878 TextSettingKey["HorizontalAlignment"] = "HorizontalAlignment"; 11879 TextSettingKey["VerticalAlignment"] = "VerticalAlignment"; 11880 TextSettingKey["Style"] = "Style"; 11881 TextSettingKey["Fit"] = "Fit"; 11882 TextSettingKey["HorizontalLinePaddingMode"] = "HorizontalLinePaddingMode"; 11883 return TextSettingKey; 11884}({}); 11885var NarrationSettingsKey = /* @__PURE__ */ function(NarrationSettingsKey) { 11886 NarrationSettingsKey["AlternativeVoice"] = "AlternativeVoice"; 11887 return NarrationSettingsKey; 11888}({}); 11889var AvatarSettingsKey = /* @__PURE__ */ function(AvatarSettingsKey) { 11890 AvatarSettingsKey["Offset"] = "Offset"; 11891 AvatarSettingsKey["Crop"] = "Crop"; 11892 AvatarSettingsKey["DeprecatedAlignment"] = "Alignment"; 11893 return AvatarSettingsKey; 11894}({}); 11895var GlobalSettingKey = /* @__PURE__ */ function(GlobalSettingKey) { 11896 GlobalSettingKey["IsHidden"] = "IsHidden"; 11897 return GlobalSettingKey; 11898}({}); 11899var BulletSettingKey = /* @__PURE__ */ function(BulletSettingKey) { 11900 BulletSettingKey["IconSize"] = "IconSize"; 11901 BulletSettingKey["IconColor"] = "IconColor"; 11902 BulletSettingKey["TextColor"] = "TextColor"; 11903 return BulletSettingKey; 11904}({}); 11905var NarratorLibrary = /* @__PURE__ */ function(NarratorLibrary) { 11906 NarratorLibrary["CC_NARRATORS"] = "cc_narrators"; 11907 NarratorLibrary["CC_AVATARS"] = "cc_avatars"; 11908 NarratorLibrary["EDITOR_ACCOUNT_LEVEL_AVATARS"] = "editor_account_level_avatars"; 11909 return NarratorLibrary; 11910}({}); 11911var AvatarCropPreset = /* @__PURE__ */ function(AvatarCropPreset) { 11912 AvatarCropPreset["FULL_BODY"] = "full-body"; 11913 AvatarCropPreset["CLOSE_UP"] = "close-up"; 11914 return AvatarCropPreset; 11915}({}); 11916var FontSizeUnit = /* @__PURE__ */ function(FontSizeUnit) { 11917 FontSizeUnit["EM"] = "em"; 11918 FontSizeUnit["PX"] = "px"; 11919 return FontSizeUnit; 11920}({}); 11921var PositionUnit = /* @__PURE__ */ function(PositionUnit) { 11922 PositionUnit["Percent"] = "%"; 11923 PositionUnit["Pixel"] = "px"; 11924 return PositionUnit; 11925}({}); 11926var DEFAULT_CONTENT = "__defaultContent"; 11927var PlaceholderIntentName = /* @__PURE__ */ function(PlaceholderIntentName) { 11928 PlaceholderIntentName["Preheading"] = "Pre-heading"; 11929 PlaceholderIntentName["Heading"] = "Heading"; 11930 PlaceholderIntentName["Subheading"] = "Sub-heading"; 11931 PlaceholderIntentName["BodyText"] = "Body Text"; 11932 PlaceholderIntentName["Footnote"] = "Footnote"; 11933 PlaceholderIntentName["Bullet"] = "Bullet"; 11934 PlaceholderIntentName["HorizontalBullet"] = "Horizontal Bullet"; 11935 PlaceholderIntentName["VerticalBullet"] = "Vertical Bullet"; 11936 PlaceholderIntentName["Price"] = "Price"; 11937 PlaceholderIntentName["Button"] = "Button"; 11938 PlaceholderIntentName["ListItem"] = "List Item"; 11939 PlaceholderIntentName["Icon"] = "Icon"; 11940 PlaceholderIntentName["Logo"] = "Logo"; 11941 PlaceholderIntentName["ImageOrVideo"] = "Image/Video"; 11942 PlaceholderIntentName["Narration"] = "Narration"; 11943 PlaceholderIntentName["CTAButton"] = "CTA Button"; 11944 PlaceholderIntentName["TextOverlay"] = "Text Overlay"; 11945 PlaceholderIntentName["Avatar"] = "Avatar"; 11946 PlaceholderIntentName["MediaOverlay"] = "Media Overlay"; 11947 return PlaceholderIntentName; 11948}({}); 11949var placeholderCreationGroupMap = { 11950 ["Heading"]: "HeadingSubheadingMedia", 11951 ["Sub-heading"]: "HeadingSubheadingMedia", 11952 ["Image/Video"]: "HeadingSubheadingMedia", 11953 ["Logo"]: "Logo", 11954 ["Footnote"]: "Footnote", 11955 ["CTA Button"]: "Button", 11956 ["Text Overlay"]: "Overlays", 11957 ["Media Overlay"]: "Overlays", 11958 ["Horizontal Bullet"]: "HorizontalBullets", 11959 ["Vertical Bullet"]: "VerticalBullets" 11960}; 11961function getPlaceholderCreationGroup(placeholderIntentName) { 11962 return placeholderCreationGroupMap[placeholderIntentName]; 11963} 11964//#endregion 11965//#region common/types/vlxTypes.ts 11966var VLXInputLogicType = /* @__PURE__ */ function(VLXInputLogicType) { 11967 VLXInputLogicType["TEXT"] = "text"; 11968 VLXInputLogicType["MEDIA"] = "media"; 11969 VLXInputLogicType["NARRATION"] = "narration"; 11970 VLXInputLogicType["ANIMATION"] = "animation"; 11971 VLXInputLogicType["COLOR"] = "color"; 11972 VLXInputLogicType["COMPOUND"] = "compound"; 11973 VLXInputLogicType["BOOLEAN"] = "boolean"; 11974 VLXInputLogicType["NUMBER"] = "number"; 11975 return VLXInputLogicType; 11976}({}); 11977var MinimumContentEndBase = /* @__PURE__ */ function(MinimumContentEndBase) { 11978 MinimumContentEndBase["ClipBegin"] = "clipBegin"; 11979 MinimumContentEndBase["ClipEnd"] = "clipEnd"; 11980 return MinimumContentEndBase; 11981}({}); 11982var ObjectFit = /* @__PURE__ */ function(ObjectFit) { 11983 ObjectFit["Cover"] = "cover"; 11984 ObjectFit["Contain"] = "contain"; 11985 ObjectFit["Fill"] = "fill"; 11986 return ObjectFit; 11987}({}); 11988var FontVariantCaps = /* @__PURE__ */ function(FontVariantCaps) { 11989 FontVariantCaps["Normal"] = "normal"; 11990 FontVariantCaps["SmallCaps"] = "small-caps"; 11991 FontVariantCaps["AllSmallCaps"] = "all-small-caps"; 11992 return FontVariantCaps; 11993}({}); 11994var TextTransform = /* @__PURE__ */ function(TextTransform) { 11995 TextTransform["None"] = "none"; 11996 TextTransform["Uppercase"] = "uppercase"; 11997 TextTransform["Lowercase"] = "lowercase"; 11998 TextTransform["Capitalize"] = "capitalize"; 11999 TextTransform["CapitalizeFirstLetter"] = "capitalize-first-letter"; 12000 return TextTransform; 12001}({}); 12002var TextHorizontalAlign = /* @__PURE__ */ function(TextHorizontalAlign) { 12003 TextHorizontalAlign["Left"] = "left"; 12004 TextHorizontalAlign["Center"] = "center"; 12005 TextHorizontalAlign["Right"] = "right"; 12006 return TextHorizontalAlign; 12007}({}); 12008var TextVerticalAlign = /* @__PURE__ */ function(TextVerticalAlign) {
12009 TextVerticalAlign["Top"] = "top"; 12010 TextVerticalAlign["Middle"] = "middle"; 12011 TextVerticalAlign["Bottom"] = "bottom"; 12012 return TextVerticalAlign; 12013}({}); 12014var VLXPlaceholderActionInstructionsAnchorMode = /* @__PURE__ */ function(VLXPlaceholderActionInstructionsAnchorMode) { 12015 VLXPlaceholderActionInstructionsAnchorMode["USER"] = "user"; 12016 VLXPlaceholderActionInstructionsAnchorMode["DISABLED"] = "disabled"; 12017 VLXPlaceholderActionInstructionsAnchorMode["DEFAULT"] = "default"; 12018 return VLXPlaceholderActionInstructionsAnchorMode; 12019}({}); 12020var VLXPlaceholderActionInstructionsAnchorType = /* @__PURE__ */ function(VLXPlaceholderActionInstructionsAnchorType) { 12021 VLXPlaceholderActionInstructionsAnchorType["PLACEHOLDER"] = "placeholderAnchor"; 12022 VLXPlaceholderActionInstructionsAnchorType["ABSOLUTE"] = "absolute"; 12023 return VLXPlaceholderActionInstructionsAnchorType; 12024}({}); 12025//#endregion 12026//#region common/vlxUtils.ts 12027var generateVlxStorySettingProjectId = (accountName, programName) => { 12028 return replaceSpecialChar(`${accountName}-${programName}`, "-"); 12029}; 12030var mapAdjustmentToFit = (adjustment) => { 12031 switch (adjustment) { 12032 case Adjustment.Stretch: return ObjectFit.Fill; 12033 case Adjustment.ScaleToFit: return ObjectFit.Contain; 12034 case Adjustment.ScaleToFill: return ObjectFit.Cover; 12035 default: return ObjectFit.Cover; 12036 } 12037}; 12038var convertToObjectPosition = (alignment) => { 12039 if (alignment != null) return `${alignment.horizontal} ${alignment.vertical}`; 12040 return `${HorizontalAlignment.Center} ${VerticalAlignment.Center}`; 12041}; 12042var cleanSceneName = (sceneName) => { 12043 return sceneName.replace(/\s/g, "__"); 12044}; 12045var originalSceneName = (sceneName) => { 12046 return sceneName.replace(/__/g, " "); 12047}; 12048function brandConfigurationTextStyleToVideoSpecStyleProps(bcTextStyle) { 12049 return { 12050 _sskyFontUrl: bcTextStyle.fontUrl, 12051 letterSpacing: bcTextStyle.letterSpacing / 1e3, 12052 fontVariantCaps: getTextStyleFontVariantCaps(bcTextStyle.letterCase), 12053 textTransform: getTextStyleTransform(bcTextStyle.letterCase), 12054 lineHeight: bcTextStyle.lineSpacing / 100 12055 }; 12056} 12057function getTextStyleFontVariantCaps(letterCase) { 12058 if (letterCase === "smallCaps") return FontVariantCaps.SmallCaps; 12059 else return FontVariantCaps.Normal; 12060} 12061function getTextStyleTransform(letterCase) { 12062 switch (letterCase) { 12063 case "lowercase": return TextTransform.Lowercase; 12064 case "uppercase": return TextTransform.Uppercase; 12065 case "capEachWord": return TextTransform.Capitalize; 12066 case "capFirstWord": return TextTransform.CapitalizeFirstLetter; 12067 default: return TextTransform.None; 12068 } 12069} 12070function getTextStyleHorizontalAlign(horizontalAlignment) { 12071 switch (horizontalAlignment) { 12072 case HorizontalAlignment.Left: return TextHorizontalAlign.Left; 12073 case HorizontalAlignment.Right: return TextHorizontalAlign.Right; 12074 case HorizontalAlignment.Center: 12075 default: return TextHorizontalAlign.Center; 12076 } 12077} 12078function getTextStyleVerticalAlign(verticalAlignment) { 12079 switch (verticalAlignment) { 12080 case VerticalAlignment.Top: return TextVerticalAlign.Top; 12081 case VerticalAlignment.Bottom: return TextVerticalAlign.Bottom; 12082 case VerticalAlignment.Center: 12083 default: return TextVerticalAlign.Middle; 12084 } 12085} 12086var MinContentEndPlayToEndOfContentIcon = { 12087 base: MinimumContentEndBase.ClipEnd, 12088 value: 0 12089}; 12090var MinContentEndPlayToEndOfContentNonIcon = { 12091 base: MinimumContentEndBase.ClipEnd, 12092 value: -1 12093}; 12094var MinContentEndTruncateAtSceneEnd = { 12095 base: MinimumContentEndBase.ClipBegin, 12096 value: 0 12097}; 12098MinimumContentEndBase.ClipEnd, -AVATAR_SILENCE_DURATION; 12099-AVATAR_SILENCE_DURATION; 12100function getCoordinatePixelValue(value, containerSize) { 12101 switch (value.unit) { 12102 case PositionUnit.Pixel: return value.value; 12103 case PositionUnit.Percent: return containerSize * value.value / 100; 12104 default: throw new Error(`Unsupported unit: ${value.unit}`); 12105 } 12106} 12107//#endregion 12108//#region common/placeholderUtils.ts 12109var ON_SCREEN_PER_LANGUAGE_PLACEHOLDER_TYPES = [ 12110 CommonPlaceholderType.TEXT, 12111 CommonPlaceholderType.BUTTON, 12112 CommonPlaceholderType.BULLET, 12113 CommonPlaceholderType.MEDIA 12114]; 12115var ON_SCREEN_PER_LANGUAGE_TRANSLATABLE_PLACEHOLDER_TYPES = [ 12116 CommonPlaceholderType.TEXT, 12117 CommonPlaceholderType.BUTTON, 12118 CommonPlaceholderType.BULLET 12119]; 12120var isOnScreenPerLanguageTranslatableType = (placeholderType) => ON_SCREEN_PER_LANGUAGE_TRANSLATABLE_PLACEHOLDER_TYPES.includes(placeholderType); 12121ON_SCREEN_PER_LANGUAGE_PLACEHOLDER_TYPES.filter((placeholderType) => !isOnScreenPerLanguageTranslatableType(placeholderType)); 12122var wrapByLanguage = (item, language) => { 12123 return { [language]: item }; 12124}; 12125var wrapByOriginLanguage = (item) => { 12126 return wrapByLanguage(item, ORIGIN_LANGUAGE); 12127}; 12128var wrapByAllLanguages = (item, additionalLanguages = []) => { 12129 return [ORIGIN_LANGUAGE, ...additionalLanguages].reduce((acc, languageType) => { 12130 acc[languageType] = item; 12131 return acc; 12132 }, {}); 12133}; 12134var buildByAllLanguages = (buildItem, additionalLanguages) => { 12135 return [ORIGIN_LANGUAGE, ...additionalLanguages].reduce((acc, languageType) => { 12136 acc[languageType] = buildItem(languageType); 12137 return acc; 12138 }, {}); 12139}; 12140/** 12141* Get the value of a specific language inside a show/staticFallback item 12142* @param item item 12143* @param language language to use 12144* @return the specific value of the specified language, or undefined if the item is falsy. 12145*/ 12146var getLanguageValue = (item, language) => { 12147 if (!item) return; 12148 return item[language]; 12149}; 12150/** 12151* Project a rich-text value onto its text content, dropping `style` and empty atoms: consecutive literal atoms merge 12152* into one part, and a personalization token contributes its data-element identity as a part of its own. 12153*/ 12154var projectRichTextContent = (atoms) => { 12155 return (atoms || []).reduce((parts, atom) => { 12156 const content = atom?.content; 12157 if (typeof content === "string") { 12158 if (!content) return parts; 12159 const lastPart = parts[parts.length - 1]; 12160 if (lastPart?.type === "text") lastPart.value += content; 12161 else parts.push({ 12162 type: "text", 12163 value: content 12164 }); 12165 return parts; 12166 } 12167 const localId = content?.localId; 12168 if (localId) parts.push({ 12169 type: "token", 12170 value: localId 12171 }); 12172 return parts; 12173 }, []); 12174}; 12175/** 12176* Whether two rich-text values differ in their TEXT, ignoring bold/italic. Applying formatting to part of a value 12177* re-splits it into more atoms carrying the same text, so comparing the atoms themselves reports a change that isn't 12178* one; comparing the content projection reports a change only when the text or a personalization token really moved. 12179*/ 12180var isRichTextContentChanged = (before, after) => { 12181 return JSON.stringify(projectRichTextContent(before)) !== JSON.stringify(projectRichTextContent(after)); 12182}; 12183/** 12184* List the languages used in a show/staticFallback item 12185* @param item item 12186* @return list of languages used 12187*/ 12188var listLanguages = (item) => { 12189 if (!item) return []; 12190 return Object.keys(item); 12191}; 12192/** 12193* Extracts and returns a list of unique languages associated with the given placeholder content. 12194* 12195* This function analyzes the `placeholderContent` object, including its `staticFallback`, 12196* `noRules.show`, and `rules.cases` properties, if they are defined and applicable. 12197* The extracted languages are consolidated into a unique list. 12198* 12199* @param {PlaceholderContent}
12199 placeholderContent - The content object containing placeholder language definitions. 12200* @returns {LanguageType[]} An array of <b>unique</b> languages derived from the placeholder content. 12201*/ 12202var listPlaceholderLanguages = (placeholderContent) => { 12203 const languages = /* @__PURE__ */ new Set(); 12204 if (placeholderContent.staticFallback) listLanguages(placeholderContent.staticFallback).forEach((lang) => languages.add(lang)); 12205 if (placeholderContent.noRules?.show) listLanguages(placeholderContent.noRules?.show).forEach((lang) => languages.add(lang)); 12206 if (placeholderContent.rules?.cases?.length > 0) placeholderContent.rules.cases.forEach((rule) => { 12207 listLanguages(rule.show).forEach((lang) => languages.add(lang)); 12208 }); 12209 return Array.from(languages); 12210}; 12211/** 12212* Updates a language-specific value in an object that stores items by language (the original item is unchanged) 12213* 12214* @template T - The type of the value associated with the specified language. 12215* @param {ItemByLanguage<T>} item - The original object containing items keyed by language. 12216* @param {LanguageType} language - The language identifier for which the value should be updated. 12217* @param {T} value - The new value to set for the specified language. 12218* @returns {ItemByLanguage<T>} A new object with the updated value for the specified language. 12219*/ 12220var setLanguageValue = (item, language, value) => { 12221 return { 12222 ...item || {}, 12223 [language]: value 12224 }; 12225}; 12226/**
12227* Updates a language-specific value within an object containing language-specific mappings (the original item is unchanged). 12228* 12229* @template T The type of the value associated with each language. 12230* @param {ItemByLanguage<T>} item An object mapping language keys to their corresponding values. 12231* @param {LanguageType} language The specific language key that needs to be updated. 12232* @param {Partial<T>} value A partial object containing the properties to update or override for the specified language. 12233* @returns {ItemByLanguage<T>} A new object with the specified language's value updated while preserving the existing structure. 12234*/ 12235var overrideLanguageValue = (item, language, value) => { 12236 if (!value || typeof value !== "object") return { 12237 ...item, 12238 [language]: value 12239 }; 12240 return { 12241 ...item, 12242 [language]: { 12243 ...item?.[language] || {}, 12244 ...value 12245 } 12246 }; 12247}; 12248var getDefaultBreathingValue = (intent) => { 12249 return [ 12250 PlaceholderIntentName.Logo, 12251 PlaceholderIntentName.Icon, 12252 PlaceholderIntentName.HorizontalBullet, 12253 PlaceholderIntentName.VerticalBullet 12254 ].includes(intent) ? buildBreathingSetting({ breathing: BreathingType.None }) : buildBreathingSetting(null); 12255}; 12256var getDefaultDurationValue = () => { 12257 return buildDurationSetting(false, DurationType.TruncateContentAtSceneEnd); 12258}; 12259var getDefaultSoundValue = () => { 12260 return buildMediaSoundSetting(); 12261}; 12262var getDefaultOverrideLogoValue = () => { 12263 return buildOverrideLogoSetting(); 12264}; 12265/** 12266* Merges a list of SingleElementIds into an ElementsDataById 12267* 12268* @param target target ElementsDataById 12269* @param sources array of SingleElementIds 12270*/ 12271var mergeElementData = (target, ...sources) => { 12272 sources.forEach((source) => { 12273 const { id, valueSetIds } = source; 12274 if (!target[id]) target[id] = source; 12275 else target[id].valueSetIds = Array.from(/* @__PURE__ */ new Set([...target[id].valueSetIds, ...valueSetIds])); 12276 }); 12277}; 12278var buildSingleElementIds = (id, valueSetIds) => ({ 12279 id, 12280 valueSetIds: valueSetIds ?? [] 12281}); 12282/** 12283* Returns data element ids from a given placeholderContent 12284* 12285* @param placeholderContent - Given placeholderContent 12286* @param includeDisabledPaths - If this is true, elements will also be collected from paths that are currently disabled (for example, if 12287* useRules=false, we will still check the rules object). This should usually be true for draft programs, and false for snapshot programs 12288* (whose disabled paths will remain disabled) 12289*/ 12290function getDataElementsFromPlaceholderContent(placeholderContent, includeDisabledPaths) { 12291 return getDataElementsAndValuesFromPlaceholderContent(placeholderContent, includeDisabledPaths).map((element) => element.id); 12292} 12293/** 12294* Returns element data (id+values ids) from a given placeholderContent 12295* 12296* @param placeholderContent - Given placeholderContent 12297* @param includeDisabledPaths - If this is true, elements will also be collected from paths that are currently disabled (for example, if 12298* useRules=false, we will still check the rules object). This should usually be true for draft programs, and false for snapshot programs 12299* (whose disabled paths will remain disabled) 12300*/ 12301var getDataElementsAndValuesFromPlaceholderContent = (placeholderContent, includeDisabledPaths) => { 12302 const dataElementsById = {}; 12303 switch (placeholderContent.placeholderType) { 12304 case CommonPlaceholderType.TEXT: 12305 mergeElementData(dataElementsById, ...getTextOrNarrationDataElementIds(placeholderContent, includeDisabledPaths)); 12306 break; 12307 case CommonPlaceholderType.MEDIA: 12308 mergeElementData(dataElementsById, ...getMediaDataElementIds(placeholderContent, includeDisabledPaths)); 12309 break; 12310 case CommonPlaceholderType.NARRATION: 12311 mergeElementData(dataElementsById, ...getTextOrNarrationDataElementIds(placeholderContent, includeDisabledPaths)); 12312 break; 12313 case CommonPlaceholderType.BUTTON: 12314 mergeElementData(dataElementsById, ...getButtonDataElementIds(placeholderContent, includeDisabledPaths)); 12315 break; 12316 case CommonPlaceholderType.AVATAR: 12317 mergeElementData(dataElementsById, ...getAvatarDataElementIds(placeholderContent, includeDisabledPaths)); 12318 break; 12319 case CommonPlaceholderType.BULLET: 12320 mergeElementData(dataElementsById, ...getBulletDataElementIds(placeholderContent, includeDisabledPaths)); 12321 break; 12322 } 12323 return Object.values(dataElementsById); 12324}; 12325var getPrimaryPlaceholderText = (placeholderType, placeholderContentShow, language) => { 12326 if (!placeholderType) return; 12327 switch (placeholderType) {
12328 case CommonPlaceholderType.NARRATION: return getLanguageValue(placeholderContentShow, language)?.text; 12329 case CommonPlaceholderType.BULLET: return getLanguageValue(placeholderContentShow, language)?.textShow; 12330 case CommonPlaceholderType.BUTTON: { 12331 const buttonShow = getLanguageValue(placeholderContentShow, language); 12332 return buttonShow?.actionShow[buttonShow.useAction]?.text?.content; 12333 } 12334 case CommonPlaceholderType.TEXT: return getLanguageValue(placeholderContentShow, language); 12335 case CommonPlaceholderType.MEDIA: 12336 case CommonPlaceholderType.AVATAR: return; 12337 default: throw new Error(`Unhandled placeholder type in getPrimaryPlaceholderText: ${placeholderType}`); 12338 } 12339}; 12340var getPrimaryPlaceholderMedia = (placeholderType, placeholderContentShow, language) => { 12341 if (!placeholderType) return; 12342 switch (placeholderType) { 12343 case CommonPlaceholderType.MEDIA: return getLanguageValue(placeholderContentShow, language); 12344 case CommonPlaceholderType.BULLET: return getLanguageValue(placeholderContentShow, language)?.iconShow; 12345 case CommonPlaceholderType.TEXT: 12346 case CommonPlaceholderType.NARRATION: 12347 case CommonPlaceholderType.BUTTON: 12348 case CommonPlaceholderType.AVATAR: return; 12349 default: throw new Error(`Unhandled placeholder type in getPrimaryPlaceholderMedia: ${placeholderType}`); 12350 } 12351}; 12352function getTextOrNarrationDataElementIds(placeholderContent, includeDisabledPaths) { 12353 const dataElementsDataByIds = {}; 12354 const languages = listPlaceholderLanguages(placeholderContent); 12355 if ((includeDisabledPaths || placeholderContent.useRules) && placeholderContent.rules?.by?.localId) { 12356 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId)); 12357 if (placeholderContent.rules?.cases) for (const ruleCase of placeholderContent.rules.cases) {
12358 languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getTextOrNarrationShowElementIds(getPrimaryPlaceholderText(placeholderContent.placeholderType, ruleCase.show, language)))); 12359 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId, ruleCase.valueIds)); 12360 } 12361 } 12362 if ((includeDisabledPaths || !placeholderContent.useRules) && placeholderContent.noRules?.show) { 12363 if (placeholderContent.noRules.show) languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getTextOrNarrationShowElementIds(getPrimaryPlaceholderText(placeholderContent.placeholderType, placeholderContent.noRules.show, language)))); 12364 } 12365 return Object.values(dataElementsDataByIds); 12366} 12367function getMediaDataElementIds(placeholderContent, includeDisabledPaths) { 12368 const dataElementsDataByIds = {}; 12369 const languages = listPlaceholderLanguages(placeholderContent); 12370 if ((includeDisabledPaths || placeholderContent.useRules) && placeholderContent.rules?.by?.localId) { 12371 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId)); 12372 for (const ruleCase of placeholderContent.rules.cases) {
12373 languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getMediaShowV6Or8ElementIds(getLanguageValue(ruleCase?.show, language), includeDisabledPaths))); 12374 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId, ruleCase.valueIds)); 12375 } 12376 } 12377 if (includeDisabledPaths || !placeholderContent.useRules) languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getMediaShowV6Or8ElementIds(getLanguageValue(placeholderContent.noRules?.show, language), includeDisabledPaths))); 12378 return Object.values(dataElementsDataByIds); 12379} 12380function getAvatarDataElementIds(placeholderContent, includeDisabledPaths) { 12381 const dataElementsDataByIds = {}; 12382 const languages = listPlaceholderLanguages(placeholderContent); 12383 if ((includeDisabledPaths || placeholderContent.useRules) && placeholderContent.rules?.by?.localId) { 12384 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId)); 12385 for (const ruleCase of placeholderContent.rules.cases) {
12386 languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getAvatarShowElementIds(getLanguageValue(ruleCase?.show, language), includeDisabledPaths))); 12387 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId, ruleCase.valueIds)); 12388 } 12389 } 12390 if (includeDisabledPaths || !placeholderContent.useRules) languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getAvatarShowElementIds(getLanguageValue(placeholderContent.noRules?.show, language), includeDisabledPaths))); 12391 return Object.values(dataElementsDataByIds); 12392} 12393function getBulletShowElementIds(show, includeDisabledPaths) { 12394 if (!show) return []; 12395 const dataElementsDataByIds = {}; 12396 mergeElementData(dataElementsDataByIds, ...getTextOrNarrationShowElementIds(show.textShow)); 12397 mergeElementData(dataElementsDataByIds, ...getMediaShowV6Or8ElementIds(show.iconShow, includeDisabledPaths)); 12398 return Object.values(dataElementsDataByIds); 12399} 12400function getBulletDataElementIds(placeholderContent, includeDisabledPaths) { 12401 const dataElementsDataByIds = {}; 12402 const languages = listPlaceholderLanguages(placeholderContent); 12403 if ((includeDisabledPaths || placeholderContent.useRules) && placeholderContent.rules?.by?.localId) { 12404 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId)); 12405 if (placeholderContent.rules?.cases) for (const ruleCase of placeholderContent.rules.cases) {
12406 languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getBulletShowElementIds(getLanguageValue(ruleCase.show, language), includeDisabledPaths))); 12407 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId, ruleCase.valueIds)); 12408 } 12409 } 12410 if (includeDisabledPaths || !placeholderContent.useRules) languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getBulletShowElementIds(getLanguageValue(placeholderContent.noRules?.show, language), includeDisabledPaths))); 12411 return Object.values(dataElementsDataByIds); 12412} 12413function getButtonDataElementIds(placeholderContent, includeDisabledPaths) { 12414 const dataElementsDataByIds = {}; 12415 const languages = listPlaceholderLanguages(placeholderContent); 12416 if ((includeDisabledPaths || placeholderContent.useRules) && placeholderContent.rules?.by?.localId) { 12417 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId)); 12418 for (const ruleCase of placeholderContent.rules.cases) {
12419 languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getButtonShowElementIds(getLanguageValue(ruleCase.show, language), includeDisabledPaths))); 12420 mergeElementData(dataElementsDataByIds, buildSingleElementIds(placeholderContent.rules.by.localId, ruleCase.valueIds)); 12421 } 12422 } 12423 if (includeDisabledPaths || !placeholderContent.useRules) languages.forEach((language) => mergeElementData(dataElementsDataByIds, ...getButtonShowElementIds(getLanguageValue(placeholderContent.noRules?.show, language), includeDisabledPaths))); 12424 return Object.values(dataElementsDataByIds); 12425} 12426/** 12427* Add used elements IDs from a button show element 12428* @param show button show element 12429* @param includeDisabledPaths whether to include elements from paths that are currently disabled (but may be enabled by user action) 12430*/ 12431function getButtonShowElementIds(show, includeDisabledPaths) { 12432 if (!show || !show.actionShow) return []; 12433 const dataElementsDataByIds = {}; 12434 for (const [actionType, buttonShowContent] of Object.entries(show.actionShow)) if (buttonShowContent && (includeDisabledPaths || actionType === show.useAction)) { 12435 mergeElementData(dataElementsDataByIds, ...getTextOrNarrationShowElementIds(buttonShowContent.text.content)); 12436 mergeElementData(dataElementsDataByIds, ...getTextOrNarrationShowElementIds(buttonShowContent.url.content)); 12437 } 12438 return Object.values(dataElementsDataByIds); 12439} 12440/** 12441* Add used elements IDs from a media show element 12442* @param show media show element 12443* @param includeDisabledPaths whether to include elements from paths that are currently disabled (but may be enabled by user action) 12444*/ 12445function getMediaShowV6Or8ElementIds(show, includeDisabledPaths) { 12446 if (!show) return []; 12447 const dataElementsDataByIds = {}; 12448 if (includeDisabledPaths || show?.showType === PlaceholderShowType.Dynamic) { 12449 const localId = show?.dynamic?.localId; 12450 if (localId) mergeElementData(dataElementsDataByIds, buildSingleElementIds(localId)); 12451 } 12452 return Object.values(dataElementsDataByIds); 12453} 12454/** 12455* Add used elements IDs from an avatar show element 12456* @param show avatar show element 12457* @param includeDisabledPaths whether to include elements from paths that are currently disabled (but may be enabled by user action) 12458*/ 12459function getAvatarShowElementIds(show, includeDisabledPaths) { 12460 if (!show) return []; 12461 const dataElementsDataByIds = {}; 12462 if (includeDisabledPaths || show?.showType === PlaceholderShowType.Dynamic) { 12463 const localId = show?.dynamic?.localId; 12464 if (localId) mergeElementData(dataElementsDataByIds, buildSingleElementIds(localId)); 12465 } 12466 return Object.values(dataElementsDataByIds); 12467} 12468/** 12469* Add used elements IDs from a text/narration show element 12470* @param show text/narration show element 12471*/ 12472function getTextOrNarrationShowElementIds(show) { 12473 const dataElementIds = {}; 12474 if (show && Array.isArray(show)) { 12475 for (const dynamicTextAtom of show) if ((dynamicTextAtom?.content)?.localId) mergeElementData(dataElementIds, buildSingleElementIds(dynamicTextAtom.content.localId)); 12476 } 12477 return Object.values(dataElementIds); 12478} 12479function getValueFromPlaceholderSettingsFactory(content) { 12480 return function settingGetterFactory(settingKey) { 12481 return function settingGetter(phSettings) { 12482 return phSettings.contents?.[content]?.settings?.[settingKey]; 12483 }; 12484 }; 12485} 12486function setValueFromPlaceholderSettingsFactory(content) { 12487 return function settingSetterFactory(settingKey) { 12488 return function settingSetter(phSettings, setting) { 12489 return { 12490 ...phSettings, 12491 contents: { 12492 ...phSettings.contents, 12493 [content]: { 12494 ...phSettings.contents[content], 12495 settings: { 12496 ...phSettings.contents[content].settings, 12497 [settingKey]: setting 12498 } 12499 } 12500 } 12501 }; 12502 }; 12503 }; 12504} 12505var getDefaultSettingAtom = getValueFromPlaceholderSettingsFactory(DEFAULT_CONTENT); 12506var setDefaultSettingAtom = setValueFromPlaceholderSettingsFactory(DEFAULT_CONTENT); 12507var getDefaultFontSizeSetting = getDefaultSettingAtom(TextSettingKey.FontSize); 12508var getDefaultColorSetting = getDefaultSettingAtom(TextSettingKey.Color); 12509var getDefaultColorSettingByKey = (phSettings, colorSettingKey = TextSettingKey.Color) => getDefaultSettingAtom(colorSettingKey)(phSettings);
12510var getDefaultTextBackgroundColorSetting = getDefaultSettingAtom(TextSettingKey.BackgroundColor); 12511var getDefaultTextHorizontalAlignmentSetting = getDefaultSettingAtom(TextSettingKey.HorizontalAlignment); 12512var getDefaultTextVerticalAlignmentSetting = getDefaultSettingAtom(TextSettingKey.VerticalAlignment); 12513var getDefaultTextFitSetting = getDefaultSettingAtom(TextSettingKey.Fit); 12514var getDefaultTextHorizontalLinePaddingModeSetting = getDefaultSettingAtom(TextSettingKey.HorizontalLinePaddingMode); 12515var getDefaultTextStyleSetting = getDefaultSettingAtom(TextSettingKey.Style); 12516var setDefaultTextHorizontalLinePaddingModeSetting = setDefaultSettingAtom(TextSettingKey.HorizontalLinePaddingMode); 12517var getBulletIconSizeSetting = getDefaultSettingAtom(BulletSettingKey.IconSize); 12518getDefaultSettingAtom(BulletSettingKey.IconColor); 12519var setBulletIconSizeSetting = setDefaultSettingAtom(BulletSettingKey.IconSize); 12520var getAdjustmentSetting = getDefaultSettingAtom(MediaSettingKey.Adjustment); 12521var getMediaAlignmentSetting = getDefaultSettingAtom(MediaSettingKey.Alignment); 12522var getBreathingSetting = getDefaultSettingAtom(MediaSettingKey.Breathing); 12523var getSoundSetting = getDefaultSettingAtom(MediaSettingKey.Sound); 12524var getLogoOverrideSetting = getDefaultSettingAtom(MediaSettingKey.OverrideLogo); 12525var getDurationSetting = getDefaultSettingAtom(MediaSettingKey.Duration); 12526getValueFromPlaceholderSettingsFactory("text")(TextSettingKey.Color); 12527var getAvatarCropSetting = getDefaultSettingAtom(AvatarSettingsKey.Crop); 12528var getNarrationAlternativeVoiceSetting = getDefaultSettingAtom(NarrationSettingsKey.AlternativeVoice); 12529var getHiddenSetting = getDefaultSettingAtom(GlobalSettingKey.IsHidden); 12530var projectBulletTextSettings = (bullet) => ({ 12531 type: ContentType.Text, 12532 settings: { 12533 ...bullet.settings, 12534 [TextSettingKey.Color]: bullet.settings[BulletSettingKey.TextColor] 12535 } 12536}); 12537var projectBulletIconSettings = (bullet) => ({ 12538 type: ContentType.Media, 12539 settings: { 12540 ...bullet.settings, 12541 [MediaSettingKey.Color]: bullet.settings[BulletSettingKey.IconColor] 12542 } 12543}); 12544/** 12545* get the color value from colorSetting - whether it's custom color, cc or should be null. 12546* @parm colorSetting - a ColorSetting object 12547* @parm getColorByCcDofLocalId - a function that given cc dof local Id can return the color value 12548* @returns color in hex format or null 12549* */ 12550var resolveColorValue = (colorSetting, getColorByCcDofLocalId) => { 12551 if (colorSetting?.useValue && colorSetting?.value) { 12552 if (colorSetting.value.ccDofLocalId) return getColorByCcDofLocalId(colorSetting.value.ccDofLocalId); 12553 else if (colorSetting.value.customColor) return colorSetting.value.customColor; 12554 } 12555 return null; 12556};
12557var resolveBackgroundColorValue = (backgroundColorSetting, getColorByCcDofLocalId) => { 12558 if (backgroundColorSetting?.useValue && backgroundColorSetting?.value) { 12559 if (backgroundColorSetting.value.ccDofLocalId) return getColorByCcDofLocalId(backgroundColorSetting.value.ccDofLocalId); 12560 else if (backgroundColorSetting.value.customColor) return backgroundColorSetting.value.customColor; 12561 } 12562 return null; 12563}; 12564var resolveFontSizeValue = (fontSizeSetting) => { 12565 if (fontSizeSetting?.useValue && fontSizeSetting?.value) return { 12566 value: fontSizeSetting.value.fontSize.value / 100, 12567 unit: fontSizeSetting.value.fontSize.unit 12568 }; 12569 return null; 12570}; 12571var resolveTextHorizontalAlignmentValue = (horizontalAlignmentSetting) => { 12572 if (horizontalAlignmentSetting?.useValue && horizontalAlignmentSetting?.value?.horizontalAlignment) return getTextStyleHorizontalAlign(horizontalAlignmentSetting.value.horizontalAlignment); 12573 return null; 12574}; 12575var resolveTextFitValue = (textFitSetting) => { 12576 if (textFitSetting?.useValue && textFitSetting?.value?.fit) return textFitSetting?.value?.fit; 12577 return null; 12578}; 12579var resolveTextHorizontalLinePaddingModeSettingValue = (textHorizonatlLinePaddingModeSetting) => { 12580 if (textHorizonatlLinePaddingModeSetting?.useValue && textHorizonatlLinePaddingModeSetting?.value?.horizontalLinePaddingMode) return textHorizonatlLinePaddingModeSetting?.value?.horizontalLinePaddingMode; 12581 return null; 12582}; 12583var resolveTextVerticalAlignmentValue = (verticalAlignmentSetting) => { 12584 if (verticalAlignmentSetting?.useValue && verticalAlignmentSetting?.value?.verticalAlignment) return getTextStyleVerticalAlign(verticalAlignmentSetting.value.verticalAlignment); 12585 return null; 12586}; 12587var resolveAdjustmentValue = (placeholderSettings) => { 12588 const adjustmentSetting = getAdjustmentSetting(placeholderSettings); 12589 return mapAdjustmentToFit(adjustmentSetting?.useValue ? adjustmentSetting.value.mediaAdjustment : null); 12590}; 12591var resolveMediaAlignmentValue = (placeholderSettings) => { 12592 const alignmentSetting = getMediaAlignmentSetting(placeholderSettings); 12593 if (alignmentSetting?.useValue && alignmentSetting?.value) { 12594 if (alignmentSetting.value.mediaAlignment) return convertToObjectPosition(alignmentSetting.value.mediaAlignment); 12595 } 12596 return null; 12597}; 12598var MediaSettingsMapping = { 12599 [MediaSettingKey.Adjustment]: { 12600 resolveFn: resolveAdjustmentValue, 12601 elementName: "objectFit" 12602 }, 12603 [MediaSettingKey.Alignment]: { 12604 resolveFn: resolveMediaAlignmentValue, 12605 elementName: "objectPosition" 12606 } 12607}; 12608var isMediaShowEmpty = (mediaShow) => { 12609 return !mediaShow?.mediaId; 12610}; 12611var updateMediaFallbackIfNeeded = (phContent, language) => { 12612 if (isMediaShowEmpty(getLanguageValue(phContent.staticFallback, language)) && !isMediaShowEmpty(getLanguageValue(phContent?.noRules?.show, language)?.static)) { 12613 const noRulesShow = getLanguageValue(phContent.noRules.show, language); 12614 phContent.staticFallback = setLanguageValue(phContent.staticFallback, language, noRulesShow.static); 12615 } 12616}; 12617var updateBulletFallbackIconIfNeeded = (phContent, language) => { 12618 const noRulesIconStatic = getLanguageValue(phContent?.noRules?.show, language)?.iconShow?.static; 12619 const fallback = getLanguageValue(phContent.staticFallback, language); 12620 if (isMediaShowEmpty(fallback?.iconShow) && !isMediaShowEmpty(noRulesIconStatic)) phContent.staticFallback = setLanguageValue(phContent.staticFallback, language, { 12621 ...fallback, 12622 iconShow: { ...noRulesIconStatic } 12623 }); 12624}; 12625var updateBulletFallbackTextIfNeeded = (phContent, language) => { 12626 const noRulesText = getLanguageValue(phContent?.noRules?.show, language)?.textShow; 12627 const fallback = getLanguageValue(phContent.staticFallback, language); 12628 const fallbackTextIsEmpty = !fallback?.textShow?.some((atom) => !!atom.content); 12629 const noRulesTextIsEmpty = !noRulesText?.some((atom) => !!atom.content); 12630 if (fallbackTextIsEmpty && !noRulesTextIsEmpty && !isPlaceholderContentNoRulesWithPersonalization(phContent, language)) { 12631 const seededText = noRulesText.map((atom) => ({ 12632 content: atom.content, 12633 style: { ...atom.style } 12634 })); 12635 phContent.staticFallback = setLanguageValue(phContent.staticFallback, language, { 12636 ...fallback, 12637 textShow: seededText 12638 }); 12639 } 12640}; 12641var seedBulletCaseIconsFromFallbackIfNeeded = (phContent, language) => { 12642 const fallbackIcon = getLanguageValue(phContent.staticFallback, language)?.iconShow; 12643 if (isMediaShowEmpty(fallbackIcon)) return; 12644 phContent.rules.cases = phContent.rules.cases.map((ruleCase) => { 12645 const caseShow = getLanguageValue(ruleCase.show, language); 12646 const iconIsEmpty = isMediaShowEmpty(caseShow?.iconShow?.static) && !caseShow?.iconShow?.dynamic?.localId; 12647 if (!caseShow || !iconIsEmpty) return ruleCase; 12648 return { 12649 ...ruleCase, 12650 show: setLanguageValue(ruleCase.show, language, { 12651 ...caseShow, 12652 iconShow: { 12653 showType: PlaceholderShowType.Static, 12654 static: { ...fallbackIcon }, 12655 dynamic: null 12656 } 12657 }) 12658 }; 12659 }); 12660}; 12661var isPlaceholderHidden = (placeholderSettings) => { 12662 if (placeholderSettings) { 12663 const hiddenSetting = getHiddenSetting(placeholderSettings); 12664 return hiddenSetting?.useValue && hiddenSetting?.value.isHidden; 12665 } 12666 return false;
12667}; 12668var isPlaceholderOverrideLogo = (placeholderSettings) => { 12669 if (placeholderSettings) return getLogoOverrideSetting(placeholderSettings)?.useValue; 12670 return false; 12671}; 12672var resolveBreathingValue = (placeholderSettings, themeBreathingValue) => { 12673 const breathingSetting = getBreathingSetting(placeholderSettings); 12674 if (breathingSetting?.useValue) return breathingSetting.value?.breathing ?? null; 12675 else if (themeBreathingValue) return themeBreathingValue; 12676 return null; 12677}; 12678var getEmptyRichTextAtoms = () => [{ 12679 content: "", 12680 style: { 12681 bold: RichTextStyleSetting.UNSET, 12682 italic: RichTextStyleSetting.UNSET 12683 } 12684}]; 12685var createPlaceholderDefaultContentAndSettings = (params) => { 12686 const { defaultTextValue, defaultMediaValue, intentName, phType, defaultShowValue, isFlexible, additionalLanguages, onScreenTextLanguages } = params; 12687 if (phType == CommonPlaceholderType.MEDIA) { 12688 const mediaId = defaultMediaValue?.startsWith("cc-entities") ? null : defaultMediaValue; 12689 return { 12690 defaultContent: { 12691 version: 14, 12692 placeholderType: phType, 12693 useRules: false, 12694 noRules: { show: defaultShowValue ?? wrapByAllLanguages({ 12695 showType: PlaceholderShowType.Static, 12696 static: { mediaId }, 12697 dynamic: null 12698 }, onScreenTextLanguages) }, 12699 rules: { 12700 by: null, 12701 cases: [{ 12702 valueIds: [], 12703 show: wrapByAllLanguages({ 12704 showType: PlaceholderShowType.Static, 12705 static: null, 12706 dynamic: null 12707 }, onScreenTextLanguages) 12708 }] 12709 }, 12710 staticFallback: null 12711 }, 12712 defaultSettings: { 12713 version: 16, 12714 contents: { [DEFAULT_CONTENT]: buildMediaSettings(intentName) } 12715 } 12716 }; 12717 } else if (phType === CommonPlaceholderType.BUTTON) return { 12718 defaultContent: { 12719 version: 14, 12720 placeholderType: phType, 12721 useRules: false, 12722 staticFallback: wrapByAllLanguages({ 12723 useAction: "OpenUrl", 12724 actionShow: initiateButtonActionShow(getDefaultButtonShowContentV9("")) 12725 }, onScreenTextLanguages), 12726 rules: { 12727 by: null, 12728 cases: [{ 12729 valueIds: [], 12730 show: wrapByAllLanguages({ 12731 useAction: "OpenUrl", 12732 actionShow: initiateButtonActionShow(getDefaultButtonShowContentV9("")) 12733 }, onScreenTextLanguages) 12734 }] 12735 }, 12736 noRules: { show: defaultShowValue ?? wrapByAllLanguages({ 12737 useAction: "OpenUrl", 12738 actionShow: initiateButtonActionShow(getDefaultButtonShowContentV9(defaultTextValue)) 12739 }, onScreenTextLanguages) } 12740 }, 12741 defaultSettings: { 12742 version: 16, 12743 contents: { [DEFAULT_CONTENT]: buildButtonSettings() } 12744 } 12745 }; 12746 else if (phType === CommonPlaceholderType.TEXT) { 12747 const defaultTextHorizontalLinePaddingMode = calculateExplicitTextHorizontalLinePaddingMode(isFlexible, intentName); 12748 return { 12749 defaultContent: { 12750 version: 14, 12751 placeholderType: phType, 12752 useRules: false, 12753 noRules: { show: defaultShowValue ?? wrapByAllLanguages([{ 12754 content: defaultTextValue, 12755 style: { 12756 bold: RichTextStyleSetting.UNSET, 12757 italic: RichTextStyleSetting.UNSET 12758 } 12759 }], onScreenTextLanguages) }, 12760 rules: { 12761 by: null, 12762 cases: [{ 12763 valueIds: [], 12764 show: wrapByAllLanguages(getEmptyRichTextAtoms(), onScreenTextLanguages) 12765 }] 12766 }, 12767 staticFallback: wrapByAllLanguages(getEmptyRichTextAtoms(), onScreenTextLanguages) 12768 }, 12769 defaultSettings: { 12770 version: 16, 12771 contents: { [DEFAULT_CONTENT]: buildTextSettings(defaultTextHorizontalLinePaddingMode) } 12772 } 12773 }; 12774 } 12775 if (phType == CommonPlaceholderType.AVATAR) return { 12776 defaultContent: { 12777 version: 14, 12778 placeholderType: phType, 12779 useRules: false, 12780 noRules: { show: defaultShowValue ?? wrapByOriginLanguage({ 12781 showType: PlaceholderShowType.Static, 12782 static: null, 12783 dynamic: null 12784 }) }, 12785 rules: { 12786 by: null, 12787 cases: [{ 12788 valueIds: [], 12789 show: wrapByOriginLanguage({ 12790 showType: PlaceholderShowType.Static, 12791 static: null, 12792 dynamic: null 12793 }) 12794 }] 12795 }, 12796 staticFallback: null 12797 }, 12798 defaultSettings: { 12799 version: 16, 12800 contents: { [DEFAULT_CONTENT]: { 12801 type: ContentType.Avatar, 12802 settings: { [AvatarSettingsKey.Crop]: buildAvatarCropSetting() } 12803 } } 12804 } 12805 };
12806 else if (phType == CommonPlaceholderType.NARRATION) return { 12807 defaultContent: { 12808 version: 14, 12809 placeholderType: phType, 12810 useRules: false, 12811 noRules: { show: defaultShowValue ?? wrapByAllLanguages({ 12812 text: [{ content: defaultTextValue }], 12813 speed: 1 12814 }, additionalLanguages) }, 12815 rules: { 12816 by: null, 12817 cases: [{ 12818 valueIds: [], 12819 show: wrapByAllLanguages({ 12820 text: [{ content: "" }], 12821 speed: 1 12822 }, additionalLanguages) 12823 }] 12824 }, 12825 staticFallback: wrapByAllLanguages({ 12826 text: [{ content: "" }], 12827 speed: 1 12828 }, additionalLanguages) 12829 }, 12830 defaultSettings: { 12831 version: 16, 12832 contents: { [DEFAULT_CONTENT]: { 12833 type: ContentType.Narration, 12834 settings: { [NarrationSettingsKey.AlternativeVoice]: buildNarrationAlternativeVoiceSetting() } 12835 } } 12836 } 12837 }; 12838 else if (phType === CommonPlaceholderType.BULLET) { 12839 const iconMediaId = defaultMediaValue?.startsWith("cc-entities") ? null : defaultMediaValue; 12840 return { 12841 defaultContent: { 12842 version: 14, 12843 placeholderType: phType, 12844 useRules: false, 12845 noRules: { show: defaultShowValue ?? wrapByAllLanguages({ 12846 textShow: [{ 12847 content: defaultTextValue, 12848 style: { 12849 bold: RichTextStyleSetting.UNSET, 12850 italic: RichTextStyleSetting.UNSET 12851 } 12852 }], 12853 iconShow: { 12854 showType: PlaceholderShowType.Static, 12855 static: { mediaId: iconMediaId }, 12856 dynamic: null 12857 } 12858 }, onScreenTextLanguages) }, 12859 rules: { 12860 by: null, 12861 cases: [{ 12862 valueIds: [], 12863 show: wrapByAllLanguages({ 12864 textShow: getEmptyRichTextAtoms(), 12865 iconShow: { 12866 showType: PlaceholderShowType.Static, 12867 static: null, 12868 dynamic: null 12869 } 12870 }, onScreenTextLanguages) 12871 }] 12872 }, 12873 staticFallback: wrapByAllLanguages({ 12874 textShow: getEmptyRichTextAtoms(), 12875 iconShow: { mediaId: "" } 12876 }, onScreenTextLanguages) 12877 }, 12878 defaultSettings: { 12879 version: 16, 12880 contents: { [DEFAULT_CONTENT]: buildBulletSettings(intentName) } 12881 } 12882 }; 12883 } 12884}; 12885var calculateExplicitTextHorizontalLinePaddingMode = (isFlexible, intentName) => { 12886 const isExcluded = intentName === PlaceholderIntentName.TextOverlay; 12887 return isFlexible && !isExcluded ? TextHorizontalLinePaddingMode.Auto : TextHorizontalLinePaddingMode.On; 12888}; 12889var getNewCase = (placeholderContent, additionalLanguages, onScreenTextLanguages) => { 12890 switch (placeholderContent.placeholderType) { 12891 case CommonPlaceholderType.TEXT: return { 12892 valueIds: [], 12893 show: wrapByAllLanguages(getEmptyRichTextAtoms(), onScreenTextLanguages) 12894 }; 12895 case CommonPlaceholderType.NARRATION: return { 12896 valueIds: [], 12897 show: wrapByAllLanguages({ 12898 text: [{ content: "" }], 12899 speed: 1 12900 }, additionalLanguages) 12901 }; 12902 case CommonPlaceholderType.MEDIA: return { 12903 valueIds: [], 12904 show: wrapByAllLanguages({ 12905 showType: PlaceholderShowType.Static, 12906 static: null, 12907 dynamic: null 12908 }, onScreenTextLanguages) 12909 }; 12910 case CommonPlaceholderType.AVATAR: return { 12911 valueIds: [], 12912 show: wrapByOriginLanguage({ 12913 showType: PlaceholderShowType.Static, 12914 static: null, 12915 dynamic: null 12916 }) 12917 }; 12918 case CommonPlaceholderType.BUTTON: return { 12919 valueIds: [], 12920 show: wrapByAllLanguages({ 12921 useAction: "OpenUrl", 12922 actionShow: initiateButtonActionShow(getDefaultButtonShowContentV9("")) 12923 }, onScreenTextLanguages) 12924 }; 12925 case CommonPlaceholderType.BULLET: { 12926 const staticFallback = placeholderContent.staticFallback; 12927 return { 12928 valueIds: [], 12929 show: buildByAllLanguages((language) => { 12930 const fallbackIcon = getLanguageValue(staticFallback, language)?.iconShow; 12931 return { 12932 textShow: getEmptyRichTextAtoms(), 12933 iconShow: { 12934 showType: PlaceholderShowType.Static, 12935 static: fallbackIcon ? { ...fallbackIcon } : null, 12936 dynamic: null 12937 } 12938 }; 12939 }, onScreenTextLanguages) 12940 }; 12941 } 12942 } 12943}; 12944var getPlaceholderContentDynamicInfo = (placeholderContent, placeholderType, language) => { 12945 if (placeholderContent?.useRules) { 12946 const byAudienceDataField = placeholderContent?.rules?.by; 12947 if (byAudienceDataField == null) return { isPersonalized: false }; 12948 const byAudienceVariationNum = countNonEmptyPlaceholderContentDynamicRules(placeholderContent); 12949 return { 12950 isPersonalized: byAudienceVariationNum > 0, 12951 byAudienceDataField, 12952 byAudienceVariationNum 12953 }; 12954 } 12955 switch (placeholderType) {
12956 case CommonPlaceholderType.AVATAR: 12957 case CommonPlaceholderType.MEDIA: { 12958 const mediaPlaceholderContent = placeholderContent; 12959 const dynamicDataField = getLanguageValue(mediaPlaceholderContent?.noRules?.show, language)?.dynamic; 12960 return { 12961 isPersonalized: getLanguageValue(mediaPlaceholderContent?.noRules?.show, language)?.showType === PlaceholderShowType.Dynamic && dynamicDataField != null, 12962 dynamicDataField 12963 }; 12964 } 12965 case CommonPlaceholderType.BUTTON: return { isPersonalized: isButtonPlaceholderContentNoRulesWithPersonalization(placeholderContent, language) }; 12966 default: { 12967 const textOrNarrationPlaceholderContent = placeholderContent; 12968 return { 12969 isPersonalized: isPlaceholderContentNoRulesWithPersonalization(textOrNarrationPlaceholderContent), 12970 dynamicDataField: getPrimaryPlaceholderText(placeholderType, textOrNarrationPlaceholderContent?.noRules?.show, language)?.find((atom) => (atom?.content)?.localId)?.content 12971 }; 12972 } 12973 } 12974}; 12975function countNonEmptyPlaceholderContentDynamicRules(placeholderContent) { 12976 return (placeholderContent?.rules.cases).filter((ruleCase) => ruleCase.valueIds.length > 0).length; 12977} 12978function isPlaceholderContentNoRulesWithPersonalization(placeholderContent, language = ORIGIN_LANGUAGE) { 12979 return !!getPrimaryPlaceholderText(placeholderContent?.placeholderType, placeholderContent?.noRules?.show, language)?.some((atom) => !!atom.content?.localId); 12980} 12981function isButtonPlaceholderContentNoRulesWithPersonalization(placeholderContent, language = ORIGIN_LANGUAGE) { 12982 const buttonShow = getLanguageValue(placeholderContent?.noRules?.show, language); 12983 if (!buttonShow) return false; 12984 const currentAction = buttonShow.useAction; 12985 const actionShowContent = buttonShow.actionShow[currentAction]; 12986 const hasLabelPersonalization = !!(actionShowContent[ButtonShowContentItemElement.Text]?.content)?.some((atom) => !!atom.content?.localId); 12987 const hasUrlPersonalization = !!(actionShowContent[ButtonShowContentItemElement.URL]?.content)?.some((atom) => !!atom.content?.localId); 12988 return hasLabelPersonalization || hasUrlPersonalization; 12989} 12990var isRichTextFormattingApplied = (richTextAtom) => { 12991 return richTextAtom.style.bold !== RichTextStyleSetting.UNSET || richTextAtom.style.italic !== RichTextStyleSetting.UNSET; 12992}; 12993var someAtomsRichTextFormattingApplied = (richTextAtoms) => { 12994 return (richTextAtoms || []).some(isRichTextFormattingApplied); 12995}; 12996var isPlaceholderValueNotEmpty = (value) => { 12997 return (value || []).some((atom) => !!atom.content); 12998}; 12999function getAvatarObjectViewBox(placeholder, avatar) { 13000 if (!placeholder.placeholderSettings) return null; 13001 switch (getAvatarCropSetting(placeholder.placeholderSettings).value.crop) { 13002 case AvatarCropPreset.FULL_BODY: return { 13003 top: { 13004 value: avatar.fullBodyCrop.top, 13005 unit: PositionUnit.Pixel 13006 }, 13007 right: { 13008 value: avatar.fullBodyCrop.right, 13009 unit: PositionUnit.Pixel 13010 }, 13011 bottom: { 13012 value: avatar.fullBodyCrop.bottom, 13013 unit: PositionUnit.Pixel 13014 }, 13015 left: { 13016 value: avatar.fullBodyCrop.left, 13017 unit: PositionUnit.Pixel 13018 } 13019 }; 13020 case AvatarCropPreset.CLOSE_UP: return { 13021 top: { 13022 value: avatar.closeUpCrop.top, 13023 unit: PositionUnit.Pixel 13024 }, 13025 right: { 13026 value: avatar.closeUpCrop.right, 13027 unit: PositionUnit.Pixel 13028 }, 13029 bottom: { 13030 value: avatar.closeUpCrop.bottom, 13031 unit: PositionUnit.Pixel 13032 }, 13033 left: { 13034 value: avatar.closeUpCrop.left, 13035 unit: PositionUnit.Pixel 13036 } 13037 }; 13038 default: return null; 13039 } 13040} 13041var AVATAR_OBJECT_FIT = ObjectFit.Contain; 13042var AVATAR_OBJECT_POSITION = "center center"; 13043//#endregion 13044//#region common/editorUtils.ts 13045init_moment(); 13046var import_dist$5 = require_dist$9(); 13047var buildHiddenSetting = () => { 13048 return { 13049 useValue: true, 13050 value: { isHidden: false } 13051 }; 13052}; 13053var buildColorSetting = () => { 13054 return { 13055 useValue: false, 13056 value: { 13057 customColor: null, 13058 ccDofLocalId: null 13059 } 13060 }; 13061}; 13062var buildFontSizeSetting = () => { 13063 return { 13064 useValue: false, 13065 value: { fontSize: { 13066 value: 100, 13067 unit: FontSizeUnit.EM 13068 } } 13069 }; 13070}; 13071var buildTextHorizontalAlignmentSetting = () => { 13072 return { 13073 useValue: false, 13074 value: { horizontalAlignment: HorizontalAlignment.Center } 13075 }; 13076}; 13077var buildTextVerticalAlignmentSetting = () => { 13078 return { 13079 useValue: false, 13080 value: { verticalAlignment: VerticalAlignment.Center } 13081 }; 13082}; 13083var buildTextStyleSetting = () => { 13084 return { 13085 useValue: false, 13086 value: { style: "" } 13087 }; 13088}; 13089var buildTextFitSetting = () => { 13090 return { 13091 useValue: false, 13092 value: { fit: TextFit.ResizeFont } 13093 }; 13094}; 13095var buildTextHorizontalLinePaddingModeSetting = (horizontalLinePaddingMode) => { 13096 return { 13097 useValue: horizontalLinePaddingMode != TextHorizontalLinePaddingMode.On, 13098 value: { horizontalLinePaddingMode } 13099 }; 13100}; 13101var buildBreathingSetting = (value) => { 13102 return { 13103 useValue: value !== null, 13104 value 13105 }; 13106}; 13107var buildMediaSoundSetting = (useValue = true, value = 100) => { 13108 return { 13109 useValue, 13110 value: { 13111 value, 13112 unit: SoundUnit.Percent 13113 } 13114 }; 13115}; 13116var buildOverrideLogoSetting = () => { 13117 return { 13118 useValue: false, 13119 value: { initialized: false } 13120 }; 13121}; 13122var buildDurationSetting = (useValue, duration) => { 13123 return { 13124 useValue, 13125 value: { duration } 13126 }; 13127}; 13128var buildMediaSettings = (intentName) => { 13129 const mediaAdjustment = [ 13130 PlaceholderIntentName.Logo, 13131 PlaceholderIntentName.Icon, 13132 PlaceholderIntentName.HorizontalBullet, 13133 PlaceholderIntentName.VerticalBullet 13134 ].includes(intentName) ? Adjustment.ScaleToFit : Adjustment.ScaleToFill; 13135 return { 13136 type: ContentType.Media, 13137 settings: { 13138 [GlobalSettingKey.IsHidden]: buildHiddenSetting(), 13139 [MediaSettingKey.Adjustment]: { 13140 useValue: true, 13141 value: { mediaAdjustment } 13142 }, 13143 [MediaSettingKey.Alignment]: { 13144 useValue: false, 13145 value: { mediaAlignment: { 13146 vertical: VerticalAlignment.Center, 13147 horizontal: HorizontalAlignment.Center 13148 } } 13149 }, 13150 [MediaSettingKey.Color]: buildColorSetting(), 13151 [MediaSettingKey.Breathing]: getDefaultBreathingValue(intentName), 13152 [MediaSettingKey.Duration]: getDefaultDurationValue(), 13153 [MediaSettingKey.Sound]: getDefaultSoundValue(), 13154 [MediaSettingKey.OverrideLogo]: getDefaultOverrideLogoValue() 13155 } 13156 }; 13157}; 13158var buildButtonSettings = () => { 13159 return { 13160 type: ContentType.Button, 13161 settings: { 13162 [GlobalSettingKey.IsHidden]: buildHiddenSetting(), 13163 [TextSettingKey.FontSize]: buildFontSizeSetting() 13164 } 13165 }; 13166}; 13167var getBulletOrientationFromIntent = (intentName) => intentName === PlaceholderIntentName.VerticalBullet ? BulletOrientation.Vertical : BulletOrientation.Horizontal; 13168var getDefaultBulletIconSizeFraction = (intentName) => { 13169 const orientation = getBulletOrientationFromIntent(intentName);
13170 return BULLET_ICON_SIZE_FRACTION_BY_ORIENTATION[orientation][DEFAULT_BULLET_ICON_SIZE_BY_ORIENTATION[orientation]]; 13171}; 13172var getBulletIconSizeLetterForFraction = (iconSize, intentName) => { 13173 const fractionsByLetter = BULLET_ICON_SIZE_FRACTION_BY_ORIENTATION[getBulletOrientationFromIntent(intentName)]; 13174 return Object.keys(fractionsByLetter).find((letter) => fractionsByLetter[letter] === iconSize) ?? null; 13175}; 13176var getBulletIconSizeFractionRoundedDown = (copiedIconFraction, orientation) => { 13177 const fractionsByLetter = BULLET_ICON_SIZE_FRACTION_BY_ORIENTATION[orientation]; 13178 for (const letter of [ 13179 BulletIconSize.XL, 13180 BulletIconSize.L, 13181 BulletIconSize.M, 13182 BulletIconSize.S 13183 ]) if (fractionsByLetter[letter] <= copiedIconFraction) return fractionsByLetter[letter]; 13184 return fractionsByLetter[BulletIconSize.S]; 13185}; 13186var buildBulletIconSizeSetting = (intentName) => { 13187 return { 13188 useValue: true, 13189 value: { iconSize: getDefaultBulletIconSizeFraction(intentName) } 13190 }; 13191}; 13192var buildBulletSettings = (intentName) => { 13193 const { [TextSettingKey.Color]: textColor, [GlobalSettingKey.IsHidden]: _textHidden, ...textRest } = buildTextSettings(calculateExplicitTextHorizontalLinePaddingMode(true, intentName)).settings; 13194 const { [MediaSettingKey.Color]: iconColor, [GlobalSettingKey.IsHidden]: _iconHidden, ...mediaRest } = buildMediaSettings(intentName).settings; 13195 return { 13196 type: ContentType.Bullet, 13197 settings: { 13198 [GlobalSettingKey.IsHidden]: buildHiddenSetting(), 13199 [BulletSettingKey.IconSize]: buildBulletIconSizeSetting(intentName), 13200 [BulletSettingKey.TextColor]: textColor, 13201 [BulletSettingKey.IconColor]: iconColor, 13202 ...textRest, 13203 ...mediaRest 13204 } 13205 }; 13206}; 13207var buildTextSettings = (horizontalLinePaddingMode) => { 13208 return { 13209 type: ContentType.Text, 13210 settings: { 13211 [TextSettingKey.Color]: buildColorSetting(), 13212 [TextSettingKey.FontSize]: buildFontSizeSetting(), 13213 [TextSettingKey.BackgroundColor]: buildColorSetting(), 13214 [TextSettingKey.HorizontalAlignment]: buildTextHorizontalAlignmentSetting(), 13215 [TextSettingKey.VerticalAlignment]: buildTextVerticalAlignmentSetting(), 13216 [GlobalSettingKey.IsHidden]: buildHiddenSetting(), 13217 [TextSettingKey.Style]: buildTextStyleSetting(), 13218 [TextSettingKey.Fit]: buildTextFitSetting(), 13219 [TextSettingKey.HorizontalLinePaddingMode]: buildTextHorizontalLinePaddingModeSetting(horizontalLinePaddingMode) 13220 } 13221 }; 13222}; 13223var buildAvatarCropSetting = () => { 13224 return { 13225 useValue: true, 13226 value: { crop: AvatarCropPreset.FULL_BODY } 13227 }; 13228}; 13229var buildNarrationAlternativeVoiceSetting = () => { 13230 return { 13231 useValue: false, 13232 value: null 13233 }; 13234}; 13235var getDefaultButtonShowContentV9 = (text) => { 13236 return { 13237 [ButtonShowContentItemElement.Text]: { 13238 content: [{ 13239 content: text, 13240 style: { 13241 bold: RichTextStyleSetting.UNSET, 13242 italic: RichTextStyleSetting.UNSET 13243 } 13244 }], 13245 isContentSameAsButtonText: true 13246 }, 13247 [ButtonShowContentItemElement.URL]: { 13248 content: [{ content: "" }], 13249 isContentSameAsButtonText: false 13250 }, 13251 [ButtonShowContentItemElement.Report]: { 13252 content: [{ content: "" }], 13253 isContentSameAsButtonText: true 13254 } 13255 }; 13256}; 13257var initiateButtonActionShow = (defaultValue) => { 13258 const buttonActions = {}; 13259 Object.keys(ButtonActions).forEach((key) => { 13260 buttonActions[key] = defaultValue; 13261 }); 13262 return buttonActions; 13263}; 13264var generateEditorProjectId = (programName, accountName, source, programId) => { 13265 return `${source}/${replaceSpecialChar(accountName, "_")}/${replaceSpecialChar(programName, "_")}/${programId}`; 13266}; 13267var isEditorAccountLibraryProgram = (programName) => { 13268 return programName === ACCOUNT_LIBRARY_PROGRAM_NAME; 13269}; 13270var ANIMATOR_TEST_ACCOUNT = "0015a00002oTaPWAA0"; 13271var isAnimatorTestAccount = (accountId) => { 13272 return accountId === ANIMATOR_TEST_ACCOUNT; 13273}; 13274var ANIMATOR_TEST_VSB_NAME = "TestLayout.vsb"; 13275var SYSTEM_ELEMENT_ORIGIN = "system"; 13276var getDuplicateName = (sourceName, usedNames) => { 13277 const baseName = (sourceName ?? "").replace(/Copy( \d+)? of (?!:.+)/g, ""); 13278 const lowerCaseUsedNames = usedNames.map((name) => name.toLowerCase()); 13279 let index = 1; 13280 let duplicatedName = `Copy ${index} of ${baseName}`; 13281 while (lowerCaseUsedNames.includes(duplicatedName.toLowerCase())) { 13282 index++; 13283 duplicatedName = `Copy ${index} of ${baseName}`; 13284 } 13285 return duplicatedName; 13286}; 13287var getDuplicateNameBySuffix = (sourceName, usedNames) => { 13288 let duplicatedName = `${sourceName}`; 13289 let index = 1; 13290 while (usedNames.includes(duplicatedName.toLowerCase())) duplicatedName = `${sourceName} ${++index}`; 13291 return duplicatedName; 13292}; 13293var MAX_FILENAME_LENGTH = 180; 13294function createDownloadedVideoFileName(programName, viewerProfileName, allScenesSelected, selectedSceneNumbers, fileFormat, includeExtension, hasAdditionalLanguages, sskyVideoLanguage) { 13295 const fullName = viewerProfileName ? `${programName}_${viewerProfileName}` : programName; 13296 const fileExtension = `.${fileFormat}`; 13297 let sceneSuffix = ""; 13298 if (!allScenesSelected) { 13299 const sceneNumbers = selectedSceneNumbers.join("_");
13300 const suffixResult = selectedSceneNumbers?.length > 3 ? `_Scenes${sceneNumbers}_etc` : `_Scenes${sceneNumbers}`; 13301 sceneSuffix += suffixResult; 13302 } 13303 const videoLanguageSuffix = hasAdditionalLanguages ? `-${(0, import_dist$5.getLanguage)(sskyVideoLanguage)?.language ?? ""}` : ""; 13304 return fullName.slice(0, MAX_FILENAME_LENGTH - sceneSuffix.length - fileExtension.length) + sceneSuffix + videoLanguageSuffix + (includeExtension ? fileExtension : ""); 13305} 13306var getTranscriptFormattedDate = (date) => { 13307 return hooks(date).format("MMM D YYYY, hh:mm A"); 13308}; 13309//#endregion 13310//#region client/logic/common/convertGqlEntityToWireframesUtils.ts 13311function sortArrayByRepresentativeFieldArray(arrToSort, representativeField, arrToSortBy) { 13312 let sortedArray = []; 13313 const arrayToSortAsObject = convertArrayOfObjectsToObject(arrToSort, representativeField); 13314 (arrToSortBy || []).forEach((id) => { 13315 if (arrayToSortAsObject[id]) sortedArray.push(arrayToSortAsObject[id]); 13316 }); 13317 return sortedArray; 13318} 13319var buildWireframesAnalyticsOrderFromGql = (gqlProgram) => { 13320 return gqlProgram.customAnalyticsOrder; 13321}; 13322var buildWireframesAnalyticFieldsFromGql = (gqlProgram) => { 13323 return gqlProgram.customAnalyticFields.reduce((acc, field) => { 13324 acc[field.id] = buildCustomAnalyticFieldFromGql(field); 13325 return acc; 13326 }, {}); 13327}; 13328var buildWireframesStoryFromGqlStory = (gqlStory, isEditor) => { 13329 return { 13330 id: getIdFromGqlId(gqlStory.id), 13331 graphQLId: gqlStory.id, 13332 graphQLUpdated: gqlStory.updated, 13333 name: gqlStory.name, 13334 description: gqlStory.description, 13335 activateCaching: gqlStory.activateCaching, 13336 initialDecisionPointId: isEditor ? void 0 : getIdFromGqlId(gqlStory.initialDecisionPoint.id), 13337 backgroundAssetType: convertBackgroundAssetTypeReverse(gqlStory.backgroundAssetType), 13338 narrator: gqlStory.narratorName, 13339 displaySceneOrder: gqlStory.displaySceneOrder.map(getIdFromGqlId), 13340 numberOfProducts: gqlStory.numberOfProducts, 13341 durationOptions: gqlStory.durationOptions, 13342 ratioAndQualityOptions: gqlStory.ratioAndQualityOptions?.map(convertStoryRationAndQualityOptionsTypeReverse) 13343 }; 13344}; 13345var buildWireframesScenePartsFromGql = (programVersionNarrationsVersion, gqlScene) => { 13346 return sortArrayByRepresentativeFieldArray(gqlScene.sceneParts, "id", gqlScene.scenePartOrder).map((gqlScenePart) => buildWireframesScenePartFromGql(programVersionNarrationsVersion, gqlScenePart)); 13347}; 13348var buildWireframesScenePartFromGql = (programVersionNarrationsVersion, gqlScenePart) => { 13349 return { 13350 scenePart: getIdFromGqlId(gqlScenePart.id), 13351 graphQLId: gqlScenePart.id, 13352 graphQLUpdated: gqlScenePart.updated, 13353 storyboardFrameThumbnailLocation: gqlScenePart.thumbnailLocation, 13354 NarrationParts: programVersionNarrationsVersion >
13354 0 ? buildWireframesNarrationsPartFromGql(gqlScenePart.narrations, gqlScenePart.narrationPartOrder) : buildWireframesLegacyNarrationsPartFromGql(gqlScenePart), 13355 placeholders: gqlScenePart.placeholders.map(buildWireframesPlaceholderFromGql), 13356 groups: gqlScenePart.placeholderGroups.map(buildWireframesGroupFromGql), 13357 parameters: gqlScenePart.animationGuidelines.map(buildWireframesParametersFromGql), 13358 prioritizedLists: gqlScenePart.prioritizedLists.map(buildWireframesPrioritizedListFromGql) 13359 }; 13360}; 13361var buildCustomAnalyticFieldFromGql = (gqlCustomAnalyticField) => { 13362 return { 13363 id: gqlCustomAnalyticField.id, 13364 name: gqlCustomAnalyticField.name, 13365 data: gqlCustomAnalyticField.logic, 13366 graphQLUpdated: gqlCustomAnalyticField.updated 13367 }; 13368}; 13369var buildWireframesSceneFromGql = (programVersionNarrationsVersion, gqlScene) => { 13370 return { 13371 id: getIdFromGqlId(gqlScene.id), 13372 graphQLId: gqlScene.id, 13373 graphQLUpdated: gqlScene.updated, 13374 name: gqlScene.name, 13375 creationTime: new Date(gqlScene.created).getTime().toString(), 13376 sceneParts: buildWireframesScenePartsFromGql(programVersionNarrationsVersion, gqlScene) 13377 }; 13378}; 13379var buildProgramFromGql = (gqlProgram) => { 13380 return { 13381 accountId: gqlProgram.accountId, 13382 projectName: gqlProgram.legacyBuilderProgramId || gqlProgram.id, 13383 graphQLId: gqlProgram.id, 13384 graphQLUpdated: gqlProgram.updated, 13385 graphQLBuilderDraftId: gqlProgram.programVersion.id, 13386 programId: gqlProgram.saleForceId, 13387 displayName: gqlProgram.name, 13388 description: gqlProgram.description, 13389 isLegacy: gqlProgram.isLegacy, 13390 programType: convertProgramTypeReverse(gqlProgram.programVersion.programType), 13391 creativeVersion: gqlProgram.programVersion.creativeVersion, 13392 RFR: gqlProgram.programVersion.rfr, 13393 RFRUpdateTimestamp: new Date(gqlProgram.programVersion.rfrUpdateTime).getTime(), 13394 creativeDDE: gqlProgram.programVersion.creativeDfde, 13395 creativeNameLabel: gqlProgram.programVersion.creativeNameLabel, 13396 narrationsVersion: gqlProgram.programVersion.narrationsVersion, 13397 storiesVersion: 1, 13398 pii: Boolean(gqlProgram.pii), 13399 editorDataConnectorEnabled: Boolean(gqlProgram.programVersion.editorDataConnectorEnabled), 13400 editorDataConnectorType: gqlProgram.programVersion.editorDataConnectorType, 13401 chapteringEnabled: Boolean(gqlProgram.programVersion.chapteringEnabled), 13402 publishTarget: gqlProgram.publishTarget 13403 }; 13404}; 13405var buildWireframesFromGql = (gqlProgram) => { 13406 const gqlProgramVersion = gqlProgram.programVersion; 13407 let gqlScenes = gqlProgramVersion.scenes.reduce((acc, scene) => { 13408 const sceneId = getIdFromGqlId(scene.id); 13409 acc[sceneId] = buildWireframesSceneFromGql(gqlProgramVersion.narrationsVersion, scene); 13410 return acc; 13411 }, {}); 13412 gqlScenes[LogicContainers.Master] = initMasterObj(); 13413 gqlScenes[LogicContainers.Master].sceneParts[0] = initMasterDataObj(); 13414 if (gqlProgramVersion.masterAnimationGuidelines.length > 0) gqlScenes[LogicContainers.Master].sceneParts[0] = { 13415 parameters: gqlProgramVersion.masterAnimationGuidelines.map(buildWireframesMasterDataFromGql), 13416 placeholders: [] 13417 }; 13418 let gqlStories = gqlProgramVersion.stories.reduce((acc, story) => { 13419 const storyId = getIdFromGqlId(story.id); 13420 acc[storyId] = buildWireframesStoryFromGqlStory(story, gqlProgram.isEditor); 13421 return acc; 13422 }, {}); 13423 return { 13424 graphQLProgramVersionId: gqlProgramVersion.id, 13425 scenes: gqlScenes, 13426 stories: gqlStories, 13427 storiesVersion: 1, 13428 customAnalyticsOrder: buildWireframesAnalyticsOrderFromGql(gqlProgram), 13429 customAnalyticFields: buildWireframesAnalyticFieldsFromGql(gqlProgram), 13430 narrationsVersion: gqlProgramVersion.narrationsVersion, 13431 creativeVersion: gqlProgramVersion.creativeVersion, 13432 creativeDDE: gqlProgramVersion.creativeDfde, 13433 creativeNameLabel: gqlProgramVersion.creativeNameLabel, 13434 programRFR: gqlProgramVersion.rfr, 13435 programRFRTimestamp: new Date(gqlProgramVersion.rfrUpdateTime).getTime(), 13436 transition: gqlProgramVersion.transition, 13437 graphQLParentProgramVersionId: gqlProgramVersion.parent1ProgramVersion?.id 13438 }; 13439}; 13440var getIdFromGqlId = (gqlId) => { 13441 return gqlId?.split("|").pop() ?? ""; 13442}; 13443var buildSlotsFromGql = (prioritizedList) => { 13444 if (prioritizedList.placeholders.length > 0) return prioritizedList.placeholders.map(buildWireframesPlaceholderFromGql); 13445 if (prioritizedList.groups.length > 0) return prioritizedList.groups.map(buildWireframesGroupFromGql); 13446 return []; 13447}; 13448var buildWireframesPlaceholderFromGql = (gqlPlaceholder) => { 13449 return { 13450 x: gqlPlaceholder.x === null ? void 0 : gqlPlaceholder.x, 13451 y: gqlPlaceholder.y === null ? void 0 : gqlPlaceholder.y, 13452 height: gqlPlaceholder.height === null ? void 0 : gqlPlaceholder.height, 13453 width: gqlPlaceholder.width === null ? void 0 : gqlPlaceholder.width, 13454 type: convertPlaceholderTypeReverse(gqlPlaceholder.type), 13455 name: gqlPlaceholder.logic.name, 13456 graphQLId: gqlPlaceholder.id, 13457 graphQLUpdated: gqlPlaceholder.updated 13458 }; 13459}; 13460var buildWireframesParametersFromGql = (gqlAnimationGuideline) => { 13461 return { 13462 type: convertAnimationGuidelineTypeReverse(gqlAnimationGuideline.type), 13463 name: gqlAnimationGuideline.logic.name, 13464 graphQLId: gqlAnimationGuideline.id, 13465 graphQLUpdated: gqlAnimationGuideline.updated 13466 }; 13467}; 13468var buildWireframesMasterDataFromGql = (gqlMasterAnimationGuideline) => { 13469 return { 13470 type: convertAnimationGuidelineTypeReverse(gqlMasterAnimationGuideline.type), 13471 name: gqlMasterAnimationGuideline.name, 13472 graphQLId: gqlMasterAnimationGuideline.id, 13473 graphQLUpdated: gqlMasterAnimationGuideline.updated 13474 }; 13475}; 13476var buildWireframesNarrationsPartFromGql = (gqlNarrations, narrationPartOrder) => { 13477 return sortArrayByRepresentativeFieldArray(gqlNarrations, "id", narrationPartOrder).map(buildWireframesNarrationPartFromGql); 13478}; 13479var buildWireframesNarrationPartFromGql = (gqlNarration) => { 13480 return { 13481 id: gqlNarration.id, 13482 graphQLId: gqlNarration.id, 13483 graphQLUpdated: gqlNarration.updated, 13484 lastUsedRecordingFileName: gqlNarration.lastUsedRecordingFileNumber || 0, 13485 key: gqlNarration.dtaasPrefixKey 13486 }; 13487}; 13488var buildWireframesLegacyNarrationsPartFromGql = (gqlScenePart) => { 13489 return gqlScenePart.oldNarrationData; 13490}; 13491var buildWireframesGroupFromGql = (group) => { 13492 return { 13493 id: getIdFromGqlId(group.logic.id), 13494 graphQLId: group.id, 13495 graphQLUpdated: group.updated, 13496 name: group.logic.name, 13497 placeholders: group.placeholders.map(buildWireframesPlaceholderFromGql) 13498 }; 13499}; 13500var buildWireframesPrioritizedListFromGql = (gqlPrioritizedList) => { 13501 return { 13502 id: getIdFromGqlId(gqlPrioritizedList.logic.id), 13503 graphQLId: gqlPrioritizedList.id, 13504 graphQLUpdated: gqlPrioritizedList.updated, 13505 name: gqlPrioritizedList.logic.name, 13506 slots: buildSlotsFromGql(gqlPrioritizedList) 13507 }; 13508}; 13509var buildDataElementsFromGql = (gqlProgram) => { 13510 let gqlDataElements = []; 13511 const gqlDerivedElements = gqlProgram.programVersion.derivedDataElements.map((de) => { 13512 return { 13513 id: getIdFromGqlId(de.id), 13514 graphQLId: de.id, 13515 graphQLUpdated: de.updated, 13516 compatibilityVersion: .3, 13517 updatedTime: new Date(de.updated).valueOf(), 13518 displayName: de.name, 13519 origin: DataElementOrigins.Derived, 13520 description: de.description, 13521 type: convertDataElementTypeReverse(de.dataType), 13522 tags: de.pii ? [TagNames.PII] : [] 13523 }; 13524 }); 13525 gqlDataElements.push(...gqlDerivedElements); 13526 const gqlCreativeElements = gqlProgram.programVersion.creativeDataElements.map((de) => { 13527 return { 13528 id: getIdFromGqlId(de.id), 13529 graphQLId: de.id, 13530 graphQLUpdated: de.updated, 13531 compatibilityVersion: .3, 13532 updatedTime: new Date(de.updated).valueOf(), 13533 displayName: de.name, 13534 origin: DataElementOrigins.Creative, 13535 description: de.description, 13536 type: convertDataElementTypeReverse(de.dataType), 13537 tags: de.pii ? [TagNames.PII] : [], 13538 valueSet: de.valueSet, 13539 useValueSet: de.useValueSet, 13540 assignedStories: de.stories.map((s) => getIdFromGqlId(s.id)), 13541 assignedToAllStories: de.assignedToAllStories 13542 }; 13543 }); 13544 gqlDataElements.push(...gqlCreativeElements); 13545 const gqlFeedElements = gqlProgram.programVersion.feedDataElements.map((de) => { 13546 return { 13547 id: getIdFromGqlId(de.id), 13548 graphQLId: de.id, 13549 graphQLUpdated: de.updated, 13550 compatibilityVersion: .3, 13551 updatedTime: new Date(de.updated).valueOf(), 13552 displayName: de.name, 13553 origin: DataElementOrigins.Feed, 13554 description: de.description, 13555 type: convertDataElementTypeReverse(de.dataType), 13556 tags: de.pii ? [TagNames.PII] : [], 13557 valueSet: de.valueSet, 13558 useValueSet: de.useValueSet, 13559 status: convertDataElementStatusReverse(de.status) 13560 }; 13561 }); 13562 gqlDataElements.push(...gqlFeedElements); 13563 gqlDataElements.push(...getAllSystemDataElements(gqlProgram.programVersion?.programType, isEditorAccountLibraryProgram(gqlProgram.name))); 13564 return gqlDataElements; 13565}; 13566var buildMasterLogicFromGql = (gqlProgram) => { 13567 let loadedLogicItems = {};
13568 gqlProgram.programVersion.masterAnimationGuidelines.forEach((g) => { 13569 if (g.logic) loadedLogicItems[g.name] = g.logic; 13570 }); 13571 return loadedLogicItems; 13572}; 13573var buildWireframesNarrationFromGql = (narr) => { 13574 return { 13575 id: narr.id, 13576 dbNarration: { 13577 graphQLId: narr.id, 13578 graphQLUpdated: narr.updated, 13579 structure: { 13580 dimensionData: narr.dimensionData, 13581 mergeData: narr.mergeData, 13582 representativeKey: narr.representativeKey, 13583 creativeOverride: narr.supportsCreativeDataElementOverride 13584 }, 13585 variationData: narr.narrationVariations.reduce((varAcc, variation) => { 13586 varAcc[variation.variationKey] = { 13587 graphQLId: variation.id, 13588 graphQLUpdated: variation.updated, 13589 text: variation.sentence, 13590 muted: variation.muted, 13591 comment: variation.note, 13592 overrideId: variation.overridingCreativeDataElement && getIdFromGqlId(variation.overridingCreativeDataElement.id) 13593 }; 13594 return varAcc; 13595 }, {}) 13596 } 13597 }; 13598}; 13599var buildWireframesNarrationsFromGql = (gqlProgram, compareGqlToDynamo, dynamoLoadedNarrations, loadNarrationIdsMap) => { 13600 const gqlToDynamoIdMap = compareGqlToDynamo ? dynamoLoadedNarrations.reduce((acc, narr) => { 13601 let graphQLId = `${loadNarrationIdsMap[narr.id]}|${narr.dbNarration?.postgresNarrationId || narr.id}`; 13602 acc[graphQLId] = narr.id; 13603 return acc; 13604 }, {}) : {}; 13605 return gqlProgram.programVersion.scenes.reduce((acc, scene) => { 13606 scene.sceneParts.forEach((part) => { 13607 part.narrations.forEach((narr) => { 13608 if (!compareGqlToDynamo || gqlToDynamoIdMap[narr.id]) { 13609 let convertedNarration = buildWireframesNarrationFromGql(narr); 13610 if (compareGqlToDynamo) convertedNarration.id = gqlToDynamoIdMap[narr.id]; 13611 acc.push(convertedNarration); 13612 } 13613 }); 13614 }); 13615 return acc; 13616 }, []); 13617}; 13618var buildDerivedLogicFromGql = (gqlProgram) => { 13619 return gqlProgram.programVersion.derivedDataElements.reduce((acc, de) => { 13620 if (de.logic) acc[getIdFromGqlId(de.id)] = de.logic; 13621 return acc; 13622 }, {}); 13623}; 13624var buildAnalyticsLogicFromGql = (gqlProgram) => { 13625 return gqlProgram.customAnalyticFields.reduce((logicItems, a) => { 13626 logicItems[a.id] = a.logic; 13627 return logicItems; 13628 }, {}); 13629}; 13630var buildStoriesLogicFromGql = (gqlProgram) => { 13631 const gqlStories = gqlProgram.isEditor ? [] : gqlProgram.programVersion.stories; 13632 const storiesLogic = gqlStories.reduce((acc, story) => { 13633 acc[getIdFromGqlId(story.id)] = buildStoryLogicFromGql(story); 13634 return acc; 13635 }, {}); 13636 return gqlStories.length ? storiesLogic : null; 13637}; 13638var buildStoryLogicFromGql = (story) => { 13639 return { 13640 [LogicContainers.BackgroundAsset]: { 13641 [MediaTypes.Image]: story?.backgroundImageLogic, 13642 [MediaTypes.Video]: story?.backgroundVideoLogic 13643 }, 13644 [LogicContainers.Soundtrack]: { [MediaTypes.Audio]: story?.backgroundAudioLogic }, 13645 [LogicContainers.VideoSettings]: { [LogicContext.StoryRatioAndQuality]: story?.ratioAndQualityLogic }, 13646 [LogicContainers.DecisionPoint]: story.decisionPoints.reduce((dpAcc, dp) => { 13647 if (dp.logic) dpAcc[getIdFromGqlId(dp.id)] = dp.logic; 13648 return dpAcc; 13649 }, {}) 13650 }; 13651}; 13652var buildScenesLogicFromGql = (gqlProgram) => { 13653 return gqlProgram.programVersion.scenes.reduce((acc, scene) => { 13654 const sceneId = getIdFromGqlId(scene.id); 13655 acc[sceneId] = buildSceneLogicFromGql(scene); 13656 return acc; 13657 }, {}); 13658}; 13659var buildSceneLogicFromGql = (gqlScene) => { 13660 let sceneLogicItems = {}; 13661 if (gqlScene.animationLogic) sceneLogicItems[`${getIdFromGqlId(gqlScene.id)}_animation`] = gqlScene.animationLogic; 13662 if (gqlScene.validationLogic) sceneLogicItems[`${getIdFromGqlId(gqlScene.id)}_validation`] = gqlScene.validationLogic; 13663 if (gqlScene.descriptiveTranscriptLogic) sceneLogicItems["descriptive-transcript"] = gqlScene.descriptiveTranscriptLogic; 13664 gqlScene.sceneParts.forEach((part) => { 13665 part.animationGuidelines.forEach((ag) => { 13666 if (ag.logic.logic) sceneLogicItems[ag.logic.name] = ag.logic.logic; 13667 }); 13668 part.placeholders.forEach((ph) => { 13669 if (ph.logic.logic) sceneLogicItems[ph.logic.name] = ph.logic.logic; 13670 }); 13671 part.placeholderGroups.forEach((gp) => { 13672 if (gp.logic.logic) sceneLogicItems[getIdFromGqlId(gp.logic.id)] = gp.logic.logic; 13673 });
13674 part.prioritizedLists.forEach((pl) => { 13675 if (pl.logic.logic) sceneLogicItems[getIdFromGqlId(pl.logic.id)] = pl.logic.logic; 13676 }); 13677 }); 13678 return sceneLogicItems; 13679}; 13680var buildProgramLogicFromGql = (gqlProgram) => { 13681 const gqlStorySelectionLogic = gqlProgram.programVersion.storySelectionLogic; 13682 return gqlStorySelectionLogic ? { [LogicContainers.StorySelection]: { [LogicContainers.StorySelection]: gqlStorySelectionLogic } } : null; 13683}; 13684var buildNarratorsFromGql = (accountId, programName, gqlNarrators) => { 13685 return gqlNarrators.map((narr) => buildNarratorFromGql(accountId, programName, narr)); 13686}; 13687var buildNarratorFromGql = (accountId, programName, gqlNarrator) => { 13688 return { 13689 graphQLId: gqlNarrator.id, 13690 projectId: `${accountId}/${programName}`, 13691 location: gqlNarrator.carUrl, 13692 status: gqlNarrator.status, 13693 createdTime: new Date(gqlNarrator.created).valueOf(), 13694 decisionTablesLoadTaskId: gqlNarrator.decisionTablesLoadTaskId, 13695 name: gqlNarrator.name, 13696 decisionTablesLocation: gqlNarrator.dtaasPrefix, 13697 assetId: `${AssetTypes.narrator}/${gqlNarrator.name}`, 13698 updatedTime: new Date(gqlNarrator.updated).valueOf(), 13699 title: gqlNarrator.name, 13700 type: AssetTypes.narrator 13701 }; 13702}; 13703var buildDataTableFromGql = (postgresDataTable) => { 13704 const assetId = getIdFromGqlId(postgresDataTable.id); 13705 return { 13706 name: postgresDataTable.legacyDataTableId || assetId, 13707 mediaType: MediaTypes.Application, 13708 type: AssetTypes.mappingTable, 13709 graphQLId: postgresDataTable.id, 13710 graphQLUpdated: postgresDataTable.updated, 13711 description: postgresDataTable.description, 13712 isPostgresAsset: true, 13713 location: postgresDataTable.location, 13714 mappingTableScheme: postgresDataTable.schema, 13715 title: postgresDataTable.name, 13716 url: postgresDataTable.downloadUrl, 13717 decisionTablesLocation: postgresDataTable.dtaasPrefix, 13718 assetId: `${AssetTypes.mappingTable}/${postgresDataTable.legacyDataTableId || assetId}`, 13719 createdTime: new Date(postgresDataTable.created).valueOf(), 13720 updatedTime: new Date(postgresDataTable.updated).valueOf(), 13721 version: 0, 13722 activeVersion: 0, 13723 inUse: true 13724 }; 13725}; 13726var buildNarrationRecordingsFromGql = (accountId, programName, gqlNarrationRecordings, isEditor) => { 13727 return gqlNarrationRecordings.map((rec) => buildNarrationRecordingFromGql(accountId, programName, rec, isEditor)); 13728}; 13729var buildNarrationRecordingFromGql = (accountId, programName, gqlNarrationRecording, isEditor) => { 13730 const name = isEditor ? gqlNarrationRecording.id : getRecordingAssetNameByKey(gqlNarrationRecording.narrationId, defaultNarratorId, gqlNarrationRecording.key); 13731 let convertedNarrationRecording = { 13732 graphQLId: gqlNarrationRecording.id, 13733 graphQLUpdated: gqlNarrationRecording.updated, 13734 projectId: `${accountId}/${programName}`, 13735 RFR: gqlNarrationRecording.rfr, 13736 type: AssetTypes.recording, 13737 mediaType: MediaTypes.Audio, 13738 filename: gqlNarrationRecording.filename, 13739 version: gqlNarrationRecording.lastVersionNumber, 13740 activeVersion: gqlNarrationRecording.narrationRecordingActiveVersion?.version || 0, 13741 activeVersionId: gqlNarrationRecording.narrationRecordingActiveVersion?.id, 13742 narrationMetadata: { 13743 ...gqlNarrationRecording.metadata, 13744 text: gqlNarrationRecording.text 13745 }, 13746 name, 13747 createdTime: new Date(gqlNarrationRecording.created).valueOf(), 13748 updatedTime: new Date(gqlNarrationRecording.updated).valueOf(), 13749 assetId: `${AssetTypes.recording}/${name}`, 13750 inUse: true, 13751 url: gqlNarrationRecording.narrationRecordingActiveVersion?.url, 13752 recordingStatus: gqlNarrationRecording.narrationRecordingActiveVersion?.status, 13753 recordingErrorReason: convertNarrationRecordingErrorReason(gqlNarrationRecording.narrationRecordingActiveVersion?.errorReason), 13754 status: gqlNarrationRecording.lastVersionNumber === 0 ? "request" : "approved", 13755 narrationId: gqlNarrationRecording.narrationId, 13756 isPostgresAsset: true, 13757 location: gqlNarrationRecording.narrationRecordingActiveVersion?.location 13758 }; 13759 if (gqlNarrationRecording.narrationRecordingVersions) convertedNarrationRecording.history = { Items: gqlNarrationRecording.narrationRecordingVersions.map((narrationRecordingVersion) => buildNarrationRecordingVersionFromGql(narrationRecordingVersion, gqlNarrationRecording.filename)).sort((a, b) => a.version > b.version ? -1 : 1) }; 13760 return convertedNarrationRecording; 13761}; 13762var buildNarrationRecordingVersionFromGql = (gqlNarrationRecordingVersion, filename) => ({ 13763 ...gqlNarrationRecordingVersion, 13764 uploadedBy: gqlNarrationRecordingVersion.createdBy, 13765 updateTime: new Date(gqlNarrationRecordingVersion.created).getTime(), 13766 recordingStatus: gqlNarrationRecordingVersion.status, 13767 recordingErrorReason: convertNarrationRecordingErrorReason(gqlNarrationRecordingVersion.errorReason), 13768 isPostgresAsset: true, 13769 filename 13770}); 13771var buildStateVersionsFromGql = (programVersionSnapshots) => { 13772 return programVersionSnapshots.map((gqlProgramVersionSnapshot) => buildStateSnapshotFromGql(gqlProgramVersionSnapshot)); 13773}; 13774var buildStateSnapshotFromGql = (gqlProgramVersionSnapshot, snapshotAssets) => { 13775 let snapshot = { 13776 createdBy: gqlProgramVersionSnapshot.snapshottedBy, 13777 createdOn: new Date(gqlProgramVersionSnapshot.snapshotted).getTime(), 13778 snapshotComment: gqlProgramVersionSnapshot.snapshotComment, 13779 snapshotName: gqlProgramVersionSnapshot.snapshotName, 13780 snapshotNumber: gqlProgramVersionSnapshot.snapshotNumber, 13781 validationData: gqlProgramVersionSnapshot.snapshotValidationData, 13782 snapshotSource: SnapshotSource.POSTGRES, 13783 graphQLId: gqlProgramVersionSnapshot.id, 13784 graphQLParentProgramVersionId: gqlProgramVersionSnapshot.parent1ProgramVersion?.id 13785 }; 13786 if (snapshotAssets) snapshot.assets = snapshotAssets; 13787 return snapshot; 13788}; 13789var buildStateSnapshotAssetsFromGql = (postgresAssets, postgresAnimations, postgresDataTables, postgresNarrationRecordings, postgresNarrators) => {
13790 let snapshotAssets = postgresAssets.map((postgresAsset) => { 13791 const { assetActiveVersion } = postgresAsset; 13792 return { 13793 name: postgresAsset.legacyAssetId.split("/").pop(), 13794 type: AssetTypes.curated, 13795 version: assetActiveVersion.version, 13796 url: assetActiveVersion.url, 13797 thumbnailUrl: assetActiveVersion.thumbnailUrl 13798 }; 13799 }); 13800 let snapshotAnimations = postgresAnimations.map((postgresAnimation) => { 13801 const { animationActiveVersion } = postgresAnimation; 13802 return { 13803 name: postgresAnimation.legacyAnimationId.split("/").pop(), 13804 type: AssetTypes.animation, 13805 version: animationActiveVersion.version 13806 }; 13807 }); 13808 let snapshotDataTables = postgresDataTables.map((postgresDataTable) => { 13809 return { 13810 name: postgresDataTable.legacyDataTableId || getIdFromGqlId(postgresDataTable.id), 13811 type: AssetTypes.mappingTable, 13812 version: 0, 13813 url: postgresDataTable.downloadUrl, 13814 decisionTablesLocation: postgresDataTable.dtaasPrefix 13815 }; 13816 }); 13817 let snapshotNarrationRecordings = postgresNarrationRecordings.map((postgresNarrationRecording) => { 13818 return { 13819 name: getRecordingAssetNameByKey(postgresNarrationRecording.narrationId, defaultNarratorId, postgresNarrationRecording.key), 13820 type: AssetTypes.recording, 13821 version: postgresNarrationRecording.narrationRecordingActiveVersion?.version || 0, 13822 location: postgresNarrationRecording.narrationRecordingActiveVersion?.location, 13823 url: postgresNarrationRecording.narrationRecordingActiveVersion?.url, 13824 RFR: postgresNarrationRecording.rfr, 13825 filename: postgresNarrationRecording.filename, 13826 recordingStatus: postgresNarrationRecording.narrationRecordingActiveVersion?.status 13827 }; 13828 }); 13829 let snapshotNarrators = postgresNarrators.map((postgresNarrator) => { 13830 return { 13831 name: postgresNarrator.legacyNarratorId.split("/").pop(), 13832 type: AssetTypes.narrator, 13833 version: 1, 13834 location: postgresNarrator.carUrl, 13835 decisionTablesLocation: postgresNarrator.dtaasPrefix 13836 }; 13837 }); 13838 return [ 13839 ...snapshotAssets, 13840 ...snapshotAnimations, 13841 ...snapshotNarrationRecordings, 13842 ...snapshotDataTables, 13843 ...snapshotNarrators 13844 ]; 13845}; 13846//#endregion 13847//#region client/components/legacyCommon/LogicPopupContainer.jsx 13848var import_react = /* @__PURE__ */ __toESM(require_react()); 13849var import_dist$4 = /* @__PURE__ */ __toESM(require_dist$3()); 13850var import_jsx_runtime = require_jsx_runtime(); 13851var LogicPopupContainer = class extends import_react.Component { 13852 constructor(props) { 13853 super(props); 13854 this.state = { activeIndex: props.selectedIndex }; 13855 } 13856 handleClickOutside = this.props.handleClickOutside || (() => {}); 13857 renderComponent(ChildComponent, isTab = false) { 13858 const { footer, title } = ChildComponent.props; 13859 const contentClassName = ChildComponent.props["data-content-class-name"]; 13860 const rest = Object.assign({}, ChildComponent.props); 13861 delete rest.footer; 13862 delete rest.title; 13863 delete rest["data-content-class-name"]; 13864 const popupContentClassName = "logic-popup-content" + (contentClassName ? " " + contentClassName : ""); 13865 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [ 13866 !isTab && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 13867 className: "logic-popup-title", 13868 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: title }) 13869 }), 13870 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 13871 className: popupContentClassName, 13872 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChildComponent.type, { ...rest }) 13873 }), 13874 footer && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 13875 className: "logic-popup-footer clearfix", 13876 children: footer 13877 }) 13878 ] }); 13879 } 13880 getTabPanesFromChildren(children) { 13881 if (children.length < 2) return; 13882 const className = children.length == 2 ? "stretch" : "fit"; 13883 return children.map((childComponent) => { 13884 return { 13885 menuItem: { 13886 key: childComponent.props.title, 13887 content: childComponent.props.title, 13888 className 13889 }, 13890 render: () => this.renderComponent(childComponent, true) 13891 }; 13892 }); 13893 } 13894 onTabChange = (event, { activeIndex }) => { 13895 this.setState({ activeIndex }); 13896 }; 13897 render() { 13898 if (!this.props.children) return null; 13899 let children = this.props.children.length ? this.props.children.filter((c) => c) : this.props.children; 13900 if (!children || Array.isArray(children) && !children.length) return null; 13901 const className = "logic-popup-container " + (this.props.className || ""); 13902 const style = {}; 13903 if (this.props.position) { 13904 style.left = this.props.position.x; 13905 style.top = this.props.position.y; 13906 style.position = "fixed"; 13907 } 13908 if (children.length && children.length > 1) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 13909 className, 13910 style, 13911 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Tab, { 13912 menu: { 13913 secondary: true, 13914 pointing: true, 13915 className: "popup-menu" 13916 }, 13917 panes: this.getTabPanesFromChildren(children), 13918 onTabChange: this.onTabChange, 13919 activeIndex: this.state.activeIndex 13920 }) 13921 }); 13922 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 13923 className, 13924 style, 13925 children: this.renderComponent(children.length ? children[0] : children) 13926 }); 13927 } 13928};
13929LogicPopupContainer.propTypes = { 13930 className: import_prop_types.default.string, 13931 selectedIndex: import_prop_types.default.number, 13932 handleClickOutside: import_prop_types.default.func, 13933 position: import_prop_types.default.shape({ 13934 x: import_prop_types.default.number, 13935 y: import_prop_types.default.number 13936 }), 13937 children: import_prop_types.default.oneOfType([ 13938 import_prop_types.default.array, 13939 import_prop_types.default.element, 13940 import_prop_types.default.bool 13941 ]) 13942}; 13943var LogicPopupContainer_default = (0, import_dist$4.default)(LogicPopupContainer); 13944//#endregion 13945//#region client/components/legacyCommon/HubContentEditable.jsx 13946var HubContentEditable = class extends import_react.Component { 13947 constructor(props) { 13948 super(props); 13949 let { isValid, validMessage } = this.extractValidationResult(props.validateFunc, props.value); 13950 this.onChange = this._onChange.bind(this); 13951 this.onConfirm = this._onConfirm.bind(this); 13952 this.onCancel = this._onCancel.bind(this); 13953 this.onKeyDown = this._onKeyDown.bind(this); 13954 this.onFocus = this._onFocus.bind(this); 13955 this.onBlur = this._onBlur.bind(this); 13956 this.state = { 13957 isValid, 13958 validMessage, 13959 value: props.value, 13960 initialValue: props.value 13961 }; 13962 } 13963 extractValidationResult(validateFunc, value, prevVal) { 13964 let validationObj = validateFunc ? validateFunc(value, prevVal) : true; 13965 let isValid; 13966 let validMessage; 13967 if (typeof validationObj === "boolean") isValid = validationObj; 13968 else { 13969 isValid = validationObj.result; 13970 validMessage = validationObj.message; 13971 } 13972 return { 13973 isValid, 13974 validMessage 13975 }; 13976 } 13977 componentDidMount() { 13978 if (this.props.isFocused && this.input) this.input.focus(); 13979 } 13980 shouldComponentUpdate(nextProps, nextState) { 13981 let update = false; 13982 for (let prop in nextProps) if (nextProps.hasOwnProperty(prop)) update = update || nextProps[prop] !== this.props[prop]; 13983 return update || this.state !== nextState; 13984 } 13985 UNSAFE_componentWillReceiveProps(nextProps) { 13986 if (nextProps.isFocused && this.input) this.input.focus(); 13987 if (!this.state.value) this.setValue(nextProps.value, nextProps); 13988 if (this.props.id !== nextProps.id) this.setValue(nextProps.value, nextProps); 13989 if (this.props.value !== nextProps.value) { 13990 this.setState({ initialValue: nextProps.value }); 13991 this.setValue(nextProps.value, nextProps); 13992 } 13993 } 13994 setValue(val, props, cb) { 13995 this.setState({ value: val }, cb); 13996 if (props.validateFunc) this.setState(this.extractValidationResult(props.validateFunc, val, this.state.initialValue)); 13997 } 13998 _onChange(e) { 13999 let replaceNBSP = new RegExp(String.fromCharCode(160), "g"); 14000 this.setValue(e.target.innerText.replace(replaceNBSP, " "), this.props); 14001 } 14002 _onCancel() { 14003 this.setState({ initialValue: void 0 }, () => this.setState({ initialValue: this.props.value })); 14004 this.setValue(this.state.initialValue, this.props); 14005 if (this.props.onCancel) this.props.onCancel(); 14006 } 14007 _onConfirm() { 14008 if (this.input) this.input.blur(); 14009 } 14010 _onBlur(e, event, isCanceled) { 14011 if (this.state.value !== this.state.initialValue) if (this.state.isValid && !isCanceled) this.props.onConfirm(this.state.value, e); 14012 else this.onCancel(); 14013 if (this.props.onBlur) this.props.onBlur(); 14014 } 14015 _onFocus(e) { 14016 this.setState({ initialValue: this.props.value }, () => { 14017 if (this.props.onClick) this.props.onClick(e); 14018 }); 14019 } 14020 _onKeyDown(e) { 14021 let preventDefault = (e) => { 14022 if (e.preventDefault) e.preventDefault(); 14023 }; 14024 let isPrintableKey = e.key && e.key.length === 1; 14025 if (e.key === "Enter") { 14026 this.input.blur(); 14027 if (this.props.onEnterClicked) this.props.onEnterClicked(); 14028 preventDefault(e); 14029 } else if (e.key === "Escape") { 14030 this.onBlur({}, {}, true); 14031 preventDefault(e); 14032 } else if (this.props.inputRegExp && isPrintableKey) { 14033 if (!new RegExp(this.props.inputRegExp).test(e.target.innerText + e.key)) preventDefault(e); 14034 } 14035 } 14036 render() { 14037 const valid = this.state.isValid ? "" : " invalid"; 14038 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { 14039 className: `hubContentEditable ${this.props.disabled ? "disabled" : ""} ${valid} ${this.props.className}`.split(" ").filter((t) => t).join(" "), 14040 children: [
14041 this.props.showIcons && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: this.props.iconClass + "-ph-icon col-xs-1" }), 14042 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 14043 className: "inline-block", 14044 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 14045 "data-testid": `hub-content-editable-${this.props.placeholder}`, 14046 spellCheck: "false", 14047 id: this.props.id, 14048 className: `contentEditable${this.props.disabled ? " disabled" : ""}`, 14049 contentEditable: !this.props.disabled, 14050 placeholder: this.props.placeholder, 14051 onClick: this.onFocus, 14052 onInput: this.onChange, 14053 onKeyDown: this.onKeyDown, 14054 suppressContentEditableWarning: true, 14055 onBlur: this.onBlur, 14056 ref: (elem) => this.input = elem, 14057 onMouseEnter: this.props.onMouseEnter, 14058 onMouseLeave: this.props.onMouseLeave, 14059 children: this.state.initialValue 14060 }) 14061 }), 14062 !!this.state.validMessage && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("label", { children: this.state.validMessage }), 14063 this.props.children 14064 ] 14065 }); 14066 } 14067}; 14068HubContentEditable.defaultProps = { 14069 className: "", 14070 fontSize: 9 14071}; 14072HubContentEditable.propTypes = { 14073 id: import_prop_types.default.string, 14074 onCancel: import_prop_types.default.func, 14075 onConfirm: import_prop_types.default.func, 14076 onClick: import_prop_types.default.func, 14077 onBlur: import_prop_types.default.func, 14078 onEnterClicked: import_prop_types.default.func, 14079 validateFunc: import_prop_types.default.func, 14080 value: import_prop_types.default.string, 14081 children: import_prop_types.default.any, 14082 placeholder: import_prop_types.default.string, 14083 isFocused: import_prop_types.default.bool, 14084 className: import_prop_types.default.string, 14085 fontSize: import_prop_types.default.number, 14086 showIcons: import_prop_types.default.bool, 14087 iconClass: import_prop_types.default.string, 14088 disabled: import_prop_types.default.bool, 14089 inputRegExp: import_prop_types.default.string, 14090 onMouseEnter: import_prop_types.default.func, 14091 onMouseLeave: import_prop_types.default.func 14092}; 14093//#endregion 14094//#region client/components/legacyCommon/HubDatePicker.tsx 14095var import_Components = require_Components(); 14096var DISPLAY_FORMAT = "MM/DD/YYYY HH:mm"; 14097var DATA_FORMAT = "YYYY-MM-DD HH:mm"; 14098var HubDatePicker = (props) => { 14099 const placeholder = `MM/DD/YYYY HH:mm${props.displayPostfix || ""}`; 14100 const onDateTimeChange = (date) => { 14101 let dateString = date?.isValid() ? date.format(DATA_FORMAT) : null; 14102 props.handleChangeStart(dateString); 14103 }; 14104 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyDateTimePicker, { 14105 id: props.id, 14106 dataTestId: "date-picker", 14107 className: props.className, 14108 variant: props.inline ? "inline" : "dialog", 14109 value: props.startDate || null, 14110 onChange: onDateTimeChange, 14111 disabled: props.readOnly, 14112 format: DISPLAY_FORMAT, 14113 placeHolder: placeholder 14114 }); 14115}; 14116//#endregion 14117//#region client/components/legacyCommon/HubDataElementPicker.tsx 14118var HubDataElementPicker = ({ dataElementName, onDataElementSelectionClick, onWhenLogicPopupSelectionClick, value, datePostfix, datePickerClassname, handleChange, dataElementCompareType, pickedActionIndex, pickedParamIndex, paramName, isLogicWhenPopup }) => { 14119 const renderDatePicker = () => { 14120 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubDatePicker, { 14121 id: "operandContentEditable", 14122 className: datePickerClassname, 14123 inline: true, 14124 readOnly: false, 14125 handleChangeStart: handleChange, 14126 startDate: value, 14127 displayPostfix: datePostfix 14128 }); 14129 }; 14130 const renderPrimitivePicker = () => { 14131 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 14132 value, 14133 placeholder: value, 14134 onConfirm: handleChange 14135 }); 14136 }; 14137 const handleWhenLogicPopupSelectionClick = (e) => { 14138 onWhenLogicPopupSelectionClick(e); 14139 }; 14140 const handleDataElementPickedLine = () => { 14141 if (dataElementName) onDataElementSelectionClick(dataElementCompareType, true, pickedActionIndex, pickedParamIndex); 14142 }; 14143 const renderDataElementPickedLine = () => { 14144 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 14145 className: "param-name", 14146 children: paramName 14147 }
14147), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 14148 className: "data-element-picked-line", 14149 value: dataElementName, 14150 placeholder: dataElementName, 14151 onClick: !isLogicWhenPopup ? handleDataElementPickedLine : handleWhenLogicPopupSelectionClick 14152 })] }); 14153 }; 14154 const handlePickDataElementIconButton = () => { 14155 onDataElementSelectionClick(dataElementCompareType, false, pickedActionIndex, pickedParamIndex); 14156 }; 14157 const renderPickDataElementIconButton = () => { 14158 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", { 14159 className: "dotsIcon", 14160 onClick: !isLogicWhenPopup ? handlePickDataElementIconButton : handleWhenLogicPopupSelectionClick, 14161 "data-testid": "data-element-selection-dots-icon" 14162 }); 14163 }; 14164 const renderBasicPicker = () => { 14165 if (dataElementCompareType === DataElementContentTypes.Date) return renderDatePicker(); 14166 if (dataElementCompareType === DataElementContentTypes.Number || dataElementCompareType === DataElementContentTypes.String) return renderPrimitivePicker(); 14167 }; 14168 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 14169 className: "data-element-picker", 14170 children: [ 14171 !dataElementName && renderBasicPicker(), 14172 dataElementName && renderDataElementPickedLine(), 14173 !dataElementName && renderPickDataElementIconButton() 14174 ] 14175 }); 14176}; 14177//#endregion 14178//#region client/components/HubEditor/logic/LogicDataSelector/SelectedItemSection.jsx 14179var SelectedItemSection = (props) => { 14180 const renderChildren = () => { 14181 if (!props.children) return null; 14182 let children = props.children.length ? props.children.filter((c) => c && (!Array.isArray(c) || c.length)) : [props.children]; 14183 if (!children || Array.isArray(children) && !children.length) return null; 14184 return children.map((child, idx) => { 14185 if (!child) return; 14186 if (Array.isArray(child)) { 14187 if (child.length > 1) return child; 14188 child = child.pop(); 14189 } 14190 const childProps = { ...child.props || {} }; 14191 const containerClass = childProps["parent-class-name"] || ""; 14192 delete childProps["parent-class-name"]; 14193 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { 14194 className: containerClass, 14195 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(child.type, { ...childProps }) 14196 }, idx); 14197 }); 14198 }; 14199 const selectedValue = (getElementInfoFromActionableData(props.selectedValue, props.dataFields) || {}).displayName; 14200 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 14201 className: "popup-selected", 14202 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", { children: [ 14203 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14204 className: "remove-selected", 14205 id: "modify-panel-remove-selected", 14206 "data-testid": "modify-panel-remove-selected-x-button", 14207 onClick: props.onSelectedItemRemoveClicked, 14208 children: "x" 14209 }), 14210 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { 14211 className: "selected-title", 14212 children: selectedValue !== "\n" ? selectedValue : "Line Break" 14213 }), 14214 renderChildren() 14215 ] }) 14216 }); 14217}; 14218SelectedItemSection.propTypes = { 14219 selectedValue: import_prop_types.default.object, 14220 dataFields: import_prop_types.default.shape({ 14221 assets: import_prop_types.default.array, 14222 dataElements: import_prop_types.default.array 14223 }), 14224 onSelectedItemRemoveClicked: import_prop_types.default.func, 14225 children: import_prop_types.default.oneOfType([ 14226 import_prop_types.default.array, 14227 import_prop_types.default.element, 14228 import_prop_types.default.bool 14229 ]) 14230}; 14231//#endregion 14232//#region client/components/HubEditor/logic/LogicDataSelector/ModifyDataElementPanel.jsx 14233init_moment(); 14234var import_numeral = /* @__PURE__ */ __toESM(require_numeral()); 14235var dateTypeComparableFunctions = /* @__PURE__ */ new Set(["datediff"]); 14236var numberTypeComparableFunctions = /* @__PURE__ */ new Set([ 14237 "add", 14238 "subtract", 14239 "multiply", 14240 "absdiff" 14241]); 14242var stringTypeComparableFunctions = /* @__PURE__ */ new Set(["replace"]); 14243var isDataElementComparable = (act) => act && (dateTypeComparableFunctions.has(act.name) || numberTypeComparableFunctions.has(act.name) || stringTypeComparableFunctions.has(act.name)); 14244var ModifyDataElementPanel = (props) => { 14245 let actions = getAvailableFunctions(); 14246 let getDropDownActions = (mediaType) => { 14247 if (mediaType === LOGIC_MEDIA_TYPES.Number) mediaType = VLX_PARAMTYPE.Numeric; 14248 else if (mediaType === LOGIC_MEDIA_TYPES.Date) mediaType = VLX_PARAMTYPE.Date; 14249 let formatters = actions.filter((act) => act.tag.some((tag) =>
14249 tag === VLX_FUNCTION_TAGS.Formatter) && act.input.some((inTypes) => inTypes === mediaType)).map((act) => ({ 14250 key: act.name, 14251 text: capitalizeFirstLetter(act.text), 14252 value: act.name 14253 })); 14254 let functions = actions.filter((act) => act.tag.some((tag) => tag === VLX_FUNCTION_TAGS.Function) && act.input.some((inTypes) => inTypes === mediaType)).map((act) => ({ 14255 key: act.name, 14256 text: capitalizeFirstLetter(act.text), 14257 value: act.name 14258 })); 14259 if (formatters && formatters.length) formatters = [{ 14260 key: "format", 14261 text: "Format", 14262 className: "header", 14263 type: "header" 14264 }, ...formatters]; 14265 if (functions && functions.length) functions = [{ 14266 key: "function", 14267 text: "Function", 14268 className: "header", 14269 type: "header" 14270 }, ...functions]; 14271 return formatters.concat(functions); 14272 }; 14273 let onActionSelected = (index, data) => { 14274 if (!props.selectedValue.actions[index] || props.selectedValue.actions[index].name !== data.value) props.onActionSelected(index, data); 14275 }; 14276 const selectedValueObj = getElementInfoFromActionableData(props.selectedValue, props.dataFields) || {}; 14277 const selectedValue = selectedValueObj.displayName; 14278 const mediaType = selectedValueObj.mediaType; 14279 let initialAvailableActions = getDropDownActions(mediaType); 14280 let showFirstAddActionsLink = (!props.selectedValue.actions || !props.selectedValue.actions.length) && initialAvailableActions && initialAvailableActions.length > 0; 14281 let validateMomentFormatting = (format) => { 14282 return { 14283 result: true, 14284 message: hooks().format(format) 14285 }; 14286 }; 14287 let validateNumberFormatting = (format) => { 14288 return { 14289 result: true, 14290 message: (0, import_numeral.default)("123456.78").format(format) 14291 }; 14292 }; 14293 let parameterTypeToDataElementCompareType = (parameter) => { 14294 switch (parameter.type) { 14295 case VLX_PARAMTYPE.Date: return DataElementContentTypes.Date; 14296 case VLX_PARAMTYPE.Numeric: return DataElementContentTypes.Number; 14297 case VLX_PARAMTYPE.String: return DataElementContentTypes.String; 14298 case "dataElement": return parameter.mediaType; 14299 default: return null; 14300 } 14301 }; 14302 const getDefaultParam = (actionName, paramIdx) => { 14303 return actions.find(({ name }) => name === actionName).params[paramIdx].text; 14304 }; 14305 const renderActionParams = (actionIdx, parameter, paramIdx, arr, isDataElementComparableFunction, actionName) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { 14306 className: "action-parameter " + parameter.type, 14307 children: [ 14308 (parameter.type === VLX_PARAMTYPE.Numeric && !isDataElementComparableFunction || parameter.type === VLX_PARAMTYPE.String) && /* @__P
14308URE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 14309 value: parameter.value ? parameter.value : "", 14310 placeholder: capitalizeFirstLetter(parameter.text), 14311 onConfirm: (value) => props.onActionParameterChanged(actionIdx, paramIdx, value) 14312 }), 14313 parameter.type === VLX_PARAMTYPE.DateTimeFormat && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 14314 value: parameter.value ? parameter.value : "", 14315 placeholder: capitalizeFirstLetter(parameter.text), 14316 onConfirm: (value) => props.onActionParameterChanged(actionIdx, paramIdx, value), 14317 validateFunc: validateMomentFormatting, 14318 isFocused: !parameter.value 14319 }), 14320 parameter.type === VLX_PARAMTYPE.NumberFormat && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 14321 value: parameter.value ? parameter.value : "", 14322 placeholder: capitalizeFirstLetter(parameter.text), 14323 onConfirm: (value) => props.onActionParameterChanged(actionIdx, paramIdx, value), 14324 validateFunc: validateNumberFormatting, 14325 isFocused: !parameter.value 14326 }), 14327 parameter.type === VLX_PARAMTYPE.Choice && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown, { 14328 className: "param-choice", 14329 options: parameter.choices.map((c) => ({ 14330 key: c, 14331 text: c, 14332 value: c 14333 })), 14334 onChange: (event, data) => props.onActionParameterChanged(actionIdx, paramIdx, data.value), 14335 value: parameter && parameter.value ? parameter.value : null, 14336 placeholder: "Choose", 14337 id: `params-choices-${paramIdx}`, 14338 floating: true 14339 }),
14340 parameter.type === VLX_PARAMTYPE.Boolean && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown, { 14341 className: "param-choice", 14342 options: [{ 14343 key: "False", 14344 text: parameter.choices[0], 14345 value: "false" 14346 }, { 14347 key: "True", 14348 text: parameter.choices[1], 14349 value: "true" 14350 }], 14351 onChange: (event, data) => { 14352 return props.onActionParameterChanged(actionIdx, paramIdx, data.value === "true"); 14353 }, 14354 value: (parameter && parameter.value ? parameter.value : !!parameter.defaultValue).toString(), 14355 placeholder: capitalizeFirstLetter(parameter.text), 14356 id: `params-choices-${paramIdx}`, 14357 floating: true 14358 }), 14359 parameter.type === VLX_PARAMTYPE.Date && !isDataElementComparableFunction && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 14360 className: "param-date", 14361 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubDatePicker, { 14362 id: "operandContentEditable", 14363 inline: true, 14364 readOnly: false, 14365 handleChangeStart: (date) => props.onActionParameterChanged(actionIdx, paramIdx, date), 14366 startDate: parameter && parameter.value && hooks(parameter.value), 14367 shouldCloseOnSelect: true 14368 }) 14369 }), 14370 (parameter.type === VLX_PARAMTYPE.Date || parameter.type === VLX_PARAMTYPE.Numeric || parameter.type === "dataElement" || parameter.type === VLX_PARAMTYPE.String) && isDataElementComparableFunction && /* @__P
14370URE__ */ (0, import_jsx_runtime.jsx)("div", { 14371 className: "param-data-element", 14372 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubDataElementPicker, { 14373 handleChange: (value) => props.onActionParameterChanged(actionIdx, paramIdx, value), 14374 value: parameter.type === VLX_PARAMTYPE.Date && parameter?.value ? hooks(parameter?.value) : parameter?.value, 14375 dataElementName: parameter?.displayName, 14376 onDataElementSelectionClick: props.onDataElementComparison, 14377 dataElementCompareType: parameterTypeToDataElementCompareType(parameter), 14378 pickedActionIndex: actionIdx && actionIdx, 14379 pickedParamIndex: paramIdx, 14380 paramName: parameter.text || getDefaultParam(actionName, paramIdx) 14381 }) 14382 }) 14383 ] 14384 }, paramIdx); 14385 let renderActions = (act, idx, array) => { 14386 let options = !idx || !array[idx - 1] ? initialAvailableActions : getDropDownActions(array[idx - 1].output); 14387 const isDataElementComparableFunction = isDataElementComparable(act); 14388 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", { children: [ 14389 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { 14390 className: "action-title", 14391 children: "Modify data element" 14392 }), 14393 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("li", { 14394 className: "actions-list-item", 14395 "data-testid": "actions-select-list-item", 14396 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown, { 14397 options, 14398 onChange: (event, data) => onActionSelected(idx, data), 14399 value: act && act.name ? act.name : null, 14400 placeholder: "Choose", 14401 text: act ? capitalizeFirstLetter(act.text) : void 0, 14402 id: `actions-dropdown-${idx}`, 14403 floating: true 14404 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14405 id: "remove-action-" + idx, 14406 className: "remove-action", 14407 onClick: () => props.onDeleteAction(idx), 14408 "data-testid": "remove-action-" + idx 14409 })] 14410 }), 14411 act && act.params && act.params.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { 14412 className: "actions-list-item params", 14413 children: act.params.filter((param) => param.type !== VLX_PARAMTYPE.TimeZone).map((parameter, paramIdx, arr) => renderActionParams(idx, parameter, paramIdx, arr, isDataElementComparableFunction, act.name)) 14414 }) 14415 ] }, idx); 14416 }; 14417 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectedItemSection, { 14418 selectedValue: props.selectedValue, 14419 dataFields: props.dataFields, 14420 onSelectedItemRemoveClicked: props.onRemoveSelectedItem, 14421 children: [ 14422 showFirstAddActionsLink && selectedValue !== "\n" && !props.isDataElementCompareMode && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14423 "parent-class": "action-lint", 14424 id: "add-first-action-button", 14425 className: "add-actions", 14426 onClick: props.onAddActionClick, 14427 "data-testid": "modify-data-element-button", 14428 children: "Modify data element" 14429 }), 14430 props.selectedValue.actions && props.selectedValue.actions.map(renderActions), 14431 props.selectedValue.actions && props.selectedValue.actions.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 14432 "parent-class": "action-lint", 14433 className: "action-link", 14434 onClick: props.onAddActionClick, 14435 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 14436 className: "add-icon with-hover", 14437 children: "\xA0" 14438 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 14439 className: "add-icon-text", 14440 "data-testid": "add-another-modification-button", 14441 children: "Add another modification" 14442 })] 14443 }) 14444 ] 14445 }); 14446}; 14447ModifyDataElementPanel.propTypes = { 14448 onRemoveSelectedItem: import_prop_types.default.func, 14449 selectedValue: import_prop_types.default.shape({ 14450 name: import_prop_types.default.string, 14451 id: import_prop_types.default.string, 14452 value: import_prop_types.default.string, 14453 mediaType: import_prop_types.default.string, 14454 type: import_prop_types.default.string, 14455 actions: import_prop_types.default.arrayOf(import_prop_types.default.shape({ 14456 name: import_prop_types.default.string, 14457 params: import_prop_types.default.arrayOf(import_prop_types.default.shape({ 14458 type: import_prop_types.default.string, 14459 text: import_prop_types.default.string, 14460 value: import_prop_types.default.oneOfType([ 14461 import_prop_types.default.string, 14462 import_prop_types.default.object, 14463 import_prop_types.default.bool 14464 ]) 14465 })), 14466 text: import_prop_types.default.string,
14467 input: import_prop_types.default.arrayOf(import_prop_types.default.string), 14468 output: import_prop_types.default.string 14469 })) 14470 }), 14471 onActionSelected: import_prop_types.default.func, 14472 onDeleteAction: import_prop_types.default.func, 14473 onActionParameterChanged: import_prop_types.default.func, 14474 onAddActionClick: import_prop_types.default.func, 14475 dataFields: import_prop_types.default.shape({ 14476 assets: import_prop_types.default.array.isRequired, 14477 dataElements: import_prop_types.default.array.isRequired 14478 }), 14479 onDataElementComparison: import_prop_types.default.func, 14480 isDataElementCompareMode: import_prop_types.default.bool 14481}; 14482//#endregion 14483//#region client/components/legacyCommon/PopupFooter.jsx 14484var PopupFooter = class extends import_react.Component { 14485 constructor(props) { 14486 super(props); 14487 } 14488 handleKeyPress = (e) => { 14489 if (this.props.enterKeyConfirms && e.key === "Enter") this.props.handleOkClicked(); 14490 if (this.props.escapeKeyCancels && e.key === "Escape") this.props.handleCancelClicked(); 14491 }; 14492 componentDidMount() { 14493 document.addEventListener("keydown", this.handleKeyPress, true); 14494 } 14495 componentWillUnmount() { 14496 document.removeEventListener("keydown", this.handleKeyPress, true); 14497 } 14498 render() { 14499 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 14500 className: "logic-data-selector-footer", 14501 onKeyDown: this.handleKeyPress,
14502 children: [!this.props.showOnlyPositiveButton && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14503 className: "negative", 14504 onClick: this.props.handleCancelClicked, 14505 children: this.props.btnNegativeText 14506 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14507 id: "btn_ok", 14508 className: "positive", 14509 disabled: this.props.btnPositiveDisabled, 14510 onClick: this.props.handleOkClicked, 14511 children: this.props.btnPositiveText 14512 })] 14513 }); 14514 } 14515}; 14516PopupFooter.defaultProps = { 14517 btnPositiveText: "OK", 14518 btnNegativeText: "Cancel", 14519 enterKeyConfirms: false, 14520 escapeKeyCancels: false 14521}; 14522PopupFooter.propTypes = { 14523 handleOkClicked: import_prop_types.default.func.isRequired, 14524 handleCancelClicked: import_prop_types.default.func.isRequired, 14525 showOnlyPositiveButton: import_prop_types.default.bool, 14526 btnPositiveText: import_prop_types.default.string, 14527 btnNegativeText: import_prop_types.default.string, 14528 btnPositiveDisabled: import_prop_types.default.bool, 14529 enterKeyConfirms: import_prop_types.default.bool, 14530 escapeKeyCancels: import_prop_types.default.bool 14531}; 14532//#endregion 14533//#region client/components/HubEditor/logic/LogicDataSelector/DataSelectionArea.jsx 14534var DataSelectionArea = class extends import_react.Component { 14535 state = { searchTerm: "" }; 14536 onSearchChange = (e) => { 14537 this.setState({ searchTerm: e.target.value }); 14538 }; 14539 applySearch = (item) => item && (!this.state.searchTerm || this.props.titleSelector(item) && this.props.titleSelector(item).toLowerCase().includes(this.state.searchTerm.toLowerCase())); 14540 renderEmptyContent = (text) => { 14541 if (this.props.emptyContent) return this.props.emptyContent; 14542 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 14543 className: "empty-content", 14544 children: text || this.props.emptyContentText 14545 }); 14546 }; 14547 renderTextElements = () => { 14548 const { className, itemIdentifier, onClick, renderItem } = this.props.textElements; 14549 return this.props.textElements.items.map((item, index) => this.renderSelectionItem({ 14550 item, 14551 className, 14552 itemIdentifier, 14553 onClick, 14554 renderItem, 14555 index 14556 })); 14557 }; 14558 renderSelectionItem = (settings) => { 14559 const { item, className, itemIdentifier, keySelector, onClick, renderItem, index } = { 14560 ...this.props, 14561 ...settings 14562 }; 14563 const id = `${itemIdentifier}-${keySelector(item)}`; 14564 const testId = `${item.displayName}-${item.type}`; 14565 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { 14566 className: `data-item ${className}`, 14567 id, 14568 onClick: () => onClick(item), 14569 "data-testid": `data-element-list-item-${testId}`, 14570 children: renderItem(item) 14571 }, keySelector(item) || index); 14572 }; 14573 render() { 14574 let { items, className, onRemove, itemIdentifier, hideSearch } = this.props; 14575 if (!itemIdentifier) itemIdentifier = className; 14576 const filteredItems = items.filter(this.applySearch); 14577 const trimmedFilteredItems = filteredItems && filteredItems.length > 0 ? filteredItems.slice(0, 300) : filteredItems; 14578 const shouldTextElementsBeRendered = this.props.itemIdentifier === "dataElement" && !!this.props.textElements && !!this.props.textElements.items && !!this.props.textElements.items.length; 14579 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 14580 className: `popup-${className}`, 14581 children: [
14582 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14583 className: "logic-popup-remove-selected", 14584 onClick: onRemove 14585 }), 14586 !hideSearch && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 14587 className: "search-bar-container", 14588 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("input", { 14589 id: `${itemIdentifier}-search-bar`, 14590 className: `${className}-search-bar`, 14591 onChange: this.onSearchChange, 14592 value: this.state.searchTerm, 14593 placeholder: "Search" 14594 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "search-icon" })] 14595 }), 14596 this.props.items && !!this.props.items.length && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", { 14597 className: "data-selection-list", 14598 children: [ 14599 shouldTextElementsBeRendered && this.renderTextElements(), 14600 shouldTextElementsBeRendered && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { className: "divider" }, "divider0"), 14601 trimmedFilteredItems.map((item, index) => this.renderSelectionItem({ 14602 item, 14603 index 14604 })), 14605 !filteredItems.length && this.renderEmptyContent("No items found") 14606 ] 14607 }), 14608 (!this.props.items || !this.props.items.length) && this.renderEmptyContent() 14609 ] 14610 }); 14611 } 14612}; 14613DataSelectionArea.defaultProps = { 14614 className: "general-selection-area", 14615 keySelector: (item) => item.name, 14616 titleSelector: (item) => item.title, 14617 renderItem: (item) => item.title, 14618 emptyContentText: "Nothing to Display :{" 14619}; 14620DataSelectionArea.propTypes = { 14621 onClick: import_prop_types.default.func.isRequired, 14622 onRemove: import_prop_types.default.func.isRequired, 14623 items: import_prop_types.default.array, 14624 className: import_prop_types.default.string, 14625 longTitle: import_prop_types.default.string, 14626 shortTitle: import_prop_types.default.string, 14627 title: import_prop_types.default.string, 14628 keySelector: import_prop_types.default.func, 14629 titleSelector: import_prop_types.default.func, 14630 renderItem: import_prop_types.default.func, 14631 itemIdentifier: import_prop_types.default.string, 14632 emptyContentText: import_prop_types.default.string, 14633 emptyContent: import_prop_types.default.element, 14634 hideSearch: import_prop_types.default.bool, 14635 textElements: import_prop_types.default.object 14636}; 14637//#endregion 14638//#region client/components/HubEditor/logic/LogicDataSelector/IconWithTooltip.jsx 14639var IconWithTooltip = (props) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { 14640 style: { display: "inherit" }, 14641 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyTooltip, { 14642 title: props.tooltipText, 14643 enterDelay: 100, 14644 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: `data-type-icon dsl-icon-${props.iconName}` }) 14645 }), props.title] 14646}); 14647IconWithTooltip.propTypes = { 14648 iconName: import_prop_types.default.string.isRequired, 14649 tooltipText: import_prop_types.default.string.isRequired, 14650 title: import_prop_types.default.string.isRequired 14651}; 14652//#endregion 14653//#region client/components/HubEditor/logic/LogicDataSelector/LogicDataSelector.jsx 14654var LogicDataSelector = class extends import_react.Component { 14655 actions = getAvailableFunctions(); 14656 state = { 14657 selectedValue: this.props.value, 14658 modificationValue: null, 14659 blockClickOutside: false, 14660 currentComparableDataElementContentType: null, 14661 isDataElementCompareMode: false, 14662 pickedActionIndex: 0, 14663 pickedParamIndex: null 14664 }; 14665 handleClickOutside = () => { 14666 if (!this.state.blockClickOutside) this.props.handleClickOutside(); 14667 }; 14668 getDataFields = index((assets, dataElements, dataTables, prioritizedLists) => { 14669 return { 14670 assets: [...assets || [], ...dataTables || []], 14671 dataElements, 14672 prioritizedLists 14673 }; 14674 }); 14675 handleOkClicked = () => { 14676 const { isDataElementCompareMode, modificationValue, selectedValue } = this.state; 14677 const currentCloneableValue = isDataElementCompareMode ? modificationValue : selectedValue; 14678 let clone = currentCloneableValue ? (0, import_lodash.cloneDeep)(currentCloneableValue) : null; 14679 clone.actions && clone.actions.forEach((action) => { 14680 if (action && action.name === "replace" && action.params) action.params.forEac
14680h((p) => { 14681 if (p.value == null) p.value = ""; 14682 }); 14683 }); 14684 if (clone && clone.actions) clone.actions = clone.actions.filter((a) => a); 14685 !isDataElementCompareMode ? this.props.onChange(clone) : this.setState({ 14686 selectedValue: currentCloneableValue, 14687 modificationValue: null, 14688 blockClickOutside: false, 14689 currentComparableDataElementContentType: null, 14690 isDataElementCompareMode: false, 14691 pickedActionIndex: 0, 14692 pickedParamIndex: null 14693 }); 14694 }; 14695 handleCancelClicked = () => { 14696 this.props.onChange(this.props.value); 14697 }; 14698 handleDataElementComparedRemove = () => { 14699 this.removeSelectedValueDataElementParam(); 14700 }; 14701 handleRemoveClicked = () => { 14702 const { isDataElementCompareMode } = this.state; 14703 return isDataElementCompareMode ? this.handleDataElementComparedRemove() : this.props.onChange(null); 14704 }; 14705 handleRemoveSelectedItem = () => { 14706 this.setState({ selectedValue: null }); 14707 }; 14708 setValueSetSelected = (value) => { 14709 let actionableData = this.props.valueSet.find((actionableData) => actionableData.name === value.name); 14710 this.props.onChange(actionableData); 14711 }; 14712 setPlaceholderSelected = (placeholder) => { 14713 let obj = { 14714 ...placeholder, 14715 displayName: placeholder.name, 14716 refName: placeholder.name, 14717 mediaType: LOGIC_MEDIA_TYPES.String 14718 }; 14719 if (placeholder.groupId) obj.path = `${placeholder.groupId}.${placeholder.name}.value`; 14720 return this.props.onChange(obj); 14721 }; 14722 setAssetSelected = (asset) => { 14723 let mediaType = asset.mediaType || asset.type; 14724 let dataType = asset.type === "animation" ? LOGIC_DATA_TYPES.Animation : LOGIC_DATA_TYPES.Asset; 14725 this.props.onChange(buildActionableData(asset.name, mediaType, dataType)); 14726 }; 14727 setDataElementSelected = (dataElement) => { 14728 let obj = buildActionableData({ 14729 id: getDataElementId(dataElement), 14730 mediaType: dataElement.type, 14731 dataType: LOGIC_DATA_TYPES.DataElement 14732 }); 14733 if (this.props.selectOnClick) return this.props.onChange(obj); 14734 if (this.state.isDataElementCompareMode) this.setSelectedValueDataElementParam(this.state.modificationValue, obj, dataElement.displayName); 14735 else this.setState({ selectedValue: obj }); 14736 }; 14737 setSelectedValueDataElementParam = (modificationValue, actionableDataForParam, dataElementDisplayName) => { 14738 let modificationValueClone = (0, import_lodash.cloneDeep)(modificationValue); 14739 if (modificationValueClone && modificationValueClone.hasOwnProperty("id")) { 14740 let initialSelectedValueType; 14741 switch (actionableDataForParam.mediaType) { 14742 case DataElementContentTypes.Date: 14743 initialSelectedValueType = VLX_PARAMTYPE.Date; 14744 break; 14745 case DataElementContentTypes.Number: 14746 initialSelectedValueType = VLX_PARAMTYPE.Numeric; 14747 break; 14748 case DataElementContentTypes.String: 14749 initialSelectedValueType = VLX_PARAMTYPE.String; 14750 break; 14751 } 14752 const { pickedActionIndex, pickedParamIndex } = this.state; 14753 const paramIndex = Number.isInteger(pickedParamIndex) ? pickedParamIndex : this.findParamIndexByType(modificationValueClone, pickedActionIndex, initialSelectedValueType); 14754 modificationValueClone.actions[pickedActionIndex].params[paramIndex] = actionableDataForParam; 14755 modificationValueClone.actions[pickedActionIndex].params[paramIndex].displayName = dataElementDisplayName; 14756 this.setState({ 14757 selectedValue: modificationValueClone, 14758 modificationValue: null, 14759 currentComparableDataElementContentType: null, 14760 isDataElementCompareMode: false 14761 }); 14762 } 14763 }; 14764 getSelectedValueDataElementParam = (pickedActionIndex, pickedParamIndex) => { 14765 const { selectedValue } = this.state; 14766 if (selectedValue && selectedValue.hasOwnProperty("id")) { 14767 const paramIndex = Number.isInteger(pickedParamIndex) ? pickedParamIndex : this.findParamIndexByType(selectedValue, pickedActionIndex, null); 14768 return selectedValue.actions[pickedActionIndex].params[paramIndex]; 14769 } 14770 return null; 14771 }; 14772 getDefaultComparedParamValue = (modificationValue, pickedActionIndex, pickedParamIndex) => { 14773 return this.actions.find(({ name }) => name === modificationValue.actions[pickedActionIndex].name).params[pickedParamIndex]; 14774 }; 14775 removeSelectedValueDataElementParam = () => { 14776 const { currentComparableDataElementContentType } = this.state; 14777 let defaultComparedParamValue; 14778 switch (currentComparableDataElementContentType) { 14779 case DataElementContentTypes.Date: 14780 defaultComparedParamValue = { 14781 type: VLX_PARAMTYPE.Date, 14782 text: "toDate" 14783 }; 14784 break; 14785 case DataElementContentTypes.Number: 14786 defaultComparedParamValue = { 14787 type: VLX_PARAMTYPE.Numeric, 14788 text: "amount" 14789 }; 14790 break; 14791 default: 14792 defaultComparedParamValue = {}; 14793 break; 14794 } 14795 let modificationValueClone = (0, import_lodash.cloneDeep)(this.state.modificationValue); 14796 if (modificationValueClone && modificationValueClone.hasOwnProperty("id")) { 14797 const { pickedActionIndex, pickedParamIndex } = this.state; 14798 let paramIndex = this.findParamIndexByType(modificationValueClone, pickedActionIndex, null); 14799 if (Number.isInteger(pickedParamIndex)) { 14800 paramIndex = pickedParamIndex; 14801 defaultComparedParamValue = this.getDefaultComparedParamValue(modificationValueClone, pickedActionIndex, pickedParamIndex); 14802 } 14803 modificationValueClone.actions[pickedActionIndex].params[paramIndex] = defaultComparedParamValue; 14804 modificationValueClone.actions.splice(pickedActionIndex + 1, modificationValueClone.actions.length); 14805 this.setState({ 14806 selectedValue: modificationValueClone, 14807 modificationValue: null, 14808 currentComparableDataElementContentType: null, 14809 isDataElementCompareMode: false 14810 }); 14811 } 14812 }; 14813 findParamIndexByType = (selectedValue, pickedActionIndex, initialSelectedValueType) => { 14814 const params = selectedValue.actions[pickedActionIndex].params; 14815 if (initialSelectedValueType) return params.findIndex((el) => el.type === initialSelectedValueType || el.type === LOGIC_DATA_TYPES.DataElement); 14816 return params.findIndex((el) => el.type === LOGIC_DATA_TYPES.DataElement); 14817 }; 14818 setTextElementSelected = (textElement) => { 14819 this.props.onChange(buildActionableData(textElement.name)); 14820 }; 14821 setMapTableSelected = (mapTableAsset) => { 14822 let obj = buildActionableData(mapTableAsset.name, LOGIC_DATA_TYPES.MappingTable, LOGIC_DATA_TYPES.MappingTable); 14823 if (this.props.selectOnClick) return this.onChange(obj); 14824 this.setState({ selectedValue: obj }); 14825 }; 14826 setPrioritizedListSelected = (prioritizedList) => { 14827 let obj = buildActionableData({ 14828 id: prioritizedList.id, 14829 displayName: prioritizedList.name, 14830 mediaType: LOGIC_TYPE.Prioritized, 14831 dataType: LOGIC_TYPE.Prioritized 14832 }); 14833 if (this.props.selectOnClick) return this.onChange(obj); 14834 this.setState({ selectedValue: obj }); 14835 }; 14836 setDataStructureSelected = (item) => { 14837 if (item.type === ASSET_TYPES.mappingTable) this.setMapTableSelected(item); 14838 else if (item.outputType === LOGIC_TYPE.Prioritized) this.setPrioritizedListSelected(item); 14839 }; 14840 footer = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PopupFooter, { 14841 handleOkClicked: this.handleOkClicked, 14842 handleCancelClicked: this.handleCancelClicked, 14843 enterKeyConfirms: true 14844 }); 14845 handleDeleteAction = (index) => { 14846 if (this.state.selectedValue.actions.length > index + 1) this.setState({ blockClickOutside: true }, () => { 14847 HubNotifications.confirm("Delete Action", "This will delete all following actions of the placeholder. Continue?", () => { 14848 this.deleteAction(index); 14849 this.setState({ blockClickOutside: false }); 14850 }, () => this.setState({ blockClickOutside: false })); 14851 }); 14852 else this.deleteAction(index); 14853 }; 14854 deleteAction = (index) => { 14855 let clone = { ...this.state.selectedValue }; 14856 if (index === 0) clone.actions = null; 14857 else clone.actions = [...clone.actions.slice(0, index)]; 14858 this.setState({ selectedValue: clone }); 14859 }; 14860 findActionCopy = (filter) => { 14861 let act = this.actions.find(filter); 14862 if (!act) return null; 14863 let actClone = { ...act }; 14864 actClone.params = actClone.params.map((i) => Object.assign({}, i)); 14865 actClone.input = actClone.input.slice(0); 14866 return actClone; 14867 }; 14868 handleActionSelected = (index, action) => { 14869 let clone = { 14870 ...this.state.selectedValue, 14871 actions: this.state.selectedValue.actions 14872 }; 14873 clone.actions[index] = this.findActionCopy((ac) => ac.name === action.value); 14874 this.setState({ selectedValue: clone }); 14875 }; 14876 handleAddActionClick = () => { 14877 let clone = { ...this.state.selectedValue }; 14878 clone.actions = clone.actions || []; 14879 clone.actions = [...clone.actions, null]; 14880 this.setState({ selectedValue: clone }); 14881 }; 14882 handleActionParameterChanged = (actionIdx, paramIdx, value) => { 14883 let clone = (0, import_lodash.cloneDeep)(this.state.selectedValue); 14884 let act = clone.actions[actionIdx]; 14885 if (!act) return; 14886 act.params[paramIdx].value = value !== "" ? value : void 0; 14887 this.setState({ selectedValue: clone }); 14888 }; 14889 handleMapTableItemSelected = (item) => { 14890 let clone = { ...this.state.selectedValue }; 14891 clone.mediaType = item.type; 14892 const tableName = getMappingTableNameFromValue(clone); 14893 clone.name = `${tableName}.${item.name}`; 14894 clone.id = `${tableName}.${item.id}`; 14895 this.setState({ selectedValue: clone }); 14896 }; 14897 handlePrioritizedListSlotSelected = (item) => { 14898 let clone = { 14899 ...this.state.selectedValue, 14900 ...item 14901 }; 14902 this.setState({ selectedValue: clone }); 14903 }; 14904 concatDataStructures = (dataStructuresList) => dataStructuresList.reduce((acc, item) => [...item || [], ...acc], []); 14905 getNumberOfTabs = () => [ 14906 this.getRelevantNonCreativeDataElements(this.props.dataElements), 14907 this.getRelevantCreativeDataElements(this.props.dataElements), 14908 this.props.assets, 14909 this.props.animations, 14910 this.getRelevantMappingTablesAndPrioritizedLists(this.props.mappingTables, this.props.prioritizedLists), 14911 this.props.valueSet, 14912 this.getRelevantPlaceholders(this.props.placeholders) 14913 ].filter((arr) => arr && arr.length).length; 14914 getMapTableTypeFromMediaType = (type) => { 14915 const { mediaType }
14915 = this.props; 14916 if ([ 14917 LOGIC_TYPE.Image, 14918 LOGIC_TYPE.Video, 14919 LOGIC_TYPE.Audio 14920 ].includes(mediaType)) return type === DATA_TABLE_OUTPUT_TYPES.Media ? DATA_TABLE_OUTPUT_TYPES.Media : DATA_TABLE_OUTPUT_TYPES.Url; 14921 if (mediaType === LOGIC_TYPE.Text) return DATA_TABLE_OUTPUT_TYPES.String; 14922 if (mediaType === LOGIC_TYPE.Color) return DATA_TABLE_OUTPUT_TYPES.Color; 14923 return "unknown_type"; 14924 }; 14925 isOutputSameAsMediaType = (output) => this.getMapTableTypeFromMediaType(output.type) === output.type || output.type.title && this.getMapTableTypeFromMediaType(output.type.title.toLowerCase()) === output.type.title.toLowerCase(); 14926 renderMapTableInputSelector = () => { 14927 const selectedMapTable = this.props.mappingTables.find((table) => table.name === this.state.selectedValue.name); 14928 let mapTableItems = []; 14929 if (selectedMapTable && selectedMapTable.mappingTableScheme && selectedMapTable.mappingTableScheme.outputs) mapTableItems = selectedMapTable.mappingTableScheme.outputs.filter((output) => output.type && (!this.props.mediaType || this.isOutputSameAsMediaType(output))).map((output) => { 14930 const type = output.type.title ? output.type.title.toLowerCase() : output.type; 14931 return { 14932 id: output.id, 14933 title: output.name, 14934 name: output.name, 14935 type 14936 }; 14937 }); 14938 const dataFieldsObj = this.getDataFields(this.props.assets, this.props.dataElements, this.props.mappingTables, this.props.prioritizedLists); 14939 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogicPopupContainer_default, { 14940 handleClickOutside: this.handleClickOutside, 14941 position: this.props.position, 14942 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 14943 title: "Data Table", 14944 "data-content-class-name": "map-table-entry-selection", 14945 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 14946 className: "logic-popup-remove-selected", 14947 onClick: this.handleRemoveClicked, 14948 "data-testid": "logic-popup-remove-selected" 14949 }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectedItemSection, { 14950 selectedValue: this.state.selectedValue, 14951 dataFields: dataFieldsObj, 14952 onSelectedItemRemoveClicked: this.handleRemoveSelectedItem, 14953 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 14954 "parent-class-name": "sub-title", 14955 children: "Choose table output:" 14956 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DataSelectionArea, { 14957 items: mapTableItems, 14958 className: "mapping-table", 14959 onRemove: this.handleRemoveClicked, 14960 onClick: this.handleMapTableItemSelected 14961 })] 14962 })] 14963 }) 14964 }); 14965 }; 14966 generatePrioritizedListSlotContentList = (prioritizedList, filterType) => { 14967 let prioritizedListPlaceholders = []; 14968 const _getPLContentObj = (prioritizedList, slotIdx, placeholder) => { 14969 const slotCharacter = mapNumToLetter(slotIdx); 14970 return { 14971 id: `${prioritizedList.id}---slot${slotCharacter}---${placeholder.name}`, 14972 name: `${prioritizedList.name} - Slot ${slotCharacter} - ${placeholder.name}`, 14973 path: `${prioritizedList.name}.slot${slotCharacter}.${placeholder.name}.value`, 14974 type: ActionableDataValueType.Variable 14975 }; 14976 }; 14977 prioritizedList.slots.forEach((slot, index) => { 14978 if (slot.placeholders) slot.placeholders.forEach((placeholder) => { 14979 if (placeholder.type === filterType) prioritizedListPlaceholders.push(_getPLContentObj(prioritizedList, index, placeholder)); 14980 }); 14981 else if (slot.type === filterType) prioritizedListPlaceholders.push(_getPLContentObj(prioritizedList, index, slot)); 14982 }); 14983 return prioritizedListPlaceholders; 14984 }; 14985 renderPrioritizedListInputSelector = () => { 14986 const selectedPrioritizedList = this.props.prioritizedLists && this.props.prioritizedLists.find((pl) => pl.id === this.state.selectedValue.id); 14987 let prioritizedListSlots = []; 14988 let prioritizedListPlaceholders = []; 14989 if (selectedPrioritizedList && selectedPrioritizedList.maxSlots) { 14990 if (!this.props.isInValue) prioritizedListSlots = Array.from({ length: selectedPrioritizedList.maxSlots }).map((_, index) => { 14991 return generateActionableData(selectedPrioritizedList, index); 14992 }); 14993 if (this.props.inputName === ADAVarName) prioritizedListPlaceholders = this.generatePrioritizedListSlotContentList(selectedPrioritizedList, this.props.mediaType); 14994 } 14995 const dataFieldsObj = this.getDataFields(this.props.assets, this.props.dataElements, this.props.mappingTables, this.props.prioritizedLists); 14996 const calcActionableDataTitle = (item) => { 14997 if (item.type === ActionableDataValueType.PrioritizedSlot) return `${selectedPrioritizedList.name} - Slot ${mapNumToLetter(item.slotIdx)}`; 14998 else return item.name; 14999 }; 15000 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogicPopupContainer_default, { 15001 handleClickOutside: this.handleClickOutside, 15002 position: this.props.position, 15003 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15004 title: "List", 15005 footer: this.footer, 15006 "data-content-class-name": "prioritized-list-entry-selection", 15007 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 15008 className: "logic-popup-remove-selected", 15009 onClick: this.handleRemoveClicked 15010 }
15010), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectedItemSection, { 15011 selectedValue: this.state.selectedValue, 15012 dataFields: dataFieldsObj, 15013 onSelectedItemRemoveClicked: this.handleRemoveSelectedItem, 15014 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 15015 "parent-class-name": "sub-title", 15016 children: "Choose Slot:" 15017 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DataSelectionArea, { 15018 items: prioritizedListSlots.concat(...prioritizedListPlaceholders), 15019 renderItem: calcActionableDataTitle, 15020 className: "prioritized-list", 15021 onRemove: this.handleRemoveClicked, 15022 onClick: this.handlePrioritizedListSlotSelected 15023 })] 15024 })] 15025 }) 15026 }); 15027 }; 15028 renderModifyElementPanel = () => { 15029 const dataFieldsObj = { 15030 assets: [...this.props.assets || [], ...this.props.mappingTables || []], 15031 dataElements: this.props.dataElements || [], 15032 prioritizedLists: this.props.prioritizedLists 15033 }; 15034 const { isDataElementCompareMode } = this.state; 15035 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogicPopupContainer_default, { 15036 handleClickOutside: this.handleClickOutside, 15037 position: this.props.position, 15038 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15039 footer: this.footer, 15040 title: "Choose data element", 15041 "data-content-class-name": "modify-data-element", 15042 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { 15043 className: "logic-popup-remove-selected", 15044 "data-testid": "logic-popup-remove-selected", 15045 onClick: !isDataElementCompareMode ? this.handleRemoveClicked : this.handleDataElementComparedRemove 15046 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ModifyDataElementPanel, { 15047 onRemoveSelectedItem: this.handleRemoveSelectedItem, 15048 selectedValue: this.state.selectedValue, 15049 onActionSelected: this.handleActionSelected, 15050 onDeleteAction: this.handleDeleteAction, 15051 onActionParameterChanged: this.handleActionParameterChanged, 15052 onAddActionClick: this.handleAddActionClick, 15053 dataFields: dataFieldsObj, 15054 onDataElementComparison: this.initiateDataElementComparison, 15055 isDataElementCompareMode 15056 })] 15057 }) 15058 }); 15059 }; 15060 generateTextElementsSelection = () => { 15061 return { 15062 items: this.props.textElements, 15063 className: "text-elements", 15064 itemIdentifier: "textElements", 15065 title: "Text Elements", 15066 onClick: this.setTextElementSelected, 15067 renderItem: (item) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconWithTooltip, { 15068 iconName: item.iconClass, 15069 tooltipText: toSentenceCase(item.title), 15070 title: item.title 15071 }) 15072 }; 15073 }; 15074 renderDataSelection = (settings) => { 15075 const { title, shortTitle, longTitle, addTextElements } = settings; 15076 const { isDataElementCompareMode } = this.state; 15077 const props = { 15078 ...settings, 15079 onRemove: this.handleRemoveClicked 15080 }; 15081 delete props.title; 15082 delete props.shortTitle; 15083 delete props.longTitle; 15084 const divTitle = title || (this.getNumberOfTabs() > 1 ? shortTitle : longTitle); 15085 if (addTextElements && this.props.textElements && this.props.textElements.length && !isDataElementCompareMode) props.textElements = this.generateTextElementsSelection(); 15086 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15087 title: divTitle, 15088 "data-content-class-name": props.className, 15089 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DataSelectionArea, { ...props }) 15090 }); 15091 }; 15092 initiateDataElementComparison = (dataElementContentType, isElementSelected, pickedActionIndex, pickedParamIndex) => { 15093 const { selectedValue } = this.state; 15094 this.setState({ 15095 selectedValue: !isElementSelected ? null : this.getSelectedValueDataElementParam(pickedActionIndex, pickedParamIndex), 15096 modificationValue: selectedValue, 15097 currentComparableDataElementContentType: dataElementContentType, 15098 isDataElementCompareMode: true, 15099 pickedActionIndex, 15100 pickedParamIndex 15101 }); 15102 }; 15103 sortItemsByField = (items, field) => { 15104 return items && items.slice().sort((item1, item2) => { 15105 let name1 = item1[field].toLowerCase(); 15106 let name2 = item2[field].toLowerCase(); 15107 return name1.localeCompare(name2); 15108 }); 15109 }; 15110 getRelevantPlaceholders = (placeholders) => { 15111 return this.props.inputName === ADAVarName ? placeholders : []; 15112 }; 15113 getRelevantNonCreativeDataElements = (dataElements) => { 15114 let relevantDataElements = filterDataElementsArrayByOrigin(dataElements, [ 15115 DataElementOrigins.Derived, 15116 DataElementOrigins.System, 15117 DataElementOrigins.Feed 15118 ]); 15119 if (this.state.currentComparableDataElementContentType) relevantDataElements = filterDataElementsArrayByType(relevantDataElements, [this.state.currentComparableDataElementContentType]); 15120 return relevantDataElements; 15121 }; 15122 getRelevantCreativeDataElements = (dataElements) => { 15123 return filterDataElementsArrayByOrigin(dataElements, [DataElementOrigins.Creative]).filter((cde) => cde.type !== CreativeDataElementContentTypes.Narration); 15124 }; 15125 getRelevantMappingTablesAndPrioritizedLists = (mappingTables, prioritizedLists) => { 15126 return this.state.isDataElementCompareMode ? [] : this.concatDataStructures([this.sortItems
15126ByField(mappingTables, "title"), this.sortItemsByField(prioritizedLists, "name")]); 15127 }; 15128 render() { 15129 const selected = this.state.selectedValue; 15130 if (selected && selected.type) { 15131 if (selected.type === LOGIC_DATA_TYPES.MappingTable && !getMappingTablePropertyFromValue(selected)) return this.renderMapTableInputSelector(); 15132 else if (selected.type === LOGIC_TYPE.Prioritized) return this.renderPrioritizedListInputSelector(); 15133 if (selected.type === LOGIC_DATA_TYPES.DataElement || selected.type === LOGIC_DATA_TYPES.MappingTable || selected.type === LOGIC_TYPE.PrioritizedSlot || selected.type === ActionableDataValueType.Variable || selected.slotPath) return this.renderModifyElementPanel(); 15134 } 15135 if (this.getNumberOfTabs() === 0) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogicPopupContainer_default, { 15136 handleClickOutside: this.handleClickOutside, 15137 position: this.props.position, 15138 children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15139 title: " No elements to show", 15140 className: "empty-content", 15141 children: ["ð³", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { children: "Try adding assets / data-elements on the panels to the right." })] 15142 }) 15143 }); 15144 let dataElements = this.getRelevantNonCreativeDataElements(this.props.dataElements); 15145 let creativeDataElements = this.getRelevantCreativeDataElements(this.props.dataElements); 15146 let placeholders = this.getRelevantPlaceholders(this.props.placeholders); 15147 let mappingTableAndPrioritizedLists = this.getRelevantMappingTablesAndPrioritizedLists(this.props.mappingTables, this.props.prioritizedLists); 15148 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(LogicPopupContainer_default, { 15149 handleClickOutside: this.handleClickOutside, 15150 selectedIndex: this.state.selectedValue ? 1 : 0, 15151 position: this.props.position, 15152 children: [ 15153 this.props.valueSet && !!this.props.valueSet.length && this.renderDataSelection({ 15154 items: this.props.valueSet.map((value) => { 15155 return { 15156 name: value.name, 15157 title: value.displayName 15158 }; 15159 }), 15160 className: "value-set", 15161 title: "Values", 15162 onClick: this.setValueSetSelected 15163 }), 15164 dataElements && !!dataElements.length && this.renderDataSelection({ 15165 items: this.sortItemsByField(dataElements, "displayName"), 15166 className: "data-elements", 15167 shortTitle: "Data Elements", 15168 longTitle: "Choose data element", 15169 itemIdentifier: "dataElement", 15170 onClick: this.setDataElementSelected, 15171 titleSelector: (item) => item.displayName, 15172 addTextElements: true, 15173 keySelector: (item) => item.id, 15174 renderItem: (item) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconWithTooltip, { 15175 iconName: item.type, 15176 tooltipText: toSentenceCase(item.type), 15177 title: item.displayName 15178 }) 15179 }), 15180 this.props.assets && !!this.props.assets.length && this.renderDataSelection({ 15181 items: this.sortItemsByField(this.props.assets, "title"), 15182 className: "assets", 15183 shortTitle: "Assets", 15184 longTitle: "Choose an asset", 15185 itemIdentifier: "asset-item", 15186 onClick: this.setAssetSelected, 15187 renderItem: (item) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconWithTooltip, { 15188 iconName: item.mediaType, 15189 tooltipText: toSentenceCase(item.mediaType), 15190 title: item.title 15191 }) 15192 }), 15193 this.props.animations && !!this.props.animations.length && this.renderDataSelection({ 15194 items: this.sortItemsByField(this.props.animations, "title"), 15195 className: "animations", 15196 shortTitle: "Animations", 15197 longTitle: "Choose an animation", 15198 itemIdentifier: "animation-item", 15199 onClick: this.setAssetSelected 15200 }), 15201 mappingTableAndPrioritizedLists && !!mappingTableAndPrioritizedLists.length && this.renderDataSelection({ 15202 items: mappingTableAndPrioritizedLists, 15203 className: "data-structures", 15204 title: "Data Structures", 15205 onClick: this.setDataStructureSelected, 15206 renderItem: (item) => { 15207 let outputType; 15208 let title; 15209 if (item.outputType === LOGIC_TYPE.Prioritized) { 15210 outputType = "prioritized-list"; 15211 title = item.name; 15212 } else if (item.type === ASSET_TYPES.mappingTable) { 15213 outputType = "data-table"; 15214 title = item.title; 15215 } 15216 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconWithTooltip, { 15217 iconName: outputType, 15218 tooltipText: toSentenceCase(outputType), 15219 title 15220 }); 15221 } 15222 }), 15223 placeholders && !!placeholders.length && this.renderDataSelection({
15224 items: this.sortItemsByField(this.props.placeholders, "name"), 15225 className: "placeholders", 15226 title: "Placeholders", 15227 itemIdentifier: "placeholder-item", 15228 onClick: this.setPlaceholderSelected, 15229 renderItem: (item) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconWithTooltip, { 15230 iconName: item.mediaType, 15231 tooltipText: toSentenceCase(item.mediaType), 15232 title: item.name 15233 }) 15234 }), 15235 creativeDataElements && !!creativeDataElements.length && this.renderDataSelection({ 15236 items: this.sortItemsByField(creativeDataElements, "displayName"), 15237 className: "creative-data-elements", 15238 shortTitle: "Content Set Data", 15239 longTitle: "Choose content set data", 15240 itemIdentifier: "dataElement", 15241 onClick: this.setDataElementSelected, 15242 titleSelector: (item) => item.displayName, 15243 addTextElements: true, 15244 keySelector: (item) => item.id, 15245 renderItem: (item) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(IconWithTooltip, { 15246 iconName: item.type, 15247 tooltipText: toSentenceCase(item.type), 15248 title: item.displayName 15249 }) 15250 }) 15251 ] 15252 }); 15253 } 15254}; 15255LogicDataSelector.defaultProps = { selectOnClick: false }; 15256LogicDataSelector.propTypes = { 15257 assets: import_prop_types.default.array, 15258 dataElements: import_prop_types.default.array, 15259 onChange: import_prop_types.default.func, 15260 value: import_prop_types.default.object, 15261 inputName: import_prop_types.default.string, 15262 actions: import_prop_types.default.arrayOf(import_prop_types.default.object), 15263 selectOnClick: import_prop_types.default.bool, 15264 handleClickOutside: import_prop_types.default.func.isRequired, 15265 animations: import_prop_types.default.array, 15266 mappingTables: import_prop_types.default.array, 15267 prioritizedLists: import_prop_types.default.array, 15268 placeholders: import_prop_types.default.array, 15269 mediaType: import_prop_types.default.string, 15270 textElements: import_prop_types.default.array, 15271 position: import_prop_types.default.shape({ 15272 x: import_prop_types.default.number, 15273 y: import_prop_types.default.number 15274 }), 15275 valueSet: import_prop_types.default.array, 15276 isInValue: import_prop_types.default.bool 15277}; 15278//#endregion 15279//#region client/components/legacyCommon/HubSemanticDropDown.jsx 15280var HubSemanticDropDown = class extends import_react.Component { 15281 onClick = (item, index) => { 15282 this.props.onChange && this.props.onChange(item, index); 15283 this.props.items[index].onChange && this.props.items[index].onChange(index); 15284 }; 15285 render() { 15286 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown, { 15287 defaultOpen: this.props.defaultOpen, 15288 text: this.props.value, 15289 icon: this.props.icon, 15290 className: `hub-semantic-drop-down ${this.props.className ? this.props.className : ""}`, 15291 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown.Menu, { children: this.props.items && this.props.items.map((item, index) => item === "divider" ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown.Divider, {}, index) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dropdown.Item, { 15292 onClick: () => this.onClick(item, index), 15293 text: item.title ? item.title : item.name ? item.name.toString() : item.name, 15294 name: valueExists(item.name) ? item.name.toString() : item.name, 15295 content: item.content, 15296 disabled: item.disabled, 15297 active: item.content === this.props.value 15298 }, index)) }) 15299 }); 15300 } 15301}; 15302HubSemanticDropDown.defaultProps = { defaultOpen: false }; 15303HubSemanticDropDown.propTypes = { 15304 items: import_prop_types.default.arrayOf(import_prop_types.default.oneOfType([import_prop_types.default.string, import_prop_types.default.shape({ 15305 disabled: import_prop_types.default.bool, 15306 title: import_prop_types.default.string, 15307 name: import_prop_types.default.oneOfType([import_prop_types.default.string, import_prop_types.default.bool]), 15308 content: import_prop_types.default.object, 15309 onChange: import_prop_types.default.func 15310 })])), 15311 icon: import_prop_types.default.element, 15312 onChange: import_prop_types.default.func, 15313 value: import_prop_types.default.string, 15314 defaultOpen: import_prop_types.default.bool, 15315 className: import_prop_types.default.string 15316}; 15317//#endregion 15318//#region client/logic/MappingTables/MappingTablesUtils.ts 15319var MappingTablesUtils = class MappingTablesUtils { 15320 static { 15321 this.extractMappingTablesFromAssets = (assets) => { 15322 return assets.filter((asset) => asset.type === AssetTypes.mappingTable); 15323 }; 15324 } 15325 static { 15326 this.findMappingTableByID = (mappingTableId, mappingTablesArray) => { 15327 return mappingTablesArray.find((MappingTable) => { 15328 return mappingTableId === MappingTable.assetId; 15329 }); 15330 }; 15331 } 15332 static { 15333 this.getTitleFromType = (type) => { 15334 for (let key in CELL) if (type === CELL[key].cellType) return CELL[key].title; 15335 }; 15336 } 15337 static { 15338 this.getTypeFromTitle = (title) => { 15339 for (let key in CELL) if (title === CELL[key].title) return CELL[key].cellType; 15340 }; 15341 } 15342 static { 15343 this.getCharFromType = (type) => { 15344 for (let key in CELL) if (type === CELL[key].cellType) return CELL[key].char; 15345 return ""; 15346 }; 15347 } 15348 static { 15349 this.fetchData = (mappingTable, isStageView, downloadFromRESTAction) => { 15350 const url = AssetUtils.getDownloadUrl(mappingTable, isStageView); 15351 if (MappingTablesUtils.isDirectUrl(url)) return fetch(url).then((res) => res.json()); 15352 else return new Promise((resolve) => { 15353 downloadFromRESTAction(url, (mappingTableData) => { 15354 resolve(mappingTableData); 15355 }); 15356 }); 15357 }; 15358 } 15359 static isDirectUrl(url) { 15360 return !url.startsWith("/rest/"); 15361 } 15362}; 15363//#endregion 15364//#region client/components/legacyCommon/ComponentLibrary/StylePicker/StylePicker.tsx 15365init_es$1(); 15366var StylePicker = class extends import_react.Component { 15367 constructor(..._args) { 15368 super(..._args); 15369 this.state = { selectedTint: "Tint1" }; 15370 this.onTintChange = (color, selectedTint) => { 15371 if (this.props.singleMode) this.props.onChange(color.hex); 15372 else if (selectedTint === "Tint2") this.props.onChange({ 15373 ...this.props.style, 15374 Tint2: color.hex 15375 }); 15376 else this.props.onChange({ 15377 ...this.props.style, 15378 Tint1: color.hex 15379 }); 15380 }; 15381 this.onRatioChange = (evt, value) => { 15382 const updatedRatio = mapRange(value.x, 0, 188, 0, 1); 15383 this.props.onChange({ 15384 ...this.props.style, 15385 Ratio: updatedRatio 15386 }); 15387 }; 15388 this.handleTabChange = (evt, selectedTabId) => { 15389 const updatedStyle = { 15390 ...this.props.style, 15391 IsOneTint: !selectedTabId 15392 }; 15393 this.props.onChange(updatedStyle); 15394 }; 15395 this.selectTint = (tintName) => { 15396 this.setState({ selectedTint: tintName }); 15397 };
15398 this.getSelectedTab = (style) => style.IsOneTint ? 0 : 1; 15399 this.renderColorPicker = (style, selectedTint) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15400 className: "color-picker", 15401 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Sketch_default, { 15402 className: "disable-box-shadow", 15403 color: style[selectedTint] || style, 15404 onChange: (evt) => this.onTintChange(evt, selectedTint), 15405 disableAlpha: true, 15406 presetColors: [], 15407 width: "200" 15408 }) 15409 }); 15410 this.renderSolidTab = () => { 15411 const { style } = this.props; 15412 const { selectedTint } = this.state; 15413 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15414 className: "tab-content", 15415 children: [!this.props.singleMode && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "grad-holder" }), this.renderColorPicker(style, selectedTint)] 15416 }); 15417 }; 15418 this.renderGradientTab = () => { 15419 const { selectedTint } = this.state; 15420 let { style } = this.props; 15421 style = style; 15422 const gradBg = inlineColor(style); 15423 const sliderPosition = { 15424 x: mapRange(style.Ratio, 0, 1, 0, 188), 15425 y: 0 15426 }; 15427 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15428 className: "tab-content", 15429 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15430 className: "grad-holder", 15431 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15432 className: "tints", 15433 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15434 className: `single-tint${selectedTint === "Tint1" ? " selected" : ""}`, 15435 style: { backgroundColor: style.Tint1 }, 15436 onClick: () => { 15437 this.selectTint("Tint1"); 15438 } 15439 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15440 className: `single-tint${selectedTint === "Tint2" ? " selected" : ""}`, 15441 style: { backgroundColor: style.Tint2 }, 15442 onClick: () => { 15443 this.selectTint("Tint2"); 15444 } 15445 })] 15446 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15447 className: "slider", 15448 style: { background: gradBg }, 15449 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Rnd, { 15450 default: sliderPosition, 15451 bounds: "parent", 15452 enableResizing: false, 15453 onDragStop: this.onRatioChange, 15454 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "slider-draggable" }) 15455 }) 15456 })] 15457 }), this.renderColorPicker(style, selectedTint)] 15458 }); 15459 }; 15460 this.renderTabs = () => [{ 15461 id: 0, 15462 label: "SOLID", 15463 disabled: false, 15464 render: this.renderSolidTab 15465 }, { 15466 id: 1, 15467 label: "GRADIENT", 15468 disabled: false, 15469 render: this.renderGradientTab 15470 }]; 15471 } 15472 render() { 15473 const { style } = this.props; 15474 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15475 className: "style-picker", 15476 children: [this.props.singleMode && this.renderSolidTab(), !this.props.singleMode && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyTabs, { 15477 tabClassName: "tab-single", 15478 tabs: this.renderTabs(), 15479 selectedTabId: this.getSelectedTab(style), 15480 handleChange: this.handleTabChange 15481 })] 15482 }); 15483 } 15484}; 15485//#endregion 15486//#region client/components/HubEditor/logic/StylePreview.tsx 15487var import_classnames = /* @__PURE__ */ __toESM(require_classnames()); 15488var initialStyle = { 15489 IsOneTint: true, 15490 Tint1: "#000000", 15491 Tint2: "#7F7F7F", 15492 Ratio: .5 15493}; 15494var StylePreview = class extends import_react.Component { 15495 constructor(..._args) { 15496 super(..._args); 15497 this.getStyleForState = () => { 15498 if (styleIsEmpty(this.props.style)) return { ...initialStyle }; 15499 else if (typeof this.props.style === "object") return { ...this.props.style }; 15500 else return this.props.style; 15501 }; 15502 this.state = { 15503 anchorEl: null, 15504 currentStyle: this.getStyleForState() 15505 }; 15506 this.handleOpenPicker = (evt) => { 15507 this.setState({ anchorEl: evt.currentTarget }); 15508 }; 15509 this.handleClosePicker = (evt) => { 15510 evt.stopPropagation(); 15511 this.props.onChange(this.state.currentStyle); 15512 this.setState({ anchorEl: null }); 15513 }; 15514 this.handleStyleChange = (style) => { 15515 let updatedStyle; 15516 if (this.props.singleMode) updatedStyle = style; 15517 else updatedStyle = { ...style }; 15518 this.setState({ currentStyle: updatedStyle }); 15519 }; 15520 this.renderPickerPopoverContent = () => { 15521 const { popoverClassName, singleMode } = this.props; 15522 const { anchorEl, currentStyle } = this.state; 15523 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyPopover, { 15524 open: Boolean(anchorEl), 15525 anchor: anchorEl, 15526 onClose: this.handleClosePicker, 15527 paperProps: { className: (0, import_classnames.default)("style-picker-popover", popoverClassName) }, 15528 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StylePicker, { 15529 style: currentStyle, 15530 onChange: this.handleStyleChange, 15531 singleMode 15532 }) 15533 }); 15534 }; 15535 } 15536 componentDidUpdate(prevProps, prevState, snapshot) { 15537 const _arePrimitiveObjectsIdentical = (obj1, obj2) => Object.keys(obj1).every((prop) => obj2[prop] === obj1[prop]); 15538 if (prevProps.style !== this.props.style || this.props.style && prevProps.style && typeof this.props.style === "object" && typeof prevProps.style === "object" && !_arePrimitiveObjectsIdentical(prevProps.style, this.props.style)) this.setState({ currentStyle: this.get
15538StyleForState() }); 15539 } 15540 render() { 15541 const { readOnly, style, disablePopover } = this.props; 15542 const { currentStyle } = this.state; 15543 const isClickable = readOnly === false || disablePopover === false; 15544 if (styleIsEmpty(style)) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15545 className: (0, import_classnames.default)("style-preview", { clickable: isClickable }, "no-style"), 15546 onClick: this.handleOpenPicker, 15547 children: !readOnly && !disablePopover && this.renderPickerPopoverContent() 15548 }); 15549 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15550 className: (0, import_classnames.default)("style-preview", { clickable: isClickable }), 15551 style: { background: inlineColor(currentStyle) }, 15552 onClick: this.handleOpenPicker, 15553 children: !readOnly && !disablePopover && this.renderPickerPopoverContent() 15554 }); 15555 } 15556}; 15557var StyledSskyFab = (0, require_material().styled)(import_Components.SskyFab)` 15558 z-index: 1; 15559`; 15560var HubAddActionButton = (props) => { 15561 const placement = props.tooltipPlacement || "bottom"; 15562 let btn = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StyledSskyFab, { 15563 className: "add-action-btn", 15564 dataTestId: props.dataTestId, 15565 onClick: props.onClick, 15566 icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(FontAwesomeIcon, { 15567 icon: ["far", "plus"], 15568 style: { fontSize: "18px" } 15569 }) 15570 }); 15571 if (props.tooltip) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyTooltip, { 15572 title: props.tooltip, 15573 placement, 15574 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 15575 "data-tracking-id": props.dataTrackingId, 15576 children: btn 15577 }) 15578 }); 15579 else return btn; 15580}; 15581//#endregion 15582//#region client/components/HubEditor/rightPanels/HubMappingTableData.tsx 15583var import_dist$3 = /* @__PURE__ */ __toESM(require_dist$4()); 15584var HubMappingTableData = class extends import_react.Component { 15585 constructor(props) { 15586 super(props); 15587 this.handleClickOutside = () => { 15588 this.setState({ showDataElementsPopUp: false }); 15589 }; 15590 this.handleAssetClickOutside = (rowIndex, index) => { 15591 let { rows } = this.state; 15592 rows[rowIndex].cells[index].showAssetsPopUp = false; 15593 this.setState({ 15594 rows, 15595 showDataElementsPopUp: false 15596 }); 15597 }; 15598 this.onInputHeaderClicked = () => { 15599 this.setState({ showDataElementsPopUp: true }); 15600 }; 15601 this.onDataElementsChange = (item) => { 15602 this.setState({ showDataElementsPopUp: false }); 15603 this.props.onInputHeaderChange(item); 15604 }; 15605 this.onAssetCellClicked = (index, rowIndex) => { 15606 let { rows } = this.state; 15607 rows[rowIndex].cells[index].showAssetsPopUp = true; 15608 this.setState({ rows }); 15609 }; 15610 this.onAssetChange = (item, index, rowIndex) => { 15611 let { rows } = this.state; 15612 rows[rowIndex].cells[index].showAssetsPopUp = false; 15613 this.props.onCellChanged(item, index, rowIndex, CELL.Media.cellType); 15614 this.setState({ rows }); 15615 }; 15616 this.rowContextMenu = (e) => { 15617 e.preventDefault(); 15618 e.stopPropagation(); 15619 this.setState({ 15620 rowPopUpAnchor: e.target, 15621 rowIndex: parseInt(e.target.id) 15622 }); 15623 }; 15624 this.onRowAddAbove = () => { 15625 this.props.onRowAdd(this.state.rowIndex); 15626 this.handleRowPopUpClose(); 15627 }; 15628 this.onRowAddBelow = () => { 15629 this.props.onRowAdd(this.state.rowIndex + 1); 15630 this.handleRowPopUpClose(); 15631 }; 15632 this.onRowRemove = () => { 15633 HubNotifications.confirm("Remove Row", "Are you sure you want to remove the row?", () => { 15634 this.props.onRowRemove(this.state.rowIndex); 15635 this.handleRowPopUpClose(); 15636 }); 15637 }; 15638 this.onRowClear = () => { 15639 HubNotifications.confirm("Clear Row", "Are you sure you want to clear the row?", () => { 15640 this.props.onRowClear(this.state.rowIndex); 15641 this.handleRowPopUpClose(); 15642 }); 15643 }; 15644 this.headerContextMenu = (e) => { 15645 e.preventDefault(); 15646 e.stopPropagation(); 15647 this.setState({ 15648 headerPopUpAnchor: e.target, 15649 headerIndex: parseInt(e.target.id) 15650 }); 15651 }; 15652 this.onOutputColumnAddAfter = () => { 15653 this.props.onOutputColumnAdd(this.state.headerIndex + 1); 15654 this.handleHeaderPopUpClose(); 15655 }; 15656 this.onOutputColumnAddBefore = () => { 15657 this.props.onOutputColumnAdd(this.state.headerIndex); 15658 this.handleHeaderPopUpClose(); 15659 }; 15660 this.onOutputColumnRemove = () => { 15661 HubNotifications.confirm("Remove Column", "Are you sure you want to remove the column?", () => { 15662 this.props.onOutputColumnRemove(this.state.headerIndex); 15663 this.handleHeaderPopUpClose(); 15664 }); 15665 }; 15666 this.onOutputColumnClear = () => { 15667 HubNotifications.confirm("Clear Column", "Are you sure you want to clear the column?", () => { 15668 this.props.onOutputColumnClear(this.state.headerIndex); 15669 this.handleHeaderPopUpClose(); 15670 }); 15671 }; 15672 this.handleHeaderPopUpClose = () => { 15673 this.setState({ 15674 headerPopUpAnchor: null, 15675 headerIndex: -1 15676 }); 15677 }; 15678 this.handleRowPopUpClose = () => { 15679 this.setState({ 15680 rowPopUpAnchor: null, 15681 rowIndex: -1 15682 }); 15683 }; 15684 this.renderInputHeaders = (header, index) => { 15685 const displayName = getDataElementDisplayName((this.props.dataElements || []).find((de) => getDataElementId(de) === getDataElementId(header.value))) || header.value.name || header.value.id; 15686 let headerStyle = { 15687 padding: "5px 11px", 15688 backgroundColor: "#F2FBFD" 15689 }; 15690 let inputHeaderClassName = header.missing ? "missingDataElement" : "dataElement";
15691 if (this.props.isViewOnly) inputHeaderClassName += " read-only"; 15692 let content = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15693 className: "inputHeader", 15694 children: [ 15695 header.missing && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_dist$3.default, { 15696 id: "tooltip_" + index, 15697 delayShow: 100, 15698 place: "top", 15699 effect: "solid" 15700 }), 15701 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15702 className: inputHeaderClassName, 15703 onClick: this.onInputHeaderClicked, 15704 "data-for": "tooltip_" + index, 15705 "data-tip": "Missing Data Element", 15706 children: displayName 15707 }), 15708 this.state.showDataElementsPopUp && !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogicDataSelector, { 15709 dataElements: this.props.dataElements, 15710 value: header.value, 15711 selectOnClick: true, 15712 onChange: this.onDataElementsChange, 15713 handleClickOutside: this.handleClickOutside 15714 }) 15715 ] 15716 }); 15717 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.HeaderCell, { 15718 style: headerStyle, 15719 content 15720 }, index); 15721 }; 15722 this.renderOutputHeaders = (header, index) => { 15723 let headerStyle = { 15724 padding: "5px 11px", 15725 backgroundColor: "#F2FBFD" 15726 }; 15727 let outputHeadersTypes;
15728 if (this.props.isViewOnly) outputHeadersTypes = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15729 className: "col-xs-2 outputHeaderType read-only", 15730 children: this.props.outputHeaders[index].type ? this.props.outputHeaders[index].type.name : "?" 15731 }); 15732 else { 15733 let ddItems = [{ 15734 name: CELL.String.char, 15735 title: CELL.String.title, 15736 id: index 15737 }, { 15738 name: CELL.Media.char, 15739 title: CELL.Media.title, 15740 id: index 15741 }]; 15742 ddItems.push({ 15743 name: CELL.Color.char, 15744 title: CELL.Color.title, 15745 id: index 15746 }); 15747 ddItems.push({ 15748 name: CELL.URL.char, 15749 title: CELL.URL.title, 15750 id: index 15751 }); 15752 outputHeadersTypes = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubSemanticDropDown, { 15753 className: "col-xs-2 outputHeaderType", 15754 value: this.props.outputHeaders[index].type ? this.props.outputHeaders[index].type.name : "?", 15755 items: ddItems, 15756 onChange: this.props.onOutputTypeChange 15757 }); 15758 } 15759 let content = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15760 className: "outputHeader row", 15761 children: [ 15762 outputHeadersTypes, 15763 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 15764 id: index.toString(), 15765 className: "col-xs-9 outputHeaderValue", 15766 value: header.text, 15767 placeholder: "Enter Text", 15768 onConfirm: this.props.onOutputHeaderChange,
15769 disabled: this.props.isViewOnly 15770 }), 15771 !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15772 id: index, 15773 className: "col-xs-1 headerContextMenuIcon", 15774 onClick: this.headerContextMenu 15775 }) 15776 ] 15777 }); 15778 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.HeaderCell, { 15779 style: headerStyle, 15780 content 15781 }, index); 15782 }; 15783 this.renderInputCell = (index, rowIndex, cell) => { 15784 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Cell, { 15785 style: { background: "white" }, 15786 children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 15787 id: rowIndex.toString() + "/" + index.toString(), 15788 className: "dataCell", 15789 value: cell.text, 15790 onConfirm: (value) => this.props.onCellChanged(value, index, rowIndex), 15791 disabled: this.props.isViewOnly 15792 }) 15793 }, index); 15794 }; 15795 this.renderStringCell = (index, rowIndex, cell, type) => { 15796 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Cell, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 15797 id: rowIndex.toString() + "/" + index.toString(), 15798 className: "dataCell", 15799 value: cell.text, 15800 onConfirm: (value) => this.props.onCellChanged(value, index, rowIndex, type),
15801 disabled: this.props.isViewOnly 15802 }) }, index); 15803 }; 15804 this.renderMediaCell = (index, rowIndex, cell) => { 15805 let assets = this.props.assets.filter((asset) => asset.type === ASSET_TYPES.curated && (asset.mediaType === CURATED_ASSETS_MEDIA_TYPES.Video || asset.mediaType === CURATED_ASSETS_MEDIA_TYPES.Image || asset.mediaType === CURATED_ASSETS_MEDIA_TYPES.Audio) && !asset.deleted && !asset.archived); 15806 if (!cell.missing && !assets.find((asset) => asset.name === cell.value.name)) cell.missing = true; 15807 let assetTitle = getAssetTitleFromName(cell.value.name, assets); 15808 let content = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15809 className: cell.missing ? "missingAssetCell" : "assetCell", 15810 children: [ 15811 assetTitle, 15812 !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 15813 className: "icon ellipsis", 15814 onClick: () => this.onAssetCellClicked(index, rowIndex) 15815 }), 15816 cell.showAssetsPopUp && !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LogicDataSelector, { 15817 assets, 15818 value: cell.value, 15819 onChange: (item) => this.onAssetChange(item, index, rowIndex), 15820 handleClickOutside: () => this.handleAssetClickOutside(rowIndex, index) 15821 }) 15822 ] 15823 }); 15824 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Cell, { content }, index); 15825 }; 15826 this.renderColorCell = (index, rowIndex, cell) => { 15827 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Cell, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(StylePreview, { 15828 style: cell.color,
15829 readOnly: this.props.isViewOnly, 15830 onChange: (value) => this.props.onCellChanged(value, index, rowIndex, CELL.Color.cellType) 15831 }) }, index); 15832 }; 15833 this.renderIndexCell = (rowIndex) => { 15834 let cellStyle = { 15835 backgroundColor: "#F2FBFD", 15836 color: "#777777", 15837 fontWeight: 500, 15838 padding: 0, 15839 textAlign: "center", 15840 minWidth: "40px" 15841 }; 15842 let content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { 15843 id: rowIndex, 15844 className: "indexCell", 15845 onContextMenu: this.rowContextMenu, 15846 children: parseInt(rowIndex) + 1 15847 }); 15848 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Cell, { 15849 content, 15850 style: cellStyle 15851 }, rowIndex + "_cell"); 15852 }; 15853 this.headerPopUpItems = [ 15854 { 15855 content: "Add column before", 15856 onClick: this.onOutputColumnAddBefore 15857 }, 15858 { 15859 content: "Add column after", 15860 onClick: this.onOutputColumnAddAfter 15861 }, 15862 { 15863 content: "Clear column", 15864 onClick: this.onOutputColumnClear 15865 }, 15866 { 15867 content: "Remove column", 15868 onClick: this.onOutputColumnRemove 15869 } 15870 ]; 15871 this.rowPopUpItems = [ 15872 { 15873 content: "Insert row above", 15874 onClick: this.onRowAddAbove 15875 }, 15876 { 15877 content: "Insert row below", 15878 onClick: this.onRowAddBelow 15879 }, 15880 { 15881 content: "Clear row", 15882 onClick: this.onRowClear 15883 }, 15884 { 15885 content: "Remove row", 15886 onClick: this.onRowRemove 15887 } 15888 ]; 15889 this.state = { 15890 rows: props.rows, 15891 rowPopUpAnchor: null, 15892 rowIndex: -1, 15893 headerPopUpAnchor: null, 15894 headerIndex: -1, 15895 showDataElementsPopUp: void 0 15896 }; 15897 } 15898 UNSAFE_componentWillReceiveProps(nextProps) { 15899 let { rows } = this.state; 15900 if (this.props.rows !== nextProps.rows) rows = nextProps.rows; 15901 this.setState({ rows }); 15902 } 15903 render() { 15904 let inputHeaders = this.props.inputHeaders.map((header, index) => { 15905 return this.renderInputHeaders(header, index); 15906 }); 15907 let outputHeaders = this.props.outputHeaders.map((header, index) => { 15908 return this.renderOutputHeaders(header, index); 15909 }); 15910 let rows = this.state.rows.map((row, rowIndex) => { 15911 let cells = row.cells.map((cell, index) => { 15912 if (index === 0) return this.renderInputCell(index, rowIndex, cell); 15913 const outputHeaderIndex = index - 1; 15914 const { type } = this.props.outputHeaders[outputHeaderIndex]; 15915 if (type) { 15916 const cellType = MappingTablesUtils.getTypeFromTitle(type.title);
15917 if (cellType === CELL.String.cellType || cellType === CELL.URL.cellType) return this.renderStringCell(index, rowIndex, cell, cellType); 15918 else if (cellType === CELL.Media.cellType) return this.renderMediaCell(index, rowIndex, cell); 15919 else if (cellType === CELL.Color.cellType) return this.renderColorCell(index, rowIndex, cell); 15920 } 15921 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Cell, {}, index); 15922 }); 15923 cells.splice(0, 0, this.renderIndexCell(rowIndex)); 15924 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Row, { children: cells }, rowIndex); 15925 }); 15926 let cellsCount = this.state.rows[0].cells.length.toString(); 15927 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 15928 className: "hubMappingTableData", 15929 children: [ 15930 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table, { 15931 celled: true, 15932 structured: true, 15933 className: "mappingTable", 15934 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table.Header, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table.Row, { children: [ 15935 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.HeaderCell, { 15936 style: { backgroundColor: "#F2FBFD" }, 15937 rowSpan: "2" 15938 }), 15939 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.HeaderCell, { 15940 style: { 15941 backgroundColor: "#F2FBFD", 15942 color: "#777777", 15943 fontSize: "12px", 15944 fontWeight: 700 15945 }, 15946 children: "input" 15947 }), 15948 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table.HeaderCell, { 15949 style: { 15950 backgroundColor: "#F2FBFD", 15951 color: "#777777", 15952 fontSize: "12px", 15953 fontWeight: 700 15954 }, 15955 colSpan: cellsCount, 15956 children: ["output", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { 15957 style: { 15958 color: "#D72828", 15959 fontWeight: 500, 15960 fontSize: "12px", 15961 lineHeight: "14px", 15962 marginLeft: "17px" 15963 }, 15964 children: this.props.outputHeadersValidation.some((validation) => !validation.result) ? "Enter column type & name" : "" 15965 })] 15966 }) 15967 ] }
15967), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table.Row, { children: [inputHeaders, outputHeaders] })] }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Table.Body, { children: rows })] 15968 }), 15969 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyMenu, { 15970 open: Boolean(this.state.headerPopUpAnchor), 15971 anchor: this.state.headerPopUpAnchor, 15972 onClose: this.handleHeaderPopUpClose, 15973 items: this.headerPopUpItems 15974 }), 15975 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyMenu, { 15976 open: Boolean(this.state.rowPopUpAnchor), 15977 anchor: this.state.rowPopUpAnchor, 15978 onClose: this.handleRowPopUpClose, 15979 items: this.rowPopUpItems 15980 }), 15981 !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubAddActionButton, { 15982 onClick: () => this.props.onRowAdd(this.state.rows.length), 15983 tooltip: "Add row", 15984 dataTestId: "dataTable-add-row" 15985 }) 15986 ] 15987 }); 15988 } 15989}; 15990//#endregion 15991//#region client/components/legacyCommon/HubSpinner.tsx 15992var import_lib$2 = /* @__PURE__ */ __toESM(require_lib$1()); 15993var HubSpinner = (props) => { 15994 const [isRendered, setRendered] = (0, import_react.useState)(!props.delay); 15995 (0, import_react.useEffect)(() => { 15996 if (!isRendered) { 15997 const timeoutId = setTimeout(() => setRendered(true), props.delay || 0); 15998 return () => clearTimeout(timeoutId); 15999 } 16000 }, []); 16001 if (!isRendered) return null; 16002 const size = Math.min(props.width, props.height); 16003 const progress = typeof props.progress === "number" ? (0, import_numeral.default)(props.progress / 100).format("0.0%") : void 0; 16004 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react.Fragment, { children: [progress && /* @__P
16004URE__ */ (0, import_jsx_runtime.jsxs)("div", { 16005 className: "spinner-progress", 16006 style: { color: props.spinnerColor }, 16007 children: [" ", progress] 16008 }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_lib$2.default, { 16009 size, 16010 spinnerColor: props.spinnerColor, 16011 spinnerWidth: props.spinnerWidth, 16012 visible: props.show 16013 })] }); 16014}; 16015//#endregion 16016//#region client/components/HubEditor/rightPanels/HubMappingTable.tsx 16017var import_lib$1 = /* @__PURE__ */ __toESM(require_lib$2()); 16018var CELL = { 16019 String: { 16020 cellType: DATA_TABLE_OUTPUT_TYPES.String, 16021 title: "String", 16022 cellKey: "text", 16023 defaultValue: () => "", 16024 char: "S" 16025 }, 16026 URL: { 16027 cellType: DATA_TABLE_OUTPUT_TYPES.Url, 16028 title: "URL", 16029 cellKey: "text", 16030 defaultValue: () => "", 16031 char: "U" 16032 }, 16033 Media: { 16034 cellType: DATA_TABLE_OUTPUT_TYPES.Media, 16035 title: "Media", 16036 cellKey: "value", 16037 defaultValue: () => ({ name: "" }), 16038 char: "M" 16039 }, 16040 Color: { 16041 cellType: DATA_TABLE_OUTPUT_TYPES.Color, 16042 title: "Color", 16043 cellKey: "color", 16044 defaultValue: () => null, 16045 char: "C" 16046 } 16047}; 16048var HubMappingTable = class HubMappingTable extends import_react.Component { 16049 static { 16050 this.initCell = () => { 16051 return { 16052 [CELL.String.cellKey]: CELL.String.defaultValue(), 16053 [CELL.Media.cellKey]: CELL.Media.defaultValue(), 16054 [CELL.URL.cellKey]: CELL.URL.defaultValue(), 16055 [CELL.Color.cellKey]: CELL.Color.defaultValue() 16056 }; 16057 }; 16058 } 16059 constructor(props) { 16060 super(props); 16061 this.csvRows = []; 16062 this.onInputHeaderChange = (dataElementAD) => { 16063 if (this.state.showUploadCsv) this.closeCsvUploadIcon(); 16064 let { inputHeaders } = this.state; 16065 const dataElement = findDataElementByLogicValue(dataElementAD, this.props.dataElements); 16066 inputHeaders[0].value = dataElement || { name: "Select Data" }; 16067 inputHeaders[0].missing = false; 16068 this.setState({ 16069 inputHeaders, 16070 isChanged: true 16071 }); 16072 }; 16073 this.onOutputHeaderChange = (value, e) => { 16074 if (this.state.showUploadCsv) this.closeCsvUploadIcon(); 16075 let { outputHeaders } = this.state; 16076 let headerIndex = e.target.id; 16077 outputHeaders[headerIndex].text = value.trim(); 16078 this.setState({ 16079 outputHeaders, 16080 isChanged: true 16081 }); 16082 }; 16083 this.onOutputTypeChange = (type) => { 16084 let { outputHeaders, inputHeaders } = this.state; 16085 let prevType = outputHeaders[type.id].type; 16086 outputHeaders[type.id].type = type;
16087 if (prevType && (prevType.title === CELL.String.title || prevType.title === CELL.URL.title) && type.title === CELL.Media.title) this.validateAssets(parseInt(type.id) + inputHeaders.length, true); 16088 this.setState({ 16089 outputHeaders, 16090 isChanged: true 16091 }); 16092 }; 16093 this.onOutputColumnAdd = (index) => { 16094 if (this.state.showUploadCsv) this.closeCsvUploadIcon(); 16095 let { outputHeaders, inputHeaders, rows } = this.state; 16096 outputHeaders.splice(index, 0, { 16097 text: "", 16098 id: v4() 16099 }); 16100 rows.forEach((row) => { 16101 row.cells.splice(index + inputHeaders.length, 0, HubMappingTable.initCell()); 16102 }); 16103 this.setState({ 16104 outputHeaders, 16105 rows, 16106 isChanged: true 16107 }); 16108 }; 16109 this.onOutputColumnRemove = (index) => { 16110 let { outputHeaders, inputHeaders, rows } = this.state; 16111 outputHeaders.splice(index, 1); 16112 rows.forEach((row) => { 16113 row.cells.splice(index + inputHeaders.length, 1); 16114 }); 16115 this.setState({ 16116 outputHeaders, 16117 rows, 16118 isChanged: true 16119 }); 16120 }; 16121 this.onOutputColumnClear = (index) => { 16122 let { outputHeaders, inputHeaders, rows } = this.state; 16123 outputHeaders[index] = { text: "" }; 16124 rows.forEach((row) => { 16125 row.cells[index + inputHeaders.length] = HubMappingTable.initCell(); 16126 }); 16127 this.setState({ 16128 outputHeaders, 16129 rows, 16130 isChanged: true 16131 }); 16132 }; 16133 this.onCellChanged = (value, cellIndex, rowIndex, type) => { 16134 if (this.state.showUploadCsv) this.closeCsvUploadIcon(); 16135 let { rows } = this.state; 16136 let cell = rows[rowIndex].cells[cellIndex]; 16137 if (type && type === CELL.Media.cellType) { 16138 cell.value = value || { name: "" }; 16139 cell.text = ""; 16140 cell.missing = false; 16141 } else if (type && type === CELL.Color.cellType) cell.color = value; 16142 else { 16143 cell.text = value; 16144 cell.value = { name: "" }; 16145 } 16146 this.setState({ 16147 rows, 16148 isChanged: true 16149 }); 16150 }; 16151 this.onRowAdd = (index) => { 16152 if (this.state.showUploadCsv) this.closeCsvUploadIcon(); 16153 let { rows } = this.state; 16154 let cellsCount = this.state.inputHeaders.length + this.state.outputHeaders.length; 16155 let cells = []; 16156 for (let i = 0; i < cellsCount; i++) cells.push(HubMappingTable.initCell()); 16157 rows.splice(index, 0, { cells }); 16158 this.setState({ 16159 rows, 16160 isChanged: true 16161 }); 16162 }; 16163 this.onRowRemove = (index) => { 16164 let { rows } = this.state; 16165 rows.splice(index, 1); 16166 this.setState({ 16167 rows, 16168 isChanged: true 16169 }); 16170 }; 16171 this.onRowClear = (index) => { 16172 let { rows } = this.state; 16173 rows[index].cells = rows[index].cells.map((cell, index) => { 16174 return HubMappingTable.initCell(); 16175 }); 16176 this.setState({ 16177 rows, 16178 isChanged: true 16179 }); 16180 }; 16181 this.onSave = (e, doneCB) => { 16182 this.setState({ showSpinner: true }); 16183 const { inputHeaders, outputHeaders, rows } = this.state; 16184 let mappingTableData = { 16185 scheme: { 16186 inputs: [], 16187 outputs: [] 16188 }, 16189 data: [] 16190 }; 16191 inputHeaders.forEach((header) => { 16192 mappingTableData.scheme.inputs.push({ 16193 id: getDataElementId(header.value), 16194 displayName: getDataElementDisplayName(header.value), 16195 name: getDataElementDisplayName(header.value), 16196 type: header.value.type 16197 }); 16198 }); 16199 outputHeaders.forEach((header) => { 16200 header.id = header.id ? header.id : v4(); 16201 mappingTableData.scheme.outputs.push({ 16202 name: header.text, 16203 id: header.id, 16204 type: MappingTablesUtils.getTypeFromTitle(header.type.title) 16205 }); 16206 }); 16207 rows.forEach((row) => { 16208 let property = ""; 16209 let rowData = {}; 16210 row.cells.forEach((cell) => { 16211 const cellIndex = row.cells.indexOf(cell); 16212 if (cellIndex > inputHeaders.length - 1) { 16213 const outputColumn = cellIndex - inputHeaders.length; 16214 const cellType = MappingTablesUtils.getTypeFromTitle(outputHeaders[outputColumn].type.title); 16215 property = outputHeaders[outputColumn].id ? outputHeaders[outputColumn].id : outputHeaders[outputColumn].text; 16216 if (cellType === CELL.Media.cellType) rowData[property] = cell.value.name ? { 16217 "repo-url": cell.value.name, 16218 repository: "curated" 16219 } : null; 16220 else if (cellType === CELL.Color.cellType) rowData[property] = cell.color; 16221 else rowData[property] = cell.text; 16222 } else { 16223 property = getDataElementDisplayName(inputHeaders[cellIndex].value); 16224 rowData[property] = cell.text; 16225 } 16226 }); 16227 mappingTableData.data.push(rowData); 16228 }); 16229 this.props.handleSaveChanges(this.state.title, mappingTableData).then(() => { 16230 this.setState({ 16231 showSpinner: false, 16232 isChanged: false 16233 }); 16234 doneCB && doneCB(); 16235 }); 16236 }; 16237 this.onCancel = () => { 16238 HubNotifications.confirm("Cancel Changes", "Are you sure you want to revert the data to last save?", () => { 16239 this.props.handleCancelChanges(); 16240 }); 16241 }; 16242 this.onClose = (e) => {
16243 if (this.state.isChanged && !this.props.isViewOnly) HubNotifications.confirmWithCancel("Close Table", "Want to save your changes?", () => { 16244 this.onSave(e, this.props.handleClose); 16245 }, () => { 16246 this.props.handleClose(); 16247 }); 16248 else this.props.handleClose(); 16249 }; 16250 this.onUpload = (files) => { 16251 if (files.length > 0) { 16252 const reader = new FileReader(); 16253 reader.onloadend = () => { 16254 import_lib$1.parse(reader.result, (err, data) => { 16255 this.parseCsvFile(data); 16256 }); 16257 }; 16258 reader.readAsText(files[0]); 16259 this.setState({ 16260 showUploadCsv: false, 16261 showSpinner: true 16262 }); 16263 } 16264 }; 16265 this.validateName = (name, prevName) => { 16266 if (!name) return { 16267 result: false, 16268 message: "Missing data table name" 16269 }; 16270 return true; 16271 }; 16272 this.validateOutputHeader = (header) => { 16273 if (header && (!header.text || !header.type)) return { result: false }; 16274 return { result: true }; 16275 }; 16276 this.confirmUpload = () => { 16277 this.setState({ 16278 rows: this.csvRows, 16279 isChanged: true, 16280 showOverrideDialog: false 16281 }); 16282 this.csvRows = []; 16283 }; 16284 this.closeCsvUploadIcon = () => { 16285 this.setState({ showUploadCsv: false }); 16286 }; 16287 let inputHeaders = [{ value: { name: "Select Data" } }]; 16288 let outputHeaders = [{ 16289 text: "", 16290 id: "", 16291 type: { 16292 name: CELL.String.char, 16293 title: CELL.String.title 16294 } 16295 }]; 16296 let rows = [{ cells: [HubMappingTable.initCell(), HubMappingTable.initCell()] }]; 16297 this.state = { 16298 inputHeaders, 16299 outputHeaders, 16300 rows, 16301 isFocused: true, 16302 showUploadCsv: true, 16303 showSpinner: false, 16304 isChanged: false, 16305 showDialog: false, 16306 showOverrideDialog: false, 16307 title: void 0 16308 }; 16309 } 16310 componentDidMount() { 16311 if (this.props.mappingTableElement) this.buildTableData(this.props.mappingTableElement); 16312 } 16313 buildTableData(mappingTable) { 16314 this.setState({ 16315 showSpinner: true, 16316 showUploadCsv: false, 16317 title: mappingTable.title 16318 }); 16319 let inputHeaders = []; 16320 let outputHeaders = []; 16321 let rows = []; 16322 MappingTablesUtils.fetchData(mappingTable, this.props.isStageView, this.props.downloadUrl).then((mappingTableData) => { 16323 let { scheme, data } = mappingTableData; 16324 scheme.inputs.forEach((input) => { 16325 let inputDataElement = this.props.dataElements.find((element) => getDataElementId(element) === (input.id || input.name)); 16326 if (inputDataElement) inputHeaders.push({ value: inputDataElement }); 16327 else inputHeaders.push({ 16328 value: { name: input.displayName || input.name || input.id }, 16329 missing: true 16330 }); 16331 }); 16332 scheme.outputs.forEach((output) => { 16333 outputHeaders.push({ 16334 text: output.name, 16335 id: output.id, 16336 type: { 16337 name: MappingTablesUtils.getCharFromType(output.type), 16338 title: MappingTablesUtils.getTitleFromType(output.type) 16339 } 16340 }); 16341 }); 16342 data.forEach((row) => { 16343 let cells = []; 16344 inputHeaders.forEach((input) => { 16345 cells.push({ 16346 text: row[getDataElementId(input.value)] || row[getDataElementDisplayName(input.value)] || row[input.value.name], 16347 value: { name: "" } 16348 }); 16349 }); 16350 outputHeaders.forEach((output) => { 16351 const cellData = row[output.id ? output.id : output.text]; 16352 const cellType = MappingTablesUtils.getTypeFromTitle(output.type.title); 16353 if (cellType === CELL.Media.cellType) cells.push({ 16354 ...HubMappingTable.initCell(), 16355 [CELL.Media.cellKey]: { name: cellData ? cellData["repo-url"] : "" } 16356 }); 16357 else if (cellType === CELL.Color.cellType) cells.push({ 16358 ...HubMappingTable.initCell(), 16359 [CELL.Color.cellKey]: cellData 16360 }); 16361 else if (cellType === CELL.URL.cellType) cells.push({ 16362 ...HubMappingTable.initCell(), 16363 [CELL.URL.cellKey]: cellData 16364 }); 16365 else cells.push({ 16366 ...HubMappingTable.initCell(), 16367 [CELL.String.cellKey]: cellData 16368 }); 16369 }); 16370 rows.push({ cells }); 16371 }); 16372 this.setState({ 16373 inputHeaders, 16374 outputHeaders, 16375 rows, 16376 showSpinner: false 16377 }); 16378 }); 16379 } 16380 parseCsvFile(data) { 16381 let outputHeaders = []; 16382 let notEmptyCells = []; 16383 let notEmptyRows = []; 16384 data.map((row, rowIndex) => { 16385 row.map((cell, cellIndex) => { 16386 if (cell) { 16387 notEmptyCells[cellIndex] = true; 16388 notEmptyRows[rowIndex] = true; 16389 } 16390 }); 16391 }); 16392 let columnsCount = notEmptyCells.filter((cell) => cell).length; 16393 if (!this.props.mappingTableElement) { 16394 let rows = HubMappingTable.fillData(data, notEmptyRows, notEmptyCells); 16395 for (let i = 0; i < columnsCount - this.state.inputHeaders.length; i++) outputHeaders.push({ 16396 text: "", 16397 type: {
16398 name: CELL.String.char, 16399 title: MappingTablesUtils.getTitleFromType(CELL.String.cellType) 16400 }, 16401 color: null 16402 }); 16403 this.setState({ 16404 outputHeaders, 16405 rows, 16406 isChanged: true 16407 }); 16408 } else if (this.state.inputHeaders.length + this.state.outputHeaders.length !== columnsCount) this.setState({ showDialog: true }); 16409 else { 16410 this.csvRows = HubMappingTable.fillData(data, notEmptyRows, notEmptyCells); 16411 this.setState({ showOverrideDialog: true }); 16412 } 16413 this.setState({ showSpinner: false }); 16414 } 16415 static fillData(data, notEmptyRows, notEmptyCells) { 16416 let rows = []; 16417 for (let rowIndex = 0; rowIndex < notEmptyRows.length; rowIndex++) if (notEmptyRows[rowIndex]) { 16418 let row = { cells: [] }; 16419 for (let cellIndex = 0; cellIndex < notEmptyCells.length; cellIndex++) if (notEmptyCells[cellIndex]) if (data[rowIndex][cellIndex] && data[rowIndex][cellIndex].charAt(0) === "{" && data[rowIndex][cellIndex].charAt(data[rowIndex][cellIndex].length - 1) === "}") row.cells.push({ 16420 ...HubMappingTable.initCell(), 16421 [CELL.Color.cellKey]: JSON.parse(data[rowIndex][cellIndex]) 16422 }); 16423 else row.cells.push({ 16424 ...HubMappingTable.initCell(), 16425 [CELL.String.cellKey]: data[rowIndex][cellIndex] 16426 }); 16427 rows.push(row); 16428 } 16429 return rows; 16430 } 16431 validateAssets(columnIndex, override) { 16432 let { rows } = this.state; 16433 let assets = this.props.assets.filter((asset) => { 16434 return asset.mediaType && (asset.mediaType === "video" || asset.mediaType === "image"); 16435 }); 16436 rows.forEach((row) => { 16437 let cell = row.cells[columnIndex]; 16438 let asset = assets.find((asset) => asset.title.toLowerCase() === cell.text.toLowerCase()); 16439 if (!asset) { 16440 cell.missing = true; 16441 cell.value.name = cell.text; 16442 } else if (override) { 16443 cell.text = ""; 16444 cell.value.name = asset.name; 16445 cell.missing = false; 16446 } 16447 }); 16448 this.setState({ rows }); 16449 } 16450 static renameInput(mappingTableData, inputId, newName) { 16451 let oldInput = mappingTableData.scheme.inputs.find((input) => inputId === (input.id || input.name)); 16452 if (!oldInput) return mappingTableData; 16453 let newMappingTableData = { 16454 scheme: { 16455 inputs: [], 16456 outputs: mappingTableData.scheme.outputs 16457 }, 16458 data: [] 16459 }; 16460 newMappingTableData.scheme.inputs = mappingTableData.scheme.inputs.map((input) => { 16461 if (input === oldInput) return { 16462 id: inputId, 16463 displayName: newName, 16464 name: newName, 16465 type: input.type 16466 }; 16467 else return input; 16468 }); 16469 newMappingTableData.data = mappingTableData.data.map((rowData) => { 16470 let newRowData = { ...rowData }; 16471 let value = newRowData[oldInput.name]; 16472 delete newRowData[oldInput.name]; 16473 newRowData[newName] = value; 16474 return newRowData; 16475 }); 16476 return newMappingTableData; 16477 } 16478 render() { 16479 const outputHeadersValidation = this.state.outputHeaders.map((header) => this.validateOutputHeader(header)); 16480 const isMappingTableValid = this.state.title && outputHeadersValidation.every((validation) => validation.result); 16481 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 16482 className: "hubMappingTable", 16483 children: [ 16484 this.state.showSpinner && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubSpinner, { 16485 width: 100, 16486 height: 100, 16487 spinnerColor: "#0099FF", 16488 show: this.state.showSpinner 16489 }),
16490 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 16491 className: "header", 16492 children: [ 16493 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubContentEditable, { 16494 className: "tableName", 16495 value: this.state.title, 16496 isFocused: this.state.isFocused, 16497 disabled: this.props.isViewOnly, 16498 placeholder: "Enter Name", 16499 validateFunc: this.validateName, 16500 onBlur: () => this.setState({ isFocused: false }), 16501 onConfirm: (value) => this.setState({ 16502 title: value.trim(), 16503 isFocused: false, 16504 isChanged: true 16505 }) 16506 }), 16507 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { 16508 className: "close-icon", 16509 onClick: this.onClose 16510 }), 16511 !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { 16512 className: "mappingTableButtonsArea", 16513 children: [ 16514 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 16515 className: "save", 16516 size: "tiny", 16517 onClick: (e) => this.onSave(e), 16518 disabled: !isMappingTableValid, 16519 children: "Save" 16520 }), 16521 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, { 16522 className: "revert", 16523 size: "tiny", 16524 onClick: this.onCancel, 16525 children: "Revert" 16526 }), 16527 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { 16528 className: "import", 16529 onClick: () => { 16530 this.setState({ showUploadCsv: true }); 16531 } 16532 }) 16533 ] 16534 }) 16535 ] 16536 }),
16537 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(HubMappingTableData, { 16538 assets: this.props.assets, 16539 dataElements: this.props.dataElements, 16540 inputHeaders: this.state.inputHeaders, 16541 outputHeaders: this.state.outputHeaders, 16542 outputHeadersValidation, 16543 rows: this.state.rows, 16544 onRowAdd: this.onRowAdd, 16545 onRowRemove: this.onRowRemove, 16546 onRowClear: this.onRowClear, 16547 onInputHeaderChange: this.onInputHeaderChange, 16548 onOutputHeaderChange: this.onOutputHeaderChange, 16549 onOutputColumnAdd: this.onOutputColumnAdd, 16550 onOutputColumnRemove: this.onOutputColumnRemove, 16551 onOutputColumnClear: this.onOutputColumnClear, 16552 onOutputTypeChange: this.onOutputTypeChange, 16553 onCellChanged: this.onCellChanged, 16554 isViewOnly: this.props.isViewOnly 16555 }), 16556 this.state.showUploadCsv && !this.props.isViewOnly && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 16557 className: "uploadCsv", 16558 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { 16559 className: "close-csv", 16560 onClick: this.closeCsvUploadIcon 16561 }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Dropzone, { 16562 onDrop: this.onUpload, 16563 className: "dndCuratedAssets", 16564 activeClassName: "active", 16565 accept: ".csv, application/vnd.ms-excel", 16566 children: [ 16567 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "uploadFiles" }), 16568 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { children: "Drop .csv file here" }), 16569 /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 16570 className: "extra", 16571 children: [ 16572 "or \xA0", 16573 /* @__PURE__ */ (0, import_jsx_runtime.jsx)("a", { children: "browse" }), 16574 "\xA0 your computer" 16575 ] 16576 }) 16577 ] 16578 })] 16579 }),
16580 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyDialog, { 16581 open: this.state.showDialog, 16582 title: "Upload new CSV", 16583 contentText: "Number of columns in the table doesn't match the number of columns in the selected file. Fix the issue and upload again.", 16584 onPositiveClick: () => this.setState({ showDialog: false }), 16585 positiveButtonText: "got it!", 16586 promptType: "error" 16587 }), 16588 /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_Components.SskyDialog, { 16589 open: this.state.showOverrideDialog, 16590 title: "Upload new CSV", 16591 contentText: "Uploading a new CSV will override the existing data in the table. Upload file?", 16592 onPositiveClick: this.confirmUpload, 16593 onNegativeClick: () => this.setState({ showOverrideDialog: false }), 16594 positiveButtonText: "Upload" 16595 }) 16596 ] 16597 }); 16598 } 16599}; 16600//#endregion 16601//#region client/logic/builder/graphql/deleteMultipleDataElements.ts 16602init_lib(); 16603var deleteMultipleDataElements = (dataElementGQLIds) => { 16604 let fullMutation = `mutation DeleteDataElement(${dataElementGQLIds.map((_, index) => "$input" + index + ": DeleteDataElementInput!").join(", ")}) { 16605 ${dataElementGQLIds.map((_, index) => `delete${index}: deleteDataElement(input: $input${index}) { 16606 result 16607 ...on DeleteDataElementOutputRefusal { 16608 usedInData 16609 } 16610 }`).join("\n")} 16611 }`; 16612 let variables = dataElementGQLIds.reduce((acc, id, index) => { 16613 acc["input" + index] = { id }; 16614 return acc; 16615 }, {}); 16616 return { 16617 mutation: lib_default` 16618 ${fullMutation} 16619 `, 16620 variables 16621 }; 16622}; 16623//#endregion 16624//#region client/logic/DataElements/DataElementActions.ts 16625var UPDATING_PROJECT_WIREFRAMES_DATA_ELEMENTS_SUCCESS = "UPDATING_PROJECT_WIREFRAMES_DATA_ELEMENTS_SUCCESS"; 16626var UPDATE_DATA_ELEMENT_SUCCESS = "UPDATE_DATA_ELEMENT_SUCCESS"; 16627var ADD_DATA_ELEMENT_SUCCESS = "ADD_DATA_ELEMENT_SUCCESS"; 16628var DELETE_DATA_ELEMENTS_SUCCESS = "DELETE_DATA_ELEMENTS_SUCCESS"; 16629(0, import_lib$3.createAction)(UPDATING_PROJECT_WIREFRAMES_DATA_ELEMENTS_SUCCESS, (accountId, projectName, dataElements, stage, version) => { 16630 return { 16631 accountId, 16632 projectName, 16633 dataElements, 16634 stage, 16635 version 16636 }; 16637}, void 0); 16638var updateDataElementSuccess$1 = (0, import_lib$3.createAction)(UPDATE_DATA_ELEMENT_SUCCESS, function(accountId, projectName, dataElement, logic) { 16639 return { 16640 accountId, 16641 projectName, 16642 dataElement, 16643 logic 16644 }; 16645}); 16646var addDataElementSuccess = (0, import_lib$3.createAction)(ADD_DATA_ELEMENT_SUCCESS, function(accountId, projectName, dataElement, logic) { 16647 return { 16648 accountId, 16649 projectName, 16650 dataElement, 16651 logic 16652 }; 16653}); 16654var deleteDataElementsSuccess$1 = (0, import_lib$3.createAction)(DELETE_DATA_ELEMENTS_SUCCESS, function(accountId, projectName, dataElementIds) { 16655 return { 16656 accountId, 16657 projectName, 16658 dataElementIds 16659 }; 16660}); 16661function nameHadChanged(currentDataElement, newDataElement) { 16662 return getDataElementDisplayName(currentDataElement) !== getDataElementDisplayName(newDataElement); 16663} 16664function valueSetHadChanged(currentDataElement, newDataElement) { 16665 return true; 16666} 16667var gqlUpdateDataElementPromise = (state, accountId, projectName, dataElementToUpdate, services, logic) => { 16668 const dataElementId = dataElementToUpdate.id; 16669 const oldDataElement = findDataElementById(dataElementId, StateReaderUtils.getProjectDataElements(state, projectName)); 16670 let gqlPromise; 16671 let programSummary = StateReaderUtils.getProgramSummaries(state).find((ps) => ps.projectIds.builders === projectName); 16672 if (oldDataElement.origin === DataElementOrigins.Feed && dataElementToUpdate.origin === DataElementOrigins.Derived) gqlPromise = services.graphQlClient.mutate({ 16673 mutation: ConvertFeedDataElementToDerivedDocument, 16674 variables: { 16675 input: { 16676 id: `${programSummary.projectIds.builderDraftVersionId}|${dataElementId}`, 16677 updated: IGNORE_UPDATED, 16678 logic 16679 }, 16680 dryRun: false, 16681 [IGNORE_SERVER_ERRORS]: true 16682 } 16683 }); 16684 else if (oldDataElement.origin === dataElementToUpdate.origin) { 16685 let mutation; 16686 let input; 16687 if (dataElementToUpdate.origin === DataElementOrigins.Feed) { 16688 mutation = UpdateFeedDataElementDocument; 16689 input = { 16690 id: `${programSummary.projectIds.builderDraftVersionId}|${dataElementId}`, 16691 updated: IGNORE_UPDATED, 16692 name: dataElementToUpdate.displayName, 16693 description: dataElementToUpdate.description, 16694 dataType: convertDataElementType(dataElementToUpdate.type), 16695 pii: dataElementToUpdate.tags && dataElementToUpdate.tags.includes(TagNames.PII), 16696 status: convertDataElementStatus(dataElementToUpdate.status), 16697 useValueSet: dataElementToUpdate.useValueSet, 16698 valueSet: dataElementToUpdate.valueSet && [...dataElementToUpdate.valueSet] 16699 }; 16700 } else if (dataElementToUpdate.origin === DataElementOrigins.Derived) { 16701 mutation = UpdateDerivedDataElementDocument; 16702 input = { 16703 id: `${programSummary.projectIds.builderDraftVersionId}|${dataElementId}`, 16704 updated: IGNORE_UPDATED, 16705 name: dataElementToUpdate.displayName, 16706 description: dataElementToUpdate.description, 16707 dataType: convertDataElementType(dataElementToUpdate.type), 16708 pii: dataElementToUpdate.tags && dataElementToUpdate.tags.includes(TagNames.PII), 16709 logic 16710 }; 16711 } else if (dataElementToUpdate.origin === DataElementOrigins.Creative) { 16712 mutation = UpdateCreativeDataElementDocument; 16713 input = { 16714 id: `${programSummary.projectIds.builderDraftVersionId}|${dataElementId}`, 16715 updated: IGNORE_UPDATED, 16716 name: dataElementToUpdate.displayName, 16717 description: dataElementToUpdate.description, 16718 dataType: convertDataElementType(dataElementToUpdate.type), 16719 pii: dataElementToUpdate.tags && dataElementToUpdate.tags.includes(TagNames.PII), 16720 storyIds: dataElementToUpdate.assignedStories.map((storyId) => `${programSummary.projectIds.builderDraftVersionId}|${storyId}`), 16721 assignedToAllStories: dataElementToUpdate.assignedToAllStories, 16722 useValueSet: dataElementToUpdate.useValueSet, 16723 valueSet: dataElementToUpdate.valueSet && [...dataElementToUpdate.valueSet] 16724 }; 16725 } 16726 gqlPromise = services.graphQlClient.mutate({ 16727 mutation, 16728 variables: { 16729 input, 16730 dryRun: false, 16731 [IGNORE_SERVER_ERRORS]: true 16732 } 16733 }); 16734 } 16735 return gqlPromise; 16736}; 16737var getDataElementFromGQLResponse = (GQLResponse) => { 16738 if (GQLResponse.data.hasOwnProperty("updateFeedDataElement")) { 16739 const output = GQLResponse.data.updateFeedDataElement; 16740 if (output.result === GqlClientUpdateFeedDataElementResult.SUCCESS) return output.feedDataElement; 16741 } else if (GQLResponse.data.hasOwnProperty("updateDerivedDataElement")) { 16742 const output = GQLResponse.data.updateDerivedDataElement; 16743 if (output.result === GqlClientUpdateDerivedDataElementResult.SUCCESS) return output.derivedDataElement; 16744 } else if (GQLResponse.data.hasOwnProperty("updateCreativeDataElement")) { 16745 const output = GQLResponse.data.updateCreativeDataElement;
16746 if (output.result === GqlClientUpdateCreativeDataElementResult.SUCCESS) return output.creativeDataElement; 16747 } else if (GQLResponse.data.hasOwnProperty("convertFeedDataElementToDerived")) { 16748 const output = GQLResponse.data.convertFeedDataElementToDerived; 16749 if (output.result === GqlClientConvertFeedDataElementToDerivedResult.SUCCESS) return output.derivedDataElement; 16750 } 16751 return null; 16752}; 16753var updateDataElement = function(args) { 16754 const { accountId, projectName, dataElementId } = args; 16755 const dataElement = args.data; 16756 const logic = args.logic; 16757 let oldDataElement; 16758 let dataElements; 16759 let derivedLogic; 16760 return (dispatch, getState, services) => { 16761 const areDataElementsFromGQL = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 16762 dataElements = StateReaderUtils.getProjectDataElements(getState(), projectName); 16763 derivedLogic = StateReaderUtils.getAllProgramLogic(getState(), projectName, LogicContainers.Derived); 16764 oldDataElement = findDataElementById(dataElementId, dataElements); 16765 let promise; 16766 if (areDataElementsFromGQL) promise = gqlUpdateDataElementPromise(getState(), accountId, projectName, dataElement, services, logic).then((GQLResponse) => { 16767 let returnedDataElement = getDataElementFromGQLResponse(GQLResponse); 16768 if (!returnedDataElement) return Promise.reject("Cannot update the data element. Please refresh the page"); 16769 const dataElementToUpdate = { ...dataElement }; 16770 dataElementToUpdate.updatedTime = new Date(returnedDataElement.updated).getTime(); 16771 dispatch(updateDataElementSuccess$1(accountId, projectName, dataElementToUpdate, logic)); 16772 }); 16773 else { 16774 let dataElementToUpdate = normalizeDataElement(dataElement); 16775 let logicToUpdate = normalizeLogic(logic, dataElements); 16776 promise = services.dataElements.updateDataElement(accountId, projectName, dataElementId, dataElementToUpdate).then((dataElement) => { 16777 dispatch(updateDataElementSuccess$1(accountId, projectName, dataElement, void 0)); 16778 }).then(() => { 16779 gqlUpdateDataElementPromise(getState(), accountId, projectName, dataElementToUpdate, services, logicToUpdate).catch(() => {}); 16780 }); 16781 } 16782 promise.then(function() { 16783 let project = StateReaderUtils.getProject(getState(), projectName); 16784 let mappingTables = StateReaderUtils.getProjectAssetsByType(project, getState().assets, ASSET_TYPES.mappingTable); 16785 let promises = []; 16786 if (nameHadChanged(oldDataElement, dataElement)) mappingTables.forEach((mappingTable) => { 16787 let inputs = getDataElementIdsFromMappingTable(mappingTable); 16788 let inputKey; 16789 if (inputs.includes(dataElementId)) inputKey = dataElementId; 16790 if (inputs.includes(getDataElementDisplayName(oldDataElement))) inputKey = getDataElementDisplayName(oldDataElement); 16791 if (inputKey) { 16792 let downloadPromise = MappingTablesUtils.fetchData(mappingTable, false, (url, cb) => services.downloadServices.downloadUrl(url).then(cb)); 16793 promises.push(Promise.all([ 16794 mappingTable, 16795 inputKey, 16796 downloadPromise 16797 ])); 16798 } 16799 }); 16800 return Promise.all(promises); 16801 }).then(function(promiseResults) { 16802 let uploadJsonPromises = []; 16803 promiseResults.map(([mappingTable, inputKey, mappingTableData]) => { 16804 let newMappingTableData = HubMappingTable.renameInput(mappingTableData, inputKey, getDataElementDisplayName(dataElement)); 16805 if (StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.DataTables)) { 16806 const promise = updateDataTableMutation(services, mappingTable.graphQLId, {}, newMappingTableData).then((result) => { 16807 if (result.data.updateDataTable.__typename === "UpdateDataTableOutputSuccess") { 16808 const gqlDataTable = result.data.updateDataTable.dataTable; 16809 return buildDataTableFromGql(gqlDataTable); 16810 } 16811 return null; 16812 }); 16813 uploadJsonPromises.push(promise); 16814 } else uploadJsonPromises.push(services.projectAssetsServices.uploadJsonAssetContent(accountId, projectName, mappingTable.name, newMappingTableData, AssetTypes.mappingTable, false)); 16815 }); 16816 return Promise.all(uploadJsonPromises); 16817 }).then(function(assets) {
16818 assets.forEach((asset) => dispatch(uploadingProjectAssetsSuccess(asset, projectName, AssetTypes.mappingTable, void 0))); 16819 }).then(function() { 16820 if (valueSetHadChanged(oldDataElement, dataElement)) { 16821 let studioDataManager = new StudioDataManager({ 16822 dataElements, 16823 derivedLogic 16824 }); 16825 studioDataManager.buildDerivedGraph(dataElements); 16826 let dependentDerivedDataElementIds = studioDataManager.getDependentDerivedDataElementIds(dataElementId); 16827 dependentDerivedDataElementIds.push(dataElementId); 16828 dispatch(valueSetsChanged(accountId, projectName, dependentDerivedDataElementIds)); 16829 } 16830 }).catch(function(err) { 16831 dispatch(reportError(err)); 16832 }); 16833 }; 16834}; 16835var deleteDataElements = function(accountId, projectName, dataElementIds, callBack, usedInEditorCallback) { 16836 return (dispatch, getState, services) => { 16837 let programSummary = StateReaderUtils.getProgramSummaries(getState()).find((ps) => ps.projectIds.builders === projectName); 16838 const gqlReadMostEntities = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), programSummary.id, BulkId.MostEntities); 16839 let mutationParams = deleteMultipleDataElements(dataElementIds.map((id) => programSummary.projectIds.builderDraftVersionId + "|" + id)); 16840 services.graphQlClient.mutate({ 16841 mutation: mutationParams.mutation, 16842 variables: { 16843 ...mutationParams.variables, 16844 [IGNORE_SERVER_ERRORS]: true 16845 } 16846 }).then((response) => { 16847 if (gqlReadMostEntities) { 16848 const dataElements = StateReaderUtils.getProjectDataElements(getState(), projectName); 16849 const derivedLogic = StateReaderUtils.getAllProgramLogic(getState(), projectName, LogicContainers.Derived); 16850 try { 16851 if (typeof usedInEditorCallback === "function") { 16852 const usedInData = Object.values(response.data).filter((mutationResult) => mutationResult.result === GqlClientDeleteDataElementResult.USED_IN_REFUSAL).map((mutationResult) => mutationResult.usedInData); 16853 if (usedInData.length > 0) { 16854 usedInEditorCallback(usedInData); 16855 const usedDeIds = new Set(usedInData.map((usedInResult) => getIdFromGqlId(usedInResult?.dataElementId))); 16856 dataElementIds = dataElementIds.filter((id) => !usedDeIds.has(id)); 16857 } 16858 } 16859 if (callBack) callBack(dataElementIds); 16860 } finally { 16861 dispatch(deleteDataElementsSuccess$1(accountId, projectName, dataElementIds)); 16862 } 16863 let studioDataManager = new StudioDataManager({ 16864 dataElements, 16865 derivedLogic 16866 }); 16867 studioDataManager.buildDerivedGraph(dataElements); 16868 let dependentDerivedDataElementIds = studioDataManager.getDependentDerivedDataElementIds(dataElementIds); 16869 const deSet = new Set(dependentDerivedDataElementIds); 16870 dataElementIds.forEach((id) => deSet.add(id)); 16871 dispatch(valueSetsChanged(accountId, projectName, Array.from(deSet))); 16872 } 16873 }).catch((err) => { 16874 if (gqlReadMostEntities) dispatch(reportError(err)); 16875 }); 16876 }; 16877}; 16878var deleteDataElement = function(accountId, projectName, dataElementId, callBack) { 16879 let dataElements; 16880 let derivedLogic; 16881 return async (dispatch, getState, services) => { 16882 const gqlReadMostEntities = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 16883 try { 16884 await services.dataElements.deleteDataElement(accountId, projectName, dataElementId); 16885 if (!gqlReadMostEntities) { 16886 dataElements = StateReaderUtils.getProjectDataElements(getState(), projectName); 16887 derivedLogic = StateReaderUtils.getAllProgramLogic(getState(), projectName, LogicContainers.Derived); 16888 try { 16889 if (callBack) callBack(dataElementId); 16890 } finally { 16891 dispatch(deleteDataElementsSuccess$1(accountId, projectName, [dataElementId])); 16892 } 16893 let studioDataManager = new StudioDataManager({ 16894 dataElements, 16895 derivedLogic 16896 }); 16897 studioDataManager.buildDerivedGraph(dataElements); 16898 let dependentDerivedDataElementIds = studioDataManager.getDependentDerivedDataElementIds(dataElementId); 16899 dependentDerivedDataElementIds.push(dataElementId); 16900 dispatch(valueSetsChanged(accountId, projectName, dependentDerivedDataElementIds)); 16901 } 16902 } catch (err) { 16903 if (!gqlReadMostEntities) dispatch(reportError(err)); 16904 } 16905 }; 16906}; 16907var addDataElement = function(accountId, projectName, dataElement, logic, callBack) { 16908 return (dispatch, getState, services) => { 16909 dataElement = changeID(dataElement, v4()); 16910 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 16911 let mutation; 16912 let input; 16913 if (dataElement.origin === DataElementOrigins.Feed) { 16914 mutation = CreateFeedDataElementDocument; 16915 input = { 16916 name: dataElement.displayName, 16917 description: dataElement.description, 16918 dataType: dataElement.type, 16919 useValueSet: dataElement.useValueSet, 16920 valueSet: dataElement.valueSet, 16921 pii: dataElement.tags.includes(TagNames.PII), 16922 status: convertDataElementStatus(dataElement.status) || DataElementStatuses.Pending 16923 }; 16924 } else if (dataElement.origin === DataElementOrigins.Derived) { 16925 mutation = CreateDerivedDataElementDocument; 16926 input = { 16927 name: dataElement.displayName, 16928 description: dataElement.description, 16929 dataType: dataElement.type, 16930 pii: dataElement.tags.includes(TagNames.PII), 16931 logic 16932 }; 16933 } else if (dataElement.origin === DataElementOrigins.Creative) { 16934 mutation = CreateCreativeDataElementDocument; 16935 input = { 16936 name: dataElement.displayName, 16937 description: dataElement.description, 16938 dataType: dataElement.type, 16939 useValueSet: dataElement.useValueSet, 16940 valueSet: dataElement.valueSet, 16941 assignedToAllStories: dataElement.assignedToAllStories, 16942 storyIds: dataElement.assignedStories.map((storyId) => programVersionId + "|" + storyId) 16943 }; 16944 } 16945 return services.graphQlClient.mutate({ 16946 mutation, 16947 variables: { 16948 programVersionId, 16949 input, 16950 legacyId: dataElement.id, 16951 [IGNORE_SERVER_ERRORS]: true 16952 } 16953 }).then((result) => { 16954 let returnedGQLDataElement; 16955 if (result.data.hasOwnProperty("createFeedDataElement")) returnedGQLDataElement = result.data.createFeedDataElement.feedDataElement; 16956 else if (result.data.hasOwnProperty("createDerivedDataElement")) returnedGQLDataElement = result.data.createDerivedDataElement.derivedDataElement; 16957 else if (result.data.hasOwnProperty("createCreativeDataElement")) returnedGQLDataElement = result.data.createCreativeDataElement.creativeDataElement; 16958 dispatch(addDataElementSuccess(accountId, projectName, buildDataElement({ 16959 id: dataElement.id, 16960 type: dataElement.type, 16961 displayName: dataElement.displayName, 16962 description: dataElement.description, 16963 origin: dataElement.origin, 16964 status: dataElement.origin === DataElementOrigins.Feed ? dataElement.status : void 0, 16965 valueSet: dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative ? dataElement.valueSet : void 0, 16966 useValueSet: dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative ? dataElement.useValueSet : void 0, 16967 updatedTime: new Date(returnedGQLDataElement.updated).getTime(), 16968 tags: dataElement.tags, 16969 assignedStories: dataElement.origin === DataElementOrigins.Creative ? dataElement.assignedStories : void 0, 16970 assignedToAllStories: dataElement.origin === DataElementOrigins.Creative ? dataElement.assignedToAllStories : void 0 16971 }), dataElement.origin === DataElementOrigins.Derived ? logic : void 0)); 16972 if (callBack) callBack(dataElement); 16973 }).catch((err) => { 16974 dispatch(reportError(err)); 16975 }); 16976 }; 16977}; 16978/*** 16979* Calculates validations for all logic stored in state 16980* @param accountId 16981* @param projectName 16982* @returns {Function} 16983*/ 16984var recalculateLogicValidations = function(accountId, projectName) { 16985 return (dispatch) => {}; 16986}; 16987//#endregion 16988//#region client/logic/projects/projectAssets/creativeRecordingAssetsUtils.ts 16989var processCreativeRecordingAssets = (allCreativesNarrationRecordings, creativeDataElementsUsedInNarrationsOverrides) => { 16990 const { program: { creatives } } = allCreativesNarrationRecordings; 16991 let creativeRecordingAssets = [];
16992 creatives.forEach((creative) => { 16993 if (creative.creativeVersionDraft.creativeNarrationRecordings.length) creative.creativeVersionDraft.creativeNarrationRecordings.forEach((creativeRecording) => { 16994 const creativeName = creative.name; 16995 const { rfr: creativeRfr } = creative.creativeVersionDraft; 16996 const sceneAndNarrationDatas = creativeDataElementsUsedInNarrationsOverrides[creativeRecording.cdeId]; 16997 const recAsset = transformCreativeNarrationRecording(creativeRecording, creativeName, creativeRfr, sceneAndNarrationDatas && sceneAndNarrationDatas.length ? sceneAndNarrationDatas[0] : emptySceneAndNarrationData); 16998 creativeRecordingAssets.push(recAsset); 16999 }); 17000 }); 17001 return creativeRecordingAssets; 17002}; 17003var transformCreativeNarrationRecording = (creativeNarrationRecording, creativeName, creativeRfr, sceneAndNarrationData) => { 17004 const { id, filename, created, narrationText, updated, rfr, activeVersionId, creativeNarrationRecordingVersions } = creativeNarrationRecording; 17005 const creativeNarrationRecordingActiveVersion = activeVersionId ? creativeNarrationRecordingVersions.find((version) => version.id === activeVersionId) ?? null : null; 17006 const { sceneName, narrationLetter } = sceneAndNarrationData; 17007 const recordingStatus = creativeNarrationRecordingActiveVersion ? creativeNarrationRecordingActiveVersion.status : STATUS_REQUEST; 17008 const assetHistory = getAssetHistory(creativeNarrationRecordingVersions, `${filename}.mp3`); 17009 let activeVersionIndex; 17010 if (creativeNarrationRecordingActiveVersion) activeVersionIndex = assetHistory.find((a) => a.id === creativeNarrationRecordingActiveVersion.id).version; 17011 else activeVersionIndex = 0; 17012 const recordingErrorReason = creativeNarrationRecordingActiveVersion ? getNarrationRecordingErrorReason(creativeNarrationRecordingActiveVersion.errorReason) : NarrationRecordingErrorReason.OTHER; 17013 return { 17014 activeVersion: activeVersionIndex, 17015 activeVersionId: creativeNarrationRecordingActiveVersion ? creativeNarrationRecordingActiveVersion.id : "", 17016 assetId: id, 17017 createdTime: new Date(created).getTime(), 17018 filename: `${filename}.mp3`, 17019 inUse: calcInUse(rfr, creativeRfr), 17020 mediaType: MediaTypes.Audio, 17021 name: narrationText, 17022 type: AssetTypes.recording, 17023 updatedTime: new Date(updated).getTime(), 17024 version: creativeNarrationRecordingVersions ? creativeNarrationRecordingVersions.length : 0, 17025 RFR: rfr, 17026 creativeRFR: creativeRfr, 17027 status: recordingStatus, 17028 recordingErrorReason, 17029 recordingStatus, 17030 origin: RecordingOrigin.Creative, 17031 narrationMetadata: { 17032 text: narrationText, 17033 sceneName, 17034 narrationPart: narrationLetter, 17035 contentSet: creativeName 17036 }, 17037 history: { Items: assetHistory }, 17038 updated, 17039 activeVersionUpdated: creativeNarrationRecordingActiveVersion ? creativeNarrationRecordingActiveVersion.updated : "", 17040 downloadSelf: creativeNarrationRecordingActiveVersion ? creativeNarrationRecordingActiveVersion.url : void 0 17041 }; 17042}; 17043var calcInUse = (recordingRfr, creativeRfr) => { 17044 return recordingRfr >= creativeRfr; 17045}; 17046var getAssetHistory = (creativeRecordingAssetVersions, filename) => { 17047 let result = []; 17048 if (creativeRecordingAssetVersions) result = creativeRecordingAssetVersions.map((version, index) => { 17049 return { 17050 id: version.id, 17051 version: index + 1, 17052 format: version.format, 17053 updateTime: new Date(version.created).getTime(), 17054 mediaType: MediaTypes.Audio, 17055 type: AssetTypes.recording, 17056 size: version.size, 17057 recordingStatus: version.status, 17058 location: version.location, 17059 mediaSubType: version.mediaSubType, 17060 uploadedBy: version.createdBy, 17061 downloadSelf: version.url, 17062 filename, 17063 recordingErrorReason: getNarrationRecordingErrorReason(version.errorReason) 17064 }; 17065 }).reverse(); 17066 return result; 17067}; 17068var emptySceneAndNarrationData = { 17069 sceneId: "", 17070 narrationId: "", 17071 sceneName: "", 17072 narrationLetter: "A" 17073}; 17074var getNarrationRecordingErrorReason = (errorReason) => { 17075 switch (errorReason) { 17076 case GqlClientNarrationRecordingErrorReason.BADINTONATION: return NarrationRecordingErrorReason.BADINTONATION; 17077 case GqlClientNarrationRecordingErrorReason.CORRUPTED: return NarrationRecordingErrorReason.CORRUPTED; 17078 case GqlClientNarrationRecordingErrorReason.TEXTDOESNOTMATCH: return NarrationRecordingErrorReason.TEXTDOESNOTMATCH; 17079 case GqlClientNarrationRecordingErrorReason.OTHER: return NarrationRecordingErrorReason.OTHER; 17080 default: return NarrationRecordingErrorReason.OTHER; 17081 } 17082}; 17083var getGqlNarrationRecordingErrorReason = (recordingErrorReason) => { 17084 switch (recordingErrorReason) { 17085 case NarrationRecordingErrorReason.BADINTONATION: return GqlClientNarrationRecordingErrorReason.BADINTONATION; 17086 case NarrationRecordingErrorReason.CORRUPTED: return GqlClientNarrationRecordingErrorReason.CORRUPTED; 17087 case NarrationRecordingErrorReason.TEXTDOESNOTMATCH: return GqlClientNarrationRecordingErrorReason.TEXTDOESNOTMATCH; 17088 case NarrationRecordingErrorReason.OTHER: return GqlClientNarrationRecordingErrorReason.OTHER; 17089 default: return GqlClientNarrationRecordingErrorReason.OTHER; 17090 } 17091}; 17092var resolveActiveVersionId = (assetHistory, activeVersionIdx) => assetHistory.find(({ version }) => version === activeVersionIdx).id; 17093//#endregion 17094//#region client/logic/projects/projectAssets/gqlUtils.ts 17095var convertPostgresAssetToDynamoAsset = (postgresAsset) => { 17096 const { assetActiveVersion, accountId } = postgresAsset; 17097 const [, projectName, , assetDynamoName] = postgresAsset.legacyAssetId.split("/"); 17098 const convertedGqlAsset = { 17099 activeVersion: assetActiveVersion.version, 17100 filename: assetActiveVersion.filename, 17101 format: assetActiveVersion.format, 17102 height: assetActiveVersion.height, 17103 size: assetActiveVersion.size, 17104 status: assetActiveVersion.version === 0 ? STATUS_REQUEST : "approved", 17105 thumbnailUrl: assetActiveVersion.thumbnailUrl, 17106 width: assetActiveVersion.width, 17107 url: assetActiveVersion.url, 17108 version: assetActiveVersion.version, 17109 ...postgresAsset.legacyData, 17110 assetId: `${AssetTypes.curated}/${assetDynamoName}`, 17111 createdTime: new Date(postgresAsset.created).getTime(), 17112 description: postgresAsset.description, 17113 id: postgresAsset.id, 17114 isPostgresAsset: true, 17115 mediaType: postgresAsset.type, 17116 name: assetDynamoName, 17117 projectId: `${accountId}/${projectName}`, 17118 title: postgresAsset.name, 17119 type: AssetTypes.curated, 17120 updatedTime: new Date(postgresAsset.anyUpdated).getTime() 17121 }; 17122 if (postgresAsset.assetVersions) convertedGqlAsset.history = { Items: postgresAsset.assetVersions.map(convertPostgresAssetVersionToDynamoAssetVersion).sort((a, b) => a.version > b.version ? -1 : 1) }; 17123 return convertedGqlAsset; 17124}; 17125var convertPostgresAssetVersionToDynamoAssetVersion = (postgresAssetVersion) => ({ 17126 ...postgresAssetVersion, 17127 uploadedBy: postgresAssetVersion.createdBy, 17128 updateTime: new Date(postgresAssetVersion.created).getTime(), 17129 isPostgresAsset: true 17130}); 17131var initLegacyData = () => ({ legacyData: { 17132 inUse: false, 17133 deleted: false, 17134 archived: false 17135} }); 17136var convertAssetUpdatedDataToGqlInput = (assetUpdatedData, gqlStateAsset) => { 17137 const gqlInput = {}; 17138 if (assetUpdatedData.title !== void 0) gqlInput.name = assetUpdatedData.title; 17139 if (assetUpdatedData.description !== void 0) gqlInput.description = assetUpdatedData.description; 17140 if (assetUpdatedData.activeVersion !== void 0) gqlInput.activeAssetVersionId = gqlStateAsset.history.Items.find((av) => av.version === assetUpdatedData.activeVersion).id; 17141 if (assetUpdatedData.inUse !== void 0 || assetUpdatedData.archived !== void 0 || assetUpdatedData.deleted !== void 0) gqlInput.legacyData = { 17142 inUse: Boolean(gqlStateAsset.inUse), 17143 archived: Boolean(gqlStateAsset.archived), 17144 deleted: Boolean(gqlStateAsset.deleted), 17145 ...assetUpdatedData 17146 }; 17147 return gqlInput; 17148}; 17149var convertPostgresAnimationToDynamoAnimation = (postgresAnimation) => { 17150 const { animationActiveVersion } = postgresAnimation; 17151 const [accountId, projectName, animationType, animationDynamoName] = postgresAnimation.legacyAnimationId.split("/"); 17152 const convertedGqlAnimation = { 17153 activeVersion: animationActiveVersion.version, 17154 assetId: `${animationType}/${animationDynamoName}`, 17155 description: postgresAnimation.description, 17156 graphQLId: postgresAnimation.id, 17157 name: animationDynamoName, 17158 projectId: `${accountId}/${projectName}`, 17159 title: postgresAnimation.name, 17160 type: AssetTypes.animation, 17161 updatedTime: new Date(postgresAnimation.updated).getTime() 17162 }; 17163 if (postgresAnimation.animationVersions) convertedGqlAnimation.history = { Items: postgresAnimation.animationVersions.map(convertPostgresAnimationVersionToDynamoAnimationVersion).sort((a, b) => a.version > b.version ? -1 : 1) }; 17164 return convertedGqlAnimation; 17165}; 17166var convertPostgresAnimationVersionToDynamoAnimationVersion = (postgresAnimationVersion) => ({ 17167 graphQLId: postgresAnimationVersion.id, 17168 type: AssetTypes.animation, 17169 version: postgresAnimationVersion.version, 17170 updateTime: new Date(postgresAnimationVersion.created).getTime(), 17171 uploadedBy: postgresAnimationVersion.createdBy, 17172 comment: postgresAnimationVersion.comment, 17173 aeFileName: postgresAnimationVersion.aeFilename 17174}); 17175//#endregion 17176//#region client/logic/projects/projectAssets/projectAssetsActions.ts 17177var UPDATE_ASSET = "UPDATE_ASSET"; 17178var UPDATE_BULK_ASSETS_SUCCESS = "UPDATE_BULK_ASSETS_SUCCESS"; 17179var LOADING_ASSETS_COUNT_SUCCESS = "LOADING_ASSETS_COUNT_SUCCESS"; 17180var LOADING_ASSETS_SUCCESS = "LOADING_ASSETS_SUCCESS"; 17181var UPLOADING_ASSET = "UPLOADING_ASSET"; 17182var UPLOADING_ASSET_START = "UPLOADING_ASSET_START"; 17183var UPLOADING_ASSET_SUCCESS = "UPLOADING_ASSET_SUCCESS"; 17184var UPLOADING_ASSET_ERROR = "UPLOADING_ASSET_ERROR"; 17185var UPDATE_RECORDING_ASSET_STATUS_SUCCESS = "UPDATE_RECORDING_ASSET_STATUS_SUCCESS"; 17186var LOADING_ASSET_CONTENT = "LOADING_ASSET_CONTEN"; 17187var DELETE_ASSET_SUCCESS = "DELETE_ASSET_SUCCESS"; 17188var CLEAR_UPLOAD_LIST = "CLEAR_UPLOAD_LIST"; 17189var LOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS = "LOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS"; 17190var UPLOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS = "UPLOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS"; 17191var UPDATING_CREATIVE_NARRATION_RECORDING_VERSION_STATUS_SUCCESS = "UPDATING_CREATIVE_NARRATION_RECORDING_VERSIONS_STATUS_SUCCESS"; 17192var UPDATING_CREATIVE_NARRATION_RECORDING_SUCCESS = "UPDATING_CREATIVE_NARRATION_RECORDING_SUCCESS"; 17193var deletingProjectAssetsSuccess = (0, import_lib$3.createAction)(DELETE_ASSET_SUCCESS, (asset, projectName) => ({ 17194 asset, 17195 projectName 17196})); 17197var updateAsset = (0, import_lib$3.createAction)(UPDATE_ASSET, (projectName, asset) => ({ 17198 projectName, 17199 asset, 17200 assetType: asset.type 17201})); 17202var updateBulkAssetsSuccess = (0, import_lib$3.createAction)(UPDATE_BULK_ASSETS_SUCCESS, (projectName, responseBody, assetType) => ({ 17203 projectName, 17204 responseBody, 17205 assetType 17206})); 17207var loadingProjectAssetsCountSuccess = (0, import_lib$3.createAction)(LOADING_ASSETS_COUNT_SUCCESS, (projectName, assets, assetType) => ({ 17208 projectName, 17209 assets, 17210 assetType 17211})); 17212var loadingProjectAssetsSuccess = (0, import_lib$3.createAction)(LOADING_ASSETS_SUCCESS, (projectName, assets, versionMode) => ({ 17213 projectName, 17214 assets, 17215 versionMode 17216})); 17217var loadingAssetContent = (0, import_lib$3.createAction)(LOADING_ASSET_CONTENT, () => {}); 17218var uploadingProjectAsset = (0, import_lib$3.createAction)(UPLOADING_ASSET, () => {}); 17219var uploadingAssetStart = (0, import_lib$3.createAction)(UPLOADING_ASSET_START, (assetN
17219ame) => ({ assetName })); 17220var uploadingProjectAssetsSuccess = (0, import_lib$3.createAction)(UPLOADING_ASSET_SUCCESS, (asset, projectName, assetType, prevName) => ({ 17221 asset, 17222 projectName, 17223 assetType, 17224 prevName 17225})); 17226var uploadingProjectAssetsError = (0, import_lib$3.createAction)(UPLOADING_ASSET_ERROR, (assetName) => ({ assetName })); 17227var clearingUploadingList = (0, import_lib$3.createAction)(CLEAR_UPLOAD_LIST, () => ({})); 17228var updatingRecordingStatusSuccess = (0, import_lib$3.createAction)(UPDATE_RECORDING_ASSET_STATUS_SUCCESS, (projectName, assetName, version, assetUpdates) => ({ 17229 projectName, 17230 assetName, 17231 version, 17232 assetUpdates 17233})); 17234var loadingCreativeRecordingAssetsSuccess = (0, import_lib$3.createAction)(LOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS, (projectName, creativeNarrationRecordings) => ({ 17235 projectName, 17236 creativeNarrationRecordings 17237})); 17238var uploadingCreativeNarrationRecordingVersionSuccess = (0, import_lib$3.createAction)(UPLOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS, ({ creativeNarrationRecordingVersion, projectName }) => ({ 17239 creativeNarrationRecordingVersion, 17240 projectName 17241})); 17242var updatingCreativeRecordingStatusSuccess = (0, import_lib$3.createAction)(UPDATING_CREATIVE_NARRATION_RECORDING_VERSION_STATUS_SUCCESS, ({ creativeNarrationRecording, projectName }) => ({ 17243 creativeNarrationRecording, 17244 projectName 17245})); 17246var updatingCreativeRecordingSuccess = (0, import_lib$3.createAction)(UPDATING_CREATIVE_NARRATION_RECORDING_SUCCESS, ({ creativeNarrationRecording, projectName }) => ({ 17247 creativeNarrationRecording, 17248 projectName 17249})); 17250var uploadAssetContent = function({ accountId, projectName, type: assetType, name, file, newAsset, cb, progress, asset, isLegacyProject }) { 17251 return async (dispatch, getState, services) => { 17252 try { 17253 uploadingProjectAsset(); 17254 dispatch(uploadingAssetStart(file.name)); 17255 if (asset && asset.origin === RecordingOrigin.Creative) { 17256 await createCreativeRecording(services, dispatch, { 17257 accountId, 17258 projectName, 17259 file, 17260 asset, 17261 cb 17262 }); 17263 return; 17264 } 17265 const state = getState(); 17266 let dynamoShapeAsset; 17267 let fileMimeType = await AssetUtils.getFileType(file); 17268 if (isLegacyProject && fileTypesExcludeFromParse.includes(file.type)) fileMimeType = file.type; 17269 AssetUtils.validateFileType(fileMimeType, void 0, isLegacyProject); 17270 validateAssetFileSize(file.size, fileMimeType); 17271 if (shouldUseGql(assetType, state, projectName)) { 17272 let assetFragment; 17273 if (newAsset) { 17274 assetFragment = await createAssetWithVersion(services, state, { 17275 projectName, 17276 file, 17277 name, 17278 fileMimeType 17279 }); 17280 dynamoShapeAsset = convertPostgresAssetToDynamoAsset(assetFragment); 17281 } else { 17282 const gqlStateAsset = StateReaderUtils.getAsset(state, accountId, projectName, assetType, name); 17283 dynamoShapeAsset = await createAssetVersion(services, { 17284 accountId, 17285 projectName, 17286 isEditor: StateReaderUtils.isEditorProgram(state, projectName), 17287 asset: gqlStateAsset, 17288 file, 17289 fileMimeType 17290 }); 17291 } 17292 progress && progress(100); 17293 } else dynamoShapeAsset = await services.projectAssetsServices.uploadAssetContent(accountId, projectName, assetType, fileMimeType, name, file, newAsset, "content", void 0, progress); 17294 dispatch(uploadingProjectAssetsSuccess(dynamoShapeAsset, projectName, assetType, void 0)); 17295 if (cb instanceof Function) cb(); 17296 } catch (err) { 17297 dispatch(uploadingProjectAssetsError(file.name)); 17298 dispatch(reportError(err)); 17299 } 17300 }; 17301}; 17302var createCreativeRecording = async (services, dispatch, { accountId, projectName, file, asset, cb }) => { 17303 const fileType = await AssetUtils.getFileType(file); 17304 const newCreativeNarrationRecordingVersionVars = { input: { 17305 creativeNarrationRecordingId: asset.assetId, 17306 file, 17307 filename: asset.filename, 17308 fileType 17309 } }; 17310 const { data: { createCreativeNarrationRecordingVersion } } = await services.graphQlClient.mutate({ 17311 mutation: CreateCreativeNarrationRecordingVersionDocument, 17312 variables: newCreativeNarrationRecordingVersionVars 17313 }); 17314 const { result, creativeNarrationRecordingVersion } = createCreativeNarrationRecordingVersion; 17315 if (result === GqlClientCreateCreativeNarrationRecordingVersionResult.SUCCESS) { 17316 dispatch(uploadingCreativeNarrationRecordingVersionSuccess({ 17317 creativeNarrationRecordingVersion, 17318 projectName 17319 })); 17320 dispatch(recalculateLogicValidations(accountId, projectName)); 17321 if (cb instanceof Function) cb(); 17322 } else dispatch(uploadingProjectAssetsError(file.name)); 17323}; 17324var createAssetWithVersion = async (services, state, { projectName, file, name, fileMimeType }) => { 17325 const variables = { input: { 17326 programVersionId: StateReaderUtils.getBuilderProgramAndDraftVersionIds(state, projectName).programVersionId, 17327 name, 17328 file, 17329 filename: file.name, 17330 fileType: fileMimeType, 17331 ...initLegacyData() 17332 } }; 17333 const { data: { createAssetWithVersion: { asset } } } = await services.graphQlClient.mutate({ 17334 mutation: CreateAssetWithVersionDocument, 17335 variables 17336 }); 17337 return asset; 17338}; 17339var createAssetVersion = async (services, { accountId, projectName, isEditor, asset, file, fileMimeType }) => { 17340 switch (asset.type) { 17341 case AssetTypes.curated: return convertPostgresAssetToDynamoAsset(await createCuratedAssetVersion(services, { 17342 assetId: asset.id, 17343 file, 17344 fileMimeType 17345 })); 17346 case AssetTypes.recording: return buildNarrationRecordingFromGql(accountId, projectName, await createRecordingAssetVersion(services, { 17347 assetId: asset.graphQLId, 17348 file, 17349 fileMimeType 17350 }), isEditor); 17351 } 17352}; 17353var createCuratedAssetVersion = async (services, { assetId, file, fileMimeType }) => { 17354 const variables = { input: { 17355 assetId, 17356 file, 17357 filename: file.name, 17358 fileType: fileMimeType 17359 } }; 17360 const { data: { createAssetVersion: { assetVersion: { asset } } } } = await services.graphQlClient.mutate({ 17361 mutation: CreateAssetVersionDocument, 17362 variables 17363 }); 17364 return asset; 17365}; 17366var createRecordingAssetVersion = async (services, { assetId, file, fileMimeType }) => { 17367 const variables = { input: { 17368 narrationRecordingId: assetId, 17369 file, 17370 fileType: fileMimeType 17371 } }; 17372 return (await services.graphQlClient.mutate({ 17373 mutation: CreateNarrationRecordingVersionDocument, 17374 variables 17375 })).data.createNarrationRecordingVersion.narrationRecordingVersion.narrationRecording; 17376}; 17377var clearUploadingList = function() { 17378 return (dispatch) => {
17379 dispatch(clearingUploadingList()); 17380 }; 17381}; 17382var uploadAssetTextContent = (accountId, projectName, assetType, assetName, textContent, newAsset, cb) => { 17383 return async (dispatch, state, services) => { 17384 try { 17385 uploadingProjectAsset(); 17386 dispatch(uploadingProjectAssetsSuccess(await services.projectAssetsServices.uploadTextAssetContent(accountId, projectName, assetName, textContent, newAsset), projectName, assetType, void 0)); 17387 if (cb instanceof Function) cb(); 17388 } catch (err) { 17389 dispatch(reportError(err)); 17390 } 17391 }; 17392}; 17393var uploadAssetJsonContent = function(accountId, projectName, assetType, assetName, jsonContent, type, newAsset, cb) { 17394 return (dispatch, state, services) => { 17395 uploadingProjectAsset(); 17396 services.projectAssetsServices.uploadJsonAssetContent(accountId, projectName, assetName, jsonContent, type, newAsset).then((res) => { 17397 dispatch(uploadingProjectAssetsSuccess(res, projectName, assetType, void 0)); 17398 if (cb instanceof Function) cb(res); 17399 }).catch((err) => { 17400 dispatch(reportError(err)); 17401 }); 17402 }; 17403}; 17404var createDataTable = function(projectName, name, data) { 17405 return (dispatch, getState, services) => { 17406 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 17407 const variables = { input: { 17408 programVersionId, 17409 name, 17410 data 17411 } }; 17412 return services.graphQlClient.mutate({ 17413 mutation: CreateDataTableDocument, 17414 variables 17415 }).then((result) => { 17416 const gqlDataTable = result.data.createDataTable.dataTable; 17417 dispatch(uploadingProjectAssetsSuccess(buildDataTableFromGql(gqlDataTable), projectName, AssetTypes.mappingTable, void 0)); 17418 }); 17419 }; 17420}; 17421var updateDataTableMutation = (services, dataTableId, dataTableUpdates, dataTableBody) => { 17422 const variables = { input: { 17423 id: dataTableId, 17424 name: dataTableUpdates.title, 17425 description: dataTableUpdates.description, 17426 updated: IGNORE_UPDATED, 17427 data: dataTableBody 17428 } }; 17429 return services.graphQlClient.mutate({ 17430 mutation: UpdateDataTableDocument, 17431 variables 17432 }); 17433}; 17434var updateDataTable = function(projectName, dataTableId, dataTableUpdates, dataTableBody) { 17435 return (dispatch, getState, services) => { 17436 return updateDataTableMutation(services, dataTableId, dataTableUpdates, dataTableBody).then((result) => { 17437 if (result.data.updateDataTable.__typename === "UpdateDataTableOutputSuccess") { 17438 const gqlDataTable = result.data.updateDataTable.dataTable; 17439 dispatch(uploadingProjectAssetsSuccess(buildDataTableFromGql(gqlDataTable), projectName, AssetTypes.mappingTable, void 0)); 17440 } 17441 }); 17442 }; 17443}; 17444var createAssetRequest = (accountId, projectName, assetType, assetName, assetMediaType, newAsset, cb, desc) => { 17445 return async (dispatch, getState, services) => { 17446 try { 17447 uploadingProjectAsset(); 17448 const state = getState(); 17449 let dynamoShapeAsset; 17450 if (shouldUseGql(assetType, state, projectName)) { 17451 const variables = { input: { 17452 programVersionId: StateReaderUtils.getBuilderProgramAndDraftVersionIds(state, projectName).programVersionId, 17453 name: assetName, 17454 type: assetMediaType, 17455 description: desc, 17456 ...initLegacyData() 17457 } }; 17458 const { data: { createAssetRequest: { asset } } } = await services.graphQlClient.mutate({ 17459 mutation: CreateAssetRequestDocument, 17460 variables 17461 }); 17462 dynamoShapeAsset = convertPostgresAssetToDynamoAsset(asset); 17463 } else dynamoShapeAsset = await services.projectAssetsServices.makeAssetRequest(accountId, projectName, assetName, assetMediaType, newAsset, desc); 17464 dispatch(uploadingProjectAssetsSuccess(dynamoShapeAsset, projectName, assetType, void 0)); 17465 dispatch(recalculateLogicValidations(accountId, projectName)); 17466 if (cb instanceof Function) cb(); 17467 } catch (err) { 17468 dispatch(reportError(err)); 17469 } 17470 }; 17471}; 17472var uploadAsset = function(accountId, projectName, type, name, location, newAsset, cb) { 17473 return (dispatch, getState, services) => { 17474 dispatch(uploadingProjectAsset()); 17475 const isProgramNarratorsDynamoMigrationDone = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.Narrators); 17476 if (newAsset) { 17477 const assetMetadata = { 17478 programVersionId: StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName).programVersionId, 17479 isProgramNarratorsDynamoMigrationDone 17480 }; 17481 services.projectAssetsServices.addAssetWaitComplete(accountId, projectName, type, name, location, assetMetadata).then((asset) => { 17482 asset = isProgramNarratorsDynamoMigrationDone ? buildNarratorFromGql(accountId, projectName, asset) : asset; 17483 dispatch(uploadingProjectAssetsSuccess(asset, projectName, type, void 0)); 17484 dispatch(recalculateLogicValidations(accountId, projectName)); 17485 if (cb instanceof Function) cb(); 17486 }).catch((err) => { 17487 dispatch(reportError(err)); 17488 }); 17489 } else {
17490 const assetMetadata = { 17491 gqlAssetId: StateReaderUtils.getAsset(getState(), accountId, projectName, AssetTypes.narrator, name)?.graphQLId, 17492 assetUpdated: IGNORE_UPDATED, 17493 isProgramNarratorsDynamoMigrationDone 17494 }; 17495 services.projectAssetsServices.updateAssetWaitComplete(accountId, projectName, type, name, { 17496 type, 17497 name, 17498 location 17499 }, assetMetadata).then((asset) => { 17500 asset = isProgramNarratorsDynamoMigrationDone ? buildNarratorFromGql(accountId, projectName, asset) : asset; 17501 dispatch(uploadingProjectAssetsSuccess(asset, projectName, type, void 0)); 17502 if (cb instanceof Function) cb(); 17503 }).catch((err) => { 17504 dispatch(reportError(err)); 17505 }); 17506 } 17507 }; 17508}; 17509var updateExistingAsset = (accountId, projectName, assetType, name, assetUpdatedData, returnWithHistory, cb, assetData) => { 17510 return async (dispatch, getState, services) => { 17511 try { 17512 dispatch(uploadingProjectAsset()); 17513 if (assetData && assetData.origin === RecordingOrigin.Creative) { 17514 await updateCreativeRecording(services, dispatch, { 17515 projectName, 17516 asset: assetUpdatedData, 17517 assetData 17518 }); 17519 return; 17520 } 17521 const state = getState(); 17522 let dynamoShapeAsset; 17523 if (shouldUseGql(assetType, state, projectName)) { 17524 const gqlStateAsset = StateReaderUtils.getAsset(state, accountId, projectName, assetType, name); 17525 if (assetType === AssetTypes.curated) dynamoShapeAsset = convertPostgresAssetToDynamoAsset(await updateAssetWithGql(services, assetUpdatedData, gqlStateAsset)); 17526 else if (assetType === AssetTypes.animation) dynamoShapeAsset = convertPostgresAnimationToDynamoAnimation(await updateAnimationWithGql(services, assetUpdatedData, gqlStateAsset)); 17527 else if (assetType === AssetTypes.recording) dynamoShapeAsset = buildNarrationRecordingFromGql(accountId, projectName, await updateRecordingWithGql(services, assetUpdatedData, gqlStateAsset), StateReaderUtils.isEditorProgram(state, projectName)); 17528 } else dynamoShapeAsset = await services.projectAssetsServices.updateAsset(accountId, projectName, assetType, name, assetUpdatedData, returnWithHistory); 17529 dispatch(uploadingProjectAssetsSuccess(dynamoShapeAsset, projectName, assetType, name)); 17530 dispatch(recalculateLogicValidations(accountId, projectName)); 17531 if (cb instanceof Function) cb(); 17532 } catch (err) { 17533 dispatch(reportError(err)); 17534 } 17535 }; 17536}; 17537var updateCreativeRecording = async (services, dispatch, { projectName, asset, assetData }) => { 17538 const updatedActiveVersionId = resolveActiveVersionId(assetData.history.Items, asset.activeVersion); 17539 const updateCreativeNarrationRecordingVars = { 17540 input: { 17541 id: assetData.assetId, 17542 updated: assetData.updated, 17543 activeCreativeNarrationRecordingVersionId: updatedActiveVersionId 17544 }, 17545 dryRun: false 17546 }; 17547 const { data: { updateCreativeNarrationRecording } } = await services.graphQlClient.mutate({ 17548 mutation: UpdateCreativeNarrationRecordingDocument, 17549 variables: updateCreativeNarrationRecordingVars 17550 }); 17551 const { result, creativeNarrationRecording } = updateCreativeNarrationRecording; 17552 if (result === GqlClientUpdateCreativeNarrationRecordingResult.SUCCESS) dispatch(updatingCreativeRecordingSuccess({ 17553 projectName, 17554 creativeNarrationRecording 17555 })); 17556}; 17557var updateAssetWithGql = async (services, assetUpdatedData, gqlStateAsset) => { 17558 const variables = { input: { 17559 id: gqlStateAsset.id, 17560 updated: IGNORE_UPDATED, 17561 ...convertAssetUpdatedDataToGqlInput(assetUpdatedData, gqlStateAsset) 17562 } }; 17563 const { data: { updateAsset } } = await services.graphQlClient.mutate({ 17564 mutation: UpdateAssetDocument, 17565 variables 17566 }); 17567 if (updateAsset.result === GqlClientUpdateAssetResult.SUCCESS) return updateAsset.asset; 17568}; 17569var updateAnimationWithGql = async (services, animationUpdatedData, gqlStateAnimation) => { 17570 let input = { 17571 id: gqlStateAnimation.graphQLId, 17572 updated: IGNORE_UPDATED 17573 }; 17574 if (animationUpdatedData.description !== void 0) input.description = animationUpdatedData.description; 17575 if (animationUpdatedData.activeVersion !== void 0) input.activeAnimationVersionId = gqlStateAnimation.history.Items.find((av) => { 17576 return av.version === animationUpdatedData.activeVersion; 17577 }).graphQLId; 17578 const variables = { input }; 17579 const { data: { updateAnimation } } = await services.graphQlClient.mutate({ 17580 mutation: UpdateAnimationDocument, 17581 variables 17582 }); 17583 if (updateAnimation.result === GqlClientUpdateAnimationResult.SUCCESS) return updateAnimation.animation; 17584}; 17585var updateRecordingWithGql = async (services, recordingUpdatedData, gqlStateRecording) => { 17586 const designatedActiveVersion = gqlStateRecording.history.Items.find((av) => { 17587 return av.version === recordingUpdatedData.activeVersion; 17588 }); 17589 const variables = { input: { 17590 id: gqlStateRecording.graphQLId, 17591 activeNarrationRecordingVersionId: designatedActiveVersion.id, 17592 updated: IGNORE_UPDATED 17593 } }; 17594 const { data: { updateNarrationRecording } } = await services.graphQlClient.mutate({ 17595 mutation: UpdateNarrationRecordingDocument, 17596 variables 17597 }); 17598 if (updateNarrationRecording.result === GqlClientUpdateNarrationRecordingResult.SUCCESS) return updateNarrationRecording.narrationRecording; 17599}; 17600var updateRecordingAssetStatus = function(accountId, projectName, assetName, version, statusUpdates, asset) { 17601 return (dispatch, getState, services) => { 17602 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 17603 if (asset && asset.origin === RecordingOrigin.Creative) { 17604 const updateCreativeNarrationRecordingVersionVars = { 17605 input: { 17606 id: asset.activeVersionId, 17607 updated: asset.activeVersionUpdated, 17608 status: statusUpdates.recordingStatus, 17609 errorReason: getGqlNarrationRecordingErrorReason(statusUpdates.recordingErrorReason) 17610 }, 17611 dryRun: false 17612 }; 17613 services.graphQlClient.mutate({ 17614 mutation: UpdateCreativeNarrationRecordingVersionDocument, 17615 variables: updateCreativeNarrationRecordingVersionVars 17616 }).then(({ data: { updateCreativeNarrationRecordingVersion } }) => { 17617 const { result, creativeNarrationRecordingVersion } = updateCreativeNarrationRecordingVersion;
17618 if (result === GqlClientUpdateCreativeNarrationRecordingVersionResult.SUCCESS) dispatch(updatingCreativeRecordingStatusSuccess({ 17619 projectName, 17620 creativeNarrationRecording: creativeNarrationRecordingVersion.creativeNarrationRecording 17621 })); 17622 }).catch((err) => { 17623 dispatch(reportError(err)); 17624 }); 17625 } else if (!isPostgresOnly) services.projectAssetsServices.updateRecordingAssetStatus(accountId, projectName, assetName, version, statusUpdates).then(() => { 17626 dispatch(updatingRecordingStatusSuccess(projectName, assetName, version, statusUpdates)); 17627 }).catch((err) => { 17628 dispatch(reportError(err)); 17629 }); 17630 else { 17631 const updateNarrationRecordingVersionVars = { 17632 input: { 17633 id: asset.activeVersionId, 17634 updated: IGNORE_UPDATED, 17635 status: statusUpdates.recordingStatus, 17636 errorReason: getGqlNarrationRecordingErrorReason(statusUpdates.recordingErrorReason), 17637 narrationRecordingId: asset.graphQLId 17638 }, 17639 dryRun: false 17640 }; 17641 services.graphQlClient.mutate({ 17642 mutation: UpdateNarrationRecordingVersionDocument, 17643 variables: updateNarrationRecordingVersionVars 17644 }).then((gqlOutput) => { 17645 if (gqlOutput.data.updateNarrationRecordingVersion.__typename === "UpdateNarrationRecordingVersionOutputSuccess") dispatch(updatingRecordingStatusSuccess(projectName, assetName, version, statusUpdates)); 17646 }).catch((err) => {}); 17647 } 17648 }; 17649}; 17650var loadAsset = (accountId, projectName, assetType, assetName) => { 17651 return async (dispatch, getState, services) => { 17652 try { 17653 const state = getState(); 17654 let dynamoShapeAsset; 17655 if (shouldUseGql(assetType, state, projectName)) { 17656 if (assetType === AssetTypes.curated) { 17657 const { id: assetId } = StateReaderUtils.getAsset(state, accountId, projectName, AssetTypes.curated, assetName); 17658 const [programId, programVersionId] = assetId.split("|"); 17659 const variables = { 17660 programId, 17661 programVersionId: `${programId}|${programVersionId}`, 17662 assetId 17663 }; 17664 const { data: { program: { programVersion: { asset } } } } = await services.graphQlClient.query({ 17665 query: GetAssetVersionsDocument, 17666 variables 17667 }); 17668 dynamoShapeAsset = convertPostgresAssetToDynamoAsset(asset); 17669 } else if (assetType === AssetTypes.animation) { 17670 const { graphQLId: animationId } = StateReaderUtils.getAsset(state, accountId, projectName, AssetTypes.animation, assetName); 17671 const [programId, programVersionId] = animationId.split("|"); 17672 const variables = { 17673 programId, 17674 programVersionId: `${programId}|${programVersionId}`, 17675 animationId 17676 }; 17677 const { data: { program: { programVersion: { animation } } } } = await services.graphQlClient.query({ 17678 query: GetAnimationVersionsDocument, 17679 variables 17680 }); 17681 dynamoShapeAsset = convertPostgresAnimationToDynamoAnimation(animation); 17682 } else if (assetType === AssetTypes.recording) { 17683 const { graphQLId: narrationRecordingId } = StateReaderUtils.getAsset(state, accountId, projectName, AssetTypes.recording, assetName); 17684 const [programId, programVersionId] = narrationRecordingId.split("|"); 17685 const variables = { 17686 programId, 17687 programVersionId: `${programId}|${programVersionId}`, 17688 narrationRecordingId 17689 }; 17690 const { data: { program: { programVersion: { narrationRecording } } } } = await services.graphQlClient.query({ 17691 query: GetNarrationRecordingVersionsDocument, 17692 variables 17693 }); 17694 dynamoShapeAsset = buildNarrationRecordingFromGql(accountId, projectName, narrationRecording, StateReaderUtils.isEditorProgram(state, projectName)); 17695 } 17696 } else dynamoShapeAsset = await services.projectAssetsServices.getAsset(accountId, projectName, assetType, assetName, true); 17697 dispatch(updateAsset(projectName, dynamoShapeAsset)); 17698 } catch (err) { 17699 dispatch(reportError(err)); 17700 } 17701 }; 17702}; 17703var deleteAsset = (accountId, projectName, assetType, assetName, callBack) => { 17704 return async (dispatch, getState, services) => { 17705 try { 17706 dispatch(loadingAssetContent()); 17707 const state = getState(); 17708 let dynamoShapeAsset; 17709 if (shouldUseGql(assetType, state, projectName)) dynamoShapeAsset = convertPostgresAssetToDynamoAsset(await updateAssetWithGql(services, { deleted: true }, StateReaderUtils.getAsset(state, accountId, projectName, AssetTypes.curated, assetName))); 17710 else dynamoShapeAsset = await services.projectAssetsServices.deleteAsset(accountId, projectName, assetType, assetName); 17711 dispatch(deletingProjectAssetsSuccess(dynamoShapeAsset, projectName)); 17712 callBack && callBack(dynamoShapeAsset.assetId); 17713 } catch (err) { 17714 dispatch(reportError(err)); 17715 } 17716 }; 17717}; 17718var loadAssetContent = function(accountId, projectName, assetType, assetName, assetVersion, cb) { 17719 return (dispatch, state, services) => { 17720 dispatch(loadingAssetContent()); 17721 services.projectAssetsServices.getAsset(accountId, projectName, assetType, assetName, false).then((asset) => { 17722 const version = assetVersion || asset.version; 17723 const promiseArray = [asset, services.projectAssetsServices.getAssetContent(accountId, projectName, assetType, assetName, version)]; 17724 return Promise.all(promiseArray); 17725 }
17725).then(([asset, content]) => { 17726 asset.content = content; 17727 dispatch(updateAsset(projectName, asset)); 17728 if (cb instanceof Function) cb(); 17729 }).catch((err) => { 17730 dispatch(reportError(err)); 17731 }); 17732 }; 17733}; 17734var shouldUseGql = (assetType, state, projectName) => { 17735 if (assetType === AssetTypes.curated) return StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(state, projectName, BulkId.Assets); 17736 if (assetType === AssetTypes.animation) return StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(state, projectName, BulkId.Animations); 17737 if (assetType === AssetTypes.recording) return StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(state, projectName, BulkId.MostEntities); 17738 return false; 17739}; 17740//#endregion 17741//#region client/logic/Logics/DecisionPointLogic.ts 17742/** 17743* return actions possible on Decision Point Logic Value 17744* @param decoratedDPLogicValue - decorated decision Point Logic Value (as it is in DB and redax store) 17745* 17746*/ 17747function buildDecisionPointLogicValue(DPLogicValue) { 17748 return createDecisionPointLogicValue(DPLogicValue.sceneId, DPLogicValue.nextDPLogicId); 17749} 17750/** 17751* return actions possible on Decision Point Logic Value 17752* @param notDecoratedDPLogicValue - NOT decorated decision Point Logic Value (used for working with LogicContainer) 17753* 17754*/ 17755function buildAndDecorateDecisionPointLogicValue(notDecoratedDPLogicValue) { 17756 return createDecisionPointLogicValue(notDecoratedDPLogicValue, null); 17757} 17758function createDecisionPointLogicValue(sceneId, nextDPLogicId) { 17759 let _sceneId = sceneId; 17760 let _nextDPLogicId = nextDPLogicId || v4(); 17761 return { 17762 getSceneId: function() { 17763 return _sceneId; 17764 }, 17765 getNextDPLogicId: function() { 17766 return _nextDPLogicId; 17767 }, 17768 updateSceneId: function(sceneIdStr) { 17769 _sceneId = sceneIdStr; 17770 }, 17771 updateNextDPLogicId: function(nextDPLogicIdStr) { 17772 _nextDPLogicId = nextDPLogicIdStr || v4(); 17773 }, 17774 serializeDecisionPointLogicValue: function() { 17775 return { 17776 nextDPLogicId: _nextDPLogicId, 17777 sceneId: _sceneId 17778 }; 17779 }, 17780 serializeNotDecoratedDecisionPointLogicValue: function() { 17781 return _sceneId; 17782 } 17783 }; 17784} 17785/** 17786* The function gets decision point logic object and replace all old Decision Point Id with new Decision Point Id 17787* @param {LogicJSON} DP logicObj 17788* @param {string} oldDecisionPointId 17789* @param {string} newDecisionPointId 17790* @return {LogicJSON} updated logic object 17791*/ 17792function replaceDPLogicIdWithOther(logicObj, oldDecisionPointId, newDecisionPointId) { 17793 let logic = parseLogicObject(logicObj); 17794 let newRules = logic.getRules().map((rule) => { 17795 if (rule.value && buildDecisionPointLogicValue(rule.value).getNextDPLogicId() === oldDecisionPointId) { 17796 let newValue = buildDecisionPointLogicValue(rule.value); 17797 newValue.updateNextDPLogicId(newDecisionPointId); 17798 return { 17799 ...rule, 17800 value: newValue.serializeDecisionPointLogicValue() 17801 }; 17802 } else return rule; 17803 }); 17804 logic.setRules(newRules); 17805 let defaultValue = logic.getDefaultValue(); 17806 if (defaultValue && buildDecisionPointLogicValue(defaultValue).getNextDPLogicId() === oldDecisionPointId) { 17807 let newDefaultValue = buildDecisionPointLogicValue(defaultValue); 17808 newDefaultValue.updateNextDPLogicId(newDecisionPointId); 17809 logic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 17810 } 17811 return logic.serializeLogicData(); 17812} 17813/** 17814* The function gets decision point logic object and replace all old Decision Point Id with new Decision Point Id 17815* @param {LogicJSON} DP logicObj 17816* @param {string} decisionPointId 17817* @return {boolean} isDPLogicItemContainDPId 17818*/ 17819function isDPLogicItemContainDPId(logicObj, decisionPointId) { 17820 return extractUniqueNextDPPointsIdsFromDPLogic(logicObj).has(decisionPointId); 17821} 17822function extractSceneIdsAndDPsFromDPLogic(logicObj, allDPLogicInStory) { 17823 if (parseLogicObject(logicObj).getOutputType() !== LOGIC_TYPE.NextScene) return { 17824 participatingSceneIds: [], 17825 participatingDPs: [], 17826 numOfOccurrencesPerDP: /* @__PURE__ */ new Map() 17827 }; 17828 const getLogic = (dpId) => allDPLogicInStory[dpId]; 17829 const participatingScenes = /* @__PURE__ */ new Set(); 17830 const visitedDPs = /* @__PURE__ */ new Map(); 17831 extractSceneIdsFromDPLogicStep(logicObj, participatingScenes, visitedDPs, getLogic); 17832 return { 17833 participatingSceneIds: Array.from(participatingScenes), 17834 participatingDPs: Array.from(visitedDPs.keys()), 17835 numOfOccurrencesPerDP: visitedDPs 17836 }; 17837} 17838function extractSceneIdsFromDPLogicStep(logicObj, participatingScenes, visitedDPs, getLogic) {
17839 getAllValues(logicObj).forEach((value) => { 17840 if (value) { 17841 if (value.sceneId) participatingScenes.add(value.sceneId); 17842 if (!visitedDPs.has(value.nextDPLogicId)) { 17843 visitedDPs.set(value.nextDPLogicId, 1); 17844 extractSceneIdsFromDPLogicStep(getLogic(value.nextDPLogicId), participatingScenes, visitedDPs, getLogic); 17845 } else visitedDPs.set(value.nextDPLogicId, visitedDPs.get(value.nextDPLogicId) + 1); 17846 } 17847 }); 17848} 17849function extractUniqueNextDPPointsIdsFromDPLogic(logicObj) { 17850 let logic = parseLogicObject(logicObj); 17851 let logicNextDPPointsIds = /* @__PURE__ */ new Set(); 17852 logic.getValues().forEach((value) => { 17853 if (value) logicNextDPPointsIds.add(buildDecisionPointLogicValue(value).getNextDPLogicId()); 17854 }); 17855 return logicNextDPPointsIds; 17856} 17857function extractParentDpIds(dpId, allDPLogicInStory) { 17858 const getLogic = (dpId) => allDPLogicInStory[dpId]; 17859 let logic = parseLogicObject(getLogic(dpId)); 17860 const dpParents = /* @__PURE__ */ new Map(); 17861 if (logic.getOutputType() !== LOGIC_TYPE.NextScene) return dpParents; 17862 dpParents.set(dpId, /* @__PURE__ */ new Set()); 17863 extractParentDpIdsStep(dpId, dpParents, getLogic); 17864 return dpParents; 17865} 17866function extractParentDpIdsStep(dpId, dpParents, getLogic) { 17867 extractUniqueNextDPPointsIdsFromDPLogic(getLogic(dpId)).forEach((childDpId) => { 17868 if (!dpParents.has(childDpId)) dpParents.set(childDpId, /* @__PURE__ */ new Set()); 17869 dpParents.get(childDpId).add(dpId); 17870 dpParents.set(childDpId, unionSets(dpParents.get(dpId), dpParents.get(childDpId))); 17871 extractParentDpIdsStep(childDpId, dpParents, getLogic); 17872 }); 17873} 17874//#endregion 17875//#region client/logic/stories/Story.ts 17876var Story = class { 17877 constructor(storyData, program) { 17878 this.name = storyData.name; 17879 this.description = storyData.description; 17880 this.initialDecisionPointId = v4(); 17881 this.displaySceneOrder = []; 17882 this.backgroundAssetType = MediaTypes.Image; 17883 this.activateCaching = program.programType === ProgramType.Ads; 17884 this.participatingSceneIds = storyData.participatingSceneIds; 17885 this.participatingDPs = storyData.participatingDPs; 17886 } 17887}; 17888//#endregion 17889//#region client/logic/stories/StoryManager.tsx 17890var StoryManager = { 17891 /** 17892 * Creates new story, returns a shallow copy of the provided story 17893 * @param storyData - the story properties 17894 */ 17895 createNewStory: function(storyData, program) { 17896 return Object.freeze(new Story(storyData, program)); 17897 }, 17898 /** 17899 * Update the name of an existing story, returns a shallow copy of the provided story 17900 * with updated filed 17901 * @param story - The story to be updated 17902 * @param name - The new name to be stored in the story 17903 */ 17904 changeStoryName: function(story, name) { 17905 return Object.freeze({ 17906 ...story, 17907 name: name.trim() 17908 }); 17909 }, 17910 /** 17911 * Updates the description of an existing story, returns a shallow copy of the provided story 17912 * @param story - The story to be updated 17913 * @param desc - The new value of description to be stored in the story 17914 */ 17915 changeStoryDescription: function(story, desc) { 17916 return Object.freeze({ 17917 ...story, 17918 description: desc 17919 }); 17920 }, 17921 /** 17922 * Update the storyBackgroundAssetTypes of an existing story, returns a shallow copy of the provided story 17923 * with updated filed 17924 * @param story - The story to be updated 17925 * @param storyBackgroundAssetType - The new storyBackgroundAssetTypes to be stored in the story 17926 */ 17927 changeStoryBackgroundAssetTypes: function(story, storyBackgroundAssetType) { 17928 return Object.freeze({ 17929 ...story, 17930 backgroundAssetType: storyBackgroundAssetType 17931 }); 17932 }, 17933 /** 17934 * Create a copy of the story, returns a shallow copy of the provided story 17935 * @param story - The story to be updated 17936 * @param initialDecisionPointId - the new initialDecisionPointId 17937 */ 17938 duplicateStory: function(oldStory, name) { 17939 return Object.freeze({ 17940 ...oldStory, 17941 name, 17942 id: void 0, 17943 graphQLId: void 0 17944 }); 17945 }, 17946 /** 17947 * The function validates story name 17948 * @param name - story name 17949 * @param storiesArray - all other stories in program 17950 * @return {{storyNameValid: boolean, storyNameHelperText: string}} 17951 */ 17952 validateStoryName: (name, storiesArray, currentStoryId = void 0) => { 17953 let storyNameValid = true; 17954 let storyNameHelperText = ""; 17955 if (!name) { 17956 storyNameValid = false;
17957 storyNameHelperText = "Enter a story name"; 17958 } else if (!HubEditorUtils.isAlphaNumeric(name)) { 17959 storyNameValid = false; 17960 storyNameHelperText = "Only A-Z, 0-9"; 17961 } else if (storiesArray.find((s) => s.name.toLowerCase() === name.toLowerCase() && s.id !== currentStoryId)) { 17962 storyNameValid = false; 17963 storyNameHelperText = "Story name is unique in a program"; 17964 } 17965 return { 17966 storyNameValid, 17967 storyNameHelperText 17968 }; 17969 }, 17970 /** 17971 * The function validates story description 17972 * @param description - story description 17973 * @return {{storyDescriptionValid: boolean, storyDescriptionHelperText: string}} 17974 */ 17975 validateStoryDescription: (description) => { 17976 return { 17977 storyDescriptionValid: true, 17978 storyDescriptionHelperText: "" 17979 }; 17980 } 17981}; 17982//#endregion 17983//#region client/logic/stories/HubStoryEditorUtils.ts 17984var StoryEditorContext = /* @__PURE__ */ function(StoryEditorContext) { 17985 StoryEditorContext["Story"] = "STORY"; 17986 StoryEditorContext["DecisionPoint"] = "DECISION_POINT"; 17987 StoryEditorContext["Scene"] = "SCENE"; 17988 StoryEditorContext["Program"] = "PROGRAM"; 17989 return StoryEditorContext; 17990}({}); 17991var DPLogicContainerWarningTypes = /* @__PURE__ */ function(DPLogicContainerWarningTypes) { 17992 DPLogicContainerWarningTypes["DeleteCondition"] = "DELETE_CONDITION"; 17993 DPLogicContainerWarningTypes["ChangeConditionValue"] = "CHANGE_CONDITION_VALUE"; 17994 return DPLogicContainerWarningTypes; 17995}({}); 17996function generateSceneNodeId(parentDPNodeId, ruleKey, sceneId) { 17997 return `${parentDPNodeId}_${ruleKey}_${sceneId}`; 17998} 17999function generateEndNodeId(parentDPNodeId, ruleKey) { 18000 return `${parentDPNodeId}_${ruleKey}_endNode`; 18001} 18002function getSceneIdFromSceneNodeId(sceneNodeId) { 18003 return sceneNodeId.split("_")[2]; 18004} 18005var sceneActionTypes = { 18006 Before: "before", 18007 After: "after", 18008 InsteadOf: "insteadOf" 18009}; 18010var SceneActionTypes = /* @__PURE__ */ function(SceneActionTypes) { 18011 SceneActionTypes["Before"] = "before"; 18012 SceneActionTypes["After"] = "after"; 18013 SceneActionTypes["InsteadOf"] = "insteadOf"; 18014 return SceneActionTypes; 18015}({}); 18016function isSceneRemovable(prevDPObject, nextDPObject) { 18017 return parseLogicObject(prevDPObject).getRules().length === 0 || parseLogicObject(nextDPObject).getRules().length === 0; 18018} 18019function getMaxLongestRouteFromNodesMap(nodesMap) { 18020 let maxLongestRoute = 0; 18021 nodesMap.forEach((node) => { 18022 maxLongestRoute = node.getLongestRoute() > maxLongestRoute ? node.getLongestRoute() : maxLongestRoute; 18023 }); 18024 return maxLongestRoute; 18025} 18026var SCENE_ID_FOR_SCENE_NOT_EXISTS = "sceneNotExists"; 18027var RULE_KEY_FOR_DEFAULT_VALUE = "default"; 18028var REMOVE_SCENE_TOOLTIP_TEXT = "Can't remove scene"; 18029var getStoryIdToStoryName = index((stories) => { 18030 return Object.keys(stories).reduce((acc, storyId) => { 18031 acc[storyId] = stories[storyId].name; 18032 return acc; 18033 }, {}); 18034}); 18035var calculateDisabledNodes = index((mergeSessionActive, storyInitialDecisionPointId, storyDPLogicItems, selectedNodeId) => { 18036 if (!mergeSessionActive) return []; 18037 const parentDpIds = extractParentDpIds(storyInitialDecisionPointId, storyDPLogicItems); 18038 const childrenDpIds = extractSceneIdsAndDPsFromDPLogic(storyDPLogicItems[selectedNodeId], storyDPLogicItems).participatingDPs; 18039 const nodeParent = parentDpIds.get(selectedNodeId) || /* @__PURE__ */ new Set(); 18040 const nodeChildren = childrenDpIds || []; 18041 return Array.from(nodeParent).concat(nodeChildren); 18042}); 18043//#endregion 18044//#region client/logic/builder/sceneUtils.ts 18045var newScene = (sceneName) => { 18046 return { 18047 name: sceneName, 18048 backgroundImage: null, 18049 sceneParts: [], 18050 creationTime: (/* @__PURE__ */ new Date()).getTime().toString() 18051 }; 18052}; 18053//#endregion 18054//#region client/logic/stories/StoryActions.ts 18055var REMOVE_SCENE_FROM_STORY = "REMOVE_SCENE_FROM_STORY"; 18056var removeSceneFromStoryAction = (0, import_lib$3.createAction)(REMOVE_SCENE_FROM_STORY, (projectName, data) => { 18057 return { 18058 projectName, 18059 data 18060 }; 18061}); 18062var ADD_NEW_STORY_SUCCESS = "ADD_NEW_STORY_SUCCESS"; 18063var addNewStory = (0, import_lib$3.createAction)(ADD_NEW_STORY_SUCCESS, (projectName, data) => { 18064 return { 18065 projectName, 18066 data 18067 }; 18068}); 18069var DUPLICATE_STORY = "DUPLICATE_STORY"; 18070var duplicateStory = (0, import_lib$3.createAction)(DUPLICATE_STORY, (projectName, data) => { 18071 return { 18072 projectName, 18073 data 18074 }; 18075}); 18076var DELETE_STORY_SUCCESS = "DELETE_STORY_SUCCESS"; 18077var deleteStory = (0, import_lib$3.createAction)(DELETE_STORY_SUCCESS, (projectName, data) => { 18078 return { 18079 projectName, 18080 data 18081 }; 18082}); 18083var UPDATE_STORY_SUCCESS = "UPDATE_STORY_SUCCESS"; 18084var updateStory = (0, import_lib$3.createAction)(UPDATE_STORY_SUCCESS, (accountId, projectName, storyId, storyData) => { 18085 return { 18086 accountId, 18087 projectName, 18088 storyId, 18089 storyData 18090 }; 18091}); 18092var ADD_SCENE_TO_STORY_SUCCESS = "ADD_NEW_SCENE_TO_STORY_SUCCESS"; 18093var addSceneToStory = (0, import_lib$3.createAction)(ADD_SCENE_TO_STORY_SUCCESS, (projectName, data) => { 18094 return { 18095 projectName, 18096 data 18097 }; 18098}); 18099var UPDATE_DECISION_POINT_LOGIC_AND_ADD_NEW_DECISION_POINT_LOGIC = "UPDATE_DECISION_POINT_LOGIC_AND_ADD_NEW_DECISION_POINT_LOGIC"; 18100var updateDPLogicAndAddNewDPLogic = (0, import_lib$3.createAction)(UPDATE_DECISION_POINT_LOGIC_AND_ADD_NEW_DECISION_POINT_LOGIC, (projectName, data) => { 18101 return { 18102 projectName, 18103 data 18104 }; 18105}); 18106var UPDATE_DECISION_POINT_LOGIC = "UPDATE_DECISION_POINT_LOGIC"; 18107var updateDPLogic = (0, import_lib$3.createAction)(UPDATE_DECISION_POINT_LOGIC, (projectName, data) => { 18108 return { 18109 projectName, 18110 data 18111 }; 18112}); 18113var UPDATE_STORY_LOGIC_ITEMS = "UPDATE_STORY_LOGIC_ITEMS"; 18114var updateStoryLogicItems = (0, import_lib$3.createAction)(UPDATE_STORY_LOGIC_ITEMS, (projectName, data) => { 18115 return { 18116 projectName, 18117 data 18118 }; 18119}); 18120var MIGRATE_TO_MULTIPLE_STORIES_SUCCESS = "MIGRATE_TO_MULTIPLE_STORIES_SUCCESS"; 18121var MERGE_DECISION_POINTS_SUCCESS = "MERGE_DECISION_POINTS_SUCCESS"; 18122var mergeDecisionPointsSuccess = (0, import_lib$3.createAction)(MERGE_DECISION_POINTS_SUCCESS, (projectName, data) => { 18123 return { 18124 projectName, 18125 data 18126 }; 18127}); 18128var scenePartDefaultData = { 18129 placeholders: [], 18130 NarrationParts: [], 18131 parameters: [] 18132}; 18133function getStoryLogicContainerId(storyId) { 18134 return getDynamoLogicContainerId("story", storyId); 18135} 18136function getDecisionPointLogicContainerId(decisionPointId) { 18137 return getDynamoLogicContainerId(LogicContainers.DecisionPoint, decisionPointId); 18138} 18139function getDynamoLogicContainerId(containerType, containerId) { 18140 return containerType + "_" + containerId; 18141} 18142function addValueToDecisionPoint(logicObj, value) { 18143 let logic = parseLogicObject(logicObj); 18144 if (isLogicEmpty(logicObj)) { 18145 logic.setLast(false); 18146 logic.setDefaultValue(value); 18147 } else logic.addRuleWithValue(value); 18148 return logic.serializeLogicData(); 18149} 18150var handleUpdateStoryWithNewSceneResponse = (dispatch, projectName, newSceneId, newSceneName, dataToDispatch, gqlOutput,
18150cb) => { 18151 if (gqlOutput.data.updateStoryWithNewScene.__typename === "UpdateStoryWithNewSceneOutputSuccess") { 18152 const sceneData = newScene(newSceneName); 18153 const gqlScene = gqlOutput.data.updateStoryWithNewScene.scene; 18154 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithNewScene.story.updated }; 18155 dataToDispatch.newSceneData = { 18156 ...sceneData, 18157 id: newSceneId, 18158 graphQLId: gqlScene.id, 18159 graphQLUpdated: gqlScene.updated, 18160 sceneParts: [{ 18161 ...scenePartDefaultData, 18162 scenePart: getIdFromGqlId(gqlScene.sceneParts[0].id), 18163 graphQLId: gqlScene.sceneParts[0].id, 18164 graphQLUpdated: gqlScene.sceneParts[0].updated 18165 }] 18166 }; 18167 dispatch(addSceneToStory(projectName, dataToDispatch)); 18168 if (typeof cb === "function") cb(); 18169 } 18170}; 18171var addNewProjectStory = (account, projectName, storyObj, cb) => { 18172 return (dispatch, getState, services) => { 18173 let dataToDispatch = { 18174 storyId: void 0, 18175 storyData: storyObj, 18176 DpLogicData: createNewDecisionPointLogic().serializeLogicData(), 18177 soundtrackLogicData: createNewSoundtrackLogic().serializeLogicData(), 18178 backgroundImageLogicData: createNewBackgroundImageLogic().serializeLogicData(), 18179 backgroundVideoLogicData: createNewBackgroundVideoLogic().serializeLogicData() 18180 }; 18181 const dispatchCreateNewStorySuccess = (dataToDispatch) => { 18182 dispatch(addNewStory(projectName, dataToDispatch)); 18183 dispatch(valueSetsChanged(account, projectName, [SYSTEM_DATA_STORY_ID])); 18184 if (typeof cb === "function") cb(dataToDispatch.storyId); 18185 }; 18186 let input = { 18187 programVersionId: StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName).programVersionId, 18188 name: dataToDispatch.storyData.name, 18189 description: dataToDispatch.storyData.description, 18190 activateCaching: dataToDispatch.storyData.activateCaching, 18191 backgroundAssetType: dataToDispatch.storyData.backgroundAssetType, 18192 backgroundVideoLogic: dataToDispatch.backgroundVideoLogicData, 18193 backgroundImageLogic: dataToDispatch.backgroundImageLogicData, 18194 backgroundAudioLogic: dataToDispatch.soundtrackLogicData, 18195 displaySceneOrder: [], 18196 initialDecisionPoint: { 18197 localId: dataToDispatch.storyData.initialDecisionPointId, 18198 logic: dataToDispatch.DpLogicData 18199 } 18200 }; 18201 return services.graphQlClient.mutate({ 18202 mutation: CreateStoryWithDecisionPointAndBackgroundAssetsDocument, 18203 variables: { input } 18204 }).then((gqlOutput) => { 18205 const gqlStory = gqlOutput.data.createStoryWithDecisionPointAndBackgroundAssets.story; 18206 const storyLocalId = getIdFromGqlId(gqlStory.id); 18207 dataToDispatch.storyData = { 18208 ...storyObj, 18209 id: storyLocalId, 18210 graphQLId: gqlStory.id, 18211 graphQLUpdated: gqlStory.updated 18212 }; 18213 dataToDispatch.storyId = storyLocalId; 18214 dispatchCreateNewStorySuccess(dataToDispatch); 18215 }).catch((err) => {}); 18216 }; 18217}; 18218var updateProjectStory = (account, projectName, storyId, story) => { 18219 return (dispatch, getState, services) => { 18220 const dispatchUpdateStorySuccess = (updatedStory) => { 18221 dispatch(updateStory(account, projectName, storyId, updatedStory)); 18222 dispatch(valueSetsChanged(account, projectName, [SYSTEM_DATA_STORY_ID])); 18223 }; 18224 let input = { 18225 id: story.graphQLId, 18226 updated: IGNORE_UPDATED, 18227 name: story.name, 18228 description: story.description, 18229 activateCaching: story.activateCaching, 18230 backgroundAssetType: story.backgroundAssetType, 18231 narratorName: story.narrator, 18232 numberOfProducts: story.numberOfProducts, 18233 durationOptions: story.durationOptions, 18234 ratioAndQualityOptions: story.ratioAndQualityOptions 18235 }; 18236 return services.graphQlClient.mutate({ 18237 mutation: UpdateStoryForBuilderDocument, 18238 variables: { 18239 input, 18240 dryRun: false 18241 } 18242 }).then((gqlOutput) => { 18243 if (gqlOutput.data.updateStoryForBuilder.__typename === "UpdateStoryForBuilderOutputSuccess") dispatchUpdateStorySuccess({ 18244 ...story, 18245 graphQLUpdated: gqlOutput.data.updateStoryForBuilder.story.updated 18246 }); 18247 }).catch((err) => {}); 18248 }; 18249}; 18250var duplicateProjectStory = (account, projectName, oldStory, storyName, cb) => { 18251 return (dispatch, getState, services) => { 18252 let newStory = StoryManager.duplicateStory(oldStory, storyName); 18253 let storyLogicItems = StateReaderUtils.getStoryLogicItems(getState(), projectName, oldStory.id); 18254 let dataToDispatch = { 18255 storyId: void 0, 18256 storyData: newStory, 18257 storyLogicItems: Object.keys(storyLogicItems).reduce((acc, logicType) => { 18258 acc[logicType] = {};
18259 Object.keys(storyLogicItems[logicType]).forEach((logicId) => { 18260 acc[logicType][logicId] = { ...storyLogicItems[logicType][logicId] }; 18261 }); 18262 return acc; 18263 }, {}) 18264 }; 18265 let creativeDataElementsToUpdate = (StateReaderUtils.getProjectDataElements(getState(), projectName) || []).filter((de) => de.origin === DataElementOrigins.Creative && de.assignedStories.includes(oldStory.id)); 18266 let newCDEArr; 18267 const dispatchDuplicateStorySuccess = (newCDEArr, dataToDispatch) => { 18268 dispatch(duplicateStory(projectName, dataToDispatch)); 18269 dispatch(valueSetsChanged(account, projectName, [SYSTEM_DATA_STORY_ID])); 18270 newCDEArr.forEach((dataElement) => { 18271 dispatch(updateDataElementSuccess$1(account, projectName, dataElement, void 0)); 18272 }); 18273 if (typeof cb === "function") cb(dataToDispatch.storyId); 18274 }; 18275 let input = { 18276 sourceId: oldStory.graphQLId, 18277 targetName: dataToDispatch.storyData.name 18278 }; 18279 return services.graphQlClient.mutate({ 18280 mutation: CopyStoryDocument, 18281 variables: { input } 18282 }).then((gqlOutput) => { 18283 const targetStory = gqlOutput.data.copyStory.targetStory; 18284 const storyLocalId = getIdFromGqlId(targetStory.id); 18285 dataToDispatch.storyId = storyLocalId; 18286 dataToDispatch.storyData = { 18287 ...dataToDispatch.storyData, 18288 id: storyLocalId, 18289 graphQLId: targetStory.id, 18290 graphQLUpdated: targetStory.updated 18291 }; 18292 newCDEArr = creativeDataElementsToUpdate.map((cde) => addAssignedStory(cde, dataToDispatch.storyId)); 18293 dispatchDuplicateStorySuccess(newCDEArr, dataToDispatch); 18294 }).catch((err) => {}); 18295 }; 18296}; 18297var deleteProjectStory = (account, projectName, storyId, cb) => { 18298 return (dispatch, getState, services) => { 18299 let dataToDispatch = { storyId }; 18300 let creativeDataElementsToUpdate = (StateReaderUtils.getProjectDataElements(getState(), projectName) || []).filter((de) => de.origin === DataElementOrigins.Creative && de.assignedStories.includes(storyId)); 18301 let newCDEArr = []; 18302 if (creativeDataElementsToUpdate && creativeDataElementsToUpdate.length > 0) newCDEArr = creativeDataElementsToUpdate.map((cde) => removeAssignedStory(cde, storyId)); 18303 const dispatchDeleteStorySuccess = (newCDEArr, dataToDispatch) => { 18304 if (typeof cb === "function") { 18305 let stories = StateReaderUtils.getStories(StateReaderUtils.getWireFrame(getState(), projectName)); 18306 cb(Object.keys(stories).find((sId) => sId !== storyId)); 18307 } 18308 dispatch(deleteStory(projectName, dataToDispatch)); 18309 dispatch(valueSetsChanged(account, projectName, [SYSTEM_DATA_STORY_ID])); 18310 newCDEArr.forEach((result) => { 18311 dispatch(updateDataElementSuccess$1(account, projectName, result, void 0)); 18312 }); 18313 }; 18314 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.deleteProjectWireframesStory(account, projectName, storyId).then((deletedStory) => { 18315 return services.wireframes.deleteProjectWireFramesInputLogics(account, projectName, getStoryLogicContainerId(storyId)); 18316 }).then(() => { 18317 let promiseArray = newCDEArr.map((newCDE) => services.dataElements.updateDataElement(account, projectName, getDataElementId(newCDE), newCDE)); 18318 return Promise.all(promiseArray); 18319 }).then(() => { 18320 dispatchDeleteStorySuccess(newCDEArr, dataToDispatch); 18321 let input = { id: `${findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName).projectIds.builderDraftVersionId}|${storyId}` }; 18322 services.graphQlClient.mutate({ 18323 mutation: DeleteStoryDocument, 18324 variables: { 18325 input, 18326 [IGNORE_SERVER_ERRORS]: true 18327 } 18328 }).catch((err) => {}); 18329 }).catch((err) => dispatch(reportError(err))); 18330 else { 18331 let input = { id: StateReaderUtils.getStoryGqlId(getState(), projectName, storyId) }; 18332 return services.graphQlClient.mutate({ 18333 mutation: DeleteStoryDocument, 18334 variables: { input } 18335 }).then(() => { 18336 dispatchDeleteStorySuccess(newCDEArr, dataToDispatch); 18337 }).catch((err) => {}); 18338 } 18339 }; 18340}; 18341var removeSceneFromStoryWithPrevDPHasNoRules = (account, projectName, storyId, prevDecisionPointLogicId, nextDecisionPointLogicId, cb) => { 18342 return (dispatch, getState, services) => { 18343 let dataToDispatch = { 18344 storyId, 18345 decisionPointLogicIdToDelete: "", 18346 updatedStoryDecisionPointsLogics: {} 18347 }; 18348 let nextDecisionPointLogic = parseLogicObject(StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, nextDecisionPointLogicId)); 18349 let storyDecisionPointsObj = StateReaderUtils.getDecisionPointLogicItemsForStory(getState(), projectName, storyId); 18350 dataToDispatch.decisionPointLogicIdToDelete = nextDecisionPointLogicId; 18351 let updatedStoryDecisionPointsObj = Object.keys(storyDecisionPointsObj).reduce((acc, dpId) => { 18352 if (isDPLogicItemContainDPId(storyDecisionPointsObj[dpId], nextDecisionPointLogicId)) acc[dpId] = replaceDPLogicIdWithOther(storyDecisionPointsObj[dpId], nextDecisionPointLogicId, prevDecisionPointLogicId); 18353 return acc; 18354 }, {}); 18355 updatedStoryDecisionPointsObj[prevDecisionPointLogicId] = nextDecisionPointLogic.serializeLogicData(); 18356 dataToDispatch.updatedStoryDecisionPointsLogics = updatedStoryDecisionPointsObj; 18357 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 18358 const dispatchRemoveSceneFromStorySuccess = (dataToDispatch) => { 18359 if (typeof cb === "function") cb(); 18360 dispatch(removeSceneFromStoryAction(projectName, dataToDispatch)); 18361 }; 18362 if (!isPostgresOnly) { 18363 let promiseArray = Object.keys(updatedStoryDecisionPointsObj).map((dpID) => { 18364 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(dpID), updatedStoryDecisionPointsObj[dpID]); 18365 }); 18366 promiseArray.push(services.wireframes.deleteProjectWireFramesInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(nextDecisionPointLogicId))); 18367 return Promise.all(promiseArray).then(() => { 18368 dispatchRemoveSceneFromStorySuccess(dataToDispatch); 18369 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18370 let input = { 18371 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18372 updated: IGNORE_UPDATED, 18373 decisionPointsToUpdate: Object.keys(dataToDispatch.updatedStoryDecisionPointsLogics).map((dpId) => { 18374 return { 18375 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${dpId}`, 18376 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId], 18377 updated: IGNORE_UPDATED 18378 }; 18379 }), 18380 decisionPointsToDeleteIds: dataToDispatch.decisionPointLogicIdToDelete ? [`${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${dataToDispatch.decisionPointLogicIdToDelete}`] : void 0 18381 }; 18382 services.graphQlClient.mutate({ 18383 mutation: UpdateStoryWithDecisionPointsDocument, 18384 variables: { 18385 input, 18386 dryRun: false, 18387 [IGNORE_SERVER_ERRORS]: true 18388 } 18389 }).catch((err) => {}); 18390 }).catch((err) => dispatch(reportError(err))); 18391 } else {
18392 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18393 let input = { 18394 id: storyGQLId, 18395 updated: IGNORE_UPDATED, 18396 decisionPointsToUpdate: Object.keys(dataToDispatch.updatedStoryDecisionPointsLogics).map((dpId) => { 18397 return { 18398 id: `${storyGQLId}|${dpId}`, 18399 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId], 18400 updated: IGNORE_UPDATED 18401 }; 18402 }), 18403 decisionPointsToDeleteIds: dataToDispatch.decisionPointLogicIdToDelete ? [`${storyGQLId}|${dataToDispatch.decisionPointLogicIdToDelete}`] : void 0 18404 }; 18405 return services.graphQlClient.mutate({ 18406 mutation: UpdateStoryWithDecisionPointsDocument, 18407 variables: { 18408 input, 18409 dryRun: false 18410 } 18411 }).then((gqlOutput) => { 18412 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 18413 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 18414 dispatchRemoveSceneFromStorySuccess(dataToDispatch); 18415 } 18416 }).catch((err) => {}); 18417 } 18418 }; 18419}; 18420var removeSceneFromStoryWithNextDPHasNoRules = (account, projectName, storyId, ruleKey, prevDecisionPointLogicId, nextDecisionPointLogicId, cb) => { 18421 return (dispatch, getState, services) => { 18422 let dataToDispatch = { 18423 storyId, 18424 decisionPointLogicIdToDelete: "", 18425 updatedStoryDecisionPointsLogics: {} 18426 }; 18427 let story = StateReaderUtils.getStoryById(StateReaderUtils.getWireFrame(getState(), projectName), storyId); 18428 let storyDecisionPointsObj = StateReaderUtils.getDecisionPointLogicItemsForStory(getState(), projectName, storyId); 18429 let prevDecisionPointLogic = parseLogicObject(StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, prevDecisionPointLogicId)); 18430 let nextDecisionPointLogic = parseLogicObject(StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, nextDecisionPointLogicId)); 18431 let isLast = nextDecisionPointLogic.isLast(); 18432 let { numOfOccurrencesPerDP } = extractSceneIdsAndDPsFromDPLogic(storyDecisionPointsObj[story.initialDecisionPointId], storyDecisionPointsObj); 18433 let isPossibleToDeleteNextDecision = !(numOfOccurrencesPerDP.get(nextDecisionPointLogicId) > 1); 18434 dataToDispatch.decisionPointLogicIdToDelete = isPossibleToDeleteNextDecision ? nextDecisionPointLogicId : ""; 18435 if (!isLast && isPossibleToDeleteNextDecision) { 18436 let value = nextDecisionPointLogic.getDefaultValue(); 18437 if (ruleKey !== "default") prevDecisionPointLogic.updateRuleValue(ruleKey, value); 18438 else prevDecisionPointLogic.setDefaultValue(value); 18439 } else if (ruleKey !== "default") prevDecisionPointLogic.removeRule(ruleKey); 18440 else { 18441 prevDecisionPointLogic.setDefaultValue(null); 18442 prevDecisionPointLogic.setLast(true); 18443 } 18444 dataToDispatch.updatedStoryDecisionPointsLogics = { [prevDecisionPointLogicId]: prevDecisionPointLogic.serializeLogicData() }; 18445 const dispatchRemoveSceneFromStorySuccess = (dataToDispatch) => { 18446 if (typeof cb === "function") cb(); 18447 dispatch(removeSceneFromStoryAction(projectName, dataToDispatch)); 18448 }; 18449 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(prevDecisionPointLogicId), prevDecisionPointLogic.serializeLogicData()).then((updateDecisionPointLogic) => { 18450 dispatchRemoveSceneFromStorySuccess(dataToDispatch); 18451 let promiseDelete = Promise.resolve(null); 18452 if (isPossibleToDeleteNextDecision) promiseDelete = services.wireframes.deleteProjectWireFramesInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(nextDecisionPointLogicId)); 18453 return promiseDelete.then(() => { 18454 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18455 let input = { 18456 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18457 updated: IGNORE_UPDATED, 18458 decisionPointsToUpdate: Object.keys(dataToDispatch.updatedStoryDecisionPointsLogics).map((dpId) => { 18459 return { 18460 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${dpId}`, 18461 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId], 18462 updated: IGNORE_UPDATED 18463 }; 18464 }), 18465 decisionPointsToDeleteIds: dataToDispatch.decisionPointLogicIdToDelete ? [`${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${dataToDispatch.decisionPointLogicIdToDelete}`] : void 0 18466 }; 18467 services.graphQlClient.mutate({ 18468 mutation: UpdateStoryWithDecisionPointsDocument, 18469 variables: { 18470 input, 18471 dryRun: false, 18472 [IGNORE_SERVER_ERRORS]: true 18473 } 18474 }).catch((err) => {}); 18475 }).catch((err) => {}); 18476 }).catch((err) => dispatch(reportError(err))); 18477 else {
18478 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18479 let input = { 18480 id: storyGQLId, 18481 updated: IGNORE_UPDATED, 18482 decisionPointsToUpdate: Object.keys(dataToDispatch.updatedStoryDecisionPointsLogics).map((dpId) => { 18483 return { 18484 id: `${storyGQLId}|${dpId}`, 18485 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId], 18486 updated: IGNORE_UPDATED 18487 }; 18488 }), 18489 decisionPointsToDeleteIds: dataToDispatch.decisionPointLogicIdToDelete ? [`${storyGQLId}|${dataToDispatch.decisionPointLogicIdToDelete}`] : void 0 18490 }; 18491 return services.graphQlClient.mutate({ 18492 mutation: UpdateStoryWithDecisionPointsDocument, 18493 variables: { 18494 input, 18495 dryRun: false 18496 } 18497 }).then((gqlOutput) => { 18498 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 18499 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 18500 dispatchRemoveSceneFromStorySuccess(dataToDispatch); 18501 } 18502 }).catch((err) => {}); 18503 } 18504 }; 18505}; 18506var addNewScene = (account, projectName, storyId, decisionPointLogicId, sceneName) => { 18507 return (dispatch, getState, services) => { 18508 let decisionPointLogic = StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId); 18509 let dataToDispatch = { 18510 updatedStoryDecisionPointsLogics: {}, 18511 storyId 18512 }; 18513 let newRuleNextDpId; 18514 let newSceneId = v4(); 18515 let newValue = buildAndDecorateDecisionPointLogicValue(newSceneId); 18516 newRuleNextDpId = newValue.getNextDPLogicId(); 18517 decisionPointLogic = addValueToDecisionPoint(decisionPointLogic, newValue.serializeDecisionPointLogicValue()); 18518 let newDecisionPointLogic = createNewDecisionPointLogic().serializeLogicData(); 18519 dataToDispatch.updatedStoryDecisionPointsLogics[newRuleNextDpId] = newDecisionPointLogic; 18520 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = decisionPointLogic; 18521 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18522 let input = { 18523 id: storyGQLId, 18524 updated: IGNORE_UPDATED, 18525 newScene: { name: sceneName }, 18526 decisionPointToUpdate: { 18527 id: `${storyGQLId}|${decisionPointLogicId}`, 18528 logic: decisionPointLogic, 18529 updated: IGNORE_UPDATED 18530 }, 18531 newDecisionPoint: { 18532 localId: newRuleNextDpId, 18533 logic: newDecisionPointLogic 18534 } 18535 }; 18536 return services.graphQlClient.mutate({ 18537 mutation: UpdateStoryWithNewSceneDocument, 18538 variables: { 18539 input, 18540 dryRun: false, 18541 sceneLegacyId: newSceneId 18542 } 18543 }).then((gqlOutput) => { 18544 handleUpdateStoryWithNewSceneResponse(dispatch, projectName, newSceneId, sceneName, dataToDispatch, gqlOutput, void 0); 18545 }).catch((err) => {}); 18546 }; 18547}; 18548var addExistingScene = (account, projectName, storyId, decisionPointLogicId, sceneId) => { 18549 return (dispatch, getState, services) => { 18550 let newDecisionPointLogic = createNewDecisionPointLogic().serializeLogicData(); 18551 let decisionPointLogic = StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId); 18552 let dataToDispatch = { 18553 updatedStoryDecisionPointsLogics: {}, 18554 storyId 18555 }; 18556 let newValue = buildAndDecorateDecisionPointLogicValue(sceneId); 18557 let newRuleNextDpId = newValue.getNextDPLogicId(); 18558 decisionPointLogic = addValueToDecisionPoint(decisionPointLogic, newValue.serializeDecisionPointLogicValue()); 18559 dataToDispatch.updatedStoryDecisionPointsLogics[newRuleNextDpId] = newDecisionPointLogic; 18560 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = decisionPointLogic; 18561 const dispatchAddSceneToStorySuccess = (dataToDispatch) => { 18562 dispatch(addSceneToStory(projectName, dataToDispatch)); 18563 }; 18564 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(newRuleNextDpId), newDecisionPointLogic).then((logicData) => { 18565 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), decisionPointLogic); 18566 }).then((logicData2) => { 18567 dispatchAddSceneToStorySuccess(dataToDispatch); 18568 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18569 let input = { 18570 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18571 updated: IGNORE_UPDATED, 18572 newDecisionPoints: [{ 18573 localId: newRuleNextDpId, 18574 logic: dataToDispatch.updatedStoryDecisionPointsLogics[newRuleNextDpId] 18575 }], 18576 decisionPointsToUpdate: [{ 18577 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 18578 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18579 updated: IGNORE_UPDATED 18580 }] 18581 }; 18582 services.graphQlClient.mutate({ 18583 mutation: UpdateStoryWithDecisionPointsDocument, 18584 variables: { 18585 input, 18586 dryRun: false, 18587 [IGNORE_SERVER_ERRORS]: true 18588 } 18589 }).catch((err) => {}); 18590 }).catch((err) => dispatch(reportError(err))); 18591 else {
18592 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18593 let input = { 18594 id: storyGQLId, 18595 updated: IGNORE_UPDATED, 18596 newDecisionPoints: [{ 18597 localId: newRuleNextDpId, 18598 logic: dataToDispatch.updatedStoryDecisionPointsLogics[newRuleNextDpId] 18599 }], 18600 decisionPointsToUpdate: [{ 18601 id: `${storyGQLId}|${decisionPointLogicId}`, 18602 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18603 updated: IGNORE_UPDATED 18604 }] 18605 }; 18606 return services.graphQlClient.mutate({ 18607 mutation: UpdateStoryWithDecisionPointsDocument, 18608 variables: { 18609 input, 18610 dryRun: false 18611 } 18612 }).then((gqlOutput) => { 18613 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 18614 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 18615 dispatchAddSceneToStorySuccess(dataToDispatch); 18616 } 18617 }).catch((err) => {}); 18618 } 18619 }; 18620}; 18621var replaceSceneWithNewScene = (account, projectName, storyId, decisionPointLogicId, ruleKey, sceneName, cb) => { 18622 return (dispatch, getState, services) => { 18623 let decisionPointLogic = parseLogicObject(StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId)); 18624 let dataToDispatch = { 18625 updatedStoryDecisionPointsLogics: {}, 18626 storyId 18627 }; 18628 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) { 18629 let sceneData; 18630 return services.wireframes.addProjectWireframesScene(account, projectName, newScene(sceneName)).then((res) => { 18631 sceneData = res; 18632 return services.wireframes.addProjectWireframesScenePart(account, projectName, sceneData.id, scenePartDefaultData); 18633 }).then((scenePart) => { 18634 sceneData.sceneParts.push(scenePart); 18635 dataToDispatch.newSceneData = sceneData; 18636 if (ruleKey !== "default") { 18637 let rulesNextDpId = buildDecisionPointLogicValue(decisionPointLogic.getRule(ruleKey).value).getNextDPLogicId(); 18638 let newRulesValue = createDecisionPointLogicValue(sceneData.id, rulesNextDpId).serializeDecisionPointLogicValue(); 18639 decisionPointLogic.updateRuleValue(ruleKey, newRulesValue); 18640 } else { 18641 let defaultValueNextDpId = buildDecisionPointLogicValue(decisionPointLogic.getDefaultValue()).getNextDPLogicId(); 18642 let newDefaultValue = createDecisionPointLogicValue(sceneData.id, defaultValueNextDpId); 18643 decisionPointLogic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 18644 } 18645 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), decisionPointLogic.serializeLogicData()); 18646 }).then((logicData) => { 18647 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = logicData; 18648 dispatch(addSceneToStory(projectName, dataToDispatch)); 18649 if (typeof cb === "function") cb(sceneData.id); 18650 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18651 let input = { 18652 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18653 updated: IGNORE_UPDATED, 18654 newScene: { name: sceneName }, 18655 decisionPointToUpdate: { 18656 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 18657 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18658 updated: IGNORE_UPDATED 18659 } 18660 }; 18661 services.graphQlClient.mutate({ 18662 mutation: UpdateStoryWithNewSceneDocument, 18663 variables: { 18664 input, 18665 dryRun: false, 18666 sceneLegacyId: dataToDispatch.newSceneData.id, 18667 scenePartLegacyId: dataToDispatch.newSceneData.sceneParts[0].scenePart, 18668 [IGNORE_SERVER_ERRORS]: true 18669 } 18670 }).catch((err) => {}); 18671 }).catch((err) => dispatch(reportError(err))); 18672 } else { 18673 let newSceneId = v4(); 18674 if (ruleKey !== "default") { 18675 let newRulesValue = createDecisionPointLogicValue(newSceneId, buildDecisionPointLogicValue(decisionPointLogic.getRule(ruleKey).value).getNextDPLogicId()).serializeDecisionPointLogicValue(); 18676 decisionPointLogic.updateRuleValue(ruleKey, newRulesValue); 18677 } else { 18678 let newDefaultValue = createDecisionPointLogicValue(newSceneId, buildDecisionPointLogicValue(decisionPointLogic.getDefaultValue()).getNextDPLogicId()); 18679 decisionPointLogic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 18680 } 18681 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = decisionPointLogic.serializeLogicData(); 18682 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18683 let input = { 18684 id: storyGQLId, 18685 updated: IGNORE_UPDATED, 18686 newScene: { name: sceneName }, 18687 decisionPointToUpdate: { 18688 id: `${storyGQLId}|${decisionPointLogicId}`, 18689 logic: decisionPointLogic.serializeLogicData(), 18690 updated: IGNORE_UPDATED 18691 } 18692 }; 18693 return services.graphQlClient.mutate({ 18694 mutation: UpdateStoryWithNewSceneDocument, 18695 variables: { 18696 input, 18697 dryRun: false, 18698 sceneLegacyId: newSceneId 18699 } 18700 }).then((gqlOutput) => { 18701 handleUpdateStoryWithNewSceneResponse(dispatch, projectName, newSceneId, sceneName, dataToDispatch, gqlOutput, () => cb && cb(newSceneId)); 18702 }).catch((err) => {}); 18703 } 18704 }; 18705}; 18706var replaceSceneWithExistingScene = (account, projectName, storyId, decisionPointLogicId, ruleKey, sceneId, cb) => { 18707 return (dispatch, getState, services) => { 18708 let decisionPointLogic = parseLogicObject(StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId)); 18709 let dataToDispatch = { 18710 updatedStoryDecisionPointsLogics: {}, 18711 storyId 18712 }; 18713 if (ruleKey !== "default") { 18714 let newRulesValue = createDecisionPointLogicValue(sceneId, buildDecisionPointLogicValue(decisionPointLogic.getRule(ruleKey).value).getNextDPLogicId()).serializeDecisionPointLogicValue(); 18715 decisionPointLogic.updateRuleValue(ruleKey, newRulesValue); 18716 } else { 18717 let newDefaultValue = createDecisionPointLogicValue(sceneId, buildDecisionPointLogicValue(decisionPointLogic.getDefaultValue()).getNextDPLogicId()); 18718 decisionPointLogic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 18719 } 18720 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = decisionPointLogic.serializeLogicData(); 18721 const dispatchAddSceneToStorySuccess = (dataToDispatch) => { 18722 dispatch(addSceneToStory(projectName, dataToDispatch)); 18723 if (typeof cb === "function") cb(); 18724 }; 18725 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), decisionPointLogic.serializeLogicData()).then((logicData) => { 18726 dispatchAddSceneToStorySuccess(dataToDispatch); 18727 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18728 let input = { 18729 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18730 updated: IGNORE_UPDATED, 18731 decisionPointsToUpdate: [{ 18732 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 18733 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18734 updated: IGNORE_UPDATED 18735 }] 18736 }; 18737 services.graphQlClient.mutate({ 18738 mutation: UpdateStoryWithDecisionPointsDocument, 18739 variables: { 18740 input, 18741 dryRun: false, 18742 [IGNORE_SERVER_ERRORS]: true 18743 } 18744 }).catch((err) => {}); 18745 }).catch((err) => dispatch(reportError(err))); 18746 else {
18747 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18748 let input = { 18749 id: storyGQLId, 18750 updated: IGNORE_UPDATED, 18751 decisionPointsToUpdate: [{ 18752 id: `${storyGQLId}|${decisionPointLogicId}`, 18753 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18754 updated: IGNORE_UPDATED 18755 }] 18756 }; 18757 return services.graphQlClient.mutate({ 18758 mutation: UpdateStoryWithDecisionPointsDocument, 18759 variables: { 18760 input, 18761 dryRun: false 18762 } 18763 }).then((gqlOutput) => { 18764 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 18765 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 18766 dispatchAddSceneToStorySuccess(dataToDispatch); 18767 } 18768 }).catch((err) => {}); 18769 } 18770 }; 18771}; 18772var addNewSceneBefore = (account, projectName, storyId, decisionPointLogicId, sceneName, cb) => { 18773 return (dispatch, getState, services) => { 18774 let dataToDispatch = { 18775 updatedStoryDecisionPointsLogics: {}, 18776 storyId 18777 }; 18778 let newDefaultValueNextDpId; 18779 let newDecisionPointLogic; 18780 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) { 18781 let sceneData; 18782 return services.wireframes.addProjectWireframesScene(account, projectName, newScene(sceneName)).then((res) => { 18783 sceneData = res; 18784 return services.wireframes.addProjectWireframesScenePart(account, projectName, sceneData.id, scenePartDefaultData); 18785 }).then((scenePart) => { 18786 sceneData.sceneParts.push(scenePart); 18787 dataToDispatch.newSceneData = sceneData; 18788 let newDefaultValue = buildAndDecorateDecisionPointLogicValue(sceneData.id); 18789 newDefaultValueNextDpId = newDefaultValue.getNextDPLogicId(); 18790 newDecisionPointLogic = createNewDecisionPointLogic(); 18791 newDecisionPointLogic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 18792 newDecisionPointLogic.setLast(false); 18793 let decisionPointLogicObj = StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId); 18794 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(newDefaultValueNextDpId), decisionPointLogicObj); 18795 }).then((logicData) => { 18796 dataToDispatch.updatedStoryDecisionPointsLogics[newDefaultValueNextDpId] = logicData; 18797 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), newDecisionPointLogic.serializeLogicData()); 18798 }).then((logicData2) => { 18799 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = logicData2; 18800 dispatch(addSceneToStory(projectName, dataToDispatch)); 18801 if (typeof cb === "function") cb(newDefaultValueNextDpId); 18802 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18803 let input = { 18804 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18805 updated: IGNORE_UPDATED, 18806 newScene: { name: sceneName }, 18807 decisionPointToUpdate: { 18808 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 18809 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18810 updated: IGNORE_UPDATED 18811 }, 18812 newDecisionPoint: { 18813 localId: newDefaultValueNextDpId, 18814 logic: dataToDispatch.updatedStoryDecisionPointsLogics[newDefaultValueNextDpId] 18815 } 18816 }; 18817 services.graphQlClient.mutate({ 18818 mutation: UpdateStoryWithNewSceneDocument, 18819 variables: { 18820 input, 18821 dryRun: false, 18822 sceneLegacyId: dataToDispatch.newSceneData.id, 18823 scenePartLegacyId: dataToDispatch.newSceneData.sceneParts[0].scenePart, 18824 [IGNORE_SERVER_ERRORS]: true 18825 } 18826 }).catch((err) => {}); 18827 }).catch((err) => dispatch(reportError(err))); 18828 } else { 18829 let newSceneId = v4(); 18830 let newDefaultValue = buildAndDecorateDecisionPointLogicValue(newSceneId); 18831 newDefaultValueNextDpId = newDefaultValue.getNextDPLogicId(); 18832 newDecisionPointLogic = createNewDecisionPointLogic(); 18833 newDecisionPointLogic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 18834 newDecisionPointLogic.setLast(false); 18835 let decisionPointLogicObj = StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId); 18836 dataToDispatch.updatedStoryDecisionPointsLogics[newDefaultValueNextDpId] = decisionPointLogicObj; 18837 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = newDecisionPointLogic.serializeLogicData(); 18838 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18839 let input = { 18840 id: storyGQLId, 18841 updated: IGNORE_UPDATED, 18842 newScene: { name: sceneName }, 18843 decisionPointToUpdate: { 18844 id: `${storyGQLId}|${decisionPointLogicId}`, 18845 logic: newDecisionPointLogic.serializeLogicData(), 18846 updated: IGNORE_UPDATED 18847 }, 18848 newDecisionPoint: { 18849 localId: newDefaultValueNextDpId, 18850 logic: decisionPointLogicObj 18851 } 18852 }; 18853 return services.graphQlClient.mutate({ 18854 mutation: UpdateStoryWithNewSceneDocument, 18855 variables: { 18856 input, 18857 dryRun: false, 18858 sceneLegacyId: newSceneId 18859 } 18860 }).then((gqlOutput) => { 18861 handleUpdateStoryWithNewSceneResponse(dispatch, projectName, newSceneId, sceneName, dataToDispatch, gqlOutput, () => cb && cb(newDefaultValueNextDpId)); 18862 }).catch((err) => {}); 18863 } 18864 }; 18865}; 18866var addExistingSceneBefore = (account, projectName, storyId, decisionPointLogicId, sceneId, cb) => { 18867 return (dispatch, getState, services) => { 18868 let newDecisionPointLogic = createNewDecisionPointLogic(); 18869 let dataToDispatch = { 18870 updatedStoryDecisionPointsLogics: {}, 18871 storyId 18872 }; 18873 let newDefaultValue = buildAndDecorateDecisionPointLogicValue(sceneId); 18874 let newDefaultValueNextDpId = newDefaultValue.getNextDPLogicId(); 18875 newDecisionPointLogic.setDefaultValue(newDefaultValue.serializeDecisionPointLogicValue()); 18876 newDecisionPointLogic.setLast(false); 18877 let decisionPointLogicObj = StateReaderUtils.getDecisionPointsLogic(getState(), projectName, storyId, decisionPointLogicId); 18878 dataToDispatch.updatedStoryDecisionPointsLogics[newDefaultValueNextDpId] = decisionPointLogicObj; 18879 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = newDecisionPointLogic.serializeLogicData(); 18880 const dispatchAddSceneToStorySuccess = (dataToDispatch) => { 18881 dispatch(addSceneToStory(projectName, dataToDispatch)); 18882 if (typeof cb === "function") cb(newDefaultValueNextDpId); 18883 }; 18884 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(newDefaultValueNextDpId), decisionPointLogicObj).then((logicData) => { 18885 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), newDecisionPointLogic.serializeLogicData()); 18886 }).then((logicData2) => { 18887 dispatchAddSceneToStorySuccess(dataToDispatch); 18888 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18889 let input = { 18890 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18891 updated: IGNORE_UPDATED, 18892 newDecisionPoints: [{ 18893 localId: newDefaultValueNextDpId, 18894 logic: dataToDispatch.updatedStoryDecisionPointsLogics[newDefaultValueNextDpId] 18895 }], 18896 decisionPointsToUpdate: [{ 18897 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 18898 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18899 updated: IGNORE_UPDATED 18900 }] 18901 }; 18902 services.graphQlClient.mutate({ 18903 mutation: UpdateStoryWithDecisionPointsDocument, 18904 variables: { 18905 input, 18906 dryRun: false, 18907 [IGNORE_SERVER_ERRORS]: true 18908 } 18909 }).catch((err) => {}); 18910 }).catch((err) => dispatch(reportError(err))); 18911 else {
18912 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18913 let input = { 18914 id: storyGQLId, 18915 updated: IGNORE_UPDATED, 18916 newDecisionPoints: [{ 18917 localId: newDefaultValueNextDpId, 18918 logic: dataToDispatch.updatedStoryDecisionPointsLogics[newDefaultValueNextDpId] 18919 }], 18920 decisionPointsToUpdate: [{ 18921 id: `${storyGQLId}|${decisionPointLogicId}`, 18922 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18923 updated: IGNORE_UPDATED 18924 }] 18925 }; 18926 return services.graphQlClient.mutate({ 18927 mutation: UpdateStoryWithDecisionPointsDocument, 18928 variables: { 18929 input, 18930 dryRun: false 18931 } 18932 }).then((gqlOutput) => { 18933 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 18934 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 18935 dispatchAddSceneToStorySuccess(dataToDispatch); 18936 } 18937 }).catch((err) => {}); 18938 } 18939 }; 18940}; 18941var updateDecisionPointLogicAndAddNewDecisionPointLogic = (account, projectName, storyId, decisionPointLogicId, decisionPointLogic, newDPLogicItemsIdsArray) => { 18942 return (dispatch, getState, services) => { 18943 let newDecisionPointLogic = createNewDecisionPointLogic().serializeLogicData(); 18944 let dataToDispatch = { 18945 storyId, 18946 updatedStoryDecisionPointsLogics: {} 18947 }; 18948 newDPLogicItemsIdsArray.forEach((logicId) => { 18949 dataToDispatch.updatedStoryDecisionPointsLogics[logicId] = newDecisionPointLogic; 18950 }); 18951 dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId] = decisionPointLogic; 18952 const dispatchUpdateDPLogicAndAddNewDPLogicSuccess = (dataToDispatch) => { 18953 dispatch(updateDPLogicAndAddNewDPLogic(projectName, dataToDispatch)); 18954 }; 18955 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) { 18956 let promiseArr = newDPLogicItemsIdsArray.map((newDecisionPointLogicId) => services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(newDecisionPointLogicId), newDecisionPointLogic)); 18957 return Promise.all(promiseArr).then((logicDataArray) => { 18958 return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), decisionPointLogic); 18959 }).then((logicData2) => { 18960 dispatchUpdateDPLogicAndAddNewDPLogicSuccess(dataToDispatch); 18961 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 18962 let input = { 18963 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 18964 updated: IGNORE_UPDATED, 18965 newDecisionPoints: newDPLogicItemsIdsArray.map((dpId) => { 18966 return { 18967 localId: dpId, 18968 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId] 18969 }; 18970 }), 18971 decisionPointsToUpdate: [{ 18972 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 18973 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 18974 updated: IGNORE_UPDATED 18975 }] 18976 }; 18977 services.graphQlClient.mutate({ 18978 mutation: UpdateStoryWithDecisionPointsDocument, 18979 variables: { 18980 input, 18981 dryRun: false, 18982 [IGNORE_SERVER_ERRORS]: true 18983 } 18984 }).catch((err) => {}); 18985 }).catch((err) => dispatch(reportError(err))); 18986 } else { 18987 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 18988 let input = { 18989 id: storyGQLId, 18990 updated: IGNORE_UPDATED, 18991 newDecisionPoints: newDPLogicItemsIdsArray.map((dpId) => { 18992 return { 18993 localId: dpId, 18994 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId] 18995 }; 18996 }), 18997 decisionPointsToUpdate: [{ 18998 id: `${storyGQLId}|${decisionPointLogicId}`, 18999 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 19000 updated: IGNORE_UPDATED 19001 }] 19002 }; 19003 return services.graphQlClient.mutate({ 19004 mutation: UpdateStoryWithDecisionPointsDocument, 19005 variables: { 19006 input, 19007 dryRun: false 19008 } 19009 }).then((gqlOutput) => { 19010 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 19011 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 19012 dispatchUpdateDPLogicAndAddNewDPLogicSuccess(dataToDispatch); 19013 } 19014 }).catch((err) => {}); 19015 } 19016 }; 19017}; 19018var updateDecisionPointLogic = (account, projectName, storyId, decisionPointLogicId, decisionPointLogic) => { 19019 return (dispatch, getState, services) => { 19020 let dataToDispatch = { 19021 storyId, 19022 updatedStoryDecisionPointsLogics: { [decisionPointLogicId]: decisionPointLogic } 19023 }; 19024 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) return services.wireframes.setProjectWireFramesSceneInputLogic(account, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(decisionPointLogicId), decisionPointLogic).then((logicData) => { 19025 dispatch(updateDPLogic(projectName, dataToDispatch)); 19026 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 19027 let input = { 19028 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 19029 updated: IGNORE_UPDATED, 19030 decisionPointsToUpdate: [{ 19031 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${decisionPointLogicId}`, 19032 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 19033 updated: IGNORE_UPDATED 19034 }] 19035 }; 19036 services.graphQlClient.mutate({ 19037 mutation: UpdateStoryWithDecisionPointsDocument, 19038 variables: { 19039 input, 19040 dryRun: false, 19041 [IGNORE_SERVER_ERRORS]: true 19042 } 19043 }).catch((err) => {}); 19044 }).catch((err) => dispatch(reportError(err))); 19045 else {
19046 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 19047 let input = { 19048 id: storyGQLId, 19049 updated: IGNORE_UPDATED, 19050 decisionPointsToUpdate: [{ 19051 id: `${storyGQLId}|${decisionPointLogicId}`, 19052 logic: dataToDispatch.updatedStoryDecisionPointsLogics[decisionPointLogicId], 19053 updated: IGNORE_UPDATED 19054 }] 19055 }; 19056 return services.graphQlClient.mutate({ 19057 mutation: UpdateStoryWithDecisionPointsDocument, 19058 variables: { 19059 input, 19060 dryRun: false 19061 } 19062 }).then((gqlOutput) => { 19063 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 19064 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 19065 dispatch(updateDPLogic(projectName, dataToDispatch)); 19066 } 19067 }).catch((err) => {}); 19068 } 19069 }; 19070}; 19071var updateSoundtrackLogic = (account, projectName, storyId, soundtrackLogic) => { 19072 return updateStoryLogic(account, projectName, storyId, LogicContainers.Soundtrack, MediaTypes.Audio, soundtrackLogic); 19073}; 19074var updateStoryBackgroundAssetLogic = (account, projectName, storyId, backgroundAssetType, backgroundLogic) => { 19075 return updateStoryLogic(account, projectName, storyId, LogicContainers.BackgroundAsset, backgroundAssetType, backgroundLogic); 19076}; 19077var updateStoryVideoRatioQualityLogic = (account, projectName, storyId, ratioQualityLogic) => { 19078 return updateStoryLogic(account, projectName, storyId, LogicContainers.VideoSettings, LogicContext.StoryRatioAndQuality, ratioQualityLogic); 19079}; 19080var updateStoryLogic = (account, projectName, storyId, logicContainerType, logicId, storyLogic) => { 19081 return (dispatch, getState, services) => { 19082 let dataToDispatch = { 19083 storyId, 19084 logicContainerType, 19085 updatedStoryLogicItems: { [logicId]: storyLogic } 19086 }; 19087 let input = { 19088 id: StateReaderUtils.getStoryGqlId(getState(), projectName, storyId), 19089 updated: IGNORE_UPDATED 19090 }; 19091 switch (logicId) { 19092 case MediaTypes.Image: 19093 input.backgroundImageLogic = storyLogic; 19094 break; 19095 case MediaTypes.Video: 19096 input.backgroundVideoLogic = storyLogic; 19097 break; 19098 case MediaTypes.Audio: 19099 input.backgroundAudioLogic = storyLogic; 19100 break; 19101 case LogicContext.StoryRatioAndQuality: 19102 input.ratioAndQualityLogic = storyLogic; 19103 break; 19104 default: break; 19105 } 19106 return services.graphQlClient.mutate({ 19107 mutation: UpdateStoryForBuilderDocument, 19108 variables: { 19109 input, 19110 dryRun: false 19111 } 19112 }).then((gqlOutput) => { 19113 if (gqlOutput.data.updateStoryForBuilder.__typename === "UpdateStoryForBuilderOutputSuccess") { 19114 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryForBuilder.story.updated }; 19115 dispatch(updateStoryLogicItems(projectName, dataToDispatch)); 19116 } 19117 }).catch((err) => {}); 19118 }; 19119}; 19120var mergeDecisionPoints = (accountId, projectName, storyId, decisionPointAId, decisionPointBId, cb) => { 19121 return (dispatch, getState, services) => { 19122 let dataToDispatch = { 19123 storyId, 19124 updatedStoryDecisionPointsLogics: {}, 19125 decisionPointLogicIdToDelete: "" 19126 }; 19127 const storyDecisionPointsObj = StateReaderUtils.getDecisionPointLogicItemsForStory(getState(), projectName, storyId); 19128 if (!isLogicEmpty(storyDecisionPointsObj[decisionPointAId]) && !isLogicEmpty(storyDecisionPointsObj[decisionPointBId])) { 19129 dispatch(reportError("illegal merge action")); 19130 if (typeof cb === "function") cb(decisionPointAId); 19131 } else { 19132 let prevDpId = decisionPointBId; 19133 let nextDpId = decisionPointAId; 19134 let nextDpLogic = !isLogicEmpty(storyDecisionPointsObj[decisionPointBId]) ? storyDecisionPointsObj[decisionPointBId] : storyDecisionPointsObj[decisionPointAId]; 19135 let updatedStoryDecisionPointsObj = Object.keys(storyDecisionPointsObj).reduce((acc, dpId) => { 19136 if (isDPLogicItemContainDPId(storyDecisionPointsObj[dpId], prevDpId)) acc[dpId] = replaceDPLogicIdWithOther(storyDecisionPointsObj[dpId], prevDpId, nextDpId); 19137 return acc; 19138 }, {}); 19139 updatedStoryDecisionPointsObj[nextDpId] = nextDpLogic; 19140 dataToDispatch.updatedStoryDecisionPointsLogics = updatedStoryDecisionPointsObj; 19141 dataToDispatch.decisionPointLogicIdToDelete = prevDpId; 19142 const dispatchMergeDecisionPointsSuccess = (dataToDispatch) => { 19143 dispatch(mergeDecisionPointsSuccess(projectName, dataToDispatch)); 19144 if (typeof cb === "function") cb(nextDpId); 19145 }; 19146 if (!StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities)) { 19147 let promiseArray = Object.keys(updatedStoryDecisionPointsObj).map((dpID) => { 19148 return services.wireframes.setProjectWireFramesSceneInputLogic(accountId, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(dpID), updatedStoryDecisionPointsObj[dpID]); 19149 }); 19150 return Promise.all(promiseArray).then((updateDecisionPointLogic) => { 19151 dispatchMergeDecisionPointsSuccess(dataToDispatch); 19152 return services.wireframes.deleteProjectWireFramesInputLogic(accountId, projectName, getStoryLogicContainerId(storyId), getDecisionPointLogicContainerId(prevDpId)).then(() => { 19153 let programSummary = findProgramSummaryForProgramId(StateReaderUtils.getProgramSummaries(getState()), projectName); 19154 let input = { 19155 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}`, 19156 updated: IGNORE_UPDATED, 19157 decisionPointsToUpdate: Object.keys(dataToDispatch.updatedStoryDecisionPointsLogics).map((dpId) => { 19158 return { 19159 id: `${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${dpId}`, 19160 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId], 19161 updated: IGNORE_UPDATED 19162 }; 19163 }), 19164 decisionPointsToDeleteIds: [`${programSummary.projectIds.builderDraftVersionId}|${dataToDispatch.storyId}|${prevDpId}`] 19165 }; 19166 services.graphQlClient.mutate({ 19167 mutation: UpdateStoryWithDecisionPointsDocument, 19168 variables: { 19169 input, 19170 dryRun: false, 19171 [IGNORE_SERVER_ERRORS]: true 19172 } 19173 }).catch((err) => {}); 19174 }).catch((err) => {}); 19175 }).catch((err) => dispatch(reportError(err))); 19176 } else { 19177 const storyGQLId = StateReaderUtils.getStoryGqlId(getState(), projectName, storyId); 19178 let input = { 19179 id: storyGQLId, 19180 updated: IGNORE_UPDATED, 19181 decisionPointsToUpdate: Object.keys(dataToDispatch.updatedStoryDecisionPointsLogics).map((dpId) => { 19182 return { 19183 id: `${storyGQLId}|${dpId}`, 19184 logic: dataToDispatch.updatedStoryDecisionPointsLogics[dpId], 19185 updated: IGNORE_UPDATED 19186 }; 19187 }), 19188 decisionPointsToDeleteIds: [`${storyGQLId}|${prevDpId}`] 19189 }; 19190 return services.graphQlClient.mutate({ 19191 mutation: UpdateStoryWithDecisionPointsDocument, 19192 variables: { 19193 input, 19194 dryRun: false 19195 } 19196 }).then((gqlOutput) => { 19197 if (gqlOutput.data.updateStoryWithDecisionPoints.__typename === "UpdateStoryWithDecisionPointsOutputSuccess") { 19198 dataToDispatch.storyDataToUpdate = { graphQLUpdated: gqlOutput.data.updateStoryWithDecisionPoints.story.updated }; 19199 dispatchMergeDecisionPointsSuccess(dataToDispatch); 19200 } 19201 }).catch((err) => {}); 19202 } 19203 } 19204 }; 19205}; 19206var moveProjectWireframesSceneInStory = function(accountId, projectName, storyId, sceneId, storyScenesOrder, offset) { 19207 return function(dispatch, getState, services) { 19208 let story = StateReaderUtils.getStoryById(StateReaderUtils.getWireFrame(getState(), projectName), storyId); 19209 let newIndex = (storyScenesOrder || []).indexOf(sceneId) + offset; 19210 if (newIndex < 0) newIndex = 0; 19211 if (newIndex >= storyScenesOrder.length) newIndex = storyScenesOrder.length - 1; 19212 let newScenesOrder = storyScenesOrder.filter((id) => id !== sceneId); 19213 newScenesOrder = [ 19214 ...newScenesOrder.slice(0, newIndex), 19215 sceneId, 19216 ...newScenesOrder.slice(newIndex) 19217 ]; 19218 const scenes = StateReaderUtils.getProjectWireframeScenes(getState(), projectName); 19219 const input = { 19220 id: story.graphQLId, 19221 updated: IGNORE_UPDATED, 19222 displaySceneOrder: newScenesOrder && newScenesOrder.map((sceneLocalId) => scenes[sceneLocalId]?.graphQLId).filter((id) => !!id) 19223 }; 19224 return services.graphQlClient.mutate({ 19225 mutation: UpdateStoryForBuilderDocument, 19226 variables: { 19227 input, 19228 dryRun: false 19229 } 19230 }).then((gqlOutput) => { 19231 if (gqlOutput.data.updateStoryForBuilder.__typename === "UpdateStoryForBuilderOutputSuccess") dispatch(updateStory(accountId, projectName, storyId, { 19232 ...story, 19233 displaySceneOrder: newScenesOrder, 19234 graphQLUpdated: gqlOutput.data.updateStoryForBuilder.story.updated 19235 })); 19236 }).catch((err) => {}); 19237 }; 19238}; 19239//#endregion 19240//#region common/featureFlags/featureFlagConst.ts 19241var featureFlagConst = { 19242 CREATIVE: "creative", 19243 UPLOAD_NARRATION_CSV: "uploadNarrationFromCSV", 19244 STORY_LOGIC: "storyLogic", 19245 CREATIVE_SHOW_UNUSED_CDES_TAB: "creativeShowUnusedCDEsTab", 19246 OVERVIEW_WITHOUT_OVERVIEW_TAB: "overviewWithoutOverviewTab", 19247 ADS_REPORT_DE_TO_VIDEOSPEC: "adsReportDeToVideospec", 19248 USE_OLD_RENDERER_BY_DEFAULT: "useOldRendererByDefault", 19249 FULL_DEMO_FLOW_BUILDER: "fullDemoFlowBuilder", 19250 CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC: "crmStoryVideoRatioQualityLogic", 19251 ADS_STORY_VIDEO_RATIO_QUALITY_DEFINITION: "adsStoryVideoRatioQualityDefinition",
19252 SSO_FOR_EXTERNAL_USERS: "ssoForExternalUsers", 19253 GET_PRESETS_VALUES_SPLIT: "getPresetsValuesSplit", 19254 _EDITOR_GENERATE_VIDEO_LINKS_DEMO_FLOW: "_editor generate video links demo flow", 19255 FORMSTACK_SURVEY_REPORT_CONFIGURATION: "formstack survey report configuration", 19256 _EDITOR_CREATE_ACCOUNTS_DB_PROGRAM: "_editor create accounts db program", 19257 _EDITOR_REMOVE_ALL_EXTERNAL_USERS_FROM_ACCOUNT: "_editor remove all external users from account", 19258 _EDITOR_ENABLE_ASSET_POST_ASSIGNING: "_editor enable asset post assigning", 19259 _EDITOR_NEW_VIDEO_PAGE: "_editor new video page", 19260 _EDITOR_INNOVATION_SCENES_TRANSITIONS: "_editor innovation week scenes transitions", 19261 _EDITOR_BLOCK_APPROVAL_GETTY_PREMIUM: "_editor block approval getty premium", 19262 _EDITOR_BLOCK_DUPLICATING_VIDEOS_USING_OLD_LAYOUTS: "_editor block duplicating videos using old layouts", 19263 _EDITOR_DRAFT_WATERMARK: "_editor draft watermark", 19264 _EDITOR_BLOCK_EDITING_OLD_LAYOUTS: "_editor block editing old layouts", 19265 _EDITOR_GENERATE_VIDEO_WITH_AI: "_editor generate video with ai", 19266 _EDITOR_IMPROVED_ASSET_EDITING: "_editor improved asset editing", 19267 _EDITOR_CUSTOM_AVATARS_CREATE_REAL_AVATAR: "_editor custom avatars create real avatar", 19268 _EDITOR_ANALYTICS_AND_REPORTS_STATUS: "_editor analytics and reports status", 19269 _EDITOR_AI_WEEK_ANIMATE_IMAGE: "_editor ai week animate image", 19270 _EDITOR_DATA_LIBRARY_DUPLICATE_AND_SWITCH: "_editor data library duplicate and switch", 19271 _EDITOR_PLACE_HOLDER_RICH_TEXT_AI_BUTTON: "_editor place holder rich text ai button", 19272 _CONTRIBUTORS_PROFILE_IMAGE: "_contributor profile image", 19273 _EDITOR_AMPLIFY_RECORDER: "_editor amplify recorder", 19274 _EDITOR_TOP_BAR_MODIFICATIONS: "_editor top bar modifications", 19275 _EDITOR_LANGUAGE_LOCALIZATION: "_editor language localization", 19276 _IMPROVED_TIERS_AND_CREDITS: "_improved tiers and credits", 19277 _EDITOR_TEMPLATE_CHANGES: "_editor template changes", 19278 _EDITOR_DUPLICATE_VIDEO_AS_TEMPLATE: "_editor duplicate video as template", 19279 _EDITOR_ACCOUNT_SETTINGS_DIALOG: "_editor account settings dialog", 19280 _EDITOR_SLIDES_TO_VIDEO: "_editor slides to video", 19281 _EDITOR_SCRIPT_TO_VIDEO: "_editor script to video", 19282 _EDITOR_SCENE_REUSE: "_editor scene reuse", 19283 _EDITOR_SCENE_REUSE_RELEASE_2: "_editor scene reuse release 2", 19284 _ANALYTICS_VIEWING_DATA_SINGLETON: "_analytics viewing data singleton", 19285 _EDITOR_ALLOW_EXTENDED_VALUE_SET: "_editor allow extended value set", 19286 _EDITOR_IMGLY_CONVERT_IMAGE_TO_VIDEO: "_editor imgly convert image to video", 19287 _EDITOR_IMGLY_NARRATION_REFERENCE: "_editor imgly narration reference", 19288 _EDITOR_TOOLBAR_MEDIA: "_editor media new toolbar", 19289 _EDITOR_INPUT_URL_VALIDATION: "_editor input URL validation", 19290 _EDITOR_GEN_AI_VID_ASSET_PROD: "_editor gen ai vid asset prod", 19291 _EDITOR_CONTENT_SECURITY_POLICY_ENFORCEMENT: "_editor content security policy enforcement", 19292 _EDITOR_DOCUMENT_TO_VIDEO_REFINEMENT: "_editor document to video refinement", 19293 _EDITOR_LOCALIZATION_AND_API_CONNECTOR: "_editor localization and api connector", 19294 _EDITOR_COPY_PLACEHOLDERS: "_editor copy placeholders", 19295 _EDITOR_AMPLIFY_ANALYTICS: "_editor amplify analytics", 19296 _SERVER_RATE_LIMIT_ENABLED: "_server rate limit enabled", 19297 _SERVER_RATE_LIMIT_BLOCKING_ENABLED: "_server rate limit blocking enabled", 19298 _EDITOR_ADD_SCENE_BEHAVIOR: "_editor add scene behavior", 19299 _EDITOR_GEN_AI_EDIT_AND_CONVERT: "_editor gen ai edit and convert", 19300 _EDITOR_ANIMATION_CUES: "_editor animation cues", 19301 _SERVER_ENFORCE_CAPTCHA_ON_FORGOT_PASSWORD: "_server enforce captcha on forgot password", 19302 _DISABLE_CLIENT_OFFLINE_DETECTION: "_disable client offline detection", 19303 _EDITOR_FILTER_ASSETS_ON_CREATE_SNAPSHOT: "_editor filter assets on create snapshot", 19304 _EDITOR_WORKFLOWS_RELEASE_1: "_editor workflows release 1", 19305 _EDITOR_WORKFLOWS_RELEASE_2: "_editor workflows release 2", 19306 _EDITOR_WORKFLOWS_RELEASE_3: "_editor workflows release 3", 19307 _EDITOR_DEPRECATE_AI_VOICES: "_editor deprecate ai voices", 19308 _IN_APP_NOTIFICATIONS_MVP: "_in app notifications mvp", 19309 _EDITOR_RESIZABLE_BUTTONS: "_editor resizable buttons", 19310 _EDITOR_FLEXIBLE_BULLETS: "_editor flexible bullets", 19311 _AMPLIFY_TEMPLATE_ACCESS_CONTROL_R1: "_amplify template access control r1", 19312 _EDITOR_ACCESS_CONTROL_R2: "_editor access control r2", 19313 _EDITOR_AMPLIFY_ANALYTICS_EXPORT_CSV: "_editor amplify analytics export csv", 19314 _EDITOR_NEW_BUTTON_TOOLBAR: "_editor new button toolbar", 19315 _EDITOR_MORE_LANGUAGES: "_editor more languages", 19316 _EDITOR_ON_SCREEN_TEXT_TRANSLATION: "_editor on screen text translation", 19317 _DATABASE_ENHANCEMENTS: "_database enhancements", 19318 _EDITOR_DOWNLOAD_FULL_HD_TS: "_editor download full hd ts", 19319 _TEMPLATE_ANALYTICS_RELEASE_3: "_template analytics release 3", 19320 _EDITOR_SELECT_FOLDER_TO_CREATE_VIDEO: "_editor select folder to create video", 19321 _AI_IMAGE_GENERATION_USE_IMAGEN_4: "_ai image generation use imagen 4", 19322 _EDITOR_AI_VOICES_TERMS: "_editor ai voices terms", 19323 _AMPLIFY_EMAIL_STATIC_THUMBNAIL: "_amplify email static thumbnail", 19324 _ADS_SPACE_R1: "_ads space r1", 19325 _USE_SES_EMAIL_SERVICE: "_use ses email service", 19326 _BRAND_PROPS_RUNTIME_OVERRIDE: "_brand props runtime override", 19327 _EDITOR_SLIDES_TO_VIDEO_REWRITE: "_editor slides to video rewrite", 19328 _EDITOR_SLIDES_TO_VIDEO_SHAPES: "_editor slides to video shapes", 19329 _EDITOR_PRONUNCIATION_CASE_INSENSITIVITY: "_editor pronunciation case insensitivity", 19330 _DATABASE_DEBUGGING: "_database debugging", 19331 _CX_ALL_PROGRAMS_READER_QUERY: "_cx all programs reader query", 19332 _ACCEPT_IDP_INITIATED_SSO_LOGIN: "_accept idp initiated sso login" 19333}; 19334//#endregion 19335//#region client/logic/framework/entities/program/program.ts 19336var onSave = (args) => { 19337 const { data, createCB, updateCB, dryRun } = args; 19338 if (!data.id) createCB({ variables: { input: data } }); 19339 else updateCB({ variables: { 19340 input: data, 19341 dryRun 19342 } }); 19343}; 19344var navigateToProgramAfterCreation = (loadProjectSummaries, userRoles, newlyCreatedProgram, history, studioMainCategoriesPath) => { 19345 loadProjectSummaries(newlyCreatedProgram.accountId, true, () => { 19346 let path;
19347 const redirectToFramework = userRoles.includes(roles.admin) || userRoles.includes(roles.frameworkEditor) || userRoles.includes(roles.frameworkViewer); 19348 if (studioMainCategoriesPath) path = (0, import_dist$9.legacyAccountAccountIdProgramProgramIdNavigationItemTypePath)({ 19349 accountId: newlyCreatedProgram.accountId, 19350 programId: newlyCreatedProgram.id, 19351 navigationItemType: studioMainCategoriesPath 19352 }); 19353 else if (redirectToFramework) path = (0, import_dist$9.legacyAccountAccountIdProgramProgramIdNavigationItemTypePath)({ 19354 accountId: newlyCreatedProgram.accountId, 19355 programId: newlyCreatedProgram.id, 19356 navigationItemType: import_dist$9.StudioMainCategoriesPaths.Framework 19357 }); 19358 else path = (0, import_dist$9.legacyAccountAccountIdProgramProgramIdNavigationItemTypePath)({ 19359 accountId: newlyCreatedProgram.accountId, 19360 programId: newlyCreatedProgram.legacyBuilderProgramId, 19361 navigationItemType: import_dist$9.StudioMainCategoriesPaths.Builder 19362 }); 19363 history.push(path); 19364 }); 19365}; 19366var Program = { 19367 queries: { 19368 data: withGetProgram({ 19369 name: "queryProgram", 19370 options: ({ programId }) => ({ variables: { id: programId } }), 19371 skip: ({ programId }) => !programId 19372 }), 19373 metadata: withGetProgramMetadata({ 19374 name: "queryProgramMetadata", 19375 options: ({ programId }) => ({ variables: { id: programId } }), 19376 skip: ({ programId }) => !programId 19377 }) 19378 }, 19379 mutations: { 19380 createProgramAndDraft: withCreateProgramAndDraft({ 19381 name: "createProgramAndDraft", 19382 options: ({ setMutationResult, setNewProgramId }) => ({ onCompleted: ({ createProgramAndDraft }) => { 19383 setMutationResult(createProgramAndDraft.result); 19384 setNewProgramId(createProgramAndDraft.program.id); 19385 } }) 19386 }), 19387 updateProgramAndDraft: withUpdateProgramAndDraft({ 19388 name: "updateProgramAndDraft", 19389 options: ({ setMutationResult }) => ({ onCompleted: ({ updateProgramAndDraft }) => { 19390 setMutationResult(updateProgramAndDraft.result); 19391 } }) 19392 }), 19393 create: withCreateProgram({ 19394 name: "createProgram", 19395 options: ({ loadProjectSummaries, history, userRoles }) => ({ onCompleted: ({ createProgram }) => { 19396 navigateToProgramAfterCreation(loadProjectSummaries, userRoles, createProgram.program, history); 19397 } }) 19398 }), 19399 update: withUpdateFrameworkProgram({ 19400 name: "updateFrameworkProgram", 19401 options: ({ loadProjectSummaries, match, history }) => ({ onCompleted: ({ updateProgram }) => { 19402 if (updateProgram.__typename === "UpdateProgramOutputSuccess") loadProjectSummaries(updateProgram.program.accountId, true, () => { 19403 const path = (0, import_dist$9.legacyAccountAccountIdProgramProgramIdNavigationItemTypePath)({ 19404 accountId: match.params.accountId, 19405 programId: updateProgram.program.name, 19406 navigationItemType: import_dist$9.StudioMainCategoriesPaths.Builder 19407 }); 19408 history.push(path); 19409 }); 19410 } }) 19411 }), 19412 delete: withDeleteProgram({ name: "deleteProgram" }) 19413 }, 19414 onSave, 19415 navigateToProgramAfterCreation 19416}; 19417//#endregion 19418//#region client/logic/admin/adminTypes.ts 19419var SuccessAction = /* @__PURE__ */ function(SuccessAction) { 19420 SuccessAction["CREATED"] = "created"; 19421 SuccessAction["UPDATED"] = "updated"; 19422 SuccessAction["DELETED"] = "deleted"; 19423 SuccessAction["RE_ACTIVATE"] = "re-activated"; 19424 return SuccessAction; 19425}({}); 19426//#endregion 19427//#region common/types/restApiTypes.ts 19428var AnalyticsOperation = /* @__PURE__ */ function(AnalyticsOperation) { 19429 AnalyticsOperation["Create"] = "create"; 19430 AnalyticsOperation["CreateOrUpdate"] = "createOrUpdate"; 19431 AnalyticsOperation["Delete"] = "delete"; 19432 AnalyticsOperation["Query"] = "query"; 19433 AnalyticsOperation["Update"] = "update"; 19434 return AnalyticsOperation; 19435}({}); 19436var PreviewContext = /* @__PURE__ */ function(PreviewContext) { 19437 PreviewContext["DRAFT_PREVIEW"] = "DRAFT_PREVIEW"; 19438 PreviewContext["DRAFT_DOWNLOAD"] = "DRAFT_DOWNLOAD"; 19439 PreviewContext["DRAFT_REVIEWLINK"] = "DRAFT_REVIEWLINK"; 19440 PreviewContext["PUBLISHED_PREVIEW"] = "PUBLISHED_PREVIEW"; 19441 PreviewContext["PUBLISHED_DOWNLOAD"] = "PUBLISHED_DOWNLOAD"; 19442 PreviewContext["PUBLISHED_POST"] = "PUBLISHED_POST"; 19443 PreviewContext["TEMPLATE_PREVIEW"] = "TEMPLATE_PREVIEW"; 19444 return PreviewContext; 19445}({}); 19446var VideoSessionRetention = /* @__PURE__ */ function(VideoSessionRetention) { 19447 VideoSessionRetention["HALFHOUR"] = "30-min"; 19448 VideoSessionRetention["DAY"] = "1-day"; 19449 VideoSessionRetention["WEEK"] = "1-week"; 19450 VideoSessionRetention["MONTH"] = "1-month";
19451 VideoSessionRetention["PERSISTED"] = "persisted"; 19452 VideoSessionRetention["YEAR"] = "1-year"; 19453 VideoSessionRetention["QA"] = "qa"; 19454 return VideoSessionRetention; 19455}({}); 19456/** 19457* POST- /rest/testSftpConnection 19458*/ 19459var SftpConnectionType = /* @__PURE__ */ function(SftpConnectionType) { 19460 SftpConnectionType["USER_PASSWORD"] = "ftp"; 19461 SftpConnectionType["SSH_KEYS"] = "sftp"; 19462 return SftpConnectionType; 19463}({}); 19464/** 19465* POST /rest/promptToVide 19466*/ 19467var getPromptToVideoChatEndpoint = (accountId) => { 19468 return `/rest/${accountId}/promptToVideoChat`; 19469}; 19470//#endregion 19471//#region client/logic/admin/adminActions.ts 19472var GET_ALL_PROJECTS_SUCCESS = "GET_ALL_PROJECTS_SUCCESS"; 19473var IS_LOADING_ALL_PROJECTS = "IS_LOADING_ALL_PROJECTS"; 19474var getAllProjectsSuccess = (0, import_lib$3.createAction)(GET_ALL_PROJECTS_SUCCESS, (projects) => ({ projects })); 19475var isLoadingAllProjects = (0, import_lib$3.createAction)(IS_LOADING_ALL_PROJECTS, (status) => status); 19476var IS_LOADING_USERS = "IS_LOADING_USERS"; 19477var isLoadingUsers = (0, import_lib$3.createAction)(IS_LOADING_USERS, (status) => status); 19478var FETCH_USERS_SUCCESS = "FETCH_USERS_SUCCESS"; 19479var fetchAllUsersSuccess = (0, import_lib$3.createAction)(FETCH_USERS_SUCCESS, (users) => users); 19480var UPDATE_USER_SUCCESS = "UPDATE_USER_SUCCESS"; 19481var updateUserSuccess = (0, import_lib$3.createAction)(UPDATE_USER_SUCCESS, (userData) => userData); 19482var ADD_USER_SUCCESS = "ADD_USER_SUCCESS"; 19483var addUserSuccess = (0, import_lib$3.createAction)(ADD_USER_SUCCESS, (userData) => userData); 19484var IS_FETCHING_USER = "IS_FETCHING_USER"; 19485var isFetchingUser = (0, import_lib$3.createAction)(IS_FETCHING_USER, (status) => status); 19486var FETCH_USER_SUCCESS = "FETCH_USER_SUCCESS"; 19487var fetchUserSuccess = (0, import_lib$3.createAction)(FETCH_USER_SUCCESS, (userName) => userName); 19488var FETCH_ROLES_SUCCESS = "FETCH_ROLES_SUCCESS"; 19489var fetchRolesSuccess = (0, import_lib$3.createAction)(FETCH_ROLES_SUCCESS, (roles) => roles); 19490var DELETE_USER_SUCCESS = "DELETE_USER_SUCCESS"; 19491var deleteUserSuccess = (0, import_lib$3.createAction)(DELETE_USER_SUCCESS, (userName) => userName); 19492var SET_SUCCESS_MESSAGE = "SET_SUCCESS_MESSAGE"; 19493var setSuccessMessageDispatcher = (0, import_lib$3.createAction)(SET_SUCCESS_MESSAGE, (message) => message); 19494var IS_SETTING_FEATURE_FLAG = "IS_SETTING_FEATURE_FLAG"; 19495var isSettingFeatureFlag = (0, import_lib$3.createAction)(IS_SETTING_FEATURE_FLAG, (status) => status); 19496var setSuccessMessage = (message) => (dispatch, state, services) => { 19497 dispatch(setSuccessMessageDispatcher(message)); 19498}; 19499var getAllUsers = () => { 19500 return (dispatch, state, services) => { 19501 dispatch(isLoadingUsers(true)); 19502 services.adminServices.listUsers().then((data) => { 19503 dispatch(fetchAllUsersSuccess(data)); 19504 dispatch(isLoadingUsers(false)); 19505 }).catch((err) => { 19506 dispatch(reportError(err)); 19507 dispatch(isLoadingUsers(false)); 19508 }); 19509 }; 19510}; 19511var updateUser = (userData) => { 19512 return (dispatch, state, services) => { 19513 services.adminServices.updateUser(userData).then((response) => { 19514 const successMessage = { success: SuccessAction.UPDATED }; 19515 successMessage.warning = extractTableauWarning(response.status); 19516 dispatch(updateUserSuccess(response.data)); 19517 dispatch(setSuccessMessageDispatcher(successMessage)); 19518 }).catch((err) => { 19519 dispatch(setSuccessMessageDispatcher(null)); 19520 dispatch(reportError(err)); 19521 }); 19522 }; 19523}; 19524var addUser = (userData) => { 19525 return (dispatch, state, services) => { 19526 services.adminServices.addUser(userData).then((response) => { 19527 const successMessage = { success: SuccessAction.CREATED }; 19528 successMessage.warning = extractTableauWarning(response.status); 19529 dispatch(addUserSuccess(response.data)); 19530 dispatch(setSuccessMessageDispatcher(successMessage)); 19531 }).catch((err) => { 19532 dispatch(setSuccessMessageDispatcher(null)); 19533 dispatch(reportError(err)); 19534 }); 19535 }; 19536}; 19537var getUser = (userName) => { 19538 return (dispatch, state, services) => { 19539 dispatch(isFetchingUser(true)); 19540 services.adminServices.getUser(userName).then((data) => { 19541 dispatch(fetchUserSuccess(data)); 19542 dispatch(isFetchingUser(false)); 19543 dispatch(setSuccessMessageDispatcher(null)); 19544 }).catch((err) => { 19545 dispatch(reportError(err)); 19546 dispatch(isFetchingUser(false)); 19547 dispatch(setSuccessMessageDispatcher(null)); 19548 }); 19549 }; 19550}; 19551var getAllRoles = () => { 19552 return (dispatch, state, services) => { 19553 services.adminServices.listRoles().then((data) => {
19554 dispatch(fetchRolesSuccess(data)); 19555 }).catch((err) => { 19556 dispatch(reportError(err)); 19557 }); 19558 }; 19559}; 19560var deleteUser = (userName) => { 19561 return (dispatch, state, services) => { 19562 services.adminServices.deleteUser(userName).then((response) => { 19563 const successMessage = { success: SuccessAction.DELETED }; 19564 successMessage.warning = extractTableauWarning(response.status); 19565 dispatch(deleteUserSuccess(response.data)); 19566 dispatch(setSuccessMessageDispatcher(successMessage)); 19567 }).catch((err) => { 19568 dispatch(setSuccessMessageDispatcher(null)); 19569 dispatch(reportError(err)); 19570 }); 19571 }; 19572}; 19573var userResetPassword = (userName, cb) => { 19574 return (dispatch, state, services) => { 19575 services.adminServices.userResetPassword(userName).then((response) => { 19576 if (typeof cb === "function") cb(response.password); 19577 }).catch((err) => { 19578 dispatch(reportError(err)); 19579 }); 19580 }; 19581}; 19582var reActivateUser = (userData) => { 19583 return (dispatch, state, services) => { 19584 services.adminServices.deleteUser(userData.email).then((deleteResponse) => { 19585 services.adminServices.addUser(userData).then((addResponse) => { 19586 const successMessage = { success: SuccessAction.RE_ACTIVATE }; 19587 successMessage.warning = extractTableauWarning(addResponse.status); 19588 dispatch(updateUserSuccess(addResponse.data)); 19589 dispatch(setSuccessMessageDispatcher(successMessage)); 19590 }).catch((err) => { 19591 extractTableauWarning(deleteResponse.status); 19592 dispatch(deleteUserSuccess(deleteResponse.data)); 19593 dispatch(setSuccessMessageDispatcher(null)); 19594 dispatch(reportError(err)); 19595 }); 19596 }).catch((err) => { 19597 dispatch(setSuccessMessageDispatcher(null)); 19598 dispatch(reportError(err)); 19599 }); 19600 }; 19601}; 19602var getAllProjects = () => { 19603 return (dispatch, state, services) => { 19604 dispatch(isLoadingAllProjects(true)); 19605 services.adminServices.getAllProjects().then((data) => { 19606 dispatch(getAllProjectsSuccess(data)); 19607 dispatch(isLoadingAllProjects(false)); 19608 }).catch((err) => { 19609 dispatch(isLoadingAllProjects(false)); 19610 dispatch(reportError(err)); 19611 }); 19612 }; 19613}; 19614var extractTableauWarning = (responseData) => { 19615 if (!responseData?.hasErrorInAnalytics) return; 19616 switch (responseData.analyticsOperation) { 19617 case AnalyticsOperation.Create: 19618 case AnalyticsOperation.Update: 19619 case AnalyticsOperation.Delete: return `Tableau user couldn't be ${responseData.analyticsOperation}d`; 19620 case AnalyticsOperation.Query: return "Tableau user status is unclear"; 19621 default: return "Tableau user couldn't be handled"; 19622 } 19623}; 19624//#endregion 19625//#region client/logic/featureFlags/featureFlagsActions.ts 19626var import_query_string = /* @__PURE__ */ __toESM(require_query_string()); 19627var ENABLING_ALL_FEATURE_FLAGS_SUCCESS = "ENABLING_ALL_FEATURE_FLAGS_SUCCESS"; 19628var enablingAllFeatureFlagsSuccess = (0, import_lib$3.createAction)(ENABLING_ALL_FEATURE_FLAGS_SUCCESS, (enable) => { 19629 return { enable }; 19630}); 19631var SET_FEATURE_FLAG_STATUS_IN_STATE = "SET_FEATURE_FLAG_STATUS_IN_STATE"; 19632var setFeatureFlagStatusInState = (0, import_lib$3.createAction)(SET_FEATURE_FLAG_STATUS_IN_STATE, (featureFlagId, status) => { 19633 return { 19634 featureFlagId, 19635 status 19636 }; 19637}); 19638var LOADING_FEATURE_FLAGS_SUCCESS = "LOADING_FEATURE_FLAGS_SUCCESS"; 19639var loadingFeatureFlagsSuccess = (0, import_lib$3.createAction)(LOADING_FEATURE_FLAGS_SUCCESS, (featureFlags) => { 19640 return { featureFlags }; 19641}); 19642var LOADING_PROGRAMS_DYNAMO_MIGRATION_STATUS = "LOADING_PROGRAMS_DYNAMO_MIGRATION_STATUS"; 19643var loadingProgramsDynamoMigrationStatus = (0, import_lib$3.createAction)(LOADING_PROGRAMS_DYNAMO_MIGRATION_STATUS, (programsDynamoMigrationStatus) => { 19644 return { programsDynamoMigrationStatus }; 19645}); 19646var SET_FEATURE_FLAG_SUCCESS = "SET_FEATURE_FLAG_SUCCESS"; 19647var setFeatureFlagSuccess = (0, import_lib$3.createAction)(SET_FEATURE_FLAG_SUCCESS, (featureFlag) => { 19648 return { featureFlag }; 19649}); 19650var loadFeatureFlags = () => { 19651 return (dispatch, state, services) => { 19652 let enableAllFeatureFlags = import_query_string.parse(window?.location?.search).enableAllFeatureFlags; 19653 if (enableAllFeatureFlags !== void 0) { 19654 enableAllFeatureFlags = enableAllFeatureFlags === "true"; 19655 dispatch(enablingAllFeatureFlagsSuccess(enableAllFeatureFlags)); 19656 } else services.featureFlags.getFeatureFlags().then((res) => { 19657 dispatch(loadingFeatureFlagsSuccess(res)); 19658 }).catch((err) => { 19659 dispatch(reportError(err)); 19660 }); 19661 }; 19662}; 19663var loadProgramsMigrationStatus = () => { 19664 return (dispatch, state, services) => { 19665 services.graphQlClient.query({ 19666 fetchPolicy: "no-cache", 19667 query: GetProgramsDynamoMigrationStatusDocument 19668 }).then((res) => { 19669 dispatch(loadingProgramsDynamoMigrationStatus(res.data.programsDynamoMigrationStatus)); 19670 }); 19671 }; 19672}; 19673var setFeatureFlag = (featureFlagId, defaultValue, excludedPrograms, excludedAccounts) => { 19674 return (dispatch, state, services) => { 19675 dispatch(isSettingFeatureFlag(true)); 19676 services.featureFlags.setFeatureFlag(featureFlagId, defaultValue, excludedPrograms, excludedAccounts).then((res) => { 19677 dispatch(setFeatureFlagSuccess(res)); 19678 dispatch(isSettingFeatureFlag(false)); 19679 }).catch((err) => { 19680 dispatch(reportError(err)); 19681 dispatch(isSettingFeatureFlag(false)); 19682 }); 19683 }; 19684}; 19685//#endregion 19686//#region client/logic/common/convertGqlLifecycleHistoryUtils.ts 19687var convertSingleGqlLifecycleHistoryEntry = (lifecycleHistoryEntry) => ({ 19688 stage: lifecycleHistoryEntry.lifecycleStage, 19689 snapshotNumber: lifecycleHistoryEntry.snapshotNumber, 19690 promotedDate: new Date(lifecycleHistoryEntry.created).valueOf(), 19691 promotedBy: lifecycleHistoryEntry.createdBy, 19692 graphQlId: lifecycleHistoryEntry.id 19693}); 19694var convertGqlLifecycleHistoryResult = (gqlResult) => { 19695 const gqlLifecycleHistory = gqlResult?.data?.program?.lifecycleHistory; 19696 let accInitialValue = Object.values(Stages).reduce((acc, stage) => { 19697 acc[stage.toString()] = []; 19698 return acc; 19699 }, {}); 19700 const lifecycleHistoryByStaged = gqlLifecycleHistory?.reduce((acc, lifecycleHistoryEntry) => { 19701 if (lifecycleHistoryEntry?.lifecycleStage && acc[lifecycleHistoryEntry.lifecycleStage]) acc[lifecycleHistoryEntry.lifecycleStage].push(convertSingleGqlLifecycleHistoryEntry(lifecycleHistoryEntry)); 19702 return acc; 19703 }, accInitialValue); 19704 return Object.keys(lifecycleHistoryByStaged).map((key) => { 19705 return { 19706 name: key, 19707 snapshots: lifecycleHistoryByStaged[key].sort((a, b) => b.promotedDate - a.promotedDate) 19708 }; 19709 }); 19710}; 19711//#endregion 19712//#region client/logic/Logics/StoryRatioAndQualityLogic.ts 19713var { CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC: CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC$2 } = featureFlagConst; 19714var createNewStoryQualityRatioValue = () => { 19715 return [{ 19716 id: "videoAspectRatio", 19717 displayName: "Ratio", 19718 outputType: LogicType.Ratio, 19719 value: null, 19720 show: true 19721 }, { 19722 id: "videoQualityProfile", 19723 displayName: "Quality", 19724 outputType: LogicType.Quality, 19725 value: null, 19726 show: true 19727 }]; 19728}; 19729var createNewStoryQualityRatioLogic = () => { 19730 return createLogic({ 19731 outputType: LogicType.Compound, 19732 defaultValue: createNewStoryQualityRatioValue(), 19733 defaultValueShow: true, 19734 rules: [] 19735 }); 19736}; 19737var RatioOptions = [ 19738 { 19739 id: VideoAspectRatio.FULL_LANDSCAPE, 19740 name: "Full Landscape (16:9)" 19741 }, 19742 { 19743 id: VideoAspectRatio.FULL_PORTRAIT, 19744 name: "Full Portrait (9:16)" 19745 }, 19746 { 19747 id: VideoAspectRatio.SQUARE, 19748 name: "Square (1:1)" 19749 } 19750]; 19751var QualityOptions = [ 19752 { 19753 id: VideoQualityProfile.SD, 19754 name: "SD" 19755 }, 19756 { 19757 id: VideoQualityProfile.SD_INTERMEDIATE, 19758 name: "SD Intermediate" 19759 }, 19760 { 19761 id: VideoQualityProfile.SD_HIGH, 19762 name: "SD High" 19763 }, 19764 { 19765 id: VideoQualityProfile.HD_READY, 19766 name: "HD-Ready" 19767 }, 19768 { 19769 id: VideoQualityProfile.HD_READY_INTERMEDIATE, 19770 name: "HD-Ready Intermediate" 19771 }, 19772 { 19773 id: VideoQualityProfile.HD_READY_HIGH, 19774 name: "HD-Ready High" 19775 }, 19776 { 19777 id: VideoQualityProfile.HD, 19778 name: "HD" 19779 } 19780]; 19781var shouldUseVideoRatioAndQualityLogic = (programType, enabledFeatureFlags) => programType === ProgramType.CRM && enabledFeatureFlags.includes(CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC$2); 19782//#endregion 19783//#region client/logic/vlx/story.ts 19784var { ADS_REPORT_DE_TO_VIDEOSPEC } = featureFlagConst; 19785var defaultFormat = "m3u8"; 19786function createStoryLogic(wireframes, sceneIdToAssetName, program, accountName, ignoreNextSceneLogic, currentStory, analytics, assets, narrationsVersion, storiesVersion, creativeVersion, enabledFeatureFlags = []) { 19787 const programDataFields = { 19788 assets, 19789 dataElements: StateReaderUtils.getProjectDataElementsFromWireframes(wireframes) 19790 }; 19791 let storyLogic = { 19792 lineup: void 0, 19793 narrator: void 0, 19794 settings: { 19795 analytics: void 0, 19796 cache: void 0, 19797 projectid: generateVlxStorySettingProjectId(accountName, program.displayName), 19798 output: { formats: { video: { format: defaultFormat } } }, 19799 background: {}, 19800 settings: { enableChaptering: Boolean(program.chapteringEnabled) } 19801 }, 19802 creativeSettings: void 0, 19803 sceneOrder: void 0, 19804 tableData: void 0, 19805 transition: void 0, 19806 variables: void 0, 19807 participatingSceneIds: void 0 19808 }; 19809 if (creativeVersion > 0) { 19810 const creativeDDEId = StateReaderUtils.getCreativeDDEFromWireframes(wireframes); 19811 const creativeDDE = creativeDDEId && findDataElementById(creativeDDEId, programDataFields.dataElements); 19812 const creativeDDEDisplayName = creativeDDE && getDataElementDisplayName(creativeDDE); 19813 const storyId = currentStory.id; 19814 if (creativeDDEDisplayName && storyId) storyLogic.creativeSettings = { 19815 storyId, 19816 creativeDDE: creativeDDEDisplayName 19817 }; 19818 } 19819 const supportMultipleStories = storiesVersion > 0; 19820 if (currentStory.activateCaching) storyLogic.settings.cache = {}; 19821 if (analytics) { 19822 const LogixAnalytics = Object.assign({ 19823 story: analytics.storyData.story, 19824 storyid: analytics.storyData.storyid 19825 }, analytics.customFields); 19826 storyLogic.settings.analytics = LogixAnalytics; 19827 } 19828 let transition = StateReaderUtils.getTransition(wireframes); 19829 if (transition) { 19830 storyLogic.transition = {}; 19831 storyLogic.transition.style = transition.style ? transition.style : transition.type; 19832 storyLogic.transition.duration = transition.duration; 19833 }
19834 function createBackgroundAsset(type) { 19835 if (type && currentStory["background" + type]) storyLogic.settings.background[type] = { href: { 19836 "repo-url": currentStory["background" + type], 19837 repository: CURATED_REPOSITORY 19838 } }; 19839 } 19840 function createBackgroundAssetWithLogic(context, mediaType) { 19841 let backgroundAssetLogic = StateReaderUtils.getStoryLogicItemFromWireframeByType(wireframes, currentStory.id, context, mediaType); 19842 if (backgroundAssetLogic && Object.keys(backgroundAssetLogic).length) { 19843 let BackgroundAsset = {}; 19844 createJsonHierarchyForVar(BackgroundAsset, mediaType, { 19845 rules: buildInputRules(backgroundAssetLogic, programDataFields, false, false, false, true), 19846 type: getInputLogicType(backgroundAssetLogic) 19847 }); 19848 storyLogic.settings.background[mediaType] = BackgroundAsset[mediaType]; 19849 } 19850 } 19851 function addVideoRatioAndQualityLogicIfEnabled() { 19852 if (shouldUseVideoRatioAndQualityLogic(program.programType, enabledFeatureFlags)) { 19853 const videoRatioQualityLogic = StateReaderUtils.getStoryVideoRatioQualityLogicWireframe(wireframes, currentStory.id); 19854 if (videoRatioQualityLogic && !isAnEmptyObject(videoRatioQualityLogic)) { 19855 let videoRatioQuality = {}; 19856 createJsonHierarchyForVar(videoRatioQuality, LogicContext.StoryRatioAndQuality, { 19857 rules: buildInputRules(videoRatioQualityLogic, programDataFields, false, false, false, false), 19858 type: getInputLogicType(videoRatioQualityLogic) 19859 }); 19860 storyLogic.settings.output[LogicContext.StoryRatioAndQuality] = videoRatioQuality[LogicContext.StoryRatioAndQuality]; 19861 } 19862 } 19863 } 19864 function createNarrator() { 19865 if (narrationsVersion > 0) storyLogic.narrator = defaultNarratorId; 19866 else if (currentStory.narrator) storyLogic.narrator = currentStory.narrator; 19867 } 19868 function createLineup() { 19869 let sceneIds = supportMultipleStories ? currentStory.participatingSceneIds : currentStory.lineup; 19870 storyLogic.lineup = sceneIds.map((sceneId) => { 19871 return { 19872 name: wireframes.scenes[sceneId].name, 19873 scene: { 19874 hsrc: sceneIdToAssetName ? sceneIdToAssetName[sceneId] : "", 19875 repository: SCENES_REPOSITORY 19876 } 19877 }; 19878 }); 19879 } 19880 function createNextSceneLogic() { 19881 storyLogic.sceneOrder = { start: {} }; 19882 currentStory.lineup.forEach((sceneId, index) => { 19883 const key = index === 0 ? "start" : sceneId; 19884 storyLogic.sceneOrder[key] = { 19885 scenes: [wireframes.scenes[sceneId].name], 19886 next: { 19887 type: "state", 19888 rules: buildInputRules(wireframes.logic[sceneId][sceneId + "_nextScene"], programDataFields) 19889 } 19890 }; 19891 }); 19892 } 19893 function createSceneOrderLogic() { 19894 let allDPLogic = StateReaderUtils.getDecisionPointLogicItemsForStoryFromWireframes(wireframes, currentStory.id); 19895 storyLogic.sceneOrder = { start: { 19896 scenes: [], 19897 next: { 19898 type: "state", 19899 rules: buildInputRules(allDPLogic[currentStory.initialDecisionPointId], programDataFields, false, supportMultipleStories) 19900 } 19901 } }; 19902 currentStory.participatingDPs.forEach((DPId) => { 19903 let DPLogic = allDPLogic[DPId];
19904 getAllValues(DPLogic).forEach((value) => { 19905 let stateName = buildValue(value, LogicType.NextScene, false, null, supportMultipleStories); 19906 storyLogic.sceneOrder[stateName] = { 19907 scenes: value && value.sceneId && wireframes.scenes[value.sceneId] ? [wireframes.scenes[value.sceneId].name] : [], 19908 next: value && { 19909 type: "state", 19910 rules: buildInputRules(allDPLogic[value.nextDPLogicId], programDataFields, false, supportMultipleStories) 19911 } 19912 }; 19913 }); 19914 }); 19915 } 19916 function createVariables() { 19917 let context = { 19918 ...programDataFields, 19919 derivedLogic: wireframes.logic[LogicContainers.Derived] 19920 }; 19921 storyLogic.variables = buildDerivedDataElements(context); 19922 if (storiesVersion > 0) { 19923 let storyDE = getDynamicSystemDataElements().find((de) => de.id === SYSTEM_DATA_STORY_ID); 19924 storyLogic.variables.splice(0, 0, { 19925 name: storyDE.name, 19926 value: currentStory.name 19927 }); 19928 } 19929 } 19930 function createMappingTables() { 19931 let mappingTablesSet = (0, import_traverse.default)(wireframes.logic).reduce((acc, node) => { 19932 if (node && node.type === LOGIC_DATA_TYPES.MappingTable) { 19933 let mappingTableName = getMappingTableNameFromValue(node); 19934 if (mappingTableName) acc[mappingTableName] = node; 19935 } 19936 return acc; 19937 }, {}); 19938 storyLogic.tableData = { tables: Object.keys(mappingTablesSet) }; 19939 } 19940 if (currentStory.backgroundAssetType) createBackgroundAssetWithLogic(LogicContainers.BackgroundAsset, currentStory.backgroundAssetType); 19941 else if (currentStory.backgroundType) createBackgroundAsset(currentStory.backgroundType); 19942 if (currentStory.backgroundaudio) createBackgroundAsset("audio"); 19943 else createBackgroundAssetWithLogic(LogicContainers.Soundtrack, MediaTypes.Audio); 19944 createNarrator(); 19945 createVariables(); 19946 createMappingTables(); 19947 if (!ignoreNextSceneLogic) if (supportMultipleStories) createSceneOrderLogic(); 19948 else createNextSceneLogic(); 19949 createLineup(); 19950 if (program.programType !== ProgramType.Ads || enabledFeatureFlags.includes(ADS_REPORT_DE_TO_VIDEOSPEC)) { 19951 const logicDataElements = (programDataFields.dataElements || []).filter((dataElement) => { 19952 return dataElement.origin !== DataElementOrigins.Creative && !hasTag(dataElement, DataElementTags.PII.tag); 19953 }).map((dataElement) => buildActionableData({ 19954 dataType: LOGIC_DATA_TYPES.DataElement, 19955 mediaType: getDataElementType(dataElement), 19956 displayName: getDataElementDisplayName(dataElement), 19957 id: getDataElementId(dataElement) 19958 })).reduce((acc, actionableData) => { 19959 const value = buildValue(actionableData, null, false, programDataFields); 19960 return { 19961 ...acc, 19962 [actionableData.displayName]: { 19963 value, 19964 type: "string" 19965 } 19966 }; 19967 }, {}); 19968 storyLogic.analyticsDataSources = {}; 19969 storyLogic.analyticsDataSources.logicDataElements = logicDataElements; 19970 } 19971 addVideoRatioAndQualityLogicIfEnabled(); 19972 return storyLogic; 19973} 19974//#endregion 19975//#region client/logic/vlx/storyInline.ts 19976function createStoryInlineLogic(wireframes, assets, currentStory, analytics, program, accountName, scenes, ignoreNextSceneLogic, narrationsVersion, storiesVersion, creativeVersion, enabledFeatureFlags) { 19977 let storyInline = createStoryLogic(wireframes, null, program, accountName, ignoreNextSceneLogic, currentStory, analytics, assets, narrationsVersion, storiesVersion, creativeVersion, enabledFeatureFlags); 19978 storyInline.lineup = storyInline.lineup.map((sceneInLineup) => { 19979 return { 19980 name: sceneInLineup.name, 19981 scene: scenes.find((scene) => scene.name === sceneInLineup.name) 19982 }; 19983 }); 19984 return storyInline; 19985} 19986//#endregion 19987//#region client/logic/vlx/scene.ts 19988var VALID_SLOTS_PATTERN = /(.*) - # of valid slots/; 19989var SLOT_NAME_PATTERN = /(.*) - Slot (.*)/; 19990/** 19991* Old code to be deleted, once all scene animations will be kept in logic 19992* */ 19993function createSceneAnimation(wireFrameScene, useAbsoluteAnimationPath) { 19994 let animationPath; 19995 if (wireFrameScene.animation) animationPath = useAbsoluteAnimationPath ? wireFrameScene.animation.self : wireFrameScene.animation.name + "/"; 19996 return { href: { 19997 "repo-url": animationPath, 19998 repository: ANIMATION_REPOSITORY 19999 } }; 20000} 20001function getNarrationDefaultText(wireframes, scenePartNarration) { 20002 if (StateReaderUtils.getNarrationsVersion(wireframes) > 0) return StateReaderUtils.getNarrationDefaultText(wireframes, scenePartNarration.id); 20003 else return scenePartNarration.mockValue; 20004} 20005function getNarrationName(wireframes, sceneId, scenePartNarration, program) { 20006 if (StateReaderUtils.getNarrationsVersion(wireframes) > 0) return StateReaderUtils.getNarrationName(wireframes, sceneId, scenePartNarration.id); 20007 else return scenePartNarration.name; 20008} 20009function getPrioritizedList(participantName) { 20010 let m; 20011 if ((m = VALID_SLOTS_PATTERN.exec(participantName)) !== null && m.length > 0) return { prioritizedListName: m[1] }; 20012 if ((m = SLOT_NAME_PATTERN.exec(participantName)) !== null && m.length > 1) return { 20013 prioritizedListName: m[1], 20014 slotName: m[2], 20015 slotIdx: mapLetterToNum(m[2]) 20016 }; 20017} 20018function getCodeforFromCodeforPattern(dimension, wireframes, narrationPartId, programDataFields) { 20019 let { id, name } = dimension; 20020 if (id.startsWith("DataElements")) { 20021 let dataElementId = id.split("__")[1]; 20022 let dataElement = findDataElementById(dataElementId, programDataFields.dataElements); 20023 if (dataElement) return buildValue(buildActionableData({ 20024 id: getDataElementId(dataElement), 20025 mediaType: dataElement.type, 20026 dataType: LOGIC_DATA_TYPES.DataElement 20027 }), void 0, void 0, programDataFields); 20028 } else if (id.startsWith(PRIORITIZED_LIST_VALUE_SET_SOURCES.CandidateNames)) { 20029 let prioritizedList = getPrioritizedList(name); 20030 if (prioritizedList && prioritizedList.prioritizedListName && !isNaN(prioritizedList.slotIdx)) return wrapPrioritizedListSlotName(prioritizedList.prioritizedListName, prioritizedList.slotIdx, VLX_SCOPE.Scene); 20031 } else if (id.startsWith(PRIORITIZED_LIST_VALUE_SET_SOURCES.NumberOfValidSlots)) { 20032 let prioritizedList = getPrioritizedList(name); 20033 if (prioritizedList && prioritizedList.prioritizedListName) return wrapPrioritizedListNumberOfSlots(prioritizedList.prioritizedListName, VLX_SCOPE.Scene); 20034 } 20035} 20036function getCodefors(wireframes, sceneId, narrationPart, programDataFields, program) { 20037 let codefor = {}; 20038 if (StateReaderUtils.getNarrationsVersion(wireframes) > 0) StateReaderUtils.getNarrationTableDimensions(wireframes, narrationPart.id).forEac
20038h((dimension) => { 20039 let codeForValue = getCodeforFromCodeforPattern(dimension, wireframes, narrationPart.id, programDataFields); 20040 if (codeForValue) codefor[dimension.id] = codeForValue; 20041 }); 20042 else if (narrationPart.participatingDataElements) narrationPart.participatingDataElements.forEach((actionableDataDataElement) => { 20043 const dataElement = findDataElementByLogicValue(actionableDataDataElement, programDataFields.dataElements); 20044 if (dataElement) codefor[getDataElementDisplayName(dataElement)] = buildValue(actionableDataDataElement, void 0, void 0, programDataFields); 20045 }); 20046 return codefor; 20047} 20048function createSceneInputsLogic({ wireframes, sceneId, skipNarration, mockNarrator, accountId, program, projectAssetsServices, programDataFields, enabledFeatureFlags = [], masterData }) { 20049 let promises = []; 20050 let wireFrameLogic = wireframes.logic; 20051 let wireframeScene = wireframes.scenes[sceneId]; 20052 const prioritizedLists = StateReaderUtils.getScenePrioritizedList(wireframes, sceneId); 20053 const context = { 20054 ...programDataFields, 20055 prioritizedLists 20056 }; 20057 wireframeScene.sceneParts.forEach((scenePart) => { 20058 if (scenePart[placeholderType.narration]) { 20059 if (mockNarrator) scenePart[placeholderType.narration].forEach((narration) => { 20060 let narrationName = getNarrationName(wireframes, sceneId, narration, program); 20061 let narrationDefaultText = getNarrationDefaultText(wireframes, narration); 20062 promises.push(buildTtsUrl(accountId, program.projectName, projectAssetsServices, mockNarrator, narrationDefaultText, narrationName)); 20063 }); 20064 } 20065 }); 20066 return Promise.all(promises).then((resultArray) => { 20067 let sceneVariables = createSceneVariables(wireframes.scenes[sceneId], wireframes.logic[sceneId], context); 20068 let placeHolders = {}; 20069 if (masterData && masterData.sceneParts && masterData.sceneParts.length) { 20070 sceneVariables.push(...createSceneVariables(masterData, wireframes.logic[LogicContainers.Master], context)); 20071 populatePlaceholders(wireframes, masterData, placeHolders, wireFrameLogic, program, context, mockNarrator, skipNarration, resultArray); 20072 } 20073 populatePlaceholders(wireframes, wireframeScene, placeHolders, wireFrameLogic, program, context, mockNarrator, skipNarration, resultArray); 20074 return { 20075 placeHolders, 20076 sceneVariables 20077 }; 20078 }); 20079} 20080function populatePlaceholders(wireframes, wireframeScene, placeHolders, wireFrameLogic, program, programDataFields, mockNarrator, skipNarration, mockNarrationsArr) { 20081 let inputs = {}; 20082 wireframeScene.sceneParts.forEach((scenePart) => { 20083 if (scenePart[placeholderType.onscreen]) scenePart[placeholderType.onscreen].forEach((placeholder) => { 20084 if (!inputs[placeholder.name] && wireFrameLogic[wireframeScene.id][placeholder.name]) { 20085 if (placeholder.type === onscreenTypes.Hotspot) createJsonHierarchyForVar(placeHolders, placeholder.name, { 20086 rules: buildInputRules(wireFrameLogic[wireframeScene.id][placeholder.name], programDataFields, false, false, true), 20087 type: LOGIC_TYPE.Text 20088 }); 20089 else createJsonHierarchyForVar(placeHolders, placeholder.name, { 20090 rules: buildInputRules(wireFrameLogic[wireframeScene.id][placeholder.name], programDataFields), 20091 type: getInputLogicType(wireFrameLogic[wireframeScene.id][placeholder.name]) 20092 }); 20093 inputs[placeholder.name] = true; 20094 } 20095 }); 20096 if (scenePart[entityType.groups]) scenePart[entityType.groups].forEach((group) => { 20097 if (!inputs[group.id] && wireFrameLogic[wireframeScene.id][group.id]) { 20098 createJsonHierarchyForVar(placeHolders, group.id, { 20099 rules: buildInputRules(wireFrameLogic[wireframeScene.id][group.id], programDataFields, false, false, true), 20100 type: getInputLogicType(wireFrameLogic[wireframeScene.id][group.id]) 20101 }); 20102 inputs[group.id] = true; 20103 } 20104 }); 20105 if (scenePart[entityType.prioritizedLists]) scenePart[entityType.prioritizedLists].forEach((pList) => { 20106 if (!inputs[pList.id] && wireFrameLogic[wireframeScene.id][pList.id]) { 20107 createJsonHierarchyForVar(placeHolders, pList.name, { 20108 value: evalScopeVariable(pList.name, VLX_SCOPE.Scene), 20109 type: "object" 20110 }); 20111 inputs[pList.id] = true; 20112 } 20113 }); 20114 if (scenePart[placeholderType.parameter]) scenePart[placeholderType.parameter].forEach((parameter) => { 20115 if (!inputs[parameter.name] && wireFrameLogic[wireframeScene.id][parameter.name]) { 20116 createJsonHierarchyForVar(placeHolders, parameter.name, { 20117 rules: buildInputRules(wireFrameLogic[wireframeScene.id][parameter.name], programDataFields), 20118 type: getInputLogicType(wireFrameLogic[wireframeScene.id][parameter.name]) 20119 }); 20120 inputs[parameter.name] = true; 20121 } 20122 }); 20123 if (scenePart[placeholderType.narration]) if (!mockNarrator) { 20124 if (!skipNarration) scenePart[placeholderType.narration].forEac
20124h((narration) => { 20125 createJsonHierarchyForVar(placeHolders, getNarrationName(wireframes, wireframeScene.id, narration, program), { 20126 type: "narration", 20127 value: { codefor: getCodefors(wireframes, wireframeScene.id, narration, programDataFields, program) } 20128 }); 20129 }); 20130 } else { 20131 let index = 0; 20132 scenePart[placeholderType.narration].forEach((narration) => { 20133 let value = { 20134 transcript: getNarrationDefaultText(wireframes, narration), 20135 source: mockNarrationsArr[index].url 20136 }; 20137 createJsonHierarchyForVar(placeHolders, getNarrationName(wireframes, wireframeScene.id, narration, program), value); 20138 ++index; 20139 }); 20140 } 20141 }); 20142} 20143function createAnimationLogic(wireFrameLogic, sceneId, wireFrameScene, useAbsoluteAnimationPath, programDataFields) { 20144 if (wireFrameScene.animaticPath) return { href: wireFrameScene.animaticPath }; 20145 if (wireFrameLogic[sceneId] && wireFrameLogic[sceneId][sceneId + "_animation"] && !isLogicEmpty(wireFrameLogic[sceneId][sceneId + "_animation"])) return { 20146 rules: buildInputRules(wireFrameLogic[sceneId][sceneId + "_animation"], programDataFields, useAbsoluteAnimationPath), 20147 type: getInputLogicType(wireFrameLogic[sceneId][sceneId + "_animation"]) 20148 }; 20149 return createSceneAnimation(wireFrameScene, useAbsoluteAnimationPath); 20150} 20151function createValidationData(wireFrameLogic, sceneId, programDataFields) { 20152 if (!isLogicEmpty(wireFrameLogic[sceneId] && wireFrameLogic[sceneId][sceneId + "_validation"])) return { 20153 rules: buildInputRules(wireFrameLogic[sceneId][sceneId + "_validation"], programDataFields), 20154 type: getInputLogicType(wireFrameLogic[sceneId][sceneId + "_validation"]) 20155 }; 20156 return true; 20157} 20158function createSceneVariables(sceneWireframesData, sceneWireframesLogic, programDataFields) { 20159 let variables = []; 20160 let prioritizedListsIDs = /* @__PURE__ */ new Set([]); 20161 sceneWireframesData.sceneParts.forEach((scenePart) => { 20162 if (scenePart[entityType.prioritizedLists]) scenePart[entityType.prioritizedLists].forEach((pList) => { 20163 if (!prioritizedListsIDs.has(pList.id)) { 20164 prioritizedListsIDs.add(pList.id); 20165 const variable = { 20166 name: pList.name, 20167 value: { 20168 type: "object", 20169 cardinality: { 20170 multiple: true, 20171 transform: "slots", 20172 limit: pList.slots.length 20173 }, 20174 rules: buildInputRules(sceneWireframesLogic[pList.id], programDataFields) 20175 } 20176 }; 20177 variables.push(variable); 20178 } 20179 }); 20180 }); 20181 let placeholdersNames = /* @__PURE__ */ new Set([]); 20182 const addVariable = (placeholder, overrideType) => { 20183 const identifier = placeholder.id || placeholder.name; 20184 if (!placeholdersNames.has(identifier)) { 20185 placeholdersNames.add(identifier); 20186 const variable = { 20187 name: identifier, 20188 value: { 20189 type: overrideType || placeholder.type, 20190 rules: buildInputRules(sceneWireframesLogic[identifier], programDataFields) 20191 } 20192 }; 20193 variables.push(variable); 20194 } 20195 }; 20196 sceneWireframesData.sceneParts.forEach((scenePart) => { 20197 if (scenePart[placeholderType.onscreen]) scenePart[placeholderType.onscreen].forEach((ph) => { 20198 addVariable(ph); 20199 }); 20200 if (scenePart[entityType.groups]) scenePart[entityType.groups].forEach((group) => { 20201 addVariable(group, LOGIC_TYPE.Compound); 20202 }); 20203 if (scenePart[placeholderType.parameter]) scenePart[placeholderType.parameter].forEach((parameter) => { 20204 addVariable(parameter); 20205 }); 20206 }); 20207 const descriptiveTranscriptLogic = sceneWireframesLogic && sceneWireframesLogic[ADAVarName]; 20208 if (descriptiveTranscriptLogic) { 20209 const descriptiveTranscriptVar = { 20210 name: ADAVarName, 20211 value: { 20212 type: LOGIC_TYPE.Text, 20213 rules: buildInputRules(descriptiveTranscriptLogic, programDataFields) 20214 } 20215 }; 20216 variables.push(descriptiveTranscriptVar); 20217 } 20218 return variables; 20219} 20220function createSceneLogic({ wireframes, assets, skipNarration, ignoreValidation, mockNarrator, selectedSceneIds, accountId, program, projectAssetsServices, enabledFeatureFlags, masterData }) { 20221 let scenesIds = Object.keys(wireframes.scenes).filter((id) => id !== LogicContainers.Master && (Array.isArray(selectedSceneIds) ? selectedSceneIds.includes(id) : true)); 20222 const programDataFields = { 20223 dataElements: StateReaderUtils.getProjectDataElementsFromWireframes(wireframes) || [], 20224 prioritizedListLogic: StateReaderUtils.getProjectPrioritizedListsFromWireframes(wireframes), 20225 assets 20226 }; 20227 let promises = []; 20228 scenesIds.map((sceneId) => { 20229 promises.push(createSceneInputsLogic({ 20230 wireframes, 20231 sceneId, 20232 skipNarration, 20233 mockNarrator, 20234 accountId, 20235 program, 20236 projectAssetsServices, 20237 programDataFields, 20238 enabledFeatureFlags, 20239 masterData 20240 })); 20241 }); 20242 return Promise.all(promises).then((resultArray) => { 20243 return scenesIds.map((sceneId, index) => { 20244 let wireFrameScene = wireframes.scenes[sceneId]; 20245 let useAbsoluteAnimationPath = !!wireframes.scenes[sceneId].animaticPath; 20246 const prioritizedLists = StateReaderUtils.getScenePrioritizedList(wireframes, sceneId); 20247 let context = { 20248 ...programDataFields, 20249 prioritizedLists 20250 }; 20251 let sceneLogic = { 20252 animation: createAnimationLogic(wireframes.logic, sceneId, wireFrameScene, useAbsoluteAnimationPath, context), 20253 id: sceneId, 20254 name: wireFrameScene.name, 20255 data: resultArray[index].placeHolders, 20256 valid: ignoreValidation ? true : createValidationData(wireframes.logic, sceneId, context) 20257 }; 20258 if (resultArray[index].sceneVariables && Array.isArray(resultArray[index].sceneVariables) && resultArray[index].sceneVariables.length > 0) { 20259 sceneLogic.variables = resultArray[index].sceneVariables;
20260 resultArray[index].sceneVariables.forEach((variable) => { 20261 if (!sceneLogic.data[variable.name]) sceneLogic.data[variable.name] = variable.value; 20262 }); 20263 } 20264 return sceneLogic; 20265 }); 20266 }); 20267} 20268function buildTtsUrl(accountId, projectName, projectAssetsServices, mockNarrator, value, defaultValue) { 20269 return projectAssetsServices.getMockNarration(accountId, projectName, mockNarrator.toLowerCase(), value ? value : defaultValue); 20270} 20271//#endregion 20272//#region client/logic/vlx/analytics.ts 20273function createAnalyticsData(accountId, program, wireframes, story, assets) { 20274 if (!program || program.programType && program.programType !== programTypes.CRM) return null; 20275 const programDataFields = { 20276 dataElements: StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), 20277 assets 20278 }; 20279 let analyticsStoryData; 20280 if (story) analyticsStoryData = { 20281 story: `${program.displayName}/${story.name}`, 20282 storyid: story.id 20283 }; 20284 const customFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(wireframes); 20285 let customFields = {}; 20286 if (customFieldsArray) customFieldsArray.forEach((customAnalyticId, index) => { 20287 const customFieldData = StateReaderUtils.getCustomAnalyticsFieldData(wireframes, customAnalyticId); 20288 if (!customFieldData) return; 20289 const customAnalyticFields = StateReaderUtils.getCustomAnalyticFields(wireframes); 20290 const customFieldName = customAnalyticFields && customAnalyticFields[customAnalyticId] && customAnalyticFields[customAnalyticId].name || customAnalyticId; 20291 customFields[`custom${index + 1}`] = { 20292 ...buildAnalyticsRules(customFieldData, customFieldName, programDataFields)[0], 20293 type: "string" 20294 }; 20295 }); 20296 return { 20297 storyData: analyticsStoryData, 20298 customFields 20299 }; 20300} 20301//#endregion 20302//#region client/logic/versionDiff/diffTable.ts 20303var DiffTable = class { 20304 constructor() { 20305 this.getByKey = (key) => this.table[key]; 20306 this.putByKey = (key, record) => { 20307 this.table[key] = record; 20308 }; 20309 this.getAllRecords = () => Object.values(this.table); 20310 this.getAllKeysAndRecords = () => Object.entries(this.table); 20311 this.deleteRecordByKey = (key) => { 20312 delete this.table[key]; 20313 }; 20314 this.table = {}; 20315 } 20316 static { 20317 this.getTableKey = (type, id) => `${type}/${id}`; 20318 } 20319}; 20320//#endregion 20321//#region client/logic/versionDiff/diffTableRecord.ts 20322var DiffTableRecord = class { 20323 constructor(diffFunc) { 20324 this.diff = diffFunc; 20325 this.diffResult = null; 20326 this.status = RecordStatus.PENDING; 20327 } 20328}; 20329//#endregion 20330//#region client/logic/versionDiff/diffManager.ts 20331var ChangeType = /* @__PURE__ */ function(ChangeType) { 20332 ChangeType["Add"] = "add"; 20333 ChangeType["Edit"] = "edit"; 20334 ChangeType["Delete"] = "delete"; 20335 ChangeType["None"] = "none"; 20336 return ChangeType; 20337}({}); 20338var DiffManager = class { 20339 constructor(entities) { 20340 this.init = (context, previousContext) => { 20341 let table = new DiffTable(); 20342 this.entities && this.entities.forEach((entity) => { 20343 let entityInstances = entity.collector({ 20344 context, 20345 previousContext 20346 }); 20347 entityInstances && entityInstances.forEach((entityInstance) => { 20348 const tableKey = DiffTable.getTableKey(entity.getType(), entityInstance.id); 20349 const record = new DiffTableRecord(entityInstance.diff); 20350 table.putByKey(tableKey, record); 20351 }); 20352 }); 20353 table.getAllRecords().forEach((record) => { 20354 if (!record.diffResult) record.diffResult = this.fulfillRecord(table, record); 20355 }); 20356 return table; 20357 }; 20358 this.fulfillRecord = (table, record) => { 20359 record.status = RecordStatus.CALCULATING; 20360 let result = record.diff((type, id) => this.resolveDiffResultById(table, type, id)); 20361 record.status = RecordStatus.DONE; 20362 return result; 20363 }; 20364 this.resolveDiffResultById = (table, type, id) => { 20365 let record = table.getByKey(DiffTable.getTableKey(type, id)); 20366 if (!record) return { 20367 type, 20368 id, 20369 name: `not found? ${id}`, 20370 changeType: "none", 20371 changes: [], 20372 isShown: false 20373 }; 20374 let diffResult = record.diffResult; 20375 if (record.status === RecordStatus.CALCULATING) { 20376 diffResult = { 20377 type, 20378 id, 20379 name: `calculating? ${id}`, 20380 changeType: "none", 20381 changes: [], 20382 isShown: false 20383 }; 20384 return diffResult; 20385 } 20386 if (!diffResult) { 20387 diffResult = this.fulfillRecord(table, record); 20388 record.diffResult = diffResult; 20389 } 20390 return diffResult; 20391 }; 20392 this.readDiffResultById = (table, type, id) => { 20393 const record = table.getByKey(DiffTable.getTableKey(type, id)); 20394 if (record) return record.diffResult; 20395 }; 20396 this.entities = entities; 20397 } 20398 /** 20399 * resolve the change of a parent from a list of it's children's changes. 20400 * @param changes - list of changes
20401 * @param assumeChildChangeType - used when there's a 1:1 link between parent and child. 20402 * for example a placeholder and it's logic object or analytics and it's logic object. 20403 * @returns 'Edit' if there's a change in one of the children, unless assumeChildChange and all children are add or delete 20404 */ 20405 static getChangeType(changes, assumeChildChangeType) { 20406 if (!changes.length) return "none"; 20407 const allSameType = changes.every((change) => change === changes[0]); 20408 if (allSameType && changes[0] === "none") return "none"; 20409 else if (allSameType) return assumeChildChangeType ? changes[0] : "edit"; 20410 else { 20411 const filteredChanges = changes.filter((change) => change !== "none"); 20412 if (filteredChanges.every((change) => change === filteredChanges[0])) return assumeChildChangeType ? filteredChanges[0] : "edit"; 20413 else return "edit"; 20414 } 20415 } 20416}; 20417//#endregion 20418//#region client/logic/entities/baseEntity.ts 20419var BaseEntity = class { 20420 constructor(type) { 20421 this.getType = () => { 20422 return this.type; 20423 }; 20424 this.validateDependency = (type, id, getValidationResult) => { 20425 return getValidationResult(type, id); 20426 }; 20427 this.getDependenciesIssue = (dependencies, dependencyType, getDependencyId, getValidationResult, issueCode) => { 20428 let dependenciesValidationResults = dependencies.map((dependency) => { 20429 return this.validateDependency(dependencyType, getDependencyId(dependency), getValidationResult); 20430 }).filter((result) => result && result.issues.length > 0); 20431 if (dependenciesValidationResults.length > 0) return { 20432 code: issueCode, 20433 severity: ValidationManager.getHighestSeverity(dependenciesValidationResults.map((result) => result.severity)), 20434 details: {}, 20435 children: dependenciesValidationResults 20436 }; 20437 }; 20438 this.diffDependency = (type, id, getDiffResult) => getDiffResult(type, id); 20439 this.getDependenciesDiff = (dependencies, dependencyType, getDependencyId, getDiffResult, assumeChildChangeType = false) => { 20440 let dependenciesDiffResults = dependencies.map((dependency) => this.diffDependency(dependencyType, getDependencyId(dependency), getDiffResult)).filter((result) => result && (result.changeType !== ChangeType.None || result.changes.length > 0)); 20441 if (dependenciesDiffResults.length > 0) { 20442 const changes = dependenciesDiffResults.map((result) => result.changeType); 20443 const changeType = DiffManager.getChangeType(changes, assumeChildChangeType); 20444 return { 20445 changeType, 20446 details: assumeChildChangeType && `assumed the change of a child - '${changeType}'`, 20447 children: dependenciesDiffResults 20448 }; 20449 } 20450 }; 20451 this.transformEntityInstanceArrayToObject = (entityList, identityFunc) => { 20452 let out = {}; 20453 entityList.forEach((entity) => { 20454 out[identityFunc(entity)] = entity; 20455 }); 20456 return out; 20457 }; 20458 this.entityListsToMap = (previousEntityList = [], currentEntityList = [], identityFunc) => { 20459 let EntitiesById = /* @__PURE__ */ new Map(); 20460 const previousObj = this.transformEntityInstanceArrayToObject(previousEntityList, identityFunc); 20461 const currentObj = this.transformEntityInstanceArrayToObject(currentEntityList, identityFunc); 20462 previousEntityList.forEach((previousEntity) => { 20463 const itemId = identityFunc(previousEntity); 20464 const currentEntity = currentObj[itemId]; 20465 EntitiesById.set(itemId, { 20466 previousEntity, 20467 currentEntity 20468 }); 20469 }); 20470 currentEntityList.forEach((currentEntity) => { 20471 const itemId = identityFunc(currentEntity); 20472 if (!EntitiesById.has(itemId)) { 20473 const previousEntity = previousObj[itemId]; 20474 EntitiesById.set(itemId, { 20475 previousEntity, 20476 currentEntity 20477 }); 20478 } 20479 }); 20480 return EntitiesById; 20481 }; 20482 this.entityObjectsToMap = (previousEntitiesObj = {}, currentEntitiesObj = {}) => { 20483 let EntitiesById = /* @__PURE__ */ new Map(); 20484 Object.entries(previousEntitiesObj).forEach(([id, previousEntity]) => { 20485 const currentEntity = currentEntitiesObj[id]; 20486 EntitiesById.set(id, { 20487 previousEntity, 20488 currentEntity 20489 }); 20490 }); 20491 Object.entries(currentEntitiesObj).forEach(([id, currentEntity]) => { 20492 if (!EntitiesById.has(id)) { 20493 const previousEntity = previousEntitiesObj[id]; 20494 EntitiesById.set(id, { 20495 previousEntity, 20496 currentEntity 20497 }); 20498 } 20499 }); 20500 return EntitiesById; 20501 }; 20502 this.getPropsFromPreviousOrCurrent = (previousEntity, currentEntity, propName) => currentEntity ? currentEntity[propName] : previousEntity[propName]; 20503 this.type = type; 20504 } 20505}; 20506//#endregion 20507//#region client/logic/versionDiff/diffUtils.ts 20508var import_deep_diff = require_deep_diff(); 20509/** FUNCTIONS **/ 20510var buildDiffEntity = (diffResult) => { 20511 const { id, name, changeType, type, changes } = diffResult; 20512 return { 20513 id, 20514 name, 20515 changeType, 20516 entityType: type, 20517 isOpen: false, 20518 changes: parseDiffEntityChanges(changes) 20519 }; 20520}; 20521var parseDiffEntityChanges = (changes) => { 20522 let entities = []; 20523 let entitiesByHeader = {};
20524 changes.forEach((change) => { 20525 change.children.forEach((result) => { 20526 if (result.isShown) { 20527 const diffEntity = buildDiffEntity(result); 20528 const header = getDiffHeaderTitle(diffEntity); 20529 if (header) if (entitiesByHeader[header]) entitiesByHeader[header].push(diffEntity); 20530 else entitiesByHeader[header] = [diffEntity]; 20531 else entities.push(diffEntity); 20532 } 20533 }); 20534 }); 20535 Object.entries(entitiesByHeader).forEach(([header, diffEntityList]) => { 20536 entities.push({ 20537 isOpen: false, 20538 id: `${header}-${v4()}`, 20539 name: header, 20540 changeType: DiffManager.getChangeType(diffEntityList.map((diff) => diff.changeType), true), 20541 entityType: null, 20542 changes: diffEntityList 20543 }); 20544 }); 20545 return entities; 20546}; 20547var diffEntities = (previousEntity, currentEntity) => { 20548 if (!previousEntity && currentEntity) return ChangeType.Add; 20549 if (previousEntity && !currentEntity) return ChangeType.Delete; 20550 return (0, import_deep_diff.diff)(normalizeEntity(previousEntity), normalizeEntity(currentEntity)) ? ChangeType.Edit : ChangeType.None; 20551}; 20552var updateDiffResultWithChanges = (result, change, isShown = true) => { 20553 if (change) { 20554 result.changes.push(change); 20555 result.changeType = change.changeType; 20556 result.isShown = isShown; 20557 } 20558 return result; 20559}; 20560var getDiffModel = (table) => { 20561 let diffModel = []; 20562 table.getAllRecords().forEach((record) => { 20563 record.diffResult.type === EntityTypes.PROGRAM && diffModel.push(...parseDiffEntityChanges(record.diffResult.changes)); 20564 }); 20565 return addDiffHeadersToDiffModel(diffModel); 20566}; 20567var getDiffHeaderTitle = (entity) => { 20568 switch (entity.entityType) { 20569 case EntityTypes.SCENE: return "Scenes"; 20570 case EntityTypes.STORY: return "Stories"; 20571 case EntityTypes.DERIVED_DATA_ELEMENT: return "Studio Data"; 20572 case EntityTypes.DATA_TABLE: return "Data Tables"; 20573 case EntityTypes.DATA_ELEMENT: return "Data Elements"; 20574 case EntityTypes.CREATIVE_DATA_ELEMENT: return "Content Set Data"; 20575 case EntityTypes.MEDIA: return "Media"; 20576 case EntityTypes.ANIMATION: return "Animation"; 20577 case EntityTypes.RECORDING: return "Narration Library"; 20578 case EntityTypes.ANALYTICS: return "Analytics"; 20579 case EntityTypes.PLACEHOLDER: 20580 case EntityTypes.GROUP: 20581 case EntityTypes.PRIORITIZED_LIST: return "Placeholders"; 20582 case EntityTypes.PARAMETER: return "Animations Guidelines"; 20583 case EntityTypes.NARRATION: return "Narrations"; 20584 default: return ""; 20585 } 20586}; 20587var composeDiffHeaderEntity = (model, header, names) => { 20588 let index = model.findIndex((entity) => names.includes(entity.name)); 20589 if (index < 0) return model; 20590 let { filteredArray, remainingArray } = getFilteredAndRemainingItems(model, names, (en) => en.name); 20591 let wrappingDiffEntity = model.find((entity) => entity.name === header); 20592 let isNewDiff = !wrappingDiffEntity; 20593 wrappingDiffEntity = wrappingDiffEntity || { 20594 isOpen: false, 20595 id: `${header}-${v4()}`, 20596 name: header, 20597 changeType: void 0, 20598 entityType: null, 20599 changes: [] 20600 }; 20601 wrappingDiffEntity.changes = [...filteredArray, ...wrappingDiffEntity.changes]; 20602 let changeTypes = [...wrappingDiffEntity.changes.map((diff) => diff.changeType)]; 20603 wrappingDiffEntity.changeType = DiffManager.getChangeType(changeTypes, true); 20604 if (isNewDiff) remainingArray.splice(index, 0, wrappingDiffEntity); 20605 return remainingArray; 20606}; 20607var addDiffHeadersToDiffModel = (model) => { 20608 let newModel = composeDiffHeaderEntity(model, "Data Library", [ 20609 "Data Elements", 20610 "Studio Data", 20611 "Data Tables", 20612 "Content Set Data" 20613 ]); 20614 newModel = composeDiffHeaderEntity(newModel, "All Stories", ["Story Selection"]); 20615 newModel = composeDiffHeaderEntity(newModel, "Stories", ["All Stories"]); 20616 newModel = composeDiffHeaderEntity(newModel, "Asset Library", ["Media", "Animation"]); 20617 return newModel; 20618}; 20619var getStoryPropertyCollectionId = (storyId, propertyName) => { 20620 return `${storyId}_${propertyName}`; 20621}; 20622var getProgramPropertyCollectionId = (propertyName) => { 20623 return `program_${propertyName}`; 20624}; 20625var exposeDiffResult = (diffResult, newName, newType) => { 20626 return { 20627 ...diffResult, 20628 name: newName, 20629 type: newType, 20630 isShown: true 20631 }; 20632}; 20633var removeVersionRelatedFields = (entity) => { 20634 const copy = { ...entity }; 20635 delete copy.graphQLId; 20636 delete copy.graphQLUpdated; 20637 return copy; 20638}; 20639var normalizeEntity = (entity) => { 20640 let normalizedEntity = removeVersionRelatedFields(entity); 20641 normalizedEntity = removeEmptyEntriesFromObject(normalizedEntity); 20642 return normalizedEntity; 20643}; 20644//#endregion 20645//#region client/logic/entities/analyticsEntity.ts 20646var AnalyticsEntity = class AnalyticsEntity extends BaseEntity { 20647 constructor() { 20648 super(EntityTypes.ANALYTICS); 20649 this.collector = (args) => { 20650 const { context, previousContext } = args; 20651 let analytics = []; 20652 const previousWireframes = previousContext && StateReaderUtils.getWireFrame(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 20653 const currentWireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 20654 const previousAnalyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(previousWireframes) || []; 20655 const currentAnalyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(currentWireframes) || []; 20656 const previousAnalytics = previousAnalyticsFieldsArray.map((aPrevAnalyticsKey) => ({ 20657 analyticsId: aPrevAnalyticsKey, 20658 ...StateReaderUtils.getCustomAnalyticsFieldData(previousWireframes, aPrevAnalyticsKey) 20659 })); 20660 const currentAnalytics = currentAnalyticsFieldsArray.map((aCurrentAnalyticsKey, index) => ({ 20661 analyticsId: aCurrentAnalyticsKey, 20662 ...StateReaderUtils.getCustomAnalyticsFieldData(currentWireframes, aCurrentAnalyticsKey), 20663 index 20664 })); 20665 this.entityListsToMap(previousAnalytics, currentAnalytics, (analyticObj) =>
20665 analyticObj.analyticsId).forEach((analyticsPair, analyticFieldKey) => { 20666 let isNewAnalyticFieldData = Boolean(analyticsPair.currentEntity && analyticsPair.currentEntity.isNew); 20667 let index = analyticsPair.currentEntity && analyticsPair.currentEntity.index; 20668 analytics.push({ 20669 id: AnalyticsEntity.generateId(analyticFieldKey), 20670 validate: (prevValidationResult, getValidationResultFunction) => { 20671 return this.doValidate(analyticFieldKey, getValidationResultFunction, isNewAnalyticFieldData, index); 20672 }, 20673 diff: (getDiffResult) => this.doDiff(getDiffResult, analyticFieldKey, currentWireframes?.customAnalyticFields) 20674 }); 20675 }); 20676 return analytics; 20677 }; 20678 this.doValidate = (analyticFieldKey, getValidationResult, isNewAnalyticFieldData, index) => { 20679 const type = this.getType(); 20680 const id = AnalyticsEntity.generateId(analyticFieldKey); 20681 let result = { 20682 type, 20683 id, 20684 issues: [], 20685 name: `custom field #${index + 1}` 20686 }; 20687 const getDependencyId = () => id; 20688 let issue = this.getDependenciesIssue([void 0], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.ANALYTICS_LOGIC_ERROR); 20689 if (issue) { 20690 result.issues.push(issue); 20691 result.severity = issue.severity; 20692 } 20693 if (isNewAnalyticFieldData) { 20694 result.issues.push({ 20695 code: IssueCodes.ANALYTICS_NAME_ERROR, 20696 severity: IssueSeverity.ERROR, 20697 details: {} 20698 }); 20699 result.severity = IssueSeverity.ERROR; 20700 } 20701 return result; 20702 }; 20703 this.doDiff = (getDiffResult, analyticFieldKey, customAnalyticFields) => { 20704 const id = AnalyticsEntity.generateId(analyticFieldKey); 20705 let result = { 20706 type: this.getType(), 20707 id, 20708 name: customAnalyticFields && customAnalyticFields[analyticFieldKey] ? customAnalyticFields[analyticFieldKey].name : analyticFieldKey, 20709 changeType: ChangeType.None, 20710 changes: [], 20711 isShown: false 20712 }; 20713 const getDependencyId = (id) => id; 20714 return updateDiffResultWithChanges(result, this.getDependenciesDiff([id], EntityTypes.LOGIC, getDependencyId, getDiffResult, true)); 20715 }; 20716 } 20717 static { 20718 this.generateId = (analyticFieldKey) => { 20719 return `${analyticFieldKey}_analytics`; 20720 }; 20721 } 20722}; 20723//#endregion 20724//#region client/components/HubEditor/rightPanels/ValueSetController.js 20725var ValueSetController = class ValueSetController { 20726 static upgradeValueSet = (valueSet) => { 20727 return valueSet.map((value) => typeof value === "string" ? { 20728 id: "_bc_" + value.toLowerCase(), 20729 dn: value 20730 } : value); 20731 }; 20732 static isValueSetEditSupportedForType(mediaType) { 20733 return mediaType === LOGIC_MEDIA_TYPES.String || mediaType === LOGIC_MEDIA_TYPES.Number; 20734 } 20735 static buildValueListFromDataElement(dataElement) { 20736 let values = []; 20737 let valueSet = dataElement.getValueSet && dataElement.getValueSet(); 20738 if (valueSet) { 20739 valueSet = ValueSetController.upgradeValueSet(valueSet); 20740 values = valueSet.map((value) => value ? { 20741 id: value.id, 20742 type: "valueGood", 20743 text: value.dn 20744 } : { 20745 id: "", 20746 type: "valueNothing", 20747 text: "Nothing" 20748 }); 20749 } 20750 return import_immutable.default.List(values); 20751 } 20752 static trimAndValidateValueList(valueList, type, acceptNewValues) { 20753 let typeIsNumber = type === LOGIC_MEDIA_TYPES.Number; 20754 let filteredValues = valueList.filter((v) => v.type === "valueNew" && acceptNewValues || v.text.trim().length > 0).map((v) => ({ 20755 id: v.id, 20756 type: v.type, 20757 text: v.text.trim() 20758 })); 20759 let valueCount = /* @__PURE__ */ new Map(); 20760 filteredValues.forEach((v) => { 20761 if (v.type !== "valueNew" || !acceptNewValues) { 20762 let normalizedText = ValueSetController.normalizeValueText(v.text, typeIsNumber); 20763 let count = valueCount.get(normalizedText) || 0; 20764 valueCount.set(normalizedText, count + 1); 20765 } 20766 }); 20767 let values = filteredValues.map((v) => { 20768 if (v.type === "valueNew" && acceptNewValues) return { 20769 id: v.id || generateValueId(), 20770 type: v.type, 20771 text: v.text 20772 }; 20773 else if (typeIsNumber && isNaN(Number(v.text))) return { 20774 id: v.id || generateValueId(), 20775 type: "valueBadWrongType", 20776 text: v.text 20777 }; 20778 else { 20779 let normalizedText = ValueSetController.normalizeValueText(v.text, typeIsNumber); 20780 let count = valueCount.get(normalizedText); 20781 return { 20782 id: v.id || generateValueId(), 20783 type: count > 1 ? "valueBadDup" : "valueGood", 20784 text: v.text 20785 }; 20786 } 20787 }); 20788 return import_immutable.default.List(values); 20789 } 20790 static countIssues(valueList) { 20791 return valueList.reduce((count, value) => count + (value.type.startsWith("valueBad") ? 1 : 0), 0); 20792 } 20793 static normalizeValueText(text, typeIsNumber) { 20794 let normalizedText = text.trim().toLowerCase(); 20795 if (typeIsNumber) { 20796 let num = Number(normalizedText); 20797 if (!isNaN(num)) normalizedText = num.toString(); 20798 } 20799 return normalizedText; 20800 } 20801}; 20802//#endregion 20803//#region common/external/videoSpecResponse.ts 20804var Status = /* @__PURE__ */ function(Status) { 20805 Status["NotStarted"] = "not_started"; 20806 Status["EncodingStart"] = "encoding_start";
20807 Status["Finished"] = "finished"; 20808 Status["Error"] = "error"; 20809 return Status; 20810}({}); 20811var MediaType = /* @__PURE__ */ function(MediaType) { 20812 MediaType["MpegUrl"] = "application/x-mpegURL"; 20813 MediaType["Mp4"] = "video/mp4"; 20814 return MediaType; 20815}({}); 20816//#endregion 20817//#region client/logic/common/callEndpoint.ts 20818var EndpointError = class extends Error { 20819 constructor(url, attempts, outcome) { 20820 const isStatus = outcome.kind === "response"; 20821 super(isStatus ? `HTTP ${outcome.response.status}: ${outcome.response.statusText}` : toErrorMessage(outcome.error)); 20822 this.name = "EndpointError"; 20823 this.url = url.split("?")[0]; 20824 this.attempts = attempts; 20825 if (isStatus) { 20826 this.status = outcome.response.status; 20827 this.statusText = outcome.response.statusText; 20828 } else this.cause = outcome.error; 20829 } 20830}; 20831var delay = (ms) => new Promise((resolve) => { 20832 setTimeout(resolve, ms); 20833}); 20834var ttfbMessage = (ms) => `First byte not downloaded after ${ms} milliseconds`; 20835var armDeadlines = (options) => { 20836 const controller = new AbortController(); 20837 const { ttfbTimeoutMs, totalTimeoutMs } = options; 20838 let expire = () => {}; 20839 const expired = new Promise((_resolve, reject) => { 20840 expire = reject; 20841 }); 20842 expired.catch(() => {}); 20843 const abortWith = (message) => { 20844 const error = new DOMException(message, "TimeoutError"); 20845 controller.abort(error); 20846 expire(error); 20847 }; 20848 const ttfbTimer = ttfbTimeoutMs ? setTimeout(() => abortWith(ttfbMessage(ttfbTimeoutMs)), ttfbTimeoutMs) : void 0; 20849 const totalTimer = totalTimeoutMs ? setTimeout(() => abortWith(`Request exceeded ${totalTimeoutMs} milliseconds`), totalTimeoutMs) : void 0; 20850 return { 20851 signal: controller.signal, 20852 expired, 20853 headersArrived: () => clearTimeout(ttfbTimer), 20854 done: () => { 20855 clearTimeout(ttfbTimer); 20856 clearTimeout(totalTimer); 20857 } 20858 }; 20859}; 20860/** 20861* One attempt is a fetch AND its body consumption, so a caller whose consumer can fail early - streaming 20862* to a sink that never opened - can retry the whole thing rather than being stuck with a dead response. 20863*/ 20864var callEndpointConsuming = async (url, options, consume) => { 20865 const maxAttempts = Math.max(1, options.attempts ?? 1); 20866 const accept = options.acceptStatus ?? ((status) => status >= 200 && status < 300); 20867 let currentUrl = url; 20868 let currentInit = { 20869 method: options.method, 20870 headers: options.headers, 20871 body: options.body, 20872 cache: options.cache 20873 }; 20874 const scheduleRetry = async (outcome, n, waitMs) => { 20875 if (outcome.kind === "response") await outcome.response.body?.cancel().catch(() => {}); 20876 const adjusted = options.onRetry?.(outcome, n); 20877 if (adjusted) { 20878 currentUrl = adjusted.url ?? currentUrl; 20879 currentInit = adjusted.init ? { 20880 ...currentInit, 20881 ...adjusted.init 20882 } : currentInit; 20883 } 20884 await delay(waitMs); 20885 }; 20886 for (let n = 1; n <= maxAttempts; n++) { 20887 const isLast = n === maxAttempts; 20888 const deadlines = armDeadlines(options); 20889 let outcome; 20890 try { 20891 const response = await fetch(currentUrl, { 20892 ...currentInit, 20893 signal: deadlines.signal 20894 }); 20895 deadlines.headersArrived(); 20896 outcome = { 20897 kind: "response", 20898 response 20899 }; 20900 } catch (error) { 20901 outcome = { 20902 kind: "error", 20903 error 20904 }; 20905 } 20906 const waitFor = (o) => isLast ? null : options.retry?.(o, n) ?? null; 20907 let wait = waitFor(outcome); 20908 if (wait === null && outcome.kind === "response" && accept(outcome.response.status)) { 20909 if (!consume) { 20910 deadlines.done(); 20911 return outcome.response; 20912 } 20913 try { 20914 const value = await Promise.race([consume(outcome.response), deadlines.expired]); 20915 deadlines.done(); 20916 return value; 20917 } catch (error) { 20918 deadlines.done(); 20919 await outcome.response.body?.cancel().catch(() => {}); 20920 const consumed = { 20921 kind: "error", 20922 error 20923 }; 20924 wait = waitFor(consumed); 20925 if (wait === null) throw new EndpointError(currentUrl, n, consumed); 20926 await scheduleRetry(consumed, n, wait); 20927 continue; 20928 } 20929 } 20930 deadlines.done(); 20931 if (wait === null) throw new EndpointError(currentUrl, n, outcome); 20932 await scheduleRetry(outcome, n, wait); 20933 } 20934 throw new EndpointError(currentUrl, maxAttempts, { 20935 kind: "error", 20936 error: /* @__PURE__ */ new Error("exhausted all attempts") 20937 }); 20938}; 20939/** Returns the raw Response, for callers that stream the body themselves. */ 20940var callEndpoint = (url, options = {}) => callEndpointConsuming(url, options, void 0); 20941var callEndpointJson = (url, options = {}) => callEndpointConsuming(url, options, (response) => response.json()); 20942var callEndpointText = (url, options = {}) => callEndpointConsuming(url, options, (response) => response.text()); 20943var STREAM_STALL_CHECK_INTERVAL_MS = 5e3; 20944/** 20945* What was actually thrown, for a rejection whose message says nothing. A bare `undefined`, a `null` and an 20946* object that stringifies to nothing all reach toErrorMessage as the same useless text, so the type is the 20947* only thing left that distinguishes them. An Error answers its `name`, which is how a DOMException reports 20948* `AbortError`. 20949*/ 20950var describeThrownType = (value) => { 20951 if (value === null) return "null"; 20952 if (value instanceof Error) return value.name; 20953 return typeof value; 20954}; 20955/** 20956* A stream that did not finish, carrying how far it got. `bytesWritten` is the difference between a sink 20957* that never really opened and a transfer that died deep into a large file. 20958* 20959* Splunk classifies download failures on these message strings, so changing their wording silently retires 20960* the existing searches. 20961*/
20962var StreamFailure = class StreamFailure extends Error { 20963 constructor(message, bytesWritten, causeType, cause) { 20964 super(message); 20965 this.name = "StreamFailure"; 20966 this.bytesWritten = bytesWritten; 20967 this.causeType = causeType; 20968 this.cause = cause; 20969 } 20970 static stalled(bytesWritten, stallTimeoutMs) { 20971 return new StreamFailure(`stalled after ${bytesWritten} bytes with no write for ${stallTimeoutMs}ms`, bytesWritten, "stall"); 20972 } 20973 static from(cause, bytesWritten) { 20974 return new StreamFailure(toErrorMessage(cause), bytesWritten, describeThrownType(cause), cause); 20975 } 20976}; 20977/** 20978* Pipes a response body to a sink, failing if the transfer STALLS rather than if it takes long: 20979* multi-hundred-MB downloads are the reason StreamSaver is here, so a total-duration cap would cut 20980* legitimate ones short. Chunks reach `transform` only once the destination accepts them, so silence 20981* here means nothing is being written. 20982* 20983* Without this the pipe can hang forever with nothing reported - the observed failure when StreamSaver's 20984* service worker is missing, since no one drains its write stream. `bytesWritten` in the message 20985* separates that (stalls at 0) from a transfer that died partway through. 20986*/ 20987var streamToWritable = async (body, sink, options) => { 20988 const { stallTimeoutMs } = options; 20989 let lastProgressAt = Date.now(); 20990 let bytesWritten = 0; 20991 const monitored = body.pipeThrough(new TransformStream({ transform(chunk, controller) { 20992 lastProgressAt = Date.now(); 20993 bytesWritten += chunk.byteLength; 20994 controller.enqueue(chunk); 20995 } })); 20996 const abortController = new AbortController(); 20997 const pipe = monitored.pipeTo(sink, { signal: abortController.signal }); 20998 pipe.catch(() => {}); 20999 let stallTimer; 21000 const stalled = new Promise((_resolve, reject) => { 21001 stallTimer = setInterval(() => { 21002 if (Date.now() - lastProgressAt < stallTimeoutMs) return; 21003 abortController.abort(); 21004 reject(StreamFailure.stalled(bytesWritten, stallTimeoutMs)); 21005 }, STREAM_STALL_CHECK_INTERVAL_MS); 21006 }); 21007 try { 21008 await Promise.race([pipe, stalled]); 21009 } catch (error) { 21010 throw error instanceof StreamFailure ? error : StreamFailure.from(error, bytesWritten); 21011 } finally { 21012 clearInterval(stallTimer); 21013 } 21014}; 21015//#endregion 21016//#region client/logic/common/downloadUtils.ts 21017var import_jszip_min = /* @__PURE__ */ __toESM(require_jszip_min()); 21018var import_StreamSaver = /* @__PURE__ */ __toESM(require_StreamSaver()); 21019import_StreamSaver.default.mitm = `${window.location.origin}/client/streamsaver/mitm.html`; 21020var MAX_DOWNLOAD_ATTEMPTS = 3; 21021var DOWNLOAD_RETRY_DELAY_MS = 1500; 21022/** 21023* A 403 on a just-finished render means "not visible yet", not "forbidden": the streamer serves the mp4 21024* straight from S3, and a large file is a multipart upload, which does not exist at all until 21025* CompleteMultipartUpload returns - so the key 403s for the whole upload, then appears atomically. The 21026* /streamer/ path has no equivalent of the waitUntilAvailable the /content/ path uses (CB-1751). 21027* 21028* Waits are longer than DOWNLOAD_RETRY_DELAY_MS because the observed gap was seconds, not milliseconds 21029* (a 209MB object was still 403ing when the render reported finished). The schedule is a first cut from 21030* one sample; tune it from the retriedStatuses reported on successful downloads. 21031*/ 21032var NOT_VISIBLE_RETRY_DELAYS_MS = [2e3, 4e3]; 21033var FIRST_BYTE_TIMEOUT_MS = 2e4; 21034var STREAM_STALL_TIMEOUT_MS = 3e4; 21035/** 21036* Carries how many attempts were spent before giving up, so a download failure reported to Splunk can be 21037* told apart from a render failure. 21038*/ 21039var DownloadFileError = class extends Error { 21040 constructor(message, attempts, telemetry = {}) { 21041 super(message); 21042 this.name = "DownloadFileError"; 21043 this.attempts = attempts; 21044 this.bytesWritten = telemetry.bytesWritten; 21045 this.contentLength = telemetry.contentLength; 21046 this.causeType = telemetry.causeType; 21047 this.downloadStarted = telemetry.downloadStarted; 21048 } 21049}; 21050var streamTelemetryOf = (cause) => cause instanceof StreamFailure ? { 21051 bytesWritten: cause.bytesWritten, 21052 causeType: cause.causeType 21053} : { causeType: describeThrownType(cause) }; 21054/** 21055* The zip path throws a StreamFailure straight through rather than wrapping it, so both shapes have to be 21056* understood here. 21057*/ 21058var describeDownloadFailure = (error) => { 21059 if (error instanceof DownloadFileError) return { 21060 fetchAttempts: error.attempts, 21061 bytesWritten: error.bytesWritten, 21062 contentLength: error.contentLength, 21063 causeType: error.causeType, 21064 downloadStarted: error.downloadStarted 21065 }; 21066 return error instanceof StreamFailure ? streamTelemetryOf(error) : {}; 21067}; 21068var appendQueryParam = (url, param) => `${url}${url.includes("?") ? "&" : "?"}${param}`; 21069var withoutQuery = (url) => url?.split("?")[0]; 21070var withCacheBuster = (url) => appendQueryParam(url, `_cacheBust=${Date.now()}`); 21071/** 21072* 200 is the only complete response. A 206 is a partial, usually a CDN-cached range response, so prefer a 21073* full 200 - but the last attempt takes the partial rather than failing, which is why 206 is accepted here. 21074*/ 21075var acceptVideoFileStatus = (status) => status === 200 || status === 206; 21076/** 21077* The wait depends on which status arrived, so it cannot be expressed as a boolean plus a fixed delay: a 21078* 403 means the multipart object is not visible yet and needs seconds, while a 206 or 504 clears sooner.
21079*/ 21080var retryStreamerFile = (outcome, attempt) => { 21081 if (outcome.kind === "error") return DOWNLOAD_RETRY_DELAY_MS; 21082 switch (outcome.response.status) { 21083 case 403: return NOT_VISIBLE_RETRY_DELAYS_MS[attempt - 1] ?? DOWNLOAD_RETRY_DELAY_MS; 21084 case 206: 21085 case 504: return DOWNLOAD_RETRY_DELAY_MS; 21086 default: return null; 21087 } 21088}; 21089var bustCache = (originalUrl) => ({ 21090 url: withCacheBuster(originalUrl), 21091 init: { cache: "no-store" } 21092}); 21093var toDownloadFileError = (error, context) => { 21094 const { phase, ...common } = context; 21095 if (!(error instanceof EndpointError)) return new DownloadFileError(toErrorMessage(error), MAX_DOWNLOAD_ATTEMPTS, { 21096 ...common, 21097 ...streamTelemetryOf(error) 21098 }); 21099 if (error.status !== void 0) return new DownloadFileError(`HTTP ${error.status}: ${error.statusText}`, error.attempts, common); 21100 return new DownloadFileError(`Video file ${phase} failed: ${toErrorMessage(error.cause)}`, error.attempts, { 21101 ...common, 21102 ...streamTelemetryOf(error.cause) 21103 }); 21104}; 21105/** 21106* Stream a fetched response body to disk via StreamSaver. Pass `size` only when the response's 21107* Content-Length is trustworthy - it lets Chrome show download progress. Omit it to stream an unknown 21108* length; a wrong size (e.g. the "1" a partial 206 reports) makes StreamSaver truncate the file. 21109* 21110* `onDownloadStarted` fires the instant StreamSaver opens the browser download (before any bytes flow), 21111* letting the caller tell a pre-download failure (safe to re-fetch) from a mid-download one (a retry 21112* would open a second browser download). 21113*/ 21114var streamResponseToFile = async (response, name, size, onDownloadStarted) => { 21115 if (!response.body) throw new Error("empty response body"); 21116 const fileStream = import_StreamSaver.default.createWriteStream(name, size !== void 0 ? { size } : void 0); 21117 onDownloadStarted(); 21118 await streamToWritable(response.body, fileStream, { stallTimeoutMs: STREAM_STALL_TIMEOUT_MS }); 21119 return "finished"; 21120}; 21121var DownloadUtils = class { 21122 constructor() { 21123 this.downloadMp4Video = (links, videoName) => { 21124 return new Promise((resolve, reject) => { 21125 let response = "error"; 21126 let videoStream; 21127 if (links && Array.isArray(links["video-stream"])) links["video-stream"].forEach((stream) => { 21128 if (stream.id === "mp4" || stream.format === MediaType.Mp4 || stream["media-type"] === MediaType.Mp4) videoStream = stream; 21129 }); 21130 else if (links && typeof links["video-stream"] === "object" && links["video-stream"]["media-type"] === MediaType.Mp4) videoStream = links["video-stream"]; 21131 if (videoStream) this.downloadVideoFile(videoStream.href + "?download=true", this.generateTitle(videoStream, videoName)).then((res) => { 21132 response = res; 21133 resolve(response); 21134 }).catch((err) => { 21135 response = err; 21136 reject(response); 21137 }); 21138 else reject(response); 21139 }); 21140 }; 21141 } 21142 static downloadFileFromUrl(url, name) { 21143 let element = document.createElement("a"); 21144 element.href = url; 21145 element.setAttribute("download", name); 21146 element.setAttribute("target", "_blank"); 21147 document.body.appendChild(element); 21148 element.click(); 21149 document.body.removeChild(element); 21150 } 21151 /** 21152 * The RaaS _links hrefs, so no Studio credentials. A data URI rather than the href directly, because 21153 * the download attribute does not reliably set the filename on a cross-origin href. 21154 */ 21155 async downloadFileFromContent(url, name, contentType) { 21156 const content = await callEndpointText(url); 21157 this.createAndDownloadFile(name, content, contentType); 21158 } 21159 createAndDownloadFile(name, content, contentType) { 21160 if (contentType === "application/json" && content instanceof Object) content = JSON.stringify(content, null, " "); 21161 let element = document.createElement("a"); 21162 element.setAttribute("href", "data:" + contentType + ";charset=utf-8," + encodeURIComponent(content)); 21163 element.setAttribute("download", name); 21164 document.body.appendChild(element); 21165 element.click(); 21166 document.body.removeChild(element); 21167 } 21168 createAndDownloadZipFile(filesNamesAndContentArray, zipName) { 21169 const zip = new import_jszip_min.default(); 21170 filesNamesAndContentArray.forEach((fileInfoObj) => { 21171 if (fileInfoObj) zip.file(fileInfoObj.fileName, fileInfoObj.fileContent); 21172 }); 21173 if (import_jszip_min.default.support.uint8array) zip.generateAsync({ type: "base64" }).then(function(base64) { 21174 let d = /* @__PURE__ */ new Date(); 21175 let element = document.createElement("a"); 21176 element.setAttribute("href", "data:application/zip;base64," + base64); 21177 element.setAttribute("download", (zipName || `DataTables-${d.toISOString()}`) + ".zip"); 21178 document.body.appendChild(element); 21179 element.click(); 21180 document.body.removeChild(element); 21181 }); 21182 } 21183 async streamAndDownloadZip(filesToFetch, zipName) { 21184 const zipStream = A(await Promise.all(filesToFetch.map(async (file) => { 21185 const response = await callEndpoint(file.url, { 21186 ttfbTimeoutMs: FIRST_BYTE_TIMEOUT_MS, 21187 attempts: MAX_DOWNLOAD_ATTEMPTS, 21188 retry: retryStreamerFile, 21189 onRetry: () => bustCache(file.url) 21190 }).catch((error) => { 21191 throw new Error(`Failed to fetch ${withoutQuery(file.url)}: ${toErrorMessage(error)}`); 21192 }); 21193 return { 21194 name: file.name, 21195 lastModified: /* @__PURE__ */ new Date(), 21196 input: response.body, 21197 size: parseInt(response.headers.get("content-length") || "0") 21198 }; 21199 }))); 21200 const fileStream = import_StreamSaver.default.createWriteStream(`${zipName}.zip`); 21201 await streamToWritable(zipStream.body, fileStream, { stallTimeoutMs: STREAM_STALL_TIMEOUT_MS }); 21202 }
21203 static createAndDownloadBlobFile(name, content, contentType) { 21204 var a = document.createElement("a"); 21205 document.body.appendChild(a); 21206 var file = new Blob([content], { type: contentType }); 21207 var objectUrl = window.URL.createObjectURL(file); 21208 a.href = objectUrl; 21209 a.download = name; 21210 a.click(); 21211 document.body.removeChild(a); 21212 setTimeout(() => window.URL.revokeObjectURL(objectUrl), 0); 21213 } 21214 /** 21215 * This method is used to download video content with name. 21216 * @param url video url 21217 * @param name desired file name including file type. e.g 'video.mp4' 21218 */ 21219 /** 21220 * Streams a rendered video to disk. Retries a fetch that fails or answers a not-yet-visible status, but 21221 * never once StreamSaver has opened the browser download - a second attempt would open a second download. 21222 */ 21223 async downloadVideoFile(url, name, onStatusRetry) { 21224 let downloadStarted = false; 21225 let phase = "fetch"; 21226 let contentLength; 21227 const streamToDisk = async (response) => { 21228 phase = "stream"; 21229 const size = response.status === 200 ? Number(response.headers.get("content-length")) || void 0 : void 0; 21230 contentLength = size; 21231 return streamResponseToFile(response, name, size, () => { 21232 downloadStarted = true; 21233 }); 21234 }; 21235 try { 21236 return await callEndpointConsuming(url, { 21237 ttfbTimeoutMs: FIRST_BYTE_TIMEOUT_MS, 21238 attempts: MAX_DOWNLOAD_ATTEMPTS, 21239 acceptStatus: acceptVideoFileStatus, 21240 retry: (outcome, attemptNumber) => downloadStarted ? null : retryStreamerFile(outcome, attemptNumber), 21241 onRetry: (outcome) => { 21242 if (outcome.kind === "response") onStatusRetry?.(outcome.response.status); 21243 phase = "fetch"; 21244 return bustCache(url); 21245 } 21246 }, streamToDisk); 21247 } catch (error) { 21248 throw toDownloadFileError(error, { 21249 phase, 21250 downloadStarted, 21251 contentLength 21252 }); 21253 } 21254 } 21255 /** 21256 * This method is used to generate video title with time stamp. 21257 * @param videoStream object from raas response 21258 * @param videoName - the desired video file name 21259 */ 21260 generateTitle(videoStream, videoName) { 21261 let d = /* @__PURE__ */ new Date(); 21262 let videoMediaType = videoStream["media-type"] || videoStream["format"]; 21263 let mediaType = videoMediaType.substring(videoMediaType.indexOf("/") + 1); 21264 return (videoName || "temp") + "-" + d.toISOString() + "." + mediaType; 21265 } 21266 getUserStatusByRaasStatus(raasStatus) { 21267 switch (raasStatus) { 21268 case "finished": return "finished"; 21269 case "error": return "error"; 21270 default: return "in progress"; 21271 } 21272 } 21273}; 21274//#endregion 21275//#region client/components/HubEditor/rightPanels/dataLibrary/DataLibraryController.ts 21276var DataLibraryController = class DataLibraryController { 21277 static { 21278 this.handleDownloadMappingTable = (mappingTableIds, assets, downloadUrl, isStageView) => { 21279 const promiseArray = mappingTableIds.map((mappingTableId) => { 21280 return MappingTablesUtils.findMappingTableByID(mappingTableId, assets); 21281 }).map((mappingTable) => { 21282 if (mappingTable) return DataLibraryController.downloadMappingTableAndConvertToCsvContent(mappingTable, assets, downloadUrl, isStageView).catch((error) => null); 21283 else return Promise.resolve(null); 21284 }); 21285 Promise.all(promiseArray).then((mappingTableCsvContentArray) => { 21286 mappingTableCsvContentArray = mappingTableCsvContentArray.filter((content) => !!content); 21287 const downloadUtils = new DownloadUtils(); 21288 if (mappingTableCsvContentArray.length === 1) downloadUtils.createAndDownloadFile(mappingTableCsvContentArray[0].fileName, mappingTableCsvContentArray[0].fileContent, "text/csv"); 21289 else downloadUtils.createAndDownloadZipFile(mappingTableCsvContentArray); 21290 }); 21291 }; 21292 } 21293 static { 21294 this.addStageAssetItem = (assets, snapshotAssets) => { 21295 assets = snapshotAssets.map((snapshotAsset) => { 21296 return { 21297 ...assets.find((projectAsset) => projectAsset.name === snapshotAsset.name && projectAsset.type === snapshotAsset.type), 21298 stageVersion: snapshotAsset.version, 21299 stageAssetItem: { ...snapshotAsset } 21300 }; 21301 }); 21302 return assets; 21303 }; 21304 } 21305 static { 21306 this.downloadMappingTableAndConvertToCsvContent = (mappingTable, assets, downloadUrl, isStageView) => { 21307 return new Promise((resolve, reject) => { 21308 MappingTablesUtils.fetchData(mappingTable, isStageView, downloadUrl).then((mappingTableData) => { 21309 if (mappingTableData) {
21310 let csvContent = []; 21311 let { scheme, data } = mappingTableData; 21312 let cells = []; 21313 scheme.inputs.forEach((input) => { 21314 cells.push(input.name); 21315 }); 21316 scheme.outputs.forEach((output) => { 21317 cells.push(output.name); 21318 }); 21319 csvContent.push(cells); 21320 data.forEach((row) => { 21321 let cells = []; 21322 scheme.inputs.forEach((input) => { 21323 cells.push(row[input.name]); 21324 }); 21325 scheme.outputs.forEach((output) => { 21326 const outputIdent = output.id || output.text || output.name; 21327 if (output.type === CELL.Media.cellType) { 21328 let asset = row[outputIdent]; 21329 cells.push(asset ? getAssetTitleFromName(asset["repo-url"], assets) : ""); 21330 } else if (output.type === CELL.Color.cellType) cells.push(JSON.stringify(row[outputIdent])); 21331 else cells.push(row[outputIdent]); 21332 }); 21333 csvContent.push(cells); 21334 }); 21335 import_lib$1.stringify(csvContent, (err, output) => { 21336 if (err) reject(err); 21337 else resolve({ 21338 fileName: `${mappingTable.title}.csv`, 21339 fileContent: output 21340 }); 21341 }); 21342 } else reject("No Data"); 21343 }); 21344 }); 21345 }; 21346 } 21347 static { 21348 this.handleDeleteMappingTables = (mappingTableIds, assets, accountId, project, deleteAsset, cb) => { 21349 let mappingTablesToBeDeleted = mappingTableIds.map((mappingTableId) => { 21350 return MappingTablesUtils.findMappingTableByID(mappingTableId, assets); 21351 }); 21352 let title; 21353 let subtitle; 21354 if (mappingTablesToBeDeleted.length > 1) { 21355 title = "Delete Data Tables"; 21356 subtitle = `Are you sure you want to delete ${mappingTablesToBeDeleted.length} data tables?`; 21357 } else { 21358 let prettyMappingTableName = mappingTablesToBeDeleted[0].title; 21359 title = "Delete Data Table"; 21360 subtitle = `Are you sure you want to delete ${prettyMappingTableName}?`; 21361 } 21362 HubNotifications.confirm(title, subtitle, () => { 21363 mappingTablesToBeDeleted.forEach((mappingTable) => { 21364 deleteAsset(accountId, project.projectName, AssetTypes.mappingTable, mappingTable.name, cb); 21365 }); 21366 }); 21367 }; 21368 } 21369 static addUsedInScenesForMappingTable(assets, wireframeScenes, logicData) { 21370 let mappingTables = MappingTablesUtils.extractMappingTablesFromAssets(assets); 21371 let mappingTableToSceneMap = extractScenesByType(Object.keys(wireframeScenes).reduce((acc, sceneId) => { 21372 if (!Object.values(LogicContainers).includes(sceneId)) { 21373 let sceneLogic = logicData[sceneId] || {}; 21374 acc[sceneId] = { 21375 ...wireframeScenes[sceneId], 21376 ...sceneLogic 21377 }; 21378 } 21379 return acc; 21380 }, {}), LOGIC_DATA_TYPES.MappingTable); 21381 Object.keys(mappingTableToSceneMap).forEach((mt) => { 21382 mappingTableToSceneMap[mt] = mappingTableToSceneMap[mt].map((id) => wireframeScenes[id].name).join(", "); 21383 }); 21384 return mappingTables.map((mt) => Object.assign({}, mt, { usedInScenes: mappingTableToSceneMap[mt.name] })); 21385 } 21386 static { 21387 this.handleUpdateDataElements = (arrayOfOldAndNewDataElementsPairs, accountId, projectName, updateDataElement, addDataElement, setInputLogic, getInputLogic) => { 21388 arrayOfOldAndNewDataElementsPairs.forEach((dataElementsPair) => { 21389 let oldDataElement = dataElementsPair[0]; 21390 let newDataElement = dataElementsPair[1]; 21391 if (oldDataElement && newDataElement) DataLibraryController.handleUpdateDataElement(oldDataElement, newDataElement, void 0, false, accountId, projectName, updateDataElement, addDataElement, setInputLogic, getInputLogic); 21392 }); 21393 }; 21394 } 21395 static { 21396 this.handleUpdateDataElement = (oldDataElement, newDataElement, newLogicData, isNewDataElement, accountId, projectName, updateDataElement, addDataElement, setInputLogic, getInputLogic) => { 21397 if (!isNewDataElement) { 21398 updateDataElement({ 21399 accountId, 21400 projectName, 21401 dataElementId: getDataElementId(newDataElement), 21402 data: newDataElement, 21403 logic: newLogicData 21404 }); 21405 if (getDataElementType(oldDataElement) !== getDataElementType(newDataElement) && getDataElementOrigin(newDataElement) === DataElementOrigins.Derived) { 21406 const derivedDataElementLogicId = getDerivedDataElementLogicId(newDataElement); 21407 let logic = getInputLogic(derivedDataElementLogicId, DataElementOrigins.Derived); 21408 if (logic) { 21409 logic.outputType = DataLibraryController.convertToLogicType(getDataElementType(newDataElement)); 21410 setInputLogic(accountId, projectName, DataElementOrigins.Derived, derivedDataElementLogicId, logic); 21411 } 21412 } 21413 if (getDataElementOrigin(oldDataElement) === DataElementOrigins.Feed && getDataElementOrigin(newDataElement) === DataElementOrigins.Derived && newLogicData) setInputLogic(accountId, projectName, DataElementOrigins.Derived, getDerivedDataElementLogicId(newDataElement), newLogicData); 21414 } else addDataElement(accountId, projectName, newDataElement, newLogicData, (createdDataElement) => { 21415 if (newLogicData) setInputLogic(accountId, projectName, DataElementOrigins.Derived, getDerivedDataElementLogicId(createdDataElement), newLogicData); 21416 }); 21417 }; 21418 } 21419 static { 21420 this.getUsedInDeleteMessage = (dataElementToBeDeleted, analyticsDataElements, assets, dataElements, logicData) => { 21421 let message = "";
21422 const dataTables = MappingTablesUtils.extractMappingTablesFromAssets(assets); 21423 const usedDataElementIds = extractDataElementIdsFromLogic(logicData[LogicContainers.Derived], dataTables); 21424 dataElementToBeDeleted.forEach((de) => { 21425 const usedInScene = getDataElementUsedInScene(de); 21426 const usedInAnalytics = DataLibraryController.isUsedInAnalytics(de, analyticsDataElements); 21427 const usedInStudio = usedDataElementIds.includes(de.id) || usedDataElementIds.includes(de.name); 21428 if (usedInScene || usedInAnalytics || usedInStudio) { 21429 message += `\n${getDataElementDisplayName(de)}: `; 21430 const usedInSceneMessage = `Used in ${usedInScene === "Master" ? "" : "scenes - "}${usedInScene}`; 21431 if (usedInScene && usedInAnalytics && usedInStudio) message += `${usedInSceneMessage}, And in Studio Data, And in Analytics Settings.`; 21432 else if (usedInScene && usedInStudio) message += `${usedInSceneMessage}, And in Studio Data.`; 21433 else if (usedInAnalytics && usedInStudio) message += "Used in Studio Data, And in Analytics Settings."; 21434 else if (usedInScene && usedInAnalytics) message += `${usedInSceneMessage}, And in Analytics Settings.`; 21435 else if (usedInScene) message += `${usedInSceneMessage}.`; 21436 else if (usedInStudio) message += "Used in Studio Data."; 21437 else message += "Used in Analytics Settings."; 21438 } 21439 }); 21440 return message; 21441 }; 21442 } 21443 static { 21444 this.isUsedInAnalytics = (de, analyticsDataElements) => { 21445 return analyticsDataElements && analyticsDataElements.includes(getDataElementId(de)); 21446 }; 21447 } 21448 static { 21449 this.handleDeleteDataElements = (dataElementIds, dataElements, accountId, projectName, deleteInputLogic, deleteDataElement, deleteDataElements, analyticsDataElements, assets, wireframesLogic, cb, isFullDemoFlowBuilder) => { 21450 let dataElementToBeDeleted = dataElementIds.map((dataElementId) => { 21451 return findDataElementById(dataElementId, dataElements); 21452 }); 21453 let numOfDataElementToBeDeleted = dataElementToBeDeleted.length; 21454 let { displayName: elementEntityName, indefiniteArticle } = getOriginDisplayNameAndIndefiniteArticle(dataElementToBeDeleted[0].origin, isFullDemoFlowBuilder); 21455 let text; 21456 let subHeader; 21457 let handleFunction; 21458 let isDeleteMessage; 21459 let usedInMessage = DataLibraryController.getUsedInDeleteMessage(dataElementToBeDeleted, analyticsDataElements, assets, dataElements, wireframesLogic); 21460 if (!usedInMessage) { 21461 if (numOfDataElementToBeDeleted === 1) { 21462 subHeader = "Permanently delete " + elementEntityName + " " + getDataElementDisplayName(dataElementToBeDeleted[0]) + "?"; 21463 text = "Once " + indefiniteArticle + " " + elementEntityName + " is deleted, it cannot be restored."; 21464 } else if (numOfDataElementToBeDeleted > 1) { 21465 subHeader = "Permanently delete the following " + elementEntityName + "s?\n" + dataElementToBeDeleted.map((element) => getDataElementDisplayName(element)).join(", "); 21466 text = "Once " + indefiniteArticle + " " + elementEntityName + " is deleted, it cannot be restored."; 21467 } 21468 handleFunction = (usedInEditorCallback) => { 21469 dataElementToBeDeleted.forEach((toBeDeleted) => { 21470 if (toBeDeleted.origin === DataElementOrigins.Derived) deleteInputLogic(accountId, projectName, DataElementOrigins.Derived, getDerivedDataElementLogicId(toBeDeleted)); 21471 deleteDataElement(accountId, projectName, getDataElementId(toBeDeleted), cb); 21472 }); 21473 deleteDataElements(accountId, projectName, dataElementIds, (deletedIds) => deletedIds.forEach((deId) => cb(deId)), usedInEditorCallback); 21474 }; 21475 isDeleteMessage = true; 21476 } else { 21477 numOfDataElementToBeDeleted === 1 ? subHeader = "The following " + elementEntityName + " is in use and cannot be deleted." : subHeader = "The following " + elementEntityName + "s are in use and cannot be deleted."; 21478 subHeader = subHeader + "\n" + usedInMessage; 21479 text = ""; 21480 handleFunction = () => {}; 21481 isDeleteMessage = false; 21482 } 21483 return { 21484 subHeader, 21485 text, 21486 isDeleteMessage, 21487 handleFunction 21488 }; 21489 }; 21490 } 21491 static { 21492 this.handleEditorUsedInResponse = (usedInData) => { 21493 const numOfDataElementToBeDeleted = usedInData.length; 21494 const text = "";
21495 const handleFunction = () => {}; 21496 const isDeleteMessage = false; 21497 const subHeaderFirstLine = `The following Data Element${numOfDataElementToBeDeleted === 1 ? " is" : "s are"} in use and cannot be deleted.`; 21498 return { 21499 subHeader: usedInData.reduce((acc, usedInResult) => { 21500 acc.push(`${usedInResult.dataElementName} - used in:`); 21501 usedInResult.usedInScenes.forEach((usedIn, index) => { 21502 acc.push(`${index + 1}. ${usedIn.programName} > ${usedIn.sceneName}`); 21503 }); 21504 return acc; 21505 }, [subHeaderFirstLine, "\xA0"]).join("\n"), 21506 text, 21507 isDeleteMessage, 21508 handleFunction 21509 }; 21510 }; 21511 } 21512 static { 21513 this.getSearchFieldPlaceholderText = (selectedTabId, isFullDemoFlowBuilder) => { 21514 if (selectedTabId === DataLibraryController.studioDataTabId) return isFullDemoFlowBuilder ? "Find Audience" : "Find Studio Data"; 21515 else if (selectedTabId === DataLibraryController.dataTablesTabId) return "Find Data Table"; 21516 else if (selectedTabId === DataLibraryController.creativeDataTabId) return "Find Content Set Data"; 21517 return "Find Data Element"; 21518 }; 21519 } 21520 static addUsedInScene(dataElementsArr, wireframes, wireframeScenes, logicData, assets) { 21521 let dataElementToScenesMap = DataLibraryController.getUsedInScenes(wireframes, dataElementsArr, wireframeScenes, logicData, assets); 21522 return dataElementsArr.map((de) => changeAndSetUsedInScene(de, dataElementToScenesMap[getDataElementId(de)])); 21523 } 21524 static { 21525 this.getScenesDataAndLogic = (wireframeScenes, logicData) => { 21526 return Object.keys(wireframeScenes).reduce((acc, sceneId) => { 21527 if (sceneId !== LogicContainers.Master || !Object.values(LogicContainers).includes(sceneId)) { 21528 let sceneLogic = logicData[sceneId] || {}; 21529 acc[sceneId] = { 21530 ...wireframeScenes[sceneId], 21531 ...sceneLogic 21532 }; 21533 } 21534 return acc; 21535 }, {}); 21536 }; 21537 } 21538 static { 21539 this.getMasterSceneDataAndLogic = (masterSceneData, logicObj) => { 21540 return { [LogicContainers.Master]: { 21541 ...masterSceneData, 21542 ...logicObj[LogicContainers.Master], 21543 ...logicObj[LogicContainers.Story], 21544 ...logicObj[LogicContainers.Analytics] 21545 } }; 21546 }; 21547 } 21548 static { 21549 this.getUsedInScenes = (wireframes, dataElementsArr, wireframeScenes, logicData, assets) => { 21550 let scenesDataAndLogic = DataLibraryController.getScenesDataAndLogic(wireframeScenes, logicData); 21551 let masterDataAndLogic = DataLibraryController.getMasterSceneDataAndLogic(wireframeScenes[LogicContainers.Master], logicData); 21552 let allScenesLogic = { 21553 ...scenesDataAndLogic, 21554 ...masterDataAndLogic 21555 }; 21556 let mappingTables = MappingTablesUtils.extractMappingTablesFromAssets(assets); 21557 let deToScenesMap = extractScenes({ 21558 wireframes, 21559 logicData: allScenesLogic, 21560 dataElementsArr, 21561 derivedLogic: logicData[LogicContainers.Derived], 21562 mappingTables 21563 }); 21564 Object.keys(deToScenesMap).forEach((de) => { 21565 deToScenesMap[de] = deToScenesMap[de].map((id) => wireframeScenes[id].name).join(", "); 21566 }); 21567 return deToScenesMap; 21568 }; 21569 } 21570 static convertToLogicType(dataElementType) { 21571 switch (dataElementType) { 21572 case LOGIC_MEDIA_TYPES.String: return LOGIC_TYPE.Text; 21573 case LOGIC_MEDIA_TYPES.Number: return LOGIC_TYPE.DataElementNumber; 21574 case LOGIC_MEDIA_TYPES.Date: return LOGIC_TYPE.DataElementDate; 21575 case LOGIC_MEDIA_TYPES.Boolean: return LOGIC_TYPE.DataElementBoolean; 21576 case LOGIC_MEDIA_TYPES.URL: return LOGIC_TYPE.Image; 21577 } 21578 return LOGIC_TYPE.Text; 21579 } 21580 static isDataElementInUseInMappingTables(dataElementId, assets) { 21581 let result = false;
21582 MappingTablesUtils.extractMappingTablesFromAssets(assets).forEach((mappingTable) => { 21583 let inputs = mappingTable.mappingTableScheme.inputs; 21584 if (inputs && !result) result = inputs.some((input) => { 21585 return input.id === dataElementId || input.name === dataElementId; 21586 }); 21587 }); 21588 return result; 21589 } 21590 static getDataElementUsedInScenesIds(dataElement, scenes) { 21591 let scenesIds = []; 21592 getDataElementUsedInScene(dataElement).split(",").forEach((sceneName) => { 21593 let scene = scenes.find((s) => s.name === sceneName.trim()); 21594 if (scene) scenesIds.push(scene.id); 21595 }); 21596 return scenesIds; 21597 } 21598 static getDataElementsUsedInScenesMap(dataElements, scenes, dataElementsFilterFunc) { 21599 let scenesToDataElementsMap = /* @__PURE__ */ new Map(); 21600 let dataElementsArr = dataElements; 21601 if (dataElementsFilterFunc && typeof dataElementsFilterFunc === "function") dataElementsArr = dataElements.filter(dataElementsFilterFunc); 21602 dataElementsArr.forEach((dataElement) => { 21603 DataLibraryController.getDataElementUsedInScenesIds(dataElement, scenes).forEach((sceneId) => { 21604 if (!scenesToDataElementsMap.has(sceneId)) scenesToDataElementsMap.set(sceneId, []); 21605 let sceneDataElements = scenesToDataElementsMap.get(sceneId); 21606 if (!sceneDataElements.includes(dataElement)) sceneDataElements.push(dataElement); 21607 }); 21608 }); 21609 scenesToDataElementsMap.forEach((value, key, map) => { 21610 let sortedDataElementsArr = value.sort(StateReaderUtils.objectComparator("displayName", 1)); 21611 map.set(key, sortedDataElementsArr); 21612 }); 21613 return scenesToDataElementsMap; 21614 } 21615 static { 21616 this.dataElementsTabId = 0; 21617 } 21618 static { 21619 this.studioDataTabId = 1; 21620 } 21621 static { 21622 this.dataTablesTabId = 2; 21623 } 21624 static { 21625 this.creativeDataTabId = 3; 21626 } 21627}; 21628//#endregion 21629//#region client/components/HubEditor/rightPanels/dataLibrary/DataElementsTabContentController.ts 21630var DataElementsTabContentController = class DataElementsTabContentController { 21631 static { 21632 this.popUpLabels = { 21633 Status: "Status", 21634 Type: "Type", 21635 Name: "Name", 21636 Description: "Description", 21637 ValueSet: "Value Set", 21638 Logic: "Logic", 21639 Tag: "Tag", 21640 Convert: "Convert To Studio Data", 21641 AssignToStory: "Assign To Story" 21642 }; 21643 } 21644 static { 21645 this.editDataElementAttribute = (editedDataElement, value, editPopUpLabel) => { 21646 let newDataElement = editedDataElement; 21647 switch (editPopUpLabel) { 21648 case DataElementsTabContentController.popUpLabels.Name: 21649 newDataElement = changeName(editedDataElement, value); 21650 break; 21651 case DataElementsTabContentController.popUpLabels.Description: 21652 newDataElement = changeDescription(editedDataElement, value); 21653 break; 21654 case DataElementsTabContentController.popUpLabels.Status: 21655 newDataElement = changeStatus(editedDataElement, value); 21656 break; 21657 case DataElementsTabContentController.popUpLabels.Type: 21658 newDataElement = changeContentType(editedDataElement, value); 21659 break; 21660 case DataElementsTabContentController.popUpLabels.AssignToStory: 21661 newDataElement = changeAssignedStories(editedDataElement, value); 21662 break; 21663 } 21664 return newDataElement; 21665 }; 21666 } 21667 static { 21668 this.validateValueSetForDataElement = (dataElement) => { 21669 let valueList = ValueSetController.buildValueListFromDataElement(dataElement); 21670 let typeIsNumber = dataElement.type === LOGIC_MEDIA_TYPES.Number; 21671 return valueList.every((value) => { 21672 return !(typeIsNumber && isNaN(Number(value.text))); 21673 }); 21674 }; 21675 } 21676 static createStubDataElement(origin = DataElementOrigins.Feed) { 21677 return buildDataElement({ 21678 id: void 0, 21679 type: DataElementContentTypes.String, 21680 origin 21681 }); 21682 } 21683 static { 21684 this.getTextForNoItemSelected = (tabId, isFullDemoFlowBuilder) => { 21685 if (tabId === DataLibraryController.studioDataTabId) return isFullDemoFlowBuilder ? "Select an Audience to view its detail" : "Select a Studio Data to view its detail"; 21686 else if (tabId === DataLibraryController.creativeDataTabId) return "Select a Content Set Data to view its details"; 21687 return "Select a data element to view its details"; 21688 }; 21689 } 21690 static { 21691 this.validateDataElementName = (name, origin, allDataElements, isFullDemoFlowBuilder) => { 21692 if (name.trim() === "") return { 21693 isValid: false, 21694 helperText: "Value must not be blank" 21695 }; 21696 if (!/^[a-zA-Z\s\.\,\-\_\d]+$/.test(name)) return { 21697 isValid: false,
21698 helperText: "Enter only letters, numbers, spaces, commas, periods, underscores & hyphens." 21699 }; 21700 if (origin === DataElementOrigins.Derived) { 21701 if (name.includes(".")) return { 21702 isValid: false, 21703 helperText: getOriginDisplayName(origin, isFullDemoFlowBuilder) + " name must not include '.'" 21704 }; 21705 } 21706 let existingDE = (allDataElements || []).find((de) => getDataElementDisplayName(de).toLowerCase() === name.toLowerCase()); 21707 if (existingDE) return { 21708 isValid: false, 21709 helperText: getOriginDisplayName(existingDE.origin, isFullDemoFlowBuilder) + " with this name already exists" 21710 }; 21711 return { 21712 isValid: true, 21713 helperText: "" 21714 }; 21715 }; 21716 } 21717 static { 21718 this.anySystemDataElements = (dataElementsIdsArray, dataElements) => { 21719 return dataElementsIdsArray.some((dataElementId) => { 21720 let dataElement = findDataElementById(dataElementId, dataElements); 21721 return Boolean(dataElement && dataElement.origin === DataElementOrigins.System); 21722 }); 21723 }; 21724 } 21725 static { 21726 this.anyAdsDataElements = (dataElementsIdsArray, dataElements) => { 21727 return dataElementsIdsArray.some((dataElementId) => { 21728 let dataElement = findDataElementById(dataElementId, dataElements); 21729 return Boolean(dataElement && DataElementsTabContentController.isAdsDataElement(dataElement)); 21730 }); 21731 }; 21732 } 21733 static { 21734 this.allSystemOrAdsDataElements = (dataElementsIdsArray, dataElements) => { 21735 return dataElementsIdsArray.every((dataElementId) => { 21736 const dataElement = findDataElementById(dataElementId, dataElements); 21737 return DataElementsTabContentController.isSystemOrAdsDataElements(dataElement); 21738 }); 21739 }; 21740 } 21741 static { 21742 this.removeSystemAndAdsDataElements = (dataElementsIdsArray, dataElements) => { 21743 return dataElementsIdsArray.filter((id) => { 21744 const dataElement = findDataElementById(id, dataElements); 21745 return !DataElementsTabContentController.isSystemOrAdsDataElements(dataElement); 21746 }); 21747 }; 21748 } 21749 static { 21750 this.isSystemOrAdsDataElements = (dataElement) => dataElement.origin === DataElementOrigins.System || DataElementsTabContentController.isAdsDataElement(dataElement); 21751 } 21752 static { 21753 this.getDataElementDisplayNameForTable = (dataElement) => { 21754 if (getDataElementOrigin(dataElement) === DataElementOrigins.System || adsDataElements.find((de) => getDataElementDisplayName(de) === getDataElementDisplayName(dataElement))) return `Sys: ${getDataElementDisplayName(dataElement)}`; 21755 return getDataElementDisplayName(dataElement); 21756 }; 21757 } 21758 static { 21759 this.removeTag = ({ tag, selected, dataElements }) => { 21760 return selected.reduce((acc, selectedId) => { 21761 const oldDe = findDataElementById(selectedId, dataElements); 21762 if (!hasTag(oldDe, getDataElementTagKey(tag))) return acc; 21763 const newDe = removeTag(oldDe, getDataElementTagKey(tag)); 21764 return [...acc, [oldDe, newDe]]; 21765 }, []); 21766 }; 21767 } 21768 static { 21769 this.addTag = ({ tag, selected, dataElements }) => { 21770 return selected.reduce((acc, selectedId) => { 21771 const oldDe = findDataElementById(selectedId, dataElements); 21772 if (hasTag(oldDe, getDataElementTagKey(tag))) return acc; 21773 const newDe = addTag(oldDe, getDataElementTagKey(tag)); 21774 return [...acc, [oldDe, newDe]]; 21775 }, []); 21776 }; 21777 } 21778 static { 21779 this.addAssignedStory = (storyId, selectedDataElementIds, allDataElements) => { 21780 return selectedDataElementIds.map((selectedId) => { 21781 const oldDe = findDataElementById(selectedId, allDataElements); 21782 if (!getDataElementAssignedStories(oldDe).includes(storyId)) return [oldDe, addAssignedStory(oldDe, storyId)]; 21783 }); 21784 }; 21785 } 21786 static { 21787 this.removeAssignedStory = (storyId, selectedDataElementIds, allDataElements, allStoriesIds) => { 21788 return selectedDataElementIds.map((selectedId) => { 21789 const oldDe = findDataElementById(selectedId, allDataElements); 21790 if (getDataElementAssignedStories(oldDe).includes(storyId)) return [oldDe, removeAssignedStory(oldDe, storyId)]; 21791 else if (getDataElementAssignedToAllStories(oldDe)) { 21792 let newDe = changeAssignedStories(oldDe, allStoriesIds.filter((sId) => sId !== storyId)); 21793 newDe = changeAssignedToAllStories(newDe, false); 21794 return [oldDe, newDe]; 21795 } 21796 }); 21797 }; 21798 } 21799 static { 21800 this.handleAssignedToAllStories = (checked, selectedDataElementIds, allDataElements) => { 21801 return selectedDataElementIds.map((selectedId) => { 21802 const oldDe = findDataElementById(selectedId, allDataElements); 21803 let newDe = changeAssignedStories(oldDe, []); 21804 newDe = changeAssignedToAllStories(newDe, checked); 21805 return [oldDe, newDe]; 21806 }); 21807 }; 21808 } 21809 static { 21810 this.getAssignedStoriesNames = (dataElement, stories) => { 21811 const assignedStories = getDataElementAssignedStories(dataElement); 21812 if (getDataElementAssignedToAllStories(dataElement)) return ASSIGN_TO_ALL_STORIES_LABEL; 21813 else if (assignedStories.length > 0) return stories.filter((story) => assignedStories.includes(story.id)).map((story) => story.name).join(", "); 21814 else return ""; 21815 }; 21816 } 21817 static { 21818 this.isAdsDataElement = (dataElement) => { 21819 return Boolean(adsDataElements.find((de) => getDataElementDisplayName(de) === getDataElementDisplayName(dataElement))); 21820 }; 21821 } 21822}; 21823//#endregion 21824//#region client/logic/entities/dataElementEntity.ts 21825var DataElementEntity = class DataElementEntity extends BaseEntity { 21826 constructor() { 21827 super(EntityTypes.DATA_ELEMENT); 21828 this.collector = (args) => { 21829 const { context, previousContext } = args; 21830 const previousDataElements = previousContext && StateReaderUtils.getProjectDataElements(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version).filter((dataElement) => dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative); 21831 const currentDataElements = StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version).filter((dataElement) => dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative); 21832 const dataElementsMap = this.entityListsToMap(previousDataElements, currentDataElements, (de) => de.id); 21833 let dataElementInstances = [];
21834 dataElementsMap.forEach((entityContextPair, key) => { 21835 dataElementInstances.push({ 21836 id: key, 21837 validate: () => this.doValidate(entityContextPair.currentEntity), 21838 diff: () => this.doDiff(entityContextPair.previousEntity, entityContextPair.currentEntity) 21839 }); 21840 }); 21841 return dataElementInstances; 21842 }; 21843 this.doValidate = (dataElement) => { 21844 let valid = true; 21845 if (dataElement.useValueSet && dataElement.valueSet && dataElement.valueSet.length > 0) valid = DataElementsTabContentController.validateValueSetForDataElement(dataElement); 21846 const type = this.getType(); 21847 const id = dataElement.id; 21848 return valid ? { 21849 type, 21850 id, 21851 issues: [] 21852 } : { 21853 type, 21854 id, 21855 issues: [{ 21856 code: IssueCodes.DATA_ELEMENT_VALUE_SET, 21857 severity: IssueSeverity.ERROR, 21858 details: {} 21859 }], 21860 severity: IssueSeverity.ERROR 21861 }; 21862 }; 21863 this.doDiff = (previousDataElement, currentDataElement) => { 21864 const changeType = diffEntities(DataElementEntity.normalizeDataElement(previousDataElement), DataElementEntity.normalizeDataElement(currentDataElement)); 21865 return { 21866 type: this.getPropsFromPreviousOrCurrent(previousDataElement, currentDataElement, "origin") === DataElementOrigins.Creative ? EntityTypes.CREATIVE_DATA_ELEMENT : EntityTypes.DATA_ELEMENT, 21867 id: this.getPropsFromPreviousOrCurrent(previousDataElement, currentDataElement, "id"), 21868 name: this.getPropsFromPreviousOrCurrent(previousDataElement, currentDataElement, "displayName"), 21869 changeType, 21870 changes: [], 21871 isShown: changeType !== ChangeType.None 21872 }; 21873 }; 21874 } 21875 static normalizeDataElement(dataElement) { 21876 if (!dataElement) return dataElement; 21877 const normalizedDataElement = { ...dataElement }; 21878 if (normalizedDataElement.getValueSet) { 21879 normalizedDataElement.valueSet = normalizedDataElement.getValueSet(); 21880 delete normalizedDataElement.getValueSet; 21881 } 21882 if (normalizedDataElement.origin === DataElementOrigins.Derived || normalizedDataElement.origin === DataElementOrigins.Creative) delete normalizedDataElement.status; 21883 if (normalizedDataElement.origin === DataElementOrigins.Derived) delete normalizedDataElement.useValueSet; 21884 if (!normalizedDataElement.assignedStories) normalizedDataElement.assignedStories = []; 21885 if (normalizedDataElement.origin === DataElementOrigins.Creative && !normalizedDataElement.assignedToAllStories) normalizedDataElement.assignedToAllStories = false; 21886 delete normalizedDataElement._objectType; 21887 delete normalizedDataElement.graphQLId; 21888 delete normalizedDataElement.graphQLUpdated; 21889 return normalizedDataElement; 21890 } 21891}; 21892//#endregion 21893//#region client/logic/entities/assetEntity.ts 21894/** 21895* This is a base class for MediaEntity, AnimationEntity, RecordingEntity & DataTableEntity, which all share the same collector. 21896* The derived classes can override the doDiff/doValidate methods written in this class. 21897* **/ 21898var AssetEntity = class extends BaseEntity { 21899 constructor(type, assetType) { 21900 super(type); 21901 this.getAssetId = (asset) => asset.name; 21902 this.collector = (args) => { 21903 const { context, previousContext } = args; 21904 let assets = []; 21905 const project = StateReaderUtils.getProject(context.state, context.projectName); 21906 const previousProjectRFR = previousContext && this.assetType === ASSET_TYPES.recording && StateReaderUtils.getProgramRFR(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version);
21907 const currentProjectRFR = this.assetType === ASSET_TYPES.recording && StateReaderUtils.getProgramRFR(context.state, context.projectName, context.stage, context.version); 21908 const previousAssets = previousContext && StateReaderUtils.getAssetsInVersionMode(project, previousContext.state.assets, previousContext.state.snapshots, previousContext.version, this.assetType); 21909 let currentAssets = StateReaderUtils.getAssetsFromSnapshotOrDraft(project, context.state.assets, context.state.snapshots, void 0, context.version, this.assetType); 21910 if (!previousContext && this.assetType === ASSET_TYPES.recording) currentAssets = currentAssets.filter((asset) => asset.RFR >= currentProjectRFR); 21911 this.entityListsToMap(previousAssets, currentAssets, this.getAssetId).forEach((entityContextPair, key) => { 21912 const { previousEntity: previousAsset, currentEntity: currentAsset } = entityContextPair; 21913 assets.push({ 21914 id: key, 21915 validate: (prevValidationResult, getValidationResultFunction) => { 21916 return this.doValidate({ 21917 asset: currentAsset, 21918 getValidationResult: getValidationResultFunction, 21919 context 21920 }); 21921 }, 21922 diff: () => { 21923 return this.doDiff({ 21924 id: key, 21925 previousAsset, 21926 currentAsset, 21927 versionView: Boolean(context.version),
21928 currentProjectRFR, 21929 previousProjectRFR 21930 }); 21931 } 21932 }); 21933 }); 21934 return assets; 21935 }; 21936 this.doValidate = ({}) => {}; 21937 this.doDiff = ({ id, previousAsset, currentAsset, versionView }) => { 21938 const normalizedPreviousAsset = this.normalizeAssetObject(previousAsset, true); 21939 const normalizedCurrentAsset = this.normalizeAssetObject(currentAsset, versionView); 21940 const changeType = diffEntities(normalizedPreviousAsset, normalizedCurrentAsset); 21941 return { 21942 type: this.getType(), 21943 id, 21944 name: this.getPropsFromPreviousOrCurrent(normalizedPreviousAsset, normalizedCurrentAsset, "title"), 21945 changeType, 21946 changes: [], 21947 isShown: changeType !== ChangeType.None 21948 }; 21949 }; 21950 this.normalizeAssetObject = (asset, versionView) => { 21951 if (!asset) return; 21952 return { 21953 assetId: asset.assetId, 21954 title: asset.title, 21955 activeVersion: AssetUtils.getVersion(asset, versionView) 21956 }; 21957 }; 21958 this.assetType = assetType; 21959 } 21960}; 21961//#endregion 21962//#region client/logic/entities/dataTableEntity.ts 21963var DataTableEntity = class extends AssetEntity { 21964 constructor() { 21965 super(EntityTypes.DATA_TABLE, ASSET_TYPES.mappingTable); 21966 this.doDiff = ({ id, previousAsset, currentAsset, versionView }) => { 21967 const normalizedPreviousAsset = this.normalizeDataTableObject(previousAsset, true); 21968 const normalizedCurrentAsset = this.normalizeDataTableObject(currentAsset, versionView); 21969 const changeType = diffEntities(normalizedPreviousAsset, normalizedCurrentAsset); 21970 return { 21971 type: this.getType(), 21972 id, 21973 name: this.getPropsFromPreviousOrCurrent(normalizedPreviousAsset, normalizedCurrentAsset, "title"), 21974 changeType, 21975 changes: [], 21976 isShown: changeType !== ChangeType.None 21977 }; 21978 }; 21979 this.doValidate = ({ asset, getValidationResult, context }) => { 21980 const mappingTable = asset; 21981 let mappingTableValidationResult = { 21982 type: this.getType(), 21983 id: mappingTable.name, 21984 issues: [] 21985 }; 21986 const inputs = mappingTable.mappingTableScheme.inputs.filter((input) => input.id !== "HubSystem:Story"); 21987 const getDependencyId = (input) => { 21988 if (input.id) return input.id; 21989 let allDataElements = StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version); 21990 let dataElement = findDataElementByName(input.name, allDataElements); 21991 return dataElement && dataElement.id; 21992 }; 21993 let issue = this.getDependenciesIssue(inputs, EntityTypes.DATA_ELEMENT, getDependencyId, getValidationResult, IssueCodes.DATA_TABLE_SCHEME_ERROR); 21994 if (issue) { 21995 mappingTableValidationResult.issues.push(issue); 21996 mappingTableValidationResult.severity = issue.severity; 21997 } 21998 return mappingTableValidationResult; 21999 }; 22000 this.normalizeDataTableObject = (dataTable, versionView) => { 22001 if (!dataTable) return; 22002 return { 22003 assetId: dataTable.assetId, 22004 title: dataTable.title, 22005 location: AssetUtils.getLocation(dataTable, versionView) 22006 }; 22007 }; 22008 } 22009}; 22010//#endregion 22011//#region client/logic/entities/groupEntity.ts 22012var GroupEntity = class extends BaseEntity { 22013 constructor() { 22014 super(EntityTypes.GROUP); 22015 this.collector = (args) => { 22016 const { context, previousContext } = args; 22017 let allLogicObjects = []; 22018 if (!previousContext) allLogicObjects = this.validationCollector(context); 22019 else allLogicObjects = this.diffCollector(previousContext, context); 22020 return allLogicObjects; 22021 }; 22022 this.validationCollector = (context) => { 22023 let groups = []; 22024 let allScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 22025 if (allScenes) Object.keys(allScenes).forEach((scene) => { 22026 allScenes[scene].sceneParts && allScenes[scene].sceneParts.forEach((scenePart) => { 22027 scenePart.groups && scenePart.groups.forEach((group) => { 22028 groups.push({ 22029 id: group.id, 22030 validate: (prevValidationResult, getValidationResultFunction) => { 22031 return this.doValidate(group, allScenes[scene].id, getValidationResultFunction); 22032 } 22033 }); 22034 }); 22035 }); 22036 }); 22037 return groups; 22038 }; 22039 this.doValidate = (group, sceneId, getValidationResult) => { 22040 const type = this.getType(); 22041 const id = `${group.id}_${sceneId}`; 22042 let groupValidationResult = { 22043 type, 22044 id, 22045 issues: [], 22046 name: group.name 22047 }; 22048 if (group) { 22049 const getDependencyId = () => id; 22050 let issue = this.getDependenciesIssue([void 0], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.GROUP_LOGIC_ERROR); 22051 if (issue) { 22052 groupValidationResult.issues.push(issue); 22053 groupValidationResult.severity = issue.severity; 22054 } 22055 } 22056 return groupValidationResult; 22057 }; 22058 this.getGroupsFromWireframes = (context) => { 22059 const scenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 22060 let groups = [];
22061 Object.values(scenes).forEach((scene) => { 22062 scene.sceneParts && scene.sceneParts.forEach((scenePart) => { 22063 scenePart.groups && scenePart.groups.forEach((group) => { 22064 groups.push({ 22065 id: group.id, 22066 name: group.name 22067 }); 22068 }); 22069 }); 22070 }); 22071 return groups; 22072 }; 22073 this.diffCollector = (previousContext, currentContext) => { 22074 let currentGroups = this.getGroupsFromWireframes(currentContext); 22075 let previousGroups = this.getGroupsFromWireframes(previousContext); 22076 let groups = []; 22077 this.entityListsToMap(previousGroups, currentGroups, (groupObj) => groupObj.id).forEach((groupsPair, groupId) => { 22078 groups.push({ 22079 id: groupId, 22080 diff: (getDiffResult) => { 22081 return this.doDiff(getDiffResult, groupsPair.currentEntity, groupsPair.previousEntity, groupId); 22082 } 22083 }); 22084 }); 22085 return groups; 22086 }; 22087 this.doDiff = (getDiffResult, currentGroup, previousGroup, groupId) => { 22088 let result = { 22089 type: this.getType(), 22090 id: groupId, 22091 name: currentGroup && currentGroup.name || previousGroup.name, 22092 changeType: ChangeType.None, 22093 changes: [], 22094 isShown: false 22095 }; 22096 result.changeType = diffEntities(previousGroup, currentGroup); 22097 if (result.changeType === ChangeType.None) return updateDiffResultWithChanges(result, this.getDependenciesDiff([groupId], EntityTypes.LOGIC, (id) => id, getDiffResult, true)); 22098 else { 22099 result.isShown = true; 22100 return result; 22101 } 22102 }; 22103 } 22104}; 22105//#endregion 22106//#region client/logic/vlx/Validations/validationsFramework.ts 22107/*** 22108* Constructs a simple validations which expects to receive an object 22109* and run the provided test on it, if the result wouldn't be 22110* successful an object will be returned with the provided message, the status and the item 22111* @param text The text which will be assigned to the result if it would not be valid 22112* @param test The test function (which might receive item, input type, array of data elements and an array of assets 22113* @param skipItem - if set to true the failing item wont be added to the returned object (to avoid circular object structure) 22114* @return {function(*=, *=, *=, *=)} the validation closure 22115*/ 22116function validate(text, test, skipItem = false) { 22117 return (item, inputType, context) => { 22118 const result = test(item, inputType, context); 22119 if (typeof result === "object" && result.status && result.status !== VALIDATION_STATUS.Valid) return result; 22120 if (result && result !== VALIDATION_STATUS.Valid) return { 22121 status: result, 22122 message: text, 22123 item: skipItem ? null : item 22124 }; 22125 }; 22126} 22127/** 22128* Construct a validation on a single objects, which consists from 22129* a list of other validations 22130*/ 22131function validateBatch(text, selector, validations) { 22132 return (item, outputType = LOGIC_MEDIA_TYPES.String, context) => { 22133 const _report = runLinearValidations(validations, selector(item), outputType, context); 22134 const finalResult = escalate(_report); 22135 if (finalResult === VALIDATION_STATUS.Valid) return; 22136 return { 22137 status: finalResult, 22138 message: text, 22139 item: selector(item), 22140 report: _report 22141 }; 22142 }; 22143} 22144/** 22145* The identity function (used below) 22146* @param item - an item which would be returned 22147*/ 22148var getIdentity = (item) => item; 22149/** 22150* The defaultExtractor object (used below) 22151* @returns object with "getItem", "getOutputType", "skipItem" - all are functions 22152*/ 22153var defaultExtractor = { 22154 getItem: (item) => item, 22155 getOutputType: (outputType, item) => outputType, 22156 skipItem: (item) => false 22157}; 22158/** 22159* Construct a validation consisting from a bach of validations on an array of items 22160* @param text The text which would be supplied to a failing test 22161* @param selector A function which would pick the array on which 22162* the tests would be run on from an item 22163* @param validations An array of either validate, validateBatch, 22164* or validateArrayBatch functions 22165* @param emptyResult the default result to be retrieved in case of a failure to 22166* initiate the tests 22167* @param extractor - object that can extract value. see defaultExtractor for example 22168* @return {function(*=)} The constructed validations closure, 22169* ready to be run on an object and would return the following object 22170* { 22171* message: <string - the text provided>,
22172* status: <VALIDATION_STATUS>, 22173* item: <object - the item which failed this batch> 22174* report: <Array - array of failed tests in similar structure> 22175* } 22176*/ 22177function validateArrayBatch(text, selector, validations, emptyResult = { status: VALIDATION_STATUS.Valid }, extractor = defaultExtractor) { 22178 return (item, outputType = LOGIC_MEDIA_TYPES.String, context) => { 22179 const items = selector(item); 22180 let _report = [emptyResult]; 22181 if (items && Array.isArray(items) && items.length) { 22182 for (let i = 0; i < items.length; i++) if (!extractor.skipItem(items[i])) _report.push(validateBatch(`${text} - #${i}`, getIdentity, validations)(extractor.getItem(items[i]), extractor.getOutputType(outputType, items[i]), context)); 22183 } 22184 const finalResult = escalate(_report); 22185 if (finalResult === VALIDATION_STATUS.Valid) return; 22186 return { 22187 report: _report, 22188 status: finalResult, 22189 message: text, 22190 item: items 22191 }; 22192 }; 22193} 22194/** 22195* @return The worst validation status Invalid > Partial > Valid 22196*/ 22197function escalate(arrayOfResults) { 22198 if (!arrayOfResults || !arrayOfResults.length) return VALIDATION_STATUS.Valid; 22199 return arrayOfResults.reduce((accumulator, result) => { 22200 if (!result) return accumulator; 22201 if (accumulator === VALIDATION_STATUS.Invalid || result.status === VALIDATION_STATUS.Invalid) return VALIDATION_STATUS.Invalid; 22202 if (result.status === VALIDATION_STATUS.Partial) return VALIDATION_STATUS.Partial; 22203 return accumulator; 22204 }, VALIDATION_STATUS.Valid); 22205} 22206/*** 22207* This runs validations in a linear order so that the first failing (VALIDATION_STATUS.Invalid) 22208* result in an array of validations will stop the following validations after it. 22209* VALIDATION_STATUS.Partial are treated as warnings, VALIDATION_STATUS.Valid are skipped 22210*/ 22211function runLinearValidations(validations, item, outputType, context) { 22212 let result = []; 22213 for (let i = 0; i < validations.length; i++) { 22214 const validationResult = validations[i](item, outputType, context); 22215 if (!validationResult) continue; 22216 result.push(validationResult); 22217 if (validationResult.status === VALIDATION_STATUS.Invalid) break; 22218 } 22219 return result; 22220} 22221//#endregion 22222//#region client/logic/validations/validationUtils.ts 22223var ValidationUtils = class { 22224 static convertIssueSeverityToValidationStatus(severity) { 22225 switch (severity) { 22226 case IssueSeverity.ERROR: return VALIDATION_STATUS.Invalid; 22227 case IssueSeverity.WARNING: return VALIDATION_STATUS.Partial; 22228 default: return VALIDATION_STATUS.Valid; 22229 } 22230 } 22231}; 22232//#endregion 22233//#region client/logic/entities/prioritizedListEntity.ts 22234var PrioritizedListEntity = class PrioritizedListEntity extends BaseEntity { 22235 constructor() { 22236 super(EntityTypes.PRIORITIZED_LIST); 22237 this.collector = ({ context, previousContext }) => { 22238 return !previousContext ? this.validationCollector(context) : this.diffCollector({ 22239 context, 22240 previousContext 22241 }); 22242 }; 22243 this.validationCollector = (context) => { 22244 let prioritizedLists = []; 22245 const wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 22246 const scenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 22247 if (scenes) Object.keys(scenes).forEach((sceneId) => { 22248 StateReaderUtils.getScenePrioritizedList(wireframes, sceneId).forEach((prioritizedList) => { 22249 prioritizedLists.push({ 22250 id: PrioritizedListEntity.generateId(prioritizedList.id, sceneId), 22251 validate: (prevValidationResult, getValidationResultFunction) => { 22252 return this.doValidate(prioritizedList, sceneId, getValidationResultFunction); 22253 } 22254 }); 22255 }); 22256 }); 22257 return prioritizedLists; 22258 }; 22259 this.diffCollector = ({ context, previousContext }) => { 22260 let prioritizedLists = []; 22261 const currentWireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 22262 const previousWireframes = StateReaderUtils.getWireFrame(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 22263 const currentPrioritizedLists = StateReaderUtils.getProjectPrioritizedLists(currentWireframes); 22264 const previousPrioritizedLists = StateReaderUtils.getProjectPrioritizedLists(previousWireframes); 22265 this.entityListsToMap(previousPrioritizedLists, currentPrioritizedLists, (pList) =>
22265 pList.id).forEach((pListsPair, pListId) => { 22266 const { currentEntity: currentPList, previousEntity: previousPList } = pListsPair; 22267 prioritizedLists.push({ 22268 id: pListId, 22269 diff: (getDiffResult) => this.doDiff(getDiffResult, currentPList, previousPList, pListId) 22270 }); 22271 }); 22272 return prioritizedLists; 22273 }; 22274 this.doValidate = (prioritizedList, sceneId, getValidationResult) => { 22275 let prioritizedListValidationResult = { 22276 type: this.getType(), 22277 id: PrioritizedListEntity.generateId(prioritizedList.id, sceneId), 22278 issues: [], 22279 name: prioritizedList.name 22280 }; 22281 if (prioritizedList.rules) { 22282 const getDependencyId = (dependency) => `${dependency.key}_${sceneId}`; 22283 let issue = this.getDependenciesIssue(prioritizedList.rules, EntityTypes.PRIORITIZED_LIST_CANDIDATE, getDependencyId, getValidationResult, IssueCodes.PRIORITIZED_LIST_CANDIDATES_ERROR); 22284 if (issue) { 22285 prioritizedListValidationResult.issues.push(issue); 22286 prioritizedListValidationResult.severity = issue.severity; 22287 } 22288 } 22289 return prioritizedListValidationResult; 22290 }; 22291 this.doDiff = (getDiffResult, currPList, prevPList, pListId) => { 22292 const changeType = diffEntities(this.normalizePriorityList(prevPList), this.normalizePriorityList(currPList)); 22293 return { 22294 type: this.getType(), 22295 id: pListId, 22296 name: this.getPropsFromPreviousOrCurrent(prevPList, currPList, "name"), 22297 changeType, 22298 changes: [], 22299 isShown: changeType !== ChangeType.None 22300 }; 22301 }; 22302 this.normalizePriorityList = (priorityList) => { 22303 if (!priorityList) return; 22304 let normalizedPriorityList = { ...priorityList }; 22305 delete normalizedPriorityList.validation; 22306 delete normalizedPriorityList.graphQLId; 22307 delete normalizedPriorityList.graphQLUpdated; 22308 if (Array.isArray(normalizedPriorityList.slots)) { 22309 normalizedPriorityList.slots = deepCloneObj(normalizedPriorityList.slots); 22310 for (let slot of normalizedPriorityList.slots) { 22311 delete slot.graphQLId; 22312 delete slot.graphQLUpdated; 22313 if (Array.isArray(slot.placeholders)) for (let ph of slot.placeholders) { 22314 delete ph.x; 22315 delete ph.y; 22316 delete ph.width; 22317 delete ph.height; 22318 delete ph.validationStatus; 22319 delete ph.graphQLId; 22320 delete ph.graphQLUpdated; 22321 } 22322 else { 22323 delete slot.x; 22324 delete slot.y; 22325 delete slot.width; 22326 delete slot.height; 22327 delete slot.validationStatus; 22328 } 22329 } 22330 } 22331 return normalizedPriorityList; 22332 }; 22333 } 22334 static { 22335 this.generateId = (prioritizedListId, sceneId) => { 22336 return prioritizedListId + "_" + sceneId; 22337 }; 22338 } 22339}; 22340//#endregion 22341//#region client/logic/vlx/Validations/logicValidations.ts 22342/*** 22343* VLX params types and Logic MediaType are different when it comes to 'Number' -_- 22344* @return {boolean} 22345*/ 22346var sameMediaType = (mediaA, mediaB) => { 22347 return mediaA === mediaB || mediaA === VLX_PARAMTYPE.Numeric && mediaB === LOGIC_MEDIA_TYPES.Number || mediaB === VLX_PARAMTYPE.Numeric && mediaA === LOGIC_MEDIA_TYPES.Number; 22348}; 22349/** 22350* Checks weather a given element reference (i.e. Actionable Data) refers to an existing element. 22351* The types of elements it checks are data element, data tables and value set values 22352* @param element An Actionable data 22353* @param context Context 22354*/ 22355function elementIsPresent(element, context) { 22356 let { dataElements, assets } = context; 22357 if (JSON.stringify(element) === JSON.stringify(TEXT_ELEMENTS[0])) return true; 22358 if (!element || !element.mediaType) return false; 22359 if (element.type === LOGIC_DATA_TYPES.Const) return true; 22360 if (element.type === LOGIC_DATA_TYPES.ValueSetValue) { 22361 const dataElement = findDataElementById(element.id, dataElements); 22362 if (dataElement) { 22363 let valueSet = dataElement.getValueSet(); 22364 if (valueSet && valueSet.find((value) => value && value.id === element.name)) return true; 22365 } 22366 return false; 22367 } 22368 if (element.type === LOGIC_DATA_TYPES.DataElement) return !!findDataElementByLogicValue(element, dataElements); 22369 if (element.type === LOGIC_DATA_TYPES.Asset) return !!assets[AssetTypes.mappingTable + "/" + element.name]; 22370 return true; 22371} 22372function convertLogicTypeToAssetType(logicType) { 22373 switch (logicType) { 22374 case LogicType.Animation: return AssetTypes.animation; 22375 case LogicType.Image: 22376 case LogicType.Video: 22377 case LogicType.Audio:
22378 case LogicType.BackgroundAsset: return AssetTypes.curated; 22379 default: return null; 22380 } 22381} 22382var getAssetsArray = index((assets) => { 22383 return Object.values(assets); 22384}); 22385function isDataElementApproved(de, dataElements) { 22386 let element = findDataElementByLogicValue(de, dataElements); 22387 if (element && element.origin === DataElementOrigins.Feed && (element.status === DataElementStatuses.Missing || element.status === DataElementStatuses.Pending)) return false; 22388 return true; 22389} 22390function isDataElementValid(dataElement, getValidationResult) { 22391 let entityType = getValidationResult && (dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative ? EntityTypes.DATA_ELEMENT : EntityTypes.DERIVED_DATA_ELEMENT); 22392 let dataElementValidationResult = getValidationResult ? getValidationResult(entityType, dataElement.id) : getDataElementValidationResult(getReduxState(), dataElement.id, dataElement.origin); 22393 return { 22394 valid: !(dataElementValidationResult && dataElementValidationResult.issues.length > 0), 22395 severity: dataElementValidationResult && dataElementValidationResult.severity 22396 }; 22397} 22398function isDerivedDataElementApproved(de, dataElements) { 22399 return true; 22400} 22401function isDataTableValid(element, context) { 22402 let { assets, getValidationResult } = context; 22403 let dataTableName = getMappingTableNameFromValue(element); 22404 const res = assets[AssetTypes.mappingTable + "/" + dataTableName]?.mappingTableScheme?.outputs.some((output) => (output.id && element.id ? output.id : output.name) === getMappingTablePropertyFromValue(element)); 22405 let validationResult = getValidationResult ? getValidationResult(EntityTypes.DATA_TABLE, dataTableName) : getDataTableValidationResult(getReduxState(), dataTableName); 22406 return res && !(validationResult && validationResult.issues.length > 0); 22407} 22408function isPrioritizedListValid(prioritizedList, containingSceneId, getValidationResult) { 22409 let entityType = EntityTypes.PRIORITIZED_LIST; 22410 let validationTableId = PrioritizedListEntity.generateId(prioritizedList.id, containingSceneId); 22411 let listValidationResult = getValidationResult ? getValidationResult(entityType, validationTableId) : getPriorityListValidationResult(getReduxState(), validationTableId); 22412 return { 22413 valid: !(listValidationResult?.issues.length > 0), 22414 severity: listValidationResult?.severity 22415 }; 22416} 22417function isActionableDataValid(actionableData, context) { 22418 let mediaType = convertLogicMediaTypToVlxParamType(getElementInfoFromActionableData(actionableData, { 22419 dataElements: context.dataElements, 22420 assets: getAssetsArray(context.assets) 22421 }).mediaType); 22422 let valid = true; 22423 if (actionableData.actions?.length) actionableData.actions.forEach((action) => { 22424 if (mediaType !== action.input[0]) valid = false; 22425 mediaType = action.output; 22426 }); 22427 return valid; 22428} 22429/******* List of validations go here *******/ 22430function isBlank(str) { 22431 return typeof str === "string" && (!str || /^\s*$/.test(str)); 22432} 22433var nextSceneDefaultValueValidations = [validate(VALIDATION_TEXT.ValueIsEmpty, (item) => { 22434 if (item === void 0 || item === null || item === "" || isBlank(item) || Array.isArray(item) && item.every((str) => isBlank(str))) return VALIDATION_STATUS.Invalid; 22435 return VALIDATION_STATUS.Valid; 22436})]; 22437var storyValueValidations = [validate(VALIDATION_TEXT.ValueIsEmpty, (item, inputType, context) => { 22438 let { stories } = context; 22439 return stories[item] ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22440})]; 22441var singleValueValidations = [ 22442 validate(VALIDATION_TEXT.ValueIsEmpty, (item, inputType) => { 22443 if (item === void 0 || item === null || item === "" || isBlank(item) || Array.isArray(item) && item.every((str) => isBlank(str))) if (inputType === LogicType.Quality || inputType === LogicType.Ratio) return VALIDATION_STATUS.Invalid; 22444 else return VALIDATION_STATUS.Partial; 22445 return VALIDATION_STATUS.Valid; 22446 }), 22447 validate(VALIDATION_TEXT.ValueCanBeComplexStringOnlyForStringPlaceholders, (item, inputType) => { 22448 if (!item) return VALIDATION_STATUS.Valid; 22449 if (inputType === LOGIC_TYPE.DataElementString || inputType === LOGIC_TYPE.Text) return Array.isArray(item) ? VALIDATION_
22449STATUS.Valid : VALIDATION_STATUS.Invalid; 22450 return VALIDATION_STATUS.Valid; 22451 }), 22452 validate(VALIDATION_TEXT.SelectedMediaTypeDoesNotMatchPlaceholderType, (item, inputType) => { 22453 if (!item) return VALIDATION_STATUS.Valid; 22454 if (inputType === LogicType.DataElementString || inputType === LogicType.Text || inputType === LogicType.DataElementNumber || inputType === LogicType.NextScene || inputType === LogicType.DataElementBoolean || inputType === LogicType.Story || inputType === LogicType.Quality || inputType === LogicType.Ratio) return VALIDATION_STATUS.Valid; 22455 if (inputType === LogicType.Color && isValidColor(item)) return VALIDATION_STATUS.Valid; 22456 if (Array.isArray(item)) return VALIDATION_STATUS.Valid; 22457 if (item.mediaType !== inputType) { 22458 if (item.actions && item.actions.length) { 22459 let last_action = item.actions[item.actions.length - 1]; 22460 if (last_action.output && sameMediaType(last_action.output, inputType)) return VALIDATION_STATUS.Valid; 22461 } 22462 if ([DATA_TABLE_OUTPUT_TYPES.Media, DATA_TABLE_OUTPUT_TYPES.Url].includes(item.mediaType) && (inputType === LOGIC_TYPE.Video || inputType === LOGIC_TYPE.Image || inputType === LOGIC_TYPE.Audio)) return VALIDATION_STATUS.Valid; 22463 return VALIDATION_STATUS.Invalid; 22464 } 22465 }), 22466 validate(VALIDATION_TEXT.SelectedDataElementIsMissingOrPending, (item, inputType, context) => { 22467 let { dataElements } = context; 22468 if (!item) return VALIDATION_STATUS.Valid; 22469 if (Array.isArray(item)) { 22470 let filtered = item.filter((elem) => elem.type === LOGIC_DATA_TYPES.DataElement); 22471 if (!filtered) return VALIDATION_STATUS.Valid; 22472 return filtered.some((elem) => !isDataElementApproved(elem, dataElements)) ? VALIDATION_STATUS.Partial : VALIDATION_STATUS.Valid; 22473 } 22474 return !isDataElementApproved(item, dataElements) ? VALIDATION_STATUS.Partial : VALIDATION_STATUS.Valid; 22475 }), 22476 validate(VALIDATION_TEXT.DataElementsOrAssetsNotValid, (item, inputType, context) => { 22477 if (!item || inputType === LogicType.Quality || inputType === LogicType.Ratio) return VALIDATION_STATUS.Valid; 22478 if (item.id && item.displayName && item.outputType && item.show !== void 0) return VALIDATION_STATUS.Valid; 22479 if (Array.isArray(item)) { 22480 let filtered = item.filter((elem) => typeof elem !== "string"); 22481 if (!filtered) return VALIDATION_STATUS.Valid; 22482 return filtered.some((elem) => !elementIsPresent(elem, context)) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid; 22483 } 22484 if (item.defaultValueShow !== void 0 && !item.defaultValueShow) return VALIDATION_STATUS.Valid; 22485 return typeof item !== "string" ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22486 }), 22487 validate(VALIDATION_TEXT.DataTableNotValid, (item, inputType, context) => { 22488 if (!item) return VALIDATION_STATUS.Valid; 22489 if (Array.isArray(item)) { 22490 let filtered = item.filter((elem) => elem.type === LOGIC_DATA_TYPES.MappingTable); 22491 if (!filtered) return VALIDATION_STATUS.Valid; 22492 return filtered.some((elem) => !isDataTableValid(elem, context)) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid; 22493 } else if (item.type === LOGIC_DATA_TYPES.MappingTable) return !isDataTableValid(item, context) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid; 22494 return VALIDATION_STATUS.Valid; 22495 }), 22496 validate(VALIDATION_TEXT.AssetIsRequestWaitingForFulfilment, (item, inputType, context) => { 22497 let { assets } = context; 22498 if (!item) return VALIDATION_STATUS.Valid; 22499 const currentAsset = assets[convertLogicTypeToAssetType(inputType) + "/" + item.name]; 22500 return currentAsset && currentAsset.status === "request" ? VALIDATION_STATUS.Partial : VALIDATION_STATUS.Valid; 22501 }), 22502 validate(VALIDATION_TEXT.DataElementValueSetNotValid, (item, mediaType, context) => { 22503 let { dataElements, getValidationResult } = context; 22504 if (!item) return VALIDATION_STATUS.Valid; 22505 if (Array.isArray(item)) { 22506 let filtered = item.filter((elem) => elem.type === LOGIC_DATA_TYPES.DataElement); 22507 if (!filtered) return VALIDATION_STATUS.Valid; 22508 let severities = []; 22509 return filtered.some((elem) => { 22510 let dataElement = findDataElementByLogicValue(elem, dataElements); 22511 let result = isDataElementValid(dataElement, getValidationResult); 22512 if (result && !result.valid) severities.push(result.severity); 22513 return !result.valid && (dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative); 22514 }) ? ValidationUtils.convertIssueSeverityToValidationStatus(ValidationManager.getHighestSeverity(severities)) : VALIDATION_
22514STATUS.Valid; 22515 } else if (item.type === LOGIC_DATA_TYPES.DataElement) { 22516 let dataElement = findDataElementByLogicValue(item, dataElements); 22517 let result = isDataElementValid(dataElement, getValidationResult); 22518 if (!result.valid && (dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative)) return ValidationUtils.convertIssueSeverityToValidationStatus(result.severity); 22519 } 22520 return VALIDATION_STATUS.Valid; 22521 }), 22522 validate(VALIDATION_TEXT.DerivedDataElementLogicIsNotValid, (item, mediaType, context) => { 22523 let { dataElements, getValidationResult } = context; 22524 if (!item) return VALIDATION_STATUS.Valid; 22525 if (Array.isArray(item)) { 22526 let filtered = item.filter((elem) => elem.type === LOGIC_DATA_TYPES.DataElement); 22527 if (!filtered) return VALIDATION_STATUS.Valid; 22528 let severities = []; 22529 return filtered.some((elem) => { 22530 let dataElement = findDataElementByLogicValue(elem, dataElements); 22531 let result = isDataElementValid(dataElement, getValidationResult); 22532 if (result && !result.valid) severities.push(result.severity); 22533 return dataElement.origin === DataElementOrigins.Derived && !result.valid; 22534 }) ? ValidationUtils.convertIssueSeverityToValidationStatus(ValidationManager.getHighestSeverity(severities)) : VALIDATION_STATUS.Valid; 22535 } else if (item.type === LOGIC_DATA_TYPES.DataElement) { 22536 let dataElement = findDataElementByLogicValue(item, dataElements); 22537 let result = isDataElementValid(dataElement, getValidationResult); 22538 if (dataElement.origin === DataElementOrigins.Derived && !result.valid) return ValidationUtils.convertIssueSeverityToValidationStatus(result.severity); 22539 } 22540 return VALIDATION_STATUS.Valid; 22541 }), 22542 validate(VALIDATION_TEXT.DerivedDataElementIsNotValid, (item, mediaType, context) => { 22543 let { dataElements } = context; 22544 if (!item) return VALIDATION_STATUS.Valid; 22545 if (Array.isArray(item)) { 22546 let filtered = item.filter((elem) => elem.type === LOGIC_DATA_TYPES.DataElement); 22547 if (!filtered) return VALIDATION_STATUS.Valid; 22548 return filtered.some((elem) => !isDerivedDataElementApproved(elem, dataElements)) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid; 22549 } 22550 return !isDerivedDataElementApproved(item, dataElements) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid; 22551 }), 22552 validate(VALIDATION_TEXT.ValueFunctionOrFormatterTypeMismatch, (item, mediaType, context) => { 22553 return getAllActionableDataFromValue(item).every((actionableData) => isActionableDataValid(actionableData, context)) ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22554 }) 22555]; 22556var compoundValueExtractor = { 22557 getItem: (item) => item.value, 22558 getOutputType: (outputType, item) => item.outputType ? item.outputType : outputType, 22559 skipItem: (item) => !item.show 22560}; 22561var hotspotValueExtractor = { 22562 ...compoundValueExtractor, 22563 skipItem: (item) => !item.show || EXCLUDED_HOTSPOT_KEYS.includes(item.id) 22564}; 22565var compoundAndSingleValueValidations = [validate(VALIDATION_TEXT.CompoundValuesMustBeValid, (itemsOrItem, inputType, context) => { 22566 if (inputType === LogicType.Compound || inputType === LogicType.Prioritized) { 22567 const isHotspot = isLogicValueHotspot(itemsOrItem); 22568 return validateArrayBatch(isHotspot ? VALIDATION_TEXT.HotspotValuesMustBeValid : VALIDATION_TEXT.CompoundValuesMustBeValid, getIdentity, compoundAndSingleValueValidations, { status: VALIDATION_STATUS.Valid }, isHotspot ? hotspotValueExtractor : compoundValueExtractor)(itemsOrItem, inputType, context); 22569 } else return validateBatch(VALIDATION_TEXT.SingleValueMustBeValid, getIdentity, singleValueValidations)(itemsOrItem, inputType, context); 22570})]; 22571var operatorValidations = [ 22572 validate(VALIDATION_TEXT.InvalidOperatorForLeftHandSideOperand, (operation, outputType, context) => { 22573 const logicUtilsContext = { 22574 dataElements: context.dataElements, 22575 assets: getAssetsArray(context.assets) 22576 }; 22577 const lhsMediaType = getLhsMediaType(operation.lhs, logicUtilsContext); 22578 if (operation.lhs && operation.operator && !getAvailableOperatorsForObject(lhsMediaType).includes(operation.operator)) return VALIDATION_STATUS.Invalid;
22579 return VALIDATION_STATUS.Valid; 22580 }), 22581 validate(VALIDATION_TEXT.OperationMustBeComplete, (op) => { 22582 if (op.lhs && op.operator && (valueExists(op.rhs) || !hasRhs(op.operator))) return VALIDATION_STATUS.Valid; 22583 return VALIDATION_STATUS.Invalid; 22584 }), 22585 validate("Value must be one of value set", (operation, outputType, context) => { 22586 let { dataElements } = context; 22587 let valueSet = getRhsValueSet(operation.operator, operation.lhs, dataElements); 22588 if (!valueSet) return VALIDATION_STATUS.Valid; 22589 if (typeof operation.rhs === "string") { 22590 if (!valueSet.some((value) => value && value.displayName === operation.rhs)) return VALIDATION_STATUS.Invalid; 22591 return VALIDATION_STATUS.Valid; 22592 } else if (Array.isArray(operation.rhs) && operation.rhs.length === 1) { 22593 if (typeof operation.rhs[0] === "string" && !valueSet.some((value) => value && value.displayName === operation.rhs[0])) return VALIDATION_STATUS.Invalid; 22594 return VALIDATION_STATUS.Valid; 22595 } else if (!Array.isArray(operation.rhs) && typeof operation.rhs === "object") { 22596 if (operation.rhs.type === LOGIC_DATA_TYPES.Const) return valueSet.some((value) => value && parseStringToRelevantMediaType(value.displayName, operation.rhs.mediaType) === operation.rhs.name) ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22597 else if (operation.rhs.type === LOGIC_DATA_TYPES.ValueSetValue) return valueSet.some((value) => value && value.name === operation.rhs.name) ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22598 return VALIDATION_STATUS.Valid; 22599 } 22600 return VALIDATION_STATUS.Invalid; 22601 }), 22602 validate(VALIDATION_TEXT.RightHandSideOperandTypeMismatch, (op, type, context) => { 22603 if (op.lhs && op.operator && valueExists(op.rhs)) { 22604 let rhsMediaType = void 0; 22605 if (Array.isArray(op.rhs) || typeof op.rhs === "string") rhsMediaType = LogicMediaType.String; 22606 else { 22607 const logicUtilsContext = { 22608 dataElements: context.dataElements, 22609 assets: getAssetsArray(context.assets) 22610 }; 22611 rhsMediaType = getElementInfoFromActionableData(op.rhs, logicUtilsContext).mediaType; 22612 } 22613 const logicUtilsContext = { 22614 dataElements: context.dataElements, 22615 assets: getAssetsArray(context.assets) 22616 }; 22617 if (getRhsMediaType(op.operator, getLhsMediaType(op.lhs, logicUtilsContext)) !== rhsMediaType) return VALIDATION_STATUS.Invalid; 22618 } 22619 return VALIDATION_STATUS.Valid; 22620 }), 22621 validate(VALIDATION_TEXT.SelectedDataElementIsMissingOrPending, (op, type, context) => { 22622 let { dataElements } = context; 22623 return isDataElementApproved(op.lhs, dataElements) ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Partial; 22624 }), 22625 validate(VALIDATION_TEXT.DataElementValueSetNotValid, (op, type, context) => { 22626 let { dataElements, getValidationResult } = context; 22627 if (op.lhs.type === LOGIC_DATA_TYPES.DataElement) { 22628 let dataElement = findDataElementByLogicValue(op.lhs, dataElements); 22629 if (dataElement && (dataElement.origin === DataElementOrigins.Feed || dataElement.origin === DataElementOrigins.Creative)) { 22630 let result = isDataElementValid(dataElement, getValidationResult); 22631 if (!result.valid) return ValidationUtils.convertIssueSeverityToValidationStatus(result.severity); 22632 } 22633 } 22634 return VALIDATION_STATUS.Valid; 22635 }), 22636 validate(VALIDATION_TEXT.DerivedDataElementLogicIsNotValid, (op, type, context) => { 22637 let { dataElements, getValidationResult } = context; 22638 if (op.lhs.type === LOGIC_DATA_TYPES.DataElement) { 22639 let dataElement = findDataElementByLogicValue(op.lhs, dataElements); 22640 if (dataElement && dataElement.origin === DataElementOrigins.Derived) { 22641 let result = isDataElementValid(dataElement, getValidationResult); 22642 if (!result.valid) return ValidationUtils.convertIssueSeverityToValidationStatus(result.severity); 22643 } 22644 } 22645 return VALIDATION_STATUS.Valid; 22646 }), 22647 validate(VALIDATION_TEXT.DataTableNotValid, (op, type, context) => { 22648 if (op.lhs.type === LOGIC_DATA_TYPES.MappingTable) { 22649 if (!isDataTableValid(op.lhs, context)) return VALIDATION_STATUS.Invalid; 22650 } 22651 return VALIDATION_STATUS.Valid; 22652 }), 22653 validate(VALIDATION_TEXT.PrioritizedListIsMissing, (op, type, context) => { 22654 if (op.lhs.type === ActionableDataValueType.PrioritizedSlot || op.lhs.t
22654ype === ActionableDataValueType.Prioritized) { 22655 const { prioritizedLists } = context; 22656 const listActionableData = op.lhs; 22657 return (prioritizedLists || []).some((pl) => pl.id === getPrioritizedListIdFromActionableDataId(listActionableData.id)) ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22658 } 22659 return VALIDATION_STATUS.Valid; 22660 }), 22661 validate(VALIDATION_TEXT.PrioritizedListLogicIsInvalid, (op, type, context) => { 22662 if (op.lhs.type === ActionableDataValueType.PrioritizedSlot || op.lhs.type === ActionableDataValueType.Prioritized) { 22663 const { prioritizedLists, getValidationResult } = context; 22664 const listActionableData = op.lhs; 22665 const result = isPrioritizedListValid((prioritizedLists || []).find((pl) => pl.id === getPrioritizedListIdFromActionableDataId(listActionableData.id)), context.containingSceneId, getValidationResult); 22666 if (!result.valid) return ValidationUtils.convertIssueSeverityToValidationStatus(result.severity); 22667 } 22668 return VALIDATION_STATUS.Valid; 22669 }), 22670 validate(VALIDATION_TEXT.PrioritizedListSlotIsMissing, (op, type, context) => { 22671 if (op.lhs.type === ActionableDataValueType.PrioritizedSlot) { 22672 const { prioritizedLists } = context; 22673 const listActionableData = op.lhs; 22674 return (prioritizedLists || []).find((pl) => pl.id === getPrioritizedListIdFromActionableDataId(listActionableData.id)).maxSlots > listActionableData.slotIdx ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22675 } 22676 return VALIDATION_STATUS.Valid; 22677 }), 22678 validate(VALIDATION_TEXT.OperandFunctionOrFormatterTypeMismatch, (op, type, context) => { 22679 const actionables = getAllActionableDataFromValue(op.rhs); 22680 if (op.lhs) actionables.push(op.lhs); 22681 return actionables.every((actionableData) => isActionableDataValid(actionableData, context)) ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22682 }) 22683]; 22684var ruleOperatorValidations = [validate(VALIDATION_TEXT.RuleMustHaveValidCondition, (condition, outputType, context) => { 22685 if (typeof condition === "string") return VALIDATION_STATUS.Valid; 22686 return validateBatch(VALIDATION_TEXT.OperatorMustBeValid, getIdentity, operatorValidations)(condition, outputType, context); 22687})]; 22688var logicWhenValidations = [validate(VALIDATION_TEXT.RuleMustHaveAtLeastOneCondition, (rule) => !rule.always && (!rule.whens || !rule.whens.length) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid), validateArrayBatch(VALIDATION_TEXT.RuleOperatorsMustBeValid, (rule) => rule.whens, ruleOperatorValidations)]; 22689var logicThenValidation = [validate(VALIDATION_TEXT.CaseMustHaveAValue, (logicRule) => { 22690 return logicRule.show !== void 0 && !logicRule.show || logicRule.value !== null && logicRule.value !== void 0 ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Partial; 22691}), validate(VALIDATION_TEXT.RuleValueMustBeValid, (rule, outputType, context) => { 22692 if (rule.show !== void 0 && !rule.show) return VALIDATION_STATUS.Valid; 22693 return validateBatch(VALIDATION_TEXT.ShownRuleValueMustBeValid, (rule) => rule.value, compoundAndSingleValueValidations)(rule, outputType, context); 22694})]; 22695var nextSceneValueValidations = [validate(VALIDATION_TEXT.ValueIsEmpty, (item, outputType, context) => { 22696 let scenes = context.scenes || {}; 22697 let sceneId; 22698 if (item) if (item.hasOwnProperty("nextDPLogicId") && item.hasOwnProperty("sceneId")) sceneId = item.sceneId; 22699 else sceneId = item; 22700 return scenes[sceneId] ? VALIDATION_STATUS.Valid : VALIDATION_STATUS.Invalid; 22701})]; 22702var logicRuleValidations = [...logicWhenValidations, ...logicThenValidation]; 22703var nextSceneLogicRuleValidations = [...logicWhenValidations, validateBatch(VALIDATION_TEXT.RuleValueMustBeValid, (rule) => rule.value, nextSceneValueValidations)]; 22704var storyRuleValidations = [...logicWhenValidations, validateBatch(VALIDATION_TEXT.RuleValueMustBeValid, (rule) => rule.value, storyValueValidations)]; 22705var prioritizedListValidations = [validate(VALIDATION_TEXT.CandidateNameMustBeValid, (input) => input.rules.some((rule) => { 22706 if (rule.name !== void 0) { 22707 if (rule.name === null || !HubEditorUtils.isAlphaNumeric(rule.name)) return true; 22708 if (input.rules.filter((r) => r.name === rule.name).length > 1) return true; 22709 } 22710 return false;
22711}) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid)]; 22712var placeholderValidations = [ 22713 validate(VALIDATION_TEXT.PlaceholderMustHaveAName, (placeholder) => !placeholder ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid, true), 22714 validate(VALIDATION_TEXT.InputMustHaveADefaultValue, (input, outputType, context) => { 22715 if (isLogicEmpty(input, context.isOptionalDefaultValueFlag)) return VALIDATION_STATUS.Invalid; 22716 return VALIDATION_STATUS.Valid; 22717 }, true), 22718 validate(VALIDATION_TEXT.DefaultValueShouldBeValid, (input, outputType, context) => { 22719 if (input.defaultValueShow !== void 0 && !input.defaultValueShow) return VALIDATION_STATUS.Valid; 22720 return validateBatch(VALIDATION_TEXT.DefaultValueShouldBeValid, (item) => item.defaultValue, compoundAndSingleValueValidations)(input, outputType, context); 22721 }, true), 22722 validateArrayBatch(VALIDATION_TEXT.AllCasesMustBeValid, (input) => input.rules, logicRuleValidations, { status: VALIDATION_STATUS.Valid }), 22723 validateArrayBatch(VALIDATION_TEXT.CandidateNameMustBeValid, (input) => input.outputType === LOGIC_TYPE.Prioritized ? [input] : null, prioritizedListValidations, { status: VALIDATION_STATUS.Valid }) 22724]; 22725var sceneAnimationValidations = [ 22726 validate(VALIDATION_TEXT.InputMustHaveADefaultValue, (input) => { 22727 if (isLogicEmpty(input)) return VALIDATION_STATUS.Partial; 22728 return VALIDATION_STATUS.Valid; 22729 }, true), 22730 validate(VALIDATION_TEXT.DefaultValueShouldBeValid, (input, outputType, context) => { 22731 if (input.defaultValueShow !== void 0 && !input.defaultValueShow) return VALIDATION_STATUS.Valid; 22732 return validateBatch(VALIDATION_TEXT.DefaultValueShouldBeValid, (item) => item.defaultValue, compoundAndSingleValueValidations)(input, outputType, context); 22733 }, true), 22734 validateArrayBatch(VALIDATION_TEXT.AllCasesMustBeValid, (input) => input.rules, logicRuleValidations, { status: VALIDATION_STATUS.Valid }) 22735]; 22736var sceneValidationValidations = [validateArrayBatch(VALIDATION_TEXT.AllCasesMustBeValid, (input) => input.rules, logicWhenValidations, { status: VALIDATION_STATUS.Valid })]; 22737var customAnalyticsValidations = [validate(VALIDATION_TEXT.PleaseChooseAnElement, (input) => { 22738 if (isLogicEmpty(input)) return VALIDATION_STATUS.Invalid; 22739 return VALIDATION_STATUS.Valid; 22740}, true), validate(VALIDATION_TEXT.InvalidDataElementSelected, (element, logicType, context) => { 22741 let { dataElements } = context; 22742 if (elementIsPresent(element.defaultValue, context) && isDataElementApproved(element.defaultValue, dataElements)) return VALIDATION_STATUS.Valid; 22743 return VALIDATION_STATUS.Invalid; 22744}, true)]; 22745var nextSceneValidations = [ 22746 validate(VALIDATION_TEXT.InputMustHaveADefaultValue, (input) => { 22747 if (!input.isLast && isLogicEmpty(input)) return VALIDATION_STATUS.Invalid; 22748 return VALIDATION_STATUS.Valid; 22749 }, true), 22750 validate(VALIDATION_TEXT.DefaultValueShouldBeValid, (input, outputType, context) => { 22751 if (input.isLast || input.defaultValueShow !== void 0 && !input.defaultValueShow) return VALIDATION_STATUS.Valid; 22752 return validateBatch(VALIDATION_TEXT.DefaultValueShouldBeValid, (item) => item.defaultValue, nextSceneDefaultValueValidations)(input, outputType, context); 22753 }, true), 22754 validateArrayBatch(VALIDATION_TEXT.AllCasesMustBeValid, (input) => input.rules, nextSceneLogicRuleValidations, { status: VALIDATION_STATUS.Valid }) 22755]; 22756var storyValidations = [ 22757 validate(VALIDATION_TEXT.InputMustHaveADefaultValue, (input) => { 22758 return isLogicEmpty(input) ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid; 22759 }, true), 22760 validate(VALIDATION_TEXT.DefaultValueShouldBeValid, (input, outputType, context) => { 22761 return validateBatch(VALIDATION_TEXT.DefaultValueShouldBeValid, (item) => item.defaultValue, storyValueValidations)(input, outputType, context); 22762 }, true), 22763 validateArrayBatch(VALIDATION_TEXT.AllCasesMustBeValid, (item) => item.rules, storyRuleValidations, { status: VALIDATION_STATUS.Valid }) 22764]; 22765function runValidations(logicObject, context, validationsArray) { 22766 let validationObj = { 22767 report: [], 22768 status: !logicObject ? VALIDATION_STATUS.Invalid : VALIDATION_STATUS.Valid 22769 }; 22770 if (!logicObject) return validationObj; 22771 validationObj.report = runLinearValidations(validationsArray, logicObject, logicObject.outputType, context); 22772 validationObj.status = escalate(validationObj.report);
22773 if (validationObj.status !== VALIDATION_STATUS.Valid) validationObj.message = validationObj.report[0].message; 22774 return validationObj; 22775} 22776function runPlaceholderValidations(logicObject, context) { 22777 let validationObj = { 22778 report: [], 22779 status: isLogicEmpty(logicObject) ? VALIDATION_STATUS.Partial : VALIDATION_STATUS.Valid 22780 }; 22781 let emptyLogicReport = { 22782 status: VALIDATION_STATUS.Partial, 22783 message: VALIDATION_TEXT.InputMustHaveADefaultValue 22784 }; 22785 if (isLogicEmpty(logicObject, context.isOptionalDefaultValueFlag)) { 22786 validationObj.report.push(emptyLogicReport); 22787 return validationObj; 22788 } 22789 return runValidations(logicObject, context, placeholderValidations); 22790} 22791function runSceneAnimationValidations(logicObject, context) { 22792 return runValidations(logicObject, context, sceneAnimationValidations); 22793} 22794function runSceneValidationValidations(logicObject, context) { 22795 return runValidations(logicObject, context, sceneValidationValidations); 22796} 22797function runCustomAnalyticsValidation(logicObject, context) { 22798 return runValidations(logicObject, context, customAnalyticsValidations); 22799} 22800function runNextSceneValidation(logicObject, context) { 22801 return runValidations(logicObject, context, nextSceneValidations); 22802} 22803function runStoryValidations(logicObject, context) { 22804 return runValidations(logicObject, context, storyValidations); 22805} 22806function validateInputLogic(logicObject, context) { 22807 try { 22808 if (logicObject.outputType === LogicType.AnalyticCustomField) return runCustomAnalyticsValidation(logicObject, context); 22809 if (logicObject.outputType === LogicType.NextScene) return runNextSceneValidation(logicObject, context); 22810 if (logicObject.outputType === LogicType.Animation) return runSceneAnimationValidations(logicObject, context); 22811 if (logicObject.outputType === LogicType.SceneValidation) return runSceneValidationValidations(logicObject, context); 22812 if (logicObject.outputType === LogicType.Story) return runStoryValidations(logicObject, context); 22813 else return runPlaceholderValidations(logicObject, context); 22814 } catch (exception) { 22815 if (window.location.host !== "studio.sundaysky.com") throw exception; 22816 } 22817} 22818//#endregion 22819//#region client/logic/entities/sceneAnimationEntity.ts 22820var SceneAnimationEntity = class SceneAnimationEntity extends BaseEntity { 22821 constructor() { 22822 super(EntityTypes.SCENE_ANIMATION); 22823 this.collector = (args) => { 22824 const { context, previousContext } = args; 22825 let scenes = []; 22826 let allScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 22827 if (allScenes) { 22828 allScenes = removeMasterFromScenes(allScenes); 22829 const wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 22830 Object.values(allScenes).forEach((scene) => { 22831 const sceneLogic = StateReaderUtils.getAllProgramLogicFromWireframes(wireframes, scene.id); 22832 const sceneAnimationLogicId = SceneAnimationEntity.generateId(scene.id); 22833 const sceneAnimationLogic = sceneLogic && sceneLogic[sceneAnimationLogicId]; 22834 scenes.push({ 22835 id: sceneAnimationLogicId, 22836 validate: (prevValidationResult, getValidationResultFunction) => { 22837 return this.doValidate(sceneAnimationLogic || {}, getValidationResultFunction, scene); 22838 } 22839 }); 22840 }); 22841 } 22842 return scenes; 22843 }; 22844 this.doValidate = (sceneAnimationLogic, getValidationResult, scene) => { 22845 const type = this.getType(); 22846 const id = SceneAnimationEntity.generateId(scene.id); 22847 let sceneAnimationValidationResult = { 22848 type, 22849 id, 22850 issues: [] 22851 }; 22852 if (sceneAnimationLogic) { 22853 const getDependencyId = () => id; 22854 let issue = this.getDependenciesIssue([sceneAnimationLogic], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.SCENE_VALIDATION_LOGIC_ERROR); 22855 if (issue) { 22856 sceneAnimationValidationResult.issues.push(issue); 22857 sceneAnimationValidationResult.severity = issue.severity; 22858 } 22859 } 22860 return sceneAnimationValidationResult; 22861 }; 22862 } 22863 static { 22864 this.generateId = (sceneId) => { 22865 return sceneId + "_animation"; 22866 }; 22867 } 22868}; 22869//#endregion 22870//#region client/logic/entities/sceneValidationEntity.ts 22871var SceneValidationEntity = class SceneValidationEntity extends BaseEntity { 22872 constructor() { 22873 super(EntityTypes.SCENE_VALIDATION); 22874 this.collector = (args) => { 22875 const { context, previousContext } = args; 22876 let scenes = []; 22877 let allScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 22878 if (allScenes) { 22879 allScenes = removeMasterFromScenes(allScenes); 22880 const wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version);
22881 Object.values(allScenes).forEach((scene) => { 22882 const sceneLogic = StateReaderUtils.getAllProgramLogicFromWireframes(wireframes, scene.id); 22883 const sceneValidationLogicId = SceneValidationEntity.generateId(scene.id); 22884 const sceneValidationLogic = sceneLogic && sceneLogic[sceneValidationLogicId]; 22885 if (sceneValidationLogic) scenes.push({ 22886 id: sceneValidationLogicId, 22887 validate: (prevValidationResult, getValidationResultFunction) => { 22888 return this.doValidate(sceneValidationLogic, getValidationResultFunction, scene); 22889 } 22890 }); 22891 else scenes.push({ 22892 id: sceneValidationLogicId, 22893 validate: () => { 22894 return { 22895 type: this.getType(), 22896 id: sceneValidationLogicId, 22897 issues: [] 22898 }; 22899 } 22900 }); 22901 }); 22902 } 22903 return scenes; 22904 }; 22905 this.doValidate = (sceneValidationLogic, getValidationResult, scene) => { 22906 const type = this.getType(); 22907 const id = SceneValidationEntity.generateId(scene.id); 22908 let sceneValidationValidationResult = { 22909 type, 22910 id, 22911 issues: [] 22912 }; 22913 if (sceneValidationLogic && sceneValidationLogic.outputType) { 22914 const getDependencyId = () => id; 22915 let issue = this.getDependenciesIssue([sceneValidationLogic], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.SCENE_VALIDATION_LOGIC_ERROR); 22916 if (issue) { 22917 sceneValidationValidationResult.issues.push(issue); 22918 sceneValidationValidationResult.severity = issue.severity; 22919 } 22920 } 22921 return sceneValidationValidationResult; 22922 }; 22923 } 22924 static { 22925 this.generateId = (sceneId) => { 22926 return sceneId + "_validation"; 22927 }; 22928 } 22929}; 22930//#endregion 22931//#region client/logic/entities/logicEntity.ts 22932var { CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC: CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC$1 } = featureFlagConst; 22933var LogicEntity = class LogicEntity extends BaseEntity { 22934 constructor() { 22935 super(EntityTypes.LOGIC); 22936 this.collector = (args) => { 22937 const { context, previousContext } = args; 22938 let allLogicObjects = []; 22939 if (!previousContext) allLogicObjects = this.validationCollector(context); 22940 else allLogicObjects = this.diffCollector(previousContext, context); 22941 return allLogicObjects; 22942 }; 22943 this.validationCollector = (context) => { 22944 let allLogicObjects = []; 22945 const { allScenesIds, logic, wireFrame, allDataElements, useVideoRatioAndQualityLogic } = this.getDataFromContext(context); 22946 if (logic) Object.keys(logic).forEach((logicContainerKey) => { 22947 if (logicContainerKey === LogicContainers.Derived) Object.keys(logic.derived).forEach((derivedId) => { 22948 let derivedObj = findDataElementById(derivedId, allDataElements) || findDataElementByName(derivedId, allDataElements); 22949 if (derivedObj) allLogicObjects.push({ 22950 id: derivedObj.id, 22951 validate: (prevValidationResult, getValidationResultFunction) => { 22952 return this.doValidate(logic.derived[derivedId], getValidationResultFunction, context, derivedObj.id); 22953 } 22954 }); 22955 }); 22956 else if (logicContainerKey === LogicContainers.Program) Object.keys(logic[LogicContainers.Program]).forEach((programLogicType) => { 22957 if (programLogicType === LogicContainers.StorySelection) { 22958 let storySelectionLogic = logic[LogicContainers.Program][LogicContainers.StorySelection][LogicContainers.StorySelection]; 22959 allLogicObjects.push({ 22960 id: LogicEntity.STORY_SELECTION_LOGIC_ID, 22961 validate: (prevValidationResult, getValidationResultFunction) => { 22962 return this.doValidate(storySelectionLogic, getValidationResultFunction, context, LogicEntity.STORY_SELECTION_LOGIC_ID); 22963 } 22964 }); 22965 } 22966 }); 22967 else if (logicContainerKey === LogicContainers.Story) Object.keys(logic.story).forEach((storyId) => { 22968 let story = StateReaderUtils.getStoryById(wireFrame, storyId); 22969 if (logic.story[storyId] && logic.story[storyId].decisionPoint) Object.keys(logic.story[storyId].decisionPoint).forEach((dp) => { 22970 const DPValidationId = getStoryPropertyCollectionId(storyId, dp); 22971 allLogicObjects.push({ 22972 id: DPValidationId, 22973 validate: (prevValidationResult, getValidationResultFunction) => { 22974 return this.doValidate(logic.story[storyId].decisionPoint[dp], getValidationResultFunction, context, DPValidationId); 22975 } 22976 }); 22977 }); 22978 if (logic.story[storyId] && logic.story[storyId][LogicContainers.Soundtrack] && logic.story[storyId][LogicContainers.Soundtrack][MediaTypes.Audio]) allLogicObjects.push({ 22979 id: getStoryPropertyCollectionId(storyId, LogicContainers.Soundtrack), 22980 validate: (prevValidationResult, getValidationResultFunction) => { 22981 return this.doValidate(logic.story[storyId][LogicContainers.Soundtrack][MediaTypes.Audio], getValidationResultFunction, context, `${storyId}_${LogicContainers.Soundtrack}`, true); 22982 } 22983 }); 22984 if (story.backgroundAssetType && logic.story[storyId] && logic.story[storyId][LogicContainers.Backgroun
22984dAsset] && logic.story[storyId][LogicContainers.BackgroundAsset][story.backgroundAssetType]) allLogicObjects.push({ 22985 id: getStoryPropertyCollectionId(storyId, LogicContainers.BackgroundAsset), 22986 validate: (prevValidationResult, getValidationResultFunction) => { 22987 return this.doValidate(logic.story[storyId][LogicContainers.BackgroundAsset][story.backgroundAssetType], getValidationResultFunction, context, `${storyId}_${LogicContainers.BackgroundAsset}`, true); 22988 } 22989 }); 22990 if (useVideoRatioAndQualityLogic) { 22991 const logicObj = StateReaderUtils.getStoryVideoRatioQualityLogicWireframe(wireFrame, storyId); 22992 const ratioAndQualityLogic = logicObj && !isAnEmptyObject(logicObj) ? logicObj : createNewStoryQualityRatioLogic().serializeLogicData(); 22993 const storyVideoRatioQualityLogicValidationId = getStoryPropertyCollectionId(story.id, LogicEntity.VIDEO_RATIO_QUALITY_LOGIC_VALIDATION_ID); 22994 allLogicObjects.push({ 22995 id: storyVideoRatioQualityLogicValidationId, 22996 validate: (prevValidationResult, getValidationResultFunction) => { 22997 return this.doValidate(ratioAndQualityLogic, getValidationResultFunction, context, storyVideoRatioQualityLogicValidationId); 22998 } 22999 }); 23000 } 23001 }); 23002 else if (logicContainerKey === LogicContainers.Analytics) Object.keys(logic.analytics).forEach((analyticsFieldKey) => { 23003 let analyticsId = AnalyticsEntity.generateId(analyticsFieldKey); 23004 let analyticsLogic = logic.analytics[analyticsFieldKey]; 23005 if (analyticsLogic && !analyticsLogic.loading) allLogicObjects.push({ 23006 id: analyticsId, 23007 validate: (prevValidationResult, getValidationResultFunction) => { 23008 return this.doValidate(analyticsLogic, getValidationResultFunction, context, analyticsId); 23009 } 23010 }); 23011 }); 23012 else if (allScenesIds && allScenesIds.indexOf(logicContainerKey) !== -1) { 23013 let sceneAnimationId = SceneAnimationEntity.generateId(logicContainerKey); 23014 let sceneAnimationLogic = logic[logicContainerKey][sceneAnimationId]; 23015 allLogicObjects.push({ 23016 id: sceneAnimationId, 23017 validate: (prevValidationResult, getValidationResultFunction) => { 23018 return this.doValidate(sceneAnimationLogic || {}, getValidationResultFunction, context, sceneAnimationId, false, logicContainerKey); 23019 } 23020 }); 23021 let sceneValidationId = SceneValidationEntity.generateId(logicContainerKey); 23022 let sceneValidationLogic = logic[logicContainerKey][sceneValidationId]; 23023 if (sceneValidationLogic) allLogicObjects.push({ 23024 id: sceneValidationId, 23025 validate: (prevValidationResult, getValidationResultFunction) => { 23026 return this.doValidate(sceneValidationLogic, getValidationResultFunction, context, sceneValidationId, false, logicContainerKey); 23027 } 23028 }); 23029 else allLogicObjects.push({ 23030 id: sceneValidationId, 23031 validate: () => { 23032 return { 23033 type: this.getType(), 23034 id: sceneValidationId, 23035 issues: [] 23036 }; 23037 } 23038 }); 23039 Object.keys(logic[logicContainerKey]).forEach((sceneItemLogic) => { 23040 if (sceneItemLogic !== sceneAnimationId && sceneItemLogic !== sceneValidationId && sceneItemLogic !== this.generateNextSceneId(logicContainerKey)) { 23041 let logicElement = logic[logicContainerKey][sceneItemLogic]; 23042 if (logicElement.outputType === LOGIC_TYPE.Prioritized) {
23043 logicElement.rules.forEach((candidate) => { 23044 let id = `${candidate.key}_${logicContainerKey}`; 23045 let singleCandidateLogicObject = { 23046 ...logicElement, 23047 rules: [candidate] 23048 }; 23049 allLogicObjects.push({ 23050 id, 23051 validate: (prevValidationResult, getValidationResultFunction) => { 23052 return this.doValidate(singleCandidateLogicObject, getValidationResultFunction, context, id); 23053 } 23054 }); 23055 }); 23056 allLogicObjects.push({ 23057 id: `${sceneItemLogic}_${logicContainerKey}`, 23058 validate: (prevValidationResult, getValidationResultFunction) => { 23059 return this.doValidate(logicElement, getValidationResultFunction, context, `${sceneItemLogic}_${logicContainerKey}`); 23060 } 23061 }); 23062 } else { 23063 let id = `${sceneItemLogic}_${logicContainerKey}`; 23064 allLogicObjects.push({ 23065 id, 23066 validate: (prevValidationResult, getValidationResultFunction) => { 23067 return this.doValidate(logicElement, getValidationResultFunction, context, id, false, logicContainerKey); 23068 } 23069 }); 23070 } 23071 } 23072 }); 23073 } 23074 }); 23075 return allLogicObjects; 23076 }; 23077 this.diffCollector = (previousContext, currentContext) => { 23078 let allLogicObjects = []; 23079 const { logic: currentLogic, allScenesIds: currentAllScenesIds, wireFrame: currentWireFrame, allDataElements: currentAllDataElements, useVideoRatioAndQualityLogic } = this.getDataFromContext(currentContext); 23080 const { logic: previousLogic, allScenesIds: previousAllScenesIds, wireFrame: previousWireFrame, allDataElements: previousAllDataElements } = this.getDataFromContext(previousContext); 23081 const previousAndCurrentSceneIds = Array.from(/* @__PURE__ */ new Set([...currentAllScenesIds, ...previousAllScenesIds])); 23082 Object.keys({ 23083 ...previousLogic, 23084 ...currentLogic 23085 }).forEach((logicContainerKey) => { 23086 if (logicContainerKey === LogicContainers.Derived) this.entityObjectsToMap(previousLogic.derived, currentLogic.derived).forEach((derivedPair, derivedId) => { 23087 const previousDerivedObj = findDataElementById(derivedId, previousAllDataElements) || findDataElementByName(derivedId, previousAllDataElements); 23088 const currentDerivedObj = findDataElementById(derivedId, currentAllDataElements) || findDataElementByName(derivedId, currentAllDataElements); 23089 allLogicObjects.push({ 23090 id: derivedId, 23091 diff: () => this.doDiff({ 23092 id: derivedId, 23093 name: "", 23094 previousLogic: DataElementEntity.normalizeDataElement(previousDerivedObj), 23095 currentLogic: DataElementEntity.normalizeDataElement(currentDerivedObj) 23096 }) 23097 }); 23098 }); 23099 else if (logicContainerKey === LogicContainers.Story) this.entityObjectsToMap(previousLogic.story, currentLogic.story).forEach((storiesPair, storyId) => { 23100 const previousStory = StateReaderUtils.getStoryById(previousWireFrame, storyId); 23101 const currentStory = StateReaderUtils.getStoryById(currentWireFrame, storyId); 23102 allLogicObjects.push({ 23103 id: storyId, 23104 diff: () => this.doDiff({ 23105 id: storyId, 23106 previousLogic: { 23107 ...previousStory, 23108 ...storiesPair.previousEntity 23109 }, 23110 currentLogic: { 23111 ...currentStory, 23112 ...storiesPair.currentEntity 23113 }, 23114 name: previousStory && previousStory.name || currentStory.name 23115 }) 23116 }); 23117 const dpID = getStoryPropertyCollectionId(storyId, LogicContainers.DecisionPoint); 23118 allLogicObjects.push({ 23119 id: dpID, 23120 diff: () => this.doDiff({ 23121 id: dpID, 23122 previousLogic: storiesPair.previousEntity ? storiesPair.previousEntity.decisionPoint : void 0,
23123 currentLogic: storiesPair.currentEntity ? storiesPair.currentEntity.decisionPoint : void 0, 23124 name: "Story logic" 23125 }) 23126 }); 23127 const soundtrackId = getStoryPropertyCollectionId(storyId, LogicContainers.Soundtrack); 23128 allLogicObjects.push({ 23129 id: soundtrackId, 23130 diff: () => this.doDiff({ 23131 id: soundtrackId, 23132 previousLogic: storiesPair.previousEntity && storiesPair.previousEntity.soundtrack ? storiesPair.previousEntity.soundtrack.audio : void 0, 23133 currentLogic: storiesPair.currentEntity && storiesPair.currentEntity.soundtrack ? storiesPair.currentEntity.soundtrack.audio : void 0, 23134 name: "Soundtrack" 23135 }) 23136 }); 23137 const backgroundId = getStoryPropertyCollectionId(storyId, LogicContainers.BackgroundAsset); 23138 allLogicObjects.push({ 23139 id: backgroundId, 23140 diff: () => this.doDiff({ 23141 id: backgroundId, 23142 previousLogic: storiesPair.previousEntity ? storiesPair.previousEntity.backgroundAsset : void 0, 23143 currentLogic: storiesPair.currentEntity ? storiesPair.currentEntity.backgroundAsset : void 0, 23144 name: "Background" 23145 }) 23146 }); 23147 if (useVideoRatioAndQualityLogic) { 23148 const storyVideoRatioQualityLogicValidationId = getStoryPropertyCollectionId(storyId, LogicEntity.VIDEO_RATIO_QUALITY_LOGIC_VALIDATION_ID); 23149 allLogicObjects.push({ 23150 id: storyVideoRatioQualityLogicValidationId, 23151 diff: () => this.doDiff({ 23152 id: storyVideoRatioQualityLogicValidationId, 23153 previousLogic: storiesPair.previousEntity?.[LogicContainers.VideoSettings]?.[LogicContext.StoryRatioAndQuality],
23154 currentLogic: storiesPair.currentEntity?.[LogicContainers.VideoSettings]?.[LogicContext.StoryRatioAndQuality], 23155 name: "Ratio and Quality logic" 23156 }) 23157 }); 23158 } 23159 }); 23160 else if (logicContainerKey === LogicContainers.Program) this.entityObjectsToMap(previousLogic[LogicContainers.Program], currentLogic[LogicContainers.Program]).forEach((programLogicTypedPair, programLogicType) => { 23161 let previousProgramLogic = StateReaderUtils.getAllProgramLogicItemsFromWireframeByType(previousWireFrame, programLogicType); 23162 let currentProgramLogic = StateReaderUtils.getAllProgramLogicItemsFromWireframeByType(currentWireFrame, programLogicType); 23163 let diffId = getProgramPropertyCollectionId(programLogicType); 23164 allLogicObjects.push({ 23165 id: diffId, 23166 diff: () => this.doDiff({ 23167 id: diffId, 23168 previousLogic: previousProgramLogic, 23169 currentLogic: currentProgramLogic, 23170 name: LogicEntity.convertTypeToName(programLogicType) 23171 }) 23172 }); 23173 }); 23174 else if (logicContainerKey === LogicContainers.Analytics) this.entityObjectsToMap(previousLogic.analytics, currentLogic.analytics).forEach((analyticsPair, analyticsFieldKey) => { 23175 const analyticsId = AnalyticsEntity.generateId(analyticsFieldKey); 23176 allLogicObjects.push({ 23177 id: analyticsId, 23178 diff: () => this.doDiff({ 23179 id: analyticsId, 23180 previousLogic: analyticsPair.previousEntity, 23181 currentLogic: analyticsPair.currentEntity, 23182 name: analyticsFieldKey 23183 }) 23184 }); 23185 }); 23186 else if (previousAndCurrentSceneIds.includes(logicContainerKey)) { 23187 let sceneAnimationId = ""; 23188 let sceneValidationId = ""; 23189 if (logicContainerKey !== LogicContainers.Master) { 23190 sceneAnimationId = SceneAnimationEntity.generateId(logicContainerKey); 23191 allLogicObjects.push({ 23192 id: sceneAnimationId, 23193 diff: () => this.doDiff({ 23194 id: sceneAnimationId, 23195 previousLogic: previousLogic[logicContainerKey] && previousLogic[logicContainerKey][sceneAnimationId], 23196 currentLogic: currentLogic[logicContainerKey] && currentLogic[logicContainerKey][sceneAnimationId], 23197 name: sceneAnimationId 23198 }) 23199 }); 23200 sceneValidationId = SceneValidationEntity.generateId(logicContainerKey); 23201 allLogicObjects.push({ 23202 id: sceneValidationId, 23203 diff: () => this.doDiff({ 23204 id: sceneValidationId, 23205 previousLogic: previousLogic[logicContainerKey] && previousLogic[logicContainerKey][sceneValidationId], 23206 currentLogic: currentLogic[logicContainerKey] && currentLogic[logicContainerKey][sceneValidationId], 23207 name: sceneValidationId 23208 }) 23209 }); 23210 } 23211 const previousPlaceholderLogic = { ...previousLogic[logicContainerKey] }; 23212 delete previousPlaceholderLogic[sceneAnimationId]; 23213 delete previousPlaceholderLogic[sceneValidationId]; 23214 const currentPlaceholderLogic = { ...currentLogic[logicContainerKey] }; 23215 delete currentPlaceholderLogic[sceneAnimationId]; 23216 delete currentPlaceholderLogic[sceneValidationId]; 23217 this.entityObjectsToMap(previousPlaceholderLogic, currentPlaceholderLogic).forEac
23217h((logicObjPair, logicId) => { 23218 const id = `${logicId}_${logicContainerKey}`; 23219 allLogicObjects.push({ 23220 id, 23221 diff: () => this.doDiff({ 23222 id, 23223 previousLogic: logicObjPair.previousEntity, 23224 currentLogic: logicObjPair.currentEntity, 23225 name: id 23226 }) 23227 }); 23228 }); 23229 } 23230 }); 23231 return allLogicObjects; 23232 }; 23233 this.doValidate = (logicObj, getValidationResult, context, id, isOptionalDefaultValueFlag, containingSceneId) => { 23234 let result = { 23235 type: this.getType(), 23236 id, 23237 issues: [] 23238 }; 23239 let dataElements = StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version); 23240 let stateProject = StateReaderUtils.getProject(context.state, context.projectName); 23241 let version = context.version || StateReaderUtils.getLatestSnapshotNumberForStage(context.state, context.projectName, context.stage); 23242 let assetsArr = StateReaderUtils.getAssetsFromSnapshotOrDraft(stateProject, context.state.assets, context.state.snapshots, void 0, version); 23243 let stories = StateReaderUtils.getProjectWireframesStories(context.state, context.projectName, context.stage, context.version); 23244 let scenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23245 let wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23246 let prioritizedLists = StateReaderUtils.getScenePrioritizedList(wireframes, containingSceneId); 23247 let validationObj = validateInputLogic(logicObj, { 23248 dataElements, 23249 assets: LogicEntity.buildAssetsForContext(assetsArr), 23250 stories, 23251 scenes, 23252 prioritizedLists, 23253 containingSceneId, 23254 getValidationResult, 23255 isOptionalDefaultValueFlag 23256 }); 23257 if (validationObj.status !== VALIDATION_STATUS.Valid) { 23258 let severity = validationObj.status === VALIDATION_STATUS.Invalid ? IssueSeverity.ERROR : IssueSeverity.WARNING; 23259 result.issues.push({ 23260 code: IssueCodes.INVALID_LOGIC, 23261 severity, 23262 details: { 23263 report: validationObj.report, 23264 message: validationObj.message 23265 } 23266 }); 23267 result.severity = severity; 23268 } 23269 return result; 23270 }; 23271 this.doDiff = ({ previousLogic, currentLogic, id, name }) => { 23272 return { 23273 type: this.getType(), 23274 id, 23275 name, 23276 changeType: diffEntities(this.normalizeLogicObject(previousLogic), this.normalizeLogicObject(currentLogic)), 23277 changes: [], 23278 isShown: false 23279 }; 23280 }; 23281 this.getDataFromContext = (context) => { 23282 const allScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23283 return { 23284 allScenesIds: allScenes && Object.keys(allScenes), 23285 logic: StateReaderUtils.getProjectWireframesLogic(context.state, context.projectName, context.stage, context.version), 23286 wireFrame: StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version), 23287 allDataElements: StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version), 23288 useVideoRatioAndQualityLogic: shouldUseVideoRatioAndQualityLogic(StateReaderUtils.getProjectType(context.state, context.projectName), StateReaderUtils.isFeatureEnable(context.state, CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC$1) ? [CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC$1] : []) 23289 }; 23290 }; 23291 this.normalizeLogicObject = (logicObject) => { 23292 if (!logicObject) return; 23293 if (logicObject.loading === true && Object.keys(logicObject).length === 1) return; 23294 if (logicObject !== Object(logicObject)) return logicObject; 23295 let normalizedObj = {}; 23296 Object.keys(logicObject).forEach((key) => { 23297 if (key !== "validation" && key !== "loading") if (Array.isArray(logicObject[ke
23297y])) logicObject[key].forEach((item, index) => { 23298 if (!normalizedObj[key]) normalizedObj[key] = []; 23299 normalizedObj[key][index] = this.normalizeLogicObject(item); 23300 }); 23301 else if (logicObject[key] && typeof logicObject[key] === "object") normalizedObj[key] = this.normalizeLogicObject(logicObject[key]); 23302 else normalizedObj[key] = logicObject[key]; 23303 }); 23304 return normalizedObj; 23305 }; 23306 this.generateNextSceneId = (logicContainerKey) => { 23307 return logicContainerKey + "_nextScene"; 23308 }; 23309 } 23310 static { 23311 this.STORY_SELECTION_LOGIC_ID = "ssl_id"; 23312 } 23313 static { 23314 this.VIDEO_RATIO_QUALITY_LOGIC_VALIDATION_ID = "ratio_quality_logic_validation_id"; 23315 } 23316 static { 23317 this.convertTypeToName = (programLogicType) => { 23318 switch (programLogicType) { 23319 case LogicContainers.StorySelection: return "Story Selection"; 23320 default: return programLogicType; 23321 } 23322 }; 23323 } 23324 static { 23325 this.buildAssetsForContext = index((assetsArr) => { 23326 return convertArrayOfObjectsToObjectWithKeys(assetsArr, ["name", "type"], (name, type) => `${type}/${name}`); 23327 }); 23328 } 23329}; 23330//#endregion 23331//#region client/logic/entities/narrationEntity.ts 23332var NarrationEntity = class extends BaseEntity { 23333 constructor() { 23334 super(EntityTypes.NARRATION); 23335 this.getEntityId = (narration) => AssetUtils.getCrossVersionId(narration.id); 23336 this.collector = (args) => { 23337 const { context, previousContext } = args; 23338 let narrations = []; 23339 const previousWireframe = previousContext && StateReaderUtils.getWireFrame(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23340 const currentWireframe = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23341 const narrationCDEsUsage = getCreativeDataElementsUsedInNarrationsOverrides(currentWireframe); 23342 const previousNarrationParts = StateReaderUtils.getProjectNarrationParts(previousWireframe); 23343 const currentNarrationParts = StateReaderUtils.getProjectNarrationParts(currentWireframe); 23344 if (StateReaderUtils.getNarrationsVersion(currentWireframe) > 0) this.entityListsToMap(previousNarrationParts, currentNarrationParts, this.getEntityId).forEach((narrationsPair, narrationId) => { 23345 const { currentEntity: currentNarrationPart, previousEntity: previousNarrationPart } = narrationsPair; 23346 const narrationName = this.getNarrationName(currentNarrationPart, previousNarrationPart, currentWireframe, previousWireframe); 23347 if (!previousContext) { 23348 if (currentNarrationPart.id) narrations.push({ 23349 id: narrationId, 23350 validate: (prevValidationResult, getValidationResultFunction) => { 23351 return this.doValidate(currentNarrationPart.id, narrationName, prevValidationResult, getValidationResultFunction, context, narrationCDEsUsage); 23352 } 23353 }); 23354 } else narrations.push({ 23355 id: narrationId, 23356 diff: () => { 23357 return this.doDiff({ 23358 currentNarrationPart, 23359 previousNarrationPart, 23360 currentWireframe, 23361 previousWireframe, 23362 narrationId, 23363 narrationName 23364 }); 23365 } 23366 }); 23367 }); 23368 return narrations; 23369 }; 23370 this.getNarrationName = (currentNarrationPart, previousNarrationPart, currentWireframe, previousWireframe) => { 23371 const wireframe = currentNarrationPart ? currentWireframe : previousWireframe; 23372 const narrationPart = currentNarrationPart ? currentNarrationPart : previousNarrationPart; 23373 return StateReaderUtils.getNarrationLetterInScene(wireframe.scenes[narrationPart.sceneId], narrationPart.id); 23374 }; 23375 this.doValidate = (narrationId, narrationName, prevValidationResult, getValidationResultFunction, context, narrationCDEsUsage) => { 23376 const type = this.getType(); 23377 let wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23378 if (wireframes.narrations) { 23379 let dimensions = StateReaderUtils.getNarrationTableDimensions(wireframes, narrationId); 23380 let variations = StateReaderUtils.getNarrationTableVariations(wireframes, narrationId); 23381 let dataElementIdsInUse = StateReaderUtils.getNarrationTableDataElements(wireframes, narrationId); 23382 let allDataElements = StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version); 23383 let invalidNarrationCreativeDataElementIds = getNarrationPartInvalidCreativeOverrides(narrationCDEsUsage, narrationId); 23384 if (prevValidationResult && prevValidationResult.dimensions === dimensions && prevValidationResult.variations === variations && prevValidationResult.dataElementIdsInUse === dataElementIdsInUse && prevValidationResult.invalidNarrationCreativeDataElementIds.join() === invali
23384dNarrationCreativeDataElementIds.join()) return prevValidationResult; 23385 let issues = this.detectIssues(narrationId, getValidationResultFunction, dimensions, variations, dataElementIdsInUse, allDataElements, invalidNarrationCreativeDataElementIds); 23386 return { 23387 type, 23388 id: narrationId, 23389 name: narrationName, 23390 issues, 23391 severity: ValidationManager.getHighestSeverity(issues.map((issue) => issue.severity)), 23392 dimensions, 23393 variations, 23394 dataElementIdsInUse, 23395 invalidNarrationCreativeDataElementIds 23396 }; 23397 } 23398 return { 23399 type, 23400 id: narrationId, 23401 issues: [], 23402 dimensions: null, 23403 variations: null, 23404 dataElementIdsInUse: null, 23405 invalidNarrationCreativeDataElementIds: [] 23406 }; 23407 }; 23408 this.detectIssues = (narrationId, getValidationResultFunction, dimensions, variations, dataElementIdsInUse, allDataElements, invalidNarrationCreativeDataElementIds) => { 23409 let issues = []; 23410 const orphanedCount = variations.count((variation) => variation.orphaned); 23411 const orphanedDimensions = dimensions.filter((dimension) => dimension.orphaned); 23412 const emptyLineCount = variations.count((variation) => !variation.variationData.muted && !variation.variationData.text && !variation.variationData.overrideId); 23413 if (orphanedDimensions.size > 0) issues.push({ 23414 code: IssueCodes.NARRATION_ORPHANED_DIMENSIONS, 23415 severity: IssueSeverity.ERROR, 23416 details: { 23417 id: narrationId, 23418 orphanedDimensions 23419 } 23420 }); 23421 if (orphanedCount > 0) issues.push({ 23422 code: IssueCodes.NARRATION_ORPHANED_VARIATIONS, 23423 severity: IssueSeverity.ERROR, 23424 details: { 23425 id: narrationId, 23426 orphanedCount 23427 } 23428 }); 23429 if (emptyLineCount > 0) issues.push({ 23430 code: IssueCodes.NARRATION_EMPTY_LINES, 23431 severity: IssueSeverity.WARNING, 23432 details: { 23433 id: narrationId, 23434 emptyLineCount 23435 } 23436 }); 23437 if (invalidNarrationCreativeDataElementIds && invalidNarrationCreativeDataElementIds.length > 0) issues.push({ 23438 code: IssueCodes.NARRATION_CREATIVE_OVERRIDE_ERROR, 23439 severity: IssueSeverity.ERROR, 23440 details: { 23441 id: narrationId, 23442 deIds: invalidNarrationCreativeDataElementIds 23443 } 23444 }); 23445 if (dataElementIdsInUse.size > 0) { 23446 dataElementIdsInUse = dataElementIdsInUse.toArray(); 23447 let dataElementObjInUse = allDataElements.filter((de) => de.origin === DATA_ELEMENT_ORIGIN.FEED && dataElementIdsInUse.some((deID) => de.id === deID)); 23448 let pendingDataElementObjInUse = dataElementObjInUse.filter((de) => de.status === DATA_ELEMENT_STATUS.MISSING || de.status === DATA_ELEMENT_STATUS.PENDING); 23449 let derivedDataElementObjInUse = allDataElements.filter((de) => de.origin === DATA_ELEMENT_ORIGIN.DERIVED && dataElementIdsInUse.some((deID) => de.id === deID)); 23450 const getDependencyId = (dataElement) => dataElement.id; 23451 let dataElementIssue = this.getDependenciesIssue(dataElementObjInUse, EntityTypes.DATA_ELEMENT, getDependencyId, getValidationResultFunction, IssueCodes.NARRATION_DATA_ELEMENTS_ERROR); 23452 let derivedDataElementIssue = this.getDependenciesIssue(derivedDataElementObjInUse, EntityTypes.DERIVED_DATA_ELEMENT, getDependencyId, getValidationResultFunction, IssueCodes.NARRATION_DERIVED_DATA_ELEMENTS_ERROR); 23453 if (dataElementIssue) { 23454 dataElementIssue.details = { names: dataElementIssue.children.map((childIssue) => allDataElements.find((de) => childIssue.id === de.id).displayName) }; 23455 issues.push(dataElementIssue); 23456 } 23457 if (derivedDataElementIssue) { 23458 derivedDataElementIssue.details = { names: derivedDataElementIssue.children.map((childIssue) => allDataElements.find((de) => childIssue.id === de.id).displayName) }; 23459 issues.push(derivedDataElementIssue); 23460 } 23461 if (pendingDataElementObjInUse && pendingDataElementObjInUse.length > 0) { 23462 let names = pendingDataElementObjInUse.map((deInUse) => deInUse.displayName); 23463 issues.push({ 23464 code: IssueCodes.NARRATION_DATA_ELEMENTS_ERROR, 23465 severity: IssueSeverity.WARNING, 23466 details: { names } 23467 }); 23468 } 23469 } 23470 return issues; 23471 }; 23472 this.doDiff = ({ currentNarrationPart, previousNarrationPart, currentWireframe, previousWireframe, narrationId, narrationName }) => { 23473 let changeType; 23474 if (!previousNarrationPart && currentNarrationPart) changeType = ChangeType.Add; 23475 else if (previousNarrationPart && !currentNarrationPart) changeType = ChangeType.Delete; 23476 else changeType = this.compareNarrationsData(currentNarrationPart, previousNarrationPart, currentWireframe, previousWireframe); 23477 return { 23478 id: narrationId, 23479 name: narrationName, 23480 type: this.getType(), 23481 changeType, 23482 changes: [], 23483 isShown: changeType !== ChangeType.None 23484 }; 23485 }; 23486 this.compareNarrationsData = (currentNarrationPart, previousNarrationPart, currentWireframe, previousWireframe) => { 23487 const previousNarrationPartDimensions = StateReaderUtils.getNarrationTableDimensions(previousWireframe, previousNarrationPart.id); 23488 const currentNarrationPartDimensions = StateReaderUtils.getNarrationTableDimensions(currentWireframe, currentNarrationPart.id); 23489 if (diffEntities(previousNarrationPartDimensions.toJS(), currentNarrationPartDimensions.toJS()) === ChangeType.Edit) return ChangeType.Edit; 23490 const previousNarrationPartVariations = StateReaderUtils.getNarrationTableVariations(previousWireframe, previousNarrationPart.id); 23491 const currentNarrationPartVariations = StateReaderUtils.getNarrationTableVariations(currentWireframe, currentNarrationPart.id); 23492 return diffEntities(previousNarrationPartVariations.toJS(), currentNarrationPartVariations.toJS()); 23493 }; 23494 } 23495}; 23496//#endregion 23497//#region client/logic/entities/parameterEntity.ts 23498var ParameterEntity = class ParameterEntity extends BaseEntity { 23499 constructor() { 23500 super(EntityTypes.PARAMETER); 23501 this.collector = (args) => { 23502 const { context, previousContext } = args; 23503 let parameters = []; 23504 const previousScenes = previousContext && StateReaderUtils.getProjectWireframeScenes(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23505 const currentScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23506 const previousParameters = ParameterEntity.getParametersFromScenes(previousScenes); 23507 const currentParameters = ParameterEntity.getParametersFromScenes(currentScenes); 23508 const idFunc = (param) => ParameterEntity.generateId(param.name, param.sceneId); 23509 this.entityListsToMap(previousParameters, currentParameters, idFunc).forEac
23509h((parametersPair, paramId) => { 23510 const { currentEntity: currentParameter, previousEntity: previousParameter } = parametersPair; 23511 parameters.push({ 23512 id: paramId, 23513 validate: (prevValidationResult, getValidationResultFunction) => { 23514 return this.doValidate(currentParameter.name, currentParameter.sceneId, getValidationResultFunction, context); 23515 }, 23516 diff: (getDiffResult) => { 23517 return this.doDiff(getDiffResult, currentParameter, previousParameter); 23518 } 23519 }); 23520 }); 23521 return parameters; 23522 }; 23523 this.doValidate = (parameterName, sceneId, getValidationResult, context) => { 23524 const type = this.getType(); 23525 const id = ParameterEntity.generateId(parameterName, sceneId); 23526 let result = { 23527 type, 23528 id, 23529 issues: [], 23530 name: parameterName 23531 }; 23532 let wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23533 let sceneLogic = StateReaderUtils.getAllProgramLogicFromWireframes(wireframes, sceneId); 23534 if (sceneLogic && sceneLogic[parameterName]) { 23535 const getDependencyId = () => id; 23536 let issue = this.getDependenciesIssue([void 0], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.PARAMETER_LOGIC_ERROR); 23537 if (issue) { 23538 result.issues.push(issue); 23539 result.severity = issue.severity; 23540 } 23541 } else { 23542 result.issues.push({ 23543 code: IssueCodes.PARAMETER_LOGIC_MISSING, 23544 severity: IssueSeverity.WARNING, 23545 details: {} 23546 }); 23547 result.severity = IssueSeverity.WARNING; 23548 } 23549 return result; 23550 }; 23551 this.doDiff = (getDiffResult, currParameter, prevParameter) => { 23552 const paramName = currParameter && currParameter.name || prevParameter && prevParameter.name || void 0; 23553 const paramScenId = currParameter && currParameter.sceneId || prevParameter && prevParameter.sceneId || void 0; 23554 const id = ParameterEntity.generateId(paramName, paramScenId); 23555 let result = { 23556 type: this.getType(), 23557 id, 23558 name: paramName, 23559 changeType: ChangeType.None, 23560 changes: [], 23561 isShown: false 23562 }; 23563 const getDependencyId = (id) => id; 23564 return updateDiffResultWithChanges(result, this.getDependenciesDiff([id], EntityTypes.LOGIC, getDependencyId, getDiffResult, true)); 23565 }; 23566 } 23567 static { 23568 this.generateId = (parameterName, sceneId) => { 23569 return parameterName + "_" + sceneId; 23570 }; 23571 } 23572 static { 23573 this.getParametersFromScenes = (scenes) => { 23574 let parameters = []; 23575 if (scenes) Object.keys(scenes).forEach((sceneId) => { 23576 scenes[sceneId].sceneParts && scenes[sceneId].sceneParts.forEach((scenePart) => { 23577 scenePart.parameters && parameters.push(...scenePart.parameters.map((param) => ({ 23578 sceneId, 23579 ...param 23580 }))); 23581 }); 23582 }); 23583 return parameters; 23584 }; 23585 } 23586}; 23587//#endregion 23588//#region client/logic/entities/placeholderEntity.ts 23589var PlaceholderEntity = class PlaceholderEntity extends BaseEntity { 23590 constructor() { 23591 super(EntityTypes.PLACEHOLDER); 23592 this.collector = (args) => { 23593 const { context, previousContext } = args; 23594 let placeholders = []; 23595 const previousScenes = previousContext && StateReaderUtils.getProjectWireframeScenes(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23596 const currentScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23597 const previousPlaceholders = PlaceholderEntity.getScenePlaceholders(previousScenes); 23598 const currentPlaceholders = PlaceholderEntity.getScenePlaceholders(currentScenes); 23599 const idFunc = (ph) => PlaceholderEntity.generateId(ph.name, ph.sceneId); 23600 this.entityListsToMap(previousPlaceholders, currentPlaceholders, idFunc).forEach((placeholdersPair, phId) => { 23601 const { currentEntity: currentPlaceholder, previousEntity: previousPlaceholder } = placeholdersPair; 23602 placeholders.push({ 23603 id: phId, 23604 validate: (prevValidationResult, getValidationResultFunction) => { 23605 return this.doValidate(currentPlaceholder.name, currentPlaceholder.sceneId, getValidationResultFunction, context); 23606 }, 23607 diff: (getDiffResult) => { 23608 return this.doDiff(getDiffResult, currentPlaceholder, previousPlaceholder, phId); 23609 } 23610 }); 23611 }); 23612 return placeholders; 23613 }; 23614 this.doValidate = (placeholderName, sceneId, getValidationResult, context) => { 23615 const type = this.getType(); 23616 const id = PlaceholderEntity.generateId(placeholderName, sceneId); 23617 let result = { 23618 type, 23619 id, 23620 issues: [], 23621 name: placeholderName 23622 }; 23623 let wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23624 let sceneLogic = StateReaderUtils.getAllProgramLogicFromWireframes(wireframes, sceneId); 23625 if (sceneLogic && sceneLogic[placeholderName]) { 23626 const getDependencyId = () => id; 23627 let issue = this.getDependenciesIssue([void 0], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.PLACEHOLDER_LOGIC_ERROR); 23628 if (issue) { 23629 result.issues.push(issue); 23630 result.severity = issue.severity; 23631 } 23632 } else { 23633 result.issues.push({ 23634 code: IssueCodes.PLACEHOLDER_LOGIC_MISSING, 23635 severity: IssueSeverity.WARNING, 23636 details: {} 23637 }); 23638 result.severity = IssueSeverity.WARNING; 23639 } 23640 return result; 23641 }; 23642 this.doDiff = (getDiffResult, currPlaceholder, prevPlaceholder, phId) => { 23643 const phName = currPlaceholder && currPlaceholder.name || prevPlaceholder.name; 23644 let result = { 23645 type: this.getType(), 23646 id: phId, 23647 name: phName, 23648 changeType: ChangeType.None, 23649 changes: [], 23650 isShown: false 23651 }; 23652 if (!prevPlaceholder && currPlaceholder) { 23653 result.changeType = ChangeType.Add; 23654 result.isShown = true; 23655 return result; 23656 } 23657 if (!currPlaceholder && prevPlaceholder) { 23658 result.changeType = ChangeType.Delete; 23659 result.isShown = true; 23660 return result; 23661 } 23662 const getDependencyId = (id) => id; 23663 return updateDiffResultWithChanges(result, this.getDependenciesDiff([phId], EntityTypes.LOGIC, getDependencyId, getDiffResult, true)); 23664 }; 23665 } 23666 static { 23667 this.generateId = (placeholderName, sceneId) => { 23668 return placeholderName + "_" + sceneId; 23669 }; 23670 } 23671 static {
23672 this.getScenePlaceholders = (scenes) => { 23673 let placeholders = []; 23674 if (scenes) Object.keys(scenes).forEach((sceneId) => { 23675 scenes[sceneId].sceneParts && scenes[sceneId].sceneParts.forEach((scenePart) => { 23676 scenePart.placeholders && placeholders.push(...scenePart.placeholders.map((ph) => ({ 23677 sceneId, 23678 ...ph 23679 }))); 23680 }); 23681 }); 23682 return placeholders; 23683 }; 23684 } 23685}; 23686//#endregion 23687//#region client/logic/entities/prioritizedListCandidateEntity.ts 23688var PrioritizedListCandidateEntity = class extends BaseEntity { 23689 constructor() { 23690 super(EntityTypes.PRIORITIZED_LIST_CANDIDATE); 23691 this.collector = (args) => { 23692 const { context, previousContext } = args; 23693 let prioritizedListsCandidates = []; 23694 const wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23695 const scenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23696 if (scenes) Object.keys(scenes).forEach((sceneId) => { 23697 StateReaderUtils.getScenePrioritizedList(wireframes, sceneId).forEach((prioritizedList) => {
23698 prioritizedList.rules.forEach((prioritizedListCandidate) => { 23699 prioritizedListsCandidates.push({ 23700 id: `${prioritizedListCandidate.key}_${sceneId}`, 23701 validate: (prevValidationResult, getValidationResultFunction) => { 23702 return this.doValidate(prioritizedListCandidate, getValidationResultFunction, prioritizedList, sceneId); 23703 } 23704 }); 23705 }); 23706 }); 23707 }); 23708 return prioritizedListsCandidates; 23709 }; 23710 this.doValidate = (prioritizedListCandidate, getValidationResult, prioritizedList, sceneId) => { 23711 let result = { 23712 type: this.getType(), 23713 id: prioritizedListCandidate.key, 23714 issues: [] 23715 }; 23716 const name = prioritizedListCandidate.name; 23717 if (!name || !HubEditorUtils.isAlphaNumeric(name)) { 23718 result.issues.push({ 23719 code: name ? IssueCodes.PRIORITIZED_LIST_INVALID_CANDIDATE_NAME : IssueCodes.PRIORITIZED_LIST_EMPTY_CANDIDATE_NAME, 23720 severity: IssueSeverity.ERROR, 23721 details: {} 23722 }); 23723 result.severity = IssueSeverity.ERROR; 23724 } 23725 if (prioritizedList.rules.filter((candidate) => candidate.name === name).length > 1) { 23726 result.issues.push({ 23727 code: IssueCodes.PRIORITIZED_LIST_DUPLICATE_CANDIDATE_NAME, 23728 severity: IssueSeverity.ERROR, 23729 details: {} 23730 }); 23731 result.severity = IssueSeverity.ERROR; 23732 } 23733 if (prioritizedListCandidate.key) { 23734 const getDependencyId = (prioritizedListCandidate) => `${prioritizedListCandidate.key}_${sceneId}`; 23735 let issue = this.getDependenciesIssue([prioritizedListCandidate], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.PRIORITIZED_LIST_LOGIC_ERROR); 23736 if (issue) { 23737 result.issues.push(issue); 23738 result.severity = ValidationManager.getHighestSeverity([result.severity, issue.severity]); 23739 } 23740 } 23741 return result; 23742 }; 23743 } 23744}; 23745//#endregion 23746//#region client/logic/entities/animationEntity.ts 23747var AnimationEntity = class extends AssetEntity { 23748 constructor() { 23749 super(EntityTypes.ANIMATION, ASSET_TYPES.animation); 23750 } 23751}; 23752//#endregion 23753//#region client/logic/entities/recordingEntity.ts 23754var RecordingEntity = class extends AssetEntity { 23755 constructor() { 23756 super(EntityTypes.RECORDING, ASSET_TYPES.recording); 23757 this.getAssetId = (asset) => AssetUtils.getCrossVersionId(asset.name); 23758 this.doValidate = ({ asset }) => { 23759 const recording = asset; 23760 let recordingValidationResult = { 23761 type: this.getType(), 23762 id: recording.name, 23763 issues: [] 23764 }; 23765 if (recording.status === "request") { 23766 const issue = { 23767 code: IssueCodes.RECORDING_IS_PENDING, 23768 severity: IssueSeverity.WARNING, 23769 details: {} 23770 }; 23771 recordingValidationResult.issues.push(issue); 23772 recordingValidationResult.severity = issue.severity; 23773 } 23774 return recordingValidationResult; 23775 }; 23776 this.doDiff = ({ id, previousAsset, currentAsset, versionView, previousProjectRFR, currentProjectR
23776FR }) => { 23777 const normalizedPreviousAsset = this.normalizeRecordingAsset(previousAsset, previousProjectRFR, true); 23778 const normalizedCurrentAsset = this.normalizeRecordingAsset(currentAsset, currentProjectRFR, versionView); 23779 let changeType; 23780 if (normalizedPreviousAsset && normalizedPreviousAsset.calculatedInUse === false && normalizedCurrentAsset && normalizedCurrentAsset.calculatedInUse === true) changeType = ChangeType.Add; 23781 else if (normalizedPreviousAsset && normalizedPreviousAsset.calculatedInUse === true && normalizedCurrentAsset && normalizedCurrentAsset.calculatedInUse === false) changeType = ChangeType.Delete; 23782 else if (!normalizedPreviousAsset && normalizedCurrentAsset && normalizedCurrentAsset.calculatedInUse === false) changeType = ChangeType.None; 23783 else changeType = diffEntities(normalizedPreviousAsset, normalizedCurrentAsset); 23784 return { 23785 type: this.getType(), 23786 id, 23787 name: this.getPropsFromPreviousOrCurrent(normalizedPreviousAsset, normalizedCurrentAsset, "name"), 23788 changeType, 23789 changes: [], 23790 isShown: changeType !== ChangeType.None 23791 }; 23792 }; 23793 this.normalizeRecordingAsset = (recordingAsset, projectRFR, versionView) => { 23794 if (!recordingAsset) return; 23795 return { 23796 name: recordingAsset.filename, 23797 activeVersion: AssetUtils.getVersion(recordingAsset, versionView), 23798 location: AssetUtils.getLocation(recordingAsset, versionView), 23799 recordingStatus: recordingAsset.recordingStatus, 23800 calculatedInUse: recordingAsset.RFR >= projectRFR 23801 }; 23802 }; 23803 } 23804}; 23805//#endregion 23806//#region client/logic/entities/mediaEntity.ts 23807var MediaEntity = class extends AssetEntity { 23808 constructor() { 23809 super(EntityTypes.MEDIA, ASSET_TYPES.curated); 23810 } 23811}; 23812//#endregion 23813//#region client/logic/entities/programEntity.ts 23814var { STORY_LOGIC: STORY_LOGIC$1 } = featureFlagConst; 23815var ProgramEntity = class extends BaseEntity { 23816 constructor() { 23817 super(EntityTypes.PROGRAM); 23818 this.collector = (args) => { 23819 const { context, previousContext } = args; 23820 let programs = []; 23821 const project = StateReaderUtils.getProject(context.state, context.projectName); 23822 if (project) programs.push({ 23823 id: project.projectName, 23824 validate: (prevValidationResult, getValidationResultFunction) => { 23825 return this.doValidate(project, getValidationResultFunction, context); 23826 }, 23827 diff: (getDiffResult) => this.doDiff(getDiffResult, project.projectName, previousContext, context) 23828 }); 23829 return programs; 23830 }; 23831 this.doValidate = (project, getValidationResult, context) => { 23832 let programValidationResult = { 23833 type: this.getType(), 23834 id: project.projectName, 23835 issues: [] 23836 }; 23837 if (!project.programId) { 23838 const sfIdIssue = { 23839 code: IssueCodes.PROGRAM_SETTINGS_ERROR, 23840 severity: IssueSeverity.ERROR, 23841 details: "" 23842 }; 23843 programValidationResult.issues.push(sfIdIssue); 23844 programValidationResult.severity = ValidationManager.getHighestSeverity([programValidationResult.severity, sfIdIssue.severity]); 23845 } 23846 let allScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23847 if (allScenes) { 23848 const getSceneDependencyId = (scene) => scene.id; 23849 let sceneIssue = this.getDependenciesIssue(Object.values(allScenes), EntityTypes.SCENE, getSceneDependencyId, getValidationResult, IssueCodes.PROGRAM_SCENES_ERROR); 23850 if (sceneIssue) { 23851 programValidationResult.issues.push(sceneIssue); 23852 programValidationResult.severity = ValidationManager.getHighestSeverity([programValidationResult.severity, sceneIssue.severity]); 23853 } 23854 } 23855 let allStories = StateReaderUtils.getProjectWireframesStories(context.state, context.projectName, context.stage, context.version); 23856 if (allStories) { 23857 const getStoryDependencyId = (story) => story.id; 23858 let storyIssue = this.getDependenciesIssue(Object.values(allStories), EntityTypes.STORY, getStoryDependencyId, getValidationResult, IssueCodes.PROGRAM_STORY_ERROR); 23859 if (storyIssue) { 23860 programValidationResult.issues.push(storyIssue); 23861 programValidationResult.severity = ValidationManager.getHighestSeverity([programValidationResult.severity, storyIssue.severity]); 23862 } 23863 } 23864 const storySelectionLogic = StateReaderUtils.getProgramStorySelectionLogic(context.state, context.projectName, context.stage, context.version); 23865 if (storySelectionLogic) { 23866 const getSSLDependencyId = () => LogicEntity.STORY_SELECTION_LOGIC_ID; 23867 let storyIssue = this.getDependenciesIssue([storySelectionLogic
23867], EntityTypes.LOGIC, getSSLDependencyId, getValidationResult, IssueCodes.PROGRAM_STORY_SELECTION_LOGIC_ERROR); 23868 if (storyIssue) { 23869 programValidationResult.issues.push(storyIssue); 23870 programValidationResult.severity = ValidationManager.getHighestSeverity([programValidationResult.severity, storyIssue.severity]); 23871 } 23872 } else if (StateReaderUtils.isFeatureEnable(context.state, STORY_LOGIC$1)) { 23873 let noLogicIssue = { 23874 code: IssueCodes.PROGRAM_STORY_SELECTION_LOGIC_ERROR, 23875 severity: IssueSeverity.ERROR, 23876 details: "" 23877 }; 23878 programValidationResult.issues.push(noLogicIssue); 23879 programValidationResult.severity = ValidationManager.getHighestSeverity([programValidationResult.severity, noLogicIssue.severity]); 23880 } 23881 const wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 23882 const analyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(wireframes); 23883 if (analyticsFieldsArray) { 23884 const getAnalyticsDependencyId = (analyticsFieldKey) => AnalyticsEntity.generateId(analyticsFieldKey); 23885 let storyIssue = this.getDependenciesIssue(analyticsFieldsArray, EntityTypes.ANALYTICS, getAnalyticsDependencyId, getValidationResult, IssueCodes.PROGRAM_ANALYTICS_ERROR); 23886 if (storyIssue) { 23887 programValidationResult.issues.push(storyIssue); 23888 programValidationResult.severity = ValidationManager.getHighestSeverity([programValidationResult.severity, storyIssue.severity]); 23889 } 23890 } 23891 return programValidationResult; 23892 }; 23893 this.doDiff = (getDiffResult, id, previousContext, currentContext) => { 23894 let result = { 23895 type: this.getType(), 23896 id, 23897 name: id, 23898 changeType: ChangeType.None, 23899 changes: [], 23900 isShown: false 23901 }; 23902 const previousProject = previousContext && StateReaderUtils.getProject(previousContext.state, previousContext.projectName); 23903 const currentProject = StateReaderUtils.getProject(currentContext.state, currentContext.projectName); 23904 const previousStories = StateReaderUtils.getProjectWireframesStories(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23905 const currentStories = StateReaderUtils.getProjectWireframesStories(currentContext.state, currentContext.projectName, currentContext.stage, currentContext.version); 23906 const storyIds = Array.from(/* @__PURE__ */ new Set([...Object.keys(previousStories), ...Object.keys(currentStories)])); 23907 updateDiffResultWithChanges(result, this.getDependenciesDiff(storyIds, EntityTypes.STORY, (id) => id, getDiffResult)); 23908 const previousScenes = StateReaderUtils.getProjectWireframeScenes(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23909 const currentScenes = StateReaderUtils.getProjectWireframeScenes(currentContext.state, currentContext.projectName, currentContext.stage, currentContext.version); 23910 const sceneIds = Array.from(/* @__PURE__ */ new Set([...Object.keys(previousScenes), ...Object.keys(currentScenes)])); 23911 updateDiffResultWithChanges(result, this.getDependenciesDiff(sceneIds, EntityTypes.SCENE, (id) => id, getDiffResult)); 23912 const storySelectionLogicId = getProgramPropertyCollectionId(LogicContainers.StorySelection); 23913 const SSLChange = this.getDependenciesDiff([storySelectionLogicId], EntityTypes.LOGIC, (id) => id, getDiffResult, true); 23914 if (SSLChange) SSLChange.children[0].isShown = SSLChange.changeType !== ChangeType.None; 23915 updateDiffResultWithChanges(result, SSLChange); 23916 const previousAllDataElements = StateReaderUtils.getProjectDataElements(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23917 const currentAllDataElements = StateReaderUtils.getProjectDataElements(currentContext.state, currentContext.projectName, currentContext.stage, currentContext.version); 23918 const previousDataElements = previousAllDataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Feed); 23919 const currentDataElements = currentAllDataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Feed); 23920 const dataElementIds = Array.from(/* @__PURE__ */ new Set([...previousDataElements.map((de) => de.id), ...currentDataElements.map((de) => de.id)])); 23921 updateDiffResultWithChanges(result, this.getDependenciesDiff(dataElementIds, EntityTypes.DATA_ELEMENT, (id) => id, getDiffResult)); 23922 const previousCreativeDataElements = previousAllDataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Creative); 23923 const currentCreativeDataElements = currentAllDataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Creative); 23924 const creativeDataElementIds = Array.from(/* @__PURE__ */ new Set([...previousCreativeDataElements.map((de) => de.id), ...currentCreativeDataElements.map((de) => de.id)])); 23925 updateDiffResultWithChanges(result, this.getDependenciesDiff(creativeDataElementIds, EntityTypes.DATA_ELEMENT, (id) => id, getDiffResult)); 23926 const previousStudioDataElements = previousAllDataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Derived); 23927 const currentStudioDataElements = currentAllDataElements.filter((dataElement) => dataElement.origin === DataElementOrigins.Derived); 23928 const studioDataElementIds = Array.from(/* @__PURE__ */ new Set([...previousStudioDataElements.map((de) => de.id), ...currentStudioDataElements.map((de) => de.id)])); 23929 updateDiffResultWithChanges(result, this.getDependenciesDiff(studioDataElementIds, EntityTypes.DERIVED_DATA_ELEMENT, (id) => id, getDiffResult)); 23930 const assetsDoDiffParams = { 23931 previousProject, 23932 currentProject, 23933 previousContext, 23934 currentContext, 23935 assetType: void 0, 23936 entity: void 0, 23937 getDiffResult, 23938 result 23939 }; 23940 this.assetsDoDiff({ 23941 ...assetsDoDiffParams, 23942 assetType: ASSET_TYPES.mappingTable, 23943 entity: new DataTableEntity() 23944 }); 23945 this.assetsDoDiff({ 23946 ...assetsDoDiffParams, 23947 assetType: ASSET_TYPES.curated, 23948 entity: new MediaEntity() 23949 }); 23950 this.assetsDoDiff({ 23951 ...assetsDoDiffParams, 23952 assetType: ASSET_TYPES.animation, 23953 entity: new AnimationEntity() 23954 }); 23955 this.assetsDoDiff({ 23956 ...assetsDoDiffParams, 23957 assetType: ASSET_TYPES.recording, 23958 entity: new RecordingEntity() 23959 }); 23960 const previousWireframes = StateReaderUtils.getWireFrame(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 23961 const currentWireframes = StateReaderUtils.getWireFrame(currentContext.state, currentContext.projectName, currentContext.stage, currentContext.version); 23962 const previousAnalyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(previousWireframes) || []; 23963 const currentAnalyticsFieldsArray = StateReaderUtils.getCustomAnalyticsFieldsArray(currentWireframes) || []; 23964 const analyticsFieldKeys = Array.from(/* @__PURE__ */ new Set([...previousAnalyticsFieldsArray, ...currentAnalyticsFieldsArray])); 23965 const getAnalyticsDependencyId = (analyticsFieldKey) => AnalyticsEntity.generateId(analyticsFieldKey); 23966 updateDiffResultWithChanges(result, this.getDependenciesDiff(analyticsFieldKeys, EntityTypes.ANALYTICS, getAnalyticsDependencyId, getDiffResult)); 23967 return result; 23968 }; 23969 this.assetsDoDiff = ({ previousProject, currentProject, previousContext, currentContext, entity, assetType, getDiffResult, result }) => { 23970 const previousAssets = StateReaderUtils.getAssetsInVersionMode(previousProject, previousContext.state.assets, previousContext.state.snapshots, previousContext.version, assetType); 23971 const currentAssets = StateReaderUtils.getAssetsFromSnapshotOrDraft(currentProject, currentContext.state.assets, currentContext.state.snapshots, void 0, currentContext.version, assetType); 23972 const assetIds = Array.from(/* @__PURE__ */ new Set([...previousAssets.map(entity.getAssetId), ...currentAssets.map(entity.getAssetId)])); 23973 updateDiffResultWithChanges(result, this.getDependenciesDiff(assetIds, entity.getType(), (id) => id, getDiffResult)); 23974 }; 23975 } 23976}; 23977//#endregion 23978//#region client/logic/entities/sceneEntity.ts 23979var SceneEntity = class extends BaseEntity { 23980 constructor() { 23981 super(EntityTypes.SCENE); 23982 this.collector = (args) => { 23983 const { context, previousContext } = args; 23984 let scenes = []; 23985 let allPreviousScenes = previousContext && StateReaderUtils.getProjectWireframeScenes(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version) || {}; 23986 let allCurrentScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 23987 this.entityObjectsToMap(allPreviousScenes, allCurrentScenes).forEac
23987h((scenesPair, sceneId) => { 23988 scenes.push({ 23989 id: sceneId, 23990 validate: (prevValidationResult, getValidationResultFunction) => { 23991 return this.doValidate(scenesPair.currentEntity, getValidationResultFunction); 23992 }, 23993 diff: (getDiffResult) => this.doDiff(getDiffResult, scenesPair.previousEntity, scenesPair.currentEntity, sceneId) 23994 }); 23995 }); 23996 return scenes; 23997 }; 23998 this.doValidate = (scene, getValidationResult) => { 23999 const type = this.getType(); 24000 const id = scene.id; 24001 let sceneValidationResult = { 24002 type, 24003 id, 24004 issues: [], 24005 name: scene.name 24006 }; 24007 if (id !== LogicContainers.Master) { 24008 const sceneValidationLogicId = `${scene.id}_validation`; 24009 const getValidationDependencyId = () => sceneValidationLogicId; 24010 let validationIssue = this.getDependenciesIssue([void 0], EntityTypes.SCENE_VALIDATION, getValidationDependencyId, getValidationResult, IssueCodes.SCENE_VALIDATION_LOGIC_ERROR); 24011 if (validationIssue) { 24012 sceneValidationResult.issues.push(validationIssue); 24013 sceneValidationResult.severity = validationIssue.severity; 24014 } 24015 const sceneAnimationLogicId = `${scene.id}_animation`; 24016 const getAnimationDependencyId = () => sceneAnimationLogicId; 24017 let animationIssue = this.getDependenciesIssue([void 0], EntityTypes.SCENE_ANIMATION, getAnimationDependencyId, getValidationResult, IssueCodes.SCENE_ANIMATION_LOGIC_ERROR); 24018 if (animationIssue) { 24019 sceneValidationResult.issues.push(animationIssue); 24020 sceneValidationResult.severity = animationIssue.severity; 24021 } 24022 } 24023 if (scene.sceneParts) { 24024 const getDependencyId = (dependency) => `${scene.id}_${dependency.scenePart}`; 24025 let issue = this.getDependenciesIssue(scene.sceneParts, EntityTypes.SCENE_PART, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_ERROR); 24026 if (issue) { 24027 sceneValidationResult.issues.push(issue); 24028 sceneValidationResult.severity = issue.severity; 24029 } 24030 } 24031 return sceneValidationResult; 24032 }; 24033 this.doDiff = (getDiffResult, previousScene, currentScene, id) => { 24034 const name = currentScene && currentScene.name || previousScene.name; 24035 let result = { 24036 type: this.getType(), 24037 id, 24038 name, 24039 changeType: ChangeType.None, 24040 changes: [], 24041 isShown: false 24042 }; 24043 if (id === LogicContainers.Master) { 24044 const logicIds = this.collectLogicIdsFromMaster(previousScene, currentScene); 24045 const getLogicDependencyId = (id) => `${id}_${LogicContainers.Master}`; 24046 const diff = this.getDependenciesDiff(logicIds, EntityTypes.LOGIC, getLogicDependencyId, getDiffResult, false); 24047 if (diff) { 24048 result.changeType = diff.changeType; 24049 result.changes.push(diff); 24050 } 24051 } else { 24052 let changeList = []; 24053 result.changeType = diffEntities(previousScene && { 24054 ...previousScene, 24055 sceneParts: void 0 24056 }, currentScene && { 24057 ...currentScene, 24058 sceneParts: void 0 24059 }); 24060 if (result.changeType === ChangeType.Add || result.changeType === ChangeType.Delete) result.isShown = true; 24061 else { 24062 const getValidationDependencyId = (id) => SceneValidationEntity.generateId(id); 24063 const sceneValidationDiff = this.getDependenciesDiff([id], EntityTypes.LOGIC, getValidationDependencyId, getDiffResult, true); 24064 if (sceneValidationDiff) { 24065 sceneValidationDiff.children[0] = exposeDiffResult(sceneValidationDiff.children[0], "Scene Validation", null); 24066 changeList.push(sceneValidationDiff.changeType); 24067 result.changes.push(sceneValidationDiff); 24068 } 24069 const getAnimationLogicId = (id) => SceneAnimationEntity.generateId(id); 24070 const sceneAnimationDiff = this.getDependenciesDiff([id], EntityTypes.LOGIC, getAnimationLogicId, getDiffResult, true); 24071 if (sceneAnimationDiff) { 24072 sceneAnimationDiff.children[0] = exposeDiffResult(sceneAnimationDiff.children[0], "Scene Animation", null); 24073 changeList.push(sceneAnimationDiff.changeType); 24074 result.changes.push(sceneAnimationDiff); 24075 } 24076 const getDescTransLogicId = (id) => `${ADAVarName}_${id}`; 24077 const sceneDescTransDiff = this.getDependenciesDiff([id], EntityTypes.LOGIC, getDescTransLogicId, getDiffResult, true); 24078 if (sceneDescTransDiff) {
24079 sceneDescTransDiff.children[0] = exposeDiffResult(sceneDescTransDiff.children[0], "Descriptive Transcript", null); 24080 changeList.push(sceneDescTransDiff.changeType); 24081 result.changes.push(sceneDescTransDiff); 24082 } 24083 const scenePartsIds = this.collectScenePartIds(previousScene, currentScene); 24084 const getScenePartDependencyId = (scenePartId) => `${id}_${scenePartId}`; 24085 const scenePartsDiff = this.getDependenciesDiff(scenePartsIds, EntityTypes.SCENE_PART, getScenePartDependencyId, getDiffResult, false); 24086 if (scenePartsDiff) { 24087 changeList.push(scenePartsDiff.changeType); 24088 result.changes.push(scenePartsDiff); 24089 } 24090 result.changeType = DiffManager.getChangeType(changeList, false); 24091 result.isShown = result.changeType !== ChangeType.None; 24092 } 24093 } 24094 return result; 24095 }; 24096 this.collectScenePartIds = (previousScene, currentScene) => { 24097 const scenePartIdent = (sp) => sp.scenePart; 24098 return Array.from(/* @__PURE__ */ new Set([...previousScene && previousScene.sceneParts.map(scenePartIdent) || [], ...currentScene && currentScene.sceneParts.map(scenePartIdent) || []])); 24099 }; 24100 this.collectLogicIdsFromMaster = (previousMaster, currentMaster) => { 24101 const phIdent = (ph) => ph.id || ph.name; 24102 let prevPlaceholders; 24103 let prevParameters; 24104 let currentPlaceholders; 24105 let currentParameters = []; 24106 if (previousMaster && previousMaster.sceneParts[0]) { 24107 prevPlaceholders = previousMaster.sceneParts[0].placeholders.map(phIdent); 24108 prevParameters = previousMaster.sceneParts[0].parameters.map(phIdent); 24109 } 24110 if (currentMaster && currentMaster.sceneParts[0]) { 24111 currentPlaceholders = currentMaster.sceneParts[0].placeholders.map(phIdent); 24112 currentParameters = currentMaster.sceneParts[0].parameters.map(phIdent); 24113 } 24114 return Array.from(/* @__PURE__ */ new Set([ 24115 ...prevPlaceholders, 24116 ...prevParameters, 24117 ...currentPlaceholders, 24118 ...currentParameters 24119 ])); 24120 }; 24121 } 24122}; 24123//#endregion 24124//#region client/logic/entities/scenePartEntity.ts 24125var ScenePartEntity = class ScenePartEntity extends BaseEntity { 24126 constructor() { 24127 super(EntityTypes.SCENE_PART); 24128 this.generateName = (scenePartIndex) => { 24129 return `Frame#${scenePartIndex + 1}`; 24130 }; 24131 this.collector = ({ context, previousContext }) => { 24132 return !previousContext ? this.validationCollector(context) : this.diffCollector({ 24133 context, 24134 previousContext 24135 }); 24136 }; 24137 this.validationCollector = (context) => { 24138 let sceneParts = []; 24139 let allScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 24140 if (allScenes) Object.keys(allScenes).forEach((sceneId) => { 24141 allScenes[sceneId].sceneParts && allScenes[sceneId].sceneParts.forEach((scenePart, index) => { 24142 const narrationPartsInScenePart = []; 24143 scenePart.NarrationParts && scenePart.NarrationParts.forEach((narrationPart) => { 24144 narrationPartsInScenePart.push(narrationPart.id); 24145 }); 24146 sceneParts.push({ 24147 id: `${sceneId}_${scenePart.scenePart}`, 24148 validate: (prevValidationResult, getValidationResultFunction) => { 24149 return this.doValidate(scenePart, sceneId, allScenes[sceneId].name, getValidationResultFunction, context, narrationPartsInScenePart, index); 24150 } 24151 }); 24152 }); 24153 }); 24154 return sceneParts; 24155 }; 24156 this.doValidate = (scenePart, sceneId, sceneName, getValidationResult, context, narrationPartsInScenePart, partIndex) => { 24157 let scenePartValidationResult = { 24158 type: this.getType(), 24159 id: scenePart.scenePart, 24160 issues: [], 24161 name: this.generateName(partIndex) 24162 }; 24163 if (scenePart.placeholders) { 24164 const getDependencyId = (dependency) => dependency.name + "_" + sceneId; 24165 let issue = this.getDependenciesIssue(scenePart.placeholders, EntityTypes.PLACEHOLDER, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_PLACEHOLDER_ERROR); 24166 if (issue) { 24167 scenePartValidationResult.issues.push(issue); 24168 scenePartValidationResult.severity = issue.severity; 24169 } 24170 } 24171 if (scenePart.groups) { 24172 const getDependencyId = (dependency) => dependency.id; 24173 let issue = this.getDependenciesIssue(scenePart.groups, EntityTypes.GROUP, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_GROUP_ERROR); 24174 if (issue) { 24175 scenePartValidationResult.issues.push(issue); 24176 scenePartValidationResult.severity = ValidationManager.getHighestSeverity([scenePartValidationResult.severity, issue.severity]); 24177 } 24178 } 24179 if (scenePart.prioritizedLists) { 24180 const getDependencyId = (dependency) => PrioritizedListEntity.generateId(dependency.id, sceneId); 24181 let issue = this.getDependenciesIssue(scenePart.prioritizedLists, EntityTypes.PRIORITIZED_LIST, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_PRIORITIZED_LIST_ERROR); 24182 if (issue) { 24183 scenePartValidationResult.issues.push(issue); 24184 scenePartValidationResult.severity = ValidationManager.getHighestSeverity([scenePartValidationResult.severity, issue.severity]); 24185 } 24186 } 24187 if (scenePart.parameters) { 24188 const getDependencyId = (dependency) => dependency.name + "_" + sceneId; 24189 let issue = this.getDependenciesIssue(scenePart.parameters, EntityTypes.PARAMETER, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_PARAMETER_ERROR); 24190 if (issue) { 24191 scenePartValidationResult.issues.push(issue); 24192 scenePartValidationResult.severity = ValidationManager.getHighestSeverity([scenePartValidationResult.severity, issue.severity]); 24193 } 24194 } 24195 let project = StateReaderUtils.getProject(context.state, context.projectName); 24196 if (StateReaderUtils.getNarrationsVersionFromState(context.state, context.projectName, context.stage, context.version) > 0) { 24197 if (scenePart.NarrationParts) { 24198 const getDependencyId = new NarrationEntity().getEntityId; 24199 let issue = this.getDependenciesIssue(scenePart.NarrationParts, EntityTypes.NARRATION, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_NARRATION_ERROR); 24200 if (issue) { 24201 scenePartValidationResult.issues.push(issue); 24202 scenePartValidationResult.severity = ValidationManager.getHighestSeverity([scenePartValidationResult.severity, issue.severity]); 24203 } 24204 } 24205 const allRecordings = StateReaderUtils.getProjectAssetsByType(project, context.state.assets, ASSET_TYPES.recording); 24206 const projectRFR = StateReaderUtils.getProgramRFR(context.state, context.projectName, context.stage, context.version); 24207 const scenePartRecordings = allRecordings.filter((rec) => rec.RFR >= projectRFR && rec.narrationMetadata && narrationPartsInScenePart && narrationPartsInScenePart.includes(getRecordingNarrationId(rec.name))); 24208 if (scenePartRecordings) { 24209 const getDependencyId = new RecordingEntity().getAssetId; 24210 let issue = this.getDependenciesIssue(scenePartRecordings, EntityTypes.RECORDING, getDependencyId, getValidationResult, IssueCodes.SCENE_PART_RECORDING_ERROR); 24211 if (issue) { 24212 scenePartValidationResult.issues.push(issue); 24213 scenePartValidationResult.severity = ValidationManager.getHighestSeverity([scenePartValidationResult.severity, issue.severity]); 24214 } 24215 } 24216 } 24217 return scenePartValidationResult; 24218 }; 24219 this.diffCollector = ({ context, previousContext }) => { 24220 let scenePartInstances = []; 24221 const allPreviousScenes = StateReaderUtils.getProjectWireframeScenes(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 24222 const allPreviousSceneParts = ScenePartEntity.extractScenePartsByIdFromAllScenes(allPreviousScenes); 24223 const allCurrentScenes = StateReaderUtils.getProjectWireframeScenes(context.state, context.projectName, context.stage, context.version); 24224 const allCurrentSceneParts = ScenePartEntity.extractScenePartsByIdFromAllScenes(allCurrentScenes); 24225 this.entityObjectsToMap(allPreviousSceneParts, allCurrentSceneParts).forEac
24225h((scenePartPair, scenePartId) => { 24226 scenePartInstances.push({ 24227 id: scenePartId, 24228 diff: (getDiffResult) => this.doDiff(getDiffResult, scenePartPair.previousEntity, scenePartPair.currentEntity) 24229 }); 24230 }); 24231 return scenePartInstances; 24232 }; 24233 this.doDiff = (getDiffResult, previousScenePart, currentScenePart) => { 24234 const belongsToScene = this.getPropsFromPreviousOrCurrent(currentScenePart, previousScenePart, "belongsToScene"); 24235 const latestKnownIndex = this.getPropsFromPreviousOrCurrent(currentScenePart, previousScenePart, "spIdx"); 24236 const id = this.getPropsFromPreviousOrCurrent(currentScenePart, previousScenePart, "scenePart"); 24237 let changeType = ChangeType.None; 24238 if (!previousScenePart && currentScenePart) changeType = ChangeType.Add; 24239 else if (previousScenePart && !currentScenePart) changeType = ChangeType.Delete; 24240 const result = { 24241 type: this.getType(), 24242 id, 24243 name: this.generateName(latestKnownIndex), 24244 changeType, 24245 changes: [], 24246 isShown: changeType !== ChangeType.None 24247 }; 24248 if (result.changeType === ChangeType.None) { 24249 let changeList = []; 24250 const placeholderIds = this.extractEntityIdsFromSceneParts(previousScenePart, currentScenePart, "placeholders", (ph) => ph.id || ph.name); 24251 const getPlaceholderDependencyId = (id) => `${id}_${belongsToScene}`; 24252 const placeholderDiff = this.getDependenciesDiff(placeholderIds, EntityTypes.PLACEHOLDER, getPlaceholderDependencyId, getDiffResult, false); 24253 if (placeholderDiff) { 24254 result.changes.push(placeholderDiff); 24255 changeList.push(placeholderDiff.changeType); 24256 } 24257 const parameterIds = this.extractEntityIdsFromSceneParts(previousScenePart, currentScenePart, "parameters", (pr) => pr.id || pr.name); 24258 const getParameterDependencyId = (id) => `${id}_${belongsToScene}`; 24259 const parameterDiff = this.getDependenciesDiff(parameterIds, EntityTypes.PARAMETER, getParameterDependencyId, getDiffResult, false); 24260 if (parameterDiff) { 24261 result.changes.push(parameterDiff); 24262 changeList.push(parameterDiff.changeType); 24263 } 24264 const groupIds = this.extractEntityIdsFromSceneParts(previousScenePart, currentScenePart, "groups", (grp) => grp.id); 24265 const getGroupDependencyId = (id) => id; 24266 const groupDiff = this.getDependenciesDiff(groupIds, EntityTypes.GROUP, getGroupDependencyId, getDiffResult, false); 24267 if (groupDiff) { 24268 result.changes.push(groupDiff); 24269 changeList.push(groupDiff.changeType); 24270 } 24271 const prioritizedListIds = this.extractEntityIdsFromSceneParts(previousScenePart, currentScenePart, "prioritizedLists", (pl) => pl.id); 24272 const getPLDependencyId = (id) => id; 24273 const prioritizedListDiff = this.getDependenciesDiff(prioritizedListIds, EntityTypes.PRIORITIZED_LIST, getPLDependencyId, getDiffResult, false); 24274 if (prioritizedListDiff) { 24275 result.changes.push(prioritizedListDiff); 24276 changeList.push(prioritizedListDiff.changeType); 24277 } 24278 const narrationIds = this.extractEntityIdsFromSceneParts(previousScenePart, currentScenePart, "NarrationParts", new NarrationEntity().getEntityId); 24279 const getNarrationDependencyId = (id) => id; 24280 const narrationsDiff = this.getDependenciesDiff(narrationIds, EntityTypes.NARRATION, getNarrationDependencyId, getDiffResult, false); 24281 if (narrationsDiff) { 24282 result.changes.push(narrationsDiff); 24283 changeList.push(narrationsDiff.changeType); 24284 } 24285 result.changeType = DiffManager.getChangeType(changeList, false); 24286 result.isShown = result.changeType !== ChangeType.None; 24287 } 24288 return result; 24289 }; 24290 this.extractEntityIdsFromSceneParts = (previousScenePart, currentScenePart, prop, identFunc) => { 24291 const allPropsArray = [...previousScenePart && previousScenePart[prop] || [], ...currentScenePart && currentScenePart[prop] || []]; 24292 return Array.from(new Set(allPropsArray.map(identFunc))); 24293 }; 24294 } 24295 static { 24296 this.extractScenePartsByIdFromAllScenes = (allScenes) => { 24297 let allSceneParts = {}; 24298 Object.entries(allScenes).forEach(([sceneId, sceneData]) => { 24299 if (sceneId !== LogicContainers.Master && sceneData.sceneParts) sceneData.sceneParts.forEac
24299h((scenePart, index) => { 24300 let dupSp = { 24301 ...scenePart, 24302 belongsToScene: sceneId, 24303 spIdx: index 24304 }; 24305 allSceneParts[`${sceneId}_${scenePart.scenePart}`] = dupSp; 24306 }); 24307 }); 24308 return allSceneParts; 24309 }; 24310 } 24311}; 24312//#endregion 24313//#region client/logic/entities/storyEntity.ts 24314var { CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC, ADS_STORY_VIDEO_RATIO_QUALITY_DEFINITION } = featureFlagConst; 24315var StoryEntity = class extends BaseEntity { 24316 constructor() { 24317 super(EntityTypes.STORY); 24318 this.collector = (args) => { 24319 const { context, previousContext } = args; 24320 let stories = []; 24321 const storiesVersion = StateReaderUtils.getStoriesVersion(context.state, context.projectName, context.stage, context.version); 24322 const currentStories = StateReaderUtils.getProjectWireframesStories(context.state, context.projectName, context.stage, context.version); 24323 const previousStories = previousContext && StateReaderUtils.getProjectWireframesStories(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version); 24324 const storiesMap = this.entityObjectsToMap(previousStories, currentStories); 24325 const programType = StateReaderUtils.getProjectType(context.state, context.projectName); 24326 const useVideoRatioAndQualityLogic = shouldUseVideoRatioAndQualityLogic(programType, StateReaderUtils.isFeatureEnable(context.state, CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC) ? [CRM_STORY_VIDEO_RATIO_QUALITY_LOGIC] : []); 24327 const includeAdsAdditionalVideoDefinitions = programType === ProgramType.Ads && StateReaderUtils.isFeatureEnable(context.state, ADS_STORY_VIDEO_RATIO_QUALITY_DEFINITION); 24328 storiesMap.forEach((storiesPair, storyId) => { 24329 stories.push({ 24330 id: storyId, 24331 validate: (prevValidationResult, getValidationResultFunction) => { 24332 return this.doValidate(currentStories[storyId], getValidationResultFunction, storiesVersion, useVideoRatioAndQualityLogic, includeAdsAdditionalVideoDefinitions); 24333 }, 24334 diff: (getDiffResult) => { 24335 return this.doDiff(getDiffResult, storiesPair.previousEntity, storiesPair.currentEntity, storiesVersion, useVideoRatioAndQualityLogic, includeAdsAdditionalVideoDefinitions); 24336 } 24337 }); 24338 }); 24339 return stories; 24340 }; 24341 this.doValidate = (story, getValidationResult, storiesVersion, useVideoRatioAndQualityLogic, includeAdsAdditionalVideoDefinitions) => { 24342 let storyValidationResult = { 24343 type: this.getType(), 24344 id: story.id, 24345 issues: [], 24346 name: story.name 24347 }; 24348 if (story.participatingSceneIds) { 24349 const getDependencyId = (dependency) => dependency; 24350 let issue = this.getDependenciesIssue(story.participatingSceneIds, EntityTypes.SCENE, getDependencyId, getValidationResult, IssueCodes.STORY_SCENE_ERROR); 24351 if (issue) { 24352 storyValidationResult.issues.push(issue); 24353 storyValidationResult.severity = issue.severity; 24354 } 24355 } 24356 if (story.participatingDPs) { 24357 const getDependencyId = (dependency) =>
24357 story.id + "_" + dependency; 24358 let issue = this.getDependenciesIssue(story.participatingDPs, EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.STORY_LOGIC_ERROR); 24359 if (issue) { 24360 storyValidationResult.issues.push(issue); 24361 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24362 } 24363 } 24364 if (storiesVersion) { 24365 const getDependencyId = (dependency) => dependency; 24366 let issue = this.getDependenciesIssue([getStoryPropertyCollectionId(story.id, LogicContainers.Soundtrack)], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.STORY_SOUNDTRACK_LOGIC_ERROR); 24367 if (issue) { 24368 storyValidationResult.issues.push(issue); 24369 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24370 } 24371 } 24372 if (storiesVersion) { 24373 const getDependencyId = (dependency) => dependency; 24374 let issue = this.getDependenciesIssue([getStoryPropertyCollectionId(story.id, LogicContainers.BackgroundAsset)], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.STORY_BACKGROUND_ASSET_LOGIC_ERROR); 24375 if (issue) { 24376 storyValidationResult.issues.push(issue); 24377 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24378 } 24379 } 24380 if (useVideoRatioAndQualityLogic) { 24381 const getDependencyId = (dependency) => getStoryPropertyCollectionId(story.id, dependency); 24382 let issue = this.getDependenciesIssue([LogicEntity.VIDEO_RATIO_QUALITY_LOGIC_VALIDATION_ID], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.STORY_VIDEO_RATIO_QUALITY_LOGIC_ERROR); 24383 if (issue) { 24384 storyValidationResult.issues.push(issue); 24385 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24386 } 24387 } 24388 if (includeAdsAdditionalVideoDefinitions) { 24389 const emptyMultiSelectErrorMessage = "At least one value must be selected"; 24390 const emptySelectErrorMessage = "Value must not be blank"; 24391 if (!(Array.isArray(story.durationOptions) && story.durationOptions.length > 0)) { 24392 const issue = { 24393 code: IssueCodes.STORY_VIDEO_DURATION_OPTIONS_ERROR, 24394 severity: IssueSeverity.ERROR, 24395 details: { message: emptyMultiSelectErrorMessage } 24396 }; 24397 storyValidationResult.issues.push(issue); 24398 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24399 } 24400 if (!(Array.isArray(story.numberOfProducts) && story.numberOfProducts.length > 0)) { 24401 const issue = { 24402 code: IssueCodes.STORY_VIDEO_NUM_OF_PRODUCT_ERROR, 24403 severity: IssueSeverity.ERROR, 24404 details: { message: emptyMultiSelectErrorMessage } 24405 }; 24406 storyValidationResult.issues.push(issue); 24407 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24408 } 24409 let isRatioAndQualityOptionsValid = true; 24410 let ratioAndQualityOptionsIssueDetails; 24411 if (Array.isArray(story.ratioAndQualityOptions) && story.ratioAndQualityOptions.length > 0) ratioAndQualityOptionsIssueDetails = story.ratioAndQualityOptions.map((ratioAndQualityOption) => { 24412 let result = {}; 24413 if (!ratioAndQualityOption.ratio) { 24414 isRatioAndQualityOptionsValid = false; 24415 result.ratioValidationMessage = emptySelectErrorMessage; 24416 } 24417 if (!ratioAndQualityOption.quality) { 24418 isRatioAndQualityOptionsValid = false; 24419 result.qualityValidationMessage = emptySelectErrorMessage; 24420 } 24421 return result; 24422 }); 24423 else { 24424 isRatioAndQualityOptionsValid = false; 24425 ratioAndQualityOptionsIssueDetails = [{ 24426 ratioValidationMessage: emptySelectErrorMessage, 24427 qualityValidationMessage: emptySelectErrorMessage 24428 }]; 24429 } 24430 if (!isRatioAndQualityOptionsValid) { 24431 const issue = { 24432 code: IssueCodes.STORY_VIDEO_RATIO_QUALITY_OPTIONS_ERROR, 24433 severity: IssueSeverity.ERROR, 24434 details: ratioAndQualityOptionsIssueDetails 24435 }; 24436 storyValidationResult.issues.push(issue); 24437 storyValidationResult.severity = ValidationManager.getHighestSeverity([storyValidationResult.severity, issue.severity]); 24438 } 24439 } 24440 return storyValidationResult; 24441 }; 24442 this.doDiff = (getDiffResult, previousStory, currentStory, storiesVersion, useVideoRatioAndQualityLogic, includeAdsAdditionalVideoDefinitions) => { 24443 const changeType = diffEntities(previousStory, currentStory); 24444 const storyId = currentStory && currentStory.id || previousStory.id; 24445 let result = { 24446 type: this.getType(), 24447 id: storyId, 24448 name: currentStory && currentStory.name || previousStory.name, 24449 changeType, 24450 changes: [], 24451 isShown: changeType !== ChangeType.None 24452 }; 24453 let changeList = []; 24454 const getDependencyId = (dependency) => dependency; 24455 if (storiesVersion) { 24456 const settingsChange = this.getPropertyChanges(storyId, previousStory, currentStory, "activateCaching", "Caching", EntityTypes.SETTINGS); 24457 if (settingsChange) { 24458 result.changes.push(settingsChange); 24459 changeList.push(settingsChange.changeType); 24460 } 24461 if (includeAdsAdditionalVideoDefinitions) { 24462 const durationOptionsChange = this.getPropertyChanges(storyId, previousStory, currentStory, "durationOptions", "Duration options", EntityTypes.SETTINGS); 24463 if (durationOptionsChange) { 24464 result.changes.push(durationOptionsChange); 24465 changeList.push(durationOptionsChange.changeType); 24466 } 24467 const numberOfProductsChange = this.getPropertyChanges(storyId, previousStory, currentStory, "numberOfProducts", "Number of products", EntityTypes.SETTINGS); 24468 if (numberOfProductsChange) { 24469 result.changes.push(numberOfProductsChange); 24470 changeList.push(numberOfProductsChange.changeType); 24471 } 24472 const ratioAndQualityOptionsChange = this.getPropertyChanges(storyId, previousStory, currentStory, "ratioAndQualityOptions", "Ratio and quality options", EntityTypes.SETTINGS); 24473 if (ratioAndQualityOptionsChange) { 24474 result.changes.push(ratioAndQualityOptionsChange); 24475 changeList.push(ratioAndQualityOptionsChange.changeType); 24476 } 24477 } 24478 if (useVideoRatioAndQualityLogic) { 24479 const ratioAndQualityChanges = this.addLogicPropertyChangeToResult(storyId, LogicEntity.VIDEO_RATIO_QUALITY_LOGIC_VALIDATION_ID, getDependencyId, getDiffResult); 24480 if (ratioAndQualityChanges?.children?.[0]) { 24481 ratioAndQualityChanges.children[0].type = EntityTypes.SETTINGS; 24482 result.changes.push(ratioAndQualityChanges); 24483 changeList.push(ratioAndQualityChanges.changeType); 24484 } 24485 } 24486 const overviewChange = this.getPropertyChanges(storyId, previousStory, currentStory, "description", "Overview", EntityTypes.OVERVIEW); 24487 if (overviewChange) { 24488 result.changes.push(overviewChange); 24489 changeList.push(overviewChange.changeType); 24490 } 24491 const decisionPointChanges = this.addLogicPropertyChangeToResult(storyId, LogicContainers.DecisionPoint, getDependencyId, getDiffResult); 24492 if (decisionPointChanges) { 24493 result.changes.push(decisionPointChanges); 24494 changeList.push(decisionPointChanges.changeType); 24495 } 24496 const soundtrackChanges = this.addLogicPropertyChangeToResult(storyId, LogicContainers.Soundtrack, getDependencyId, getDiffResult); 24497 if (soundtrackChanges) { 24498 result.changes.push(soundtrackChanges); 24499 changeList.push(soundtrackChanges.changeType); 24500 } 24501 const backgroundChanges = this.addLogicPropertyChangeToResult(storyId, LogicContainers.Backgroun
24501dAsset, getDependencyId, getDiffResult); 24502 if (backgroundChanges) { 24503 result.changes.push(backgroundChanges); 24504 changeList.push(backgroundChanges.changeType); 24505 } 24506 } else if (result.changeType === ChangeType.None) return updateDiffResultWithChanges(result, this.getDependenciesDiff([result.id], EntityTypes.LOGIC, getDependencyId, getDiffResult, true)); 24507 if (result.changeType === ChangeType.None) result.changeType = DiffManager.getChangeType(changeList, false); 24508 if (result.changeType !== ChangeType.None) result.isShown = true; 24509 return result; 24510 }; 24511 this.getPropertyChanges = (storyId, previousStory, currentStory, propertyName, propertyHeader, entityType) => { 24512 const propertyChange = diffEntities(previousStory ? previousStory[propertyName] : void 0, currentStory ? currentStory[propertyName] : void 0); 24513 if (propertyChange && propertyChange !== ChangeType.None) return { 24514 changeType: propertyChange, 24515 details: "", 24516 children: [{ 24517 type: entityType, 24518 id: getStoryPropertyCollectionId(storyId, propertyName), 24519 name: propertyHeader, 24520 changeType: propertyChange, 24521 changes: [], 24522 isShown: true 24523 }] 24524 }; 24525 }; 24526 this.addLogicPropertyChangeToResult = (storyId, propertyName, getDependencyId, getDiffResult) => { 24527 const logicPropertyChange = this.getDependenciesDiff([getStoryPropertyCollectionId(storyId, propertyName)], EntityTypes.LOGIC, getDependencyId, getDiffResult, true); 24528 if (logicPropertyChange) { 24529 if (logicPropertyChange.children && logicPropertyChange.children.length > 0) { 24530 logicPropertyChange.children[0].isShown = logicPropertyChange.changeType !== ChangeType.None; 24531 return logicPropertyChange; 24532 } 24533 } 24534 }; 24535 } 24536}; 24537//#endregion 24538//#region client/logic/entities/studioDataElementEntity.ts 24539var StudioDataElementEntity = class extends BaseEntity { 24540 constructor() { 24541 super(EntityTypes.DERIVED_DATA_ELEMENT); 24542 this.collector = (args) => { 24543 const { context, previousContext } = args; 24544 const previousStudioData = previousContext && StateReaderUtils.getProjectDataElements(previousContext.state, previousContext.projectName, previousContext.stage, previousContext.version).filter((dataElement) => dataElement.origin === DataElementOrigins.Derived); 24545 const currentStudioData = StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version).filter((dataElement) => dataElement.origin === DataElementOrigins.Derived); 24546 const studioDataMap = this.entityListsToMap(previousStudioData, currentStudioData, (de) => de.id); 24547 let studioDataInstances = []; 24548 studioDataMap.forEach((entityContextPair, key) => { 24549 studioDataInstances.push({ 24550 id: key, 24551 validate: (prevValidationResult, getValidationResultFunction) => { 24552 return this.doValidate(entityContextPair.currentEntity, getValidationResultFunction, context); 24553 }, 24554 diff: (getDiffResult) => this.doDiff(getDiffResult, entityContextPair.previousEntity, entityContextPair.currentEntity) 24555 }); 24556 }); 24557 return studioDataInstances; 24558 }; 24559 this.doValidate = (derivedDataElement, getValidationResult, context) => { 24560 let result = { 24561 type: this.getType(), 24562 id: derivedDataElement.id, 24563 issues: [] 24564 }; 24565 let wireframes = StateReaderUtils.getWireFrame(context.state, context.projectName, context.stage, context.version); 24566 let allDataElements = StateReaderUtils.getProjectDataElements(context.state, context.projectName, context.stage, context.version); 24567 if (StateReaderUtils.getProjectWireframesSceneInputLogic(context.state, context.projectName, DataElementOrigins.Derived, getDerivedDataElementLogicId(derivedDataElement), context.stage, context.version)) { 24568 const getDependencyId = (derivedDataElement) => derivedDataElement.id; 24569 let issue = this.getDependenciesIssue([derivedDataElement], EntityTypes.LOGIC, getDependencyId, getValidationResult, IssueCodes.DERIVED_LOGIC_ERROR); 24570 if (issue) { 24571 result.issues.push(issue); 24572 result.severity = issue.severity; 24573 } 24574 } else { 24575 result.issues.push({ 24576 code: IssueCodes.DERIVED_LOGIC_MISSING, 24577 severity: IssueSeverity.WARNING, 24578 details: {} 24579 }); 24580 result.severity = IssueSeverity.WARNING; 24581 } 24582 const derivedLogicCycles = StateReaderUtils.getDerivedLogicCycles(wireframes); 24583 let positionInLogicCycle = derivedLogicCycles.indexOf(derivedDataElement.id); 24584 if (positionInLogicCycle > -1) { 24585 let cycle = [...derivedLogicCycles.slice(0, positionInLogicCycle), ...derivedLogicCycles.slice(positionInLogicCycle + 1)]; 24586 cycle = cycle.map((dataElementId) => findDataElementById(dataElementId, allDataElements).displayName); 24587 result.issues.push({ 24588 code: IssueCodes.DERIVED_DATA_ELEMENT_CYCLIC_DEPENDENCY, 24589 severity: IssueSeverity.ERROR, 24590 details: { cycle } 24591 }); 24592 result.severity = IssueSeverity.ERROR; 24593 } 24594 return result; 24595 }; 24596 this.doDiff = (getDiffResult, previousStudioData, currentStudioData) => { 24597 const changeType = diffEntities(DataElementEntity.normalizeDataElement(previousStudioData), DataElementEntity.normalizeDataElement(currentStudioData)); 24598 let result = { 24599 type: this.getType(), 24600 id: currentStudioData && currentStudioData.id || previousStudioData.id, 24601 name: currentStudioData && currentStudioData.displayName || previousStudioData.displayName, 24602 changeType, 24603 changes: [], 24604 isShown: changeType !== ChangeType.None 24605 }; 24606 if (result.changeType === ChangeType.None) { 24607 const getDependencyId = (id) => id; 24608 return updateDiffResultWithChanges(result, this.getDependenciesDiff([result.id], EntityTypes.LOGIC, getDependencyId, getDiffResult, true)); 24609 } 24610 return result; 24611 }; 24612 } 24613}; 24614//#endregion 24615//#region client/logic/validations/validationReducer.ts 24616var getValidationManager = (function() { 24617 let validationManager; 24618 return () => { 24619 if (!validationManager) validationManager = new ValidationManager([ 24620 new AnalyticsEntity(), 24621 new DataTableEntity(), 24622 new GroupEntity(), 24623 new LogicEntity(), 24624 new NarrationEntity(), 24625 new ParameterEntity(), 24626 new PlaceholderEntity(), 24627 new PrioritizedListCandidateEntity(), 24628 new PrioritizedListEntity(), 24629 new ProgramEntity(), 24630 new RecordingEntity(), 24631 new SceneAnimationEntity(), 24632 new SceneEntity(), 24633 new ScenePartEntity(), 24634 new SceneValidationEntity(), 24635 new StoryEntity(), 24636 new StudioDataElementEntity(), 24637 new DataElementEntity() 24638 ]); 24639 return validationManager; 24640 }; 24641})(); 24642var nonRelevantAction = (actionType) => { 24643 return actionType === "LOADING_PROJECT_LIFECYCLE_STAGE_SUCCESS" || actionType === "GET_PROJECT_VERSIONS_COMPLETE" || actionType === "LOADING_PROJECT_WIREFRAMES_PRESETS_SUCCESS" || actionType === "UPDATE_ASSET" || actionType === "LOADING_PROJECT_SNAPSHOT_SUCCESS"; 24644}; 24645function validationReducer(state, action) { 24646 if (!action || nonRelevantAction(action.type) || state.isLoading || state.loadingCount > 0 || action.payload && action.payload.stage === "diff") return state; 24647 if (action.type === "LOADING_PROJECT_WIREFRAMES_FROM_UIASSET") return { 24648 ...state, 24649 validationData: new ValidationTable() 24650 }; 24651 if (action.payload && action.payload.projectName) { 24652 let table = getValidationManager().init(state.validationData, { 24653 state, 24654 projectName: action.payload.projectName, 24655 stage: action.payload.stage, 24656 version: action.payload.version 24657 }); 24658 return { 24659 ...state, 24660 validationData: table 24661 }; 24662 } 24663 return state; 24664} 24665function getDataElementValidationResult(state, dataElementId, dataElementOrigin) { 24666 if (dataElementOrigin === DataElementOrigins.Feed || dataElementOrigin === DataElementOrigins.Creative) return getValidationManager().readValidationResultById(state.validationData, EntityTypes.DATA_ELEMENT, dataElementId); 24667 else if (dataElementOrigin === DataElementOrigins.Derived) return getValidationManager().readValidationResultById(state.validationData, EntityTypes.DERIVED_DATA_ELEMENT, dataElementId); 24668} 24669function getNarrationValidationResult(state, narrationId) { 24670 const narrationEntityId = AssetUtils.getCrossVersionId(narrationId); 24671 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.NARRATION, narrationEntityId); 24672}
24673function getSceneValidationResult(state, sceneId) { 24674 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.SCENE, sceneId); 24675} 24676function getPriorityListCandidateValidationResult(state, prioritizedListCandidateKey) { 24677 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.PRIORITIZED_LIST_CANDIDATE, prioritizedListCandidateKey); 24678} 24679function getPriorityListValidationResult(state, prioritizedListId) { 24680 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.PRIORITIZED_LIST, prioritizedListId); 24681} 24682function getStoryValidationResult(state, storyId) { 24683 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.STORY, storyId); 24684} 24685function getPlaceholderValidationResult(state, placeholderName, sceneId) { 24686 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.PLACEHOLDER, PlaceholderEntity.generateId(placeholderName, sceneId)); 24687} 24688function getGroupValidationResult(state, groupId) { 24689 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.GROUP, groupId); 24690} 24691function getParameterValidationResult(state, parameterName, sceneId) { 24692 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.PARAMETER, ParameterEntity.generateId(parameterName, sceneId)); 24693} 24694function getDataTableValidationResult(state, dataTableName) { 24695 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.DATA_TABLE, dataTableName); 24696} 24697function getProgramValidationResult(state, projectName) { 24698 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.PROGRAM, projectName); 24699} 24700function getLogicValidationResult(state, logicId) { 24701 return getValidationManager().readValidationResultById(state.validationData, EntityTypes.LOGIC, logicId); 24702} 24703/** 24704* filter issues by code including children 24705* @param result the validation result with the issues array 24706* @param code the issue code to filter by 24707* returns array of issues with the requested issue code 24708*/ 24709function filterIssues(result, code) { 24710 return (0, import_traverse.default)(result).reduce((acc, node) => { 24711 if (node && node.code === code) acc.push(node); 24712 return acc; 24713 }, []); 24714} 24715//#endregion 24716//#region client/logic/common/pollingHandler.ts 24717var POLLING_INTERVAL_MS = 2e3; 24718var POLL_TTFB_MS = 1e4; 24719var POLL_TOTAL_MS = 15e3; 24720var MAX_CONSECUTIVE_POLL_FAILURES = 5; 24721var PollingError = class extends Error { 24722 constructor(message, cause) { 24723 super(message); 24724 this.name = "PollingError"; 24725 this.cause = cause; 24726 const code = cause?.sskyCode; 24727 if (code) this.sskyCode = code; 24728 } 24729}; 24730var sleep = (ms) => new Promise((resolve) => { 24731 setTimeout(resolve, ms); 24732}); 24733/** 24734* Polls until the task reports Done, and returns its data. Rejects with a PollingError - never with a bare 24735* string, which the old implementation did and which left the Splunk classifier nothing to read. 24736*/ 24737var waitForTaskToComplete = async (kickOff, options = {}) => { 24738 const { updateProgressCb, deadlineMs } = options; 24739 const { pollingUrl } = await kickOff; 24740 const startedAt = Date.now(); 24741 let consecutiveFailures = 0; 24742 const giveUp = (message, cause) => { 24743 updateProgressCb?.(void 0, void 0); 24744 return new PollingError(message, cause); 24745 }; 24746 for (;;) { 24747 if (deadlineMs !== void 0 && Date.now() - startedAt >= deadlineMs) throw giveUp(`Task did not finish within ${deadlineMs} milliseconds`); 24748 let response; 24749 try { 24750 response = await callEndpointJson(pollingUrl, { 24751 ttfbTimeoutMs: POLL_TTFB_MS, 24752 totalTimeoutMs: POLL_TOTAL_MS, 24753 cache: "no-store" 24754 }); 24755 consecutiveFailures = 0; 24756 } catch (error) { 24757 consecutiveFailures++; 24758 if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) throw giveUp(`Polling failed ${consecutiveFailures} times in a row: ${toErrorMessage(error)}`, error); 24759 await sleep(POLLING_INTERVAL_MS); 24760 continue; 24761 } 24762 const { status, progress, data, error } = response; 24763 switch (status) { 24764 case "Done": 24765 updateProgressCb?.(100, data); 24766 return data; 24767 case "Failed": 24768 case "Not Found": throw giveUp(`Task reported ${status}: ${toErrorMessage(error)}`, error); 24769 case "Pending": 24770 updateProgressCb?.(progress, data); 24771 await sleep(POLLING_INTERVAL_MS); 24772 break; 24773 default: throw giveUp(`Unknown polling status ${status}`); 24774 } 24775 } 24776}; 24777//#endregion 24778//#region client/logic/vlx/program.ts 24779function createProgramLogic(state, projectName, storyIdToStoryAssetName) { 24780 let program = StateReaderUtils.getProject(state, projectName); 24781 const programDataFields = { 24782 dataElements: StateReaderUtils.getProjectDataElements(state, projectName), 24783 assets: StateReaderUtils.getProjectAssets(program, state.assets), 24784 storyIdToStoryAssetName 24785 }; 24786 return { storyName: { 24787 rules: buildInputRules(StateReaderUtils.getProgramStorySelectionLogic(state, projectName), programDataFields, false, false, true), 24788 type: VLXInputLogicType.TEXT 24789 } }; 24790} 24791//#endregion 24792//#region client/logic/projects/projectLifecycle/projectLifecycleActions.ts 24793var LOADING_PROJECT_SNAPSHOT_SUCCESS = "LOADING_PROJECT_SNAPSHOT_SUCCESS"; 24794var loadingProjectSnapshotSuccess = (0, import_lib$3.createAction)(LOADING_PROJECT_SNAPSHOT_SUCCESS, (accountId, projectName, projectSnapShot) => ({ 24795 accountId, 24796 projectName, 24797 projectSnapShot 24798})); 24799var ADDING_PROJECT_SNAPSHOT_UPDATE_PROGRESS = "ADDING_PROJECT_SNAPSHOT_UPDATE_PROGRESS"; 24800var ADDING_PROJECT_SNAPSHOT_SUCCESS = "ADDING_PROJECT_SNAPSHOT_SUCCESS"; 24801var ADDING_PROJECT_STAGE_SNAPSHOT_SUCCESS = "ADDING_PROJECT_STAGE_SNAPSHOT_SUCCESS"; 24802var SETTING_PROJECT_SNAPSHOT_SUCCESS = "SETTING_PROJECT_SNAPSHOT_SUCCESS"; 24803var UPDATING_PROJECT_SNAPSHOT_SUCCESS = "UPDATING_PROJECT_SNAPSHOT_SUCCESS"; 24804var SET_PROJECT_BASED_ON_SNAPSHOT = "SET_PROJECT_BASED_ON_SNAPSHOT"; 24805var SET_PROMOTE_STATUS = "SET_PROMOTE_STATUS"; 24806var addingProjectSnapshotUpdateProgress = (0, import_lib$3.createAction)(ADDING_PROJECT_SNAPSHOT_UPDATE_PROGRESS, (progress) => ({ progress })); 24807var addingProjectSnapshotSuccess = (0, import_lib$3.createAction)(ADDING_PROJECT_SNAPSHOT_SUCCESS, (accountId, projectName, projectSnapShot) => ({ 24808 accountId, 24809 projectName, 24810 projectSnapShot 24811})); 24812var addingProjectStageSnapshotSuccess = (0, import_lib$3.createAction)(ADDING_PROJECT_STAGE_SNAPSHOT_SUCCESS, (accountId, projectName, projectSnapShot) => ({ 24813 accountId, 24814 projectName, 24815 projectSnapShot 24816})); 24817var setProjectLifecycleStageSnapshotSuccess = (0, import_lib$3.createAction)(SETTING_PROJECT_SNAPSHOT_SUCCESS, (accountId, projectName, projectSnapShot) => ({ 24818 accountId, 24819 projectName, 24820 projectSnapShot 24821})); 24822var setProjectBasedOnSnapshot = (0, import_lib$3.createAction)(SET_PROJECT_BASED_ON_SNAPSHOT, (accountId, projectName, snapshotNumber) => ({ 24823 accountId, 24824 projectName, 24825 snapshotNumber 24826})); 24827var updatingProjectSnapshotSuccess = (0, import_lib$3.createAction)(UPDATING_PROJECT_SNAPSHOT_SUCCESS, (accountId, projectName, snapshotNumber, snapshotObject) => ({ 24828 accountId, 24829 projectName, 24830 snapshotNumber, 24831 snapshotObject 24832}
24832)); 24833var setPromoteStatus = (0, import_lib$3.createAction)(SET_PROMOTE_STATUS, (status) => status); 24834var { STORY_LOGIC } = featureFlagConst; 24835function addProjectLifecycleStageSnapshotInternal(getState, services, dispatch, accountId, projectName, snapshotNumber, snapshotName, stage, assets, cb, userName, snapshotComment, validationData, isLegacyProject, programId, programVersionId) { 24836 function updateLoadingProgress(progress) { 24837 dispatch(addingProjectSnapshotUpdateProgress(progress)); 24838 } 24839 let snapshotProgramVersionId; 24840 return services.projectLifeCycleServices.addProjectSnapshot(accountId, projectName, snapshotNumber, snapshotName, assets, updateLoadingProgress, userName, snapshotComment, validationData, isLegacyProject, programVersionId).then(() => { 24841 let input = { 24842 sourceId: programVersionId, 24843 snapshotNumber, 24844 snapshotName, 24845 snapshotComment, 24846 snapshotValidationData: validationData 24847 }; 24848 return !isLegacyProject ? services.graphQlClient.mutate({ 24849 mutation: CreateProgramVersionSnapshotDocument, 24850 variables: { 24851 input, 24852 [IGNORE_SERVER_ERRORS]: true 24853 } 24854 }) : Promise.resolve(void 0); 24855 }).then((result) => { 24856 snapshotProgramVersionId = result?.data?.createProgramVersionSnapshot?.targetProgramVersion?.id; 24857 const newDraftGraphQLParentProgramVersionId = result?.data?.createProgramVersionSnapshot?.sourceProgramVersion?.parent1ProgramVersion?.id; 24858 if (newDraftGraphQLParentProgramVersionId) dispatch(updateWireframeGraphQLParentProgramVersionId(projectName, newDraftGraphQLParentProgramVersionId)); 24859 if (stage) return addLifecycleHistoryEntry(getState, services, dispatch, accountId, projectName, stage, snapshotNumber, "promote", userName); 24860 }).then((projectLifeCycle) => { 24861 if (projectLifeCycle) dispatch(addingProjectStageSnapshotSuccess(accountId, projectName, projectLifeCycle)); 24862 if (!isLegacyProject) return getProjectSnapshotFromGQL(services, programId, snapshotProgramVersionId); 24863 else return services.projectLifeCycleServices.getProjectSnapshot(accountId, projectName, snapshotNumber); 24864 }).then((snapshot) => { 24865 dispatch(addingProjectSnapshotSuccess(accountId, projectName, snapshot)); 24866 return services.wireframes.setProjectWireframesDraftDirtyBit(accountId, projectName, false); 24867 }).then(() => { 24868 dispatch(setLoading(false, accountId, projectName)); 24869 if (typeof cb === "function") cb(snapshotNumber); 24870 }).catch((err) => { 24871 dispatch(reportError(err)); 24872 dispatch(setLoading(false, accountId, projectName)); 24873 }); 24874} 24875async function getNewVersionSnapshotNumber(getState, services, programId, projectName) { 24876 const variables = { 24877 input: { id: programId }, 24878 [IGNORE_SERVER_ERRORS]: true 24879 }; 24880 const newVersionSnapshotNumber = (await services.graphQlClient.mutate({ 24881 mutation: UpdateProgramLastSnapshotNumberDocument, 24882 variables 24883 })).data.updateProgramLastSnapshotNumber.snapshotNumber; 24884 if (StateReaderUtils.getLatestVersionNumber(getState(), projectName) >= newVersionSnapshotNumber) throw Error("snapshot number already exist"); 24885 return newVersionSnapshotNumber; 24886} 24887var createVersion = function(userName, accountId, projectName, snapshotName, snapshotComment, relateToStage, wireframes, enabledFeatureFlags, narratorId, selectedVoice, cb) { 24888 return function(dispatch, getState, services) { 24889 dispatch(setLoading(true, accountId, projectName)); 24890 let state = getState(); 24891 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 24892 let program = StateReaderUtils.getProject(state, projectName); 24893 const { programId, programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 24894 let assets = StateReaderUtils.getProjectAssets(program, state.assets); 24895 const storyIds = Object.keys(wireframes.stories); 24896 let scenesLogic; 24897 let uploadStoryInlineJob; 24898 let snapshotNumber; 24899 return getNewVersionSnapshotNumber(getState, services, programId, projectName).then((newSnapshotNumber) => { 24900 snapshotNumber = newSnapshotNumber; 24901 return createSceneLogic({ 24902 wireframes, 24903 assets, 24904 program, 24905 masterData: wireframes.scenes[LogicContainers.Master] 24906 }); 24907 }).then((createScenesLogicResult) => { 24908 scenesLogic = createScenesLogicResult; 24909 const program = StateReaderUtils.getProject(state, projectName); 24910 const accountName = StateReaderUtils.getAccountDisplayName(state.accounts.byId[accountId]); 24911 let storyInlineLogics = []; 24912 const creativeVersion = StateReaderUtils.getCreativeVersionFromWireframes(wireframes); 24913 storyIds.forEach((storyId) => { 24914 const currentStory = wireframes.stories[storyId]; 24915 const analytics = createAnalyticsData(accountId, program, wireframes, currentStory, assets); 24916 const narrationsVersion = StateReaderUtils.getNarrationsVersion(wireframes); 24917 const storiesVersion = StateReaderUtils.getStoriesVersion(state, projectName); 24918 let storyInlineLogic = createStoryInlineLogic(wireframes, assets, currentStory, analytics, program, accountName, scenesLogic, false, narrationsVersion, storiesVersion, creativeVersion, enabledFeatureFlags); 24919 storyInlineLogics.push(storyInlineLogic); 24920 }); 24921 return { storyInlineLogics }; 24922 }).then(({ storyInlineLogics }) => { 24923 let uploadStoryInlineContent = storyIds.map((storyId, index) => { 24924 return { 24925 assetName: wireframes.stories[storyId].name, 24926 jsonContent: storyInlineLogics[index] 24927 }; 24928 }); 24929 uploadStoryInlineJob = waitForTaskToComplete(services.projectAssetsServices.uploadBulkJsonAssetContent(accountId, projectName, uploadStoryInlineContent, storyInlineAssetType, false)); 24930 return uploadStoryInlineJob; 24931 }).then((storyAssets) => { 24932 if (StateReaderUtils.isFeatureEnable(state, STORY_LOGIC)) { 24933 let storyIdToStoryAssetName = storyIds.reduce((acc, item, index) => { 24934 acc[item] = storyAssets[index].name; 24935 return acc; 24936 }, {}); 24937 let programLogic = createProgramLogic(state, projectName, storyIdToStoryAssetName); 24938 return services.projectAssetsServices.uploadJsonAssetContent(accountId, projectName, "program", programLogic, AssetTypes.program, false); 24939 } 24940 }).then((programAsset) => { 24941 const program = StateReaderUtils.getProject(state, projectName); 24942 const recordings = StateReaderUtils.getProjectAssetsByType(program, state.assets, AssetTypes.recording); 24943 if (StateReaderUtils.getNarrationsVersion(wireframes) > 0) { 24944 let narrationData = createDtaasObj(wireframes, narratorId, recordings); 24945 let narrationParts = StateReaderUtils.getProjectNarrationParts(wireframes).reduce((acc, narrationPart) => { 24946 acc[narrationPart.id] = narrationPart; 24947 return acc; 24948 }, {});
24949 return dispatch(uploadToDtaasIfNeeded(accountId, projectName, narratorId, narrationData, selectedVoice, wireframes.scenes, narrationParts, snapshotNumber)); 24950 } 24951 }).then(() => { 24952 let validationData = getProgramValidationContent(getProgramValidationResult(state, projectName)); 24953 return addProjectLifecycleStageSnapshotInternal(getState, services, dispatch, accountId, projectName, snapshotNumber, snapshotName, relateToStage, void 0, cb, userName, snapshotComment, validationData, false, programId, programVersionId); 24954 }).catch((err) => { 24955 dispatch(reportError(err)); 24956 dispatch(setLoading(false, accountId, projectName)); 24957 }); 24958 }; 24959}; 24960var addProjectLifecycleStageSnapshot = function(accountId, projectName, snapshotName, stage, assets, cb, isLegacyProject) { 24961 return function(dispatch, getState, services) { 24962 dispatch(setLoading(true, accountId, projectName)); 24963 const { programId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 24964 return getNewVersionSnapshotNumber(getState, services, programId, projectName).then((snapshotNumber) => { 24965 return addProjectLifecycleStageSnapshotInternal(getState, services, dispatch, accountId, projectName, snapshotNumber, snapshotName, stage, assets, cb, void 0, void 0, void 0, true, void 0, void 0); 24966 }).catch((err) => { 24967 dispatch(reportError(err)); 24968 dispatch(setLoading(false, accountId, projectName)); 24969 }); 24970 }; 24971}; 24972var setProjectLifecycleStageSnapshot = (accountId, projectName, stage, projectSnapshotNumber, analyticsAction, cb, userName) => { 24973 return async (dispatch, getState, services) => { 24974 try { 24975 await loadProjectSnapshotPromise(services, getState(), dispatch, accountId, projectName, projectSnapshotNumber); 24976 const projectType = StateReaderUtils.getProjectType(getState(), projectName); 24977 const projectSFId = StateReaderUtils.getProjectId(getState(), projectName); 24978 const isEditorProgram = StateReaderUtils.isEditorProgram(getState(), projectName); 24979 let snapshotData; 24980 if (isEditorProgram) snapshotData = await createEditorLifecycleEntry(services, dispatch, StateReaderUtils.getProgramId(getState(), projectName), stage, projectSnapshotNumber, userName); 24981 else snapshotData = await addLifecycleHistoryEntry(getState, services, dispatch, accountId, projectName, stage, projectSnapshotNumber, analyticsAction, userName, projectType, projectSFId); 24982 dispatch(setProjectLifecycleStageSnapshotSuccess(accountId, projectName, snapshotData)); 24983 if (typeof cb === "function") cb(); 24984 } catch (err) { 24985 dispatch(reportError(err)); 24986 } 24987 }; 24988}; 24989var createEditorLifecycleEntry = async (services, dispatch, programId, stage, projectSnapshotNumber, userName) => { 24990 let input = { 24991 programId, 24992 lifecycleStage: convertStageType(stage), 24993 snapshotNumber: projectSnapshotNumber 24994 }; 24995 const lifecycleHistoryEntry = (await services.graphQlClient.mutate({ 24996 mutation: CreateEditorLifecycleEntryDocument, 24997 variables: { 24998 input, 24999 [IGNORE_SERVER_ERRORS]: true 25000 }, 25001 context: { allowedModes: [EDITING_MODE, STAGE_MODE] } 25002 })).data.createEditorLifecycleEntry.lifecycleHistoryEntry; 25003 return { 25004 stage, 25005 snapshotNumber: projectSnapshotNumber, 25006 promotedDate: new Date(lifecycleHistoryEntry.created).valueOf(), 25007 promotedBy: userName, 25008 graphQLId: lifecycleHistoryEntry.id 25009 }; 25010}; 25011var getProjectSnapshotFromGQL = (services, programId, programVersionId) => { 25012 const variables = { 25013 programId, 25014 programVersionId 25015 }; 25016 return services.graphQlClient.query({ 25017 query: GetProgramVersionSnapshotWithAssetsDocument, 25018 variables 25019 }).then((result) => { 25020 const gqlProgramVersionSnapshot = result.data.program.programVersion; 25021 return buildStateSnapshotFromGql(gqlProgramVersionSnapshot, buildStateSnapshotAssetsFromGql(gqlProgramVersionSnapshot.assets, gqlProgramVersionSnapshot.animations, gqlProgramVersionSnapshot.dataTables, gqlProgramVersionSnapshot.narrationRecordings, gqlProgramVersionSnapshot.narrators)); 25022 }); 25023}; 25024var loadProjectSnapshotPromise = (services, state, dispatch, accountId, projectName, snapshotNumber) => { 25025 const snapshotDetails = StateReaderUtils.getSnapshotDetails(state, Number(snapshotNumber)); 25026 let getProjectSnapshotPromise; 25027 if (snapshotDetails?.snapshotSource === SnapshotSource.POSTGRES) { 25028 const programId = StateReaderUtils.getProgramId(state, projectName); 25029 const programVersionId = snapshotDetails.graphQLId; 25030 getProjectSnapshotPromise = getProjectSnapshotFromGQL(services, programId, programVersionId); 25031 } else getProjectSnapshotPromise = services.projectLifeCycleServices.getProjectSnapshot(accountId, projectName, snapshotNumber); 25032 return getProjectSnapshotPromise.then((projectSnapshot) => { 25033 dispatch(loadingProjectSnapshotSuccess(accountId, projectName, projectSnapshot)); 25034 }); 25035}; 25036var loadProjectSnapshot = function(accountId, projectName, snapshotNumber) { 25037 return (dispatch, getState, services) => { 25038 loadProjectSnapshotPromise(services, getState(), dispatch, accountId, projectName, snapshotNumber).catch((err) => { 25039 dispatch(reportError(err)); 25040 }); 25041 }; 25042}; 25043var loadProjectSnapshotLegacy = function(accountId, projectName, snapshotNumber,
25043cb) { 25044 return (dispatch, getState, services) => { 25045 dispatch(setLoading(true, accountId, projectName)); 25046 loadProjectSnapshotPromise(services, getState(), dispatch, accountId, projectName, snapshotNumber).then(() => { 25047 dispatch(setProjectBasedOnSnapshot(accountId, projectName, snapshotNumber)); 25048 if (typeof cb === "function") cb(); 25049 dispatch(setLoading(false, accountId, projectName)); 25050 }).catch((err) => { 25051 dispatch(reportError(err)); 25052 dispatch(setLoading(false, accountId, projectName)); 25053 }); 25054 }; 25055}; 25056var updateProjectSnapshot = function(accountId, projectName, snapshotNumber, newSnapshotObject, cb) { 25057 return function(dispatch, getState, services) { 25058 dispatch(setLoading(true, accountId, projectName)); 25059 const snapshotDetails = StateReaderUtils.getSnapshotDetails(getState(), snapshotNumber); 25060 let postgresPromise = Promise.resolve(); 25061 const dispatchUpdateSuccess = (snapshotDetailsToUpdate) => { 25062 dispatch(updatingProjectSnapshotSuccess(accountId, projectName, snapshotNumber, snapshotDetailsToUpdate)); 25063 if (typeof cb === "function") cb(); 25064 dispatch(setLoading(false, accountId, projectName)); 25065 }; 25066 return services.projectLifeCycleServices.updateProjectSnapshot(accountId, projectName, snapshotNumber, newSnapshotObject).then(() => { 25067 if (snapshotDetails?.snapshotSource === SnapshotSource.POSTGRES) { 25068 let input = { 25069 id: snapshotDetails.graphQLId, 25070 updated: IGNORE_UPDATED, 25071 snapshotName: newSnapshotObject.snapshotName, 25072 snapshotComment: newSnapshotObject.snapshotComment 25073 }; 25074 postgresPromise = services.graphQlClient.mutate({ 25075 mutation: UpdateProgramVersionSnapshotDocument, 25076 variables: { 25077 input, 25078 [IGNORE_SERVER_ERRORS]: true 25079 }, 25080 context: { allowedModes: [EDITING_MODE, STAGE_MODE] } 25081 }); 25082 } 25083 return postgresPromise; 25084 }).then(() => { 25085 dispatchUpdateSuccess(newSnapshotObject); 25086 }).catch((err) => { 25087 dispatch(reportError(err)); 25088 dispatch(setLoading(false, accountId, projectName)); 25089 }); 25090 }; 25091}; 25092var addLifecycleHistoryEntry = async (getState, services, dispatch, accountId, projectName, stage, projectSnapshotNumber, analyticsAction, userName, projectType, projectSFId) => { 25093 let programId = StateReaderUtils.getProgramId(getState(), projectName); 25094 if (!programId) { 25095 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 25096 programId = StateReaderUtils.getProgramId({ projectSummaries }, projectName); 25097 } 25098 const writeLifecycleHistoryPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), programId, BulkId.LifecycleHistory); 25099 let dynamoLifecycleHistoryEntry; 25100 try { 25101 dynamoLifecycleHistoryEntry = await services.projectLifeCycleServices.setProjectLifecycleStageSnapshot(accountId, projectName, stage, projectSnapshotNumber, analyticsAction, userName, projectType, projectSFId, programId, writeLifecycleHistoryPostgresOnly); 25102 } catch (err) { 25103 dispatch(reportError(err)); 25104 } 25105 let postgresLifecycleHistoryEntry; 25106 try { 25107 let input = { 25108 programId, 25109 lifecycleStage: convertStageType(stage), 25110 snapshotNumber: projectSnapshotNumber 25111 }; 25112 const addLifecycleHistoryEntryOutput = (await services.graphQlClient.mutate({ 25113 mutation: AddLifecycleHistoryEntryDocument, 25114 variables: { 25115 input, 25116 [IGNORE_SERVER_ERRORS]: !writeLifecycleHistoryPostgresOnly 25117 }, 25118 context: { allowedModes: [EDITING_MODE, STAGE_MODE] } 25119 })).data.addLifecycleHistoryEntry; 25120 postgresLifecycleHistoryEntry = { 25121 stage, 25122 snapshotNumber: projectSnapshotNumber, 25123 promotedDate: new Date(addLifecycleHistoryEntryOutput.lifecycleHistoryEntry.created).valueOf(), 25124 promotedBy: userName, 25125 graphQLId: addLifecycleHistoryEntryOutput.lifecycleHistoryEntry.id 25126 }; 25127 } catch (err) {} 25128 return writeLifecycleHistoryPostgresOnly ? postgresLifecycleHistoryEntry : dynamoLifecycleHistoryEntry; 25129}; 25130var uploadToDtaasIfNeeded = function(accountId, projectName, narratorId, narrationData, selectedVoice, scenes, narrationParts, version, updateProgressCb) { 25131 return async (dispatch, getState, services) => { 25132 return services.dtaasServices.uploadToDtaasIfNeeded(accountId, projectName, narratorId, narrationData, selectedVoice, scenes, narrationParts, version).then((narrationPartsUploadResultArray) => { 25133 if (updateProgressCb) updateProgressCb(100); 25134 let updatedNarrationParts = {}; 25135 let uploadedNeeded = false;
25136 narrationPartsUploadResultArray.forEach((narrationPartResult) => { 25137 if (narrationPartResult.uploaded) { 25138 updatedNarrationParts[narrationPartResult.id] = narrationPartResult; 25139 uploadedNeeded = true; 25140 } 25141 }); 25142 if (uploadedNeeded) { 25143 let bulkScenePartUpdates = {}; 25144 let narrationsToUpdate = []; 25145 scenes && Object.values(scenes).forEach((scene) => { 25146 scene && scene.sceneParts && scene.sceneParts.forEach((scenePart) => { 25147 scenePart && scenePart.NarrationParts && scenePart.NarrationParts.forEach((narrationPart, narrationPartIndex) => { 25148 if (updatedNarrationParts[narrationPart.id]) { 25149 const updatedKey = updatedNarrationParts[narrationPart.id].key; 25150 const bulkScenePartUpdateKey = `${scene.id}/${scenePart.scenePart}`; 25151 let newScenePart = bulkScenePartUpdates[bulkScenePartUpdateKey] || { ...scenePart }; 25152 newScenePart.NarrationParts = [...newScenePart.NarrationParts]; 25153 newScenePart.NarrationParts[narrationPartIndex] = { 25154 ...narrationPart, 25155 key: updatedKey 25156 }; 25157 bulkScenePartUpdates[bulkScenePartUpdateKey] = newScenePart; 25158 narrationsToUpdate.push({ 25159 id: narrationPart.id, 25160 dtaasPrefixKey: updatedKey, 25161 updated: "$IGNORE$" 25162 }); 25163 } 25164 }); 25165 }); 25166 }); 25167 const isPostgresOnly = StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.MostEntities); 25168 let dynamoPromise; 25169 let gqlPromise; 25170 if (!isPostgresOnly) { 25171 dynamoPromise = services.wireframes.bulkUpdateProjectWireframesSceneParts(accountId, projectName, bulkScenePartUpdates); 25172 gqlPromise = Promise.resolve(null); 25173 } else { 25174 dynamoPromise = Promise.resolve(null); 25175 let input = { 25176 programVersionId: StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName).programVersionId, 25177 narrationsToUpdate 25178 }; 25179 gqlPromise = services.graphQlClient.mutate({ 25180 mutation: UpdateNarrationsDtaasPrefixKeyDocument, 25181 variables: { 25182 input, 25183 dryRun: false 25184 } 25185 }); 25186 } 25187 return Promise.all([ 25188 dynamoPromise, 25189 gqlPromise, 25190 bulkScenePartUpdates, 25191 narrationPartsUploadResultArray 25192 ]); 25193 } else return Promise.all([ 25194 void 0, 25195 void 0, 25196 void 0, 25197 narrationPartsUploadResultArray 25198 ]); 25199 }).then(([responseBody, gqlResponse, bulkScenePartUpdates, narrationPartsUploadResultArray]) => { 25200 if (bulkScenePartUpdates) { 25201 const allScenePartsSucceededDynamo = responseBody && Object.keys(responseBody).every((scenePartId) => responseBody[scenePartId].status === 200); 25202 const gqlSucceeded = gqlResponse?.data?.updateNarrationsDtaasPrefixKey?.result === GqlClientUpdateNarrationsDtaasPrefixKeyResult.SUCCESS; 25203 if (allScenePartsSucceededDynamo || gqlSucceeded) dispatch(ChangingBulkScenePartsSuccess(accountId, projectName, bulkScenePartUpdates)); 25204 } 25205 return narrationPartsUploadResultArray.reduce((acc, current) => { 25206 acc.narrationPartNameToKey[current.narrationPartName] = current.key; 25207 acc.narrationPartIdToKey[current.id] = current.key; 25208 return acc; 25209 }, { 25210 narrationPartNameToKey: {}, 25211 narrationPartIdToKey: {} 25212 }); 25213 }); 25214 }; 25215}; 25216var loadProjectLifecycleHistory = memoizeThunkAction((accountId, projectName) => { 25217 return async function(dispatch, getState, services) { 25218 let programId = StateReaderUtils.getProgramId(getState(), projectName); 25219 convertGqlLifecycleHistoryResult(await services.graphQlClient.query({ 25220 fetchPolicy: "no-cache", 25221 query: GetProgramLifecycleHistoryDocument, 25222 variables: { programId } 25223 }).catch(() => null)).forEach((lifecycleItem) => { 25224 dispatch(loadingProjectLifeCycleStageSuccess(accountId, projectName, lifecycleItem, lifecycleItem.name)); 25225 }); 25226 }; 25227}); 25228var revertToVersion = function(accountId, projectName, snapshotNumber, cb, failureCb) { 25229 return function(dispatch, getState, services) { 25230 dispatch(setSoftLoading(true)); 25231 let input = { sourceId: StateReaderUtils.getSnapshotDetails(getState(), snapshotNumber).graphQLId }; 25232 return services.graphQlClient.mutate({ 25233 mutation: CreateProgramVersionDraftFromSnapshotDocument, 25234 variables: { input },
25235 context: { allowedModes: [EDITING_MODE, STAGE_MODE] } 25236 }).then(() => { 25237 if (typeof cb === "function") cb(); 25238 dispatch(setSoftLoading(false)); 25239 }).catch(() => { 25240 if (typeof failureCb === "function") failureCb(); 25241 dispatch(setSoftLoading(false)); 25242 }); 25243 }; 25244}; 25245//#endregion 25246//#region client/components/versionManager/VersionManagerUtil.tsx 25247var getBasedOnSnapshotNumber = (snapshots, graphQLParentProgramVersionId, latestSnapshotNumber) => { 25248 if (graphQLParentProgramVersionId && latestSnapshotNumber) { 25249 const parentSnapshotNumber = snapshots?.find((version) => version.graphQLId === graphQLParentProgramVersionId)?.snapshotNumber; 25250 return parentSnapshotNumber && parentSnapshotNumber !== latestSnapshotNumber ? parentSnapshotNumber : null; 25251 } else return null; 25252}; 25253var getBasedOnSnapshotNumberForSnapshot = (snapshots, currentSnapshot) => { 25254 if (currentSnapshot.graphQLParentProgramVersionId) { 25255 const previousSnapshots = snapshots?.filter((snapshot) => snapshot.snapshotNumber < currentSnapshot.snapshotNumber); 25256 const previousSnapshotNumbers = previousSnapshots?.map((ver) => ver.snapshotNumber); 25257 const latestSnapshotNumber = previousSnapshotNumbers && previousSnapshotNumbers.length > 1 && Math.max(...previousSnapshotNumbers); 25258 return getBasedOnSnapshotNumber(previousSnapshots, currentSnapshot.graphQLParentProgramVersionId, latestSnapshotNumber); 25259 } else return null; 25260}; 25261var getActiveVersion = (versions) => { 25262 return versions[0] ? versions[0].snapshotNumber : null; 25263}; 25264var getActiveStage = (versionNumber, devVersion, uatVersion, prodVersion) => { 25265 if (versionNumber === prodVersion) return Stages.prod; 25266 if (versionNumber === uatVersion) return Stages.UAT; 25267 if (versionNumber === devVersion) return Stages.dev; 25268 return ""; 25269}; 25270var getActiveStages = (versionNumber, devVersion, uatVersion, prodVersion) => { 25271 let stages = []; 25272 if (versionNumber === prodVersion) stages.push(Stages.prod); 25273 if (versionNumber === uatVersion) stages.push(Stages.UAT); 25274 if (versionNumber === devVersion) stages.push(Stages.dev); 25275 return stages; 25276}; 25277var renderDateTimeColumn = (timestamp) => { 25278 if (!timestamp) return "N/A"; 25279 return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { 25280 className: "date-time-cell", 25281 style: { 25282 display: "flex", 25283 flexDirection: "column", 25284 margin: "-10px 0px" 25285 }, 25286 children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: TimeUtils.getReadableDate(timestamp) }
25286), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: TimeUtils.getReadableTime(timestamp) })] 25287 }); 25288}; 25289//#endregion 25290//#region client/components/errorBoundary/Components/EnhancedError.ts 25291var combineStackTraces = (currentStackTrace, originalErrorStackTrace) => { 25292 return `${currentStackTrace}${originalErrorStackTrace ? `\nOriginal error:\n${originalErrorStackTrace}` : ""}`; 25293}; 25294var EnhancedError = class extends Error { 25295 constructor(error, sskyCode, details) { 25296 super(toErrorMessage(error)); 25297 this.getSskyErrorCode = () => { 25298 return this[SSKY_ERROR_CODE_KEY]; 25299 }; 25300 this.getErrorId = () => { 25301 return this[ERROR_ID_KEY]; 25302 }; 25303 this.name = this.constructor.name; 25304 this.stack = combineStackTraces(this.stack, error?.stack); 25305 this.details = details; 25306 this[ERROR_ID_KEY] = details?.["errorId"] ?? error?.["errorId"] ?? error?.extensions?.["errorId"] ?? v4(); 25307 this[SSKY_ERROR_CODE_KEY] = sskyCode; 25308 } 25309}; 25310//#endregion 25311//#region common/publicKeys.ts 25312var pendoPublicKey = "2c7961ea-f861-45be-6486-0fbe5ca184c2"; 25313//#endregion 25314//#region client/components/pendoService.ts 25315var usersToDisable = ["[email protected]"]; 25316var escapeSavedWords = (eventData) => { 25317 if (eventData?.videoId) { 25318 const newEventData = { 25319 ...eventData, 25320 _videoId: eventData.videoId 25321 }; 25322 delete newEventData["videoId"]; 25323 return newEventData; 25324 } 25325 return eventData; 25326}; 25327var PendoService = class PendoService { 25328 constructor() { 25329 this.pendoSessionInfo = { 25330 visitor: { 25331 id: "", 25332 userType: "", 25333 role: "", 25334 email: "" 25335 }, 25336 account: {}, 25337 disableGuides: false 25338 }; 25339 this.videoId = ""; 25340 if (window.pendo) this.pendoObject = window.pendo; 25341 } 25342 /** 25343 * initUserData 25344 * @param userId required identifier - user email 25345 * @param userRoles user roles 25346 * @param accountInfo account info to be initialised 25347 */ 25348 initUserInfoIfRequired(userId, userRoles, accountInfo) { 25349 if (!this.isReady()) { 25350 this.updateAccountInfoInternally(accountInfo); 25351 this.updateVisitorInfoInternally({ 25352 id: userId, 25353 userType: "Core Platform", 25354 role: userRoles, 25355 email: userId 25356 }); 25357 if (usersToDisable.includes(userId)) this.pendoSessionInfo.disableGuides = true; 25358 this.pendoObject?.initialize(this.pendoSessionInfo); 25359 } 25360 } 25361 /** 25362 * getInstance 25363 * Get single pendo service 25364 */ 25365 static getInstance() { 25366 if (!PendoService.instance) PendoService.instance = new PendoService(); 25367 return PendoService.instance; 25368 } 25369 /** 25370 * stopTracking 25371 * Stop sending events of user actions to pendo 25372 */ 25373 stopTracking() { 25374 this.pendoObject?.stopSendingEvents(); 25375 } 25376 /** 25377 * startTracking 25378 * Start sending events of user actions to pendo 25379 */ 25380 startTracking() { 25381 this.pendoObject?.startSendingEvents(); 25382 } 25383 showGuideById(id) { 25384 this.pendoObject?.showGuideById(id); 25385 } 25386 /** 25387 * updateInfo 25388 * Initializes pendo if not initialized yet 25389 * Sends update event with updated account information 25390 * @param pendoPartialAccountInfo required account info for updating pendo object 25391 */ 25392 updateAccountInfoIfChanged(pendoPartialAccountInfo) { 25393 if (this.pendoAccountNeedsUpdate(pendoPartialAccountInfo)) { 25394 this.updateAccountInfoInternally(pendoPartialAccountInfo); 25395 this.pendoObject?.updateOptions(this.pendoSessionInfo); 25396 } 25397 } 25398 /** 25399 * trackEvent 25400 * Sends track event with various information. 25401 * A track event can be sent with or without data. 25402 * @param eventName required the name of the event - a new track event will be created for every eventName (in Pendo dashboard) 25403 * @param eventData data to be passed in the form of key: value. Video context will be added to eventData. 25404 */ 25405 trackEvent(eventName, eventData) { 25406 eventData = escapeSavedWords(eventData); 25407 if (this.videoId) eventData = eventData ? { 25408 ...eventData, 25409 videoId: this.videoId 25410 } : { videoId: this.videoId }; 25411 if (eventData) this.pendoObject?.track(eventName, eventData); 25412 else this.pendoObject?.track(eventName); 25413 } 25414 updateVideoId(videoId) { 25415 this.videoId = videoId; 25416 } 25417 updateAccountInfoInternally(pendoPartialAccountInfo) { 25418 Object.keys(pendoPartialAccountInfo).map((key) => { 25419 if (pendoPartialAccountInfo.id !== void 0 || pendoPartialAccountInfo.name !== void 0) localStorage.removeItem(`_pendo_feedback_ping_sent.${pendoPublicKey}`); 25420 if (pendoPartialAccountInfo[key] !== void 0) this.pendoSessionInfo.account[key] = pendoPartialAccountInfo[key]; 25421 }); 25422 } 25423 updateVisitorInfoInternally(pendoVisitorInfo) { 25424 Object.keys(pendoVisitorInfo).map((key) => { 25425 if (pendoVisitorInfo[key] !== void 0) this.pendoSessionInfo.visitor[key] = pendoVisitorInfo[key]; 25426 }); 25427 } 25428 pendoAccountNeedsUpdate(pendoPartialAccountInfo) { 25429 let needsUpdate = false;
25430 Object.keys(pendoPartialAccountInfo).map((key) => { 25431 if (pendoPartialAccountInfo[key] !== this.pendoSessionInfo?.account[key]) needsUpdate = true; 25432 }); 25433 return needsUpdate; 25434 } 25435 isReady() { 25436 return this.pendoObject?.isReady?.(); 25437 } 25438}; 25439//#endregion 25440//#region client/components/editor/types.ts 25441var AssetGenerationFlowTrigger = /* @__PURE__ */ function(AssetGenerationFlowTrigger) { 25442 AssetGenerationFlowTrigger["PH"] = "Placeholder"; 25443 AssetGenerationFlowTrigger["IMGLY"] = "img.ly"; 25444 AssetGenerationFlowTrigger["MEDIA_LIB_LEFT_PANEL"] = "Media lib - left panel"; 25445 AssetGenerationFlowTrigger["MEDIA_LIB_EXTERNAL"] = "Media lib - external"; 25446 AssetGenerationFlowTrigger["BRAND"] = "Brand"; 25447 AssetGenerationFlowTrigger["LP_BUILDER"] = "Landing page builder"; 25448 AssetGenerationFlowTrigger["EMBED_CODE_BUILDER"] = "Embed code builder"; 25449 AssetGenerationFlowTrigger["CUSTOM_BACKGROUND"] = "Custom background"; 25450 return AssetGenerationFlowTrigger; 25451}({}); 25452var PreviewDialogType = /* @__PURE__ */ function(PreviewDialogType) { 25453 PreviewDialogType["Video"] = "video"; 25454 PreviewDialogType["Scene"] = "scene"; 25455 return PreviewDialogType; 25456}({}); 25457var BooleanType = /* @__PURE__ */ function(BooleanType) { 25458 BooleanType["True"] = "true"; 25459 BooleanType["False"] = "false"; 25460 return BooleanType; 25461}({}); 25462var StudioElementOrigin = /* @__PURE__ */ function(StudioElementOrigin) { 25463 StudioElementOrigin["Program"] = "program"; 25464 StudioElementOrigin["System"] = "system"; 25465 StudioElementOrigin["Contributor"] = "contributor"; 25466 return StudioElementOrigin; 25467}({}); 25468var Libraries = /* @__PURE__ */ function(Libraries) { 25469 Libraries["BrandsPanel"] = "BrandsPanel"; 25470 Libraries["MusicPanel"] = "MusicPanel"; 25471 Libraries["NarratorsPanel"] = "NarratorsPanel"; 25472 Libraries["DataPanel"] = "DataPanel"; 25473 Libraries["AspectRatio"] = "AspectRatio"; 25474 Libraries["ThemePanel"] = "ThemePanel"; 25475 Libraries["TruffleMediaLibrary"] = "TruffleMediaLibrary"; 25476 Libraries["AiGenerator"] = "AiGenerator"; 25477 Libraries["AvatarPanel"] = "AvatarPanel"; 25478 Libraries["InputsPanel"] = "InputsPanel"; 25479 Libraries["LanguagesPanel"] = "LanguagesPanel"; 25480 Libraries["CommentsPanel"] = "CommentsPanel"; 25481 return Libraries; 25482}({}); 25483var LibraryOpener = /* @__PURE__ */ function(LibraryOpener) { 25484 LibraryOpener["Default"] = "Default"; 25485 LibraryOpener["LibraryIcon"] = "LibraryIcon"; 25486 LibraryOpener["LibraryMenu"] = "LibraryMenu"; 25487 LibraryOpener["MediaPlaceholderConfiguration"] = "MediaPlaceholderConfiguration"; 25488 LibraryOpener["NarrationPlaceholderConfiguration"] = "NarrationPlaceholderConfiguration"; 25489 LibraryOpener["NoDataLibrary"] = "NoDataLibrary"; 25490 LibraryOpener["AvatarPlaceholderConfiguration"] = "AvatarPlaceholderConfiguration"; 25491 LibraryOpener["EditorContainer"] = "EditorContainer"; 25492 LibraryOpener["VideoOverviewPage"] = "VideoOverviewPage"; 25493 LibraryOpener["AppBar"] = "AppBar"; 25494 LibraryOpener["LanguagesLibrary"] = "LanguagesLibrary"; 25495 LibraryOpener["DocToVideo"] = "DocToVideo"; 25496 return LibraryOpener; 25497}({}); 25498var MediaLibraryActiveTab = /* @__PURE__ */ function(MediaLibraryActiveTab) { 25499 MediaLibraryActiveTab["YourLibrary"] = "YourLibrary"; 25500 MediaLibraryActiveTab["Stock"] = "Stock"; 25501 MediaLibraryActiveTab["Dam"] = "Dam"; 25502 return MediaLibraryActiveTab; 25503}({}); 25504var AddSceneDialogActiveTab = /* @__PURE__ */ function(AddSceneDialogActiveTab) { 25505 AddSceneDialogActiveTab["SceneLibrary"] = "SceneLibrary"; 25506 AddSceneDialogActiveTab["ImportScene"] = "ImportScene"; 25507 return AddSceneDialogActiveTab; 25508}({}); 25509var PlaceholderToolIntent = /* @__PURE__ */ function(PlaceholderToolIntent) { 25510 PlaceholderToolIntent["Logo"] = "logo"; 25511 PlaceholderToolIntent["Media"] = "media"; 25512 PlaceholderToolIntent["Text"] = "text"; 25513 PlaceholderToolIntent["Button"] = "button"; 25514 PlaceholderToolIntent["Avatar"] = "avatar"; 25515 return PlaceholderToolIntent; 25516}({}); 25517var MediaLibrarySortBy = /* @__PURE__ */ function(MediaLibrarySortBy) { 25518 MediaLibrarySortBy["LAST_ADDED"] = "LAST_ADDED"; 25519 MediaLibrarySortBy["A_Z"] = "A_Z"; 25520 return MediaLibrarySortBy; 25521}({}); 25522var MediaLibrarySortDirection = /* @__PURE__ */ function(MediaLibrarySortDirection) { 25523 MediaLibrarySortDirection["TOP_TO_BOTTOM"] = "TOP_TO_BOTTOM"; 25524 MediaLibrarySortDirection["BOTTOM_TO_TOP"] = "BOTTOM_TO_TOP"; 25525 return MediaLibrarySortDirection; 25526}({}); 25527var MediaLibraryFilterMediaType = /* @__PURE__ */ function(MediaLibraryFilterMediaType) { 25528 MediaLibraryFilterMediaType["ALL"] = "ALL"; 25529 MediaLibraryFilterMediaType["IMAGES"] = "IMAGES"; 25530 MediaLibraryFilterMediaType["IMAGES_AND_ANIMATIONS"] = "IMAGES_AND_ANIMATIONS"; 25531 MediaLibraryFilterMediaType["VIDEOS"] = "VIDEOS"; 25532 return MediaLibraryFilterMediaType; 25533}({}); 25534var MediaLibraryFilterMediaSource = /* @__PURE__ */ function(MediaLibraryFilterMediaSource) { 25535 MediaLibraryFilterMediaSource["ALL"] = "ALL"; 25536 MediaLibraryFilterMediaSource["USER"] = "USER"; 25537 MediaLibraryFilterMediaSource["GETTY"] = "GETTY"; 25538 MediaLibraryFilterMediaSource["AI_IMAGE"] = "AI_IMAGE";
25539 MediaLibraryFilterMediaSource["ACQUIA_DAM"] = "ACQUIA_DAM"; 25540 return MediaLibraryFilterMediaSource; 25541}({}); 25542var MediaLibraryFilterMediaOrientation = /* @__PURE__ */ function(MediaLibraryFilterMediaOrientation) { 25543 MediaLibraryFilterMediaOrientation["ALL"] = "ALL"; 25544 MediaLibraryFilterMediaOrientation["HORIZONTAL"] = "horizontal"; 25545 MediaLibraryFilterMediaOrientation["VERTICAL"] = "vertical"; 25546 MediaLibraryFilterMediaOrientation["SQUARE"] = "square"; 25547 return MediaLibraryFilterMediaOrientation; 25548}({}); 25549var UploadedGettyUrlTarget = /* @__PURE__ */ function(UploadedGettyUrlTarget) { 25550 UploadedGettyUrlTarget["LOGO"] = "logo"; 25551 UploadedGettyUrlTarget["PLACEHOLDER"] = "ph"; 25552 UploadedGettyUrlTarget["LANDING_PAGE_POSTER_IMAGE"] = "lpb_poster"; 25553 UploadedGettyUrlTarget["LANDING_PAGE_LOGO"] = "lpb_logo"; 25554 UploadedGettyUrlTarget["VIDEO_CUSTOM_BACKGROUND"] = "video_custom_background"; 25555 return UploadedGettyUrlTarget; 25556}({}); 25557var EditorMediaDragAndDropSnackbarState = /* @__PURE__ */ function(EditorMediaDragAndDropSnackbarState) { 25558 EditorMediaDragAndDropSnackbarState["CLOSED"] = "CLOSED"; 25559 EditorMediaDragAndDropSnackbarState["INFO"] = "INFO"; 25560 EditorMediaDragAndDropSnackbarState["ERROR"] = "ERROR"; 25561 return EditorMediaDragAndDropSnackbarState; 25562}({}); 25563var UploadOrigin = /* @__PURE__ */ function(UploadOrigin) { 25564 UploadOrigin["COMPUTER_DRAG_AND_DROP"] = "computer drag and drop"; 25565 UploadOrigin["COMPUTER_BROWSE"] = "computer browse"; 25566 UploadOrigin["STOCK_THROUGH_USAGE"] = "stock through usage"; 25567 UploadOrigin["STOCK_3_DOTS_MENU"] = "stock 3 dots menu"; 25568 UploadOrigin["AI_IMAGE_THROUGH_USAGE"] = "ai image generator use"; 25569 UploadOrigin["AI_IMAGE_GENERATOR_ADD"] = "ai image generator add"; 25570 UploadOrigin["AI_VIDEO_GENERATED"] = "ai video generated"; 25571 UploadOrigin["CONVERT_IMAGE_TO_VIDEO"] = "convert image to video"; 25572 UploadOrigin["ACQUIA_USE"] = "acquia use"; 25573 UploadOrigin["ACQUIA_ADD"] = "acquia add"; 25574 UploadOrigin["SUNDAYSKY_RECORDER"] = "sundaysky recorder"; 25575 UploadOrigin["SAVE_AS"] = "save as"; 25576 return UploadOrigin; 25577}({}); 25578var CloudIndicatorState = /* @__PURE__ */ function(CloudIndicatorState) { 25579 CloudIndicatorState["REGULAR"] = "regular"; 25580 CloudIndicatorState["SAVING"] = "saving"; 25581 CloudIndicatorState["ACTION_ERROR"] = "action-error"; 25582 CloudIndicatorState["NETWORK_ERROR"] = "network-error"; 25583 return CloudIndicatorState; 25584}({}); 25585var DocToVideoSource = /* @__PURE__ */ function(DocToVideoSource) { 25586 DocToVideoSource["DOC"] = "DOC"; 25587 DocToVideoSource["SLIDES"] = "SLIDES"; 25588 return DocToVideoSource; 25589}({}); 25590//#endregion 25591//#region client/components/editor/Utils/wireframeThemeSupport.ts 25592var SEPARATOR = "_"; 25593var constructWireframeThemeSupportKey = (wireframeId, themeId) => { 25594 return `${wireframeId}${SEPARATOR}${themeId}`; 25595}; 25596var createWireframeThemeSupport = (wireframes, themes) => { 25597 const wireframeThemeSupport = {}; 25598 for (const wireframe of wireframes) for (const theme of themes) wireframeThemeSupport[constructWireframeThemeSupportKey(wireframe.id, theme.id)] = wireframe.animatedWireframes.some((aw) => aw.theme.id === theme.id); 25599 return wireframeThemeSupport; 25600}; 25601//#endregion 25602//#region common/idUtils.ts 25603var getLocalIdFromGqlId = (id) => { 25604 return id?.split("|")?.pop(); 25605}; 25606//#endregion 25607//#region common/aspectRatioUtils.ts 25608function getAspectRatio(aspectRatioEnum) { 25609 return RATIOS[aspectRatioEnum]; 25610} 25611/** 25612* This is an immutable class designed to represent an aspect ratio. 25613*/ 25614var AspectRatio = class { 25615 #width; 25616 #height; 25617 #displayName; 25618 #icon; 25619 #playerFormat; 25620 #videoRatio; 25621 constructor(width, height, displayName, icon, playerFormat, videoRatio) { 25622 this.#width = width; 25623 this.#height = height; 25624 this.#displayName = displayName; 25625 this.#icon = icon; 25626 this.#playerFormat = playerFormat; 25627 this.#videoRatio = videoRatio; 25628 } 25629 displayName() { 25630 return this.#displayName; 25631 } 25632 ratio() { 25633 return this.#width / this.#height; 25634 } 25635 icon() { 25636 return this.#icon; 25637 } 25638 width() { 25639 return this.#width; 25640 } 25641 height() { 25642 return this.#height; 25643 } 25644 playerFormat() { 25645 return this.#playerFormat; 25646 } 25647 videoRatio() { 25648 return this.#videoRatio; 25649 } 25650}; 25651var RATIOS = { 25652 ar_14_9: new AspectRatio(14, 9, "Horizontal (14:9)", "rectangle-wide", "horizontal", VideoAspectRatio.FULL_LANDSCAPE), 25653 ar_16_9: new AspectRatio(16, 9, "Horizontal (16:9)", "rectangle-wide", "horizontal", VideoAspectRatio.FULL_LANDSCAPE), 25654 ar_191_100: new AspectRatio(1.91, 1, "Horizontal (1.91:1)", "rectangle-wide", "horizontal", VideoAspectRatio.FULL_LANDSCAPE), 25655 ar_1_1: new AspectRatio(1, 1, "Square (1:1)", "square", "square", VideoAspectRatio.SQUARE), 25656 ar_4_5: new AspectRatio(4, 5, "Vertical (4:5)", "rectangle-portrait", "vertical-4-5", VideoAspectRatio.PORTRAIT),
25657 ar_9_16: new AspectRatio(9, 16, "Vertical (9:16)", "rectangle-portrait", "vertical", VideoAspectRatio.FULL_PORTRAIT) 25658}; 25659//#endregion 25660//#region client/components/editor/Utils/EmbedVideoLandingPageUtils.ts 25661function getPosterImage(aspectRatio, defaultPosterImages) { 25662 if (aspectRatio === "vertical") return defaultPosterImages.get("vertical"); 25663 if (aspectRatio === "vertical-4-5") return defaultPosterImages.get("vertical-4-5"); 25664 return defaultPosterImages.get("horizontal"); 25665} 25666var defaultPosterImageAssetNameList = { 25667 ["horizontal"]: "Poster Image", 25668 ["vertical"]: "Poster Image Vertical", 25669 ["vertical-4-5"]: "Poster Image Vertical 4_5" 25670}; 25671function getDefaultPosterImagesPerProgram(editorProgram) { 25672 const posterImageAsset = editorProgram.programVersionDraft.assetLibrary.media.find((asset) => asset.name === defaultPosterImageAssetNameList.horizontal); 25673 const posterImageVerticalAsset = editorProgram.programVersionDraft.assetLibrary.media.find((asset) => asset.name === defaultPosterImageAssetNameList.vertical); 25674 const posterImageVertical4on5Asset = editorProgram.programVersionDraft.assetLibrary.media.find((asset) => asset.name === defaultPosterImageAssetNameList["vertical-4-5"]); 25675 const defaultPosterImages = /* @__PURE__ */ new Map(); 25676 defaultPosterImages.set("horizontal", { 25677 url: posterImageAsset?.mediaUrl ?? "", 25678 platformId: getLocalIdFromGqlId(posterImageAsset?.id) || "" 25679 }); 25680 defaultPosterImages.set("vertical", { 25681 url: posterImageVerticalAsset?.mediaUrl ?? "", 25682 platformId: getLocalIdFromGqlId(posterImageVerticalAsset?.id) || "" 25683 }); 25684 defaultPosterImages.set("vertical-4-5", { 25685 url: posterImageVertical4on5Asset?.mediaUrl ?? "", 25686 platformId: getLocalIdFromGqlId(posterImageVertical4on5Asset?.id) || "" 25687 }); 25688 return defaultPosterImages; 25689} 25690var updatePosterImageValue = (currentPosterImage, defaultPosterImages, aspectRatio) => { 25691 const defaultPlatformIds = Array.from(defaultPosterImages.values()).map((image) => image.platformId); 25692 if (currentPosterImage.platformId in defaultPlatformIds) return defaultPosterImages.get(aspectRatio) || defaultPosterImages.get("horizontal"); 25693 return currentPosterImage; 25694}; 25695//#endregion 25696//#region client/components/editor/Utils/LandingPageBuilder.ts 25697var GENERIC_POSTER_BASE_PATH = "cc-entities/d916a00b-2c5a-439a-9ac4-4bd6fec10d95/media/445473db-ded4-44c5-9e5e-63f8f397430e/"; 25698var GENERIC_POSTER_KEYS = { 25699 horizontal: `${GENERIC_POSTER_BASE_PATH}Generic_Poster_Image_Horizontal_16_9.png`, 25700 vertical: `${GENERIC_POSTER_BASE_PATH}Generic_Poster_Image_Vertical_9_16.png`, 25701 "vertical-4-5": `${GENERIC_POSTER_BASE_PATH}Generic_Poster_Image_4_5.png` 25702}; 25703var buildAssetUrl = (key) => { 25704 return `https://${import_dist$7.assetsBucketCloudFront ? import_dist$7.assetsBucketCloudFront : `${import_dist$7.assetsBucket}.s3.amazonaws.com`}/${key}`; 25705}; 25706var defaultLpConfigurationValues = { 25707 headlineText: "We've got a video for you", 25708 subheadlineText: "Click 'Play' and watch it now", 25709 isButtonVisible: false, 25710 isPrivacyPolicyVisible: false, 25711 buttonUrl: "", 25712 buttonText: "", 25713 disclaimerText: "" 25714}; 25715var newDefaultLpConfigurationValues = { 25716 ...defaultLpConfigurationValues, 25717 buttonText: "Click here" 25718}; 25719var defaultTextColorDofName = "primary_color"; 25720var defaultButtonColorDofName = "buttonText_color"; 25721var createDeltaFromInput = (text, font, color, size) => { 25722 return [{ 25723 insert: text, 25724 attributes: { 25725 size: `${size}px`, 25726 font, 25727 color 25728 } 25729 }, { 25730 insert: "\n", 25731 attributes: { align: "center" } 25732 }]; 25733}; 25734var getFontNameForClass = (name) => name?.replace(/[, \W]/g, ""); 25735var EMPTY_LP_CONFIGURATION = (programId, aspectRatio, logoMedia) => ({ 25736 version: 8, 25737 getSessionEndpointPrefix: "", 25738 background: { color: "#ffffff" }, 25739 loader: { 25740 logo: { 25741 url: "", 25742 platformId: "" 25743 }, 25744 color: "#f2f3eb" 25745 }, 25746 header: { logo: logoMedia }, 25747 main: { 25748 headline: { delta: { ops: [] } }, 25749 subheadline: { delta: { ops: [] } }, 25750 playerConfiguration: { 25751 posterImage: { 25752 url: buildAssetUrl(GENERIC_POSTER_KEYS[aspectRatio] || GENERIC_POSTER_KEYS.horizontal), 25753 platformId: "" 25754 }, 25755 analyticsToken: programId, 25756 showLogo: false, 25757 playButtonColor: "#0053e5", 25758 lockPlayerBar: false, 25759 addTranscriptButton: true, 25760 ccOnByDefault: false, 25761 largeCenterPlayIcon: false, 25762 rectangleCenterPlayIcon: false, 25763 logoOverlay: { 25764 url: "", 25765 platformId: "", 25766 displayLogo: false 25767 }, 25768 aspectRatio 25769 }, 25770 surveyConfiguration: { 25771 surveyId: "", 25772 backgroundColor: "#FFFFFF", 25773 showAt: .9 25774 }, 25775 buttons: [{ 25776 isVisible: false, 25777 url: "", 25778 color: "#f2f3eb", 25779 text: { delta: { ops: [] } } 25780 }] 25781 }, 25782 footer: { 25783 disclaimer: { delta: { ops: [] } }, 25784 showWatermark: false, 25785 privacyPolicy: { 25786 font: "RobotoRegular", 25787 isVisible: false, 25788 url: "", 25789 text: "", 25790 color: "#B2B2B2" 25791 } 25792 }, 25793 fonts: {}, 25794 standalonePlayerConfiguration: true 25795}); 25796var createInitialLpConfiguration = (input) => { 25797 return { 25798 version: 8, 25799 getSessionEndpointPrefix: "", 25800 background: { color: "#ffffff" }, 25801 loader: { 25802 logo: input.logo, 25803 color: input.colors.primary_color 25804 }, 25805 header: { logo: input.logo }, 25806 main: { 25807 headline: { delta: { "ops": createDeltaFromInput(defaultLpConfigurationValues.headlineText, input.fonts.Heading, input.colors[defaultTextColorDofName], 54) } }, 25808 subheadline: { delta: { "ops": createDeltaFromInput(defaultLpConfigurationValues.subheadlineText, input.fonts["Sub-heading"], input.colors[defaultTextColorDofName], 28) } }, 25809 playerConfiguration: { 25810 posterImage: getPosterImage(input.aspectRatio, input.defaultPosterImages), 25811 analyticsToken: input.analyticsToken, 25812 showLogo: true, 25813 playButtonColor: input.colors.primary_color, 25814 lockPlayerBar: false, 25815 addTranscriptButton: true, 25816 ccOnByDefault: false, 25817 largeCenterPlayIcon: false, 25818 rectangleCenterPlayIcon: false, 25819 logoOverlay: { 25820 ...input.logo, 25821 displayLogo: false 25822 }, 25823 aspectRatio: input.aspectRatio 25824 }, 25825 surveyConfiguration: { 25826 surveyId: "", 25827 backgroundColor: "#FFFFFF", 25828 showAt: .9 25829 }, 25830 buttons: [{ 25831 isVisible: defaultLpConfigurationValues.isButtonVisible, 25832 url: defaultLpConfigurationValues.buttonUrl, 25833 color: input.colors.primary_color, 25834 text: { delta: { "ops": createDeltaFromInput(newDefaultLpConfigurationValues.buttonText, input.fonts.Button, input.colors[defaultButtonColorDofName], 18) } } 25835 }] 25836 }, 25837 footer: { 25838 disclaimer: { delta: { "ops": [{ 25839 insert: "\n", 25840 attributes: { align: "center" } 25841 }] } }, 25842 showWatermark: true, 25843 privacyPolicy: { 25844 font: input.fonts.Footnote, 25845 isVisible: defaultLpConfigurationValues.isPrivacyPolicyVisible, 25846 url: "", 25847 text: "privacy policy", 25848 color: "#B2B2B2" 25849 } 25850 }, 25851 fonts: input.fonts, 25852 standalonePlayerConfiguration: false 25853 }; 25854}; 25855var updateConfigurationWithCurrentSettings = (configuration, input) => { 25856 const fontsNamesByFontFile = Object.entries(input.fonts).reduce((acc, [fontName, location]) => { 25857 const fontFile = location?.split("/").pop(); 25858 if (fontFile) acc.set(fontFile, fontName); 25859 return acc; 25860 }
25860, /* @__PURE__ */ new Map()); 25861 const fixFontNameForClass = (fontName) => { 25862 if ([ 25863 "headline", 25864 "subheadline", 25865 "disclaimer", 25866 "button0" 25867 ].includes(fontName)) { 25868 const fontFileFromConfiguration = configuration.fonts?.[fontName]?.split("/").pop(); 25869 return getFontNameForClass(fontFileFromConfiguration && fontsNamesByFontFile.get(fontFileFromConfiguration) || fontName); 25870 } else return getFontNameForClass(fontName); 25871 }; 25872 const fixOpFontNameForClass = (op) => { 25873 if (op?.attributes?.font) return { 25874 ...op, 25875 attributes: { 25876 ...op.attributes, 25877 font: fixFontNameForClass(op.attributes.font) 25878 } 25879 }; 25880 return op; 25881 }; 25882 return { 25883 ...configuration, 25884 main: { 25885 ...configuration.main, 25886 playerConfiguration: { 25887 ...configuration.main.playerConfiguration, 25888 posterImage: updatePosterImageValue(configuration.main.playerConfiguration.posterImage, input.defaultPosterImages, input.aspectRatio), 25889 analyticsToken: input.analyticsToken, 25890 aspectRatio: input.aspectRatio 25891 }, 25892 headline: { delta: { ops: (configuration.main.headline?.delta?.ops || []).map(fixOpFontNameForClass) } }, 25893 subheadline: { delta: { ops: (configuration.main.subheadline?.delta?.ops || []).map(fixOpFontNameForClass) } }, 25894 buttons: (configuration.main.buttons || []).map((button) => ({ 25895 ...button, 25896 text: { delta: { ops: (button?.text?.delta?.ops || []).map(fixOpFontNameForClass) } } 25897 })) 25898 }, 25899 footer: { 25900 ...configuration.footer, 25901 disclaimer: { delta: { ops: (configuration.footer?.disclaimer?.delta?.ops || []).map(fixOpFontNameForClass) } }, 25902 privacyPolicy: { 25903 ...configuration.footer?.privacyPolicy, 25904 font: fixFontNameForClass(configuration.footer?.privacyPolicy?.font) 25905 } 25906 }, 25907 fonts: { ...input.fonts } 25908 }; 25909}; 25910var getInitialLpConfigurationInput = (editorProgram) => { 25911 const fonts = editorProgram.programVersionDraft.selectedBrandConfiguration.textStyles.reduce((acc, style) => { 25912 acc[style.ccTextStyle.name] = style.fontSource === "account" ? getFontNameForClass(style.accountFont.name) : getFontNameForClass(style.ccFont.name); 25913 return acc; 25914 }, {}); 25915 const ccFonts = editorProgram.programVersionDraft.ccLibraryVersion.fonts.reduce((acc, font) => { 25916 acc[font.name] = font.webFontUrl; 25917 return acc; 25918 }, {}); 25919 const accountFonts = editorProgram.programVersionDraft.assetLibrary.fonts.reduce((acc, font) => { 25920 acc[font.name] = font.webFontUrl; 25921 return acc; 25922 }, {}); 25923 const colors = editorProgram.programVersionDraft.selectedBrandConfiguration.colors.reduce((acc, color) => { 25924 acc[color.ccDof.name] = color.color; 25925 return acc; 25926 }, {}); 25927 const logoAsset = editorProgram.programVersionDraft.selectedBrandConfiguration.logoMedia; 25928 const defaultPosterImages = getDefaultPosterImagesPerProgram(editorProgram); 25929 return { 25930 logo: { 25931 url: logoAsset?.mediaUrl ?? "", 25932 platformId: getLocalIdFromGqlId(logoAsset?.id) || "" 25933 }, 25934 colors, 25935 fonts: { 25936 ...fonts, 25937 ...ccFonts, 25938 ...accountFonts 25939 }, 25940 defaultPosterImages, 25941 analyticsToken: editorProgram.saleForceId, 25942 aspectRatio: getAspectRatio(editorProgram.programVersionDraft.aspectRatio).playerFormat() 25943 }; 25944}; 25945//#endregion 25946//#region client/components/editor/Utils/EmbedVideoPageBuilder.ts 25947var createInitialEvpConfiguration = (input) => { 25948 return { 25949 __type: "EmbedVideoPageConfiguration", 25950 version: 3, 25951 getSessionEndpointPrefix: "", 25952 loader: { color: input.colors.primary_color }, 25953 main: { 25954 playerConfiguration: { 25955 posterImage: getPosterImage(input.aspectRatio, input.defaultPosterImages), 25956 analyticsToken: input.analyticsToken, 25957 showLogo: true, 25958 playButtonColor: input.colors.primary_color, 25959 lockPlayerBar: false, 25960 addTranscriptButton: true, 25961 ccOnByDefault: false, 25962 largeCenterPlayIcon: false, 25963 rectangleCenterPlayIcon: false, 25964 logoOverlay: { 25965 ...input.logo, 25966 displayLogo: false 25967 }, 25968 aspectRatio: input.aspectRatio 25969 }, 25970 surveyConfiguration: { 25971 surveyId: "", 25972 backgroundColor: "#FFFFFF", 25973 showAt: .9 25974 } 25975 }, 25976 iframeMode: false 25977 }; 25978}; 25979var updateEvpConfigurationWithCurrentSettings = (configuration, input) => { 25980 return { 25981 ...configuration, 25982 main: { 25983 ...configuration.main, 25984 playerConfiguration: { 25985 ...configuration.main.playerConfiguration, 25986 posterImage: updatePosterImageValue(configuration.main.playerConfiguration.posterImage, input.defaultPosterImages, input.aspectRatio), 25987 analyticsToken: input.analyticsToken, 25988 aspectRatio: input.aspectRatio 25989 } 25990 } 25991 }; 25992}; 25993var getInitialEvpConfigurationInput = (editorProgram) => { 25994 const colors = editorProgram.programVersionDraft.selectedBrandConfiguration.colors.reduce((acc, color) => { 25995 acc[color.ccDof.name] = color.color; 25996 return acc; 25997 }, {}); 25998 const logoAsset = editorProgram.programVersionDraft.selectedBrandConfiguration.logoMedia; 25999 return { 26000 logo: { 26001 url: logoAsset?.mediaUrl ?? "", 26002 platformId: getLocalIdFromGqlId(logoAsset?.id) || "" 26003 }, 26004 colors, 26005 defaultPosterImages: getDefaultPosterImagesPerProgram(editorProgram), 26006 analyticsToken: editorProgram.saleForceId, 26007 aspectRatio: getAspectRatio(editorProgram.programVersionDraft.aspectRatio).playerFormat() 26008 }; 26009}; 26010//#endregion 26011//#region common/fontsUtils.ts 26012var getFontItalicVariation = (font, fonts) => { 26013 return fonts.find((f) => f.familyName === font.familyName && f.weight === font.weight && f.isBold === font.isBold && f.isItalic === !font.isItalic); 26014}; 26015var getFontFamilyDefaults = (familyName, fonts) => { 26016 const regular = getFontFamilyRegular(familyName, fonts); 26017 const italic = regular && getFontItalicVariation(regular, fonts); 26018 const bold = getFontFamilyBold(familyName, fonts); 26019 return { 26020 regular, 26021 italic, 26022 bold, 26023 boldItalic: bold && getFontItalicVariation(bold, fonts) 26024 }; 26025}; 26026var getFontFamilyRegular = (familyName, fonts) => { 26027 const sortedRegularOptions = stableSort(fonts.filter((f) => f.familyName === familyName && f.weight >= 400 && f.weight < 700 && !f.isBold && !f.isItalic), (a, b) => a.weight - b.weight); 26028 return sortedRegularOptions.length ? sortedRegularOptions[0] : void 0; 26029}; 26030var getFontFamilyBold = (familyName, fonts) => { 26031 return fonts.find((f) => f.familyName === familyName && f.weight === 700 && f.isBold && !f.isItalic); 26032}; 26033var getFontVariations = (font, fontItalicVariation, fontFamilyDefaults) => { 26034 const fontVariations = {}; 26035 if (font.isBold && font.isItalic) { 26036 fontVariations.boldItalic = font; 26037 fontVariations.bold = fontItalicVariation; 26038 } else if (font.isBold && !font.isItalic) { 26039 fontVariations.bold = font; 26040 fontVariations.boldItalic = fontItalicVariation; 26041 } else if (!font.isBold && font.isItalic) { 26042 fontVariations.italic = font; 26043 fontVariations.regular = fontItalicVariation; 26044 } else { 26045 fontVariations.regular = font; 26046 fontVariations.italic = fontItalicVariation; 26047 } 26048 return { 26049 ...fontFamilyDefaults, 26050 ...fontVariations 26051 }; 26052}; 26053var getFontVariation = (fontVariations, isBold, isItalic) => { 26054 if (isBold && isItalic) return fontVariations.boldItalic; 26055 else if (isBold && !isItalic) return fontVariations.bold; 26056 else if (!isBold && isItalic) return fontVariations.italic; 26057 else return fontVariations.regular; 26058}; 26059var convertRichTextStyleSettingToBoolean = (fontUnsetValue, setting) => { 26060 switch (setting) { 26061 case RichTextStyleSetting.TRUE: return true; 26062 case RichTextStyleSetting.FALSE: return false;
26063 default: return fontUnsetValue; 26064 } 26065}; 26066var FontsManager = class { 26067 constructor(fonts) { 26068 this.fonts = []; 26069 this.fontsById = /* @__PURE__ */ new Map(); 26070 this.fontFamiliesDefaults = /* @__PURE__ */ new Map(); 26071 this.fontsVariations = /* @__PURE__ */ new Map(); 26072 this.getFont = (fontId) => { 26073 return this.fontsById.get(fontId); 26074 }; 26075 this.getFontVariationsForFormatting = (fontId) => { 26076 if (this.isFontDoNotSupportStyling(fontId)) { 26077 const font = this.getFont(fontId); 26078 return { 26079 regular: font, 26080 italic: font, 26081 bold: font, 26082 boldItalic: font 26083 }; 26084 } 26085 const fontVariations = this.getFontVariations(fontId); 26086 return { 26087 regular: fontVariations.regular, 26088 italic: fontVariations.italic || fontVariations.regular, 26089 bold: fontVariations.bold || fontVariations.regular, 26090 boldItalic: fontVariations.boldItalic || fontVariations.bold || fontVariations.italic 26091 }; 26092 }; 26093 this.doesFontSupportItalic = (fontId) => { 26094 return !!this.getFontVariations(fontId)?.italic; 26095 }; 26096 this.doesFontSupportBold = (fontId) => { 26097 return !!this.getFontVariations(fontId)?.bold; 26098 }; 26099 this.doesFontSupportBoldItalic = (fontId) => { 26100 return !!this.getFontVariations(fontId)?.boldItalic; 26101 }; 26102 this.doesFontSupportRegular = (fontId) => { 26103 return !!this.getFontVariations(fontId)?.regular; 26104 }; 26105 this.getFontVariationUrlForRichTextStyle = (fontId, style) => { 26106 if (!fontId || !this.fontsById.has(fontId)) return; 26107 return this.getFontVariationForRichTextStyle(fontId, style).url; 26108 }; 26109 this.getFontVariationForRichTextStyle = (fontId, richTextStyle) => { 26110 if (!this.fontsById.has(fontId)) return; 26111 const font = this.fontsById.get(fontId); 26112 return getFontVariation(this.getFontVariationsForFormatting(fontId), convertRichTextStyleSettingToBoolean(font.isBold, richTextStyle.bold), convertRichTextStyleSettingToBoolean(font.isItalic, richTextStyle.italic)); 26113 }; 26114 this.getFonts = () => { 26115 return this.fonts; 26116 }; 26117 this.isFontFullySupportStyling = (fontId) => { 26118 const fontVariations = this.getFontVariations(fontId); 26119 return !!fontVariations.regular && !!fontVariations.italic && !!fontVariations.bold && !!fontVariations.boldItalic; 26120 }; 26121 this.isFontPartiallySupportStylingOnly = (fontId) => { 26122 const fontVariations = this.getFontVariations(fontId);
26123 return !this.isFontFullySupportStyling(fontId) && !!fontVariations.regular && (!!fontVariations.italic || !!fontVariations.bold); 26124 }; 26125 this.isFontDoNotSupportStyling = (fontId) => { 26126 return !this.isFontFullySupportStyling(fontId) && !this.isFontPartiallySupportStylingOnly(fontId); 26127 }; 26128 this.getFontVariations = (fontId) => { 26129 if (!this.fontsById.has(fontId)) return {}; 26130 const font = this.fontsById.get(fontId); 26131 if (!this.fontsVariations.has(font.id)) { 26132 const fontItalicVariation = getFontItalicVariation(font, this.fonts); 26133 const fontFamilyDefaults = this.getFontFamilyDefaults(font.familyName); 26134 this.fontsVariations.set(font.id, getFontVariations(font, fontItalicVariation, fontFamilyDefaults)); 26135 } 26136 return this.fontsVariations.get(font.id); 26137 }; 26138 this.getFontFamilyDefaults = (familyName) => { 26139 if (!this.fontFamiliesDefaults.has(familyName)) this.fontFamiliesDefaults.set(familyName, getFontFamilyDefaults(familyName, this.fonts)); 26140 return this.fontFamiliesDefaults.get(familyName); 26141 }; 26142 this.fonts = fonts.sort((a, b) => a.creationTime - b.creationTime); 26143 this.fonts.forEach((font) => this.fontsById.set(font.id, font)); 26144 } 26145}; 26146//#endregion 26147//#region client/graphql/graphqlGeneratedTypes/graphqlFragmentTypes.ts 26148var result = { possibleTypes: { 26149 AccountNarratorLibraryChangedPayload: [ 26150 "AccountNarratorLibraryChangedPayloadError", 26151 "AccountNarratorLibraryChangedPayloadKeepAlive", 26152 "AccountNarratorLibraryChangedPayloadPending", 26153 "AccountNarratorLibraryChangedPayloadSuccess" 26154 ], 26155 AiDraftVideoRefinedPayload: [ 26156 "AiDraftVideoRefinedPayloadError", 26157 "AiDraftVideoRefinedPayloadKeepAlive", 26158 "AiDraftVideoRefinedPayloadPending", 26159 "AiDraftVideoRefinedPayloadSuccess" 26160 ], 26161 AiGenerateVideoBriefOutput: ["AiGenerateVideoBriefOutputFailure", "AiGenerateVideoBriefOutputSuccess"], 26162 AiPreviewProgramCreatedPayload: [ 26163 "AiPreviewProgramCreatedPayloadError", 26164 "AiPreviewProgramCreatedPayloadKeepAlive", 26165 "AiPreviewProgramCreatedPayloadPending", 26166 "AiPreviewProgramCreatedPayloadSuccess" 26167 ], 26168 AiRefineDraftVideoOutput: ["AiRefineDraftVideoOutputFailure", "AiRefineDraftVideoOutputSuccess"], 26169 AiSwitchDraftVideoOutlineVersionOutput: ["AiSwitchDraftVideoOutlineVersionOutputFailure", "AiSwitchDraftVideoOutlineVersionOutputSuccess"], 26170 AiVideoAssetGeneratedPayload: [ 26171 "AiVideoAssetGeneratedPayloadError", 26172 "AiVideoAssetGeneratedPayloadKeepAlive", 26173 "AiVideoAssetGeneratedPayloadPending", 26174 "AiVideoAssetGeneratedPayloadSuccess" 26175 ], 26176 AiVideoBriefIfc: ["AiExtendedVideoBrief", "AiVideoBrief"], 26177 AiVideoFromImageGeneratedPayload: [ 26178 "AiVideoFromImageGeneratedPayloadError", 26179 "AiVideoFromImageGeneratedPayloadKeepAlive", 26180 "AiVideoFromImageGeneratedPayloadPending", 26181 "AiVideoFromImageGeneratedPayloadSuccess" 26182 ], 26183 CcAnimatedWireframeVersionPlaceholdersSettings: [ 26184 "CcAnimatedWireframeVersionBulletPlaceholdersSettings", 26185 "CcAnimatedWireframeVersionButtonPlaceholdersSettings", 26186 "CcAnimatedWireframeVersionMediaPlaceholdersSettings", 26187 "CcAnimatedWireframeVersionTextPlaceholdersSettings" 26188 ], 26189 CcLibraryVersionPublishedPayload: [ 26190 "CcLibraryVersionPublishedPayloadError", 26191 "CcLibraryVersionPublishedPayloadKeepAlive", 26192 "CcLibraryVersionPublishedPayloadPending", 26193 "CcLibraryVersionPublishedPayloadSuccess" 26194 ], 26195 CompleteFirstLoginOutput: ["CompleteFirstLoginOutputRefusal", "CompleteFirstLoginOutputSuccess"], 26196 ContributorAssetMediaUploadedPayload: [ 26197 "ContributorAssetMediaUploadedPayloadError", 26198 "ContributorAssetMediaUploadedPayloadKeepAlive", 26199 "ContributorAssetMediaUploadedPayloadPending", 26200 "ContributorAssetMediaUploadedPayloadSuccess" 26201 ], 26202 ContributorVideoSharedPayload: [ 26203 "ContributorVideoSharedPayloadError", 26204 "ContributorVideoSharedPayloadKeepAlive", 26205 "ContributorVideoSharedPayloadPending", 26206 "ContributorVideoSharedPayloadSuccess" 26207 ], 26208 ConvertFeedDataElementToDerivedOutput: ["ConvertFeedDataElementToDerivedOutputConflict", "ConvertFeedDataElementToDerivedOutputSuccess"], 26209 CreateEditorAccountUserOutput: ["CreateEditorAccountUserOutputRefusal", "CreateEditorAccountUserOutputSuccess"], 26210 CreateEditorAssetFolderOutput: ["CreateEditorAssetFolderOutputAlreadyExists", "CreateEditorAssetFolderOutputSuccess"], 26211 CreateOrUpdateEditorApplicationOutput: ["CreateOrUpdateEditorApplicationOutputConflict", "CreateOrUpdateEditorApplicationOutputSuccess"], 26212 CreateRFRVersionOutput: ["CreateRFRVersionOutputConflict", "CreateRFRVersionOutputSuccess"], 26213 CustomAvatarCreationStartedPayload: [ 26214 "CustomAvatarCreationStartedPayloadError", 26215 "CustomAvatarCreationStartedPayloadKeepAlive", 26216 "CustomAvatarCreationStartedPayloadPending", 26217 "CustomAvatarCreationStartedPayloadSuccess" 26218 ], 26219 DataLibraryImportDataUpdatedPayload: [ 26220 "DataLibraryImportDataUpdatedPayloadError", 26221 "DataLibraryImportDataUpdatedPayloadKeepAlive", 26222 "DataLibraryImportDataUpdatedPayloadPending", 26223 "DataLibraryImportDataUpdatedPayloadSuccess" 26224 ], 26225 DatabricksEntitiesResultOutput: ["DatabricksEntitiesResultOutputError", "DatabricksEntitiesResultOutputSuccess"], 26226 DeleteDataElementOutput: ["DeleteDataElementOutputRefusal", "DeleteDataElementOutputSuccess"], 26227 DeleteEditorAssetFolderOutput: ["DeleteEditorAssetFolderOutputFailure", "DeleteEditorAssetFolderOutputSuccess"], 26228 DeleteEditorAssetMediaAndFoldersOutput: ["DeleteEditorAssetMediaAndFoldersOutputRefusal", "DeleteEditorAssetMediaAndFoldersOutputSuccess"], 26229 DeleteEditorAssetMediaOutput: ["DeleteEditorAssetMediaOutputRefusal", "DeleteEditorAssetMediaOutputSuccess"], 26230 DocumentUploadedToS3Payload: [ 26231 "DocumentUploadedToS3PayloadError", 26232 "DocumentUploadedToS3PayloadKeepAlive", 26233 "DocumentUploadedToS3PayloadPending", 26234 "DocumentUploadedToS3PayloadSuccess" 26235 ], 26236 EditAiImageOutput: ["EditAiImageOutputError", "EditAiImageOutputSuccess"], 26237 EditorAssetEditedPayload: [ 26238 "EditorAssetEditedPayloadError", 26239 "EditorAssetEditedPayloadKeepAlive", 26240 "EditorAssetEditedPayloadPending", 26241 "EditorAssetEditedPayloadSuccess" 26242 ], 26243 EditorAssetMediaFromUrlUploadedPayload: [ 26244 "EditorAssetMediaFromUrlUploadedPayloadError", 26245 "EditorAssetMediaFromUrlUploadedPayloadKeepAlive", 26246 "EditorAssetMediaFromUrlUploadedPayloadPending", 26247 "EditorAssetMediaFromUrlUploadedPayloadSuccess" 26248 ], 26249 EditorAssetMediaUploadedPayload: [ 26250 "EditorAssetMediaUploadedPayloadError", 26251 "EditorAssetMediaUploadedPayloadKeepAlive", 26252 "EditorAssetMediaUploadedPayloadPending", 26253 "EditorAssetMediaUploadedPayloadSuccess" 26254 ], 26255 EditorExternalAssetMediaUploadedPayload: [ 26256 "EditorExternalAssetMediaUploadedPayloadError", 26257 "EditorExternalAssetMediaUploadedPayloadKeepAlive", 26258 "EditorExternalAssetMediaUploadedPayloadPending", 26259 "EditorExternalAssetMediaUploadedPayloadSuccess" 26260 ], 26261 EditorProgramCreatedFromPresentationPayload: [ 26262 "EditorProgramCreatedFromPresentationPayloadError", 26263 "EditorProgramCreatedFromPresentationPayloadKeepAlive", 26264 "EditorProgramCreatedFromPresentationPayloadPending", 26265 "EditorProgramCreatedFromPresentationPayloadSuccess" 26266 ], 26267 EditorProgramTranslatedPayload: [ 26268 "EditorProgramTranslatedPayloadError", 26269 "EditorProgramTranslatedPayloadKeepAlive", 26270 "EditorProgramTranslatedPayloadPending", 26271 "EditorProgramTranslatedPayloadSuccess" 26272 ], 26273 GenericDataElement: [ 26274 "CreativeDataElement", 26275 "DerivedDataElement", 26276 "FeedDataElement" 26277 ], 26278 GettyMediaMetadata: ["GettyImageMetadata", "GettyVideoMetadata"], 26279 GoogleSheetResultOutput: ["GoogleSheetResultOutputError", "GoogleSheetResultOutputSuccess"], 26280 NextRecommendedVideoCreatedPayload: [ 26281 "NextRecommendedVideoCreatedPayloadError",
26282 "NextRecommendedVideoCreatedPayloadKeepAlive", 26283 "NextRecommendedVideoCreatedPayloadPending", 26284 "NextRecommendedVideoCreatedPayloadSuccess" 26285 ], 26286 OutputProgram: ["EditorProgram", "Program"], 26287 Personalization: [ 26288 "AudiencePersonalization", 26289 "ChannelPersonalization", 26290 "TouchpointPersonalization" 26291 ], 26292 ProgramEditorPublishedPayload: [ 26293 "ProgramEditorPublishedPayloadError", 26294 "ProgramEditorPublishedPayloadKeepAlive", 26295 "ProgramEditorPublishedPayloadPending", 26296 "ProgramEditorPublishedPayloadSuccess" 26297 ], 26298 ProgramVersionNarrationRecordingStateCalculatedPayload: [ 26299 "ProgramVersionNarrationRecordingStateCalculatedPayloadError", 26300 "ProgramVersionNarrationRecordingStateCalculatedPayloadKeepAlive", 26301 "ProgramVersionNarrationRecordingStateCalculatedPayloadPending", 26302 "ProgramVersionNarrationRecordingStateCalculatedPayloadSuccess" 26303 ], 26304 RecorderMediaUploadedToS3Payload: [ 26305 "RecorderMediaUploadedToS3PayloadError", 26306 "RecorderMediaUploadedToS3PayloadKeepAlive", 26307 "RecorderMediaUploadedToS3PayloadPending", 26308 "RecorderMediaUploadedToS3PayloadSuccess" 26309 ], 26310 RequestedAvatarAnimationStatusPayload: [ 26311 "RequestedAvatarAnimationStatusPayloadError", 26312 "RequestedAvatarAnimationStatusPayloadPending", 26313 "RequestedAvatarAnimationStatusPayloadReady" 26314 ], 26315 ResolveAnimationOutput: ["ResolveAnimationOutputNotMigrated", "ResolveAnimationOutputSuccess"], 26316 ResolveAnimationsOutput: ["ResolveAnimationsOutputNotMigrated", "ResolveAnimationsOutputSuccess"], 26317 ResolveAssetOutput: ["ResolveAssetOutputNotMigrated", "ResolveAssetOutputSuccess"], 26318 ResolveAssetsOutput: ["ResolveAssetsOutputNotMigrated", "ResolveAssetsOutputSuccess"], 26319 ResolveDataTablesOutput: ["ResolveDataTablesOutputNotMigrated", "ResolveDataTablesOutputSuccess"], 26320 ResolveNarratorsOutput: ["ResolveNarratorsOutputNotMigrated", "ResolveNarratorsOutputSuccess"], 26321 SnowflakeColumnsResultOutput: ["SnowflakeColumnsResultOutputError", "SnowflakeColumnsResultOutputSuccess"], 26322 SnowflakeEntitiesResultOutput: ["SnowflakeEntitiesResultOutputError", "SnowflakeEntitiesResultOutputSuccess"], 26323 TranslationForAccountDisabledPayload: [ 26324 "TranslationForAccountDisabledPayloadError", 26325 "TranslationForAccountDisabledPayloadKeepAlive", 26326 "TranslationForAccountDisabledPayloadPending", 26327 "TranslationForAccountDisabledPayloadSuccess" 26328 ], 26329 UpdateAccountDataLibraryConnectorTypeAndMappingOutput: ["UpdateAccountDataLibraryConnectorTypeAndMappingOutputConflict", "UpdateAccountDataLibraryConnectorTypeAndMappingOutputSuccess"], 26330 UpdateAccountDataLibraryMetadataOutput: ["UpdateAccountDataLibraryMetadataOutputConflict", "UpdateAccountDataLibraryMetadataOutputSuccess"], 26331 UpdateAccountReportOutput: ["UpdateAccountReportOutputConflict", "UpdateAccountReportOutputSuccess"], 26332 UpdateAnimationOutput: ["UpdateAnimationOutputConflict", "UpdateAnimationOutputSuccess"], 26333 UpdateAssetOutput: ["UpdateAssetOutputConflict", "UpdateAssetOutputSuccess"], 26334 UpdateAudienceOutput: ["UpdateAudienceOutputConflict", "UpdateAudienceOutputSuccess"], 26335 UpdateAudienceWithDataElementsOutput: ["UpdateAudienceWithDataElementsOutputConflict", "UpdateAudienceWithDataElementsOutputSuccess"], 26336 UpdateBasicFeedDataElementOutput: ["UpdateBasicFeedDataElementOutputConflict", "UpdateBasicFeedDataElementOutputSuccess"], 26337 UpdateBcCollectionWithColorsAndTextStylesOutput: ["UpdateBcCollectionWithColorsAndTextStylesOutputConflict", "UpdateBcCollectionWithColorsAndTextStylesOutputSuccess"], 26338 UpdateCcAnimatedWireframeOutput: ["UpdateCcAnimatedWireframeOutputConflict", "UpdateCcAnimatedWireframeOutputSuccess"], 26339 UpdateCcThemeOutput: ["UpdateCcThemeOutputConflict", "UpdateCcThemeOutputSuccess"], 26340 UpdateCcWireframeOutput: ["UpdateCcWireframeOutputConflict", "UpdateCcWireframeOutputSuccess"], 26341 UpdateChannelOutput: ["UpdateChannelOutputConflict", "UpdateChannelOutputSuccess"], 26342 UpdateCreativeAssetOutput: ["UpdateCreativeAssetOutputConflict", "UpdateCreativeAssetOutputSuccess"], 26343 UpdateCreativeDataElementOutput: ["UpdateCreativeDataElementOutputConflict", "UpdateCreativeDataElementOutputSuccess"], 26344 UpdateCreativeDraftDefinitionsOutput: ["UpdateCreativeDraftDefinitionsOutputConflict", "UpdateCreativeDraftDefinitionsOutputSuccess"], 26345 UpdateCreativeDraftOutput: ["UpdateCreativeDraftOutputConflict", "UpdateCreativeDraftOutputSuccess"], 26346 UpdateCreativeNarrationRecordingOutput: ["UpdateCreativeNarrationRecordingOutputConflict", "UpdateCreativeNarrationRecordingOutputSuccess"], 26347 UpdateCreativeNarrationRecordingVersionOutput: ["UpdateCreativeNarrationRecordingVersionOutputConflict", "UpdateCreativeNarrationRecordingVersionOutputSuccess"], 26348 UpdateCreativeOutput: ["UpdateCreativeOutputConflict", "UpdateCreativeOutputSuccess"], 26349 UpdateCustomAnalyticFieldOutput: ["UpdateCustomAnalyticFieldOutputConflict", "UpdateCustomAnalyticFieldOutputSuccess"], 26350 UpdateDataTableOutput: ["UpdateDataTableOutputConflict", "UpdateDataTableOutputSuccess"], 26351 UpdateDerivedDataElementOutput: ["UpdateDerivedDataElementOutputConflict", "UpdateDerivedDataElementOutputSuccess"], 26352 UpdateEditorAccountUserOutput: ["UpdateEditorAccountUserOutputRefusal", "UpdateEditorAccountUserOutputSuccess"], 26353 UpdateEditorIsArchivedOutput: ["UpdateEditorIsArchivedOutputConflict", "UpdateEditorIsArchivedOutputSuccess"], 26354 UpdateEditorPlaceholderOutput: ["UpdateEditorPlaceholderOutputConflict", "UpdateEditorPlaceholderOutputSuccess"], 26355 UpdateEditorPlaceholdersOutput: ["UpdateEditorPlaceholdersOutputConflict", "UpdateEditorPlaceholdersOutputSuccess"], 26356 UpdateEditorProgramLifecycleStageOutput: ["UpdateEditorProgramLifecycleStageOutputConflict", "UpdateEditorProgramLifecycleStageOutputSuccess"], 26357 UpdateEditorProgramNameOutput: ["UpdateEditorProgramNameOutputConflict", "UpdateEditorProgramNameOutputSuccess"], 26358 UpdateEditorProgramThemeOutput: ["UpdateEditorProgramThemeOutputConflict", "UpdateEditorProgramThemeOutputSuccess"], 26359 UpdateEditorProgramVersionAspectRatioOutput: ["UpdateEditorProgramVersionAspectRatioOutputConflict", "UpdateEditorProgramVersionAspectRatioOutputSuccess"], 26360 UpdateEditorProgramVersionSourceLanguageOutput: ["UpdateEditorProgramVersionSourceLanguageOutputConflict", "UpdateEditorProgramVersionSourceLanguageOutputSuccess"], 26361 UpdateEditorSceneOutput: ["UpdateEditorSceneOutputConflict", "UpdateEditorSceneOutputSuccess"], 26362 UpdateEditorSceneSelectedAnimatedWireframeOutput: ["UpdateEditorSceneSelectedAnimatedWireframeOutputConflict", "UpdateEditorSceneSelectedAnimatedWireframeOutputSuccess"], 26363 UpdateEditorSelectedBcCollectionOutput: ["UpdateEditorSelectedBcCollectionOutputConflict", "UpdateEditorSelectedBcCollectionOutputSuccess"], 26364 UpdateEditorTtsFullEnablementOutput: ["UpdateEditorTtsFullEnablementOutputConflict", "UpdateEditorTtsFullEnablementOutputSuccess"], 26365 UpdateEditorViewerProfileOutput: ["UpdateEditorViewerProfileOutputConflict", "UpdateEditorViewerProfileOutputSuccess"], 26366 UpdateFeedDataElementOutput: ["UpdateFeedDataElementOutputConflict", "UpdateFeedDataElementOutputSuccess"], 26367 UpdateGoalWithKPIsOutput: ["UpdateGoalWithKPIsOutputConflict", "UpdateGoalWithKPIsOutputSuccess"], 26368 UpdateMasterAnimationGuidelineOutput: ["UpdateMasterAnimationGuidelineOutputConflict", "UpdateMasterAnimationGuidelineOutputSuccess"], 26369 UpdateMasterDataOutput: ["UpdateMasterDataOutputConflict", "UpdateMasterDataOutputSuccess"], 26370 UpdateNarrationOrderOutput: ["UpdateNarrationOrderConflict", "UpdateNarrationOrderSuccess"], 26371 UpdateNarrationOutput: ["UpdateNarrationOutputConflict", "UpdateNarrationOutputSuccess"], 26372 UpdateNarrationRecordingOutput: ["UpdateNarrationRecordingOutputConflict", "UpdateNarrationRecordingOutputSuccess"], 26373 UpdateNarrationRecordingVersionOutput: ["UpdateNarrationRecordingVersionOutputConflict", "UpdateNarrationRecordingVersionOutputSuccess"], 26374 UpdateNarrationsDtaasPrefixKeyOutput: ["UpdateNarrationsDtaasPrefixKeyOutputConflict", "UpdateNarrationsDtaasPrefixKeyOutputSuccess"], 26375 UpdateNarratorOutput: ["UpdateNarratorOutputConflict", "UpdateNarratorOutputSuccess"], 26376 UpdatePlaceholderGroupLogicOutput: ["UpdatePlaceholderGroupLogicOutputConflict", "UpdatePlaceholderGroupLogicOutputSuccess"], 26377 UpdatePresetOutput: ["UpdatePresetOutputConflict", "UpdatePresetOutputSuccess"], 26378 UpdatePrioritizedListLogicOutput: ["UpdatePrioritizedListLogicOutputConflict", "UpdatePrioritizedListLogicOutputSuccess"], 26379 UpdateProgramAndDraftOutput: ["UpdateProgramAndDraftOutputConflict", "UpdateProgramAndDraftOutputSuccess"], 26380 UpdateProgramOutput: ["UpdateProgramOutputConflict", "UpdateProgramOutputSuccess"], 26381 UpdateProgramVersionDraftOutput: ["UpdateProgramVersionDraftOutputConflict", "UpdateProgramVersionDraftOutputSuccess"], 26382 UpdateProgramVersionSnapshotOutput: ["UpdateProgramVersionSnapshotOutputConflict", "UpdateProgramVersionSnapshotOutputSuccess"], 26383 UpdateSceneEntityLogicOutput: ["UpdateSceneEntityLogicOutputConflict", "UpdateSceneEntityLogicOutputSuccess"], 26384 UpdateSceneOutput: ["UpdateSceneOutputConflict", "UpdateSceneOutputSuccess"], 26385 UpdateScenePartOutput: ["UpdateScenePartOutputConflict", "UpdateScenePartOutputSuccess"], 26386 UpdateScenePartWithAllPlaceholdersOutput: ["UpdateScenePartWithAllPlaceholdersOutputConflict", "UpdateScenePartWithAllPlaceholdersOutputSuccess"], 26387 UpdateScenePlaceholdersAndAnimatedWireframeOutput: ["UpdateScenePlaceholdersAndAnimatedWireframeOutputConflict", "UpdateScenePlaceholdersAndAnimatedWireframeOutputSuccess"], 26388 UpdateSceneWithKPIsPersonalizationsAndDataElementsOutput: ["UpdateSceneWithKPIsPersonalizationsAndDataElementsOutputConflict", "UpdateSceneWithKPIsPersonalizationsAndDataElementsOutputSuccess"], 26389 UpdateStoryForBuilderOutput: ["UpdateStoryForBuilderOutputConflict", "UpdateStoryForBuilderOutputSuccess"], 26390 UpdateStoryForFrameworkOutput: ["UpdateStoryForFrameworkOutputConflict", "UpdateStoryForFrameworkOutputSuccess"], 26391 UpdateStoryWithAllDecisionPointsOutput: ["UpdateStoryWithAllDecisionPointsOutputConflict", "UpdateStoryWithAllDecisionPointsOutputSuccess"], 26392 UpdateStoryWithDecisionPointsOutput: ["UpdateStoryWithDecisionPointsOutputConflict", "UpdateStoryWithDecisionPointsOutputSuccess"], 26393 UpdateStoryWithNewSceneOutput: ["UpdateStoryWithNewSceneOutputConflict", "UpdateStoryWithNewSceneOutputSuccess"], 26394 UpdateStoryWithReachAndScenesOutput: ["UpdateStoryWithReachAndScenesOutputConflict", "UpdateStoryWithReachAndScenesOutputSuccess"], 26395 UpdateSurveyOutput: ["UpdateSurveyOutputConflict", "UpdateSurveyOutputSuccess"], 26396 UpdateTouchpointOutput: ["UpdateTouchpointOutputConflict", "UpdateTouchpointOutputSuccess"], 26397 VideoDraftCreatedPayload: [ 26398 "VideoDraftCreatedPayloadError", 26399 "VideoDraftCreatedPayloadKeepAlive", 26400 "VideoDraftCreatedPayloadPending", 26401 "VideoDraftCreatedPayloadSuccess" 26402 ] 26403} }; 26404//#endregion 26405//#region client/utils/timedActivityReportingUtils.ts 26406init_moment(); 26407function reportTimedActivity(name, startTime, endTime, options = {}) { 26408 const activityProps = options.props || {}; 26409 const eventName = "Timed Activity"; 26410 const eventData = { 26411 name, 26412 startTime: startTime.toString(), 26413 endTime: endTime.toString(), 26414 duration: (endTime - startTime).toString(), 26415 ...Object.entries(activityProps).reduce((acc, [k, v]) => { 26416 return { 26417 ...acc, 26418 [`activity_${k}`]: v.toString() 26419 }; 26420 }, {}) 26421 }; 26422 PendoService.getInstance().trackEvent(eventName, eventData); 26423} 26424function startActivity(name) { 26425 const startTime = Date.now(); 26426 return (options = {}) => { 26427 reportTimedActivity(name, startTime, Date.now(), options); 26428 }; 26429} 26430function TimedComponent(props) { 26431 const { name, children } = props; 26432 (0, import_react.useEffect)(() => { 26433 const endActivity = startActivity(name); 26434 return () => { 26435 endActivity(); 26436 }; 26437 }, [name]); 26438 return import_react.createElement(import_react.Fragment, null, children); 26439} 26440var lastReportedTime = 0; 26441function reportPageContentLoad() { 26442 const changedAt = Date.now(); 26443 const lastLocation = window["data-lastLocation"]; 26444 const target = pagePathToName(lastLocation.currentPathname); 26445 if (!target) return; 26446 if (lastReportedTime === lastLocation.changedAt) return; 26447 PendoService.getInstance().trackEvent("Page content loaded post navigation", { 26448 origin: lastLocation.lastPathname ? pagePathToName(lastLocation.lastPathname) ?? "Other Page" : "Direct Navigation", 26449 target, 26450 duration: (changedAt - lastLocation.changedAt).toString(), 26451 dateTime: hooks().toISOString(true), 26452 fullStoryURL: window?.FS?.getCurrentSessionURL?.(true) 26453 }); 26454 lastReportedTime = lastLocation.changedAt; 26455} 26456//#endregion 26457//#region client/logic/globals/globalPerformance.ts 26458var globalPerformance = { current: null }; 26459var startGlobalPerformance = (taskName) => { 26460 globalPerformance.current = { 26461 taskName, 26462 startTime: Date.now(), 26463 networkActions: [] 26464 }; 26465}; 26466var endGlobalPerformance = () => { 26467 if (!globalPerformance.current) return; 26468 summarizeGlobalPerformance(); 26469}; 26470var summarizeGlobalPerformance = () => { 26471 const currentGlobalPerformance = globalPerformance.current; 26472 currentGlobalPerformance.endTime = Date.now(); 26473 currentGlobalPerformance.totalDuration = currentGlobalPerformance.endTime - currentGlobalPerformance.startTime; 26474 currentGlobalPerformance.clientWaitDuration = waitingTimeAccumulator(currentGlobalPerformance.startTime, currentGlobalPerformance.endTime, currentGlobalPerformance.networkActions); 26475 currentGlobalPerformance.clientWorkDuration = currentGlobalPerformance.totalDuration - currentGlobalPerformance.clientWaitDuration; 26476 currentGlobalPerformance.networkActionsKey = parseNetworkActionsKey(currentGlobalPerformance.networkActions); 26477 reportInfoToSplunkRedux("Task duration", currentGlobalPerformance); 26478 globalPerformance.current = null; 26479}; 26480var addNetworkActionPerformance = (rp) => { 26481 reportTimedActivity(`${rp.kind}: ${rp.name}`, rp.startTime, rp.endTime, { props: { 26482 serverDuration: rp.serverDuration.toString(), 26483 payload: rp.payload.toString() 26484 } }); 26485 const currentGlobalPerformance = globalPerformance.current; 26486 if (!currentGlobalPerformance) return; 26487 const totalDuration = rp.endTime - rp.startTime; 26488 let networkDuration; 26489 let networkBandwidth; 26490 if (rp.serverDuration) { 26491 networkDuration = totalDuration - rp.serverDuration; 26492 if (rp.payload) networkBandwidth = rp.payload / networkDuration; 26493 } 26494 const requestPerformance = { 26495 kind: rp.kind, 26496 name: rp.name, 26497 startTime: rp.startTime, 26498 endTime: rp.endTime, 26499 payload: rp.payload, 26500 totalDuration, 26501 serverDuration: rp.serverDuration, 26502 networkDuration, 26503 networkBandwidth 26504 }; 26505 currentGlobalPerformance.networkActions.push(requestPerformance); 26506}; 26507/** 26508* Accumulates waiting timings from network actions 26509* 26510* @param startTime global performance start-time 26511* @param endTime global performance end-time 26512* @param networkActions list of network actions 26513*/ 26514var waitingTimeAccumulator = (startTime, endTime, networkActions) => { 26515 if (!networkActions || Number.isNaN(startTime) || Number.isNaN(endTime)) return 0; 26516 return networkActions.sort((action1, action2) => action2.startTime > action1.startTime ? -1 : 1).reduce((acc, networkAction) => { 26517 const actionStartTime = Math.max(acc.indexTime, networkAction.startTime); 26518 const actionEndTime = Math.min(endTime, networkAction.endTime); 26519 const actionNonOverlappingDuration = Math.max(actionEndTime - actionStartTime, 0); 26520 acc.duration += actionNonOverlappingDuration; 26521 acc.indexTime = Math.max(acc.indexTime, actionEndTime); 26522 return acc; 26523 }, { 26524 duration: 0, 26525 indexTime: startTime 26526 }).duration; 26527}; 26528var parseNetworkActionsKey = (networkActions) => { 26529 return networkActions.map((na) => na.name).sort().toString(); 26530}; 26531//#endregion 26532//#region client/apollo/typePolicies.ts 26533/** 26534* On the Editor initial load, we make a query to fetch all scenes: 26535* editorProgram(id: $programId) { 26536programVersion(id: $programVersionId) { 26537scenes { 26538...EditorScene 26539} 26540} 26541} 26542* But in some hooks we wish to get a single scene by id: 26543* editorScene(id: $sceneId) @client { 26544...EditorScene 26545} 26546} 26547* So, we need to tell the cache that whenever someone asks for scene(id), it should first look if it's already cached under a different reference. 26548* We can do that with typePolicies. 26549* 26550* same goes for placeholders :) 26551* 26552* More info: https://www.apollographql.com/docs/react/caching/advanced-topics/#cache-redirects-using-field-policy-read-functions 26553* **/ 26554var typePolicies = { 26555 AdsSpaceChildRow: { keyFields: false }, 26556 AdsSpaceEntityRow: { keyFields: false }, 26557 Query: { fields: { 26558 localEditorScene(_, { args, toReference }) { 26559 return toReference({ 26560 __typename: "EditorScene", 26561 id: args.id 26562 }); 26563 }, 26564 localEditorPlaceholder(_, { args, toReference }) { 26565 return toReference(
26565{ 26566 __typename: "EditorPlaceholder", 26567 id: args.id 26568 }); 26569 }, 26570 localEditorBrand(_, { args, toReference }) { 26571 return toReference({ 26572 __typename: "BrandConfigurationCollection", 26573 id: args.id 26574 }); 26575 }, 26576 localEditorViewerProfile(_, { args, toReference }) { 26577 return toReference({ 26578 __typename: "ViewerProfile", 26579 id: args.id 26580 }); 26581 }, 26582 userSettings(_, { args, toReference }) { 26583 return toReference({ 26584 __typename: "UserSettings", 26585 id: args.id 26586 }); 26587 }, 26588 storyTemplate(_, { args, toReference }) { 26589 return toReference({ 26590 __typename: "EditorApplication", 26591 id: args.programVersionId 26592 }); 26593 }, 26594 acquiaAssets: { 26595 keyArgs: [ 26596 "categoryPath", 26597 "searchTerm", 26598 "sortBy", 26599 "sortDirection", 26600 "mediaType", 26601 "orientation" 26602 ], 26603 merge(existing, incoming, { args }) { 26604 const mergedAssets = existing?.assets ? existing.assets.slice(0) : []; 26605 const { pageNumber } = args; 26606 if (incoming?.assets) for (let i = 0; i < incoming.assets.length; ++i) mergedAssets[pageNumber * 50 + i] = incoming.assets[i]; 26607 return { 26608 __typename: "AcquiaAssetsOutput", 26609 resultCount: incoming?.resultCount ?? existing?.resultCount ?? 0, 26610 assets: mergedAssets 26611 }; 26612 } 26613 }, 26614 gettySearchMetadata: { 26615 keyArgs: [ 26616 "includeImages", 26617 "includeVideos", 26618 "searchTerm", 26619 "orientation", 26620 "minClipDuration", 26621 "maxClipDuration", 26622 "sortOrder" 26623 ], 26624 merge(existing, incoming, { args }) { 26625 const mergedAssets = existing?.assets ? existing.assets.slice(0) : []; 26626 const { pageNumber } = args; 26627 if (incoming?.assets) for (let i = 0; i < incoming.assets.length; ++i) mergedAssets[pageNumber * 50 + i] = incoming.assets[i]; 26628 return { 26629 __typename: "GettySearchMetadataOutput", 26630 resultCount: incoming?.resultCount ?? existing?.resultCount ?? 0, 26631 assets: mergedAssets 26632 }; 26633 } 26634 }, 26635 editorNarrationDurationBySsml: { merge(existing, incoming) { 26636 if (incoming) return incoming; 26637 else return existing; 26638 } } 26639 } } 26640}; 26641//#endregion 26642//#region client/components/editor/Nooks/Account/account.ts 26643var setLocalEditorAccountDataVersion = (accountDataVersion) => { 26644 localEditorAccountDataVersion(accountDataVersion); 26645}; 26646var getLocalEditorAccountDataVersion = () => { 26647 return localEditorAccountDataVersion(); 26648}; 26649var setEditorAccountDetails = (accountName, accountId, accountType) => { 26650 localEditorAccountNameVar(accountName); 26651 localEditorAccountIdVar(accountId); 26652 localEditorAccountTypeVar(accountType); 26653}; 26654var getEditorAccountId = () => { 26655 return localEditorAccountIdVar(); 26656}; 26657var loadAccountCcLibraryVersion = async () => { 26658 const client = getApolloClient(); 26659 const accountCcLibraryResult = await client.query({ query: AccountCcLibraryVersionDocument }); 26660 const libraryId = accountCcLibraryResult?.data?.currentAccount?.ccLibraryVersion?.library?.id; 26661 const libraryVersionId = accountCcLibraryResult?.data?.currentAccount?.ccLibraryVersion?.id; 26662 if (libraryId && libraryVersionId) return client.query({ 26663 query: CcLibraryVersionDocument, 26664 variables: { 26665 libraryId, 26666 libraryVersionId 26667 } 26668 }); 26669 else return null; 26670}; 26671var getAccountEditorLevelBrandData = () => { 26672 return getApolloClient().query({ 26673 query: EditorAccountLevelDataBrandsDocument, 26674 variables: {} 26675 }); 26676}; 26677var getAccountEditorLevelMusicData = () => { 26678 return getApolloClient().query({ 26679 query: EditorAccountLevelDataMusicDocument, 26680 variables: {} 26681 }); 26682}; 26683var getAccountEditorLevelAvatarsData = () => { 26684 return getApolloClient().query({ 26685 query: EditorAccountLevelDataAvatarsDocument, 26686 variables: {} 26687 }); 26688}; 26689var getAccountEditorLevelNarratorData = () => { 26690 return getApolloClient().query({ 26691 query: EditorAccountLevelDataNarratorsDocument, 26692 variables: {} 26693 }); 26694}; 26695var loadAccountEditorLevelFontsData = () => { 26696 const { watchQuery } = getApolloClient(); 26697 return watchQuery({ query: EditorAccountLevelDataFontsDocument }).subscribe(({ data }) => { 26698 updateAssetLibraryFontsManagerVar(data.editorAccountLevelData.assetLibraryVersion?.fonts); 26699 }).unsubscribe; 26700}; 26701var reportNumSelectedGetLinksItems = (numItems) => { 26702 const eventName = "Selected Get Links Items"; 26703 const eventData = { numItems: numItems?.toString() || "N/A" }; 26704 PendoService.getInstance().trackEvent(eventName, eventData); 26705}; 26706//#endregion 26707//#region client/components/newNav/nooks/model.ts 26708var getFeatureFlags = () => featureFlagsVar(); 26709var getUserData = () => userDataVar(); 26710var setAccessDenied = (isDenied) => accessDeniedVar(isDenied); 26711//#endregion 26712//#region client/components/newNav/nooks/featureFlags.ts 26713var isFeatureEnabled = (featureFlagId, overridingProgramId, overrideAccountId) => { 26714 const featureFlags = getFeatureFlags(); 26715 const featureFlagObj = featureFlags && featureFlags[featureFlagId]; 26716 if (!featureFlagObj) return false;
26717 const accountId = overrideAccountId ?? getAccountIdFromPath(); 26718 if (featureFlagObj.excludedAccounts.some((account) => account.accountId === accountId)) return !featureFlagObj.defaultValue; 26719 const { program: programIdFromUrl } = UrlUtils.getAccountAndProgramFromPath(); 26720 const programId = overridingProgramId ?? programIdFromUrl; 26721 const programKey = `${accountId}/${programId}`; 26722 const isProgramExcluded = featureFlagObj.excludedPrograms.some((program) => program === programKey || program.dynamoUniqueId === programKey || program.postgresUniqueId === programKey); 26723 return programId && isProgramExcluded ? !featureFlagObj.defaultValue : featureFlagObj.defaultValue; 26724}; 26725//#endregion 26726//#region client/apollo/client.ts 26727init_ApolloClient(), init_ApolloLink(), init_inMemoryCache(), init_module(), init_split(); 26728init_utilities(); 26729var import_timeoutLink = /* @__PURE__ */ __toESM(require_timeoutLink()); 26730var import_dist$2 = require_dist$5(); 26731var APOLLO_OPERATION_NAME_HEADER = "x-apollo-operation-name"; 26732var APOLLO_FEDERATION_INCLUDE_TRACE_HEADER = "apollo-federation-include-trace"; 26733var APOLLO_FEDERATION_INCLUDE_TRACE_VALUE = "ftv1"; 26734var APOLLO_CACHE_LIMIT_EXECUTE_SELECTION_SET = 2e5; 26735var APOLLO_CACHE_LIMIT_EXECUTE_SUB_SELECTED_ARRAY = 5e4; 26736var APOLLO_CACHE_LIMIT_MAYBE_BROADCAST_WATCH = 1e4; 26737var CLIENT_CACHE_ITEM_LIMIT_URL_PARAM = "clientCacheItemLimit"; 26738var applyApolloCacheSizeLimits = () => { 26739 const override = Number(new URLSearchParams(window.location.search).get(CLIENT_CACHE_ITEM_LIMIT_URL_PARAM)); 26740 const useOverride = override > 0; 26741 cacheSizes["inMemoryCache.executeSelectionSet"] = useOverride ? override : APOLLO_CACHE_LIMIT_EXECUTE_SELECTION_SET; 26742 cacheSizes["inMemoryCache.executeSubSelectedArray"] = useOverride ? override : APOLLO_CACHE_LIMIT_EXECUTE_SUB_SELECTED_ARRAY; 26743 cacheSizes["inMemoryCache.maybeBroadcastWatch"] = useOverride ? override : APOLLO_CACHE_LIMIT_MAYBE_BROADCAST_WATCH; 26744}; 26745var StudioModeError = class extends Error { 26746 constructor(currentMode) { 26747 super(`Action not allowed in mode ${currentMode}`); 26748 this.name = this.constructor.name; 26749 Error.captureStackTrace(this, this.constructor); 26750 } 26751}; 26752var CLIENT_VERSION = "8.0.25919"; 26753var apolloClientInstance; 26754var getApolloCacheSizesSnapshot = () => { 26755 const internals = apolloClientInstance?.getMemoryInternals?.(); 26756 if (!internals) return null; 26757 const limits = internals.limits; 26758 const sizes = internals.sizes?.inMemoryCache; 26759 return { 26760 executeSelectionSet: { 26761 size: sizes?.executeSelectionSet ?? null, 26762 limit: limits?.["inMemoryCache.executeSelectionSet"] ?? null 26763 }, 26764 executeSubSelectedArray: { 26765 size: sizes?.executeSubSelectedArray ?? null, 26766 limit: limits?.["inMemoryCache.executeSubSelectedArray"] ?? null 26767 }, 26768 maybeBroadcastWatch: { 26769 size: sizes?.maybeBroadcastWatch ?? null, 26770 limit: limits?.["inMemoryCache.maybeBroadcastWatch"] ?? null 26771 } 26772 }; 26773}; 26774var getApolloClient = () => { 26775 if (!apolloClientInstance) throw new Error("Apollo client is not initialized"); 26776 return apolloClientInstance; 26777}; 26778var initApolloClient = ({ authServiceGetterPromise, builderModeRetriever, reportError, getActiveAccountId, getActiveAccountName, getProgramNameFromPath }) => { 26779 if (apolloClientInstance) return; 26780 const defaultAllowedModes = (operation) => { 26781 let definitions = operation && operation.query && operation.query.definitions; 26782 if (definitions && definitions.some((definition) => definition.kind === "OperationDefinition" && definition.operation === "mutation")) return [EDITING_MODE]; 26783 return [EDITING_MODE, STAGE_MODE]; 26784 }; 26785 const createStudioModeLink = (builderModeRetriever) => { 26786 return new ApolloLink((operation, forward) => { 26787 const allowedModes = operation.getContext().allowedModes || defaultAllowedModes(operation); 26788 const currentMode = builderModeRetriever.getMode(); 26789 if (allowedModes.includes(currentMode)) return forward(operation); 26790 return new Observable((observer) => observer.error(new StudioModeError(currentMode))); 26791 }); 26792 }; 26793 const createAccountDataVersionLink = () => { 26794 return new ApolloLink((operation, forward) => { 26795 return forward(operation).map((response) => { 26796 const { response: { headers } } = operation.getContext(); 26797 const accountVersion = headers.get(X_SSKY_ACCOUNT_DATA_VERSION_HEADER); 26798 if (accountVersion) setLocalEditorAccountDataVersion(accountVersion); 26799 return response; 26800 }); 26801 }); 26802 }; 26803 const createReportPerformanceLink = () => { 26804 return new ApolloLink((operation, forward) => { 26805 const startTime = Date.now(); 26806 return forward(operation).map((data) => { 26807 const headers = operation.getContext()?.response?.headers; 26808 const serverDuration = Number(headers?.get(X_SSKY_SERVER_TIMING_HEADER)); 26809 const payload = Number(headers?.get(X_SSKY_PAYLOAD_SIZE_HEADER)
26809); 26810 addNetworkActionPerformance({ 26811 kind: "GraphQL", 26812 name: operation.operationName, 26813 startTime, 26814 endTime: Date.now(), 26815 serverDuration: !Number.isNaN(serverDuration) ? serverDuration : 0, 26816 payload: !Number.isNaN(payload) ? payload : 0 26817 }); 26818 return data; 26819 }); 26820 }); 26821 }; 26822 const createAuthLink = () => setContext(async (operation, prevContext) => { 26823 const token = await (await authServiceGetterPromise).getUserAccessToken(); 26824 let studioHeaders = { 26825 [studioApiVersionHeaderName]: 69 .toString(), 26826 Authorization: token ? `Bearer ${token}` : "", 26827 [APOLLO_FEDERATION_INCLUDE_TRACE_HEADER]: APOLLO_FEDERATION_INCLUDE_TRACE_VALUE, 26828 "account-id": getActiveAccountId(), 26829 "account-name": gBase64.encode(getActiveAccountName() || ""), 26830 "legacy-program-id": getProgramNameFromPath() 26831 }; 26832 const editorAccountDataVersion = getLocalEditorAccountDataVersion(); 26833 const isVideoPage = import_dist$9.newNavVideoPagePath.match(window.location.pathname); 26834 const isEditor = import_dist$9.newNavEditorPath.match(window.location.pathname); 26835 if ((isVideoPage || isEditor) && editorAccountDataVersion) studioHeaders[X_SSKY_ACCOUNT_DATA_VERSION_HEADER] = editorAccountDataVersion; 26836 const operationName = operation?.operationName; 26837 if (operationName) studioHeaders[APOLLO_OPERATION_NAME_HEADER] = operationName; 26838 return { 26839 ...prevContext, 26840 headers: { 26841 ...prevContext.headers, 26842 ...studioHeaders 26843 } 26844 }; 26845 }); 26846 const createFSLink = () => setContext((_, prevContext) => { 26847 const fullStorySessionURL = window && window.FS && typeof window.FS.getCurrentSessionURL === "function" && window.FS.getCurrentSessionURL(true); 26848 let studioHeaders = { "x-ssky-fsurl": fullStorySessionURL ? Buffer.from(fullStorySessionURL).toString("base64") : "" }; 26849 return { 26850 ...prevContext, 26851 headers: { 26852 ...prevContext.headers, 26853 ...studioHeaders 26854 } 26855 }; 26856 }); 26857 const createClientVersionLink = () => setContext((_, prevContext) => { 26858 const clientVersionHeader = {}; 26859 clientVersionHeader[studioClientVersionHeaderName] = CLIENT_VERSION; 26860 return { 26861 ...prevContext, 26862 headers: { 26863 ...prevContext.headers, 26864 ...clientVersionHeader 26865 } 26866 }; 26867 }); 26868 const handleErrorInEditorContext = (gqlErrorObj) => { 26869 if (!gqlErrorObj.graphQLErrors && gqlErrorObj.networkError) if (isFeatureEnabled(featureFlagConst._DISABLE_CLIENT_OFFLINE_DETECTION)) { 26870 notifyGeneralError(); 26871 handleError({ error: gqlErrorObj }).catch(() => {}); 26872 localEditorCloudIndicatorVar(CloudIndicatorState.ACTION_ERROR); 26873 } else { 26874 setNoInternetNotification(); 26875 handleError({ error: gqlErrorObj }).catch(() => {}); 26876 localEditorCloudIndicatorVar(CloudIndicatorState.NETWORK_ERROR); 26877 } 26878 else { 26879 if ((gqlErrorObj.graphQLErrors ?? []).some((error) => getSskyErrorCodeFromGqlError(error) === SskyErrorCode.AccessDenied)) { 26880 setAccessDenied(true); 26881 return; 26882 } 26883 const firstGqlError = gqlErrorObj.graphQLErrors[0]; 26884 handleEditorError({ 26885 error: firstGqlError, 26886 sskyCode: getSskyErrorCodeFromGqlError(firstGqlError) 26887 }); 26888 if (import_dist$9.newNavEditorPath.match(window.location.pathname)) localEditorCloudIndicatorVar(CloudIndicatorState.ACTION_ERROR); 26889 } 26890 }; 26891 const handleErrorInNonEditorContext = (gqlErrorObj, showErrorToUser) => { 26892 let userErrorMessage; 26893 if (showErrorToUser) if (gqlErrorObj.networkError && gqlErrorObj.networkError instanceof StudioModeError) userErrorMessage = gqlErrorObj.networkError.message; 26894 else userErrorMessage = "An error occurred. If the problem persists, please contact support."; 26895 reportError(gqlErrorObj, showErrorToUser, userErrorMessage); 26896 }; 26897 const createErrorLink = () => onError(({ graphQLErrors, networkError, operation }) => { 26898 const gqlErrorObj = { 26899 operationData: { 26900 name: operation.operationName, 26901 variables: operation.variables 26902 }, 26903 graphQLErrors, 26904 networkError 26905 }; 26906 const showErrorToUser = !gqlErrorObj.operationData.variables[IGNORE_SERVER_ERRORS]; 26907 if (isNewNav) handleErrorInEditorContext(gqlErrorObj); 26908 else handleErrorInNonEditorContext(gqlErrorObj, showErrorToUser); 26909 }); 26910 const createTerminatingSplitLink = (httpLink) => { 26911 return split(({ query }) => { 26912 const definition = getMainDefinition(query); 26913 return definition.kind === "OperationDefinition" && definition.operation === "subscription"; 26914 }, new GraphQLWsLink(createClient({ 26915 url: `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/subscriptions`, 26916 shouldRetry: (errOrCloseEvent) => { 26917 return true; 26918 }, 26919 retryWait: async () => { 26920 await (0, import_dist$2.sleepMs)(2e3); 26921 }, 26922 retryAttempts: 1800,
26923 connectionParams: () => authServiceGetterPromise.then((authService) => { 26924 return authService.getUserAccessToken?.(); 26925 }).then((authToken) => ({ 26926 "studio-client-name": "Studio", 26927 [studioApiVersionHeaderName]: 69 .toString(), 26928 authorization: authToken ? `Bearer ${authToken}` : "", 26929 "account-id": getActiveAccountId() 26930 })) 26931 })), httpLink); 26932 }; 26933 const createInstance = () => { 26934 applyApolloCacheSizeLimits(); 26935 const timeoutLink = new import_timeoutLink.default(-1); 26936 const authLink = createAuthLink(); 26937 const fsLink = createFSLink(); 26938 const errorLink = createErrorLink(); 26939 const studioModeLink = createStudioModeLink(builderModeRetriever); 26940 const accountDataVersionLink = createAccountDataVersionLink(); 26941 const reportPerformanceLink = createReportPerformanceLink(); 26942 const uploadLink = (0, import_createUploadLink.default)(); 26943 const clientVersionLink = createClientVersionLink(); 26944 const httpLink = ApolloLink.from([ 26945 timeoutLink, 26946 authLink, 26947 fsLink, 26948 clientVersionLink, 26949 errorLink, 26950 studioModeLink, 26951 accountDataVersionLink, 26952 reportPerformanceLink, 26953 uploadLink 26954 ]); 26955 const options = { 26956 link: createTerminatingSplitLink(httpLink), 26957 cache: new InMemoryCache({ 26958 possibleTypes: result.possibleTypes, 26959 typePolicies 26960 }), 26961 name: "Studio", 26962 version: CLIENT_VERSION 26963 }; 26964 if ({}.JEST_WORKER_ID !== void 0) { 26965 options.defaultOptions = { query: { 26966 fetchPolicy: "cache-only", 26967 errorPolicy: "all" 26968 } }; 26969 options.link = httpLink; 26970 } 26971 return new ApolloClient(options); 26972 }; 26973 apolloClientInstance = createInstance(); 26974}; 26975//#endregion 26976//#region client/components/editor/State/localState.ts 26977init_lib(), init_reactiveVars(); 26978var import_dist$1 = require_dist$6(); 26979var RESTRICTED_ACTION_DIALOG_DEFAULT_DATA = { 26980 open: false, 26981 messageTitle: "", 26982 message: "" 26983}; 26984var localEditorPermissionsVar = makeVar({}); 26985var localEditorIsInReviewVar = makeVar(false); 26986var localEditorAutoOpenReviewPanelVar = makeVar(false); 26987var localEditorCommentsPanelOpenVar = makeVar(false); 26988var localEditorUnresolvedCommentsCountVar = makeVar(0); 26989var localEditorPublishedUnresolvedCommentCountVar = makeVar(0); 26990var localEditorPendingApprovalActionVar = makeVar(false); 26991var localEditorReviewPanelModeVar = makeVar("review"); 26992var localEditorIsPreviewDialogOpenVar = makeVar(false); 26993var localEditorPreviewDialogTypeVar = makeVar(PreviewDialogType.Video); 26994var localEditorPreviewDialogScenesVar = makeVar([]); 26995var localEditorAccountIdVar = makeVar(""); 26996var localEditorAccountTypeVar = makeVar(""); 26997var localEditorAccountDataVersion = makeVar(""); 26998var localEditorAccountNameVar = makeVar(""); 26999var localEditorProcessedFilesVar = makeVar([]); 27000var localEditorNotificationDataVar = makeVar({ 27001 message: "", 27002 type: "neutral", 27003 isOpen: false 27004}); 27005var localEditorCloudIndicatorVar = makeVar(CloudIndicatorState.REGULAR); 27006var localEditorPublishStateVar = makeVar(null); 27007var localEditorIsLpChangingActiveState = makeVar(false); 27008var localEditorIsSelectedSceneIsNewVar = makeVar(false); 27009var localVideosToIgnoreUserIntentDialog = makeVar(/* @__PURE__ */ new Set()); 27010var localEditorDocToVideoCreateSuccessSnackbarState = makeVar(null); 27011var localEditorLivePreviewPendingSetVar; 27012var localEditorSelectedFramePerSceneVar = makeVar({}); 27013var localEditorSelectedPlaceholderIdsVar; 27014var localEditorSelectedPlaceholderOpenEditVar; 27015var localEditorSelectedNarrationPlaceholderOpenEditVar; 27016var localEditorSelectedSceneIdVar = makeVar(null); 27017var localBrandByAudienceFallbackIdVar; 27018var localEditedBrandIdVar; 27019var localIsNewBrandVar; 27020var localDeleteCandidateBrandIdVar; 27021var localEditedBrandLogoAssetInfoVar; 27022var localEditedBrandColorsVar; 27023var localEditedBrandTextStylesVar; 27024var localEditedButtonShapeValueVar; 27025var localEditorWireframeThemeSupport; 27026var localEditorSelectedAudioPreview; 27027var localEditorRaasPlaceholderData; 27028var localEditorSelectedLibraryVar = makeVar({ 27029 library: null, 27030 opener: null 27031}); 27032var localEditorPreSelectedLibrary = makeVar(null); 27033var localEditorProgramNameVar; 27034var localEditorDataConnectorEnabledVar = makeVar(false); 27035var localEditorLandingPageConfigurationVar = makeVar(null); 27036var localEditorInitialLandingPageConfigurationVar = makeVar(null); 27037var localEditorEmbedVideoPageConfigurationVar = makeVar((0, import_dist$1.getEmptyEvpConfiguration)()); 27038var localEditorInitialEmbedVideoPageConfigurationVar = makeVar((0, import_dist$1.getEmptyEvpConfiguration)()); 27039var cCFontsManagerVar = makeVar(null); 27040var assetLibraryFontsManagerVar = makeVar(null); 27041var localEditorIsPreviewM2Layouts = makeVar(false); 27042var localEditorBrandByAudienceIndicatorVar = makeVar(false); 27043var localEditorUploadedGettyUrlsVar = makeVar([]); 27044var localEditorMediaLibraryByAudienceCaseIndex = makeVar(null); 27045var localEditorMediaDragAndDropSnackbarState = makeVar(EditorMediaDragAndDropSnackbarState.CLOSED); 27046var localEditorShowDropHintFromMediaLibrary = makeVar(false); 27047var localEditorMediaLibraryDraggingFromFolderId = makeVar(null); 27048var localRestrictedActionDialog = makeVar(RESTRICTED_ACTION_DIALOG_DEFAULT_DATA); 27049var localEditorMediaLibraryGridColumns = makeVar(2); 27050var localEditorDraggedItemTypeVar = makeVar(null); 27051var localAiMediaGenerationDialogInfo = makeVar(null); 27052var localEditorActiveCueDialogVar = makeVar(null); 27053var localEditorAllCuesDialogVar = makeVar(null); 27054var localEditorCueConnectFromPlaceholderIdVar = makeVar(null); 27055var localEditorShowReplaceAvatarHint = makeVar(false); 27056var localEditorShowPlaceholderLibrary = makeVar(false); 27057var localEditorDisplayLanguage = makeVar(null); 27058var localLivePreviewDisplayLanguage = makeVar(null); 27059var localEditorSlidesToVideoBrandDisclaimers = makeVar({}); 27060var localEditorDockedMediaLibrarySearchValue = makeVar(""); 27061var localEditorDockedMediaLibraryFilterMediaType = makeVar(MediaLibraryFilterMediaType.ALL); 27062var localEditorDockedMediaLibraryFilterMediaSource = makeVar(MediaLibraryFilterMediaSource.ALL); 27063var localEditorDockedMediaLibraryFilterStockOrientation = makeVar(MediaLibraryFilterMediaOrientation.ALL); 27064var localEditorDockedMediaLibraryFilterMinVideoDuration = makeVar(0); 27065var localEditorDockedMediaLibraryFilterMaxVideoDuration = makeVar(600); 27066var localEditorDockedMediaLibrarySortBy = makeVar(MediaLibrarySortBy.LAST_ADDED); 27067var localEditorDockedMediaLibrarySortDirection = makeVar(MediaLibrarySortDirection.TOP_TO_BOTTOM); 27068var localEditorDockedMediaLibraryStockSortOrder = makeVar(GqlClientGettySortOrder.BEST_MATCH); 27069var localEditorDockedMediaLibraryActiveTab = makeVar(MediaLibraryActiveTab.YourLibrary); 27070var localEditorDockedMediaLibraryCurrentFolderId = makeVar(null); 27071var localEditorFloatingMediaLibraryCurrentFolderId = makeVar(null); 27072var localEditorFloatingMediaLibrarySelectedItemData = makeVar(null); 27073var localEditorIsFloatingMediaLibraryVar = makeVar(false); 27074var localEditorDockedMediaLibrarySelectedItemData = makeVar(null); 27075var localEditorUserNameVar = makeVar(""); 27076var localEditorAddSceneDialogState = makeVar({ 27077 isOpen: false, 27078 activeTab: AddSceneDialogActiveTab.SceneLibrary 27079}); 27080var localEditorShowPronunciationLibraryVar = makeVar(false); 27081var localEditorVideoPlayerControlVar = makeVar({ 27082 playerKey: "", 27083 abortControllerRef: null 27084}); 27085makeVar(null); 27086var localEditedViewerProfileVar = makeVar({ 27087 editedViewerProfileId: "", 27088 editedViewerProfileName: "", 27089 editedViewerProfileValues: {} 27090}); 27091var filterFontsForFontManager = (fonts) => { 27092 return (fonts || []).map((font) => ({ 27093 ...font, 27094 creationTime: new Date(font.created).getTime() 27095 })).filter((font) => font.lifecycleStage === GqlClientAssetLifecycleStage.ENABLED && isNumber(font.weight) && font.familyName && font.isBold !== null && font.isItalic !== null); 27096}; 27097var updateCcFontManagerVar = (fonts) => {
27098 cCFontsManagerVar(new FontsManager(filterFontsForFontManager(fonts))); 27099}; 27100var updateAssetLibraryFontsManagerVar = (fonts) => { 27101 assetLibraryFontsManagerVar(new FontsManager(filterFontsForFontManager(fonts))); 27102}; 27103var editorDisplayLanguageAutoUpdaterSubscription; 27104var initEditorDisplayLanguageAutoUpdater = (editorProgram) => { 27105 if (editorDisplayLanguageAutoUpdaterSubscription) editorDisplayLanguageAutoUpdaterSubscription.unsubscribe(); 27106 const GetSourceAndAdditionalLanguagesDocument = gql` 27107 query GetSourceAndAdditionalLanguages($editorProgramId: ID!, $editorProgramVersionId: ID!) { 27108 editorProgram(id: $editorProgramId) { 27109 programVersion(id: $editorProgramVersionId) { 27110 id 27111 sourceLanguage 27112 additionalLanguages 27113 } 27114 } 27115 } 27116 `; 27117 editorDisplayLanguageAutoUpdaterSubscription = getApolloClient().watchQuery({ 27118 query: GetSourceAndAdditionalLanguagesDocument, 27119 variables: { 27120 editorProgramId: editorProgram.id, 27121 editorProgramVersionId: editorProgram.programVersion.id 27122 }, 27123 fetchPolicy: "cache-only" 27124 }).subscribe((result) => { 27125 const { sourceLanguage, additionalLanguages } = result.data.editorProgram.programVersion; 27126 const currentDisplayLanguage = localEditorDisplayLanguage(); 27127 if (currentDisplayLanguage !== sourceLanguage && !additionalLanguages.includes(currentDisplayLanguage)) localEditorDisplayLanguage(sourceLanguage); 27128 }); 27129}; 27130var initLocalStateForEditor = ({ editorProgram, brandConfigurationVersion }) => { 27131 localEditorLivePreviewPendingSetVar = makeVar(/* @__PURE__ */ new Set()); 27132 localEditorSelectedFramePerSceneVar = makeVar({}); 27133 localEditorSelectedPlaceholderIdsVar = makeVar([]); 27134 localEditorSelectedPlaceholderOpenEditVar = makeVar(false); 27135 localEditorSelectedNarrationPlaceholderOpenEditVar = makeVar(false); 27136 localEditorSelectedSceneIdVar = makeVar(editorProgram.programVersion.sceneLineup[0] || null); 27137 localEditedBrandIdVar = makeVar(null); 27138 localDeleteCandidateBrandIdVar = makeVar(null); 27139 localIsNewBrandVar = makeVar(false); 27140 localBrandByAudienceFallbackIdVar = makeVar(editorProgram.programVersion.bcUseRules ? brandConfigurationVersion.brandConfigurationCollections.find((brand) => brand.localId === editorProgram.programVersion.bcRules.fallback).id : null); 27141 localEditedBrandLogoAssetInfoVar = makeVar({ 27142 logoLocation: null, 27143 logoUrl: null 27144 }); 27145 localEditedBrandColorsVar = makeVar({}); 27146 makeVar(null); 27147 localEditedBrandTextStylesVar = makeVar([]); 27148 localEditedButtonShapeValueVar = makeVar(null); 27149 localEditorSelectedAudioPreview = makeVar(null); 27150 localEditorRaasPlaceholderData = makeVar({}); 27151 localEditorProgramNameVar = makeVar(editorProgram.name); 27152 localEditorDataConnectorEnabledVar = makeVar(editorProgram.programVersion.editorDataConnectorEnabled); 27153 localEditorPreviewDialogTypeVar(PreviewDialogType.Video); 27154 localEditorAddSceneDialogState({ 27155 isOpen: false, 27156 activeTab: AddSceneDialogActiveTab.SceneLibrary 27157 }); 27158 localEditorShowPronunciationLibraryVar(false); 27159 localEditorIsPreviewDialogOpenVar(false); 27160 localAiMediaGenerationDialogInfo(null); 27161 localEditorActiveCueDialogVar(null); 27162 localEditorAllCuesDialogVar(null); 27163 localEditorCueConnectFromPlaceholderIdVar(null); 27164 localEditorUploadedGettyUrlsVar([]); 27165 localEditorMediaLibraryByAudienceCaseIndex(null); 27166 localEditorMediaDragAndDropSnackbarState(EditorMediaDragAndDropSnackbarState.CLOSED); 27167 localRestrictedActionDialog(RESTRICTED_ACTION_DIALOG_DEFAULT_DATA); 27168 localEditorCloudIndicatorVar(CloudIndicatorState.REGULAR); 27169 const preSelectedLibrary = localEditorPreSelectedLibrary(); 27170 localEditorSelectedLibraryVar = makeVar(preSelectedLibrary ?? { 27171 library: null, 27172 opener: null 27173 }); 27174 if (preSelectedLibrary) localEditorPreSelectedLibrary(null); 27175 localEditorDockedMediaLibrarySearchValue(""); 27176 localEditorDockedMediaLibraryFilterMediaType(MediaLibraryFilterMediaType.ALL); 27177 localEditorDockedMediaLibraryFilterMediaSource(MediaLibraryFilterMediaSource.ALL); 27178 localEditorDockedMediaLibraryFilterStockOrientation(MediaLibraryFilterMediaOrientation.ALL); 27179 localEditorDockedMediaLibraryFilterMinVideoDuration(0); 27180 localEditorDockedMediaLibraryFilterMaxVideoDuration(600); 27181 localEditorDockedMediaLibrarySortBy(MediaLibrarySortBy.LAST_ADDED); 27182 localEditorDockedMediaLibrarySortDirection(MediaLibrarySortDirection.TOP_TO_BOTTOM); 27183 localEditorDockedMediaLibraryStockSortOrder(GqlClientGettySortOrder.BEST_MATCH); 27184 localEditorDockedMediaLibraryActiveTab(MediaLibraryActiveTab.YourLibrary); 27185 localEditorDockedMediaLibraryCurrentFolderId(null); 27186 localEditorDockedMediaLibrarySelectedItemData(null); 27187 localEditorShowDropHintFromMediaLibrary(false); 27188 localEditorMediaLibraryDraggingFromFolderId(null); 27189 localEditorShowReplaceAvatarHint(false); 27190 localEditorShowPlaceholderLibrary(false); 27191 localEditorDisplayLanguage(editorProgram.programVersion.sourceLanguage); 27192 localLivePreviewDisplayLanguage(editorProgram.programVersion.sourceLanguage);
27193 initEditorDisplayLanguageAutoUpdater(editorProgram); 27194}; 27195var initLocalStateForDocumentToVideo = (programName, ccLibraryFonts, fonts) => { 27196 localEditorLivePreviewPendingSetVar = makeVar(/* @__PURE__ */ new Set()); 27197 updateCcFontManagerVar(ccLibraryFonts ?? []); 27198 updateAssetLibraryFontsManagerVar(fonts ?? []); 27199 localEditedBrandIdVar = makeVar(null); 27200 localDeleteCandidateBrandIdVar = makeVar(null); 27201 localIsNewBrandVar = makeVar(false); 27202 localBrandByAudienceFallbackIdVar = makeVar(null); 27203 localEditedBrandLogoAssetInfoVar = makeVar({ 27204 logoLocation: null, 27205 logoUrl: null 27206 }); 27207 localEditedBrandColorsVar = makeVar({}); 27208 makeVar(null); 27209 localEditedBrandTextStylesVar = makeVar([]); 27210 localEditedButtonShapeValueVar = makeVar(null); 27211 localEditorSelectedAudioPreview = makeVar(null); 27212 localEditorRaasPlaceholderData = makeVar({}); 27213 localEditorProgramNameVar = makeVar(programName); 27214 localEditorDataConnectorEnabledVar = makeVar(false); 27215 localEditorPreviewDialogTypeVar(PreviewDialogType.Video); 27216 localEditorAddSceneDialogState({ 27217 isOpen: false, 27218 activeTab: AddSceneDialogActiveTab.SceneLibrary 27219 }); 27220 localEditorIsPreviewDialogOpenVar(false); 27221 localEditorUploadedGettyUrlsVar([]); 27222 localRestrictedActionDialog(RESTRICTED_ACTION_DIALOG_DEFAULT_DATA); 27223}; 27224var initCcLibraryLocalStateForEditor = (ccLibraryVersion) => { 27225 const { themes, wireframes } = ccLibraryVersion; 27226 localEditorWireframeThemeSupport = makeVar(createWireframeThemeSupport(wireframes, themes)); 27227 updateCcFontManagerVar(ccLibraryVersion?.fonts); 27228}; 27229makeVar(null); 27230var processedFilesSnackbarCompletedVar = makeVar(false); 27231var localEditorCopyPlaceholderSuccessVar = makeVar(null); 27232var localEditorSceneAnimationCuesData = makeVar({ 27233 sortedAnimationCuesWithData: [], 27234 animationCuesWithDataByLocalId: {}, 27235 connectedPlaceholdersIds: /* @__PURE__ */ new Set(), 27236 placeholderConnectionsByAnimationCueLocalId: {} 27237}); 27238//#endregion 27239//#region client/components/editor/Utils/errorHandling.ts 27240var openContactSupportForm = (errorId) => { 27241 window.open("https://help.sundaysky.com/hc/en-us/requests/new", "_blank"); 27242}; 27243var reloadPage = () => { 27244 window.location.reload(); 27245}; 27246//#endregion 27247//#region common/dynamicElementsUtils.ts 27248var import_dist = require_dist$7(); 27249var SPECIAL_CHAR_VALIDATION = "Use only letters, numbers, spaces, and/or: _ , / \\ - %"; 27250var isNameEmpty = (name) => { 27251 return !name?.trim?.(); 27252}; 27253var isNameWithInvalidChars = (name) => { 27254 return !/^[a-zA-Z\s\-\\,/_%\d]+$/.test(name); 27255}; 27256var getDefaultSourceFromStringElementName = (connectorType, name) => { 27257 return (0, import_dist.getDefaultSourceFromTarget)(connectorType, getStringElementTarget(name)).name; 27258}; 27259var getStringElementTarget = (name) => { 27260 return { 27261 name, 27262 type: import_dist.ElementType.STRING 27263 }; 27264}; 27265var getStringElementSource = (name) => { 27266 return { 27267 name, 27268 type: import_dist.ElementType.STRING 27269 }; 27270}; 27271var createSerializedDynamicElement = (source, target, valueSet, index, pii) => { 27272 return new import_dist.DynamicElement(source, target, valueSet, [], { order: index }, null, pii ?? false).serialize(); 27273}; 27274var buildDynamicElement = (name, valueSet, index, connectorType, pii) => { 27275 const target = getStringElementTarget(name); 27276 return createSerializedDynamicElement((0, import_dist.getDefaultSourceFromTarget)(connectorType, target), target, valueSet, index, pii ?? false); 27277}; 27278//#endregion 27279//#region client/components/editor/Nooks/AccountProgramFolder/accountProgramFolder.ts 27280var deleteFolder = async (folderId) => { 27281 const { mutate } = getApolloClient(); 27282 return mutate({ 27283 mutation: DeleteAccountProgramFolderDocument, 27284 variables: { input: { folderId } } 27285 }); 27286}; 27287var createAccountProgramFolder = async (folderName, parentFolderId) => { 27288 return (await getApolloClient().mutate({ 27289 mutation: CreateAccountProgramFolderDocument, 27290 variables: { input: { 27291 name: folderName, 27292 parentFolderId 27293 } } 27294 })).data?.createAccountProgramFolder.folder.id; 27295}; 27296var renameAccountProgramFolder = async (folderId, folderName) => { 27297 return await getApolloClient().mutate({ 27298 mutation: RenameAccountProgramFolderDocument, 27299 variables: { input: { 27300 name: folderName, 27301 id: folderId 27302 } } 27303 }); 27304}; 27305var moveAccountFolderToFolder = (folderId, folderName, targetFolderId) => { 27306 return getApolloClient().mutate({ 27307 mutation: MoveAccountProgramFolderToFolderDocument, 27308 variables: { input: { 27309 folderId, 27310 folderName, 27311 targetFolderId 27312 } } 27313 }); 27314}; 27315var moveProgramToFolder = (programId, programName, targetFolderId) => { 27316 return getApolloClient().mutate({ 27317 mutation: MoveProgramToFolderDocument, 27318 variables: { input: { 27319 programId, 27320 programName, 27321 targetFolderId 27322 } } 27323 }); 27324}; 27325//#endregion 27326//#region client/components/newNav/components/videos/common.ts 27327var MISSING_DATA_SOURCE_WARNING = "Missing data source. Video will not feature data personalization.";
27328var LibraryType = /* @__PURE__ */ function(LibraryType) { 27329 LibraryType["Videos"] = "videos"; 27330 LibraryType["Templates"] = "templates"; 27331 return LibraryType; 27332}({}); 27333var ItemType = /* @__PURE__ */ function(ItemType) { 27334 ItemType["EditorVideo"] = "EDITOR_VIDEO"; 27335 ItemType["BuilderProgram"] = "BUILDER_PROGRAM"; 27336 ItemType["FOLDER"] = "FOLDER"; 27337 return ItemType; 27338}({}); 27339var VideosArchiveSortingMethod = /* @__PURE__ */ function(VideosArchiveSortingMethod) { 27340 VideosArchiveSortingMethod["NAME"] = "name"; 27341 VideosArchiveSortingMethod["LAST_CREATED"] = "created"; 27342 VideosArchiveSortingMethod["LAST_UPDATED"] = "edited"; 27343 VideosArchiveSortingMethod["LAST_ARCHIVED"] = "archived"; 27344 return VideosArchiveSortingMethod; 27345}({}); 27346var VideosCoPilotDraftsSortingMethod = /* @__PURE__ */ function(VideosCoPilotDraftsSortingMethod) { 27347 VideosCoPilotDraftsSortingMethod["NAME"] = "name"; 27348 VideosCoPilotDraftsSortingMethod["LAST_CREATED"] = "created"; 27349 return VideosCoPilotDraftsSortingMethod; 27350}({}); 27351var YourVideosSortingMethod = /* @__PURE__ */ function(YourVideosSortingMethod) { 27352 YourVideosSortingMethod["NAME"] = "name"; 27353 YourVideosSortingMethod["LAST_CREATED"] = "created"; 27354 YourVideosSortingMethod["LAST_UPDATED"] = "edited"; 27355 YourVideosSortingMethod["PUBLISH_STATUS"] = "published"; 27356 YourVideosSortingMethod["ONGOING_DRAFT"] = "ongoingDraft"; 27357 return YourVideosSortingMethod; 27358}({}); 27359var UserOptionsViewType = /* @__PURE__ */ function(UserOptionsViewType) { 27360 UserOptionsViewType["GRID"] = "grid"; 27361 UserOptionsViewType["TABLE"] = "table"; 27362 return UserOptionsViewType; 27363}({}); 27364var NEW_YOUR_VIDEOS_ROOT_NAME = "Video Library"; 27365var ARCHIVE_FOLDER_NAME = "Archive"; 27366var AI_VIDEO_DRAFTS_FOLDER_NAME = "AI Video Drafts"; 27367var VIDEO_PAGE_NAME = "Video Page"; 27368var RESERVED_ARCHIVE_NAME_MESSAGE = "This name is reserved. Use a different name."; 27369var RESERVED_COPILOT_DRAFTS_NAME_MESSAGE = "This name is reserved. Use a different name."; 27370var TEMPLATES_ROOT_NAME = "Amplify Template Library"; 27371function gqlAccountProgramFolderToVideoFolderItem(folder) { 27372 return { 27373 ...folder, 27374 name: folder.isRoot ? NEW_YOUR_VIDEOS_ROOT_NAME : folder.name, 27375 pathFromRoot: [], 27376 lastEdited: folder.updated, 27377 lastEditedBy: folder.updatedBy, 27378 type: "FOLDER" 27379 }; 27380} 27381var VideoCreationMethod = /* @__PURE__ */ function(VideoCreationMethod) { 27382 VideoCreationMethod["COPILOT"] = "copilot"; 27383 VideoCreationMethod["COPY_BETWEEN_ACCOUNTS"] = "copy_between_accounts"; 27384 VideoCreationMethod["COPY_INSIDE_ACCOUNT"] = "copy_inside_account"; 27385 VideoCreationMethod["FROM_SCRATCH"] = "from_scratch"; 27386 VideoCreationMethod["FROM_SNOWFLAKE"] = "from_snowflake"; 27387 VideoCreationMethod["FROM_STORY_TEMPLATE"] = "from_story_template"; 27388 VideoCreationMethod["FROM_DOCUMENT"] = "ai_doc_to_video"; 27389 VideoCreationMethod["FROM_PROMPT"] = "ai_prompt_to_video"; 27390 VideoCreationMethod["FROM_SCRIPT"] = "ai_script_to_video"; 27391 return VideoCreationMethod; 27392}({}); 27393var VIDEO_TO_TEMPLATE_DISPLAY_NAME = "Based on {ORIGINAL_VIDEO} video"; 27394var VideoCreationMethodDisplayName = { 27395 ["copilot"]: "AI Copilot", 27396 ["copy_between_accounts"]: "Duplicated from another video", 27397 ["copy_inside_account"]: "Duplicated from", 27398 ["from_scratch"]: "From scratch", 27399 ["from_snowflake"]: "AI Copilot", 27400 ["from_story_template"]: "Inspiration Gallery", 27401 ["ai_doc_to_video"]: "Document to video", 27402 ["ai_prompt_to_video"]: "Prompt to video", 27403 ["ai_script_to_video"]: "Script to video" 27404}; 27405function gqlEditorProgramToEditorVideoItem(program) { 27406 return { 27407 id: program.id, 27408 name: program.name, 27409 lastEdited: program.programVersionDraft.anyUpdated, 27410 lastEditedBy: program.programVersionDraft.anyUpdatedBy, 27411 created: program.created, 27412 createdBy: program.createdBy, 27413 video: program, 27414 isArchive: program.isArchive, 27415 isTemplate: program.isTemplate, 27416 type: "EDITOR_VIDEO", 27417 lastArchived: program.lastArchived, 27418 thumbnailUrl: program.programVersionDraft.thumbnail?.url, 27419 origin: program.creationMethod, 27420 originProgramId: program.originProgramId, 27421 originalStoryTemplateProgramId: program.originalStoryTemplateProgramId, 27422 originalStoryTemplateProgramVersionId: program.originalStoryTemplateProgramVersionId, 27423 ...program.prodVersion ? { 27424 datePublished: program.prodVersion.created,
27425 publishedBy: program.prodVersion.createdBy 27426 } : {}, 27427 prodVersion: program.prodVersion, 27428 isLive: program.isLive, 27429 publishTarget: program.publishTarget, 27430 uatVersion: program.uatVersion, 27431 hasOnlineLandingPage: !!program.landingPage?.isActive, 27432 hasEmbedCode: !!program.embedVideoCode?.id, 27433 latestTemplateVersion: program.latestTemplateVersion 27434 }; 27435} 27436function gqlBuilderProgramToBuilderVideoItem(program) { 27437 return { 27438 id: program.id, 27439 name: program.name, 27440 lastEdited: program.anyUpdated, 27441 lastEditedBy: program.anyUpdatedBy, 27442 created: program.created, 27443 createdBy: program.createdBy, 27444 video: program, 27445 isArchive: program.isArchive, 27446 type: "BUILDER_PROGRAM", 27447 lastArchived: program.lastArchived, 27448 legacyBuilderProgramId: program.legacyBuilderProgramId 27449 }; 27450} 27451var menuPopoverHeaderSxProps = { 27452 display: "flex", 27453 flexDirection: "column", 27454 gap: "8px", 27455 padding: "8px" 27456}; 27457var menuPopoverPathSxProps = { 27458 display: "flex", 27459 flexDirection: "row", 27460 gap: "10px", 27461 alignItems: "center" 27462}; 27463var menuPopoverPathTextSxProps = { 27464 textOverflow: "ellipsis", 27465 overflow: "hidden", 27466 whiteSpace: "nowrap", 27467 direction: "rtl", 27468 textAlign: "left", 27469 color: "text.secondary" 27470}; 27471var validateEditedFolderName = (newValue, siblingFoldersNames) => { 27472 if (newValue.trim() === "") return "Folder name cannot be empty"; 27473 else if (siblingFoldersNames.some((siblingFolderName) => newValue.trim().toLowerCase() === siblingFolderName.toLowerCase())) return "This name is being used by another folder"; 27474 else if (newValue.trim().toLowerCase() === "Archive".toLowerCase()) return RESERVED_ARCHIVE_NAME_MESSAGE; 27475 else if (newValue.trim().toLowerCase() === "AI Video Drafts".toLowerCase()) return RESERVED_COPILOT_DRAFTS_NAME_MESSAGE; 27476 else return null; 27477}; 27478var renameFolder = async (newName, prevName, folderId, callback) => { 27479 if (newName.trim() !== prevName) { 27480 await renameAccountProgramFolder(folderId, newName.trim()); 27481 PendoService.getInstance().trackEvent("Video folder name change", { 27482 originFolderName: prevName, 27483 targetFolderName: newName.trim() 27484 }); 27485 callback?.(); 27486 } 27487}; 27488var createVideoFolder = async (newFolderName, parentFolderId, parentFolderName, flowType) => { 27489 const newFolderId = await createAccountProgramFolder(newFolderName.trim(), parentFolderId); 27490 PendoService.getInstance().trackEvent("Video folder created", { 27491 folderName: newFolderName, 27492 parentFolderName: parentFolderName || "Root", 27493 flowType 27494 }); 27495 return newFolderId; 27496}; 27497var moveToFolder = async (targetFolder, itemToMove, trackingIdOrigin, snackBarNotificationClickCallback) => { 27498 if (itemToMove.type === "FOLDER") await moveAccountFolderToFolder(itemToMove.id, itemToMove.name, targetFolder.id); 27499 else await moveProgramToFolder(itemToMove.id, itemToMove.name, targetFolder.id); 27500 setSuccessNotification({ 27501 message: `${itemToMove.type === "FOLDER" ? "Folder" : "Video"} moved to new destination`, 27502 showCloseButton: true, 27503 actionButton: { 27504 label: `Open ${!targetFolder.isRoot ? "folder" : NEW_YOUR_VIDEOS_ROOT_NAME}`, 27505 onClick: snackBarNotificationClickCallback, 27506 dataTrackingId: `tracking-id-${trackingIdOrigin}-move-to-folder-go-to-folder` 27507 } 27508 }); 27509}; 27510var pathSxProps = { 27511 textOverflow: "ellipsis", 27512 overflow: "hidden", 27513 whiteSpace: "nowrap", 27514 direction: "rtl", 27515 textAlign: "left" 27516}; 27517var ellipsisInputSxProps = { "& .MuiInput-input": { 27518 overflow: "hidden", 27519 textOverflow: "ellipsis" 27520} }; 27521var getUserName = (editorAccountUsers, userId) => { 27522 const user = editorAccountUsers.find((accountUser) => accountUser.id === userId); 27523 return user?.firstName ? `${user.firstName} ${user?.lastName ?? ""}` : userId; 27524}; 27525//#endregion 27526//#region client/components/editor/Nooks/Notification/notificationText.tsx 27527var NotificationInfoText = { 27528 NoInternetConnection: "Looks like you're offline. Editing is disabled to prevent any issues. Check your connection and", 27529 InternetConnectionNotStable: "Looks like you're offline. Some actions might not work.", 27530 InternetConnectionRestored: "Your internet connection was restored.", 27531 UploadingAsset: "Uploading...", 27532 Downloading: "Downloading...", 27533 PreparingDownload: "Preparing download...", 27534 SharingVideo: "Sharing Video...", 27535 SendingRecordingRequest: "Sending recording request...", 27536 BrandUploadInProgress: "Upload is still in process, brand couldn't be saved. Try again when upload is completed", 27537 CopyProgramInProgress: "Copying program...", 27538 CreateStudioElementsUploadCsv: "Uploading CSV file...", 27539 AssetDeleted: "1 file deleted", 27540 PreviewVideoPartialNarrations: "Couldn't play all voiceover files. Try again or", 27541 GenerateVideoLinks: "Generating video links...", 27542 GetVideoLinks: "Creating a file of unique links", 27543 ImportingData: "Importing data...", 27544 MightTakeAWhile: "This might take a while...", 27545 VideoArchived: (name) => `${name} was Archived`, 27546 TruffleVideoArchived: "Video moved to Archive", 27547 VideoRestoredFromArchive: (name) => `${name} was Restored`, 27548 TruffleVideoRestoredFromArchive: "Video restored", 27549 DownloadingScript: "Downloading script", 27550 ExportingScript: "Exporting script ...",
27551 ReviewInvitationSent: (pluralSuffix) => `Invitation${pluralSuffix} sent`, 27552 RemoveAllExternalUsersProcessing: "Processing your request to remove all external users...", 27553 DefaultAssetNotEditable: "Default asset can't be edited", 27554 EditSourceLanguageFirst: "To enable editing in other languages, first edit the source language.", 27555 VideoDuplicated: "Video duplicated", 27556 TemplateDuplicated: "Template duplicated", 27557 TemplateCreatedFromVideo: "Template created successfully", 27558 FolderCreated: "Folder created", 27559 noVersionNotificationText: () => isFeatureEnabled(featureFlagConst._EDITOR_WORKFLOWS_RELEASE_1) ? "To share this video, a version must be published first" : "To share this video, a version must be approved first", 27560 restoreVideoToShare: "To share this video, restore it from the archive first", 27561 viewOnlyCantShare: "Only users with Editor permissions can share this video", 27562 duringApprovalCantShare: () => isFeatureEnabled(featureFlagConst._EDITOR_WORKFLOWS_RELEASE_1) ? "Once this version is published, the video can be shared" : "Once this version is approved, the video can be shared", 27563 VideoNoChanges: () => isFeatureEnabled(featureFlagConst._EDITOR_WORKFLOWS_RELEASE_1) ? "No changes to publish" : "No changes to be approved", 27564 TemplateNoChanges: "No updates to re-publish", 27565 TemplateAlreadyUnpublished: "This template has already been unpublished", 27566 RecordingStopped: "Something stopped the recording", 27567 ActionBlockedWhileRenderingAvatar: "This action is unavailable while Avatars are being animated.", 27568 NoShareMethodsEnabled: "Set up at least one sharing option to publish this template", 27569 AiVideoSavedToVideoLibrary: `Video saved successfully to folder â${NEW_YOUR_VIDEOS_ROOT_NAME}â`, 27570 AiVideoSavedToAiDrafts: `Video saved successfully to folder â${AI_VIDEO_DRAFTS_FOLDER_NAME}â`, 27571 VideoUnderApproval: "This video is under approval. You can edit it once the approver responds.", 27572 VideoUnderApprovalByApprovers: (approvers) => `This video is under approval by ${approvers}. You can edit it once the approvers respond.`, 27573 TemplateUnderApprovalByApprovers: (approvers) => `This template is under approval by ${approvers}. You can edit it once the approvers respond.`, 27574 ApproverNoLongerNeeded: (approverName) => `${approverName} has already responded to the approval request for this video. No further action is needed from you.`, 27575 ApproverNoLongerNeededTemplate: (approverName) => `${approverName} has already responded to the approval request for this template. No further action is needed from you.`, 27576 ApprovalReviewNoLongerNeeded: "You no longer need to review this video. No further action is needed from you.", 27577 ApprovalReviewNoLongerNeededTemplate: "You no longer need to review this template. No further action is needed from you.", 27578 VideoUnderApprovalTooltipLine1: (approverName) => `Approval in progress by ${approverName}.`, 27579 VideoUnderApprovalTooltipLine2: "Editing will be available once it's complete.", 27580 CommentsSent: (creatorName) => `Comments sent to ${creatorName}. We'll email you when it's resubmitted for approval.`, 27581 ResubmittedToApprover: (approverName) => `Video resubmitted to ${approverName} for approval`, 27582 ResubmittedToApproverTemplate: (approverName) => `Template resubmitted to ${approverName} for approval`, 27583 ApprovalCanceledForApprover: (cancellerName, canceledAtFormatted) => `Approval request was canceled. ${cancellerName} canceled the approval request on ${canceledAtFormatted}.` 27584}; 27585var CreateStudioElementsUploadCsvSuccess = (created, updated, removed) => { 27586 const getMessage = (action, amount, isFirst) => { 27587 return isFirst ? `${amount} data element${amount > 1 ? "s" : ""} ${action}.` : `${amount} ${action}.`; 27588 }; 27589 let isFirstMessage = true; 27590 let noChangesWereMade = true; 27591 let messages = ["Upload completed successfully."]; 27592 if (created > 0) { 27593 messages.push(getMessage("created", created, isFirstMessage)); 27594 isFirstMessage = false; 27595 noChangesWereMade = false; 27596 } 27597 if (updated > 0) { 27598 messages.push(getMessage("updated", updated, isFirstMessage)); 27599 isFirstMessage = false; 27600 noChangesWereMade = false; 27601 } 27602 if (removed > 0) { 27603 messages.push(getMessage("deleted", removed, isFirstMessage)); 27604 noChangesWereMade = false;
27605 } 27606 if (noChangesWereMade) messages.push("No changes were made."); 27607 return messages.join(" "); 27608}; 27609var UpdateStudioElementsUploadCsvSuccess = (created, updated) => { 27610 const getMessage = (action, amount) => { 27611 return `${amount} data field${amount > 1 ? "s" : ""} ${action}`; 27612 }; 27613 if (created > 0 && updated > 0) return `${getMessage("created", created)} and ${updated} updated`; 27614 if (created > 0) return `${getMessage("created", created)} successfully`; 27615 if (updated > 0) return `${getMessage("updated", updated)} successfully`; 27616 return "No changes were made"; 27617}; 27618var NotificationSuccessText = { 27619 PublishCompleted: "Published successfully", 27620 ApproveCompleted: "Approved successfully", 27621 VideoApproved: "Video approved", 27622 VideoPublished: "Video published", 27623 TemplatePublished: "Template published to Amplify", 27624 TemplateUnpublished: "Template unpublished from Amplify", 27625 DownloadCompleted: "Download completed", 27626 RecordingRequestSent: "Recording request submitted successfully. Your SundaySky team will give you status updates.", 27627 CopyProgramSuccess: isNewNav ? "Video copied" : "Program copied", 27628 SaveViewerProfileSuccess: "Viewer profile saved", 27629 CreateViewerProfileSuccess: "Viewer profile created", 27630 ShareVideoCompleted: "Shared", 27631 EmailTemplatePreviewSent: "A preview of the email template has been sent to your email.", 27632 PostUrlCopied: "Post URL copied!", 27633 LandingPageCopyLinkSuccess: "Link copied", 27634 LandingPagePreviewUrlSuccess: "Preview generated successfully and copied to clipboard. The preview URL will be valid for 1 week", 27635 CreateStudioElementsUploadCsvSuccess, 27636 UpdateStudioElementsUploadCsvSuccess, 27637 DataFieldAddedSuccess: "Data field added successfully", 27638 DataFieldEditedSuccess: "Data field edited successfully", 27639 InputFieldAddedSuccess: "Input Field created", 27640 InputFieldEditedSuccess: "Input Field edited", 27641 InputFieldDeletedSuccess: "Input Field deleted successfully", 27642 DataFieldDeletedSuccess: "Data field deleted successfully", 27643 DataLibraryDetachedSuccess: "Data Library removed", 27644 LogicAndDataLibraryRemovedSuccess: "Data Library removed, personalization deleted", 27645 DataLibraryDeletedSuccess: "Data Library deleted", 27646 DataLibraryCreatedSuccess: (libraryName) => `Data Library "${libraryName}" created`, 27647 DataLibraryDuplicatedSuccess: "Data Library duplicated and linked to video", 27648 ConnectorAuthenticationSuccess: (connectorName) => `The ${connectorName} data connector has been authenticated`, 27649 RemoveAllExternalUsersFinished: "All external users were successfully removed", 27650 CodeCopied: "Code copied", 27651 LinkCopied: "Link copied", 27652 ApprovalLinkCopied: "Link copied successfully. The approver will need to log in to view the video.", 27653 ApprovalRequestedNotifyMe: (date) => `Approval requested on ${date}. You'll be notified by email when feedback is received.`, 27654 WorkflowApprovalRequestSentText: (approver, date) => `Approval request sent to ${approver} on ${date}`, 27655 WorkflowApprovalRequestSentToApproversText: (approvers, date) => `Approval request sent to ${approvers} on ${date}.`, 27656 WorkflowApprovalGrantedSnackbar: (videoName) => `You approved '${videoName}'`, 27657 BriefCopied: "Brief copied to clipboard", 27658 TextCopied: "Text copied to clipboard", 27659 BriefSaved: "Brief saved", 27660 BriefDeleted: "Brief deleted", 27661 EditorVideoDeleted: "The video has been deleted", 27662 MediaAssetSaved: "Asset saved", 27663 AccountProgramFolderDeleted: "Folder deleted", 27664 PlaceholdersPasted: "Placeholders pasted", 27665 PlaceholdersPastedWithDestinationStyle: "Placeholders pasted with destination style", 27666 LayoutsUpgradeSuccess: "Video upgraded to the Optimized Scene Library", 27667 CustomAvatarReady: "Your Custom Avatar is ready", 27668 ImportDataSuccess: (numSuccessfulUsers, numFailedUsers) => numFailedUsers > 0 ? `${numSuccessfulUsers} Data Fields imported, ${numFailedUsers} failed` : `${numSuccessfulUsers} Data Fields imported`, 27669 VideoDeleted: "Video deleted", 27670 MailSentConfirmation: "We've received your request. A sales rep will be in touch shortly.", 27671 CustomVoiceCreated: "Voice created.", 27672 UserDownloadIntentAskMeLaterClicked: "We'll check back with you the next time you enter.", 27673 ImportSceneSuccessful: (sceneName) => `"${sceneName}" imported successfully`, 27674 AmplifyAnalyticsExportStarted: "Export started. The file will be saved to Downloads.", 27675 MembersAddedToGroup: (count, groupName) => `${count} member${count === 1 ? "" : "s"} added to "${groupName}"` 27676}; 27677var NotificationErrorText = { 27678 UnexpectedError: "Something went wrong. Try again or",
27679 [SskyErrorCode.ImageAssetSizeTooBig]: `Image files cannot be larger than ${getImageMaxUploadFileSizeMB()}MB`, 27680 [SskyErrorCode.VideoAssetSizeTooBig]: `Video files cannot be larger than ${getVideoMaxUploadFileSizeMB()}MB`, 27681 [SskyErrorCode.AudioAssetSizeTooBig]: "Audio files cannot be larger than 25MB", 27682 [SskyErrorCode.UnsupportedAssetTypeImageAndVideo]: "File must be one of the following formats: jpg, png, gif, mov, flv, mp4, webm", 27683 [SskyErrorCode.UnsupportedAssetTypeMusic]: "File must be mp3 format", 27684 [SskyErrorCode.RecordingRequestFailed]: "Whoops! Your request for recording didn't go through! Try again or contact your SundaySky team directly.", 27685 [SskyErrorCode.OutdatedEditorVersion]: "A new version is available. To start using it", 27686 [SskyErrorCode.PreviewError]: "Preview couldn't be displayed. Try again or", 27687 [SskyErrorCode.DownloadVideoError]: "File couldn't be downloaded. Try again or", 27688 [SskyErrorCode.UnsupportedAssetFontType]: "Font couldn't be uploaded. Font must be one of the following formats: OTF, TTF", 27689 [SskyErrorCode.AssetFontUploadError]: "Font couldn't be uploaded. Try again", 27690 [SskyErrorCode.CopyProgramFailed]: "Program couldn't be copied", 27691 [SskyErrorCode.CopyProgramBetweenAccountsFailed]: "Program couldn't be copied to a different account", 27692 [SskyErrorCode.ViewerProfileSaveError]: "Viewer profile couldn't be saved. Try again or", 27693 [SskyErrorCode.ViewerProfileCreateError]: "Viewer profile couldn't be created. Try again or", 27694 [SskyErrorCode.ViewerProfileDeleteError]: "Viewer profile couldn't be deleted. Try again or", 27695 [SskyErrorCode.CsvUploadUnsupportedFile]: "This file could not be uploaded. File format must be CSV.", 27696 [SskyErrorCode.CsvUploadFileNotUtf8]: "This file could not be uploaded because some of the content is not encoded in UTF-8.", 27697 [SskyErrorCode.CsvUploadFileTooBig]: "File couldn't be uploaded. File cannot be larger than 100MB.", 27698 [SskyErrorCode.CsvUploadFileEmpty]: "This file couldn't be uploaded because it is empty.", 27699 [SskyErrorCode.CsvUploadDuplicateHeaders]: "This file could not be uploaded. Column headings must be unique.", 27700 [SskyErrorCode.CsvUploadIllegalCharacterInHeaders]: `This file could not be uploaded, one or more of the fields contain illegal characters. ${SPECIAL_CHAR_VALIDATION}`, 27701 [SskyErrorCode.StudioElementsCreationErrorParsingCsv]: "CSV couldn't be uploaded. Try again or", 27702 [SskyErrorCode.EditorProgramGenerateVideoLinksFailed]: "Links couldn't be generated.", 27703 [SskyErrorCode.BulkUploadAssetsTooMany]: `Upload cannot exceed 100 files at a time`, 27704 [SskyErrorCode.GettyImagesGeneralError]: "Error getting stock media. Try again later or", 27705 [SskyErrorCode.ShareVideoToSocialError]: "There has been an error sharing your video. Try again or", 27706 [SskyErrorCode.LandingPagePreviewError]: "There has been an error previewing this landing page", 27707 [SskyErrorCode.LandingPageSaveError]: "There has been an error saving this landing page", 27708 [SskyErrorCode.LandingPageActivationError]: "There has been an error activating this landing page", 27709 [SskyErrorCode.LandingPageDeactivationError]: "There has been an error deactivating this landing page", 27710 [SskyErrorCode.PublishToChannelsError]: "Your program couldn't be published to your channel. please try again later", 27711 [SskyErrorCode.LandingPageDeletionError]: "There has been an error deleting this landing page", 27712 [SskyErrorCode.PromptToVideoError]: "There has been an error creating the video", 27713 [SskyErrorCode.DuplicateProgramWithRemovedWireframeError]: "This video uses discontinued scene templates. Please switch to current templates before duplicating the video", 27714 [SskyErrorCode.DataImportFailed]: "Data import failed, please verify the file contents", 27715 [SskyErrorCode.AiImageGenerationFailedGeneral]: "AI Image Generation failed - please contact support or try again later", 27716 [SskyErrorCode.AiImageGenerationFailedBadPrompt]: "AI Image Generation failed - your prompt is not suitable for this service", 27717 [SskyErrorCode.DeprecatedProviderError]: "Preview video failed - AI voice is expired", 27718 [SskyErrorCode.OpeningImglyFailed]: "Media Editor could not be opened. Please contact support or try again later",
27719 [SskyErrorCode.MailSendingFailed]: "The request couldn't be processed. Try again later." 27720}; 27721//#endregion 27722//#region client/components/editor/Nooks/ProcessedFiles/processedFiles.ts 27723var PROCESSED_FILE_SUCCESS_TTL = 2e3; 27724var PROCESSED_FILE_LONG_PROCESSING = 6e3; 27725var getProcessedFileIndex = (fileName) => { 27726 return localEditorProcessedFilesVar().findIndex((processedFile) => fileName === processedFile.fileName); 27727}; 27728var updateLongProcessing = (processedFile) => { 27729 const index = getProcessedFileIndex(processedFile.fileName); 27730 if (index < 0) return; 27731 const updatedProcessedFiles = [...localEditorProcessedFilesVar()]; 27732 const oldProcessedFile = updatedProcessedFiles[index]; 27733 if (oldProcessedFile.status === "loading") { 27734 const updatedProcessedFile = { 27735 ...oldProcessedFile, 27736 info: NotificationInfoText.MightTakeAWhile 27737 }; 27738 updatedProcessedFiles.splice(index, 1, updatedProcessedFile); 27739 localEditorProcessedFilesVar(updatedProcessedFiles); 27740 } 27741}; 27742var insertProcessedFile = (processedFile) => { 27743 localEditorProcessedFilesVar([processedFile, ...localEditorProcessedFilesVar()]); 27744 setTimeout(() => updateLongProcessing(processedFile), PROCESSED_FILE_LONG_PROCESSING); 27745}; 27746var updateProcessedFile = (fileIndex, type, updatedData) => { 27747 const updatedProcessedFiles = [...localEditorProcessedFilesVar()]; 27748 const updatedProcessedFile = { 27749 ...updatedProcessedFiles[fileIndex], 27750 ...updatedData, 27751 type 27752 }; 27753 updatedProcessedFiles.splice(fileIndex, 1, updatedProcessedFile); 27754 localEditorProcessedFilesVar(updatedProcessedFiles); 27755}; 27756var deleteProcessedFile = (processedFile) => { 27757 const index = getProcessedFileIndex(processedFile.fileName); 27758 if (index >= 0) { 27759 const processedFiles = [...localEditorProcessedFilesVar()]; 27760 processedFiles.splice(index, 1); 27761 localEditorProcessedFilesVar(processedFiles); 27762 } 27763}; 27764var createErrorProcessedFile = ({ fileName, sskyCode }) => { 27765 return { 27766 fileName, 27767 status: "error", 27768 info: NotificationErrorText[sskyCode] 27769 }; 27770}; 27771var clearInfoIfSuccess = ({ fileName, fileId, status }) => { 27772 const processedFile = { 27773 fileName, 27774 fileId, 27775 status 27776 }; 27777 if (status === "success") processedFile.info = null; 27778 return processedFile; 27779}; 27780var upsertProcessedFile = (params) => { 27781 const processedFile = "sskyCode" in params ? createErrorProcessedFile(params) : clearInfoIfSuccess(params); 27782 const index = getProcessedFileIndex(processedFile.fileName); 27783 index < 0 ? insertProcessedFile(processedFile) : updateProcessedFile(index, params.type, processedFile); 27784 processedFile.status === "success" && setTimeout(() => deleteProcessedFile(processedFile), PROCESSED_FILE_SUCCESS_TTL); 27785}; 27786var upsertEditorUploadedGettyUrl = (uploadedGettyUrlToUpsert) => { 27787 localEditorUploadedGettyUrlsVar([...localEditorUploadedGettyUrlsVar().filter((uploadedGettyUrl) => Object.keys(uploadedGettyUrl).filter((key) => key !== "assetId" && key !== "mediaUrl" && key !== "thumbnailUrl").some((key) => uploadedGettyUrlToUpsert[key] !== uploadedGettyUrl[key])), uploadedGettyUrlToUpsert]); 27788}; 27789var removeEditorUploadedGettyUrl = (data) => { 27790 localEditorUploadedGettyUrlsVar(localEditorUploadedGettyUrlsVar().filter((uploadedGettyUrl) => Object.keys(data).filter((key) => key !== "mediaUrl" && key !== "thumbnailUrl").some((key) => data[key] !== uploadedGettyUrl[key]))); 27791}; 27792//#endregion 27793//#region client/components/editor/Nooks/Notification/notification.ts 27794var getContactSupportActionButton = (errorId) => { 27795 return { 27796 label: "Contact support", 27797 onClick: () => openContactSupportForm(errorId) 27798 }; 27799}; 27800var reloadPageActionButton = { 27801 label: "Reload page", 27802 onClick: reloadPage 27803}; 27804var setNotification = (notificationData) => { 27805 localEditorNotificationDataVar(notificationData); 27806}; 27807var setNeutralNotification = (notificationData) => { 27808 setNotification({ 27809 ...notificationData, 27810 type: "neutral", 27811 isOpen: true 27812 }); 27813}; 27814var setSuccessNotification = (notificationData) => { 27815 setNotification({ 27816 ...notificationData, 27817 type: "success", 27818 isOpen: true 27819 }); 27820}; 27821var setErrorNotification = (notificationData) => { 27822 setNotification({ 27823 ...notificationData, 27824 type: "error", 27825 isOpen: true 27826 }); 27827}; 27828var setInfoNotification = (notificationData) => { 27829 setNotification({ 27830 ...notificationData, 27831 type: "info", 27832 isOpen: true 27833 }); 27834}; 27835var setWarningNotification = (notificationData) => { 27836 setNotification({ 27837 ...notificationData, 27838 type: "warning", 27839 isOpen: true 27840 }); 27841}; 27842var closeNotification = () => { 27843 setNotification({ 27844 ...localEditorNotificationDataVar(), 27845 isOpen: false 27846 }); 27847}; 27848var setNoInternetNotification = () => {
27849 setNeutralNotification({ 27850 message: NotificationInfoText.NoInternetConnection, 27851 actionButton: reloadPageActionButton, 27852 blockUserActions: true 27853 }); 27854}; 27855var notifyUsingProcessedFilesSnackbar = (sskyCode, fileName) => { 27856 upsertProcessedFile({ 27857 fileName, 27858 sskyCode 27859 }); 27860}; 27861var notifyUsingNotificationSnackbar = (sskyCode, editorError, duration) => { 27862 if (silentErrorCodes.has(sskyCode)) return; 27863 const errorId = editorError.getErrorId(); 27864 const notificationData = { 27865 type: "error", 27866 message: null, 27867 duration, 27868 isOpen: true 27869 }; 27870 switch (sskyCode) { 27871 case SskyErrorCode.ImageAssetSizeTooBig: 27872 case SskyErrorCode.VideoAssetSizeTooBig: 27873 case SskyErrorCode.AudioAssetSizeTooBig: 27874 case SskyErrorCode.UnsupportedAssetTypeImageAndVideo: 27875 case SskyErrorCode.UnsupportedAssetTypeMusic: 27876 case SskyErrorCode.CsvUploadUnsupportedFile: 27877 case SskyErrorCode.CsvUploadFileTooBig: 27878 case SskyErrorCode.CsvUploadFileEmpty: 27879 case SskyErrorCode.CsvUploadFileNotUtf8: 27880 case SskyErrorCode.CsvUploadDuplicateHeaders: 27881 case SskyErrorCode.CsvUploadIllegalCharacterInHeaders: 27882 case SskyErrorCode.BulkUploadAssetsTooMany: 27883 case SskyErrorCode.LandingPagePreviewError: 27884 case SskyErrorCode.LandingPageSaveError: 27885 case SskyErrorCode.LandingPageActivationError: 27886 case SskyErrorCode.LandingPageDeactivationError: 27887 case SskyErrorCode.PublishToChannelsError: 27888 case SskyErrorCode.LandingPageDeletionError: 27889 case SskyErrorCode.DuplicateProgramWithRemovedWireframeError: 27890 notificationData.message = NotificationErrorText[sskyCode]; 27891 break; 27892 case SskyErrorCode.RecordingRequestFailed: 27893 case SskyErrorCode.CopyProgramFailed: 27894 case SskyErrorCode.CopyProgramBetweenAccountsFailed: 27895 case SskyErrorCode.PreviewError: 27896 case SskyErrorCode.DownloadVideoError: 27897 case SskyErrorCode.ShareVideoToSocialError: 27898 case SskyErrorCode.ViewerProfileSaveError: 27899 case SskyErrorCode.ViewerProfileDeleteError: 27900 case SskyErrorCode.ViewerProfileCreateError: 27901 case SskyErrorCode.StudioElementsCreationErrorParsingCsv: 27902 case SskyErrorCode.EditorProgramGenerateVideoLinksFailed: 27903 case SskyErrorCode.GettyImagesGeneralError: 27904 case SskyErrorCode.PromptToVideoError: 27905 notificationData.message = NotificationErrorText[sskyCode]; 27906 notificationData.actionButton = getContactSupportActionButton(errorId); 27907 break; 27908 case SskyErrorCode.OutdatedEditorVersion: 27909 notificationData.type = "neutral"; 27910 notificationData.message = NotificationErrorText[sskyCode]; 27911 notificationData.actionButton = reloadPageActionButton; 27912 notificationData.blockUserActions = true; 27913 break; 27914 case SskyErrorCode.PreviewVideoPartialNarrations: 27915 notificationData.type = "neutral"; 27916 notificationData.message = NotificationInfoText[sskyCode]; 27917 notificationData.actionButton = getContactSupportActionButton(v4()); 27918 break; 27919 default: 27920 notificationData.type = "neutral"; 27921 notificationData.message = NotificationErrorText.UnexpectedError; 27922 notificationData.actionButton = getContactSupportActionButton(errorId); 27923 break; 27924 } 27925 setNotification(notificationData); 27926}; 27927function notifyGeneralError() { 27928 setNeutralNotification({ 27929 message: NotificationErrorText.UnexpectedError, 27930 actionButton: getContactSupportActionButton(v4()) 27931 }); 27932} 27933var handleEditorError = ({ error, sskyCode, details, fileName, notificationDuration }) => { 27934 const editorError = new EnhancedError(error, sskyCode, details); 27935 if (!silentErrorCodes.has(sskyCode)) captureExceptionToSentry(error, sskyCode, { errorId: editorError.getErrorId() }); 27936 handleError({ 27937 error: editorError, 27938 skipSentryCapture: true 27939 }).catch(() => {}); 27940 if (fileName) notifyUsingProcessedFilesSnackbar(sskyCode, fileName); 27941 else notifyUsingNotificationSnackbar(sskyCode, editorError, notificationDuration); 27942}; 27943var getNotificationData = () => { 27944 return { ...localEditorNotificationDataVar() }; 27945}; 27946var UploadFileContext = /* @__PURE__ */ function(UploadFileContext) { 27947 UploadFileContext["DataLibrary"] = "DataLibrary"; 27948 UploadFileContext["GenerateLinks"] = "GenerateLinks"; 27949 UploadFileContext["MediaAssetLibrary"] = "MediaAssetLibrary"; 27950 UploadFileContext["MusicLibrary"] = "MusicLibrary"; 27951 UploadFileContext["FontsLibrary"] = "FontsLibrary"; 27952 UploadFileContext["NonLibraryMedia"] = "NonLibraryMedia"; 27953 UploadFileContext["FileToVideo"] = "FileToVideo"; 27954 return UploadFileContext; 27955}({}); 27956var UploadFileClientSideValidations = [
27957 SskyErrorCode.UnsupportedAssetTypeImageAndVideo, 27958 SskyErrorCode.UnsupportedAssetTypeMusic, 27959 SskyErrorCode.ImageAssetSizeTooBig, 27960 SskyErrorCode.VideoAssetSizeTooBig, 27961 SskyErrorCode.AudioAssetSizeTooBig, 27962 SskyErrorCode.UnsupportedAssetFontType, 27963 SskyErrorCode.CsvUploadUnsupportedFile, 27964 SskyErrorCode.CsvUploadFileNotUtf8, 27965 SskyErrorCode.CsvUploadFileTooBig, 27966 SskyErrorCode.CsvUploadFileEmpty, 27967 SskyErrorCode.CsvUploadDuplicateHeaders, 27968 SskyErrorCode.CsvUploadIllegalCharacterInHeaders 27969]; 27970var handleFileUploadError = (fileName, error, context, notUsingProcessedFilesSnackbar) => { 27971 const sskyErrorCode = error?.getSskyErrorCode?.(); 27972 if (UploadFileClientSideValidations.includes(sskyErrorCode)) { 27973 const pendo = PendoService.getInstance(); 27974 fileName && !notUsingProcessedFilesSnackbar ? notifyUsingProcessedFilesSnackbar(sskyErrorCode, fileName) : notifyUsingNotificationSnackbar(sskyErrorCode, error); 27975 pendo.trackEvent("Invalid File Upload", { 27976 context, 27977 sskyErrorCode, 27978 message: NotificationErrorText[sskyErrorCode], 27979 fileName 27980 }); 27981 } else handleEditorError({ 27982 error, 27983 sskyCode: sskyErrorCode, 27984 fileName 27985 }); 27986}; 27987//#endregion 27988//#region client/logic/projects/projectsActions.ts 27989var { CREATIVE } = featureFlagConst; 27990var LOADING_ALL_PROJECTS_SUCCESS = "LOADING_ALL_PROJECTS_SUCCESS"; 27991var LOADING_PROJECT_DETAILS = "LOADING_PROJECT_DETAILS"; 27992var LOADING_PROJECT_DETAILS_SUCCESS = "LOADING_PROJECT_DETAILS_SUCCESS"; 27993var ADD_PROJECT_SUCCESS = "ADD_PROJECT_SUCCESS"; 27994var DELETE_PROJECT_COMPLETE = "DELETE_PROJECT_COMPLETE"; 27995var UPDATE_PROJECT_COMPLETE = "UPDATE_PROJECT_COMPLETE"; 27996var GET_PROJECT_VERSIONS_COMPLETE = "GET_PROJECT_VERSIONS_COMPLETE"; 27997var LOAD_PROJECT_SUMMARIES_SUCCESS = "LOAD_PROJECT_SUMMARIES_SUCCESS"; 27998var loadProjectSummariesSuccess = (0, import_lib$3.createAction)(LOAD_PROJECT_SUMMARIES_SUCCESS, (projectSummaries) => ({ projectSummaries })); 27999var UPDATE_PROGRAM_SUMMARY_SUCCESS = "UPDATE_PROGRAM_SUMMARY_SUCCESS"; 28000var updateProgramSummarySuccess = (0, import_lib$3.createAction)(UPDATE_PROGRAM_SUMMARY_SUCCESS, (programId, updatedFields) => ({ 28001 programId, 28002 updatedFields 28003})); 28004(0, import_lib$3.createAction)(LOADING_PROJECT_DETAILS, (project) => ({ project })); 28005var loadingProjectDetailsSuccess = (0, import_lib$3.createAction)(LOADING_PROJECT_DETAILS_SUCCESS, (project) => ({ project })); 28006var loadingAllProjectsSuccess = (0, import_lib$3.createAction)(LOADING_ALL_PROJECTS_SUCCESS, (projects) => ({ projects })); 28007var LOADING_GQL_PROGRAM_SUCCESS = "LOADING_GQL_PROJECT_SUCCESS"; 28008var loadingGqlProgramSuccess = (0, import_lib$3.createAction)(LOADING_GQL_PROGRAM_SUCCESS, (program) => ({ program })); 28009var LOADING_NEW_PROGRAMS_SUCCESS = "LOADING_NEW_PROGRAMS_SUCCESS"; 28010var getNewProgramsSuccess = (0, import_lib$3.createAction)(LOADING_NEW_PROGRAMS_SUCCESS, function(accountId, newPrograms) { 28011 return { 28012 accountId, 28013 newPrograms 28014 }; 28015}); 28016var LOADING_PROJECT_LIFECYCLE_SUCCESS = "LOADING_PROJECT_LIFECYCLE_SUCCESS"; 28017var loadingProjectLifeCycleSuccess = (0, import_lib$3.createAction)(LOADING_PROJECT_LIFECYCLE_SUCCESS, function(accountId, projectName, projectLifeCycle) { 28018 return { 28019 accountId, 28020 projectName, 28021 projectLifeCycle 28022 }; 28023}); 28024var LOADING_PROJECT_LIFECYCLE_STAGE_SUCCESS = "LOADING_PROJECT_LIFECYCLE_STAGE_SUCCESS"; 28025var loadingProjectLifeCycleStageSuccess = (0, import_lib$3.createAction)(LOADING_PROJECT_LIFECYCLE_STAGE_SUCCESS, function(accountId, projectName, projectLifeCycle, stage) { 28026 return { 28027 accountId, 28028 projectName, 28029 projectLifeCycle, 28030 stage 28031 }; 28032}); 28033var addProjectSuccess = (0, import_lib$3.createAction)(ADD_PROJECT_SUCCESS, function(project) { 28034 return project; 28035}); 28036(0, import_lib$3.createAction)(DELETE_PROJECT_COMPLETE, function(index) { 28037 return { index }; 28038}); 28039var updateProjectComplete = (0, import_lib$3.createAction)(UPDATE_PROJECT_COMPLETE, function(project) { 28040 return { project }; 28041}); 28042var getProjectVersionsComplete = (0, import_lib$3.createAction)(GET_PROJECT_VERSIONS_COMPLETE, function(projectName, versions) { 28043 return { 28044 projectName, 28045 versions 28046 }; 28047}); 28048var GENERATE_REC_DOC_SUCCESS = "GENERATE_REC_DOC_SUCCESS"; 28049var generateRecordingDocSuccess = (0, import_lib$3.createAction)(GENERATE_REC_DOC_SUCCESS, (recordingDoc, projectName) => ({ 28050 recordingDoc, 28051 projectName 28052})); 28053var LOADING_REC_DOC_SUCCESS = "LOADING_REC_DOC_SUCCESS"; 28054var loadingProjectRecordingDocSuccess = (0, import_lib$3.createAction)(LOADING_REC_DOC_SUCCESS, function(projectName, docs) { 28055 return { 28056 projectName, 28057 docs 28058 }; 28059}); 28060var UPDATE_PROGRAM_LOGIC_ITEMS = "UPDATE_PROGRAM_LOGIC_ITEMS"; 28061var updateProgramLogicItems = (0, import_lib$3.createAction)(UPDATE_PROGRAM_LOGIC_ITEMS, (projectName, data) => { 28062 return { 28063 projectName, 28064 data 28065 }; 28066}); 28067var mutateProjectUpdate = function(programId, programVersionId, project, services) { 28068 if (project.hasOwnProperty("description") || project.hasOwnProperty("displayName") || project.hasOwnProperty("programId") || project.hasOwnProperty("pii") || project.hasOwnProperty("publishTarget")) { 28069 let input = { 28070 id: programId, 28071 updated: IGNORE_UPDATED, 28072 name: project.displayName, 28073 description: project.description, 28074 salesforceId: project.programId, 28075 pii: project.pii, 28076 publishTarget: project.publishTarget 28077 }; 28078 return services.graphQlClient.mutate({ 28079 mutation: UpdateProgramDocument, 28080 variables: { 28081 input, 28082 [IGNORE_SERVER_ERRORS]: true 28083 } 28084 }); 28085 } else if (project.hasOwnProperty("creativeNameLabel") || project.hasOwnProperty("creativeDDE") || project.hasOwnProperty("creativeVersion") || project.hasOwnProperty("programType") || project.hasOwnProperty("editorDataConnectorEnabled") || project.hasOwnProperty("chapteringEnabled")) { 28086 let input = { 28087 id: programVersionId, 28088 updated: IGNORE_UPDATED, 28089 creativeNameLabel: project.creativeNameLabel, 28090 creativeDDE: project.creativeDDE, 28091 chapteringEnabled: project.chapteringEnabled, 28092 supportsCreatives: project.hasOwnProperty("creativeVersion") ? !!project.creativeVersion : void 0, 28093 programType: getGQLProgramType(project.programType), 28094 editorDataConnectorEnabled: project.editorDataConnectorEnabled 28095 }; 28096 return services.graphQlClient.mutate({ 28097 mutation: UpdateProgramVersionDocument, 28098 variables: { 28099 input, 28100 [IGNORE_SERVER_ERRORS]: true 28101 } 28102 }); 28103 } 28104}; 28105var getProgramFromGQLResponse = (gqlResponse) => { 28106 if (gqlResponse.data.hasOwnProperty("updateProgramVersionDraft")) { 28107 const output = gqlResponse.data.updateProgramVersionDraft; 28108 if (output.__typename === "UpdateProgramVersionDraftOutputSuccess") return output.programVersion.program; 28109 } else if (gqlResponse.data.hasOwnProperty("updateProgram")) { 28110 const output = gqlResponse.data.updateProgram; 28111 if (output.__typename === "UpdateProgramOutputSuccess") return output.program; 28112 } 28113 return null; 28114}; 28115var generateRecordingDoc = function(accountId, projectName, recordingAssets, cb) { 28116 return (dispatch, getState, services) => { 28117 let programVersionId = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName).programVersionId; 28118 if (StateReaderUtils.isProgramBulkDynamoMigrationDoneByLegacyId(getState(), projectName, BulkId.RecordingDocs)) { 28119 const program = StateReaderUtils.getProject(getState(), projectName); 28120 const input = { 28121 programVersionId, 28122 recordingAssets: recordingAssets.recordingAssets, 28123 programName: program.displayName 28124 }; 28125 services.graphQlClient.mutate({ 28126 context: { headers: { "legacy-program-id": projectName } }, 28127 mutation: CreateRecordingDocDocument, 28128 variables: { input } 28129 }).then(function(res) { 28130 dispatch(generateRecordingDocSuccess(AssetUtils.convertGraphQLRecordingDocForRedux(res.data.createRecordingDoc.recordingDoc), projectName)); 28131 cb(); 28132 }).catch((err) => { 28133 dispatch(reportError(err)); 28134 cb(); 28135 }); 28136 } else services.projectServices.generateRecordingDoc(accountId, projectName, recordingAssets, programVersionId).then(function(res) { 28137 dispatch(generateRecordingDocSuccess(res, projectName)); 28138 cb(); 28139 }).catch((err) => { 28140 dispatch(reportError(err)); 28141 cb(); 28142 }); 28143 }; 28144}; 28145var syncAnimations = function(accountId, projectName) { 28146 return async function(dispatch, state, services) { 28147 let { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(state(), projectName); 28148 if (!programVersionId) { 28149 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 28150 programVersionId = StateReaderUtils.getBuilderProgramAndDraftVersionIds({ projectSummaries }, projectName).programVersionId; 28151 } 28152 return services.projectAssetsServices.syncAnimations(accountId, projectName, programVersionId).then(function(syncData) { 28153 if (Object.keys(syncData).length !== 0) dispatch(loadProjectDetails(accountId, projectName, void 0, void 0, void 0, true)); 28154 }).catch(function(err) { 28155 dispatch(reportError(err)); 28156 }); 28157 }; 28158}; 28159var loadProjectDetails = function(accountId, projectName, version = void 0, stage = void 0, triggeredWithForceLoad = false, includeCreativeNarrations = true) { 28160 return async function(dispatch, getState) { 28161 if (!version && !stage) { 28162 let { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 28163 dispatch(loadProjectAndAssets(accountId, projectName, programVersionId, includeCreativeNarrations, stage, version)); 28164 } else { 28165 let versionNumber = Number(version); 28166 if (stage) versionNumber = (getState().projects.byName[projectName]?.[stage + "Snapshots"]?.[0])?.snapshotNumber; 28167 if (Number.isInteger(versionNumber)) { 28168 if (StateReaderUtils.getSnapshotDetails(getState(), versionNumber)) dispatch(loadProjectAndAssets(accountId, projectName, versionNumber, includeCreativeNarrations, stage, version)); 28169 } 28170 } 28171 }; 28172}; 28173var loadProjectDetailsLegacy = function(accountId, projectName, stages, cb = void 0, version = void 0, stageToView = void 0, triggeredWithForceLoad = false, includeCreativeNarrations = true) { 28174 return async function(dispatch, state, services) { 28175 dispatch(setLoading(true, accountId, projectName)); 28176 let { programId, programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(state(), projectName); 28177 if (!programVersionId || !programVersionId) { 28178 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 28179 let programAndVersionId = StateReaderUtils.getBuilderProgramAndDraftVersionIds({ projectSummaries }, projectName); 28180 programId = programAndVersionId.programId; 28181 programVersionId = programAndVersionId.programVersionId; 28182 } 28183 let projectLifecycleResult; 28184 if (version || stageToView) { 28185 let snapshotNumber; 28186 if (stageToView) { 28187 projectLifecycleResult = await services.projectLifeCycleServices.getProjectLifeCycle(accountId, projectName); 28188 snapshotNumber = (projectLifecycleResult || []).find((lifecycleStage) => lifecycleStage.stage === stageToView)?.snapshotNumber; 28189 } else snapshotNumber = Number(version); 28190 const snapshotDetails = StateReaderUtils.getSnapshotDetails(state(), snapshotNumber); 28191 if (snapshotDetails?.snapshotSource === SnapshotSource.POSTGRES) programVersionId = snapshotDetails.graphQLId; 28192 } 28193 let isTypeOfAssetFromGql = {}; 28194 isTypeOfAssetFromGql[AssetTypes.curated] = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.Assets); 28195 isTypeOfAssetFromGql[AssetTypes.narrator] = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.Narrators); 28196 isTypeOfAssetFromGql[AssetTypes.animation] = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.Animations); 28197 isTypeOfAssetFromGql[AssetTypes.mappingTable] = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.DataTables); 28198 const getProgramFromGQL = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.MostEntities); 28199 let gqlProgramPromise = Promise.resolve(null); 28200 const anyAssetFromGql = Object.values(isTypeOfAssetFromGql).some((flag) => !!flag); 28201 const getRecordingDocsFromGQL = StateReaderUtils.isProgramBulkDynamoMigrationDone(state(), programId, BulkId.RecordingDocs); 28202 if (getProgramFromGQL || anyAssetFromGql || getRecordingDocsFromGQL) { 28203 const variables = { 28204 programId, 28205 programVersionId 28206 }; 28207 gqlProgramPromise = services.graphQlClient.query({ 28208 fetchPolicy: "no-cache", 28209 query: GetProgramWithAssetsDocument, 28210 variables 28211 }); 28212 } 28213 let failedToGetVersion = false;
28214 let graphQlError = false; 28215 let forceLoad = triggeredWithForceLoad || StateReaderUtils.getForceLoad(state()); 28216 let project = StateReaderUtils.getProject(state(), projectName); 28217 let projectPromise = getProgramFromGQL || project && !forceLoad ? Promise.resolve(null) : services.projectServices.getProject(accountId, projectName); 28218 let assetCountPromise = isTypeOfAssetFromGql[AssetTypes.curated] ? Promise.resolve() : services.projectAssetsServices.getAssetCount(accountId, projectName, AssetTypes.curated); 28219 let recordingDocsPromise = getRecordingDocsFromGQL ? Promise.resolve(null) : services.projectServices.getRecordingDocs(accountId, projectName); 28220 let lifecyclePromise = projectLifecycleResult ? Promise.resolve(projectLifecycleResult) : services.projectLifeCycleServices.getProjectLifeCycle(accountId, projectName); 28221 let assetsPromises = Object.values(AssetTypes).map((assetType) => { 28222 let hasAssetsOfThisType = project && project.assets && project.assets.some((projectAssetId) => AssetUtils.getAssetTypeFromId(projectAssetId) === assetType); 28223 if (isTypeOfAssetFromGql[assetType] || hasAssetsOfThisType && !forceLoad || assetType === AssetTypes.recording) return null; 28224 else return services.projectAssetsServices.getAllAssets(accountId, projectName, assetType, void 0, void 0, true); 28225 }).filter(Boolean); 28226 let creativeEnabled = StateReaderUtils.isFeatureEnable(state(), CREATIVE); 28227 let creativesRecordingsPromise; 28228 if (creativeEnabled && !version && includeCreativeNarrations) creativesRecordingsPromise = services.graphQlClient.query({ 28229 fetchPolicy: "no-cache", 28230 query: GetAllCreativesNarrationRecordingsDocument, 28231 variables: { id: programId } 28232 }); 28233 else creativesRecordingsPromise = Promise.resolve({ data: { program: { creatives: [] } } }); 28234 Promise.all([ 28235 projectPromise, 28236 assetCountPromise, 28237 recordingDocsPromise, 28238 lifecyclePromise, 28239 creativesRecordingsPromise, 28240 gqlProgramPromise, 28241 ...assetsPromises 28242 ]).then(async ([project, totalCuratedAssets, recordingDocs, projectLifecycle, creativeRecordingAssetsData, gqlProgramResponse, ...dbAssets]) => { 28243 const gqlProgram = gqlProgramResponse ? buildProgramFromGql(gqlProgramResponse?.data?.program) : null; 28244 const gqlProgramVersion = gqlProgramResponse?.data?.program?.programVersion; 28245 if (project || getProgramFromGQL) dispatch(loadingProjectDetailsSuccess(getProgramFromGQL ? gqlProgram : project)); 28246 if (isTypeOfAssetFromGql[AssetTypes.narrator]) { 28247 const gqlNarrators = gqlProgramVersion.narrators; 28248 dispatch(loadingProjectAssetsSuccess(projectName, { Items: buildNarratorsFromGql(accountId, projectName, gqlNarrators || []) }, void 0)); 28249 } 28250 if (isTypeOfAssetFromGql[AssetTypes.curated]) { 28251 let convertedAssets = (gqlProgramVersion.assets || []).map(convertPostgresAssetToDynamoAsset); 28252 let totalCount = convertedAssets.length; 28253 dispatch(loadingProjectAssetsCountSuccess(projectName, { totalCount }, AssetTypes.curated)); 28254 dispatch(loadingProjectAssetsSuccess(projectName, { Items: convertedAssets }, void 0)); 28255 } else dispatch(loadingProjectAssetsCountSuccess(projectName, totalCuratedAssets, AssetTypes.curated)); 28256 if (isTypeOfAssetFromGql[AssetTypes.animation]) dispatch(loadingProjectAssetsSuccess(projectName, { Items: (gqlProgramVersion.animations || []).map(convertPostgresAnimationToDynamoAnimation) }, void 0)); 28257 if (isTypeOfAssetFromGql[AssetTypes.mappingTable]) dispatch(loadingProjectAssetsSuccess(projectName, { Items: (gqlProgramVersion.dataTables || []).map(buildDataTableFromGql) }, void 0)); 28258 dbAssets.map((typeAssets) => { 28259 dispatch(loadingProjectAssetsSuccess(projectName, typeAssets, void 0)); 28260 }); 28261 if (getRecordingDocsFromGQL) dispatch(loadingProjectRecordingDocSuccess(projectName, (gqlProgramVersion.recordingDocs || []).map(AssetUtils.convertGraphQLRecordingDocForRedux))); 28262 else dispatch(loadingProjectRecordingDocSuccess(projectName, recordingDocs)); 28263 dispatch(loadingProjectLifeCycleSuccess(accountId, projectName, projectLifecycle)); 28264 const { data: allCreativesNarrationRecordings } = creativeRecordingAssetsData; 28265 dispatch(loadingCreativeRecordingAssetsSuccess(projectName, allCreativesNarrationRecordings)); 28266 let resArray = []; 28267 if (version) try { 28268 await loadProjectSnapshotPromise(services, state(), dispatch, accountId, projectName, version); 28269 } catch (e) { 28270 failedToGetVersion = true; 28271 throw e; 28272 } 28273 else if (stages && stages.length > 0) { 28274 resArray = await getProjectLifecycleHistory(state, services, accountId, projectName, programId, stages, forceLoad); 28275 if (resArray) { 28276 let stagePromises = []; 28277 resArray.forEach((res) => { 28278 if (stages.includes(res.name)) { 28279 dispatch(loadingProjectLifeCycleStageSuccess(accountId, projectName, res, res.name)); 28280 if (res.snapshots[0]) stagePromises.push(loadProjectSnapshotPromise(services, state(), dispatch, accountId, projectName, res.snapshots[0].snapshotNumber)); 28281 } 28282 }); 28283 await Promise.all(stagePromises); 28284 } else graphQlError = true; 28285 } 28286 dispatch(setLoading(false, accountId, projectName)); 28287 if (cb instanceof Function) cb(); 28288 }).catch((err) => { 28289 if (failedToGetVersion) dispatch(reportError(`Version ${version} doesn't exist.`)); 28290 else if (!graphQlError) dispatch(reportError(err)); 28291 dispatch(setLoading(false, accountId, projectName)); 28292 }); 28293 }; 28294}; 28295var loadProjectAndAssets = memoizeThunkAction((accountId, projectName, versionIdOrNumber, includeCreativeNarrations, stage, version) => { 28296 return async function(dispatch, getState, services) { 28297 let { programId, programVersionId: draftVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 28298 const isDraft = versionIdOrNumber === draftVersionId; 28299 let loadVersionFromDynamo = false;
28300 let programVersionId = versionIdOrNumber; 28301 if (typeof versionIdOrNumber === "number") { 28302 const snapshotDetails = StateReaderUtils.getSnapshotDetails(getState(), versionIdOrNumber); 28303 if (snapshotDetails.snapshotSource === SnapshotSource.POSTGRES) programVersionId = snapshotDetails.graphQLId; 28304 else { 28305 programVersionId = draftVersionId; 28306 loadVersionFromDynamo = true; 28307 } 28308 } 28309 try { 28310 dispatch(setLoading(true, accountId, projectName)); 28311 const creativeEnabled = StateReaderUtils.isFeatureEnable(getState(), CREATIVE); 28312 let creativeRecordingAssetsPromise; 28313 if (creativeEnabled && isDraft && includeCreativeNarrations) creativeRecordingAssetsPromise = services.graphQlClient.query({ 28314 fetchPolicy: "no-cache", 28315 query: GetAllCreativesNarrationRecordingsDocument, 28316 variables: { id: programId } 28317 }); 28318 else creativeRecordingAssetsPromise = Promise.resolve({ data: { program: { creatives: [] } } }); 28319 const [gqlProgramResponse, creativeRecordingAssetsData] = await Promise.all([services.graphQlClient.query({ 28320 fetchPolicy: "no-cache", 28321 query: GetProgramWithAssetsDocument, 28322 variables: { 28323 programId, 28324 programVersionId 28325 } 28326 }), creativeRecordingAssetsPromise]); 28327 const gqlProgram = gqlProgramResponse?.data?.program; 28328 dispatch(loadingProjectDetailsSuccess(buildProgramFromGql(gqlProgram))); 28329 const gqlProgramVersion = gqlProgramResponse?.data?.program?.programVersion; 28330 if (!isDraft) if (loadVersionFromDynamo) dispatch(loadingProjectSnapshotSuccess(accountId, projectName, await services.projectLifeCycleServices.getProjectSnapshot(accountId, projectName, versionIdOrNumber))); 28331 else dispatch(loadingProjectSnapshotSuccess(accountId, projectName, buildStateSnapshotFromGql(gqlProgramVersion, buildStateSnapshotAssetsFromGql(gqlProgramVersion.assets, gqlProgramVersion.animations, gqlProgramVersion.dataTables, gqlProgramVersion.narrationRecordings, gqlProgramVersion.narrators)))); 28332 const gqlNarrators = gqlProgramVersion.narrators; 28333 dispatch(loadingProjectAssetsSuccess(projectName, { Items: buildNarratorsFromGql(accountId, projectName, gqlNarrators) }, !isDraft)); 28334 let convertedAssets = gqlProgramVersion.assets.map(convertPostgresAssetToDynamoAsset); 28335 let totalCount = convertedAssets.length; 28336 dispatch(loadingProjectAssetsCountSuccess(projectName, { totalCount }, AssetTypes.curated)); 28337 dispatch(loadingProjectAssetsSuccess(projectName, { Items: convertedAssets }, !isDraft)); 28338 dispatch(loadingProjectAssetsSuccess(projectName, { Items: gqlProgramVersion.animations.map(convertPostgresAnimationToDynamoAnimation) }, !isDraft)); 28339 dispatch(loadingProjectAssetsSuccess(projectName, { Items: gqlProgramVersion.dataTables.map(buildDataTableFromGql) }, !isDraft)); 28340 dispatch(loadingProjectAssetsSuccess(projectName, { Items: buildNarrationRecordingsFromGql(accountId, projectName, gqlProgramVersion.narrationRecordings, gqlProgram.isEditor) }, !isDraft)); 28341 dispatch(loadingProjectRecordingDocSuccess(projectName, gqlProgramVersion.recordingDocs.map(AssetUtils.convertGraphQLRecordingDocForRedux))); 28342 const { data: allCreativesNarrationRecordings } = creativeRecordingAssetsData; 28343 dispatch(loadingCreativeRecordingAssetsSuccess(projectName, allCreativesNarrationRecordings)); 28344 } catch (err) { 28345 dispatch(reportError(err)); 28346 } finally { 28347 dispatch(setLoading(false, accountId, projectName, stage, version)); 28348 } 28349 }; 28350}); 28351var loadGraphQLProgram = (accountId, projectName) => { 28352 return (dispatch, getState, services) => { 28353 const { programId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 28354 services.graphQlClient.query({ 28355 query: GetProgramDocument, 28356 variables: { 28357 id: programId, 28358 [IGNORE_SERVER_ERRORS]: true 28359 } 28360 }).then((result) => { 28361 dispatch(loadingGqlProgramSuccess(result.data.program)); 28362 }); 28363 }; 28364}; 28365var loadProjectForDashboard = (accountId, stages) => { 28366 return (dispatch, state, services) => { 28367 dispatch(setLoading(true, accountId, void 0)); 28368 services.projectServices.getProjects(accountId).then((data) => { 28369 dispatch(loadingAllProjectsSuccess(data)); 28370 data.forEach((project) => { 28371 dispatch(setLoading(true, accountId, project.projectName)); 28372 let projectName = project.projectName; 28373 let promises = [services.projectServices.getProject(accountId, projectName), services.projectLifeCycleServices.getProjectLifeCycle(accountId, projectName)]; 28374 Promise.all(promises).then(async ([project, projectLifecycle]) => { 28375 if (project) { 28376 dispatch(loadingProjectDetailsSuccess(project)); 28377 dispatch(loadingProjectLifeCycleSuccess(accountId, projectName, projectLifecycle)); 28378 } else dispatch(reportError("Project " + projectName + " not found")); 28379 let resArray = []; 28380 if (stages && stages.length > 0) { 28381 let programId = StateReaderUtils.getProgramId(state(), projectName); 28382 if (!programId) { 28383 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 28384 programId = StateReaderUtils.getProgramId({ projectSummaries }, projectName); 28385 } 28386 resArray = await getProjectLifecycleHistory(state, services, accountId, projectName, programId, stages); 28387 } 28388 resArray.forEach((res) => { 28389 dispatch(loadingProjectLifeCycleStageSuccess(accountId, projectName, res, res.name)); 28390 }); 28391 dispatch(setLoading(false, accountId, projectName)); 28392 }).catch((err) => { 28393 dispatch(reportError(err)); 28394 dispatch(setLoading(false, accountId, projectName)); 28395 }); 28396 }); 28397 dispatch(setLoading(false, accountId, void 0)); 28398 }); 28399 }; 28400}; 28401var updateProject = function(accountId, projectName, project) { 28402 return async function(dispatch, getState, services) { 28403 const { programId, programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 28404 try { 28405 const currentProgram = StateReaderUtils.getProject(getState(), projectName); 28406 const gqlProgram = getProgramFromGQLResponse(await mutateProjectUpdate(programId, programVersionId, project, services)); 28407 const updatedFields = Object.keys(project); 28408 if (updatedFields.includes("displayName") && currentProgram.displayName !== project.displayName || updatedFields.includes("creativeVersion") && currentProgram.creativeVersion !== project.creativeVersion || updatedFields.includes("programId") && currentProgram.programId !== project.programId || updatedFields.includes("programType") && currentProgram.programType !== project.programType) dispatch(loadProjectSummariesSuccess(await services.projectServices.loadProjectSummaries(accountId))); 28409 dispatch(updateProjectComplete({ 28410 ...project, 28411 projectName, 28412 graphQLUpdated: gqlProgram.updated 28413 })); 28414 } catch (err) { 28415 dispatch(reportError(err)); 28416 } 28417 }; 28418}; 28419var updateArchiveProgram = function(programId, updatedIsArchive, cb) { 28420 return async function(dispatch, getState, services) { 28421 const onArchiveSuccess = () => { 28422 dispatch(updateProgramSummarySuccess(programId, { isArchive: updatedIsArchive })); 28423 cb(); 28424 }; 28425 if (StateReaderUtils.isEditorProgram(getState(), programId)) { 28426 const input = { 28427 id: programId, 28428 updated: IGNORE_UPDATED, 28429 isArchive: updatedIsArchive 28430 }; 28431 if ((await services.graphQlClient.mutate({ 28432 mutation: UpdateEditorIsArchivedDocument, 28433 variables: { input } 28434 }))?.data?.updateEditorIsArchived?.result === GqlClientUpdateEditorIsArchivedResult.SUCCESS) onArchiveSuccess(); 28435 } else {
28436 const input = { 28437 id: programId, 28438 updated: IGNORE_UPDATED, 28439 isArchive: updatedIsArchive 28440 }; 28441 if ((await services.graphQlClient.mutate({ 28442 mutation: UpdateProgramDocument, 28443 variables: { input } 28444 }))?.data?.updateProgram?.__typename === "UpdateProgramOutputSuccess") onArchiveSuccess(); 28445 } 28446 }; 28447}; 28448var updateProjectThumbnail = function(accountId, projectName, projectThumbnail, cb) { 28449 return function(dispatch, state, services) { 28450 dispatch(setLoading(true, accountId, projectName)); 28451 services.projectServices.addProjectThumbnail(accountId, projectName, projectThumbnail).then(function(updatedProject) { 28452 dispatch(updateProjectComplete(updatedProject)); 28453 if (cb instanceof Function) cb(); 28454 dispatch(setLoading(false, accountId, projectName)); 28455 }).catch(function(err) { 28456 dispatch(reportError(err)); 28457 dispatch(setLoading(false, accountId, projectName)); 28458 }); 28459 }; 28460}; 28461/** 28462* When the GQL Builders FF is open and we create a program, we need to create a Builder program version in Postgres as well or else 28463* all GQL mutations in the Builder will fail (NOT_IN_DB => no program version). 28464* Creation of Builder program version can occur when: 28465* 1. creating a new program as described above. 28466* 2. clicking "+ Builder" when there is only Framework in the program. 28467* Both cases are handled here. This is why `postgresProgramId` and `shouldCreateProgram` params were added to this thunk 28468* **/ 28469var addProject = ({ accountId, postgresProgramId, project, shouldCreateProgram, history, cb }) => { 28470 return async (dispatch, getState, services) => { 28471 let audienceDeId; 28472 let projectName; 28473 project.narrationsVersion = 1; 28474 project.RFR = 0; 28475 project.storiesVersion = 1; 28476 let state = getState(); 28477 const permanentlyMigratedToPostgres = programDefaultDynamoMigrationStatusFields.most_entities === "done" || accountId === "0010b00002R0wc3AAB"; 28478 if (!permanentlyMigratedToPostgres) try { 28479 let data = await services.projectServices.addProject(accountId, project); 28480 projectName = data.projectName; 28481 if (data.programType && data.programType.toLowerCase() === programTypes.ADS.toLowerCase()) audienceDeId = (await services.dataElements.addDataElement(accountId, data.projectName, adsDataElements[0])).id; 28482 dispatch(addProjectSuccess(data)); 28483 if (cb instanceof Function) cb(data); 28484 } catch (err) { 28485 dispatch(reportError(err)); 28486 return; 28487 } 28488 try { 28489 if (project.programType && project.programType.toLowerCase() === programTypes.ADS.toLowerCase() && !audienceDeId) audienceDeId = v4(); 28490 let newlyCreatedProgram; 28491 if (shouldCreateProgram) if (project.isEditor) { 28492 const mutationVariables = { 28493 input: { 28494 name: project.projectDisplayName, 28495 type: getGQLEditorProgramType(project.programType), 28496 accountCcLibraryId: CC_LIBRARY_ID, 28497 aspectRatio: project.aspectRatio 28498 }, 28499 [IGNORE_SERVER_ERRORS]: true 28500 }; 28501 newlyCreatedProgram = (await services.graphQlClient.mutate({ 28502 mutation: CreateEditorProgramDocument, 28503 variables: mutationVariables 28504 })).data.createEditorProgram.editorProgram; 28505 } else { 28506 const mutationVariables = { 28507 input: { 28508 name: project.projectDisplayName, 28509 type: getGQLProgramType(project.programType) 28510 }, 28511 legacyBuilderProgramId: projectName, 28512 legacyAudienceDataElementId: audienceDeId, 28513 [IGNORE_SERVER_ERRORS]: true 28514 }; 28515 newlyCreatedProgram = (await services.graphQlClient.mutate({ 28516 mutation: CreateProgramAndBuilderDraftDocument, 28517 variables: mutationVariables 28518 })).data.createProgramAndBuilderDraft.program; 28519 } 28520 else { 28521 const mutationVariables = { 28522 input: { 28523 name: project.projectDisplayName, 28524 type: getGQLProgramType(project.programType), 28525 isBuilder: true 28526 }, 28527 programId: postgresProgramId, 28528 legacyBuilderProgramId: projectName, 28529 legacyAudienceDataElementId: audienceDeId, 28530 [IGNORE_SERVER_ERRORS]: true 28531 }; 28532 newlyCreatedProgram = (await services.graphQlClient.mutate({ 28533 mutation: CreateProgramVersionDraftDocument, 28534 variables: mutationVariables 28535 })).data.createProgramVersionDraft.programVersion.program; 28536 } 28537 if (permanentlyMigratedToPostgres) { 28538 project.displayName = project.projectDisplayName; 28539 project.description = project.projectDescription; 28540 project.projectName = newlyCreatedProgram.id; 28541 project.graphQLId = newlyCreatedProgram.id; 28542 project.graphQLUpdated = newlyCreatedProgram.created; 28543 if (!project.isEditor) project.graphQLBuilderDraftId = newlyCreatedProgram.programVersions[0].id; 28544 dispatch(addProjectSuccess(project)); 28545 } 28546 const userRoles = StateReaderUtils.getUserRoles(state); 28547 const loadProjectSummariesCB = (accountId, forceLoad, cb) => dispatch(loadProjectSummaries(accountId, forceLoad, cb)); 28548 Program.navigateToProgramAfterCreation(loadProjectSummariesCB, userRoles, newlyCreatedProgram, history, project.isEditor ? import_dist$9.StudioMainCategoriesPaths.Editor : void 0); 28549 dispatch(loadProgramsMigrationStatus()); 28550 dispatch(setLoading(false, accountId, projectName)); 28551 } catch (err) { 28552 if (permanentlyMigratedToPostgres) dispatch(reportError(err)); 28553 } 28554 }; 28555}; 28556var duplicateProgram = ({ accountId, sourceProgramVersionId, targetAccountId, targetProgramName, targetProgramDescription, isEditor, history, cb }) => { 28557 return async (dispatch, getState, services) => { 28558 let isError = false;
28559 try { 28560 dispatch(setLoading(true, accountId, void 0)); 28561 let input = { 28562 sourceProgramVersionId, 28563 targetProgramName, 28564 targetProgramDescription, 28565 copyStoryTemplateData: true 28566 }; 28567 if (accountId !== targetAccountId) input.targetAccountId = targetAccountId; 28568 let newlyCreatedProgram; 28569 if (isEditor) { 28570 const { data: { copyEditorProgram } } = await services.graphQlClient.mutate({ 28571 mutation: CopyEditorProgramDocument, 28572 variables: { 28573 input, 28574 [IGNORE_SERVER_ERRORS]: true 28575 } 28576 }); 28577 newlyCreatedProgram = copyEditorProgram.targetProgram; 28578 } else { 28579 const { data: { copyProgram } } = await services.graphQlClient.mutate({ 28580 mutation: CopyProgramDocument, 28581 variables: { 28582 input, 28583 [IGNORE_SERVER_ERRORS]: true 28584 } 28585 }); 28586 newlyCreatedProgram = copyProgram.targetProgram; 28587 } 28588 dispatch(loadFeatureFlags()); 28589 dispatch(loadProgramsMigrationStatus()); 28590 const userRoles = StateReaderUtils.getUserRoles(getState()); 28591 const loadProjectSummariesCB = (accountId, forceLoad, cb) => dispatch(loadProjectSummaries(accountId, forceLoad, cb)); 28592 Program.navigateToProgramAfterCreation(loadProjectSummariesCB, userRoles, newlyCreatedProgram, history, isEditor ? import_dist$9.StudioMainCategoriesPaths.Overview : void 0); 28593 } catch (error) { 28594 isError = true; 28595 let sskyCode = SskyErrorCode.CopyProgramFailed; 28596 if (getSskyErrorCodeFromGqlError(error?.graphQLErrors?.[0]) === SskyErrorCode.DuplicateProgramWithRemovedWireframeError) sskyCode = SskyErrorCode.DuplicateProgramWithRemovedWireframeError; 28597 handleEditorError({ 28598 error, 28599 sskyCode 28600 }); 28601 } finally { 28602 dispatch(setLoading(false, accountId, void 0)); 28603 if (typeof cb === "function") cb(isError); 28604 } 28605 }; 28606}; 28607var copyProgramBetweenAccounts = ({ accountId, sourceProgramVersionId, targetAccountId, targetProgramName, targetProgramDescription, history, cb }) => { 28608 return async (dispatch, getState, services) => { 28609 let isError = false; 28610 try { 28611 dispatch(setLoading(true, accountId, void 0)); 28612 const input = { 28613 sourceDraftEditorProgramId: sourceProgramVersionId, 28614 targetAccount: targetAccountId, 28615 name: targetProgramName, 28616 description: targetProgramDescription 28617 }; 28618 let newlyCreatedProgram; 28619 const { data: { copyDraftEditorProgramBetweenAccounts } } = await services.graphQlClient.mutate({ 28620 mutation: CopyDraftEditorProgramBetweenAccountsDocument, 28621 variables: { 28622 input, 28623 [IGNORE_SERVER_ERRORS]: true 28624 } 28625 }); 28626 newlyCreatedProgram = copyDraftEditorProgramBetweenAccounts.editorProgram; 28627 dispatch(loadFeatureFlags()); 28628 dispatch(loadProgramsMigrationStatus()); 28629 const userRoles = StateReaderUtils.getUserRoles(getState()); 28630 const loadProjectSummariesCB = (accountId, forceLoad, cb) => dispatch(loadProjectSummaries(accountId, forceLoad, cb)); 28631 Program.navigateToProgramAfterCreation(loadProjectSummariesCB, userRoles, newlyCreatedProgram, history, import_dist$9.StudioMainCategoriesPaths.Overview); 28632 } catch (error) { 28633 isError = true; 28634 let sskyCode = SskyErrorCode.CopyProgramBetweenAccountsFailed; 28635 if (getSskyErrorCodeFromGqlError(error?.graphQLErrors?.[0]) === SskyErrorCode.DuplicateProgramWithRemovedWireframeError) sskyCode = SskyErrorCode.DuplicateProgramWithRemovedWireframeError; 28636 handleEditorError({ 28637 error, 28638 sskyCode 28639 }); 28640 } finally { 28641 dispatch(setLoading(false, accountId, void 0)); 28642 if (typeof cb === "function") cb(isError); 28643 } 28644 }; 28645}; 28646var getNewPrograms = function(accountId) { 28647 return function(dispatch, state, services) { 28648 dispatch(setLoading(true, accountId, void 0)); 28649 services.projectServices.getNewPrograms(accountId).then(function(data) { 28650 dispatch(getNewProgramsSuccess(accountId, data)); 28651 dispatch(setLoading(false, accountId, void 0)); 28652 }).catch(function(err) { 28653 dispatch(reportError(err)); 28654 dispatch(setLoading(false, accountId, void 0)); 28655 }); 28656 }; 28657}; 28658var getProjectVersions = function(accountId, projectName) { 28659 return async function(dispatch, getState, services) { 28660 let programId = StateReaderUtils.getProgramId(getState(), projectName); 28661 if (!programId) { 28662 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 28663 programId = StateReaderUtils.getProgramId({ projectSummaries }, projectName); 28664 } 28665 const combineSnapshots = (postgresSnapshots, dynamoSnapshots) => { 28666 if (!postgresSnapshots || !postgresSnapshots[0]) return dynamoSnapshots; 28667 if (!dynamoSnapshots || !dynamoSnapshots[0]) return postgresSnapshots; 28668 const dynamoSnapshotsObject = convertArrayOfObjectsToObject(dynamoSnapshots, "snapshotNumber"); 28669 const postgresSnapshotsObject = convertArrayOfObjectsToObject(postgresSnapshots, "snapshotNumber"); 28670 const combineSnapshotsObject = { 28671 ...dynamoSnapshotsObject, 28672 ...postgresSnapshotsObject 28673 }; 28674 return Object.values(combineSnapshotsObject).sort((a, b) => a.snapshotNumber - b.snapshotNumber); 28675 }; 28676 return Promise.all([services.projectServices.getProjectSnapshots(accountId, projectName), services.graphQlClient.query({ 28677 fetchPolicy: "no-cache", 28678 query: GetProgramVersionSnapshotsDocument, 28679 variables: { programId } 28680 })]).then(([data, gqlData]) => { 28681 const postgresSnapshots = buildStateVersionsFromGql(gqlData.data.program.programVersionSnapshots); 28682 const dynamoSnapshots = data && data.Items && data.Items.map((snapshot) => { 28683 snapshot.snapshotSource = SnapshotSource.DYNAMO; 28684 return snapshot; 28685 }); 28686 dispatch(getProjectVersionsComplete(projectName, combineSnapshots(postgresSnapshots, dynamoSnapshots))); 28687 }).catch(function(err) { 28688 dispatch(reportError(err)); 28689 }); 28690 }; 28691}; 28692var getProjectVersionsForDuplicate = function(accountId, projectName, cb) { 28693 return async function(dispatch, getState, services) { 28694 let programId = StateReaderUtils.getProgramId(getState(), projectName); 28695 if (!programId) { 28696 const projectSummaries = await services.projectServices.loadProjectSummaries(accountId); 28697 programId = StateReaderUtils.getProgramId({ projectSummaries }, projectName); 28698 } 28699 return Promise.all([ 28700 services.projectServices.getProjectSnapshots(accountId, projectName), 28701 services.graphQlClient.query({ 28702 fetchPolicy: "no-cache", 28703 query: GetProgramVersionSnapshotsDocument, 28704 variables: { programId } 28705 }), 28706 services.projectLifeCycleServices.getProjectLifeCycle(accountId, projectName) 28707 ]).then(([projectSnapshots, gqlProjectSnapshots, projectLifecycle]) => { 28708 const postgresSnapshots = gqlProjectSnapshots.data.program.programVersionSnapshots; 28709 const dynamoSnapshots = projectSnapshots && projectSnapshots.Items && projectSnapshots.Items.map((snapshot) => { 28710 snapshot.snapshotSource = SnapshotSource.DYNAMO; 28711 return snapshot; 28712 }); 28713 let devVersion; 28714 let uatVersion; 28715 let prodVersion; 28716 projectLifecycle?.forEach((lifecycle) => { 28717 switch (lifecycle.stage) { 28718 case Stages.dev: 28719 devVersion = lifecycle.snapshotNumber; 28720 break; 28721 case Stages.UAT: 28722 uatVersion = lifecycle.snapshotNumber; 28723 break; 28724 case Stages.prod: 28725 prodVersion = lifecycle.snapshotNumber; 28726 break; 28727 } 28728 }); 28729 const allVersions = postgresSnapshots.map((snapshot) => ({ 28730 ...snapshot, 28731 activeStages: getActiveStages(snapshot.snapshotNumber, devVersion, uatVersion, prodVersion).reverse() 28732 })); 28733 const gqlSnapshotByNumber = convertArrayOfObjectsToObject(postgresSnapshots, "snapshotNumber"); 28734 const isPartialVersions = dynamoSnapshots.some((snapshot) => !gqlSnapshotByNumber[snapshot.snapshotNumber]); 28735 if (typeof cb === "function") cb(allVersions, isPartialVersions); 28736 }).catch(function(err) { 28737 dispatch(reportError(err)); 28738 }); 28739 }; 28740}; 28741var loadProjectSummaries = (accountId, forceLoad = false, cb) => { 28742 return (dispatch, getState, services) => { 28743 let projectSummaries = StateReaderUtils.getProgramSummaries(getState()); 28744 if (!forceLoad && projectSummaries && projectSummaries.length > 0) return; 28745 dispatch(setLoading(true, accountId, void 0)); 28746 services.projectServices.loadProjectSummaries(accountId).then((projectSummaries) => { 28747 dispatch(loadProjectSummariesSuccess(projectSummaries)); 28748 if (cb instanceof Function) cb(); 28749 dispatch(setLoading(false, accountId, void 0)); 28750 }).catch(function(err) { 28751 dispatch(reportError(err)); 28752 dispatch(setLoading(false, accountId, void 0)); 28753 }); 28754 }; 28755}; 28756var updateProjectStorySelectionLogic = (accountId, projectName, storySelectionLogic) => { 28757 return (dispatch, getState, services) => { 28758 const program = StateReaderUtils.getProject(getState(), projectName); 28759 const isProgramPermanentlyMigratedToPostgres = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), program.graphQLId, BulkId.MostEntities); 28760 let dataToDispatch = { 28761 logicContainerType: LogicContainers.StorySelection, 28762 logicItems: { [LogicContainers.StorySelection]: storySelectionLogic } 28763 }; 28764 if (!isProgramPermanentlyMigratedToPostgres) return services.wireframes.setProjectWireFramesSceneInputLogic(accountId, projectName, LogicContainers.Program, getDynamoLogicContainerId(LogicContainers.StorySelection, LogicContainers.StorySelection), storySelectionLogic).then(() => { 28765 dispatch(updateProgramLogicItems(projectName, dataToDispatch)); 28766 }).then(() => { 28767 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 28768 let input = { 28769 id: programVersionId, 28770 updated: IGNORE_UPDATED, 28771 storySelectionLogic 28772 }; 28773 return services.graphQlClient.mutate({ 28774 mutation: UpdateProgramVersionDocument, 28775 variables: { 28776 input, 28777 [IGNORE_SERVER_ERRORS]: true 28778 } 28779 }).catch(() => {}); 28780 }).catch((err) => dispatch(reportError(err))); 28781 else {
28782 const { programVersionId } = StateReaderUtils.getBuilderProgramAndDraftVersionIds(getState(), projectName); 28783 let input = { 28784 id: programVersionId, 28785 updated: IGNORE_UPDATED, 28786 storySelectionLogic 28787 }; 28788 return services.graphQlClient.mutate({ 28789 mutation: UpdateProgramVersionDocument, 28790 variables: { 28791 input, 28792 [IGNORE_SERVER_ERRORS]: true 28793 } 28794 }).then((res) => { 28795 const program = getProgramFromGQLResponse(res); 28796 dataToDispatch.updated = program.updated; 28797 dispatch(updateProgramLogicItems(projectName, dataToDispatch)); 28798 }).catch((err) => dispatch(reportError(err))); 28799 } 28800 }; 28801}; 28802var getProjectLifecycleHistory = async (getState, services, accountId, projectName, programId, stages, forceLoad) => { 28803 const readBuilderLifecycleHistoryFromPostgres = StateReaderUtils.isProgramBulkDynamoMigrationDone(getState(), programId, BulkId.LifecycleHistory); 28804 let dynamoProjectLifecycleHistory; 28805 let gqlProjectLifecycleHistory; 28806 if (!readBuilderLifecycleHistoryFromPostgres) { 28807 let promises = []; 28808 stages.forEac
28808h((stage) => { 28809 if (StateReaderUtils.getProjectStageSnapshots(getState(), projectName, stage).length <= 1 || forceLoad) promises.push(services.projectLifeCycleServices.getProjectLifecycleStage(accountId, projectName, stage)); 28810 }); 28811 dynamoProjectLifecycleHistory = await Promise.all(promises); 28812 } 28813 if (readBuilderLifecycleHistoryFromPostgres) gqlProjectLifecycleHistory = convertGqlLifecycleHistoryResult(await services.graphQlClient.query({ 28814 fetchPolicy: "no-cache", 28815 query: GetProgramLifecycleHistoryDocument, 28816 variables: { programId } 28817 }).catch(() => null)); 28818 return readBuilderLifecycleHistoryFromPostgres ? gqlProjectLifecycleHistory : dynamoProjectLifecycleHistory; 28819}; 28820//#endregion 28821//#region client/logic/projects/projectsReducer.ts 28822function projectsReducer(state, action) { 28823 let projectAllNames; 28824 let projectsByName; 28825 switch (action.type) { 28826 case LOADING_ALL_PROJECTS_SUCCESS: { 28827 let byName = action.payload.projects.reduce((acc, cur) => { 28828 acc[cur.projectName] = cur; 28829 return acc; 28830 }, {}); 28831 let allNames = action.payload.projects.reduce((acc, cur) => { 28832 acc.push(cur.projectName); 28833 return acc; 28834 }, []); 28835 return Object.assign({}, state, { 28836 projects: { 28837 byName, 28838 allNames, 28839 isInitialized: true 28840 }, 28841 error: false 28842 }); 28843 } 28844 case UPDATE_PROGRAM_SUMMARY_SUCCESS: { 28845 const { programId, updatedFields } = action.payload; 28846 const currProgramSummaries = StateReaderUtils.getProgramSummaries(state); 28847 let updatedProgramSummaries = [...currProgramSummaries]; 28848 const programSummeryIndex = findProgramSummaryIndexForProgramId(currProgramSummaries, programId); 28849 if (programSummeryIndex > -1) { 28850 const currProgramSummary = currProgramSummaries[programSummeryIndex]; 28851 updatedProgramSummaries.splice(programSummeryIndex, 1, { 28852 ...currProgramSummary, 28853 ...updatedFields 28854 }); 28855 } 28856 return { 28857 ...state, 28858 projectSummaries: updatedProgramSummaries 28859 }; 28860 } 28861 case ADD_PROJECT_SUCCESS: { 28862 projectsByName = state.projects.byName; 28863 projectsByName = { 28864 ...projectsByName, 28865 [action.payload.projectName]: action.payload 28866 }; 28867 projectAllNames = [...state.projects.allNames, action.payload.projectName]; 28868 const showCampaignSettings = action.payload.programType === ProgramType.Ads && StateReaderUtils.isAllowedCampaignSetting(state); 28869 const showReports = action.payload.programType !== ProgramType.Ads && StateReaderUtils.isAllowedDetailedReport(state); 28870 const showExperiments = action.payload.programType !== ProgramType.Ads && StateReaderUtils.isAllowedExperiments(state); 28871 const isEditor = action.payload.isEditor; 28872 let programSummary = { 28873 id: action.payload.graphQLId, 28874 displayName: action.payload.displayName, 28875 isLegacy: action.payload.isLegacy || false, 28876 programType: action.payload.programType, 28877 showCreative: false, 28878 campaignSettings: showCampaignSettings, 28879 showReports, 28880 showExperiments, 28881 isArchive: false, 28882 isEditor, 28883 projectIds: { 28884 builders: action.payload.projectName, 28885 dashboards: void 0, 28886 canvas: void 0, 28887 sfId: action.payload.programId, 28888 builderDraftVersionId: action.payload.graphQLBuilderDraftId 28889 }, 28890 reasonsCopyToOtherAccountIsForbidden: [], 28891 notificationCopyToAnotherAccount: NotificationCopyToAnotherAccount.None 28892 }; 28893 let projectSummaries = [...state.projectSummaries, programSummary]; 28894 projectSummaries = projectSummaries.sort((projectA, projectB) => projectA.displayName.localeCompare(projectB.displayName)); 28895 return { 28896 ...state, 28897 projects: { 28898 byName: projectsByName, 28899 allNames: projectAllNames, 28900 isInitialized: true 28901 }, 28902 projectSummaries, 28903 error: false 28904 }; 28905 } 28906 case DELETE_PROJECT_COMPLETE: return Object.assign({}, state, { 28907 projects: [...state.projects.slice(0, action.payload.index), ...state.projects.slice(action.payload.index + 1)], 28908 error: false 28909 }); 28910 case UPDATE_PROJECT_COMPLETE: { 28911 const project = action.payload.project; 28912 projectsByName = { 28913 ...state.projects.byName, 28914 [project.projectName]: { 28915 ...state.projects.byName[project.projectName], 28916 ...project 28917 } 28918 }; 28919 projectAllNames = state.projects.allNames; 28920 return { 28921 ...state, 28922 projects: {
28923 byName: projectsByName, 28924 allNames: projectAllNames, 28925 isInitialized: true 28926 }, 28927 error: false 28928 }; 28929 } 28930 case LOADING_PROJECT_DETAILS_SUCCESS: 28931 projectAllNames = state.projects.allNames.indexOf(action.payload.project.projectName) < 0 ? [...state.projects.allNames, action.payload.project.projectName] : state.projects.allNames; 28932 projectsByName = { 28933 ...state.projects.byName, 28934 [action.payload.project.projectName]: { 28935 ...state.projects.byName[action.payload.project.projectName], 28936 ...action.payload.project 28937 } 28938 }; 28939 return Object.assign({}, state, { 28940 projects: { 28941 byName: projectsByName, 28942 allNames: projectAllNames, 28943 isInitialized: true 28944 }, 28945 error: false 28946 }); 28947 case LOADING_NEW_PROGRAMS_SUCCESS: return Object.assign({}, state, { newPrograms: action.payload.newPrograms }); 28948 case GET_PROJECT_VERSIONS_COMPLETE: { 28949 const snapshots = action.payload.versions; 28950 const projectName = action.payload.projectName; 28951 let newState = immutablyReplaceValue(state, ["versions"], snapshots); 28952 const snapshotsById = state.snapshots?.byId || {}; 28953 const allIds = snapshots.map((snapshot) => `${projectName}/${snapshot.snapshotNumber}`); 28954 const byId = snapshots.reduce((acc, snapshot, index) => { 28955 const snapshotId = allIds[index]; 28956 acc[snapshotId] = snapshotsById[snapshotId]?.assets ? { 28957 ...snapshot, 28958 assets: snapshotsById[snapshotId].assets 28959 } : snapshot; 28960 return acc; 28961 }, {}); 28962 newState = immutablyReplaceValue(newState, ["snapshots", "allIds"], allIds); 28963 newState = immutablyReplaceValue(newState, ["snapshots", "byId"], byId); 28964 return newState; 28965 } 28966 case LOAD_PROJECT_SUMMARIES_SUCCESS: { 28967 let sortedProjects = action.payload.projectSummaries.sort((projectA, projectB) => projectA.displayName.localeCompare(projectB.displayName)); 28968 return { 28969 ...state, 28970 projectSummaries: sortedProjects 28971 }; 28972 } 28973 case LOADING_REC_DOC_SUCCESS: { 28974 let recordingDocs = []; 28975 if (action.payload && action.payload.docs && action.payload.docs && action.payload.docs.length > 0) recordingDocs = [...action.payload.docs]; 28976 return Object.assign({}, state, { recordingDocs }); 28977 } 28978 case GENERATE_REC_DOC_SUCCESS: { 28979 let recordingDocs = state.recordingDocs ? [...state.recordingDocs] : []; 28980 if (action.payload && action.payload.recordingDoc) { 28981 let recDoc = { ...action.payload.recordingDoc }; 28982 recordingDocs.push(recDoc); 28983 } 28984 return Object.assign({}, state, { recordingDocs }); 28985 } 28986 case UPDATE_PROGRAM_LOGIC_ITEMS: { 28987 let { projectName, data } = action.payload; 28988 let { logicContainerType, logicItems, updated } = data; 28989 let byName = state.wireframes.byName; 28990 let allNames = state.wireframes.allNames; 28991 let currentLogic = byName[projectName] ? byName[projectName].logic : {}; 28992 let currentProgramLogic = currentLogic[LogicContainers.Program] || {}; 28993 projectsByName = state.projects.byName; 28994 if (updated) projectsByName = { 28995 ...projectsByName, 28996 [projectName]: { 28997 ...projectsByName[projectName], 28998 graphQLUpdated: updated 28999 } 29000 }; 29001 return { 29002 ...state, 29003 projects: { 29004 allNames: state.projects.allNames, 29005 byName: projectsByName 29006 }, 29007 wireframes: { 29008 byName: { 29009 ...byName, 29010 [projectName]: { 29011 ...byName[projectName], 29012 logic: { 29013 ...currentLogic, 29014 [LogicContainers.Program]: { 29015 ...currentProgramLogic, 29016 [logicContainerType]: { 29017 ...currentProgramLogic[logicContainerType], 29018 ...logicItems 29019 } 29020 } 29021 } 29022 } 29023 }, 29024 allNames 29025 }, 29026 error: false 29027 }; 29028 } 29029 case LOADING_GQL_PROGRAM_SUCCESS: { 29030 const { program } = action.payload; 29031 return { 29032 ...state, 29033 activeGqlProgram: program 29034 }; 29035 } 29036 default: return state; 29037 } 29038} 29039//#endregion 29040//#region client/logic/projects/projectAssets/projectAssetsReducer.ts 29041function assetsReducer(state, action) { 29042 let { byName: projectsByName, allNames: projectsAllNames } = state.projects; 29043 let { byId: assetsById, allIds: allAssetsIds } = state.assets; 29044 let uploadingAssets = Array.isArray(state.uploadingAssets) ? [...state.uploadingAssets] : []; 29045 const deleteAsset = (projectName, assetId) => { 29046 let index = allAssetsIds.indexOf(assetId); 29047 let newAllAssetsIds = allAssetsIds; 29048 if (index > -1) { 29049 newAllAssetsIds = [...allAssetsIds.slice(0, index), ...allAssetsIds.slice(index + 1)]; 29050 delete assetsById[assetId]; 29051 let assets = projectsByName[projectName].assets; 29052 let indexInProject = assets.indexOf(assetId); 29053 projectsByName[projectName].assets = [...assets.slice(0, indexInProject), ...assets.slice(indexInProject + 1)]; 29054 } 29055 return newAllAssetsIds; 29056 }; 29057 const updateAssets = (projectName, assets, shouldReplaceCurrent) => { 29058 const allAssetsIdsSet = new Set(allAssetsIds); 29059 const projectAssetsSet = new Set(projectsByName[projectName].assets || []); 29060 assetsById = assetsById ? { ...assetsById } : {}; 29061 for (let i = 0, len = assets.length; i < len; i++) { 29062 const asset = assets[i]; 29063 const assetId = StateReaderUtils.getAssetUniqueId(projectsByName[projectName].accountId, projectName, asset.type, asset.name); 29064 allAssetsIdsSet.add(assetId); 29065 projectAssetsSet.add(assetId); 29066 assetsById[assetId] = shouldReplaceCurrent ? asset : { 29067 ...assetsById[assetId], 29068 ...asset 29069 }; 29070 } 29071 allAssetsIds = [...allAssetsIdsSet]; 29072 projectsByName = { 29073 ...projectsByName, 29074 [projectName]: { 29075 ...projectsByName[projectName], 29076 assets: [...projectAssetsSet] 29077 } 29078 }; 29079 }; 29080 const updateCreativesWithCreativeNarrationRecording = (creativeRecordingAssets, creativeNarrationRecording, projectName) => { 29081 const [programId, creativeId, creativeVersionId, creativeNarrationRecordingVersionId] = creativeNarrationRecording.id.split("|"); 29082 let updatedCreatives = [...creativeRecordingAssets.program.creatives]; 29083 const creativeToUpdateIdx = updatedCreatives.findIndex(({ id }) => id === `${programId}|${creativeId}`);
29084 const currentCreativeNarrationRecordings = updatedCreatives[creativeToUpdateIdx].creativeVersionDraft.creativeNarrationRecordings; 29085 const creativeNarrationRecordingToUpdateIdx = currentCreativeNarrationRecordings.findIndex(({ id }) => id === creativeNarrationRecording.id); 29086 let updatedCreativeNarrationRecordings = [...currentCreativeNarrationRecordings]; 29087 updatedCreativeNarrationRecordings.splice(creativeNarrationRecordingToUpdateIdx, 1, creativeNarrationRecording); 29088 const updatedCreative = { 29089 ...updatedCreatives[creativeToUpdateIdx], 29090 creativeVersionDraft: { 29091 ...updatedCreatives[creativeToUpdateIdx].creativeVersionDraft, 29092 creativeNarrationRecordings: updatedCreativeNarrationRecordings 29093 } 29094 }; 29095 updatedCreatives.splice(creativeToUpdateIdx, 1, updatedCreative); 29096 return updatedCreatives; 29097 }; 29098 switch (action.type) { 29099 case UPLOADING_ASSET: 29100 case LOADING_ASSET_CONTENT: return { 29101 ...state, 29102 error: false 29103 }; 29104 case LOADING_ASSETS_COUNT_SUCCESS: { 29105 let assetType = action.payload.assetType ? action.payload.assetType : "all"; 29106 let projectTotalAssetCount = projectsByName[action.payload.projectName].totalAssetCount || {}; 29107 projectsByName = { 29108 ...projectsByName, 29109 [action.payload.projectName]: { 29110 ...projectsByName[action.payload.projectName], 29111 totalAssetCount: { 29112 ...projectTotalAssetCount, 29113 [assetType]: action.payload.assets.totalCount 29114 } 29115 } 29116 }; 29117 return { 29118 ...state, 29119 projects: { 29120 byName: projectsByName, 29121 allNames: projectsAllNames, 29122 isInitialized: true 29123 }, 29124 assets: { 29125 byId: assetsById, 29126 allIds: allAssetsIds 29127 }, 29128 error: false 29129 }; 29130 } 29131 case DELETE_ASSET_SUCCESS: { 29132 let assetStateId = action.payload.asset.projectId + "/" + action.payload.asset.assetId; 29133 let newAllAssetsIds = deleteAsset(action.payload.projectName, assetStateId); 29134 return { 29135 ...state, 29136 projects: { 29137 byName: projectsByName, 29138 allNames: projectsAllNames, 29139 isInitialized: true 29140 }, 29141 assets: { 29142 byId: assetsById, 29143 allIds: newAllAssetsIds 29144 } 29145 }; 29146 } 29147 case LOADING_ASSETS_SUCCESS: { 29148 const { projectName, assets, versionMode } = action.payload; 29149 updateAssets(projectName, assets.Items, true); 29150 let nextPageAssetUrl = assets.nextPageAssetUrl; 29151 if (nextPageAssetUrl) projectsByName = { 29152 ...projectsByName, 29153 [projectName]: { 29154 ...projectsByName[projectName], 29155 nextPageAssetUrl 29156 } 29157 }; 29158 let newState = immutablyReplaceValue(state, ["assets", "byId"], assetsById); 29159 newState = immutablyReplaceValue(newState, ["assets", "allIds"], allAssetsIds); 29160 if (!versionMode) newState = immutablyReplaceValue(newState, ["projects", "byName"], projectsByName); 29161 newState.error = false; 29162 return newState; 29163 } 29164 case LOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS: { 29165 const { projectName, creativeNarrationRecordings } = action.payload; 29166 const allIds = Array.from(/* @__PURE__ */ new Set([...state.creativeRecordingAssets.allIds, projectName])); 29167 return { 29168 ...state, 29169 creativeRecordingAssets: { 29170 allIds, 29171 byId: { 29172 ...state.creativeRecordingAssets.byId, 29173 [projectName]: creativeNarrationRecordings 29174 } 29175 } 29176 }; 29177 } 29178 case UPLOADING_ASSET_START: { 29179 let assetName = action.payload.assetName; 29180 let uploadAsset = uploadingAssets.find((uploadingAsset) => uploadingAsset.fileName.toLowerCase() === assetName.toLowerCase()); 29181 uploadAsset ? uploadAsset.status = "loading" : uploadingAssets.unshift({ 29182 fileName: assetName, 29183 status: "loading" 29184 }); 29185 return { 29186 ...state, 29187 uploadingAssets: [...uploadingAssets] 29188 }; 29189 } 29190 case UPLOADING_CREATIVE_NARRATION_RECORDING_VERSIONS_SUCCESS: { 29191 const { creativeNarrationRecordingVersion, projectName } = action.payload; 29192 const { creativeNarrationRecording: updatedCreativeNarrationRecording } = creativeNarrationRecordingVersion; 29193 const creativeRecordingAssets = StateReaderUtils.getCreativeRecordingAssets(state, projectName); 29194 const updatedCreatives = updateCreativesWithCreativeNarrationRecording(creativeRecordingAssets, updatedCreativeNarrationRecording, projectName); 29195 const updatedProgram = { 29196 ...creativeRecordingAssets, 29197 program: { 29198 ...creativeRecordingAssets.program, 29199 creatives: updatedCreatives 29200 } 29201 }; 29202 const index = uploadingAssets.findIndex(({ fileName }) => fileName.toLowerCase() === `${updatedCreativeNarrationRecording.filename}.mp3`.toLowerCase()); 29203 if (index !== -1) uploadingAssets[index] = { 29204 ...uploadingAssets[index], 29205 status: "success" 29206 }; 29207 return { 29208 ...state, 29209 uploadingAssets: [...uploadingAssets], 29210 creativeRecordingAssets: { 29211 ...state.creativeRecordingAssets,
29212 byId: { 29213 ...state.creativeRecordingAssets.byId, 29214 [projectName]: { ...updatedProgram } 29215 } 29216 } 29217 }; 29218 } 29219 case UPLOADING_ASSET_ERROR: { 29220 const { assetName } = action.payload; 29221 const index = uploadingAssets.findIndex((uploadingAsset) => uploadingAsset.fileName.toLowerCase() === assetName.toLowerCase()); 29222 if (index !== -1) uploadingAssets[index] = { 29223 ...uploadingAssets[index], 29224 status: "error" 29225 }; 29226 return { 29227 ...state, 29228 uploadingAssets: [...uploadingAssets] 29229 }; 29230 } 29231 case CLEAR_UPLOAD_LIST: return { 29232 ...state, 29233 uploadingAssets: [] 29234 }; 29235 case UPDATE_ASSET: 29236 case UPLOADING_ASSET_SUCCESS: { 29237 const { projectName, asset, assetType: payloadAssetType, prevName } = action.payload; 29238 updateAssets(projectName, [asset], true); 29239 let updatedAssetNumber = projectsByName[projectName].updatedAssetNumber === 0 ? projectsByName[projectName].updatedAssetNumber + 1 : projectsByName[projectName].updatedAssetNumber; 29240 projectsByName = { 29241 ...projectsByName, 29242 [projectName]: { 29243 ...projectsByName[projectName], 29244 updatedAssetNumber 29245 } 29246 }; 29247 let assetType = payloadAssetType || "all"; 29248 if (!projectsByName[projectName].totalAssetCount) projectsByName[projectName].totalAssetCount = { [assetType]: 0 }; 29249 projectsByName[projectName].totalAssetCount[assetType]++; 29250 if (prevName && prevName !== asset.name) allAssetsIds = deleteAsset(projectName, asset.projectId + "/" + asset.type + "/" + prevName); 29251 const index = uploadingAssets.findIndex((uploadingAsset) => asset.filename && uploadingAsset.fileName.toLowerCase() === asset.filename.toLowerCase()); 29252 if (index !== -1) uploadingAssets[index] = { 29253 ...uploadingAssets[index], 29254 status: "success" 29255 }; 29256 return { 29257 ...state, 29258 projects: { 29259 byName: projectsByName, 29260 allNames: projectsAllNames, 29261 isInitialized: true 29262 }, 29263 assets: { 29264 byId: assetsById, 29265 allIds: allAssetsIds 29266 }, 29267 uploadingAssets: [...uploadingAssets] 29268 }; 29269 } 29270 case UPDATE_RECORDING_ASSET_STATUS_SUCCESS: { 29271 const { projectName, assetName, version, assetUpdates } = action.payload; 29272 const program = projectsByName[projectName]; 29273 const assetId = StateReaderUtils.getAssetUniqueId(program.accountId, projectName, ASSET_TYPES.recording, assetName); 29274 updateAssets(projectName, [{ 29275 ...assetUpdates, 29276 type: ASSET_TYPES.recording, 29277 name: assetName 29278 }], false); 29279 const asset = assetsById[assetId]; 29280 if (asset.activeVersionItem) asset.activeVersionItem = { 29281 ...asset.activeVersionItem, 29282 ...assetUpdates 29283 }; 29284 if (asset.history) { 29285 const index = asset.history.Items.findIndex((item) => item.version === version); 29286 asset.history = { 29287 ...asset.history, 29288 Items: [ 29289 ...asset.history.Items.slice(0, index), 29290 { 29291 ...asset.history.Items[index], 29292 ...assetUpdates 29293 }, 29294 ...asset.history.Items.slice(index + 1) 29295 ] 29296 }; 29297 } 29298 return { 29299 ...state, 29300 projects: { 29301 byName: projectsByName, 29302 allNames: projectsAllNames, 29303 isInitialized: true 29304 }, 29305 assets: { 29306 byId: assetsById, 29307 allIds: allAssetsIds 29308 }, 29309 uploadingAssets 29310 }; 29311 } 29312 case UPDATING_CREATIVE_NARRATION_RECORDING_VERSION_STATUS_SUCCESS: { 29313 const { projectName, creativeNarrationRecording } = action.payload; 29314 const creativeRecordingAssets = StateReaderUtils.getCreativeRecordingAssets(state, projectName); 29315 const updatedCreatives = updateCreativesWithCreativeNarrationRecording(creativeRecordingAssets, creativeNarrationRecording, projectName); 29316 const updatedProgram = { 29317 ...creativeRecordingAssets, 29318 program: { 29319 ...creativeRecordingAssets.program, 29320 creatives: updatedCreatives 29321 } 29322 }; 29323 return { 29324 ...state, 29325 creativeRecordingAssets: { 29326 ...state.creativeRecordingAssets, 29327 byId: { 29328 ...state.creativeRecordingAssets.byId, 29329 [projectName]: { ...updatedProgram } 29330 } 29331 } 29332 }; 29333 } 29334 case UPDATING_CREATIVE_NARRATION_RECORDING_SUCCESS: { 29335 const { projectName, creativeNarrationRecording } = action.payload; 29336 const creativeRecordingAssets = StateReaderUtils.getCreativeRecordingAssets(state, projectName); 29337 const updatedCreatives = updateCreativesWithCreativeNarrationRecording(creativeRecordingAssets, creativeNarrationRecording, projectName); 29338 const updatedProgram = { 29339 ...creativeRecordingAssets, 29340 program: { 29341 ...creativeRecordingAssets.program, 29342 creatives: updatedCreatives 29343 } 29344 }; 29345 return { 29346 ...state, 29347 creativeRecordingAssets: { 29348 ...state.creativeRecordingAssets,
29349 byId: { 29350 ...state.creativeRecordingAssets.byId, 29351 [projectName]: { ...updatedProgram } 29352 } 29353 } 29354 }; 29355 } 29356 case UPDATE_BULK_ASSETS_SUCCESS: { 29357 const { projectName, responseBody, assetType } = action.payload; 29358 const assets = []; 29359 Object.keys(responseBody).forEach((assetName) => { 29360 if (responseBody[assetName].status === 200) { 29361 const assetUpdates = responseBody[assetName].response; 29362 assets.push({ 29363 ...assetUpdates, 29364 type: assetType, 29365 name: assetName 29366 }); 29367 } 29368 }); 29369 updateAssets(projectName, assets, false); 29370 return { 29371 ...state, 29372 projects: { 29373 byName: projectsByName, 29374 allNames: projectsAllNames, 29375 isInitialized: true 29376 }, 29377 assets: { 29378 byId: assetsById, 29379 allIds: allAssetsIds 29380 }, 29381 error: false 29382 }; 29383 } 29384 default: return state; 29385 } 29386} 29387//#endregion 29388//#region client/logic/admin/adminReducer.ts 29389function adminReducer(state, action) { 29390 let userAllNames; 29391 let userId; 29392 let index; 29393 switch (action.type) { 29394 case IS_LOADING_ALL_PROJECTS: return { 29395 ...state, 29396 admin: { 29397 ...state.admin, 29398 isLoadingAllProjects: action.payload 29399 } 29400 }; 29401 case GET_ALL_PROJECTS_SUCCESS: return { 29402 ...state, 29403 admin: { 29404 ...state.admin, 29405 allProjects: action.payload.projects 29406 } 29407 }; 29408 case IS_SETTING_FEATURE_FLAG: return { 29409 ...state, 29410 admin: { 29411 ...state.admin, 29412 isSettingFeatureFlag: action.payload 29413 } 29414 }; 29415 case IS_LOADING_USERS: return { 29416 ...state, 29417 admin: { 29418 ...state.admin, 29419 isLoadingUsers: action.payload 29420 } 29421 }; 29422 case IS_FETCHING_USER: return { 29423 ...state, 29424 admin: { 29425 ...state.admin, 29426 isFetchingUser: action.payload 29427 } 29428 }; 29429 case FETCH_USERS_SUCCESS: 29430 userAllNames = [...action.payload].sort(); 29431 return { 29432 ...state, 29433 users: { 29434 ...state.users, 29435 allNames: userAllNames 29436 } 29437 }; 29438 case ADD_USER_SUCCESS: 29439 userId = action.payload.userPool.Username; 29440 userAllNames = [...state.users.allNames, userId].sort(); 29441 return { 29442 ...state, 29443 users: { 29444 ...state.users, 29445 allNames: userAllNames, 29446 selectedUser: { ...action.payload } 29447 } 29448 }; 29449 case DELETE_USER_SUCCESS: 29450 userId = action.payload; 29451 userAllNames = state.users.allNames; 29452 index = userAllNames.indexOf(userId); 29453 userAllNames = [...userAllNames.slice(0, index), ...userAllNames.slice(index + 1)]; 29454 return { 29455 ...state, 29456 users: { 29457 ...state.users, 29458 allNames: userAllNames, 29459 selectedUser: {} 29460 } 29461 }; 29462 case FETCH_ROLES_SUCCESS: return { 29463 ...state, 29464 users: { 29465 ...state.users, 29466 roles: action.payload 29467 } 29468 }; 29469 case FETCH_USER_SUCCESS: return { 29470 ...state, 29471 users: { 29472 ...state.users, 29473 selectedUser: { ...action.payload } 29474 } 29475 }; 29476 case UPDATE_USER_SUCCESS: return { 29477 ...state, 29478 users: { 29479 ...state.users, 29480 selectedUser: { ...action.payload } 29481 } 29482 }; 29483 case SET_SUCCESS_MESSAGE: return { 29484 ...state, 29485 users: { 29486 ...state.users, 29487 successMessage: action.payload?.success, 29488 warningMessage: action.payload?.warning 29489 } 29490 }; 29491 default: return state; 29492 } 29493} 29494//#endregion 29495//#region client/logic/user/userActions.ts 29496var LOADING_USER_DATA_SUCCESS = "LOADING_USER_DATA_SUCCESS"; 29497var loadingUserDataSuccess = (0, import_lib$3.createAction)(LOADING_USER_DATA_SUCCESS, function(userData) { 29498 return userData; 29499}); 29500var LOADING_ACTIVE_ACCOUNT_SUCCESS = "LOADING_ACTIVE_ACCOUNT_SUCCESS"; 29501(0, import_lib$3.createAction)(LOADING_ACTIVE_ACCOUNT_SUCCESS, function(selectedAccount) { 29502 return selectedAccount; 29503}); 29504var SET_ACTIVE_ACCOUNT_ID = "SET_ACTIVE_ACCOUNT_ID"; 29505var setActiveAccountId = (0, import_lib$3.createAction)(SET_ACTIVE_ACCOUNT_ID, (accountId) => accountId); 29506var loadUserData = (cb, cbError) => async (dispatch, state, services) => { 29507 try { 29508 const userData = await services.userServices.getUserData(); 29509 dispatch(loadingUserDataSuccess(userData)); 29510 if (typeof cb === "function") cb(userData); 29511 } catch (err) { 29512 if (typeof cbError === "function") cbError(err); 29513 else dispatch(reportError(err)); 29514 } 29515}; 29516var switchAccount = function(accountId, newAccount, newLocation, browserHistory) { 29517 return function(dispatch, state, services) { 29518 services.userServices.switchAccount(newAccount).then(function() { 29519 if (!newLocation) newLocation = window.location.pathname.includes(`/${accountId}/`) ? window.location.pathname.replace(accountId, newAccount.accountId) : UrlUtils.append(window.location.pathname, newAccount.accountId); 29520 browserHistory.push(newLocation); 29521 }).catch(function(err) { 29522 dispatch(reportError(err)); 29523 }); 29524 }; 29525}; 29526var logout = function() { 29527 return function(dispatch, state, services) { 29528 services.userServices.logout().finally(() => { 29529 (0, import_createBrowserHistory.default)().push((0, import_dist$9.legacyLoginPath)()); 29530 location.reload(); 29531 }); 29532 }; 29533}; 29534//#endregion 29535//#region client/logic/user/userReducer.js 29536function userReducer(state, action) { 29537 let byId; 29538 let allIds; 29539 switch (action.type) { 29540 case LOADING_USER_DATA_SUCCESS: 29541 byId = action.payload.accounts.reduce((acc, cur) => { 29542 acc[cur.accountId] = cur; 29543 return acc; 29544 }, {}); 29545 allIds = action.payload.accounts.reduce((acc, cur) => { 29546 acc.push(cur.accountId); 29547 return acc; 29548 }, []); 29549 return Object.assign({}, state, { 29550 activeAccountId: action.payload.selectedAccountId, 29551 userName: action.payload.userName, 29552 userRoles: action.payload.userRoles, 29553 accounts: {
29554 byId, 29555 allIds, 29556 isInitialized: true 29557 }, 29558 resolverEndPoint: action.payload.resolverEndPoint, 29559 dtaasEndPoint: action.payload.dtaasEndPoint, 29560 narrationServerEndpoint: action.payload.narrationServerEndpoint, 29561 mockNarrationServerEndpoint: action.payload.mockNarrationServerEndpoint, 29562 tableauBaseURL: action.payload.tableauBaseURL, 29563 tableauWorkbookName: action.payload.tableauWorkbookName, 29564 isLoading: false, 29565 error: false 29566 }); 29567 case LOADING_ACTIVE_ACCOUNT_SUCCESS: 29568 byId = { 29569 ...state.accounts.byId, 29570 [action.payload.accountId]: action.payload 29571 }; 29572 allIds = state.accounts.allIds.indexOf(action.payload.accountId) < 0 ? [...state.accounts.allIds, action.payload.accountId] : state.accounts.allIds; 29573 return Object.assign({}, state, { 29574 activeAccountId: action.payload.accountId, 29575 accounts: { 29576 byId, 29577 allIds 29578 }, 29579 isLoading: false, 29580 error: false 29581 }); 29582 case SET_ACTIVE_ACCOUNT_ID: return Object.assign({}, state, { activeAccountId: action.payload }); 29583 default: return state; 29584 } 29585} 29586//#endregion 29587//#region client/logic/preview/previewActions.js 29588var UPDATE_PROJECT_APIKEY_ENDPOINT = "UPDATE_PROJECT_APIKEY_ENDPOINT"; 29589var updateProjectApikeyEndpoint = (0, import_lib$3.createAction)(UPDATE_PROJECT_APIKEY_ENDPOINT, function(apiKeys, endPoint, renderer3EndPoint) { 29590 return { 29591 apiKeys, 29592 endPoint, 29593 renderer3EndPoint 29594 }; 29595}); 29596var getAndUpdateProjectApikeyEndpoint = function(accountId, projectName) { 29597 return function(dispatch, state, services) { 29598 services.previewServices.getProjectApiKeyAndEndPoint(accountId, projectName).then(function(res) { 29599 dispatch(updateProjectApikeyEndpoint(res.apiKey, res.url, res.renderer3EndPoint)); 29600 }).catch(function(err) { 29601 dispatch(reportError(err)); 29602 }); 29603 }; 29604}; 29605//#endregion 29606//#region client/logic/preview/previewReducer.js 29607function previewReducer(state, action) { 29608 switch (action.type) { 29609 case UPDATE_PROJECT_APIKEY_ENDPOINT: { 29610 const { endPoint, apiKeys, renderer3EndPoint } = action.payload; 29611 return Object.assign({}, state, { 29612 endPoint, 29613 apiKeys, 29614 renderer3EndPoint 29615 }); 29616 } 29617 default: return state; 29618 } 29619} 29620//#endregion 29621//#region client/logic/projects/projectLifecycle/projectLifecycleReducer.ts 29622function projectLifeCycleReducer(state, action) { 29623 let projectStageProperty; 29624 let projectName; 29625 let snapshotId; 29626 /** 29627 * Creates a new stage Snapshot object 29628 * @returns {stageSnapshot:*} the new stage snapshot 29629 */ 29630 let createStageSnapshot = function(snapshotId, promotedDate, snapshotNumber, promotedBy) { 29631 let stageSnapshot = { snapshotId }; 29632 if (promotedDate) stageSnapshot.promotedDate = promotedDate; 29633 if (snapshotNumber) stageSnapshot.snapshotNumber = snapshotNumber; 29634 if (promotedBy) stageSnapshot.promotedBy = promotedBy; 29635 return stageSnapshot; 29636 }; 29637 /** 29638 * Add a stage snapshot in the projectStagePropertyArray. <b>Returns a new Array</b> 29639 * @param projectStagePropertyArray 29640 * @param stageSnapshot 29641 * @returns a new array with the stage snapshot updated in it 29642 */ 29643 let updateProjectStageSnapshotInArray = function(projectStagePropertyArray, stageSnapshot) { 29644 return Array.isArray(projectStagePropertyArray) ? [stageSnapshot, ...projectStagePropertyArray] : [stageSnapshot]; 29645 }; 29646 let snapshotsAllIds = state.snapshots.allIds; 29647 let projectsByName = state.projects.byName; 29648 let projectsAllNames = state.projects.allNames; 29649 let versionManagerState; 29650 switch (action.type) { 29651 case LOADING_PROJECT_LIFECYCLE_SUCCESS: { 29652 let updatedStageSnapshots = {}; 29653 action.payload.projectLifeCycle.forEach(function(lifeCycleItem) { 29654 projectStageProperty = lifeCycleItem.stage + "Snapshots"; 29655 snapshotId = action.payload.projectName + "/" + lifeCycleItem.snapshotNumber; 29656 let stageSnapshot = createStageSnapshot(snapshotId, void 0, lifeCycleItem.snapshotNumber, void 0); 29657 updatedStageSnapshots[projectStageProperty] = updateProjectStageSnapshotInArray(projectsByName[action.payload.projectName][projectStageProperty], stageSnapshot); 29658 }); 29659 projectsByName = { 29660 ...projectsByName, 29661 [action.payload.projectName]: { 29662 ...projectsByName[action.payload.projectName], 29663 ...updatedStageSnapshots 29664 } 29665 }; 29666 return Object.assign({}, state, { projects: { 29667 byName: projectsByName, 29668 allNames: projectsAllNames, 29669 isInitialized: true 29670 } }); 29671 } 29672 case LOADING_PROJECT_LIFECYCLE_STAGE_SUCCESS: { 29673 projectName = action.payload.projectName; 29674 projectStageProperty = action.payload.stage + "Snapshots"; 29675 let projectStageSnapshotArray = projectsByName[action.payload.projectName]?.[projectStageProperty]; 29676 for (let i = action.payload.projectLifeCycle.snapshots.length - 1; i >= 0; --i) { 29677 let item = action.payload.projectLifeCycle.snapshots[i]; 29678 let stageSnapshot = createStageSnapshot(projectName + "/" + item.snapshotNumber, item.promotedDate, item.snapshotNumber, item.promotedBy); 29679 projectStageSnapshotArray = updateProjectStageSnapshotInArray(projectStageSnapshotArray, stageSnapshot); 29680 } 29681 return immutablyReplaceValue(state, [ 29682 "projects", 29683 "byName", 29684 projectName, 29685 projectStageProperty 29686 ], projectStageSnapshotArray); 29687 } 29688 case LOADING_PROJECT_SNAPSHOT_SUCCESS: { 29689 const { projectName, projectSnapShot: snapshot } = action.payload; 29690 let newState = state; 29691 snapshotId = projectName + "/" + snapshot.snapshotNumber; 29692 if (!snapshotsAllIds.includes(snapshotId)) { 29693 snapshotsAllIds = [...snapshotsAllIds, snapshotId]; 29694 newState = immutablyReplaceValue(newState, ["snapshots", "allIds"], snapshotsAllIds); 29695 } 29696 snapshot.snapshotId = snapshotId; 29697 newState = immutablyReplaceValue(newState, [ 29698 "snapshots", 29699 "byId", 29700 snapshotId 29701 ], snapshot, true); 29702 return newState; 29703 } 29704 case SET_PROJECT_BASED_ON_SNAPSHOT: { 29705 let snapshotNumber = action.payload.snapshotNumber; 29706 let project = projectsByName[action.payload.projectName]; 29707 let devProjectId = project.devSnapshots && project.devSnapshots[0] && project.devSnapshots[0].snapshotId; 29708 snapshotId = snapshotNumber > -1 ? action.payload.projectName + "/" + action.payload.snapshotNumber : devProjectId; 29709 project.basedOnSnapshot = { 29710 snapshotNumber, 29711 snapshotId 29712 }; 29713 return Object.assign({}, state, { projects: { 29714 byName: projectsByName, 29715 allNames: projectsAllNames, 29716 isInitialized: true 29717 } }); 29718 } 29719 case ADDING_PROJECT_SNAPSHOT_UPDATE_PROGRESS: return Object.assign({}, state, { loadingProgress: action.payload.progress }); 29720 case ADDING_PROJECT_SNAPSHOT_SUCCESS: { 29721 const currentSnapshot = action.payload.projectSnapShot;
29722 const allSnapshots = [...state.versions, currentSnapshot]; 29723 const snapshotId = `${action.payload.projectName}/${currentSnapshot.snapshotNumber}`; 29724 let newState = immutablyReplaceValue(state, ["versions"], allSnapshots); 29725 newState = immutablyReplaceValue(newState, [ 29726 "snapshots", 29727 "byId", 29728 snapshotId 29729 ], currentSnapshot); 29730 newState = immutablyReplaceValue(newState, ["snapshots", "allIds"], [...snapshotsAllIds, snapshotId]); 29731 return newState; 29732 } 29733 case UPDATING_PROJECT_SNAPSHOT_SUCCESS: { 29734 const snapshotDetailsToUpdate = action.payload.snapshotObject; 29735 const snapshotNumber = action.payload.snapshotNumber; 29736 snapshotId = `${action.payload.projectName}/${snapshotNumber}`; 29737 let allVersions = [...state.versions]; 29738 let index = allVersions.findIndex((item) => item.snapshotNumber === snapshotNumber); 29739 if (index > -1) allVersions[index] = { 29740 ...allVersions[index], 29741 ...snapshotDetailsToUpdate 29742 }; 29743 return immutablyReplaceValue(immutablyReplaceValue(state, ["versions"], allVersions), [ 29744 "snapshots", 29745 "byId", 29746 snapshotId 29747 ], snapshotDetailsToUpdate, true); 29748 } 29749 case ADDING_PROJECT_STAGE_SNAPSHOT_SUCCESS: { 29750 snapshotId = action.payload.projectName + "/" + action.payload.projectSnapShot.snapshotNumber; 29751 projectStageProperty = action.payload.projectSnapShot.stage + "Snapshots"; 29752 let updatedStageSnapshots = {}; 29753 let stageSnapshot = createStageSnapshot(snapshotId, action.payload.projectSnapShot.promotedDate, action.payload.projectSnapShot.snapshotNumber, action.payload.projectSnapShot.promotedBy); 29754 updatedStageSnapshots[projectStageProperty] = updateProjectStageSnapshotInArray(projectsByName[action.payload.projectName][projectStageProperty], stageSnapshot); 29755 projectsByName = { 29756 ...projectsByName, 29757 [action.payload.projectName]: { 29758 ...projectsByName[action.payload.projectName], 29759 ...updatedStageSnapshots 29760 } 29761 }; 29762 const wireframeKey = `${action.payload.projectSnapShot.stage}wireframes`; 29763 let byName = state[wireframeKey].byName ? Object.assign({}, state[wireframeKey].byName) : {}; 29764 if (byName[action.payload.projectName]) delete byName[action.payload.projectName]; 29765 let allNames = state[wireframeKey].allNames ? state[wireframeKey].allNames.filter((name) => name !== action.payload.projectName) : []; 29766 return Object.assign({}, state, { 29767 projects: { 29768 byName: projectsByName, 29769 allNames: projectsAllNames, 29770 isInitialized: true 29771 }, 29772 [wireframeKey]: { 29773 byName, 29774 allNames 29775 } 29776 }); 29777 } 29778 case SETTING_PROJECT_SNAPSHOT_SUCCESS: { 29779 snapshotId = action.payload.projectName + "/" + action.payload.projectSnapShot.snapshotNumber; 29780 projectStageProperty = action.payload.projectSnapShot.stage + "Snapshots"; 29781 let updatedStageSnapshots = {}; 29782 let stageSnapshot = createStageSnapshot(snapshotId, action.payload.projectSnapShot.promotedDate, action.payload.projectSnapShot.snapshotNumber, action.payload.projectSnapShot.promotedBy); 29783 updatedStageSnapshots[projectStageProperty] = updateProjectStageSnapshotInArray(projectsByName[action.payload.projectName][projectStageProperty], stageSnapshot); 29784 versionManagerState = state.versionManager || {}; 29785 versionManagerState = { 29786 ...versionManagerState, 29787 promoteStatus: true 29788 }; 29789 projectsByName = { 29790 ...projectsByName, 29791 [action.payload.projectName]: { 29792 ...projectsByName[action.payload.projectName], 29793 ...updatedStageSnapshots, 29794 updatedAssetNumber: action.payload.projectSnapShot.updatedAssetNumber 29795 } 29796 }; 29797 const wireframeKey = `${action.payload.projectSnapShot.stage}wireframes`; 29798 let byName = state[wireframeKey].byName ? Object.assign({}, state[wireframeKey].byName) : {}; 29799 if (byName[action.payload.projectName]) delete byName[action.payload.projectName]; 29800 let allNames = state[wireframeKey].allNames ? state[wireframeKey].allNames.filter((name) => name !== action.payload.projectName) : []; 29801 return Object.assign({}, state, { 29802 projects: { 29803 byName: projectsByName, 29804 allNames: projectsAllNames, 29805 isInitialized: true 29806 }, 29807 versionManager: versionManagerState, 29808 [wireframeKey]: {
29809 byName, 29810 allNames 29811 } 29812 }); 29813 } 29814 case SET_PROMOTE_STATUS: 29815 versionManagerState = state.versionManager || {}; 29816 versionManagerState.promoteStatus = action.payload; 29817 return Object.assign({}, state, { versionManager: versionManagerState }); 29818 default: return state; 29819 } 29820} 29821//#endregion 29822//#region client/logic/featureFlags/featureFlagsReducer.js 29823function featureFlagsReducer(state, action) { 29824 switch (action.type) { 29825 case LOADING_FEATURE_FLAGS_SUCCESS: return { 29826 ...state, 29827 featureFlags: action.payload.featureFlags 29828 }; 29829 case LOADING_PROGRAMS_DYNAMO_MIGRATION_STATUS: return { 29830 ...state, 29831 programsDynamoMigrationStatus: convertArrayOfObjectsToObject(action.payload.programsDynamoMigrationStatus, "programId") 29832 }; 29833 case ENABLING_ALL_FEATURE_FLAGS_SUCCESS: return { 29834 ...state, 29835 featureFlags: {}, 29836 enableAllFeatureFlags: action.payload.enable 29837 }; 29838 case SET_FEATURE_FLAG_STATUS_IN_STATE: { 29839 const featureFlags = { ...state.featureFlags }; 29840 if (featureFlags[action.payload.featureFlagId]) featureFlags[action.payload.featureFlagId].defaultValue = action.payload.status; 29841 return { 29842 ...state, 29843 featureFlags 29844 }; 29845 } 29846 case SET_FEATURE_FLAG_SUCCESS: { 29847 const featureFlags = { ...state.featureFlags }; 29848 const { defaultValue, excludedPrograms, featureFlagId, excludedAccounts } = action.payload.featureFlag; 29849 featureFlags[featureFlagId] = { 29850 defaultValue, 29851 excludedPrograms, 29852 excludedAccounts 29853 }; 29854 return { 29855 ...state, 29856 featureFlags 29857 }; 29858 } 29859 default: return state; 29860 } 29861} 29862//#endregion 29863//#region client/logic/dashboards/accountOverview/accountOverviewActions.js 29864var GET_ACCOUNT_DASHBOARD_DATA_SUCCESS = "GET_ACCOUNT_DASHBOARD_DATA_SUCCESS"; 29865var GET_ACCOUNT_VIDEO_VIEWS_SUCCESS = "GET_ACCOUNT_VIDEO_VIEWS_SUCCESS"; 29866var getAccountDashboardDataSuccess = (0, import_lib$3.createAction)(GET_ACCOUNT_DASHBOARD_DATA_SUCCESS, (dashboardData) => dashboardData); 29867var getAccountVideoViewsSuccess = (0, import_lib$3.createAction)(GET_ACCOUNT_VIDEO_VIEWS_SUCCESS, (accountVideoViews, timespan, selectedProgramIds) => ({ accountVideoViews })); 29868var getAccountDashboardData = (accountId) => { 29869 return async function(dispatch, state, services) { 29870 const { accountOverviewServices } = services; 29871 try { 29872 dispatch(getAccountDashboardDataSuccess(await Promise.all([ 29873 accountOverviewServices.getAccountInfo(accountId), 29874 accountOverviewServices.getAccountPrograms(accountId), 29875 accountOverviewServices.getAccountScenes(accountId) 29876 ]))); 29877 } catch (err) { 29878 dispatch(reportError(err)); 29879 } 29880 }; 29881}; 29882var getAccountVideoViews = (accountId, programIDs, timespan) => { 29883 return async function(dispatch, state, services) { 29884 try { 29885 dispatch(getAccountVideoViewsSuccess(await services.accountOverviewServices.getAccountVideoViews(accountId, programIDs, timespan), timespan, programIDs)); 29886 } catch (err) { 29887 dispatch(reportError(err)); 29888 } 29889 }; 29890}; 29891//#endregion 29892//#region client/logic/dashboards/accountOverview/accountOverviewReducer.js 29893var accountOverviewReducer = (state, action) => { 29894 let allProgramsIds = state.dashboardPrograms.allIds; 29895 let programsById = state.dashboardPrograms.byId; 29896 let allScenesIds = state.dashboardScenes.allIds; 29897 let scenesById = state.dashboardScenes.byId; 29898 switch (action.type) { 29899 case GET_ACCOUNT_DASHBOARD_DATA_SUCCESS: { 29900 const [accountInfo, accountPrograms, accountScenes] = action.payload; 29901 accountPrograms.forEach((program) => { 29902 if (programsById[program.id]) programsById[program.id] = { 29903 ...programsById[program.id], 29904 program 29905 }; 29906 else { 29907 allProgramsIds.push(program.id); 29908 programsById[program.id] = program; 29909 } 29910 }); 29911 accountScenes.forEach((scene) => { 29912 if (scenesById[scene.id]) scenesById[scene.id] = { 29913 ...scenesById[scene.id], 29914 scene 29915 }; 29916 else { 29917 allScenesIds.push(scene.id); 29918 scenesById[scene.id] = scene; 29919 } 29920 if (scene.usedInPrograms) scene.usedInPrograms.forEach((pId) => { 29921 if (!programsById[pId]) { 29922 allProgramsIds.push(pId); 29923 programsById[pId] = {}; 29924 } 29925 if (!programsById[pId].scenes) programsById[pId].scenes = []; 29926 if (programsById[pId].scenes.indexOf(scene.id) < 0) programsById[pId].scenes.push(scene.id); 29927 }); 29928 }); 29929 return { 29930 ...state, 29931 accountInfo, 29932 dashboardPrograms: { 29933 allIds: allProgramsIds,
29934 byId: programsById 29935 }, 29936 dashboardScenes: { 29937 allIds: allScenesIds, 29938 byId: scenesById 29939 } 29940 }; 29941 } 29942 case GET_ACCOUNT_VIDEO_VIEWS_SUCCESS: return { 29943 ...state, 29944 accountVideoViews: action.payload.accountVideoViews 29945 }; 29946 default: return state; 29947 } 29948}; 29949//#endregion 29950//#region client/logic/projects/projectWireframes/projectsWireframesReducer.ts 29951function cleanWireframes(wireframes) { 29952 if (wireframes && wireframes.logic) Object.keys(wireframes.logic).forEach((logicContainer) => { 29953 if (StateReaderUtils.isLogicContainerAScene(logicContainer) || logicContainer === LogicContainers.Master) { 29954 let allSceneLogic = wireframes.logic[logicContainer]; 29955 Object.values(allSceneLogic).forEach((logic) => { 29956 if (logic && logic.outputType === "parameter") logic.outputType = LogicType.Text; 29957 }); 29958 } 29959 }); 29960} 29961function updateLogic(state, projectName, logicContainer, logicOwner, logicData, replace) { 29962 if (!logicData) return state; 29963 const byName = state.wireframes.byName; 29964 const allNames = state.wireframes.allNames; 29965 const currentProjectLogic = byName[projectName] ? byName[projectName].logic : {}; 29966 const currentSceneLogic = byName[projectName] && byName[projectName].logic ? byName[projectName].logic[logicContainer] : {}; 29967 const currentInputLogic = byName[projectName] && byName[projectName].logic && byName[projectName].logic[logicContainer] ? byName[projectName].logic[logicContainer][logicOwner] : {}; 29968 const newLogic = replace ? logicData : { 29969 ...currentInputLogic, 29970 ...logicData 29971 }; 29972 return { 29973 ...state, 29974 wireframes: { 29975 byName: { 29976 ...byName, 29977 [projectName]: { 29978 ...byName[projectName], 29979 logic: { 29980 ...currentProjectLogic, 29981 [logicContainer]: { 29982 ...currentSceneLogic, 29983 [logicOwner]: newLogic 29984 } 29985 } 29986 } 29987 }, 29988 allNames 29989 }, 29990 error: false 29991 }; 29992} 29993/** 29994* Updates the logic in the state. If the logic belongs to a placeholder, update the validation on the placeholder section 29995* @param state The Redux state 29996* @param projectName The project name 29997* @param logicContainer The container of all the logic. e.g. sceneId, 'derived', 'analytics', etc. 29998* @param logicOwner The element which the logic belongs to. e.g. placeholder name, derived DE Id, Decision Point Id etc. 29999* @param logicData The logic 30000* @param replace boolean 30001*/ 30002function updateSceneInputLogic(state, projectName, logicContainer, logicOwner, logicData, replace) { 30003 if (logicData && typeof logicData === "object" && !logicData.loading) logicData = cleanInputLogic(logicData); 30004 return updateLogic(state, projectName, logicContainer, logicOwner, logicData, replace); 30005} 30006function deleteSceneInputLogic(state, projectName, sceneId, inputName) { 30007 let byName = state.wireframes.byName; 30008 let allNames = state.wireframes.allNames; 30009 let newstate = Object.assign({}, state, { 30010 wireframes: { 30011 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { logic: Object.assign({}, byName[projectName] ? byName[projectName].logic : {}, { [sceneId]: Object.assign({}, byName[projectName] && byName[projectName].logic ? byName[projectName].logic[sceneId] : {}) }) }) }), 30012 allNames 30013 }, 30014 error: false 30015 }); 30016 delete newstate.wireframes.byName[projectName].logic[sceneId][inputName]; 30017 return newstate; 30018} 30019function cleanWireframeLogicItems(logicData) { 30020 if (!logicData) return {}; 30021 return Object.keys(logicData).reduce((acc, logicContainer) => { 30022 const logicItems = logicData[logicContainer]; 30023 acc[logicContainer] = Object.keys(logicItems).reduce((acc, inputName) => { 30024 acc[inputName] = cleanInputLogic(logicItems[inputName]); 30025 return acc; 30026 }, {}); 30027 return acc; 30028 }, {}); 30029} 30030var constructInitialWireframe = (state, projectName, data, stage, version) => { 30031 const wireframeKey = getWireframeKey(stage, version); 30032 let byName = state[wireframeKey].byName ? Object.assign({}, state[wireframeKey].byName) : {}; 30033 let allNames; 30034 if (state[wireframeKey].allNames.indexOf(projectName) > -1) allNames = state[wireframeKey].allNames; 30035 else allNames = [...state[wireframeKey].allNames, projectName]; 30036 if (stage === "diff") { 30037 if (!byName[projectName]) byName[projectName] = {}; 30038 byName[projectName] = { 30039 ...byName[projectName], 30040 [version]: data 30041 }; 30042 } else byName[projectName] = data; 30043 return { [wireframeKey]: { 30044 byName, 30045 allNames 30046 } }; 30047}; 30048function getWireframeKey(stage, version) { 30049 if (stage) return `${stage}wireframes`; 30050 else if (version) return "versionwireframes"; 30051 return "wireframes"; 30052} 30053function wireFramesReducer(state, action) { 30054 switch (action.type) { 30055 case CHANGING_PROJECT_WIREFRAMES_SCENE_SUCCESS: 30056 case ADDING_PROJECT_WIREFRAMES_SCENE_SUCCESS: { 30057 let { projectName, sceneId, sceneData } = action.payload; 30058 const wireframesPath = StateReaderUtils.getWireframesPathOnState(projectName); 30059 let newState; 30060 newState = immutablyReplaceValue(state, [ 30061 ...wireframesPath, 30062 "scenes", 30063 sceneId 30064 ], sceneData); 30065 newState = immutablyReplaceValue(newState, ["lastRelevantNarrationUpdateTimeStamp"], Date.now()); 30066 return newState; 30067 } 30068 case CHANGING_PROJECT_WIREFRAMES_STORY_SUCCESS: { 30069 let { projectName, storyId, storyData } = action.payload; 30070 let byName = state.wireframes.byName; 30071 let allNames = state.wireframes.allNames; 30072 let currentStories = byName[projectName] ? byName[projectName].stories : {}; 30073 return Object.assign({}, state, { 30074 wireframes: {
30075 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { stories: Object.assign({}, currentStories, { [storyId]: storyData }) }) }), 30076 allNames 30077 }, 30078 error: false 30079 }); 30080 } 30081 case DELETING_PROJECT_WIREFRAMES_SCENE_SUCCESS: { 30082 let { projectName, sceneId } = action.payload; 30083 let byName = state.wireframes.byName; 30084 let allNames = state.wireframes.allNames; 30085 let modifiedScenesList = Object.assign({}, byName[projectName].scenes); 30086 delete modifiedScenesList[sceneId]; 30087 byName = { 30088 ...byName, 30089 [projectName]: Object.assign({}, byName[projectName], { scenes: modifiedScenesList }) 30090 }; 30091 return Object.assign({}, state, { 30092 wireframes: { 30093 byName, 30094 allNames 30095 }, 30096 error: false 30097 }); 30098 } 30099 case LOADING_PROJECT_WIREFRAMES_FROM_UIASSET: { 30100 let { projectName, data, stage, version } = action.payload; 30101 if (stage || version) data && (data.snapshotNumber = version); 30102 cleanWireframes(data); 30103 return { 30104 ...state, 30105 ...constructInitialWireframe(state, projectName, data, stage, version), 30106 error: false, 30107 middlePanelCollapsed: state.middlePanelCollapsed === void 0 ? true : state.middlePanelCollapsed 30108 }; 30109 } 30110 case ADDING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS: { 30111 let { projectName, sceneId, scenePart } = action.payload; 30112 let byName = state.wireframes.byName; 30113 let allNames = state.wireframes.allNames; 30114 let sceneData = Object.assign({}, {}, byName[projectName].scenes[sceneId]); 30115 sceneData.sceneParts = [...sceneData.sceneParts, scenePart]; 30116 let byNameProj = Object.assign({}, byName[projectName], { scenes: Object.assign({}, byName[projectName].scenes, { [sceneId]: sceneData }) }); 30117 byName = { 30118 ...byName, 30119 [projectName]: byNameProj 30120 }; 30121 return Object.assign({}, state, { 30122 wireframes: { 30123 byName, 30124 allNames 30125 }, 30126 error: false 30127 }); 30128 } 30129 case CHANGING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS: { 30130 const { projectName, sceneId, scenePart, scenePartIndex } = action.payload; 30131 const byName = state.wireframes.byName; 30132 const allNames = state.wireframes.allNames; 30133 let sceneParts = [...byName[projectName].scenes[sceneId].sceneParts]; 30134 sceneParts[scenePartIndex] = scenePart; 30135 return { 30136 ...state, 30137 lastRelevantNarrationUpdateTimeStamp: Date.now(), 30138 wireframes: { 30139 byName: { 30140 ...byName, 30141 [projectName]: { 30142 ...byName[projectName], 30143 scenes: { 30144 ...byName[projectName].scenes, 30145 [sceneId]: { 30146 ...byName[projectName].scenes[sceneId], 30147 sceneParts 30148 } 30149 } 30150 } 30151 }, 30152 allNames 30153 }, 30154 error: false 30155 }; 30156 } 30157 case CHANGING_BULK_SCENE_PARTS_SUCCESS: { 30158 let { projectName, bulkSceneParts } = action.payload; 30159 let byName = state.wireframes.byName; 30160 let allNames = state.wireframes.allNames; 30161 let scenes = { ...byName[projectName].scenes }; 30162 Object.keys(bulkSceneParts).forEach((bulkId) => { 30163 let ids = bulkId.split("/"); 30164 let sceneId = ids[0]; 30165 let scenePartId = ids[1]; 30166 let scenePartIndex = scenes[sceneId].sceneParts.findIndex((scenePart) => scenePart.scenePart === scenePartId); 30167 scenes[sceneId] = scenes[sceneId] === byName[projectName].scenes[sceneId] ? { ...scenes[sceneId] } : scenes[sceneId]; 30168 scenes[sceneId].sceneParts = [...scenes[sceneId].sceneParts]; 30169 scenes[sceneId].sceneParts[scenePartIndex] = bulkSceneParts[bulkId]; 30170 }); 30171 byName[projectName] = { 30172 ...byName[projectName], 30173 scenes 30174 }; 30175 return { 30176 ...state, 30177 lastRelevantNarrationUpdateTimeStamp: Date.now(), 30178 wireframes: { 30179 byName, 30180 allNames 30181 }, 30182 error: false 30183 }; 30184 } 30185 case DELETING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS: { 30186 let { projectName, sceneId, scenePartIndex } = action.payload; 30187 let byName = state.wireframes.byName; 30188 let allNames = state.wireframes.allNames; 30189 let sceneData = byName[projectName].scenes[sceneId]; 30190 byName[projectName] = Object.assign({}, byName[projectName], { scenes: Object.assign({}, byName[projectName].scenes, { [sceneId]: Object.assign({}, sceneData, { sceneParts: byName[projectName].scenes[sceneId].sceneParts.filter((scenePartItem) =>
30190 scenePartItem.scenePart !== scenePartIndex) }) }) }); 30191 return Object.assign({}, state, { 30192 wireframes: { 30193 byName, 30194 allNames 30195 }, 30196 error: false 30197 }); 30198 } 30199 case LOADING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC: { 30200 let { projectName, sceneId, inputName } = action.payload; 30201 return updateSceneInputLogic(state, projectName, sceneId, inputName, { loading: true }, false); 30202 } 30203 case UPDATING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC_SUCCESS: { 30204 let { projectName, sceneId, inputName, logicData } = action.payload; 30205 return updateSceneInputLogic(state, projectName, sceneId, inputName, logicData, true); 30206 } 30207 case LOADING_PROGRAM_WIREFRAMES_SUCCESS: { 30208 let { projectName, initialWireframes, logicData, programLogic, storiesLogic, stage, version } = action.payload; 30209 if (stage || version) initialWireframes && (initialWireframes.snapshotNumber = version); 30210 let wireFrameLogic = cleanWireframeLogicItems(logicData); 30211 if (programLogic) wireFrameLogic[LogicContainers.Program] = programLogic; 30212 if (storiesLogic) wireFrameLogic[LogicContainers.Story] = storiesLogic; 30213 initialWireframes.logic = wireFrameLogic; 30214 return { 30215 ...state, 30216 ...constructInitialWireframe(state, projectName, initialWireframes, stage, version), 30217 error: false, 30218 middlePanelCollapsed: state.middlePanelCollapsed === void 0 ? true : state.middlePanelCollapsed 30219 }; 30220 } 30221 case DELETING_PROJECT_WIREFRAMES_INPUT_LOGICS_SUCCESS: { 30222 let { projectName, sceneId, logicName } = action.payload; 30223 return deleteSceneInputLogic(state, projectName, sceneId, logicName); 30224 } 30225 case ADDING_PROJECT_WIREFRAMES_SCENE_PART_STORYBOARD_FRAME_SUCCESS: { 30226 let { projectName, sceneId, scenePartData, scenePartIndex } = action.payload; 30227 let byName = state.wireframes.byName; 30228 let allNames = state.wireframes.allNames; 30229 let sceneData = byName[projectName].scenes[sceneId]; 30230 sceneData.sceneParts[scenePartIndex] = scenePartData; 30231 byName[projectName] = { 30232 ...byName[projectName], 30233 scenes: { 30234 ...byName[projectName].scenes, 30235 [sceneId]: sceneData 30236 } 30237 }; 30238 return { 30239 ...state, 30240 wireframes: { 30241 byName, 30242 allNames 30243 }, 30244 error: false 30245 }; 30246 } 30247 case CHANGE_ACTIVE_PRESET: return Object.assign({}, state, { activePresetId: action.payload.presetId }); 30248 case ADDING_PROJECT_WIREFRAMES_PRESET_SUCCESS: { 30249 let projectName = action.payload.projectName; 30250 let presetId = action.payload.preset.id; 30251 let presetData = action.payload.preset; 30252 let byName = state.presets.byName; 30253 let allNames = state.presets.allNames; 30254 byName[projectName] = Object.assign({}, byName[projectName], Object.assign({}, byName[projectName] ? byName[projectName] : {}, { [presetId]: presetData })); 30255 return Object.assign({}, state, { 30256 presets: { 30257 byName, 30258 allNames 30259 }, 30260 error: false, 30261 activePresetId: presetId 30262 }); 30263 } 30264 case DELETING_PROJECT_WIREFRAMES_PRESET_SUCCESS: { 30265 let { projectName, presetId } = action.payload; 30266 let byName = state.presets.byName; 30267 let allNames = state.presets.allNames; 30268 let modifiedPresetList = Object.assign({}, byName[projectName]); 30269 delete modifiedPresetList[presetId]; 30270 byName[projectName] = Object.assign({}, modifiedPresetList); 30271 return Object.assign({}, state, { 30272 presets: { 30273 byName, 30274 allNames 30275 }, 30276 error: false, 30277 activePresetId: null 30278 }); 30279 } 30280 case CHANGING_PROJECT_WIREFRAMES_PRESET_SUCCESS: { 30281 let { projectName, presetId, presetData } = action.payload; 30282 let newState = immutablyReplaceValue(state, [ 30283 "presets", 30284 "byName", 30285 projectName, 30286 presetId 30287 ], presetData, true); 30288 newState = immutablyReplaceValue(newState, ["activePresetId"], presetId); 30289 return newState; 30290 } 30291 case LOADING_PROJECT_WIREFRAMES_PRESETS_SUCCESS: { 30292 let { projectName, presets } = action.payload; 30293 let byName = state.presets.byName; 30294 let allNames; 30295 if (state.presets.allNames.indexOf(projectName) > -1) allNames = state.presets.allNames; 30296 else allNames = [...state.presets.allNames, projectName]; 30297 byName = { 30298 ...byName, 30299 [projectName]: presets 30300 }; 30301 return Object.assign({}, state, { 30302 presets: {
30303 byName, 30304 allNames 30305 }, 30306 error: false 30307 }); 30308 } 30309 case SET_CUSTOM_ANALYTICS_ORDER_SUCCESS: { 30310 let { projectName, analyticsOrder, updated } = action.payload; 30311 let byName = state.wireframes.byName; 30312 let allNames = state.wireframes.allNames; 30313 byName[projectName] = { 30314 ...byName[projectName], 30315 customAnalyticsOrder: analyticsOrder 30316 }; 30317 return { 30318 ...state, 30319 projects: { 30320 byName: { 30321 ...state.projects.byName, 30322 [projectName]: { 30323 ...state.projects.byName[projectName], 30324 graphQLUpdated: updated 30325 } 30326 }, 30327 allNames: state.projects.allNames 30328 }, 30329 wireframes: { 30330 byName, 30331 allNames 30332 }, 30333 error: false 30334 }; 30335 } 30336 case SET_CUSTOM_ANALYTIC_FIELD_SUCCESS: { 30337 let { projectName, analyticFieldUpdates } = action.payload; 30338 const logic = analyticFieldUpdates.data; 30339 delete analyticFieldUpdates.data; 30340 let newState = state; 30341 if (logic) newState = updateLogic(state, projectName, LogicContainers.Analytics, analyticFieldUpdates.id, logic, true); 30342 let byName = { ...newState.wireframes.byName }; 30343 let allNames = newState.wireframes.allNames; 30344 byName[projectName] = { 30345 ...byName[projectName], 30346 customAnalyticFields: { 30347 ...byName[projectName].customAnalyticFields, 30348 [analyticFieldUpdates.id]: { 30349 ...byName[projectName].customAnalyticFields[analyticFieldUpdates.id], 30350 ...analyticFieldUpdates 30351 } 30352 } 30353 }; 30354 return { 30355 ...newState, 30356 wireframes: { 30357 byName, 30358 allNames 30359 }, 30360 error: false 30361 }; 30362 } 30363 case ADD_CUSTOM_ANALYTIC_FIELD_SUCCESS: { 30364 let { projectName, analyticField } = action.payload; 30365 const newState = updateLogic(state, projectName, LogicContainers.Analytics, analyticField.id, analyticField.data, false); 30366 let byName = { ...newState.wireframes.byName }; 30367 let allNames = newState.wireframes.allNames; 30368 byName[projectName] = { 30369 ...byName[projectName], 30370 customAnalyticsOrder: [...byName[projectName].customAnalyticsOrder, analyticField.id], 30371 customAnalyticFields: { 30372 ...byName[projectName].customAnalyticFields, 30373 [analyticField.id]: analyticField 30374 } 30375 }; 30376 return { 30377 ...newState, 30378 wireframes: { 30379 byName, 30380 allNames 30381 }, 30382 error: false 30383 }; 30384 } 30385 case DELETE_CUSTOM_ANALYTIC_FIELD_SUCCESS: { 30386 let { projectName, analyticFieldId } = action.payload; 30387 const newState = deleteSceneInputLogic(state, projectName, LogicContainers.Analytics, analyticFieldId); 30388 let byName = { ...newState.wireframes.byName }; 30389 let allNames = newState.wireframes.allNames; 30390 const customAnalyticsOrder = byName[projectName].customAnalyticsOrder; 30391 const index = customAnalyticsOrder.indexOf(analyticFieldId); 30392 const newOrder = [...customAnalyticsOrder.slice(0, index), ...customAnalyticsOrder.slice(index + 1)]; 30393 const customAnalyticFields = { ...byName[projectName].customAnalyticFields }; 30394 delete customAnalyticFields[analyticFieldId]; 30395 byName[projectName] = { 30396 ...byName[projectName], 30397 customAnalyticsOrder: newOrder, 30398 customAnalyticFields 30399 }; 30400 return { 30401 ...newState, 30402 wireframes: { 30403 byName, 30404 allNames 30405 }, 30406 error: false 30407 }; 30408 } 30409 case DELETING_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS: { 30410 const { projectName, animationName } = action.payload; 30411 const wireframe = StateReaderUtils.getWireFrame(state, projectName); 30412 const { allNames, byName } = state.wireframes; 30413 const projectScenes = wireframe && wireframe.scenes || {}; 30414 const masterData = StateReaderUtils.getProjectMasterData(state, projectName) || {}; 30415 const masterParameters = masterData?.parameters || []; 30416 const newMasterParameters = [...masterParameters]; 30417 const index = masterParameters.findIndex((param) => param.name === animationName); 30418 if (index > -1) newMasterParameters.splice(index, 1); 30419 const projectLogic = StateReaderUtils.getProjectWireframesLogic(state, projectName) || {}; 30420 const newProjectMasterLogic = { ...StateReaderUtils.getAllProgramLogicFromWireframes(wireframe, LogicContainers.Master) || {} }; 30421 delete newProjectMasterLogic[animationName]; 30422 const updatedByName = { 30423 ...byName, 30424 [projectName]: { 30425 ...byName[projectName], 30426 scenes: { 30427 ...projectScenes, 30428 [LogicContainers.Master]: { 30429 ...projectScenes[LogicContainers.Master], 30430 sceneParts: [{ 30431 ...masterData, 30432 parameters: newMasterParameters 30433 }] 30434 } 30435 }, 30436 logic: { 30437 ...projectLogic, 30438 [LogicContainers.Master]: newProjectMasterLogic 30439 } 30440 } 30441 }; 30442 return { 30443 ...state, 30444 wireframes: {
30445 byName: updatedByName, 30446 allNames 30447 } 30448 }; 30449 } 30450 case CREATE_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS: { 30451 const { projectName, animationGuideline } = action.payload; 30452 const wireframe = StateReaderUtils.getWireFrame(state, projectName); 30453 const { allNames, byName } = state.wireframes; 30454 const projectScenes = wireframe && wireframe.scenes || {}; 30455 const masterData = StateReaderUtils.getProjectMasterData(state, projectName) || {}; 30456 const masterParameters = masterData?.parameters || []; 30457 const updatedByName = { 30458 ...byName, 30459 [projectName]: { 30460 ...byName[projectName], 30461 scenes: { 30462 ...projectScenes, 30463 [LogicContainers.Master]: { 30464 ...projectScenes[LogicContainers.Master], 30465 sceneParts: [{ 30466 ...masterData, 30467 parameters: [...masterParameters, animationGuideline] 30468 }] 30469 } 30470 } 30471 } 30472 }; 30473 return { 30474 ...state, 30475 wireframes: { 30476 byName: updatedByName, 30477 allNames 30478 } 30479 }; 30480 } 30481 case RENAME_PROJECT_MASTER_ANIMATION_GUIDELINE_SUCCESS: { 30482 const { projectName, updatedAnimationGuidelineIndex, updatedAnimationGuideline } = action.payload; 30483 const wireframe = StateReaderUtils.getWireFrame(state, projectName); 30484 const { allNames, byName } = state.wireframes; 30485 const projectScenes = wireframe && wireframe.scenes || {}; 30486 const masterData = StateReaderUtils.getProjectMasterData(state, projectName) || {}; 30487 const masterParameters = masterData?.parameters || []; 30488 const currentMasterAnimationGuideline = masterParameters[updatedAnimationGuidelineIndex]; 30489 const oldName = currentMasterAnimationGuideline.name; 30490 const newMasterAnimationGuideline = { 30491 ...currentMasterAnimationGuideline, 30492 ...updatedAnimationGuideline 30493 }; 30494 const newMasterParameters = [...masterParameters]; 30495 newMasterParameters.splice(updatedAnimationGuidelineIndex, 1, newMasterAnimationGuideline); 30496 const projectLogic = StateReaderUtils.getProjectWireframesLogic(state, projectName) || {}; 30497 const projectMasterLogic = StateReaderUtils.getAllProgramLogicFromWireframes(wireframe, LogicContainers.Master) || {}; 30498 const newProjectMasterLogic = { ...projectMasterLogic }; 30499 const oldLogic = projectMasterLogic[oldName]; 30500 if (oldLogic) { 30501 newProjectMasterLogic[updatedAnimationGuideline.name] = oldLogic; 30502 delete newProjectMasterLogic[oldName]; 30503 } 30504 const updatedByName = { 30505 ...byName, 30506 [projectName]: { 30507 ...byName[projectName], 30508 scenes: { 30509 ...projectScenes, 30510 [LogicContainers.Master]: { 30511 ...projectScenes[LogicContainers.Master], 30512 sceneParts: [{ 30513 ...masterData, 30514 parameters: newMasterParameters 30515 }] 30516 } 30517 }, 30518 logic: { 30519 ...projectLogic, 30520 [LogicContainers.Master]: newProjectMasterLogic 30521 } 30522 } 30523 }; 30524 return { 30525 ...state, 30526 wireframes: { 30527 byName: updatedByName, 30528 allNames 30529 } 30530 }; 30531 } 30532 case UPDATE_PROJECT_MASTER_SUCCESS: { 30533 const { projectName, masterData } = action.payload; 30534 const { allNames, byName } = state.wireframes; 30535 const projectScenes = byName[projectName] && byName[projectName].scenes || {}; 30536 const updatedByName = { 30537 ...byName, 30538 [projectName]: { 30539 ...byName[projectName], 30540 scenes: { 30541 ...projectScenes, 30542 [LogicContainers.Master]: { 30543 ...projectScenes[LogicContainers.Master], 30544 sceneParts: [masterData] 30545 } 30546 } 30547 } 30548 }; 30549 return { 30550 ...state, 30551 wireframes: { 30552 byName: updatedByName, 30553 allNames 30554 } 30555 }; 30556 } 30557 case UPDATE_PROJECT_COMPLETE: { 30558 const project = action.payload.project; 30559 const projectName = project && project.projectName; 30560 let byName = state.wireframes.byName; 30561 let projectWireframe = byName && byName[projectName]; 30562 let allNames = state.wireframes.allNames; 30563 if (!project || !projectName || !projectWireframe) return state; 30564 const updatedFields = Object.keys(project); 30565 if (updatedFields.includes("creativeVersion") || updatedFields.includes("creativeDDE") || updatedFields.includes("creativeNameLabel")) { 30566 let projectWireframeNew = Object.assign({}, projectWireframe, project); 30567 byName = { 30568 ...byName, 30569 [projectName]: projectWireframeNew 30570 }; 30571 return Object.assign({}, state, { wireframes: {
30572 byName, 30573 allNames 30574 } }); 30575 } 30576 return state; 30577 } 30578 case ADDING_SURVEY_SUCCESS: 30579 case UPDATING_SURVEY_SUCCESS: { 30580 let projectName = action.payload.projectName; 30581 let surveyId = action.payload.surveyId; 30582 let surveyData = action.payload.surveyData; 30583 let wireframes = state.wireframes.byName[projectName]; 30584 let newSurveys = wireframes.surveys ? [...wireframes.surveys] : []; 30585 let index = newSurveys.findIndex((survey) => survey.surveyId === surveyId); 30586 if (index > -1) newSurveys[index] = { 30587 ...newSurveys[index], 30588 surveyData 30589 }; 30590 else newSurveys.push({ 30591 ...surveyData, 30592 id: surveyId 30593 }); 30594 return { 30595 ...state, 30596 wireframes: { 30597 byName: { 30598 ...state.wireframes.byName, 30599 [projectName]: { 30600 ...wireframes, 30601 surveys: newSurveys 30602 } 30603 }, 30604 allNames: state.wireframes.allNames 30605 }, 30606 error: false 30607 }; 30608 } 30609 case DELETING_SURVEY_SUCCESS: { 30610 let { projectName, surveyId } = action.payload; 30611 let wireframes = state.wireframes.byName[projectName]; 30612 let newSurveys = wireframes.surveys ? [...wireframes.surveys] : []; 30613 let index = newSurveys.findIndex((survey) => survey.surveyId === surveyId); 30614 newSurveys.splice(index, 1); 30615 return { 30616 ...state, 30617 wireframes: { 30618 byName: { 30619 ...state.wireframes.byName, 30620 [projectName]: { 30621 ...wireframes, 30622 surveys: newSurveys 30623 } 30624 }, 30625 allNames: state.wireframes.allNames 30626 }, 30627 error: false 30628 }; 30629 } 30630 case LOADING_SURVEYS_SUCCESS: { 30631 let { projectName, surveys } = action.payload; 30632 let wireframes = state.wireframes.byName[projectName]; 30633 return { 30634 ...state, 30635 wireframes: { 30636 byName: { 30637 ...state.wireframes.byName, 30638 [projectName]: { 30639 ...wireframes, 30640 surveys 30641 } 30642 }, 30643 allNames: state.wireframes.allNames 30644 }, 30645 error: false 30646 }; 30647 } 30648 case UPDATE_WIREFRAME_GRAPHQL_PARENT_PROGRAM_VERSION_ID: { 30649 let { projectName, graphQLParentProgramVersionId } = action.payload; 30650 const wireframesPath = StateReaderUtils.getWireframesPathOnState(projectName); 30651 let newState; 30652 newState = immutablyReplaceValue(state, [...wireframesPath, "graphQLParentProgramVersionId"], graphQLParentProgramVersionId); 30653 return newState; 30654 } 30655 default: return state; 30656 } 30657} 30658//#endregion 30659//#region client/logic/projects/projectWireframes/projectNarrations/projectNarrationsReducer.ts 30660function projectNarrationsReducer(state, action) { 30661 switch (action.type) { 30662 case ADD_NARRATION_SUCCESS: { 30663 let { projectName, narrationId, sceneId, structure, variationDataMap, postgresNarrationId, graphQLUpdated } = action.payload; 30664 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 30665 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 30666 let narrationState = { 30667 updating: false, 30668 postgresNarrationId, 30669 structure, 30670 variationDataMap, 30671 graphQLUpdated 30672 }; 30673 narrationState.dimensions = NarrationsModelUtils.buildDimensions(narrationState.structure, valueSetProviders); 30674 narrationState.variations = NarrationsModelUtils.buildVariations(narrationState.structure, narrationState.variationDataMap, narrationState.dimensions, valueSetProviders); 30675 return updatedStateWithNewNarration(state, projectName, null, null, narrationId, narrationState); 30676 } 30677 case DELETE_NARRATION_SUCCESS: { 30678 let { projectName, narrationId } = action.payload; 30679 return updatedStateWithDeletedNarration(state, projectName, narrationId); 30680 } 30681 case LOAD_NARRATIONS_SUCCESS: 30682 case LOADING_PROGRAM_WIREFRAMES_SUCCESS: { 30683 let { projectName, narrations, stage, version } = action.payload; 30684 const wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 30685 const dataElements = StateReaderUtils.getProjectDataElementsFromWireframes(wireframes); 30686 const dataElementValueSetProviders = generateValueSetProviders(dataElements, []); 30687 const allValueSetProviders = generateValueSetProviders(dataElements, StateReaderUtils.getProjectPrioritizedLists(wireframes)); 30688 narrations.forEach((loadedNarration) => { 30689 let narrationId = loadedNarration.id; 30690 let dbNarration = loadedNarration.dbNarration; 30691 let dbStructure = dbNarration.structure; 30692 let dbDimensionData = dbStructure.dimensionData; 30693 let dbMergeData = dbStructure.mergeData; 30694 let dbRepresentativeKey = dbStructure.representativeKey; 30695 let dbCreativeOverride = dbStructure.creativeOverride; 30696 let dbVariationData = dbNarration.variationData;
30697 let structure = NarrationsModelUtils.dbBuildStructureFromDBData(dbDimensionData, dbMergeData, dbRepresentativeKey, dbCreativeOverride); 30698 let variationDataMap = NarrationsModelUtils.dbBuildVariationDataMapFromVariationData(dbVariationData); 30699 let narrationState = { 30700 graphQLUpdated: dbNarration.graphQLUpdated, 30701 updating: false, 30702 postgresNarrationId: dbNarration.postgresNarrationId, 30703 structure, 30704 variationDataMap 30705 }; 30706 let sceneId = StateReaderUtils.getSceneIdOfNarration(wireframes, narrationId); 30707 let valueSetProviders; 30708 if (sceneId) { 30709 let sceneValueSetProviders = generateValueSetProviders([], StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 30710 valueSetProviders = [...dataElementValueSetProviders, ...sceneValueSetProviders]; 30711 } else valueSetProviders = allValueSetProviders; 30712 narrationState.dimensions = NarrationsModelUtils.buildDimensions(narrationState.structure, valueSetProviders); 30713 narrationState.variations = NarrationsModelUtils.buildVariations(narrationState.structure, narrationState.variationDataMap, narrationState.dimensions, valueSetProviders); 30714 state = updatedStateWithNewNarration(state, projectName, stage, version, narrationId, narrationState); 30715 }); 30716 state = { 30717 ...state, 30718 lastRelevantNarrationUpdateTimeStamp: Date.now(), 30719 showMutedNarrationRows: true, 30720 showNarrationNoteColumn: true, 30721 showNarrationStatusColumn: false 30722 }; 30723 return state; 30724 } 30725 case LOADING_PROJECT_WIREFRAMES_FROM_UIASSET: { 30726 let { projectName, data, stage, version } = action.payload; 30727 if (data.narrations) { 30728 const wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 30729 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getProjectPrioritizedLists(wireframes)); 30730 Object.keys(data.narrations.byId).forEach((narrationId) => { 30731 let serializedNarrationState = data.narrations.byId[narrationId]; 30732 let narrationState = { 30733 updating: false, 30734 structure: NarrationsModelUtils.unserializeStructure(serializedNarrationState.structure), 30735 variationDataMap: NarrationsModelUtils.unserializeVariationDataMap(serializedNarrationState.variationDataMap) 30736 }; 30737 narrationState.dimensions = NarrationsModelUtils.buildDimensions(narrationState.structure, valueSetProviders); 30738 narrationState.variations = NarrationsModelUtils.buildVariations(narrationState.structure, narrationState.variationDataMap, narrationState.dimensions, valueSetProviders); 30739 state = updatedStateWithNewNarration(state, projectName, stage, version, narrationId, narrationState); 30740 }); 30741 state = { 30742 ...state, 30743 lastRelevantNarrationUpdateTimeStamp: Date.now(), 30744 showMutedNarrationRows: true, 30745 showNarrationNoteColumn: true, 30746 showNarrationStatusColumn: false 30747 }; 30748 } 30749 return state; 30750 } 30751 case UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_PENDING: { 30752 let { projectName, narrationId, variationDataUpdates } = action.payload; 30753 let narrationState = { ...StateReaderUtils.getWireFrame(state, projectName).narrations.byId[narrationId] }; 30754 narrationState.updating = true; 30755 if (variationDataUpdates) Object.keys(variationDataUpdates).forEach((variationKey) => { 30756 let variationDataUpdate = variationDataUpdates[variationKey]; 30757 narrationState.variationDataMap = NarrationsModelUtils.updateVariationDataMap(narrationState.variationDataMap, variationKey, variationDataUpdate); 30758 let variationData = narrationState.variationDataMap.get(variationKey); 30759 if (variationData) narrationState.variations = NarrationsModelUtils.applyVariationDataToVariations(narrationState.variations, variationKey, variationData); 30760 }); 30761 return updatedStateWithNarration(state, projectName, narrationId, narrationState); 30762 } 30763 case UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_SUCCESS: { 30764 let { projectName, sceneId, narrationId, structureUpdate, mayCauseChangeInAssetLibrary, graphQLUpdated } = action.payload; 30765 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 30766 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 30767 let narrationState = { 30768 ...wireframes.narrations.byId[narrationId], 30769 graphQLUpdated 30770 }; 30771 narrationState.updating = false;
30772 if (structureUpdate) { 30773 narrationState.structure = NarrationsModelUtils.updateStructure(narrationState.structure, structureUpdate); 30774 narrationState.dimensions = NarrationsModelUtils.buildDimensions(narrationState.structure, valueSetProviders); 30775 narrationState.variations = NarrationsModelUtils.buildVariations(narrationState.structure, narrationState.variationDataMap, narrationState.dimensions, valueSetProviders); 30776 } 30777 return updatedStateWithNarration(state, projectName, narrationId, narrationState, mayCauseChangeInAssetLibrary); 30778 } 30779 case UPDATE_NARRATION_STRUCTURE_AND_VARIATIONDATA_FAILURE: { 30780 let { projectName, narrationId, variationReverts, variationDataMapReverts } = action.payload; 30781 let narrationState = { ...StateReaderUtils.getWireFrame(state, projectName).narrations.byId[narrationId] }; 30782 narrationState.updating = false; 30783 if (variationReverts) Object.keys(variationReverts).forEach((variationKey) => { 30784 narrationState.variations = NarrationsModelUtils.applyVariationDataToVariations(narrationState.variations, variationKey, variationReverts[variationKey]); 30785 }); 30786 if (variationDataMapReverts) Object.keys(variationDataMapReverts).forEach((variationKey) => { 30787 narrationState.variationDataMap = NarrationsModelUtils.applyVariationDataToVariationDataMap(narrationState.variationDataMap, variationKey, variationDataMapReverts[variationKey]); 30788 }); 30789 return updatedStateWithNarration(state, projectName, narrationId, narrationState); 30790 } 30791 case REMOVE_NARRATION_DIMENSION: { 30792 let { projectName, narrationId, sceneId, index } = action.payload; 30793 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 30794 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 30795 let narrationState = { ...wireframes.narrations.byId[narrationId] }; 30796 narrationState.dimensions = NarrationsModelUtils.removeDimension(narrationState.dimensions, index); 30797 narrationState.variations = NarrationsModelUtils.buildVariations(narrationState.structure, narrationState.variationDataMap, narrationState.dimensions, valueSetProviders); 30798 return updatedStateWithNarration(state, projectName, narrationId, narrationState, true); 30799 } 30800 case UPDATE_NARRATION_POSTGRES_ID_SUCCESS: { 30801 const { accountId, projectName, narrationId, postgresId, isPostgresOnly } = action.payload; 30802 let narrationState = { ...StateReaderUtils.getWireFrame(state, projectName).narrations.byId[narrationId] }; 30803 if (!isPostgresOnly) { 30804 narrationState.postgresNarrationId = postgresId; 30805 return updatedStateWithNarration(state, projectName, narrationId, narrationState); 30806 } else { 30807 const newAssetsByIds = {}; 30808 const newAssetAllIds = []; 30809 state.assets.allIds.forEach((assetId) => { 30810 const asset = state.assets.byId[assetId]; 30811 if (asset.type === AssetTypes.recording && asset.narrationId === narrationId) { 30812 let newName = asset.name.replace(narrationId, postgresId); 30813 let newAssetId = StateReaderUtils.getAssetUniqueId(accountId, projectName, AssetTypes.recording, newName); 30814 newAssetsByIds[newAssetId] = { 30815 ...asset, 30816 name: newName, 30817 assetId: newAssetId, 30818 narrationId: postgresId 30819 }; 30820 newAssetAllIds.push(newAssetId); 30821 } else { 30822 newAssetsByIds[assetId] = asset; 30823 newAssetAllIds.push(assetId); 30824 } 30825 }); 30826 const program = StateReaderUtils.getProject(state, projectName); 30827 const newProgramAssets = []; 30828 program.assets.forEach((assetId) => { 30829 if (assetId.includes(narrationId)) newProgramAssets.push(assetId.replace(narrationId, postgresId)); 30830 else newProgramAssets.push(assetId); 30831 }); 30832 let newState = immutablyReplaceValue(state, ["assets", "byId"], newAssetsByIds); 30833 newState = immutablyReplaceValue(newState, ["assets", "allIds"], newAssetAllIds); 30834 newState = immutablyReplaceValue(newState, [ 30835 "projects", 30836 "byName", 30837 projectName, 30838 "assets" 30839 ], newProgramAssets); 30840 return updatedStateWithNarration(newState, projectName, postgresId, narrationState); 30841 } 30842 } 30843 case CANCEL_REMOVE_NARRATION_DIMENSION: 30844 case NARRATION_USED_VALUE_SET_PROVIDER_CHANGED: { 30845 let { projectName, sceneId, narrationId } = action.payload; 30846 const wireframes = StateReaderUtils.getWireFrame(state, projectName); 30847 let valueSetProviders = generateValueSetProviders(StateReaderUtils.getProjectDataElementsFromWireframes(wireframes), StateReaderUtils.getScenePrioritizedList(wireframes, sceneId)); 30848 let narrationState = { ...wireframes.narrations.byId[narrationId] }; 30849 narrationState.dimensions = NarrationsModelUtils.buildDimensions(narrationState.structure, valueSetProviders); 30850 narrationState.variations = NarrationsModelUtils.buildVariations(narrationState.structure, narrationState.variationDataMap, narrationState.dimensions, valueSetProviders); 30851 return updatedStateWithNarration(state, projectName, narrationId, narrationState); 30852 } 30853 case SET_SHOW_MUTED_ROWS: return { 30854 ...state, 30855 showMutedNarrationRows: action.payload.show 30856 }; 30857 case SET_SHOW_NOTE_COLUMN: return { 30858 ...state, 30859 showNarrationNoteColumn: action.payload.show 30860 }; 30861 case SET_SHOW_STATUS_COLUMN: return { 30862 ...state, 30863 showNarrationStatusColumn: action.payload.show 30864 }; 30865 default: return state; 30866 } 30867} 30868function updatedStateWithNarration(state, projectName, narrationId, narrationState, mayCauseChangeInAssetLibrary) { 30869 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 30870 let wireframesNarrations = _getOrInitWireFramesNarration(wireframes); 30871 let newState = { 30872 ...state, 30873 wireframes: { 30874 ...state.wireframes, 30875 byName: { 30876 ...state.wireframes.byName, 30877 [projectName]: { 30878 ...wireframes, 30879 narrations: { 30880 ...wireframesNarrations, 30881 byId: { 30882 ...wireframesNarrations.byId, 30883 [narrationId]: { ...narrationState } 30884 } 30885 } 30886 } 30887 } 30888 } 30889 }; 30890 if (mayCauseChangeInAssetLibrary) newState.lastRelevantNarrationUpdateTimeStamp = Date.now(); 30891 return newState; 30892} 30893function updatedStateWithNewNarration(state, projectName, stage, version, narrationId, narrationState) { 30894 let wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 30895 let wireframesNarrations = _getOrInitWireFramesNarration(wireframes); 30896 let wireframeKey; 30897 if (stage) wireframeKey = `${stage}wireframes`; 30898 else if (version) wireframeKey = "versionwireframes"; 30899 else wireframeKey = "wireframes"; 30900 const narrationObj = { 30901 ...wireframesNarrations, 30902 allIds: [...wireframesNarrations.allIds, narrationId], 30903 byId: { 30904 ...wireframesNarrations.byId, 30905 [narrationId]: { ...narrationState } 30906 } 30907 }; 30908 const byNameObj = stage === "diff" ? { 30909 ...state[wireframeKey].byName[projectName], 30910 [version]: { 30911 ...wireframes, 30912 narrations: narrationObj 30913 } 30914 } : { 30915 ...wireframes, 30916 narrations: narrationObj 30917 }; 30918 return { 30919 ...state, 30920 [wireframeKey]: { 30921 ...state[wireframeKey], 30922 byName: { 30923 ...state[wireframeKey].byName, 30924 [projectName]: byNameObj 30925 } 30926 } 30927 }; 30928} 30929function updatedStateWithDeletedNarration(state, projectName, narrationId) { 30930 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 30931 let newState = { 30932 ...state, 30933 wireframes: { 30934 ...state.wireframes, 30935 byName: { 30936 ...state.wireframes.byName, 30937 [projectName]: { 30938 ...wireframes, 30939 narrations: { 30940 ...wireframes.narrations, 30941 allIds: wireframes.narrations.allIds.filter((id) => id !== narrationId) 30942 } 30943 } 30944 } 30945 }, 30946 lastRelevantNarrationUpdateTimeStamp: Date.now() 30947 }; 30948 let newWireframes = StateReaderUtils.getWireFrame(newState, projectName); 30949 delete newWireframes.narrations.byId[narrationId]; 30950 return newState; 30951} 30952function _getOrInitWireFramesNarration(wireframes) { 30953 return wireframes.narrations ? { ...wireframes.narrations } : { 30954 byId: {}, 30955 allIds: [] 30956 }; 30957} 30958//#endregion 30959//#region client/logic/dashboards/programOverview/programOverviewActions.ts 30960var GENERATE_MOVIE_SUCCESS = "GENERATE_MOVIE_SUCCESS"; 30961var GET_PRESET_DATA_ELEMENTS_SUCCESS = "GET_PRESET_DATA_ELEMENTS_SUCCESS"; 30962var SAVE_PRESET_SUCCESS = "SAVE_PRESET_SUCCESS"; 30963var GET_ANALYTICS_SUCCESS = "GET_ANALYTICS_SUCCESS"; 30964var GET_PROGRAM_DETAILS_SUCCESS = "GET_PROGRAM_DETAILS_SUCCESS"; 30965var UPLOAD_IMAGE = "UPLOAD_IMAGE_SUCCESS"; 30966var SECOND_UPLOAD_IMAGE = "SECOND_UPLOAD_IMAGE"; 30967var CREATE_SHARE_URL_SUCCESS = "CREATE_SHARE_URL_SUCCESS"; 30968var RESET_ANALYTICS = "RESET_ANALYTICS"; 30969var generatingMovieSuccess = (0, import_lib$3.createAction)(GENERATE_MOVIE_SUCCESS, function(previewDashboardSessionId, stateObjName, stateShareUrlObjName = "shareUrl") { 30970 return { 30971 sessionId: previewDashboardSessionId.body, 30972 stateObjName, 30973 shortUrl: previewDashboardSessionId.shortUrl, 30974 stateShareUrlObjName 30975 }; 30976}); 30977var savePresetSuccess = (0, import_lib$3.createAction)(SAVE_PRESET_SUCCESS, function(previewDashboardSessionId) { 30978 return { sessionId: previewDashboardSessionId }; 30979}); 30980var getPresetDataElementsSuccess = (0, import_lib$3.createAction)(GET_PRESET_DATA_ELEMENTS_SUCCESS, function(presetDataElements, stateObjName) { 30981 return { 30982 presetDataElements, 30983 stateObjName 30984 }; 30985}); 30986var getAnalyticsSuccess = (0, import_lib$3.createAction)(GET_ANALYTICS_SUCCESS, function(analyticsEmbedContainerChartUrl) { 30987 return { chartUrl: analyticsEmbedContainerChartUrl }; 30988}); 30989var resetAnalyticsUrl = (0, import_lib$3.createAction)(RESET_ANALYTICS, function() { 30990 return { chartUrl: void 0 }; 30991}); 30992var getProgramDetailsSuccess = (0, import_lib$3.createAction)(GET_PROGRAM_DETAILS_SUCCESS, function(programId, programDetails) { 30993 return { 30994 programId, 30995 programDetails 30996 }; 30997}); 30998(0, import_lib$3.createAction)(UPLOAD_IMAGE, function({ url, thumbnail }) { 30999 return { 31000 url, 31001 thumbnail 31002 }; 31003}); 31004(0, import_lib$3.createAction)(SECOND_UPLOAD_IMAGE, function({ url, thumbnail }) { 31005 return { 31006 url, 31007 thumbnail 31008 }; 31009}); 31010var createShareUrlSuccess = (0, import_lib$3.createAction)(CREATE_SHARE_URL_SUCCESS, function(shareUrl) { 31011 return { shareUrl }; 31012}); 31013var getProgramDetails = function(accountId, programId) { 31014 return function(dispatch, state, services) { 31015 services.programOverviewServices.getProgramDetails(accountId, programId).then(function(res) { 31016 dispatch(getProgramDetailsSuccess(programId, res)); 31017 }).catch(function(err) { 31018 dispatch(reportError(err)); 31019 }); 31020 }; 31021}; 31022var getPresetDataElements = function(accountId, programId, presetId, stateObjName = "presetDataElements") { 31023 return function(dispatch, state, services) { 31024 services.programOverviewServices.getPresetDataElements(accountId, programId, presetId).then(function(res) { 31025 dispatch(getPresetDataElementsSuccess(res, stateObjName)); 31026 }).catch(function(err) { 31027 dispatch(reportError(err)); 31028 }); 31029 }; 31030}; 31031var getSecondPresetDataElements = function(accountId, programId, presetId) { 31032 return getPresetDataElements(accountId, programId, presetId, "secondPresetDataElements"); 31033}; 31034var createVideoSession = function({ accountId, programId, presetId, dataElements, stateObjName = "previewDashboardSessionObj", generateShareUrl, previewSettings, videoFormat, requestId }) { 31035 return function(dispatch, state, services) { 31036 services.programOverviewServices.createVideoSession({ 31037 accountId, 31038 programId, 31039 presetId, 31040 dataElements, 31041 generateShareUrl, 31042 previewSettings, 31043 videoFormat, 31044 requestId 31045 }).then(function(res) { 31046 dispatch(generatingMovieSuccess(res, stateObjName)); 31047 }).catch(function(err) { 31048 dispatch(reportError(err)); 31049 }); 31050 }; 31051}; 31052var createShareUrl = function(accountId, programId, presetId, dataElements) { 31053 return function(dispatch, state, services) { 31054 services.programOverviewServices.createShareUrl(accountId, programId, presetId, dataElements).then(function(res) { 31055 dispatch(createShareUrlSuccess(res)); 31056 }).catch(function(err) { 31057 dispatch(reportError(err)); 31058 }); 31059 }; 31060}; 31061var createSecondVideoSession = function({ accountId, programId, presetId, dataElements, previewSettings, requestId }) { 31062 return createVideoSession({ 31063 accountId, 31064 programId, 31065 presetId, 31066 dataElements, 31067 stateObjName: "secondPreviewDashboardSessionObj", 31068 generateShareUrl: false, 31069 previewSettings, 31070 requestId 31071 }); 31072}; 31073var getAnalytics = function(accountId, programId, programFlow) { 31074 return function(dispatch, state, services) { 31075 dispatch(resetAnalyticsUrl()); 31076 services.programOverviewServices.getAnalytics(accountId, programId, programFlow).then(function(res) { 31077 dispatch(getAnalyticsSuccess(res)); 31078 }).catch(function(err) { 31079 dispatch(reportError(err, false)); 31080 }); 31081 }; 31082}; 31083var savePreset = function(accountId, programId, presetId, dataElements, presetName) { 31084 return function(dispatch, state, services) { 31085 services.programOverviewServices.savePreset(accountId, programId, presetId, dataElements, presetName).then(function(res) { 31086 dispatch(savePresetSuccess(res)); 31087 }).catch(function(err) { 31088 dispatch(reportError(err)); 31089 }); 31090 }; 31091}; 31092//#endregion 31093//#region client/logic/dashboards/programOverview/programOverviewReducer.js 31094function programOverviewReducer(state, action) { 31095 let allProgramsIds = state.dashboardPrograms.allIds; 31096 let programsById = state.dashboardPrograms.byId; 31097 switch (action.type) { 31098 case GENERATE_MOVIE_SUCCESS: return Object.assign({}, state, { 31099 [[action.payload.stateObjName]]: { sessionId: action.payload.sessionId }, 31100 [[action.payload.stateShareUrlObjName]]: action.payload.shortUrl 31101 }); 31102 case GET_PRESET_DATA_ELEMENTS_SUCCESS: return Object.assign({}, state, { [[action.payload.stateObjName]]: action.payload.presetDataElements }); 31103 case GET_ANALYTICS_SUCCESS: return Object.assign({}, state, { analyticsEmbedContainerChartUrl: action.payload.chartUrl }); 31104 case RESET_ANALYTICS: return Object.assign({}, state, { analyticsEmbedContainerChartUrl: action.payload.chartUrl }); 31105 case GET_PROGRAM_DETAILS_SUCCESS: 31106 programsById[action.payload.programId].details = action.payload.programDetails; 31107 return Object.assign({}, state, { 31108 dashboardPrograms: { 31109 allIds: allProgramsIds,
31110 byId: programsById 31111 }, 31112 selectedProgramId: action.payload.programId 31113 }); 31114 case UPLOAD_IMAGE: return Object.assign({}, state, { 31115 imageUrl: action.payload.url, 31116 imageThumbnail: action.payload.thumbnail 31117 }); 31118 case SECOND_UPLOAD_IMAGE: return Object.assign({}, state, { 31119 secondImageUrl: action.payload.url, 31120 secondImageThumbnail: action.payload.thumbnail 31121 }); 31122 case CREATE_SHARE_URL_SUCCESS: return Object.assign({}, state, { shareUrl: action.payload.shareUrl }); 31123 default: return state; 31124 } 31125} 31126//#endregion 31127//#region client/logic/DataElements/DataElementReducers.ts 31128/*** 31129* Returens a merge state object with the data elements array of the given program 31130* @param state - existing redux state object 31131* @param programName - the name of the program 31132* @param dataElementsArr - the data elements array to be merged upon the state 31133* @param stage - stage 31134* @param version - version 31135* @return {{wireframes: {byName: {}, allNames: *}, error: boolean}} - The new merged state 31136*/ 31137function reduceDataElementsArray(state, programName, dataElementsArr, stage, version) { 31138 const wireframesPath = StateReaderUtils.getWireframesPathOnState(programName, stage, version); 31139 wireframesPath.push("dataElements"); 31140 let newState = immutablyReplaceValue(state, wireframesPath, dataElementsArr); 31141 newState.error = false; 31142 return newState; 31143} 31144function updateDataElementSuccess(state, args) { 31145 const { projectName, dataElement, logic } = args; 31146 const dataElementsArr = StateReaderUtils.getProjectDataElements(state, projectName) || []; 31147 const elementIndex = dataElementsArr.findIndex((de) => de.id === dataElement.id); 31148 let newDataElementsArr = []; 31149 if (elementIndex < 0) newDataElementsArr = dataElementsArr.concat([buildDataElement({ ...dataElement })]); 31150 else newDataElementsArr = [ 31151 ...dataElementsArr.slice(0, elementIndex), 31152 buildDataElement({ ...dataElement }), 31153 ...dataElementsArr.slice(elementIndex + 1) 31154 ]; 31155 let newState = reduceDataElementsArray(state, projectName, newDataElementsArr, void 0, void 0); 31156 const { byName } = newState.wireframes; 31157 const derivedLogic = byName[projectName].logic[LogicContainers.Derived]; 31158 if (logic === void 0) return newState; 31159 else { 31160 let newDerivedLogic = { ...derivedLogic }; 31161 if (logic) newDerivedLogic[dataElement.id] = logic; 31162 else delete newDerivedLogic[dataElement.id]; 31163 return { 31164 ...newState, 31165 wireframes: { 31166 ...newState.wireframes, 31167 byName: { 31168 ...byName, 31169 [projectName]: { 31170 ...byName[projectName], 31171 logic: { 31172 ...byName[projectName].logic, 31173 [LogicContainers.Derived]: newDerivedLogic 31174 } 31175 } 31176 } 31177 } 31178 }; 31179 } 31180} 31181function deleteDataElementsSuccess(state, args) { 31182 const { projectName, dataElementIds } = args; 31183 const dataElementsArr = StateReaderUtils.getProjectDataElements(state, projectName) || []; 31184 const newDataElementsArr = dataElementsArr.filter((de) => !dataElementIds.includes(de.id)); 31185 if (newDataElementsArr.length === dataElementsArr.length) return state; 31186 return reduceDataElementsArray(state, projectName, newDataElementsArr, void 0, void 0); 31187} 31188function dataElementReducer(state, action) { 31189 switch (action.type) { 31190 case LOADING_PROGRAM_WIREFRAMES_SUCCESS: { 31191 let { projectName, dataElements, stage, version } = action.payload; 31192 return reduceDataElementsArray(state, projectName, dataElements.map((de) => buildDataElement(de)), stage, version); 31193 } 31194 case ADD_DATA_ELEMENT_SUCCESS: return updateDataElementSuccess(state, action.payload); 31195 case UPDATE_DATA_ELEMENT_SUCCESS: return updateDataElementSuccess(state, action.payload); 31196 case DELETE_DATA_ELEMENTS_SUCCESS: return deleteDataElementsSuccess(state, action.payload); 31197 default: return state; 31198 } 31199} 31200//#endregion 31201//#region client/logic/projects/projectWireframes/projectCombinedReducer.js 31202function projectCombinedReducer(state, action) { 31203 function getDerivedLogicCycles(wireframes) { 31204 let dataElements = StateReaderUtils.getProjectDataElementsFromWireframes(wireframes); 31205 let derivedDataElements = dataElements.filter((de) => de.origin === DataElementOrigins.Derived); 31206 let studioDataManager = new StudioDataManager({ 31207 dataElements, 31208 derivedLogic: wireframes && wireframes.logic && wireframes.logic[LogicContainers.Derived] 31209 }); 31210 studioDataManager.buildDerivedGraph(derivedDataElements); 31211 return studioDataManager.detectCycles(); 31212 } 31213 switch (action.type) { 31214 case UPDATING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC_SUCCESS: 31215 case DELETING_PROJECT_WIREFRAMES_INPUT_LOGICS_SUCCESS: 31216 case LOADING_PROGRAM_WIREFRAMES_SUCCESS: { 31217 let logicContainer = action.payload.sceneId; 31218 let projectName = action.payload.projectName; 31219 let stage = action.payload.stage; 31220 let version = action.payload.version; 31221 if (logicContainer !== LogicContainers.Derived && !action.payload.calculateDeriveCycles) return state; 31222 let wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 31223 let wireframesPath = StateReaderUtils.getWireframesPathOnState(projectName, stage, version); 31224 let cycles = getDerivedLogicCycles(wireframes); 31225 return immutablyReplaceValue(state, [...wireframesPath, "derivedLogicCycles"], cycles); 31226 } 31227 case LOADING_PROJECT_WIREFRAMES_FROM_UIASSET: { 31228 let { projectName, stage, version } = action.payload; 31229 let wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 31230 let wireframesPath = StateReaderUtils.getWireframesPathOnState(projectName, stage, version); 31231 const cycles = getDerivedLogicCycles(wireframes); 31232 return immutablyReplaceValue(state, [...wireframesPath, "derivedLogicCycles"], cycles); 31233 } 31234 case UPDATE_PROJECT_COMPLETE: { 31235 let { RFR, RFRUpdateTimestamp, projectName } = action.payload.project; 31236 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 31237 if (!wireframes) return state; 31238 return { 31239 ...state, 31240 wireframes: {
31241 byName: { 31242 ...state.wireframes.byName, 31243 [projectName]: { 31244 ...wireframes, 31245 programRFR: RFR, 31246 programRFRTimestamp: RFRUpdateTimestamp 31247 } 31248 }, 31249 allNames: state.wireframes.allNames 31250 }, 31251 error: false 31252 }; 31253 } 31254 default: return state; 31255 } 31256} 31257//#endregion 31258//#region client/logic/stories/StoryReducer.ts 31259function getParticipatingSceneIdsAndDPs(initialDPId, allDPLogicInStory, allScenes) { 31260 let { participatingSceneIds, participatingDPs } = initialDPId && allDPLogicInStory ? extractSceneIdsAndDPsFromDPLogic(allDPLogicInStory[initialDPId], allDPLogicInStory) : { 31261 participatingSceneIds: [], 31262 participatingDPs: [] 31263 }; 31264 if (initialDPId) participatingDPs.push(initialDPId); 31265 participatingSceneIds = participatingSceneIds.filter((sceneId) => !!allScenes[sceneId]); 31266 return { 31267 participatingDPs, 31268 participatingSceneIds 31269 }; 31270} 31271function storyReducer(state, action) { 31272 switch (action.type) { 31273 case ADD_NEW_STORY_SUCCESS: { 31274 let { projectName, data } = action.payload; 31275 let { storyId, storyData, DpLogicData, soundtrackLogicData, backgroundImageLogicData, backgroundVideoLogicData } = data; 31276 let byName = state.wireframes.byName; 31277 let allNames = state.wireframes.allNames; 31278 let currentStories = byName[projectName] ? byName[projectName].stories : {}; 31279 let currentLogic = byName[projectName] ? byName[projectName].logic : {}; 31280 let currentStoriesLogic = currentLogic ? currentLogic[LogicContainers.Story] : {}; 31281 storyData.participatingSceneIds = []; 31282 storyData.participatingDPs = [storyData.initialDecisionPointId]; 31283 return Object.assign({}, state, { 31284 wireframes: { 31285 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { 31286 stories: Object.assign({}, currentStories, { [storyId]: storyData }), 31287 logic: Object.assign({}, currentLogic, { [LogicContainers.Story]: { 31288 ...currentStoriesLogic, 31289 [storyId]: { 31290 [LogicContainers.DecisionPoint]: { [storyData.initialDecisionPointId]: DpLogicData }, 31291 [LogicContainers.Soundtrack]: { [MediaTypes.Audio]: soundtrackLogicData }, 31292 [LogicContainers.BackgroundAsset]: { 31293 [MediaTypes.Image]: backgroundImageLogicData, 31294 [MediaTypes.Video]: backgroundVideoLogicData 31295 } 31296 } 31297 } }) 31298 }) }), 31299 allNames 31300 }, 31301 error: false 31302 }); 31303 } 31304 case DUPLICATE_STORY: { 31305 let { projectName, data } = action.payload; 31306 let { storyId, storyData, storyLogicItems } = data; 31307 let byName = state.wireframes.byName; 31308 let allNames = state.wireframes.allNames; 31309 let currentStories = byName[projectName] ? byName[projectName].stories : {}; 31310 let currentLogic = byName[projectName] ? byName[projectName].logic : {}; 31311 let currentStoriesLogic = currentLogic ? currentLogic[LogicContainers.Story] : {}; 31312 return Object.assign({}, state, { 31313 wireframes: { 31314 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { 31315 stories: Object.assign({}, currentStories, { [storyId]: storyData }), 31316 logic: Object.assign({}, currentLogic, { [LogicContainers.Story]: { 31317 ...currentStoriesLogic, 31318 [storyId]: storyLogicItems 31319 } }) 31320 }) }), 31321 allNames 31322 }, 31323 error: false 31324 }); 31325 } 31326 case DELETE_STORY_SUCCESS: { 31327 let { projectName, data } = action.payload; 31328 let { storyId } = data; 31329 let byName = state.wireframes.byName; 31330 let allNames = state.wireframes.allNames; 31331 let currentStories = byName[projectName].stories; 31332 let updatedStories = excludeKeysFromObject([storyId], currentStories); 31333 let currentLogic = byName[projectName].logic; 31334 let currentStoryLogic = byName[projectName].logic[LogicContainers.Story]; 31335 let updatedStoriesLogic = excludeKeysFromObject([storyId], currentStoryLogic); 31336 return Object.assign({}, state, { 31337 wireframes: { 31338 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { 31339 stories: Object.assign({}, updatedStories), 31340 logic: Object.assign({}, currentLogic, { [LogicContainers.Story]: updatedStoriesLogic }) 31341 }) }), 31342 allNames 31343 }, 31344 error: false 31345 }); 31346 } 31347 case LOADING_PROGRAM_WIREFRAMES_SUCCESS: { 31348 let { projectName, storiesLogic, stage, version } = action.payload; 31349 if (!storiesLogic) return state; 31350 let wireframes = StateReaderUtils.getWireFrame(state, projectName, stage, version); 31351 let stories = StateReaderUtils.getStories(wireframes) || {}; 31352 let newStories = Object.keys(stories).reduce((acc, storyId) => { 31353 let story = stories[storyId]; 31354 let allDPLogic = storiesLogic[storyId][LogicContainers.DecisionPoint]; 31355 const { participatingDPs, participatingSceneIds } = getParticipatingSceneIdsAndDPs(story.initialDecisionPointId, allDPLogic, wireframes.scenes); 31356 acc[storyId] = { 31357 ...story, 31358 participatingDPs, 31359 participatingSceneIds 31360 }; 31361 return acc; 31362 }, {}); 31363 return immutablyReplaceValue(state, [...StateReaderUtils.getWireframesPathOnState(projectName, stage, version), "stories"], newStories); 31364 } 31365 case UPDATE_DECISION_POINT_LOGIC_AND_ADD_NEW_DECISION_POINT_LOGIC: 31366 case UPDATE_DECISION_POINT_LOGIC: 31367 case MERGE_DECISION_POINTS_SUCCESS: 31368 case REMOVE_SCENE_FROM_STORY: { 31369 let { projectName, data } = action.payload; 31370 let { storyId, updatedStoryDecisionPointsLogics, decisionPointLogicIdToDelete, storyDataToUpdate } = data; 31371 let byName = state.wireframes.byName; 31372 let allNames = state.wireframes.allNames; 31373 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 31374 let currentStories = wireframes ? wireframes.stories : {}; 31375 let currentLogic = wireframes ? wireframes.logic : {}; 31376 let currentStoryLogic = currentLogic[LogicContainers.Story][storyId] || {}; 31377 let currentStoryDPLogic = currentStoryLogic[LogicContainers.DecisionPoint] || {}; 31378 let story = currentStories[storyId]; 31379 let updatedStoryDPLogic = { 31380 ...currentStoryDPLogic, 31381 ...updatedStoryDecisionPointsLogics 31382 }; 31383 if (decisionPointLogicIdToDelete) updatedStoryDPLogic = excludeKeysFromObject([decisionPointLogicIdToDelete], updatedStoryDPLogic); 31384 let updatedStory = { 31385 ...story, 31386 ...storyDataToUpdate ? storyDataToUpdate : {} 31387 }; 31388 const { participatingDPs, participatingSceneIds } = getParticipatingSceneIdsAndDPs(updatedStory.initialDecisionPointId, updatedStoryDPLogic, wireframes.scenes); 31389 let updatedStories = { 31390 ...currentStories, 31391 [storyId]: { 31392 ...updatedStory, 31393 participatingDPs, 31394 participatingSceneIds 31395 } 31396 }; 31397 return { 31398 ...state, 31399 wireframes: {
31400 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { 31401 stories: updatedStories, 31402 logic: { 31403 ...currentLogic, 31404 [LogicContainers.Story]: { 31405 ...currentLogic[LogicContainers.Story], 31406 [storyId]: { 31407 ...currentStoryLogic, 31408 [LogicContainers.DecisionPoint]: updatedStoryDPLogic 31409 } 31410 } 31411 } 31412 }) }), 31413 allNames 31414 }, 31415 error: false 31416 }; 31417 } 31418 case UPDATE_STORY_SUCCESS: { 31419 let { projectName, storyId, storyData } = action.payload; 31420 let byName = state.wireframes.byName; 31421 let allNames = state.wireframes.allNames; 31422 let currentStories = byName[projectName] ? byName[projectName].stories : {}; 31423 return Object.assign({}, state, { 31424 wireframes: { 31425 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { stories: Object.assign({}, currentStories, { [storyId]: storyData }) }) }), 31426 allNames 31427 }, 31428 error: false 31429 }); 31430 } 31431 case ADD_SCENE_TO_STORY_SUCCESS: { 31432 let { projectName, data } = action.payload; 31433 let { newSceneData, updatedStoryDecisionPointsLogics, storyId, storyDataToUpdate } = data; 31434 const wireframesPath = StateReaderUtils.getWireframesPathOnState(projectName); 31435 let newState = state; 31436 if (newSceneData) { 31437 newState = immutablyReplaceValue(newState, [ 31438 ...wireframesPath, 31439 "scenes", 31440 newSceneData.id 31441 ], newSceneData); 31442 newState = immutablyReplaceValue(newState, [ 31443 ...wireframesPath, 31444 "logic", 31445 newSceneData.id 31446 ], {}, true); 31447 } 31448 if (storyDataToUpdate) newState = immutablyReplaceValue(newState, [ 31449 ...wireframesPath, 31450 "stories", 31451 storyId 31452 ], storyDataToUpdate, true); 31453 if (updatedStoryDecisionPointsLogics) { 31454 newState = immutablyReplaceValue(newState, [ 31455 ...wireframesPath, 31456 "logic", 31457 LogicContainers.Story, 31458 storyId, 31459 LogicContainers.DecisionPoint 31460 ], updatedStoryDecisionPointsLogics, true); 31461 let story = StateReaderUtils.getProjectWireframesStories(newState, projectName)[storyId]; 31462 const initialDPId = storyDataToUpdate.initialDecisionPointId || story.initialDecisionPointId; 31463 const storyDPLogic = StateReaderUtils.getDecisionPointLogicItemsForStory(newState, projectName, storyId); 31464 const scenes = StateReaderUtils.getWireFrame(newState, projectName).scenes; 31465 const { participatingDPs, participatingSceneIds } = getParticipatingSceneIdsAndDPs(initialDPId, storyDPLogic, scenes); 31466 newState = immutablyReplaceValue(newState, [ 31467 ...wireframesPath, 31468 "stories", 31469 storyId 31470 ], { 31471 participatingDPs, 31472 participatingSceneIds 31473 }, true); 31474 } 31475 newState = immutablyReplaceValue(newState, ["error"], false); 31476 return newState; 31477 } 31478 case DELETING_PROJECT_WIREFRAMES_SCENE_SUCCESS: { 31479 let { projectName } = action.payload; 31480 let byName = state.wireframes.byName; 31481 let allNames = state.wireframes.allNames; 31482 let wireframes = StateReaderUtils.getWireFrame(state, projectName); 31483 let stories = StateReaderUtils.getStories(wireframes) || {}; 31484 let newStories = Object.keys(stories).reduce((acc, storyId) => { 31485 let story = stories[storyId]; 31486 let allDPLogic = wireframes.logic[LogicContainers.Story][storyId][LogicContainers.DecisionPoint]; 31487 const { participatingDPs, participatingSceneIds } = getParticipatingSceneIdsAndDPs(story.initialDecisionPointId, allDPLogic, wireframes.scenes); 31488 acc[storyId] = { 31489 ...story, 31490 participatingDPs, 31491 participatingSceneIds 31492 }; 31493 return acc; 31494 }, {}); 31495 return { 31496 ...state, 31497 wireframes: { 31498 byName: { 31499 ...byName, 31500 [projectName]: { 31501 ...byName[projectName], 31502 stories: newStories 31503 } 31504 }, 31505 allNames 31506 }, 31507 error: false 31508 }; 31509 } 31510 case UPDATE_STORY_LOGIC_ITEMS: { 31511 let { projectName, data } = action.payload; 31512 let { storyId, updatedStoryLogicItems, logicContainerType, storyDataToUpdate } = data; 31513 let programWireframes = StateReaderUtils.getWireFrame(state, projectName); 31514 let byName = state.wireframes.byName; 31515 let allNames = state.wireframes.allNames; 31516 let currentStories = programWireframes ? programWireframes.stories : {}; 31517 let updatedStory = { 31518 ...currentStories[storyId] || {}, 31519 ...storyDataToUpdate ? storyDataToUpdate : {} 31520 }; 31521 let updatedStories = { 31522 ...currentStories, 31523 [storyId]: updatedStory 31524 }; 31525 let currentLogic = byName[projectName] ? byName[projectName].logic : {}; 31526 let currentStoryLogic = currentLogic[LogicContainers.Story][storyId] || {}; 31527 let currentStoryContainerTypeLogic = currentStoryLogic[logicContainerType] || {}; 31528 return { 31529 ...state, 31530 wireframes: {
31531 byName: Object.assign({}, byName, { [projectName]: Object.assign({}, byName[projectName], { 31532 stories: updatedStories, 31533 logic: { 31534 ...currentLogic, 31535 [LogicContainers.Story]: { 31536 ...currentLogic[LogicContainers.Story], 31537 [storyId]: { 31538 ...currentStoryLogic, 31539 [logicContainerType]: { 31540 ...currentStoryContainerTypeLogic, 31541 ...updatedStoryLogicItems 31542 } 31543 } 31544 } 31545 } 31546 }) }), 31547 allNames 31548 }, 31549 error: false 31550 }; 31551 } 31552 case MIGRATE_TO_MULTIPLE_STORIES_SUCCESS: { 31553 let { projectName } = action.payload; 31554 return { 31555 ...state, 31556 projects: { 31557 ...state.projects, 31558 byName: { 31559 ...state.projects.byName, 31560 [projectName]: { 31561 ...state.projects.byName[projectName], 31562 storiesVersion: 1 31563 } 31564 } 31565 } 31566 }; 31567 } 31568 default: return state; 31569 } 31570} 31571//#endregion 31572//#region client/logic/versionDiff/diffActions.ts 31573var GENERATE_DIFF_MODEL = "GENERATE_DIFF_MODEL"; 31574var generateDiffModelAction = (0, import_lib$3.createAction)(GENERATE_DIFF_MODEL, (programName, currentVersion, previousVersion) => ({ 31575 programName, 31576 currentVersion, 31577 previousVersion 31578})); 31579var TOGGLE_DIFF_MODEL_BY_ID = "TOGGLE_DIFF_MODEL_BY_ID"; 31580var toggleDiffModelByIdAction = (0, import_lib$3.createAction)(TOGGLE_DIFF_MODEL_BY_ID, (id) => id); 31581var EXPAND_OR_COLLAPSE_DIFF_MODEL = "EXPAND_OR_COLLAPSE_DIFF_MODEL"; 31582var expandOrCollapseDiffModelAction = (0, import_lib$3.createAction)(EXPAND_OR_COLLAPSE_DIFF_MODEL, (expandAll) => expandAll); 31583var CLEAR_DIFF_MODEL = "CLEAR_DIFF_MODEL"; 31584var clearDiffModelAction = (0, import_lib$3.createAction)(CLEAR_DIFF_MODEL); 31585var generateDiffModel = (accountId, programName, currentVersion, previousVersion, failureCb) => { 31586 return async (dispatch, getState, services) => { 31587 dispatch(setSoftLoading(true)); 31588 try { 31589 const state = getState(); 31590 const currentSnapshot = StateReaderUtils.getSnapshotByNumber(state, programName, currentVersion); 31591 const previousSnapshot = StateReaderUtils.getSnapshotByNumber(state, programName, previousVersion); 31592 const loadSnapshotPromises = []; 31593 if (currentVersion !== "draft" && (!currentSnapshot || !currentSnapshot.assets)) loadSnapshotPromises.push(loadProjectSnapshotPromise(services, state, dispatch, accountId, programName, currentVersion)); 31594 if (!previousSnapshot || !previousSnapshot.assets) loadSnapshotPromises.push(loadProjectSnapshotPromise(services, state, dispatch, accountId, programName, previousVersion)); 31595 await Promise.all(loadSnapshotPromises); 31596 const loadDiffDataPromises = [dispatch(loadProjectWireframes(accountId, programName, currentVersion === "draft" ? void 0 : "diff", currentVersion === "draft" ? void 0 : currentVersion.toString(), false, false)), dispatch(loadProjectWireframes(accountId, programName, "diff", previousVersion.toString(), false, false))]; 31597 await Promise.all(loadDiffDataPromises); 31598 dispatch(generateDiffModelAction(programName, currentVersion, previousVersion)); 31599 } catch (err) { 31600 dispatch(reportError(err)); 31601 if (typeof failureCb === "function") failureCb(); 31602 } finally { 31603 dispatch(setSoftLoading(false)); 31604 } 31605 }; 31606}; 31607var toggleDiffModelById = (id) => { 31608 return (dispatch) => { 31609 dispatch(toggleDiffModelByIdAction(id)); 31610 }; 31611}; 31612var expandOrCollapseDiffModel = (expandAll) => { 31613 return (dispatch) => { 31614 dispatch(expandOrCollapseDiffModelAction(expandAll)); 31615 }; 31616}; 31617//#endregion 31618//#region client/logic/versionDiff/diffReducer.ts 31619var getDiffTable = (state, projectName, previousVersion, currentVersion) => { 31620 const previousWireFrames = StateReaderUtils.getDiffWireframes(state, projectName, previousVersion); 31621 const currentWireFrames = currentVersion === "draft" ? StateReaderUtils.getWireFrame(state, projectName, currentVersion) : StateReaderUtils.getDiffWireframes(state, projectName, currentVersion); 31622 if (!previousWireFrames) throw `Failed to find previous version (${previousVersion}) for diff ð`; 31623 if (!currentWireFrames) throw `Failed to find current version (${currentVersion}) for diff ð`; 31624 const previousContext = { 31625 state, 31626 projectName, 31627 stage: "diff", 31628 version: previousVersion 31629 }; 31630 const currentContext = { 31631 state, 31632 projectName, 31633 stage: currentVersion === "draft" ? "draft" : "diff", 31634 version: currentVersion === "draft" ? void 0 : currentVersion 31635 }; 31636 return new DiffManager([ 31637 new AnimationEntity(), 31638 new AnalyticsEntity(), 31639 new DataElementEntity(), 31640 new LogicEntity(), 31641 new ParameterEntity(), 31642 new PlaceholderEntity(), 31643 new ScenePartEntity(), 31644 new DataTableEntity(), 31645 new MediaEntity(), 31646 new StudioDataElementEntity(), 31647 new SceneEntity(), 31648 new StoryEntity(), 31649 new ProgramEntity(), 31650 new PrioritizedListEntity(), 31651 new GroupEntity(), 31652 new NarrationEntity(), 31653 new RecordingEntity() 31654 ]).init(currentContext, previousContext); 31655}; 31656var diffReducer = (state, action) => { 31657 switch (action.type) { 31658 case GENERATE_DIFF_MODEL: { 31659 const { programName, currentVersion, previousVersion } = action.payload; 31660 const diffModel = getDiffModel(getDiffTable(state, programName, previousVersion, currentVersion)); 31661 return { 31662 ...state, 31663 diffModel: { 31664 currentVersion, 31665 previousVersion, 31666 model: diffModel 31667 } 31668 }; 31669 } 31670 case CLEAR_DIFF_MODEL: return { 31671 ...state, 31672 diffModel: { 31673 currentVersion: void 0, 31674 previousVersion: void 0, 31675 model: void 0 31676 } 31677 }; 31678 case TOGGLE_DIFF_MODEL_BY_ID: { 31679 const id = action.payload; 31680 const updatedModel = toggleDiffModel({ 31681 diffModel: state.diffModel.model, 31682 id 31683 }); 31684 return { 31685 ...state, 31686 diffModel: { 31687 ...state.diffModel, 31688 model: updatedModel 31689 } 31690 }; 31691 } 31692 case EXPAND_OR_COLLAPSE_DIFF_MODEL: { 31693 const expandAll = action.payload; 31694 const updatedModel = toggleDiffModel({ 31695 diffModel: state.diffModel.model, 31696 expandAll 31697 }); 31698 return { 31699 ...state, 31700 diffModel: { 31701 ...state.diffModel, 31702 model: updatedModel 31703 } 31704 }; 31705 } 31706 default: return state; 31707 } 31708}; 31709var toggleDiffModel = ({ diffModel, id, expandAll }) => { 31710 let updatedModel = deepCloneObj(diffModel); 31711 let queue = [...updatedModel]; 31712 while (queue.length) { 31713 let currentEntity = queue.pop(); 31714 if (currentEntity) { 31715 if (typeof expandAll === "boolean") currentEntity.isOpen = expandAll; 31716 else if (currentEntity.id === id) { 31717 currentEntity.isOpen = !currentEntity.isOpen; 31718 break; 31719 } 31720 if (currentEntity.changes.length) queue = queue.concat(currentEntity.changes); 31721 } 31722 } 31723 return updatedModel; 31724}; 31725//#endregion 31726//#region client/logic/common/rootReducer.ts 31727var reducers = [ 31728 commonReducer, 31729 projectsReducer, 31730 adminReducer,
31731 assetsReducer, 31732 userReducer, 31733 previewReducer, 31734 projectLifeCycleReducer, 31735 featureFlagsReducer, 31736 wireFramesReducer, 31737 programOverviewReducer, 31738 accountOverviewReducer, 31739 dataElementReducer, 31740 projectNarrationsReducer, 31741 storyReducer, 31742 diffReducer, 31743 projectCombinedReducer, 31744 validationReducer 31745]; 31746function getInitialState() { 31747 return { 31748 studioProgramsDrawerFilter: DrawerFilters.AllButArchive, 31749 loadingCount: 0, 31750 activeAccountId: void 0, 31751 accounts: { 31752 byId: {}, 31753 allIds: [], 31754 isInitialized: false 31755 }, 31756 projects: { 31757 byName: {}, 31758 allNames: [], 31759 isInitialized: false 31760 }, 31761 assets: { 31762 byId: {}, 31763 allIds: [] 31764 }, 31765 snapshots: { 31766 byId: {}, 31767 allIds: [] 31768 }, 31769 dashboardAccountInfo: {}, 31770 dashboardScenes: { 31771 byId: {}, 31772 allIds: [] 31773 }, 31774 dashboardPrograms: { 31775 byId: {}, 31776 allIds: [] 31777 }, 31778 error: false, 31779 errorMessage: "", 31780 browserHistory: { 31781 activeId: 0, 31782 byLink: {}, 31783 allLinks: [] 31784 }, 31785 wireframes: { 31786 byName: {}, 31787 allNames: [] 31788 }, 31789 devwireframes: { 31790 byName: {}, 31791 allNames: [] 31792 }, 31793 uatwireframes: { 31794 byName: {}, 31795 allNames: [] 31796 }, 31797 prodwireframes: { 31798 byName: {}, 31799 allNames: [] 31800 }, 31801 versionwireframes: { 31802 byName: {}, 31803 allNames: [] 31804 }, 31805 diffwireframes: { 31806 byName: {}, 31807 allNames: [] 31808 }, 31809 diffModel: { 31810 currentVersion: void 0, 31811 previousVersion: void 0, 31812 model: void 0 31813 }, 31814 presets: { 31815 byName: {}, 31816 allNames: [] 31817 }, 31818 userName: "", 31819 users: { 31820 allNames: [], 31821 selectedUser: {} 31822 }, 31823 admin: { 31824 isLoadingUsers: false, 31825 isFetchingUser: false, 31826 isSettingFeatureFlag: false, 31827 isLoadingAllProjects: false, 31828 allProjects: [] 31829 }, 31830 projectSummaries: [], 31831 versions: [], 31832 renderErrorMessage: "", 31833 versionManager: {}, 31834 hubStickyBarLogoMenuItemsArray: [], 31835 enableHubStickyBarLogoMenu: false, 31836 validationData: new ValidationTable(), 31837 recordingDocs: [], 31838 creativeRecordingAssets: { 31839 byId: {}, 31840 allIds: [] 31841 } 31842 }; 31843} 31844function rootReduce(state, action) { 31845 if (state === void 0) return getInitialState(); 31846 return reducers.reduce((state, reducer) => reducer(state, action), state); 31847} 31848//#endregion 31849//#region client/components/store.ts 31850init_es(); 31851var import_redux_devtools_extension = require_redux_devtools_extension(); 31852var import_lib = /* @__PURE__ */ __toESM(require_lib$3()); 31853var store; 31854var getStore = () => { 31855 if (!store) store = createStore(rootReduce, (0, import_redux_devtools_extension.composeWithDevTools)(applyMiddleware(import_lib.default))); 31856 return store; 31857}; 31858var getReduxState = () => { 31859 return getStore().getState(); 31860}; 31861//#endregion 31862//#region client/components/services.ts 31863var services = /* @__PURE__ */ new Map(); 31864function getService(name) { 31865 return services.get(name); 31866} 31867function addService(name, service) { 31868 services.set(name, service); 31869} 31870//#endregion 31871//#region client/logic/common/logReportUtils.ts 31872var reportErrorToSplunk = (errorMessage, metadataObj) => { 31873 const data = getLogReportContent(errorMessage, metadataObj, ReportEventType.Error, getReduxState()); 31874 getService("commonServices").reportLog(data); 31875}; 31876var reportInfoToSplunkRedux = (message, data) => { 31877 const reportData = getLogReportContent(message, data, ReportEventType.Info, getReduxState()); 31878 getService("commonServices").reportLog(reportData); 31879}; 31880var reportInfoToSplunk = (message, data) => { 31881 const reportData = getLogReportContent(message, data, ReportEventType.Info); 31882 getService("commonServices").reportLog(reportData); 31883}; 31884var getLogReportContent = (message, reportData, eventType, state) => { 31885 const FS = window.FS; 31886 const fsUrl = FS && FS.getCurrentSessionURL ? FS.getCurrentSessionURL(true) : ""; 31887 const fsSession = FS && FS.getCurrentSession ? FS.getCurrentSession() : ""; 31888 const accountProgram = UrlUtils.getAccountAndProgramFromPath(); 31889 let programId = accountProgram?.program; 31890 let accountId; 31891 let accountName; 31892 if (state !== void 0) { 31893 accountId = accountProgram?.accountId; 31894 accountName = StateReaderUtils.getActiveAccount(state)?.displayName ?? ""; 31895 } else { 31896 accountId = activeAccountIdVar(); 31897 accountName = userDataVar()?.accounts.find((account) => account.accountId === accountId)?.name ?? ""; 31898 } 31899 const basicInfo = { 31900 accountId, 31901 accountName, 31902 projectName: programId, 31903 stage: getStageFromPathname(window?.location?.pathname), 31904 version: getVersionFromPathname(window?.location?.pathname), 31905 clientVersion: "8.0.25919", 31906 fsUrl, 31907 fsSession 31908 }; 31909 const metadata = { 31910 ...reportData, 31911 ...basicInfo 31912 };
31913 Object.keys(metadata).forEach((key) => { 31914 if (reportData && !reportData[key]) reportData[key] = ""; 31915 }); 31916 return { 31917 msg: message, 31918 metadata, 31919 eventType 31920 }; 31921}; 31922//#endregion 31923export { setNeutralNotification as $, updateUser as $a, MinContentEndTruncateAtSceneEnd as $c, localRecordingToolMenuAnchorVar as $d, previewPaths as $f, roles as $g, LOGIC_MEDIA_TYPES as $h, uploadToDtaasIfNeeded as $i, deleteProjectWireframesScenePart as $l, isUniquePlaceholderInSlot as $m, localEditorMediaLibraryGridColumns as $n, updateExistingAsset as $o, addPlaceholdersToGroup as $p, startGlobalPerformance as $r, getAvatarCropSetting as $s, initLocalStateForEditor as $t, getDefaultValueForSystemDataElement as $u, duplicateProgram as A, ValueSetController as Aa, listLanguages as Ac, setDrawerFilter as Ad, shouldShowAddProgramButton as Af, fileTypesWhitelist as Ag, TimeUtils as Ah, PlaceholderToolIntent as Ai, PlaceholderShowType as Al, getValidationReportOnObject as Am, localEditorDockedMediaLibraryFilterStockOrientation as An, SCENE_ID_FOR_SCENE_NOT_EXISTS as Ao, getDataElementStatus as Ap, localIsNewBrandVar as Ar, buildBulletSettings as As, gqlEditorProgramToEditorVideoItem as At, narrationUsedValueSetProviderChanged as Au, syncAnimations as B, shouldUseVideoRatioAndQualityLogic as Ba, resolveTextHorizontalAlignmentValue as Bc, activeAccountNameVar as Bd, frameworkLegacyPaths as Bf, wireFramesAssetType as Bg, LogicType as Bh, getBasedOnSnapshotNumber as Bi, VALUE_SETS_CHANGED as Bl, renamePlaceholderInGroup as Bm, localEditorInitialEmbedVideoPageConfigurationVar as Bn, sceneActionTypes as Bo, removeAssignedStory as Bp, isFeatureEnabled as Br, getBulletOrientationFromIntent as Bs, buildDynamicElement as Bt, unmergeNarrationPoints as Bu, getAndUpdateProjectApikeyEndpoint as C, describeDownloadFailure as Ca, getSoundSetting as Cc, pushHistory as Cd, getStageFromPathname as Cf, STATIC_DEFAULT_PROFILE_NAME as Cg, removeMasterFromScenes as Ch, LibraryOpener as Ci, GlobalSettingKey as Cl, getLhsMediaType as Cm, localEditorDocToVideoCreateSuccessSnackbarState as Cn, updateProjectStory as Co, findDataElementById as Cp, localEditorShowReplaceAvatarHint as Cr, HubDatePicker as Cs, VideosCoPilotDraftsSortingMethod as Ct, addNarrationDimension as Cu, switchAccount as D, callEndpointJson as Da, isPlaceholderOverrideLogo as Dc, reportUnhandledError as Dd, shouldShowAddBuilderProgramButton as Df, defaultNarratorId as Dg, sortByVersionString as Dh, MediaLibraryFilterMediaType as Di, NarratorLibrary as Dl, getRhsMediaType as Dm, localEditorDockedMediaLibraryFilterMediaSource as Dn, DPLogicContainerWarningTypes as Do, getDataElementDisplayName as Dp, localEditorUserNameVar as Dr, ANIMATOR_TEST_VSB_NAME as Ds, getUserName as Dt, deleteNarration as Du, setActiveAccountId as E, callEndpointConsuming as Ea, isPlaceholderHidden as Ec, reportEscapeClick as Ed, isFrameworkRoute as Ef, adsDataElements as Eg, sortByString as Eh, MediaLibraryFilterMediaSource as Ei, NarrationSettingsKey as El, getProgramValidationContent as Em, localEditorDockedMediaLibraryFilterMaxVideoDuration as En, updateStoryVideoRatioQualityLogic as Eo, getDataElementDescription as Ep, localEditorUploadedGettyUrlsVar as Er, getIdFromGqlId as Es, ellipsisInputSxProps as Et, createDataElementsFromDimensions as Eu, loadGraphQLProgram as F, createStoryLogic as Fa, resolveBackgroun
31923dColorValue as Fc, toggleMiddlePanelCollapse as Fd, buildersBasePath as Ff, sceneAssetType as Fg, BulkId as Fh, PendoService as Fi, TextSettingKey as Fl, isLogicValueHotspot as Fm, localEditorDockedMediaLibraryStockSortOrder as Fn, generateSceneNodeId as Fo, getDataElementUpdatedTime as Fp, updateAssetLibraryFontsManagerVar as Fr, buildTextHorizontalLinePaddingModeSetting as Fs, pathSxProps as Ft, setNarrationRepresentative as Fu, UploadFileContext as G, addUser as Ga, setDefaultTextHorizontalLinePaddingModeSetting as Gc, duplicateTemplateIdVar as Gd, getFrameworkPaths as Gf, TagNames as Gg, ASSET_TYPES as Gh, loadProjectLifecycleHistory as Gi, addProjectWireframesScenePartStoryboardFrame as Gl, addPlaceHolderToSlots as Gm, localEditorIsPreviewDialogOpenVar as Gn, extractUniqueNextDPPointsIdsFromDPLogic as Go, convertArrayOfObjectsToObjectWithKeys as Gp, getAccountEditorLevelNarratorData as Gr, isAnimatorTestAccount as Gs, isNameEmpty as Gt, updateNarrationStructureAndVariationData as Gu, updateProject as H, loadProgramsMigrationStatus as Ha, resolveTextVerticalAlignmentValue as Hc, assetMediaVar as Hd, getEditorPaths as Hf, DataElementContentTypes as Hg, buildActionableData as Hh, renderDateTimeColumn as Hi, addProjectWireframesPreset as Hl, valueCanBeFromValueSet as Hm, localEditorIsFloatingMediaLibraryVar as Hn, buildAndDecorateDecisionPointLogicValue as Ho, compareArrays as Hp, getAccountEditorLevelAvatarsData as Hr, getDuplicateName as Hs, getDefaultSourceFromStringElementName as Ht, updateNarrationFromCSVData as Hu, loadProjectDetails as I, QualityOptions as Ia, resolveBreathingValue as Ic, handleUnexpectedError as Id, creativePaths as If, storyAssetType as Ig, Order as Ih, EnhancedError as Ii, VerticalAlignment as Il, isPlaceholderOfType as Im, localEditorDraggedItemTypeVar as In, getMaxLongestRouteFromNodesMap as Io, getDataElementUsedInScene as Ip, updateCcFontManagerVar as Ir, createDownloadedVideoFileName as Is, renameFolder as It, setNarrationText as Iu, handleEditorError as J, getAllRoles as Ja, updateBulletFallbackIconIfNeeded as Jc, editHelpCenterOpenVar as Jd, getStoryBuilderPageUrl as Jf, ACCOUNT_LEVEL_ROLES as Jg, EXCLUDED_HOTSPOT_KEYS as Jh, revertToVersion as Ji, deleteCustomField as Jl, checkIfPrioritizedListSlotIsGroup as Jm, localEditorLandingPageConfigurationVar as Jn, createDataTable as Jo, isLogicEmpty as Jp, loadAccountEditorLevelFontsData as Jr, AVATAR_OBJECT_POSITION as Js, reloadPage as Jt, getRecordingAssetName as Ju, closeNotification as K, deleteUser as Ka, setLanguageValue as Kc, editHelpCenterDataVar as Kd, getFrameworkTab as Kf, UrlUtils as Kg, CURATED_ASSETS_MEDIA_TYPES as Kh, loadProjectSnapshot as Ki, changeActivePreset as Kl, calcPrioritizedListSize as Km, localEditorIsPreviewM2Layouts as Kn, clearUploadingList as Ko, removeDuplicatesFromArrayByPropName as Kp, getEditorAccountId as Kr, isEditorAccountLibraryProgram as Ks, isNameWithInvalidChars as Kt, createDtaasObj as Ku, loadProjectDetailsLegacy as L, RatioOptions as La, resolveColorValue as Lc, captureExceptionToSentry as Ld, dashboardPaths as Lf, studioApiVersionHeaderName as Lg, HubNotifications as Lh, getActiveStage as Li, getPlaceholderCreationGroup as Ll, isTransparentColor as Lm, localEditorEmbedVideoPageConfigurationVar as Ln, getSceneIdFromSceneNodeId as Lo, getDerivedDataElementLogicId as Lp, getApolloCacheSizesSnapshot as Lr, generateEditorProjectId as Ls, validateEditedFolderName as Lt, setShowMutedRows as Lu, getNewPrograms as M, ChangeType as Ma, overrideLanguageValue as Mc, setHubStickyBarLogoMenuItemsArray as Md, addBuilderTypeToUrl as Mf, onscreenTypes as Mg, designSystemReadableDateFormat as Mh, StudioElementOrigin as Mi, RichTextStyleSetting as Ml, hasRhs as Mm, localEditorDockedMediaLibrarySelectedItemData as Mn, StoryEditorContext as Mo, getDataElementTagKey as Mp, localRestrictedActionDialog as Mr, buildDurationSetting as Ms, menuPopoverPathSxProps as Mt, removeNarrationDimension as Mu, getProjectVersions as N, createAnalyticsData as Na, projectBulletIconSettings as Nc, setLoading as Nd, addVersionToUrl as Nf, parameterType as Ng, designSystemReadableTimeFormat as Nh, UploadOrigin as Ni, TextFit as Nl, isArrayOfCompoundValues as Nm, localEditorDockedMediaLibrarySortBy as Nn, calculateDisabledNodes as No, getDataElementTags as Np, localVideosToIgnoreUserIntentDialog as Nr, buildMediaSoundSetting as Ns, menuPopoverPathTextSxProps as Nt, setNarrationComment as Nu, addProject as O, callEndpointText as Oa, isPlaceholderValueNotEmpty as Oc, setBreadcrumbsArray as Od, shouldShowAddEditorProgramButton as Of, entityType as Og, shallowEqual as Oh, MediaLibrarySortBy as Oi, ORIGIN_LANGUAGE as Ol, getRhsValueSet as Om, localEditorDockedMediaLibraryFilterMediaType as On, REMOVE_SCENE_TOOLTIP_TEXT as Oo, getDataElementId as Op, localEditorVideoPlayerControlVar as Or, SYSTEM_ELEMENT_ORIGIN as Os, gqlAccountProgramFolderToVideoFolderItem as Ot, mergeNarrationVariations as Ou, getProjectVersionsForDuplicate as P, createSceneLogic as Pa, projectBulletTextSettings as Pc, setPageTitle as Pd, builderPaths as Pf, placeholderType as Pg, reportsPageDateFormat as Ph, UploadedGettyUrlTarget as Pi, TextHorizontalLinePaddingMode as Pl, isCompoundValue as Pm, localEditorDockedMediaLibrarySortDirection as Pn, generateEndNodeId as Po, getDataElementType as Pp, processedFilesSnackbarCompletedVar as Pr, buildOverrideLogoSetting as Ps, moveToFolder as Pt, setNarrationDefaultText as Pu, setInfoNotification as Q, setSuccessMessage as Qa, MinContentEndPlayToEndOfContentNonIcon as Qc, isBreadCrumbsVisibleVar as Qd, navigateToEditorPath as Qf, permissions as Qg, LOGIC_DATA_TYPES as Qh, updateProjectSnapshot as Qi, deleteProjectWireframesSceneInputLogic as Ql, getMaxSlotsForPrioritizedList as Qm, localEditorMediaLibraryDraggingFromFolderId as Qn, updateDataTable as Qo, VALIDATION_
31923SEVERITY_LABEL as Qp, endGlobalPerformance as Qr, getAdjustmentSetting as Qs, initLocalStateForDocumentToVideo as Qt, extractDataElementsFromLogic as Qu, loadProjectForDashboard as R, createNewStoryQualityRatioLogic as Ra, resolveFontSizeValue as Rc, accessDeniedVar as Rd, dashboardsPaths as Rf, studioClientVersionHeaderName as Rg, LogicContext as Rh, getActiveStages as Ri, CHANGING_PROJECT_WIREFRAMES_SCENE_PART_SUCCESS as Rl, isValidColor as Rm, localEditorFloatingMediaLibraryCurrentFolderId as Rn, getStoryIdToStoryName as Ro, hasTag as Rp, getApolloClient as Rr, getBulletIconSizeFractionRoundedDown as Rs, deleteFolder as Rt, setShowNoteColumn as Ru, getAccountVideoViews as S, appendQueryParam as Sa, getPrimaryPlaceholderText as Sc, onEscapeClick as Sd, getProgramNameFromPathname as Sf, NpsSurveyId as Sg, getSortByDisplayDateFunc as Sh, Libraries as Si, FontSizeUnit as Sl, getHotspotDefaultLogicObj as Sm, localEditorDisplayLanguage as Sn, updateDecisionPointLogicAndAddNewDecisionPointLogic as So, filterDataElementsArrayByType as Sp, localEditorShowPronunciationLibraryVar as Sr, HubDataElementPicker as Ss, VideosArchiveSortingMethod as St, addNarration as Su, logout as T, EndpointError as Ta, isPlaceholderContentNoRulesWithPersonalization as Tc, reportErrorRV as Td, isEditorRoute as Tf, X_SSKY_SERVER_TIMING_HEADER as Tg, sortByPropName as Th, MediaLibraryFilterMediaOrientation as Ti, MediaSettingKey as Tl, getNarrationPartInvalidCreativeOverrides as Tm, localEditorDockedMediaLibraryCurrentFolderId as Tn, updateStoryBackgroundAssetLogic as To, getDataElementAssignedToAllStories as Tp, localEditorUnresolvedCommentsCountVar as Tr, LogicPopupContainer_default as Ts, createVideoFolder as Tt, cancelRemoveNarrationDimension as Tu, updateProjectStorySelectionLogic as U, setFeatureFlag as Ua, seedBulletCaseIconsFromFallbackIfNeeded as Uc, deleteEditorVideoVar as Ud, getEditorUrl as Uf, DataElementOrigins as Ug, getValueFromActionableData as Uh, addProjectLifecycleStageSnapshot as Ui, addProjectWireframesScene as Ul, toggleTransparency as Um, localEditorIsInReviewVar as Un, buildDecisionPointLogicValue as Uo, convertArrayOfObjectsToObject as Up, getAccountEditorLevelBrandData as Ur, getDuplicateNameBySuffix as Us, getStringElementSource as Ut, updateNarrationFromLogic as Uu, updateArchiveProgram as V, loadFeatureFlags as Va, resolveTextHorizontalLinePaddingModeSettingValue as Vc, aiVideoGeneratedSnackbarVar as Vd, getAccountIdFromPath as Vf, CreativeDataElementContentTypes as Vg, ActionableDataPropType as Vh, getBasedOnSnapshotNumberForSnapshot as Vi, addCustomField as Vl, validationStatusToString as Vm, localEditorInitialLandingPageConfigurationVar as Vn, StoryManager as Vo, supportsTag as Vp, getUserData as Vr, getDefaultBulletIconSizeFraction as Vs, createSerializedDynamicElement as Vt, unmuteNarration as Vu, updateProjectThumbnail as W, setFeatureFlagStatusInState as Wa, setBulletIconSizeSetting as Wc, duplicateEditorVideoIdVar as Wd, getEditorUrlPartWithQueryParams as Wf, DataElementStatuses as Wg, ADAVarName as Wh, createVersion as Wi, addProjectWireframesScenePart as Wl, addNewPlaceholderLogicToList as Wm, localEditorIsLpChangingActiveState as Wn, createDecisionPointLogicValue as Wo, convertArrayOfObjectsToObjectWithDuplicates as Wp, getAccountEditorLevelMusicData as Wr, getTranscriptFormattedDate as Ws, getStringElementTarget as Wt, updateNarrationLibrary as Wu, notifyGeneralError as X, getUser as Xa, updateMediaFallbackIfNeeded as Xc, helpCenterDataVar as Xd, isSharedFrameworkViewerUser as Xf, deprecatedRoles as Xg, HOTSPOT_TYPES as Xh, setProjectLifecycleStageSnapshot as Xi, deleteProjectWireframesPreset as Xl, findPrioritizedListFromScenes as Xm, localEditorMediaDragAndDropSnackbarState as Xn, loadAsset as Xo, VALIDATION_ANIMATED_WIREFRAMES_COMPATIBILITY_LABEL as Xp, setEditorAccountDetails as Xr, calculateExplicitTextHorizontalLinePaddingMode as Xs, cCFontsManagerVar as Xt, buildDerivedDataElementsFromLogic as Xu, handleFileUploadError as Y, getAllUsers as Ya, updateBulletFallbackTextIfNeeded as Yc, featureFlagsVar as Yd, getUserHomePageUrl as Yf, USER_LEVEL_ROLES as Yg, HOTSPOT_DISPLAY_MAPP
31923ERS as Yh, setProjectBasedOnSnapshot as Yi, deleteMasterAnimationGuideline as Yl, deletePlaceholderFromPrioritizedList as Ym, localEditorLivePreviewPendingSetVar as Yn, deleteAsset as Yo, parseLogicObject as Yp, reportNumSelectedGetLinksItems as Yr, MediaSettingsMapping as Ys, assetLibraryFontsManagerVar as Yt, testSingleInputLogic as Yu, setErrorNotification as Z, reActivateUser as Za, MinContentEndPlayToEndOfContentIcon as Zc, helpCenterOpenVar as Zd, mainContainerPathByUserRoles as Zf, isPermitted as Zg, LOGIC_CONTEXT as Zh, setPromoteStatus as Zi, deleteProjectWireframesScene as Zl, findPrioritizedListNameFromId as Zm, localEditorMediaLibraryByAudienceCaseIndex as Zn, loadAssetContent as Zo, VALIDATION_PROGRAM_SETTINGS_LABEL as Zp, addNetworkActionPerformance as Zr, createPlaceholderDefaultContentAndSettings as Zs, initCcLibraryLocalStateForEditor as Zt, createDataFeed as Zu, getPresetDataElements as _, PrioritizedListEntity as _a, getMediaAlignmentSetting as _c, videoSizeExceededMsg as _d, DrawerFilters as _f, DEPRECATED_ELEVENLABS_NARRATOR_NAMES as _g, isAnEmptyObject as _h, AssetGenerationFlowTrigger as _i, BulletSettingKey as _l, generatePlaceholderLogicDataFromGroup as _m, localEditorCloudIndicatorVar as _n, removeSceneFromStoryWithNextDPHasNoRules as _o, changeName as _p, localEditorSelectedPlaceholderIdsVar as _r, LogicDataSelector as _s, UserOptionsViewType as _t, SnapshotSource as _u, addService as a, getNarrationValidationResult as aa, getDefaultFontSizeSetting as ac, createPrioritizedListCandidatesValueSetAdapter as ad, saveVideoAsTemplateIdVar as af, VALIDATION_STATUS as ag, HubEditorUtils as ah, updateEvpConfigurationWithCurrentSettings as ai, VLXPlaceholderActionInstructionsAnchorType as al, createHotspotLogicObject as am, localEditedBrandLogoAssetInfoVar as an, SuccessAction as ao, urlsToSupportForLegacyPrograms as ap, localEditorPreviewDialogTypeVar as ar, processCreativeRecordingAssets as as, upsertEditorUploadedGettyUrl as at, editProjectWireframesScene as au, savePreset as b, DataLibraryController as ba, getPlaceholderContentDynamicInfo as bc, clearError as bd, getBuildersProgramsToCombine as bf, M2_Logo_Aspect_Ratio_Value as bg, toSentenceCase as bh, DocToVideoSource as bi, DEFAULT_CONTENT as bl, getCreativeDataElementsUsedInNarrationsOverrides as bm, localEditorCueConnectFromPlaceholderIdVar as bn, replaceSceneWithNewScene as bo, convertDataElementToStudioData as bp, localEditorShowDropHintFromMediaLibrary as br, PopupFooter as bs, VideoCreationMethod as bt, AddOrRemove as bu, getStore as c, getPriorityListCandidateValidationResult as ca, getDefaultTextHorizontalAlignmentSetting as cc, AssetUtils as cd, updateTemplateDetailsIdVar as cf, ANALYTICS_DEMO_ACCOUNTS as cg, MediaTypes as ch, defaultButtonColorDofName as ci, AvatarSettingsKey as cl, createLogic$1 as cm, localEditedViewerProfileVar as cn, addExistingScene as co, ASSIGN_TO_ALL_STORIES_LABEL as cp, localEditorPublishStateVar as cr, deleteDataElements as cs, NotificationInfoText as ct, getProjectWireframesPresetsWithoutValues as cu, generateDiffModel as d, getStoryValidationResult as da, getDefaultTextVerticalAlignmentSetting as dc, csvMaxUploadSize as dd, StateReaderUtils as df, BUTTON_FILL_COLOR_NAME as dg, IssueCodes as dh, updateConfigurationWithCurrentSettings as di, BULLET_ICON_SIZE_FRACTION_BY_ORIENTATION as dl, excludeHotspotKeys as dm, localEditorAccountTypeVar as dn, addNewScene as do, addTag as dp, localEditorReviewPanelModeVar as dr, HubMappingTable as ds, ARCHIVE_FOLDER_NAME as dt, renameMasterAnimationGuideline as du, rolesPermissions as e_, waitForTaskToComplete as ea, getAvatarObjectViewBox as ec, extractScenesByType as ed, localRecordingToolPermissionsDeniedState as ef, LOGIC_TYPE as eg, renamePlaceholderInList as eh, TimedComponent as ei, brandConfigurationTextStyleToVideoSpecStyleProps as el, capitalizeFirstLetter as em, localAiMediaGenerationDialogInfo as en, userResetPassword as eo, removeVersionFromUrl as ep, localEditorNotificationDataVar as er, updateRecordingAssetStatus as es, setNoInternetNotification as et, deleteScenePartStoryboardFrame as eu, toggleDiffModelById as f, PlaceholderEntity as fa, getDurationSetting as fc, getImageMaxUploadFileSizeMB as fd, CREATIVES_PRESET_ID as ff, BUTTON_TEXT_COLOR_NAME as fg, IssueSeverity as fh, defaultPosterImageAssetNameList as fi, BULLET_ICON_TEXT_GAP_FACTOR as fl, extractPlaceholderNamesAndTypesFromWireframes as fm, localEditorActiveCueDialogVar as fn, addNewSceneBefore as fo, buildDataElement as fp, localEditorSceneAnimationCuesData as fr, HubSpinner as fs, ItemType as ft, setProjectWireframesSceneInputLogic as fu, getAnalytics as g, validateInputLogic as ga, getLogoOverrideSetting as gc, validateAssetFileSize as gd, STAGE_MODE as gf, DEFAULT_NARRATOR_NAME as gg, escapeRegExp as gh, AddSceneDialogActiveTab as gi, BulletOrientation as gl, findInCompoundValue as gm, localEditorBrandByAudienceIndicatorVar as gn, moveProjectWireframesSceneInStory as go, changeDescription as gp, localEditorSelectedNarrationPlaceholderOpenEditVar as gr, HubSemanticDropDown as gs, TEMPLATES_ROOT_NAME as gt, updateProjectMasterData as gu, createVideoSession as h, SceneAnimationEntity as ha, getLanguageValue as hc, imageSizeExceededMsg as hd, IGNORE_UPDATED as hf, CC_TEST_ACCOUNT_IDS as hg, escapeHTML as hh, constructWireframeThemeSupportKey as hi, BulletIconSize as hl, findHotspotValuesInRule as hm, localEditorAutoOpenReviewPanelVar as hn, mergeDecisionPoints as ho, changeContentType as hp, localEditorSelectedLibraryVar as hr, MappingTablesUtils as hs, NEW_YOUR_VIDEOS_ROOT_NAME as ht, updateCustomField as hu, reportInfoToSplunkRedux as i, getLogicValidationResult as ia, getDefaultColorSettingByKey as ic, PRIORITIZED_LIST_VALUE_SET_SOURCES as id, programAccessVar as if, TEXT_ELEMENTS as ig, calcGroupCoords as ih, getInitialEvpConfigurationInput as ii, VLXPlaceholderActionInstructionsAnchorMode as il, createHotspotInputArray as im, localEditedBrandIdVar as in, getPromptToVideoChatEndpoint as io, urlsToRedirectToHomePage as ip, localEditorPreviewDialogScenesVar as ir, uploadAssetTextContent as is, removeEditorUploadedGettyUrl as it, editProjectWireframesPreset as iu, generateRecordingDoc as j, getStoryPropertyCollectionId as ja, listPlaceholderL
31923anguages as jc, setForceLoad as jd, RouterPropType as jf, illegalFileFormatMsg as jg, designSystemReadableDateAndYearFormat as jh, PreviewDialogType as ji, PositionUnit as jl, getValueValidationForCompoundValue as jm, localEditorDockedMediaLibrarySearchValue as jn, SceneActionTypes as jo, getDataElementTagDisplayName as jp, localLivePreviewDisplayLanguage as jr, buildColorSetting as js, menuPopoverHeaderSxProps as jt, overrideWithCreative as ju, copyProgramBetweenAccounts as k, Status as ka, isRichTextContentChanged as kc, setDataLibrarySelectedTabId as kd, shouldShowAddFrameWorkProgramButton as kf, fileExtByMediaType as kg, DETAILED_REPORTS_DATE_FORMAT as kh, MediaLibrarySortDirection as ki, PlaceholderIntentName as kl, getSceneValidationContent as km, localEditorDockedMediaLibraryFilterMinVideoDuration as kn, RULE_KEY_FOR_DEFAULT_VALUE as ko, getDataElementOrigin as kp, localEditorWireframeThemeSupport as kr, buildBreathingSetting as ks, gqlBuilderProgramToBuilderVideoItem as kt, muteNarration as ku, clearDiffModelAction as l, getProgramValidationResult as la, getDefaultTextHorizontalLinePaddingModeSetting as lc, AcceptedFileTypes as ld, userDataVar as lf, APPS as lg, NarrationRecordingErrorReason as lh, defaultTextColorDofName as li, AvatarSource as ll, createLogicFromValueSet as lm, localEditorAccountIdVar as ln, addExistingSceneBefore as lo, DataElementTags as lp, localEditorPublishedUnresolvedCommentCountVar as lr, updateDataElement as ls, NotificationSuccessText as lt, loadProjectWireframes as lu, createShareUrl as m, SceneValidationEntity as ma, getHiddenSetting as mc, getVideoMaxUploadFileSizeMB as md, IGNORE_SERVER_ERRORS as mf, CC_STAGING_ACCOUNT_IDS as mg, convertMapToPlainObject as mh, getLocalIdFromGqlId as mi, BreathingType as ml, filterTransformTextPlaceholders as mm, localEditorAllCuesDialogVar as mn, duplicateProjectStory as mo, changeAssignedToAllStories as mp, localEditorSelectedFramePerSceneVar as mr, StylePreview as ms, MISSING_DATA_SOURCE_WARNING as mt, updateCustomAnalyticsOrder as mu, reportErrorToSplunk as n, getDataElementValidationResult as na, getDataElementsFromPlaceholderContent as nc, generatePrioritizedListCandidateNamesValueSetProviders as nd, localRecordingToolState as nf, LogicMediaTypeValues as ng, updatePrioritizedListWireFrames as nh, reportTimedActivity as ni, getCoordinatePixelValue as nl, convertLogicTypeToDataElementType as nm, localDeleteCandidateBrandIdVar as nn, SftpConnectionType as no, settingsPathsForOwnedMedia as np, localEditorPermissionsVar as nr, uploadAssetContent as ns, setWarningNotification as nt, duplicateProjectWireframesScenePart as nu, get
31923Service as o, getParameterValidationResult as oa, getDefaultTextBackgroundColorSetting as oc, createPrioritizedListValidSlotsValueSetAdapter as od, scrollToBottomVar as of, VALIDATION_TEXT as og, AssetTypes as oh, EMPTY_LP_CONFIGURATION as oi, Adjustment as ol, createInitialCompoundLogic as om, localEditedBrandTextStylesVar as on, Program as oo, SYSTEM_DATA_STORY_ID as op, localEditorProcessedFilesVar as or, addDataElement as os, upsertProcessedFile as ot, getProjectWireframesPresetValues as ou, createSecondVideoSession as p, LogicEntity as pa, getEmptyRichTextAtoms as pc, getMaxUploadFileSizeMbByType as pd, EDITING_MODE as pf, CC_LIBRARY_ID as pg, areAllObjectPropertiesEmpty as ph, getAspectRatio as pi, BULLET_TEXT_PART_NAME as pl, filterDataElementsByMediaType as pm, localEditorAddSceneDialogState as pn, deleteProjectStory as po, changeAssignedStories as pp, localEditorSelectedAudioPreview as pr, HubAddActionButton as ps, LibraryType as pt, setProjectWireframesScenePart as pu, getNotificationData as q, getAllProjects as qa, someAtomsRichTextFormattingApplied as qc, editHelpCenterEnabled as qd, getHomePageByUserRoles as qf, ReportEventType as qg, CYCLIC_ERROR_MESSAGE as qh, loadProjectSnapshotLegacy as qi, createMasterAnimationGuideline as ql, cascadePrioritizedListSlots as qm, localEditorIsSelectedSceneIsNewVar as qn, createAssetRequest as qo, createNewStorySelectionLogic as qp, loadAccountCcLibraryVersion as qr, AVATAR_OBJECT_FIT as qs, openContactSupportForm as qt, createExcelObj as qu, reportInfoToSplunk as r, getGroupValidationResult as ra, getDefaultColorSetting as rc, generateValueSetProviders as rd, mainContainerRefVar as rf, LogicTypeValues as rg, validatePrioritizedListNameFromScenes as rh, createInitialEvpConfiguration as ri, originalSceneName as rl, createEmptyCompoundValue as rm, localEditedBrandColorsVar as rn, VideoSessionRetention as ro, settingsPathsForPaidMedia as rp, localEditorPreSelectedLibrary as rr, uploadAssetJsonContent as rs, getProcessedFileIndex as rt, duplicateScene as ru, getReduxState as s, getPlaceholderValidationResult as sa, getDefaultTextFitSetting as sc, createDataElementValueSetAdapter as sd, templatesVar as sf, VLX_FUNCTION_TAGS as sg, EditorLibraryMediaType as sh, createInitialLpConfiguration as si, AvatarCropPreset as sl, createInitialPrioritizedListLogic as sm, localEditedButtonShapeValueVar as sn, featureFlagConst as so, NarrationsModelUtils as sp, localEditorProgramNameVar as sr, deleteDataElement as ss, NotificationErrorText as st, getProjectWireframesPresets as su, getLogReportContent as t, stringToRole as t_, filterIssues as ta, getBulletIconSizeSetting as tc, parseStringToRelevantMediaType as td, localRecordingToolSession as tf, LogicContextValues as tg, renamePlaceholderInListLogic as th, reportPageContentLoad as ti, cleanSceneName as tl, compareCompoundValues as tm, localBrandByAudienceFallbackIdVar as tn, PreviewContext as to, setProgramAndNavigationItemToUrl as tp, localEditorPendingApprovalActionVar as tr, uploadAsset as ts, setSuccessNotification as tt, duplicateNarration as tu, expandOrCollapseDiffModel as u, getSceneValidationResult as ua, getDefaultTextStyleSetting as uc, audioSizeExceededMsg as ud, videosAndFoldersVar as uf, BUTTON_BORDER_COLOR_NAME as ug, RecordingOrigin as uh, getInitialLpConfigurationInput as ui, BULLET_ICON_PART_NAME as ul, createLogicWithDerived as um, localEditorAccountNameVar as un, addNewProjectStory as uo, addAssignedStory as up, localEditorRaasPlaceholderData as ur, CELL as us, AI_VIDEO_DRAFTS_FOLDER_NAME as ut, moveNarrationPartUpOrDown as uu, getProgramDetails as v, ValidationUtils as va, getNarrationAlternativeVoiceSetting as vc, MAX_FILE_SIZE as vd, findProgramSummaryForProgramId as vf, EditorProjectIdsPrefix as vg, mapNumToLetter as vh, BooleanType as vi, ButtonShowContentItemElement as vl, getAssetTitleFromName as vm, localEditorCommentsPanelOpenVar as vn, removeSceneFromStoryWithPrevDPHasNoRules as vo, changeUseValueSet as vp, localEditorSelectedPlaceholderOpenEditVar as vr, IconWithTooltip as vs, VIDEO_PAGE_NAME as vt, convertStageTypeReverse as vu, loadUserData as w, withoutQuery as wa, isButtonPlaceholderContentNoRulesWithPersonalization as wc, reportError as wd, getVersionFromPathname as wf, X_SSKY_PAYLOAD_SIZE_HEADER as wg, sortByDisplayText as wh, MediaLibraryActiveTab as wi, HorizontalAlignment as wl, getMediaTypeByValue as wm, localEditorDockedMediaLibraryActiveTab as wn, updateSoundtrackLogic as wo, findDataElementByLogicValue as wp, localEditorSlidesToVideoBrandDisclaimers as wr, HubContentEditable as ws, YourVideosSortingMethod as wt, addOrRemoveCreative as wu, getAccountDashboardData as x, DownloadUtils as xa, getPrimaryPlaceholderMedia as xc, enableHubStickyBarLogoMenu as xd, getNumOfDashboardsPrograms as xf, MEDIA_OVERLAY_UNSUPPORTED_LAYOUT_NAME as xg, deepCloneObj as xh, EditorMediaDragAndDropSnackbarState as xi, DurationType as xl, getElementInfoFromActionableData as xm, localEditorDataConnectorEnabledVar as xn, updateDecisionPointLogic as xo, filterDataElementsArrayByOrigin as xp, localEditorShowPlaceholderLibrary as xr, SelectedItemSection as xs, VideoCreationMethodDisplayName as xt, acceptNarrationOrphansAndRemoved as xu, getSecondPresetDataElements as y, DataElementsTabContentController as ya, getNewCase as yc, RefineValidationErrorType as yd, getAccountIdFromPathname as yf, LogicContainers as yg, sortAlphaNum as yh, CloudIndicatorState as yi, CommonPlaceholderType as yl, getAvailableOperatorsForObject as ym, localEditorCopyPlaceholderSuccessVar as yn, replaceSceneWithExistingScene as yo, changeValueSet as yp, localEditorSelectedSceneIdVar as yr, DataSelectionArea as ys, VIDEO_TO_TEMPLATE_DISPLAY_NAME as yt, Stages as yu, loadProjectSummaries as z, createNewStoryQualityRatioValue as za, resolveTextFitValue as zc, activeAccountIdVar as zd, editorLegacyPaths as zf, urlPlaceHolderTypes as zg, LogicMediaType as zh, getActiveVersion as zi, UPDATING_PROJECT_WIREFRAMES_SCENE_INPUT_LOGIC_SUCCESS as zl, removePlaceHolderFromGroup as zm, localEditorFloatingMediaLibrarySelectedItemData as zn, isSceneRemovable as zo, isDataElementAssignedToStory as zp, initApolloClient as zr, getBulletIconSizeLetterForFraction as zs, SPECIAL_CHAR_VALIDATION as zt, setShowStatusColumn as zu }; 31924 31925//# sourceMappingURL=logReportUtils.CM1MPldf.js.map 31926//# debugId=f4b1ba88-5426-5f5a-8a3e-3a1944d220f7
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.