All files / modules/72-templates-library/components/TemplateStudio/TemplateContext TemplateContext.tsx

19.23% Statements 35/182
0% Branches 0/254
0% Functions 0/40
20.11% Lines 35/174

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703              45x 45x 45x 45x 45x 45x   45x 45x 45x   45x   45x 45x                 45x 45x 45x   45x 45x 45x   45x   45x     45x 45x 45x                             45x                                                           45x                                                                           45x                                                                                                                                                                                   45x                                                                                                                                                                                                                                             45x                                                                                                     45x             45x                                                                                                                                   45x                                                                                       45x                                                       45x                           45x         45x                                                                                                                                                                                                                                                                                                            
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React from 'react'
import merge from 'lodash-es/merge'
import { deleteDB, IDBPDatabase, openDB } from 'idb'
import { cloneDeep, defaultTo, isEqual, maxBy } from 'lodash-es'
import { VisualYamlSelectedView as SelectedView } from '@wings-software/uicore'
import { parse } from 'yaml'
import type { Color } from '@harness/design-system'
import SessionToken from 'framework/utils/SessionToken'
import { loggerFor } from 'framework/logging/logging'
import { ModuleName } from 'framework/types/ModuleName'
import type { GetPipelineQueryParams } from 'services/pipeline-ng'
import { useLocalStorage } from '@common/hooks'
import type { YamlBuilderHandlerBinding } from '@common/interfaces/YAMLBuilderProps'
import { TemplateListType } from '@templates-library/pages/TemplatesPage/TemplatesPageUtils'
import {
  EntityGitDetails,
  EntityValidityDetails,
  getTemplateListPromise,
  GetTemplateListQueryParams,
  GetTemplateQueryParams,
  NGTemplateInfoConfig,
  TemplateSummaryResponse
} from 'services/template-ng'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { usePermission } from '@rbac/hooks/usePermission'
import type { PermissionCheck } from 'services/rbac'
import { DefaultNewTemplateId, DefaultNewVersionLabel, DefaultTemplate } from 'framework/Templates/templates'
import { ActionReturnType, TemplateContextActions } from './TemplateActions'
import { initialState, TemplateReducer, TemplateReducerState, TemplateViewData } from './TemplateReducer'
 
const logger = loggerFor(ModuleName.CD)
 
const DBInitializationFailed = 'DB Creation retry exceeded.'
 
let IdbTemplate: IDBPDatabase | undefined
const IdbTemplateStoreName = 'template-cache'
export const TemplateDBName = 'template-db'
const KeyPath = 'identifier'
 
interface TemplatePayload {
  identifier: string
  template?: NGTemplateInfoConfig
  originalTemplate?: NGTemplateInfoConfig
  isUpdated: boolean
  versions?: string[]
  stableVersion?: string
  gitDetails?: EntityGitDetails
  entityValidityDetails?: EntityValidityDetails
  templateYaml?: string
  lastPublishedVersion?: string
}
 
const getId = (
  accountIdentifier: string,
  orgIdentifier: string,
  projectIdentifier: string,
  templateIdentifier: string,
  versionLabel: string,
  repoIdentifier = '',
  branch = ''
): string =>
  `${accountIdentifier}_${orgIdentifier}_${projectIdentifier}_${templateIdentifier}_${encodeURIComponent(
    versionLabel
  )}_${repoIdentifier}_${branch}`
 
export interface FetchTemplateBoundProps {
  dispatch: React.Dispatch<ActionReturnType>
  queryParams: GetTemplateQueryParams
  templateIdentifier: string
  versionLabel?: string
  gitDetails: EntityGitDetails
  templateType: string
}
 
export interface FetchTemplateUnboundProps {
  forceFetch?: boolean
  forceUpdate?: boolean
  signal?: AbortSignal
  repoIdentifier?: string
  branch?: string
}
 
