'use strict';

const featureFlagController = require('./feature-flag-controller-9129ef52.js');
const tokenExtension = require('./token-extension-5fe2467b.js');
const splitCellOperation = require('./split-cell-operation-181cd474.js');
const globalSlimmerRegistry = require('./global-slimmer-registry-b3bce7e0.js');
const vegaDialogController = require('./vega-dialog-controller-03ef4d9a.js');
const typography = require('./typography-4560e7f1.js');
const iconManager = require('./icon-manager-c12c6ea9.js');
const internalTranslationController = require('./internal-translation-controller-8360a89c.js');
const validCreditCardNumberRule = require('./valid-credit-card-number-rule-2d7d20ce.js');
const vegaEnvManager = require('./vega-env-manager-23b8b23c.js');
const staticSubjectTitle = require('./static-subject-title-5829a298.js');
const changeManager = require('./change-manager-a297e4d2.js');
const observer = require('./observer-f49483e8.js');
const index = require('./index-58ea899e.js');
const contentState = require('./content-state-254ff7c7.js');
const vegaNonceManager = require('./vega-nonce-manager-df69d3ed.js');
const codeBlock = require('./code-block-f54099d9.js');

var __decorate$2 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * The `VegaWatchMethodCancelSlimmer` class is a TypeScript class that removes
 * the body of watch methods when a component is not fully instantiated and
 * applies the original method body when the component is fully instantiated.
 */
class VegaWatchMethodCancelSlimmer extends globalSlimmerRegistry.VegaSlimmer {
  /**
   * The constructor function takes a component object as a parameter and assigns it to the "component"
   * property of the class.
   *
   * @param {GlobalSlimmerConfig} option - The `option` parameter is of type `GlobalSlimmerConfig`.
   * It is an object that represents a component in a software system.
   */
  constructor(option) {
    super();
    this.originalWatchers = new Map();
    /**
     * while component reattached, the component will call `connectedCallback` but not call `componentDidLoad`,
     * so we add this flag to skip empty the watch function in this case.
     */
    this.hasDisconnected = false;
    this.isEnabled = featureFlagController.FeatureFlag.isEnabled('VEGA_REACT.PREVENT_CALL_WATCH_METHOD_BEFORE_COMPONENT_LOAD') &&
      featureFlagController.FeatureFlag.isEnabled('VEGA_FRAMEWORK.PREVENT_CALL_WATCH_METHOD_BEFORE_COMPONENT_LOAD');
    this.component = option.component;
  }
  /**
   * The connectedCallback function removes the body of watch methods when the component is not fully
   * instantiated.
   */
  connectedCallback() {
    if (!this.isEnabled)
      return;
    if (this.hasDisconnected)
      return;
    const watchers = this.component.constructor['watchers'];
    for (const propName in watchers) {
      const watchMethodNames = watchers[propName];
      watchMethodNames.forEach((methodName) => {
        // while watch method listen by multiple property, we should skip make originalMethod as empty.
        if (!this.originalWatchers.has(methodName)) {
          const originalMethod = this.component[methodName];
          this.originalWatchers.set(methodName, originalMethod);
          /**
           * Remove the watch method body when the component not fully instantiated.
           */
          // eslint-disable-next-line @typescript-eslint/no-empty-function
          this.component[methodName] = function () { };
        }
      });
    }
  }
  /**
   * The `@MapToComponentMethod('disconnectedCallback')` decorator is used to map the `disconnectedCallback` method
   * to the corresponding method in the Stencil component.
   */
  disconnectedCallback() {
    if (!this.isEnabled)
      return;
    this.hasDisconnected = true;
  }
  /**
   * The `componentDidLoad` function applies the original method body to the component's watchers when
   * the component is fully instantiated.
   */
  componentDidLoad() {
    if (!this.isEnabled)
      return;
    this.originalWatchers.forEach((method, methodName) => {
      const originalMethodBody = method;
      /**
       * Apply the watch original method body when the component fully instantiated.
       *
       * @param {...any} args - watch method args
       * @returns {unknown} method results
       */
      this.component[methodName] = function (...args) {
        return originalMethodBody.apply(this, args);
      };
    });
  }
}
__decorate$2([
  globalSlimmerRegistry.MapToComponentMethod('connectedCallback')
], VegaWatchMethodCancelSlimmer.prototype, "connectedCallback", null);
__decorate$2([
  globalSlimmerRegistry.MapToComponentMethod('disconnectedCallback')
], VegaWatchMethodCancelSlimmer.prototype, "disconnectedCallback", null);
__decorate$2([
  globalSlimmerRegistry.MapToComponentMethod('componentDidLoad')
], VegaWatchMethodCancelSlimmer.prototype, "componentDidLoad", null);

