import { FeatureFlag } from './feature-flag-controller-b7e7da75.js';
import { M as MapToComponentMethod, V as VegaSlimmer, G as GlobalSlimmersRegistry } from './global-slimmer-registry-0a7aa308.js';
import { T as TypographyUrls } from './typography-396de03f.js';
import { U as UPDATE_TRANSLATION } from './static-subject-title-52f93124.js';
import { C as ChangeManager } from './change-manager-ecbd3a2a.js';
import { O as Observer } from './observer-3959f9dd.js';
import { f as forceUpdate } from './index-090d31ca.js';
import { V as VegaInternalTranslation } from './internal-translation-controller-0776fa78.js';
import { v as vegaEnvManager } from './vega-env-manager-8f8dc473.js';
import { vegaNonceManager } from './vega-nonce-manager-209a4c0a.js';
import { VegaThemeManager } from './theme-manager-a0e7283e.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 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 = FeatureFlag.isEnabled('VEGA_REACT.PREVENT_CALL_WATCH_METHOD_BEFORE_COMPONENT_LOAD') &&
      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([
  MapToComponentMethod('connectedCallback')
], VegaWatchMethodCancelSlimmer.prototype, "connectedCallback", null);
__decorate$2([
  MapToComponentMethod('disconnectedCallback')
], VegaWatchMethodCancelSlimmer.prototype, "disconnectedCallback", null);
__decorate$2([
  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 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(this.isAcceptable.bind(this), () => {
      forceUpdate(this.component);
    });
    ChangeManager.register(UPDATE_TRANSLATION, this.observer);
  }
  /**
   * Component lifecycle - [disconnectedCallback]
   * Unregister the observer when the component is disconnected from the DOM.
   */
  disconnectedCallback() {
    if (this.observer) {
      ChangeManager.unregister(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 = VegaInternalTranslation.getConnectedComponents().get(host.tagName)) === null || _a === void 0 ? void 0 : _a.has(host)) !== null && _b !== void 0 ? _b : false;
  }
}
__decorate$1([
  MapToComponentMethod('connectedCallback')
], VegaTranslateObserverSlimmer.prototype, "connectedCallback", null);
__decorate$1([
  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 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.nonce;
        if (nonce !== undefined) {
          newElement.setAttribute('nonce', nonce);
        }
      }
      return originalInsertBefore.call(this, newElement, referenceElement);
    };
  }
}
__decorate([
  MapToComponentMethod('connectedCallback')
], VegaNonceInjectorSlimmer.prototype, "connectedCallback", null);

/* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/typedef, jsdoc/require-jsdoc, jsdoc/require-param-type, jsdoc/require-returns-type, jsdoc/require-returns, jsdoc/tag-lines, spellcheck/spell-checker */
/**
 * VegaModuleLoader provides a lazy loading mechanism for Vega's public API modules.
 *
 * Instead of eagerly injecting all modules into `globalThis` at startup (as `vega.esm.js`
 * does for backward compatibility), consumers can use the lean entry (`vega-lean.esm.js`)
 * which registers only `VegaModuleLoader` on `globalThis`, then load modules on demand:
 *
 * ```js
 * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
 * ```
 *
 * This results in significantly smaller initial bundle sizes for vanilla JS consumers
 * who only need a subset of Vega's public API modules.
 *
 * VegaModuleLoader is available in ALL entry points (full browser, lean browser,
 * and framework loaders), so it can be used alongside eager injection too.
 *
 * ⚠ AUTO-GENERATED — do not edit manually.
 *   Source of truth: src/global/scripts/vanilla-js-global-setup.ts
 *   Generator:       scripts/generate-vega-module-loader.js
 *   Re-generate:     yarn generate:module-loader
 */
/**
 * Registry mapping module names to their dynamic import factories.
 * Each factory returns a Promise that resolves to the module's exported value.
 * The dynamic `import()` calls enable Rollup code-splitting — modules are
 * only loaded when `VegaModuleLoader.load()` is called.
 */