const getTemplatesByIdentifier = (
  queryParams: GetTemplateListQueryParams,
  identifier: string,
  signal?: AbortSignal
): Promise<TemplateSummaryResponse[]> => {
  return getTemplateListPromise(
    {
      queryParams,
      body: {
        filterType: 'Template',
        templateIdentifiers: [identifier]
      }
    },
    signal
  )
    .then(response => {
      if (response.status === 'SUCCESS' && response.data?.content) {
        return response.data?.content
      }
      throw new Error()
    })
    .catch(error => {
      throw new Error(error)
    })
}
 
interface DispatchTemplateSuccessArgs {
  dispatch: React.Dispatch<ActionReturnType>
  data: TemplatePayload
  forceUpdate: boolean
  template: NGTemplateInfoConfig
  templateYamlStr: string
  versions: string[]
  templateWithGitDetails: TemplateSummaryResponse | undefined
  id: string
  stableVersion: string | undefined
  lastPublishedVersion: string | undefined
}
const dispatchTemplateSuccess = async (args: DispatchTemplateSuccessArgs): Promise<void> => {
  const {
    dispatch,
    data,
    forceUpdate,
    template,
    templateYamlStr,
    versions,
    templateWithGitDetails,
    id,
    stableVersion,
    lastPublishedVersion
  } = args
  if (data && !forceUpdate) {
    dispatch(
      TemplateContextActions.success({
        error: '',
        template: data.template,
        originalTemplate: cloneDeep(template),
        isBETemplateUpdated: !isEqual(template, data.originalTemplate),
        isUpdated: !isEqual(template, data.template),
        versions: versions,
        lastPublishedVersion,
        stableVersion: data.stableVersion,
        gitDetails: templateWithGitDetails?.gitDetails?.objectId
          ? templateWithGitDetails.gitDetails
          : defaultTo(data?.gitDetails, {}),
        entityValidityDetails: defaultTo(
          templateWithGitDetails?.entityValidityDetails,
          defaultTo(data?.entityValidityDetails, {})
        ),
        templateYaml: data?.templateYaml
      })
    )
    dispatch(TemplateContextActions.initialized())
  } else if (IdbTemplate) {
    const payload: TemplatePayload = {
      [KeyPath]: id,
      template: template,
      originalTemplate: cloneDeep(template),
      isUpdated: false,
      versions: versions,
      lastPublishedVersion,
      stableVersion: stableVersion,
      gitDetails: templateWithGitDetails?.gitDetails?.objectId
        ? templateWithGitDetails.gitDetails
        : defaultTo(data?.gitDetails, {}),
      entityValidityDetails: defaultTo(
        templateWithGitDetails?.entityValidityDetails,
        defaultTo(data?.entityValidityDetails, {})
      ),
      templateYaml: templateYamlStr
    }
    await IdbTemplate.put(IdbTemplateStoreName, payload)
    dispatch(
      TemplateContextActions.success({
        error: '',
        template: template,
        originalTemplate: cloneDeep(template),
        isBETemplateUpdated: false,
        isUpdated: false,
        versions: versions,
        lastPublishedVersion,
        stableVersion: stableVersion,
        gitDetails: payload.gitDetails,
        entityValidityDetails: payload.entityValidityDetails,
        templateYaml: payload.templateYaml
      })
    )
    dispatch(TemplateContextActions.initialized())
  } else {
    dispatch(
      TemplateContextActions.success({
        error: '',
        template: template,
        originalTemplate: cloneDeep(template),
        isBETemplateUpdated: false,
        isUpdated: false,
        versions: versions,
        lastPublishedVersion,
        stableVersion: stableVersion,
        gitDetails: templateWithGitDetails?.gitDetails?.objectId ? templateWithGitDetails.gitDetails : {},
        entityValidityDetails: defaultTo(templateWithGitDetails?.entityValidityDetails, {}),
        templateYaml: templateYamlStr
      })
    )
    dispatch(TemplateContextActions.initialized())
  }
}
 