var __decorate$1 = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Class responsible for observing translation updates and triggering re-renders.
 */
class VegaTranslateObserverSlimmer extends globalSlimmerRegistry.VegaSlimmer {
  constructor(option) {
    super();
    this.component = option.component;
  }
  /**
   * Component lifecycle - [connectedCallback]
   * Registers an observer to watch for translation updates, which triggers a forced update on the component.
   */
  connectedCallback() {
    this.observer = new observer.Observer(this.isAcceptable.bind(this), () => {
      index.forceUpdate(this.component);
    });
    changeManager.ChangeManager.register(staticSubjectTitle.UPDATE_TRANSLATION, this.observer);
  }
  /**
   * Component lifecycle - [disconnectedCallback]
   * Unregister the observer when the component is disconnected from the DOM.
   */
  disconnectedCallback() {
    if (this.observer) {
      changeManager.ChangeManager.unregister(staticSubjectTitle.UPDATE_TRANSLATION, this.observer);
      this.observer = null;
    }
  }
  /**
   * Determines whether the observer should accept changes.
   *
   * @returns {boolean} Always returns true in the current implementation.
   */
  isAcceptable() {
    var _a, _b;
    const host = this.component['host'];
    return (_b = (_a = internalTranslationController.VegaInternalTranslation.getConnectedComponents().get(host.tagName)) === null || _a === void 0 ? void 0 : _a.has(host)) !== null && _b !== void 0 ? _b : false;
  }
}
__decorate$1([
  globalSlimmerRegistry.MapToComponentMethod('connectedCallback')
], VegaTranslateObserverSlimmer.prototype, "connectedCallback", null);
__decorate$1([
  globalSlimmerRegistry.MapToComponentMethod('disconnectedCallback')
], VegaTranslateObserverSlimmer.prototype, "disconnectedCallback", null);

var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Class responsible for injecting nonce into inline style attributes for vega components.
 */
class VegaNonceInjectorSlimmer extends globalSlimmerRegistry.VegaSlimmer {
  constructor(option) {
    super();
    this.component = option.component;
  }
  /**
   * Component lifecycle - [connectedCallback]
   * Registers an observer to watch for translation updates, which triggers a forced update on the component.
   */
  /**
   * Lifecycle callback that is invoked when the custom element is added to the DOM.
   *
   * This implementation overrides the `insertBefore` method of the element's shadow root
   * to automatically set the `nonce` attribute on any inline `<style>` elements that are inserted.
   * This is typically used to support Content Security Policy (CSP) by ensuring that dynamically
   * injected styles have the correct nonce value.
   */
  connectedCallback() {
    const shadowRoot = this.component['host'].shadowRoot;
    // override element#insertBefore to set nonce attribute for inline style element
    const originalInsertBefore = shadowRoot.insertBefore;
    /**
     * Overrides the shadowRoot's insertBefore method to inject a CSP nonce into any STYLE element being inserted.
     *
     * @template T - The type of Node being inserted.
     * @param {T} newElement - The new node to insert.
     * @param {Node | null} referenceElement - The node before which newElement is inserted, or null to insert at the end.
     * @returns {T} The inserted node.
     */
    shadowRoot.insertBefore = function (newElement, referenceElement) {
      if (newElement.nodeName === 'STYLE') {
        const nonce = vegaNonceManager.vegaNonceManager.nonce;
        if (nonce !== undefined) {
          newElement.setAttribute('nonce', nonce);
        }
      }
      return originalInsertBefore.call(this, newElement, referenceElement);
    };
  }
}
__decorate([
  globalSlimmerRegistry.MapToComponentMethod('connectedCallback')
], VegaNonceInjectorSlimmer.prototype, "connectedCallback", null);