const MODULE_REGISTRY = {
  VegaLoader: () => import('./vega-loader-controller-7762f777.js').then(m => m.VegaLoader),
  VegaNotify: () => import('./vega-notify-controller-fc42330a.js').then(m => m.VegaNotify),
  VegaThemeManager: () => import('./theme-manager-a0e7283e.js').then(m => m.VegaThemeManager),
  setVegaLogLevel: () => import('./global-slimmer-registry-0a7aa308.js').then(function (n) { return n.l; }).then(m => m.setVegaLogLevel),
  VegaDialog: () => import('./vega-dialog-controller-6e0d9dd2.js').then(m => m.VegaDialog),
  VegaEventManager: () => import('./vega-event-manager-b6bec2a6.js').then(m => m.default),
  VegaIconManager: () => import('./icon-manager-e586cf50.js').then(m => m.VegaIconManager),
  VegaZIndexManager: () => import('./vega-z-index-manager-6b9cd9c5.js').then(m => m.default),
  ValidCreditCardNumberRule: () => import('./valid-credit-card-number-rule-077ca831.js').then(m => m.ValidCreditCardNumberRule),
  waitForVega: () => import('./wait-for-vega-handler-06f9caa2.js').then(m => m.waitForVega),
  VegaSkeletonLoader: () => import('./vega-skeleton-loader-controller-e538117d.js').then(m => m.VegaSkeletonLoader),
  VegaTranslation: () => import('./translation-f1ee0efc.js').then(m => m.VegaTranslation),
  VegaTranslationResourceEN: () => import('./internal-translation-controller-0776fa78.js').then(function (n) { return n.e; }).then(m => m.default),
  VegaRTEContent: () => import('./content-state-cc491c0b.js').then(function (n) { return n.j; }).then(m => m.VegaRTEContent),
  VegaRTETokenExtension: () => import('./token-extension-8ec3c047.js').then(function (n) { return n.t; }).then(m => m.VegaRTETokenExtension),
  VegaRTELanguageExtension: () => import('./language-extension-0d2c7cbc.js').then(function (n) { return n.l; }).then(m => m.VegaRTELanguageExtension),
  VegaRTEPresetToolbarItems: () => import('./constant-d3f8d036.js').then(m => m.VegaRTEPresetToolbarItems),
  VegaRTEFunctionExtension: () => import('./function-extension-496aca45.js').then(m => m.VegaRTEFunctionExtension),
  VegaRTETableExtension: () => import('./table-extension-8010b08c.js').then(m => m.VegaRTETableExtension),
  setVegaNonce: () => import('./vega-nonce-manager-209a4c0a.js').then(m => m.setVegaNonce),
  VegaValidationRules: () => import('./public-rules-c47b6240.js'),
  FeatureFlag: () => import('./feature-flag-controller-b7e7da75.js').then(m => m.FeatureFlag),
};
const moduleCache = new Map();
const VegaModuleLoader = {
  /**
   * Lazily load a Vega module by name.
   *
   * @param moduleName - The name of the module to load (e.g. 'VegaThemeManager')
   * @returns A Promise that resolves to the module's value
   *
   * @example
   * ```js
   * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
   * VegaThemeManager.applyBranding('gp');
   * ```
   */
  async load(moduleName) {
    var _a;
    // Check cache first
    if (moduleCache.has(moduleName)) {
      return moduleCache.get(moduleName);
    }
    // Check if already available on globalThis (backward compat with full entry).
    // Guard against the browser's "named access on the Window object" feature,
    // which auto-exposes DOM elements with an `id` as `window[id]` properties.
    // E.g. `<vega-button id="VegaThemeManager">` would make
    // `window.VegaThemeManager` return the DOM element instead of the module.
    // Uses nodeType === 1 instead of instanceof Element for cross-environment
    // compatibility (Stencil mock-doc, jsdom, browser).
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    if (globalThis[moduleName] !== undefined && ((_a = globalThis[moduleName]) === null || _a === void 0 ? void 0 : _a.nodeType) !== 1) {
      moduleCache.set(moduleName, globalThis[moduleName]);
      return globalThis[moduleName];
    }
    const factory = MODULE_REGISTRY[moduleName];
    if (!factory) {
      throw new Error(`VegaModuleLoader: Unknown module "${moduleName}". ` +
        `Available modules: ${Object.keys(MODULE_REGISTRY).join(', ')}`);
    }
    const module = await factory();
    moduleCache.set(moduleName, module);
    return module;
  },
  /**
   * Returns the list of all available module names that can be loaded.
   */
  getAvailableModules() {
    return Object.keys(MODULE_REGISTRY);
  },
};