const _fetchTemplate = async (props: FetchTemplateBoundProps, params: FetchTemplateUnboundProps): Promise<void> => {
  const { dispatch, queryParams, templateIdentifier, versionLabel = '', gitDetails, templateType } = props
  const { forceFetch = false, forceUpdate = false, signal, repoIdentifier, branch } = params
  let id = getId(
    queryParams.accountIdentifier,
    defaultTo(queryParams.orgIdentifier, ''),
    defaultTo(queryParams.projectIdentifier, ''),
    templateIdentifier,
    versionLabel,
    defaultTo(gitDetails.repoIdentifier, ''),
    defaultTo(gitDetails.branch, '')
  )
  if (IdbTemplate) {
    dispatch(TemplateContextActions.fetching())
    let data: TemplatePayload = await IdbTemplate.get(IdbTemplateStoreName, id)
    if ((!data || forceFetch) && templateIdentifier !== DefaultNewTemplateId) {
      try {
        const templatesList: TemplateSummaryResponse[] = await getTemplatesByIdentifier(
          {
            ...queryParams,
            templateListType: TemplateListType.All,
            ...(repoIdentifier && branch ? { repoIdentifier, branch } : {})
          },
          templateIdentifier,
          signal
        )
 
        const versions: string[] = templatesList.map(item => defaultTo(item.versionLabel, ''))
        const defaultVersion = defaultTo(templatesList.find(item => item.stableTemplate)?.versionLabel, '')
        const selectedVersion = versions.includes(versionLabel) ? versionLabel : defaultVersion
        const stableVersion = templatesList.find(item => item.stableTemplate)?.versionLabel
        const lastPublishedVersion = maxBy(templatesList, 'createdAt')?.versionLabel
        const templateWithGitDetails = templatesList.find(item => item.versionLabel === selectedVersion)
        id = getId(
          queryParams.accountIdentifier,
          defaultTo(queryParams.orgIdentifier, ''),
          defaultTo(queryParams.projectIdentifier, ''),
          templateIdentifier,
          versionLabel,
          defaultTo(gitDetails.repoIdentifier, templateWithGitDetails?.gitDetails?.repoIdentifier ?? ''),
          defaultTo(gitDetails.branch, templateWithGitDetails?.gitDetails?.branch ?? '')
        )
        data = await IdbTemplate.get(IdbTemplateStoreName, id)
        let template: NGTemplateInfoConfig
        const templateYamlStr = defaultTo(templateWithGitDetails?.yaml, '')
        try {
          template = defaultTo(parse(templateYamlStr)?.template, {})
        } catch (e) {
          // It is assumed that execution will come here, if there are only syntatical errors in yaml string
          template = {
            name: defaultTo(templateWithGitDetails?.name, ''),
            identifier: defaultTo(templateWithGitDetails?.identifier, ''),
            type: defaultTo(templateWithGitDetails?.childType, 'Step') as 'Step' | 'Stage',
            versionLabel: defaultTo(templateWithGitDetails?.versionLabel, ''),
            spec: {}
          }
        }
 
        dispatchTemplateSuccess({
          dispatch,
          data,
          forceUpdate,
          id,
          stableVersion,
          lastPublishedVersion,
          template,
          templateWithGitDetails,
          templateYamlStr,
          versions
        })
      } catch (_) {
        logger.info('Failed to fetch template list')
      }
    } else {
      dispatch(
        TemplateContextActions.success({
          error: '',
          template: defaultTo(data?.template, {
            ...DefaultTemplate,
            type: templateType as NGTemplateInfoConfig['type'],
            projectIdentifier: queryParams.projectIdentifier,
            orgIdentifier: queryParams.orgIdentifier
          }),
          originalTemplate: defaultTo(
            cloneDeep(data?.template),
            cloneDeep({
              ...DefaultTemplate,
              type: templateType as NGTemplateInfoConfig['type'],
              projectIdentifier: queryParams.projectIdentifier,
              orgIdentifier: queryParams.orgIdentifier
            })
          ),
          isUpdated: true,
          isBETemplateUpdated: false,
          versions: [DefaultNewVersionLabel],
          stableVersion: DefaultNewVersionLabel,
          gitDetails: defaultTo(data?.gitDetails, {}),
          entityValidityDetails: defaultTo(data?.entityValidityDetails, {}),
          templateYaml: defaultTo(data?.templateYaml, '')
        })
      )
      dispatch(TemplateContextActions.initialized())
    }
  } else {
    dispatch(TemplateContextActions.success({ error: 'DB is not initialized' }))
  }
}
 