/**
 * Default export function that will be used by stencil global script,
 * which will be invoked before library loaded.
 */
function appGlobalScript () {
  disableFeatureFlagFromClientGlobal();
  enableFeatureFlagFromClientGlobal();
  injectVegaLoaderIntoGlobal();
  injectVegaNotifyIntoGlobal();
  injectVegaThemeManagerIntoGlobal();
  injectVegaLogLevelIntoGlobal();
  injectVegaDialogIntoGlobal();
  registerGlobalVegaSlimmers();
  injectSetEventSemanticsIntoGlobal();
  injectVegaTypography();
  injectVegaIconManager();
  injectVegaZIndexManagerIntoGlobal();
  injectValidCreditCardNumberRuleIntoGlobal();
  initRuntimeMetricsTelemetryCollection();
  injectWaitForVegaIntoGlobal();
  injectVegaSkeletonLoaderIntoGlobal();
  injectVegaTranslationIntoGlobal();
  injectVegaRichTextEditorClassIntoGlobal();
  injectVegaPublicValidationRules();
  applyBrandingFromClientGlobal();
  injectSetNonceIntoGlobal();
  patchHeadInsertBeforeWithNonce();
}
/**
 * Disable feature flags from the client global defined lists.
 */
function disableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaDisabledFeatureKeys']) {
    featureFlagController.FeatureFlag.disable(...globalThis['VegaDisabledFeatureKeys']);
  }
}
/**
 * This function enables feature flags based on a global variable in TypeScript.
 */
function enableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaEnabledFeatureKeys']) {
    featureFlagController.FeatureFlag.enable(...globalThis['VegaEnabledFeatureKeys']);
  }
}
/**
 * Inject VegaLoader to global as a public api
 */
function injectVegaLoaderIntoGlobal() {
  globalThis['VegaLoader'] = tokenExtension.VegaLoader;
}
/**
 * Inject VegaNotify to global as a public api
 */
function injectVegaNotifyIntoGlobal() {
  globalThis.VegaNotify = tokenExtension.VegaNotify;
}
/**
 * Inject VegaThemeManager to global as a public api
 */
function injectVegaThemeManagerIntoGlobal() {
  globalThis.VegaThemeManager = splitCellOperation.VegaThemeManager;
}
/**
 * Inject VegaLogLevel to global as a public api
 */
function injectVegaLogLevelIntoGlobal() {
  globalThis.setVegaLogLevel = globalSlimmerRegistry.setVegaLogLevel;
}
/**
 * Inject VegaDialog to global as a public api
 */
function injectVegaDialogIntoGlobal() {
  globalThis.VegaDialog = vegaDialogController.VegaDialog;
}
/**
 * register global vega slimmers
 */
function registerGlobalVegaSlimmers() {
  globalSlimmerRegistry.GlobalSlimmersRegistry.register([
    VegaWatchMethodCancelSlimmer,
    VegaTranslateObserverSlimmer,
    VegaNonceInjectorSlimmer,
  ]);
}
/**
 * Inject setEventSemantics to global as a public api
 */
function injectSetEventSemanticsIntoGlobal() {
  globalThis.VegaEventManager = tokenExtension.VegaEventManager;
}
/**
 * Inject Vega typography stylesheet
 */
function injectVegaTypography() {
  Object.keys(typography.TypographyUrls).forEach((key) => {
    const { url } = typography.TypographyUrls[key];
    const typographyLinkId = `vega-typography-${key}`;
    // eslint-disable-next-line no-restricted-globals
    if (!document.querySelector(`#${typographyLinkId}`)) {
      // eslint-disable-next-line no-restricted-globals
      const typographyLink = document.createElement('link');
      typographyLink.id = typographyLinkId;
      typographyLink.href = url;
      typographyLink.rel = 'stylesheet';
      // eslint-disable-next-line no-restricted-globals
      document.head.append(typographyLink);
    }
  });
}
/**
 * Inject VegaIconManager to global as a public api
 */