// eslint-disable-next-line spellcheck/spell-checker
/**
 * Default export function that will be used by stencil global script,
 * which will be invoked before library loaded.
 *
 * This lean version only contains essential setup that ALL consumers need:
 * - Feature flag configuration from client globals
 * - Global slimmers (component lifecycle hooks)
 * - Typography injection
 * - Telemetry initialization (VegaEnvInfo + runtime metrics)
 * - CSP nonce head patch
 * - VegaModuleLoader on globalThis (for on-demand lazy loading of public API modules)
 * - Apply branding from client global (via VegaModuleLoader, zero static-import cost)
 *
 * The heavier vanilla-JS-only globalThis injections are handled separately
 * by vanillaJsGlobalSetup (only in `vega.esm.js`, the full browser entry).
 * Consumers who want a leaner bundle can use `vega-lean.esm.js` instead.
 */
function appGlobalScript () {
  disableFeatureFlagFromClientGlobal();
  enableFeatureFlagFromClientGlobal();
  registerGlobalVegaSlimmers();
  injectVegaTypography();
  initRuntimeMetricsTelemetryCollection();
  patchHeadInsertBeforeWithNonce();
  exposeVegaModuleLoader();
  applyBrandingFromClientGlobal();
}
/**
 * Disable feature flags from the client global defined lists.
 */
function disableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaDisabledFeatureKeys']) {
    FeatureFlag.disable(...globalThis['VegaDisabledFeatureKeys']);
  }
}
/**
 * This function enables feature flags based on a global variable in TypeScript.
 */
function enableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaEnabledFeatureKeys']) {
    FeatureFlag.enable(...globalThis['VegaEnabledFeatureKeys']);
  }
}
/**
 * register global vega slimmers
 */
function registerGlobalVegaSlimmers() {
  GlobalSlimmersRegistry.register([
    VegaWatchMethodCancelSlimmer,
    VegaTranslateObserverSlimmer,
    VegaNonceInjectorSlimmer,
  ]);
}
/**
 * Inject Vega typography stylesheet
 */
function injectVegaTypography() {
  Object.keys(TypographyUrls).forEach((key) => {
    const { url } = 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);
    }
  });
}
/**
 * init telemetry runtime metrics.
 * 1. Inject VegaEnvInfo to global (used by vega-telemetry-runtime-metrics for environment tracking)
 * 2. Register runtime metrics add page hide listener method
 */
function initRuntimeMetricsTelemetryCollection() {
  globalThis.VegaEnvInfo = vegaEnvManager.getVegaEnv();
  // eslint-disable-next-line spellcheck/spell-checker
  void import('./index-bfc6dfa2.js').then((
  // eslint-disable-next-line spellcheck/spell-checker
  module) => {
    module['default']['init'](FeatureFlag);
  });
}
/**
 * Patch document.head.insertBefore to ensure nonce is set on injected elements.
 */
function patchHeadInsertBeforeWithNonce() {
  vegaNonceManager.patchHeadInsertBeforeWithNonceToStencil();
}
/**
 * Expose VegaModuleLoader on globalThis so vanilla JS consumers using the lean entry
 * can load public API modules on demand:
 *
 * ```js
 * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
 * ```
 *
 * VegaModuleLoader has no static imports — all module references use dynamic import(),
 * so adding it here does not increase the lean bundle's initial load size.
 */
function exposeVegaModuleLoader() {
  globalThis['VegaModuleLoader'] = VegaModuleLoader;
}
/**
 * Switch the Vega theme to a new brand theme from the client global defined options.
 *
 * This runs synchronously so that branding is guaranteed to be applied before
 * any component renders, in both the lean and full entries.
 */
function applyBrandingFromClientGlobal() {
  if (globalThis['VegaThemeManagerApplyBranding']) {
    VegaThemeManager.applyBranding(globalThis['VegaThemeManagerApplyBranding']);
  }
}

const globalScripts = appGlobalScript;

export { globalScripts as g };