interface UpdateTemplateArgs {
  dispatch: React.Dispatch<ActionReturnType>
  queryParams: GetTemplateQueryParams
  identifier: string
  versionLabel?: string
  originalTemplate: NGTemplateInfoConfig
  versions: string[]
  stableVersion: string
  gitDetails?: EntityGitDetails
}
 
const _updateTemplate = async (
  args: UpdateTemplateArgs,
  templateArg: NGTemplateInfoConfig | ((p: NGTemplateInfoConfig) => NGTemplateInfoConfig)
): Promise<void> => {
  const {
    dispatch,
    queryParams,
    identifier,
    versionLabel = '',
    originalTemplate,
    versions,
    stableVersion,
    gitDetails
  } = args
  const id = getId(
    queryParams.accountIdentifier,
    queryParams.orgIdentifier || '',
    queryParams.projectIdentifier || '',
    identifier,
    versionLabel,
    defaultTo(gitDetails?.repoIdentifier, ''),
    defaultTo(gitDetails?.branch, '')
  )
  if (IdbTemplate) {
    let template = templateArg
 
    if (typeof templateArg === 'function') {
      const dbTemplate = await IdbTemplate.get(IdbTemplateStoreName, id)
      if (dbTemplate?.template) {
        template = templateArg(dbTemplate.template)
      } else {
        template = {} as NGTemplateInfoConfig
      }
    }
    const isUpdated = !isEqual(originalTemplate, template)
    const payload: TemplatePayload = {
      [KeyPath]: id,
      template: template as NGTemplateInfoConfig,
      originalTemplate,
      versions,
      stableVersion,
      isUpdated,
      gitDetails
    }
    if (IdbTemplate) {
      await IdbTemplate.put(IdbTemplateStoreName, payload)
      dispatch(TemplateContextActions.success({ error: '', template: template as NGTemplateInfoConfig, isUpdated }))
    }
  }
}
 
const cleanUpDBRefs = (): void => {
  if (IdbTemplate) {
    IdbTemplate.close()
    IdbTemplate = undefined
  }
}
 
const _initializeDb = async (dispatch: React.Dispatch<ActionReturnType>, version: number, trial = 0): Promise<void> => {
  if (!IdbTemplate) {
    try {
      dispatch(TemplateContextActions.updating())
      IdbTemplate = await openDB(TemplateDBName, version, {
        upgrade(db) {
          try {
            db.deleteObjectStore(IdbTemplateStoreName)
          } catch (_) {
            // logger.error('There was no DB found')
            dispatch(TemplateContextActions.error({ error: 'There was no DB found' }))
          }
          const objectStore = db.createObjectStore(IdbTemplateStoreName, { keyPath: KeyPath, autoIncrement: false })
          objectStore.createIndex(KeyPath, KeyPath, { unique: true })
        },
        async blocked() {
          cleanUpDBRefs()
        },
        async blocking() {
          cleanUpDBRefs()
        }
      })
      dispatch(TemplateContextActions.dbInitialized())
    } catch (e) {
      logger.info('DB downgraded, deleting and re creating the DB')
 
      await deleteDB(TemplateDBName)
      IdbTemplate = undefined
 
      ++trial
 
      if (trial < 5) {
        await _initializeDb(dispatch, version, trial)
      } else {
        logger.error(DBInitializationFailed)
        dispatch(TemplateContextActions.error({ error: DBInitializationFailed }))
      }
    }
  } else {
    dispatch(TemplateContextActions.dbInitialized())
  }
}
 
export interface TemplateAttributes {
  type: string
  primaryColor: Color
  secondaryColor: Color
}
export interface TemplatesMap {
  [key: string]: TemplateAttributes
}
 