function injectVegaIconManager() {
  globalThis.VegaIconManager = iconManager.VegaIconManager;
}
/**
 * Inject VegaZIndexManager to global as a public api
 */
function injectVegaZIndexManagerIntoGlobal() {
  globalThis.VegaZIndexManager = tokenExtension.VegaZIndexManager;
}
/**
 * Inject ValidCreditCardNumberRule to global as a public api.
 */
function injectValidCreditCardNumberRuleIntoGlobal() {
  globalThis.ValidCreditCardNumberRule = validCreditCardNumberRule.ValidCreditCardNumberRule;
}
/**
 * init telemetry runtime metrics.
 * 1. Inject VegaEnvInfo to global
 * 2. Register runtime metrics add page hide listener method
 */
function initRuntimeMetricsTelemetryCollection() {
  globalThis.VegaEnvInfo = vegaEnvManager.vegaEnvManager.getVegaEnv();
  // eslint-disable-next-line spellcheck/spell-checker
  void Promise.resolve().then(function () { return require('./index-f054eb5d.js'); }).then((
  // eslint-disable-next-line spellcheck/spell-checker
  module) => {
    module['default']['init'](featureFlagController.FeatureFlag);
  });
}
/**
 * Inject waitForVega to global as a public api
 */
function injectWaitForVegaIntoGlobal() {
  globalThis['waitForVega'] = tokenExtension.waitForVega;
}
/**
 * Inject VegaSkeletonLoader to global as a public api
 */
function injectVegaSkeletonLoaderIntoGlobal() {
  globalThis.VegaSkeletonLoader = tokenExtension.VegaSkeletonLoader;
}
/**
 * Inject VegaTranslation to global as a public api
 */
function injectVegaTranslationIntoGlobal() {
  globalThis.VegaTranslation = tokenExtension.VegaTranslation;
  globalThis.VegaTranslationResourceEN = internalTranslationController.staticTranslations;
}
/**
 * Inject VegaRTEContent to global as a public api
 * Inject VegaRTETokenExtension to global as a public api
 * Inject VegaRTELanguageExtension to global as a public api
 * Inject VegaRTEPresetToolbarItems to global as a variable
 */
function injectVegaRichTextEditorClassIntoGlobal() {
  globalThis.VegaRTEContent = contentState.VegaRTEContent;
  globalThis.VegaRTETokenExtension = tokenExtension.VegaRTETokenExtension;
  globalThis.VegaRTELanguageExtension = tokenExtension.VegaRTELanguageExtension;
  globalThis.VegaRTEPresetToolbarItems = codeBlock.VegaRTEPresetToolbarItems;
  globalThis.VegaRTEFunctionExtension = tokenExtension.VegaRTEFunctionExtension;
  globalThis.VegaRTETableExtension = tokenExtension.VegaRTETableExtension;
}
/**
 * Inject VegaPublicValidationRules to global as a public api
 */
function injectVegaPublicValidationRules() {
  void Promise.resolve().then(function () { return require('./public-rules-52e34985.js'); }).then((module) => {
    Object.entries(module).forEach(([name, value]) => {
      globalThis[name] = value;
    });
  });
}
/**
 * Switch the Vega theme to a new brand theme from the client global defined options.
 */
function applyBrandingFromClientGlobal() {
  if (globalThis['VegaThemeManagerApplyBranding']) {
    splitCellOperation.VegaThemeManager.applyBranding(globalThis['VegaThemeManagerApplyBranding']);
  }
}
/**
 * Injects the `setVegaNonce` function into the global scope as `setVegaNonce`.
 */
function injectSetNonceIntoGlobal() {
  globalThis.setVegaNonce = vegaNonceManager.setVegaNonce;
}
/**
 * Patch document.head.insertBefore to ensure nonce is set on injected elements.
 */
function patchHeadInsertBeforeWithNonce() {
  vegaNonceManager.vegaNonceManager.patchHeadInsertBeforeWithNonceToStencil();
}

const globalScripts = appGlobalScript;

exports.globalScripts = globalScripts;