export interface TemplateContextInterface {
  state: TemplateReducerState
  view: string
  isReadonly: boolean
  setView: (view: SelectedView) => void
  fetchTemplate: (args: FetchTemplateUnboundProps) => Promise<void>
  setYamlHandler: (yamlHandler: YamlBuilderHandlerBinding) => void
  updateTemplate: (template: NGTemplateInfoConfig) => Promise<void>
  updateTemplateView: (data: TemplateViewData) => void
  deleteTemplateCache: (gitDetails?: EntityGitDetails) => Promise<void>
  setLoading: (loading: boolean) => void
  updateGitDetails: (gitDetails: EntityGitDetails) => Promise<void>
}
 
const _deleteTemplateCache = async (
  queryParams: GetTemplateQueryParams,
  identifier: string,
  versionLabel?: string,
  gitDetails?: EntityGitDetails
): Promise<void> => {
  if (IdbTemplate) {
    const id = getId(
      queryParams.accountIdentifier,
      queryParams.orgIdentifier || '',
      queryParams.projectIdentifier || '',
      identifier,
      versionLabel || '',
      defaultTo(gitDetails?.repoIdentifier, ''),
      defaultTo(gitDetails?.branch, '')
    )
    await IdbTemplate.delete(IdbTemplateStoreName, id)
  }
 
  // due to async operation, IdbPipeline may be undefined
  if (IdbTemplate) {
    const defaultId = getId(
      queryParams.accountIdentifier,
      queryParams.orgIdentifier || '',
      queryParams.projectIdentifier || '',
      DefaultNewTemplateId,
      DefaultNewVersionLabel,
      defaultTo(gitDetails?.repoIdentifier, ''),
      defaultTo(gitDetails?.branch, '')
    )
    await IdbTemplate.delete(IdbTemplateStoreName, defaultId)
  }
}
interface UpdateGitDetailsArgs {
  dispatch: React.Dispatch<ActionReturnType>
  queryParams: GetTemplateQueryParams
  identifier: string
  versionLabel?: string
  originalTemplate: NGTemplateInfoConfig
  template: NGTemplateInfoConfig
  versions: string[]
  stableVersion: string
}
 
const _updateGitDetails = async (args: UpdateGitDetailsArgs, gitDetails: EntityGitDetails): Promise<void> => {
  const { dispatch, queryParams, identifier, originalTemplate, template, versionLabel } = args
  await _deleteTemplateCache(queryParams, identifier, versionLabel, {})
 
  const id = getId(
    queryParams.accountIdentifier,
    defaultTo(queryParams.orgIdentifier, ''),
    defaultTo(queryParams.projectIdentifier, ''),
    identifier,
    defaultTo(versionLabel, ''),
    defaultTo(gitDetails.repoIdentifier, ''),
    defaultTo(gitDetails.branch, '')
  )
 
  const isUpdated = !isEqual(originalTemplate, template)
  if (IdbTemplate) {
    const payload: TemplatePayload = {
      [KeyPath]: id,
      template,
      originalTemplate,
      isUpdated,
      gitDetails
    }
    await IdbTemplate.put(IdbTemplateStoreName, payload)
  }
  dispatch(TemplateContextActions.success({ error: '', template, isUpdated, gitDetails }))
}
 
export const TemplateContext = React.createContext<TemplateContextInterface>({
  state: initialState,
  isReadonly: false,
  view: SelectedView.VISUAL,
  setView: () => void 0,
  fetchTemplate: () => new Promise<void>(() => undefined),
  updateTemplateView: () => undefined,
  setYamlHandler: () => undefined,
  updateTemplate: () => new Promise<void>(() => undefined),
  deleteTemplateCache: () => new Promise<void>(() => undefined),
  setLoading: () => void 0,
  updateGitDetails: () => new Promise<void>(() => undefined)
})
 
export const TemplateProvider: React.FC<{
  queryParams: GetPipelineQueryParams
  templateIdentifier: string
  versionLabel?: string
  templateType: string
}> = ({ queryParams, templateIdentifier, versionLabel, templateType, children }) => {
  const { repoIdentifier, branch } = queryParams
  const abortControllerRef = React.useRef<AbortController | null>(null)
  const isMounted = React.useRef(false)
  const [state, dispatch] = React.useReducer(
    TemplateReducer,
    merge(
      {
        template: {
          projectIdentifier: queryParams.projectIdentifier,
          orgIdentifier: queryParams.orgIdentifier
        },
        originalTemplate: {
          projectIdentifier: queryParams.projectIdentifier,
          orgIdentifier: queryParams.orgIdentifier
        }
      },
      initialState
    )
  )
  const [view, setView] = useLocalStorage<SelectedView>(
    'pipeline_studio_view',
    state.entityValidityDetails.valid === false ? SelectedView.YAML : SelectedView.VISUAL
  )
  state.templateIdentifier = templateIdentifier
  const fetchTemplate = _fetchTemplate.bind(null, {
    dispatch,
    queryParams,
    templateIdentifier,
    versionLabel,
    gitDetails: {
      repoIdentifier,
      branch
    },
    templateType
  })
 
  const updateTemplate = _updateTemplate.bind(null, {
    dispatch,
    queryParams,
    identifier: templateIdentifier,
    versionLabel: versionLabel,
    originalTemplate: state.originalTemplate,
    versions: state.versions,
    stableVersion: state.stableVersion,
    gitDetails: state.gitDetails
  })
 
  const updateGitDetails = _updateGitDetails.bind(null, {
    dispatch,
    queryParams,
    identifier: templateIdentifier,
    versionLabel: versionLabel,
    originalTemplate: state.originalTemplate,
    template: state.template,
    versions: state.versions,
    stableVersion: state.stableVersion
  })
 
  const setLoading = (isLoading: boolean) => {
    dispatch(TemplateContextActions.loading({ isLoading }))
  }
 
  const [isEdit] = usePermission(
    {
      resourceScope: {
        accountIdentifier: queryParams.accountIdentifier,
        orgIdentifier: queryParams.orgIdentifier,
        projectIdentifier: queryParams.projectIdentifier
      },
      resource: {
        resourceType: ResourceType.TEMPLATE,
        resourceIdentifier: templateIdentifier
      },
      permissions: [PermissionIdentifier.EDIT_TEMPLATE],
      options: {
        skipCache: true,
        skipCondition: (permissionCheck: PermissionCheck) => {
          return permissionCheck.resourceIdentifier === '-1'
        }
      }
    },
    [queryParams.accountIdentifier, queryParams.orgIdentifier, queryParams.projectIdentifier, templateIdentifier]
  )
 
  const isReadonly = !isEdit
  const deleteTemplateCache = _deleteTemplateCache.bind(
    null,
    queryParams,
    templateIdentifier,
    versionLabel,
    state.gitDetails
  )
  const setYamlHandler = React.useCallback((yamlHandler: YamlBuilderHandlerBinding) => {
    dispatch(TemplateContextActions.setYamlHandler({ yamlHandler }))
  }, [])
  const updateTemplateView = React.useCallback((data: TemplateViewData) => {
    dispatch(TemplateContextActions.updateTemplateView({ templateView: data }))
  }, [])
 
  React.useEffect(() => {
    fetchTemplate({ forceFetch: true, forceUpdate: true })
  }, [templateIdentifier, versionLabel, repoIdentifier, branch])
 
  React.useEffect(() => {
    if (state.isDBInitialized) {
      abortControllerRef.current = new AbortController()
 
      fetchTemplate({ forceFetch: true, signal: abortControllerRef.current?.signal })
    }
 
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort()
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [state.isDBInitialized])
 
  React.useEffect(() => {
    isMounted.current = true
    const time = SessionToken.getLastTokenSetTime()
    _initializeDb(dispatch, time || +new Date())
 
    return () => {
      isMounted.current = false
      cleanUpDBRefs()
    }
  }, [])
 
  return (
    <TemplateContext.Provider
      value={{
        state,
        view,
        setView,
        isReadonly,
        fetchTemplate,
        updateTemplate,
        updateTemplateView,
        deleteTemplateCache,
        setYamlHandler,
        setLoading,
        updateGitDetails
      }}
    >
      {children}
    </TemplateContext.Provider>
  )
}