Best JavaScript code snippet using playwright-internal
loader.js
Source:loader.js  
1"use strict";2Object.defineProperty(exports, "__esModule", {3  value: true4});5exports.Loader = void 0;6var _transform = require("./transform");7var _util = require("./util");8var _globals = require("./globals");9var _test = require("./test");10var path = _interopRequireWildcard(require("path"));11var url = _interopRequireWildcard(require("url"));12var fs = _interopRequireWildcard(require("fs"));13var _project = require("./project");14var _runner = require("./runner");15function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }16function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }17/**18 * Copyright Microsoft Corporation. All rights reserved.19 *20 * Licensed under the Apache License, Version 2.0 (the "License");21 * you may not use this file except in compliance with the License.22 * You may obtain a copy of the License at23 *24 *     http://www.apache.org/licenses/LICENSE-2.025 *26 * Unless required by applicable law or agreed to in writing, software27 * distributed under the License is distributed on an "AS IS" BASIS,28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.29 * See the License for the specific language governing permissions and30 * limitations under the License.31 */32class Loader {33  constructor(defaultConfig, configOverrides) {34    this._defaultConfig = void 0;35    this._configOverrides = void 0;36    this._fullConfig = void 0;37    this._config = {};38    this._configFile = void 0;39    this._projects = [];40    this._fileSuites = new Map();41    this._defaultConfig = defaultConfig;42    this._configOverrides = configOverrides;43    this._fullConfig = baseFullConfig;44  }45  static async deserialize(data) {46    const loader = new Loader(data.defaultConfig, data.overrides);47    if ('file' in data.configFile) await loader.loadConfigFile(data.configFile.file);else loader.loadEmptyConfig(data.configFile.rootDir);48    return loader;49  }50  async loadConfigFile(file) {51    if (this._configFile) throw new Error('Cannot load two config files');52    let config = await this._requireOrImport(file);53    if (config && typeof config === 'object' && 'default' in config) config = config['default'];54    this._config = config;55    this._configFile = file;56    const rawConfig = { ...config57    };58    this._processConfigObject(path.dirname(file));59    return rawConfig;60  }61  loadEmptyConfig(rootDir) {62    this._config = {};63    this._processConfigObject(rootDir);64  }65  _processConfigObject(rootDir) {66    validateConfig(this._configFile || '<default config>', this._config); // Resolve script hooks relative to the root dir.67    if (this._config.globalSetup) this._config.globalSetup = resolveScript(this._config.globalSetup, rootDir);68    if (this._config.globalTeardown) this._config.globalTeardown = resolveScript(this._config.globalTeardown, rootDir);69    const configUse = (0, _util.mergeObjects)(this._defaultConfig.use, this._config.use);70    this._config = (0, _util.mergeObjects)((0, _util.mergeObjects)(this._defaultConfig, this._config), {71      use: configUse72    });73    if (this._config.testDir !== undefined) this._config.testDir = path.resolve(rootDir, this._config.testDir);74    const projects = 'projects' in this._config && this._config.projects !== undefined ? this._config.projects : [this._config];75    this._fullConfig.rootDir = this._config.testDir || rootDir;76    this._fullConfig.forbidOnly = takeFirst(this._configOverrides.forbidOnly, this._config.forbidOnly, baseFullConfig.forbidOnly);77    this._fullConfig.globalSetup = takeFirst(this._configOverrides.globalSetup, this._config.globalSetup, baseFullConfig.globalSetup);78    this._fullConfig.globalTeardown = takeFirst(this._configOverrides.globalTeardown, this._config.globalTeardown, baseFullConfig.globalTeardown);79    this._fullConfig.globalTimeout = takeFirst(this._configOverrides.globalTimeout, this._configOverrides.globalTimeout, this._config.globalTimeout, baseFullConfig.globalTimeout);80    this._fullConfig.grep = takeFirst(this._configOverrides.grep, this._config.grep, baseFullConfig.grep);81    this._fullConfig.grepInvert = takeFirst(this._configOverrides.grepInvert, this._config.grepInvert, baseFullConfig.grepInvert);82    this._fullConfig.maxFailures = takeFirst(this._configOverrides.maxFailures, this._config.maxFailures, baseFullConfig.maxFailures);83    this._fullConfig.preserveOutput = takeFirst(this._configOverrides.preserveOutput, this._config.preserveOutput, baseFullConfig.preserveOutput);84    this._fullConfig.reporter = takeFirst(toReporters(this._configOverrides.reporter), resolveReporters(this._config.reporter, rootDir), baseFullConfig.reporter);85    this._fullConfig.reportSlowTests = takeFirst(this._configOverrides.reportSlowTests, this._config.reportSlowTests, baseFullConfig.reportSlowTests);86    this._fullConfig.quiet = takeFirst(this._configOverrides.quiet, this._config.quiet, baseFullConfig.quiet);87    this._fullConfig.shard = takeFirst(this._configOverrides.shard, this._config.shard, baseFullConfig.shard);88    this._fullConfig.updateSnapshots = takeFirst(this._configOverrides.updateSnapshots, this._config.updateSnapshots, baseFullConfig.updateSnapshots);89    this._fullConfig.workers = takeFirst(this._configOverrides.workers, this._config.workers, baseFullConfig.workers);90    this._fullConfig.webServer = takeFirst(this._configOverrides.webServer, this._config.webServer, baseFullConfig.webServer);91    for (const project of projects) this._addProject(project, this._fullConfig.rootDir);92    this._fullConfig.projects = this._projects.map(p => p.config);93  }94  async loadTestFile(file) {95    if (this._fileSuites.has(file)) return this._fileSuites.get(file);96    try {97      const suite = new _test.Suite(path.relative(this._fullConfig.rootDir, file) || path.basename(file));98      suite._requireFile = file;99      suite.location = {100        file,101        line: 0,102        column: 0103      };104      (0, _globals.setCurrentlyLoadingFileSuite)(suite);105      await this._requireOrImport(file);106      this._fileSuites.set(file, suite);107      return suite;108    } finally {109      (0, _globals.setCurrentlyLoadingFileSuite)(undefined);110    }111  }112  async loadGlobalHook(file, name) {113    let hook = await this._requireOrImport(file);114    if (hook && typeof hook === 'object' && 'default' in hook) hook = hook['default'];115    if (typeof hook !== 'function') throw (0, _util.errorWithFile)(file, `${name} file must export a single function.`);116    return hook;117  }118  async loadReporter(file) {119    let func = await this._requireOrImport(path.resolve(this._fullConfig.rootDir, file));120    if (func && typeof func === 'object' && 'default' in func) func = func['default'];121    if (typeof func !== 'function') throw (0, _util.errorWithFile)(file, `reporter file must export a single class.`);122    return func;123  }124  fullConfig() {125    return this._fullConfig;126  }127  projects() {128    return this._projects;129  }130  fileSuites() {131    return this._fileSuites;132  }133  serialize() {134    return {135      defaultConfig: this._defaultConfig,136      configFile: this._configFile ? {137        file: this._configFile138      } : {139        rootDir: this._fullConfig.rootDir140      },141      overrides: this._configOverrides142    };143  }144  _addProject(projectConfig, rootDir) {145    let testDir = takeFirst(projectConfig.testDir, rootDir);146    if (!path.isAbsolute(testDir)) testDir = path.resolve(rootDir, testDir);147    let outputDir = takeFirst(this._configOverrides.outputDir, projectConfig.outputDir, this._config.outputDir, path.resolve(process.cwd(), 'test-results'));148    if (!path.isAbsolute(outputDir)) outputDir = path.resolve(rootDir, outputDir);149    const fullProject = {150      define: takeFirst(this._configOverrides.define, projectConfig.define, this._config.define, []),151      expect: takeFirst(this._configOverrides.expect, projectConfig.expect, this._config.expect, undefined),152      outputDir,153      repeatEach: takeFirst(this._configOverrides.repeatEach, projectConfig.repeatEach, this._config.repeatEach, 1),154      retries: takeFirst(this._configOverrides.retries, projectConfig.retries, this._config.retries, 0),155      metadata: takeFirst(this._configOverrides.metadata, projectConfig.metadata, this._config.metadata, undefined),156      name: takeFirst(this._configOverrides.name, projectConfig.name, this._config.name, ''),157      testDir,158      testIgnore: takeFirst(this._configOverrides.testIgnore, projectConfig.testIgnore, this._config.testIgnore, []),159      testMatch: takeFirst(this._configOverrides.testMatch, projectConfig.testMatch, this._config.testMatch, '**/?(*.)@(spec|test).@(ts|js|mjs)'),160      timeout: takeFirst(this._configOverrides.timeout, projectConfig.timeout, this._config.timeout, 10000),161      use: (0, _util.mergeObjects)((0, _util.mergeObjects)(this._config.use, projectConfig.use), this._configOverrides.use)162    };163    this._projects.push(new _project.ProjectImpl(fullProject, this._projects.length));164  }165  async _requireOrImport(file) {166    const revertBabelRequire = (0, _transform.installTransform)();167    try {168      const esmImport = () => eval(`import(${JSON.stringify(url.pathToFileURL(file))})`);169      if (file.endsWith('.mjs')) {170        return await esmImport();171      } else {172        try {173          return require(file);174        } catch (e) {175          // Attempt to load this module as ESM if a normal require didn't work.176          if (e.code === 'ERR_REQUIRE_ESM') return await esmImport();177          throw e;178        }179      }180    } catch (error) {181      if (error instanceof SyntaxError && error.message.includes('Cannot use import statement outside a module')) throw (0, _util.errorWithFile)(file, 'JavaScript files must end with .mjs to use import.');182      throw error;183    } finally {184      revertBabelRequire();185    }186  }187}188exports.Loader = Loader;189function takeFirst(...args) {190  for (const arg of args) {191    if (arg !== undefined) return arg;192  }193  return undefined;194}195function toReporters(reporters) {196  if (!reporters) return;197  if (typeof reporters === 'string') return [[reporters]];198  return reporters;199}200function validateConfig(file, config) {201  if (typeof config !== 'object' || !config) throw (0, _util.errorWithFile)(file, `Configuration file must export a single object`);202  validateProject(file, config, 'config');203  if ('forbidOnly' in config && config.forbidOnly !== undefined) {204    if (typeof config.forbidOnly !== 'boolean') throw (0, _util.errorWithFile)(file, `config.forbidOnly must be a boolean`);205  }206  if ('globalSetup' in config && config.globalSetup !== undefined) {207    if (typeof config.globalSetup !== 'string') throw (0, _util.errorWithFile)(file, `config.globalSetup must be a string`);208  }209  if ('globalTeardown' in config && config.globalTeardown !== undefined) {210    if (typeof config.globalTeardown !== 'string') throw (0, _util.errorWithFile)(file, `config.globalTeardown must be a string`);211  }212  if ('globalTimeout' in config && config.globalTimeout !== undefined) {213    if (typeof config.globalTimeout !== 'number' || config.globalTimeout < 0) throw (0, _util.errorWithFile)(file, `config.globalTimeout must be a non-negative number`);214  }215  if ('grep' in config && config.grep !== undefined) {216    if (Array.isArray(config.grep)) {217      config.grep.forEach((item, index) => {218        if (!(0, _util.isRegExp)(item)) throw (0, _util.errorWithFile)(file, `config.grep[${index}] must be a RegExp`);219      });220    } else if (!(0, _util.isRegExp)(config.grep)) {221      throw (0, _util.errorWithFile)(file, `config.grep must be a RegExp`);222    }223  }224  if ('grepInvert' in config && config.grepInvert !== undefined) {225    if (Array.isArray(config.grepInvert)) {226      config.grepInvert.forEach((item, index) => {227        if (!(0, _util.isRegExp)(item)) throw (0, _util.errorWithFile)(file, `config.grepInvert[${index}] must be a RegExp`);228      });229    } else if (!(0, _util.isRegExp)(config.grepInvert)) {230      throw (0, _util.errorWithFile)(file, `config.grep must be a RegExp`);231    }232  }233  if ('maxFailures' in config && config.maxFailures !== undefined) {234    if (typeof config.maxFailures !== 'number' || config.maxFailures < 0) throw (0, _util.errorWithFile)(file, `config.maxFailures must be a non-negative number`);235  }236  if ('preserveOutput' in config && config.preserveOutput !== undefined) {237    if (typeof config.preserveOutput !== 'string' || !['always', 'never', 'failures-only'].includes(config.preserveOutput)) throw (0, _util.errorWithFile)(file, `config.preserveOutput must be one of "always", "never" or "failures-only"`);238  }239  if ('projects' in config && config.projects !== undefined) {240    if (!Array.isArray(config.projects)) throw (0, _util.errorWithFile)(file, `config.projects must be an array`);241    config.projects.forEach((project, index) => {242      validateProject(file, project, `config.projects[${index}]`);243    });244  }245  if ('quiet' in config && config.quiet !== undefined) {246    if (typeof config.quiet !== 'boolean') throw (0, _util.errorWithFile)(file, `config.quiet must be a boolean`);247  }248  if ('reporter' in config && config.reporter !== undefined) {249    if (Array.isArray(config.reporter)) {250      config.reporter.forEach((item, index) => {251        if (!Array.isArray(item) || item.length <= 0 || item.length > 2 || typeof item[0] !== 'string') throw (0, _util.errorWithFile)(file, `config.reporter[${index}] must be a tuple [name, optionalArgument]`);252      });253    } else if (typeof config.reporter !== 'string') {254      throw (0, _util.errorWithFile)(file, `config.reporter must be a string`);255    }256  }257  if ('reportSlowTests' in config && config.reportSlowTests !== undefined && config.reportSlowTests !== null) {258    if (!config.reportSlowTests || typeof config.reportSlowTests !== 'object') throw (0, _util.errorWithFile)(file, `config.reportSlowTests must be an object`);259    if (!('max' in config.reportSlowTests) || typeof config.reportSlowTests.max !== 'number' || config.reportSlowTests.max < 0) throw (0, _util.errorWithFile)(file, `config.reportSlowTests.max must be a non-negative number`);260    if (!('threshold' in config.reportSlowTests) || typeof config.reportSlowTests.threshold !== 'number' || config.reportSlowTests.threshold < 0) throw (0, _util.errorWithFile)(file, `config.reportSlowTests.threshold must be a non-negative number`);261  }262  if ('shard' in config && config.shard !== undefined && config.shard !== null) {263    if (!config.shard || typeof config.shard !== 'object') throw (0, _util.errorWithFile)(file, `config.shard must be an object`);264    if (!('total' in config.shard) || typeof config.shard.total !== 'number' || config.shard.total < 1) throw (0, _util.errorWithFile)(file, `config.shard.total must be a positive number`);265    if (!('current' in config.shard) || typeof config.shard.current !== 'number' || config.shard.current < 1 || config.shard.current > config.shard.total) throw (0, _util.errorWithFile)(file, `config.shard.current must be a positive number, not greater than config.shard.total`);266  }267  if ('updateSnapshots' in config && config.updateSnapshots !== undefined) {268    if (typeof config.updateSnapshots !== 'string' || !['all', 'none', 'missing'].includes(config.updateSnapshots)) throw (0, _util.errorWithFile)(file, `config.updateSnapshots must be one of "all", "none" or "missing"`);269  }270  if ('workers' in config && config.workers !== undefined) {271    if (typeof config.workers !== 'number' || config.workers <= 0) throw (0, _util.errorWithFile)(file, `config.workers must be a positive number`);272  }273}274function validateProject(file, project, title) {275  if (typeof project !== 'object' || !project) throw (0, _util.errorWithFile)(file, `${title} must be an object`);276  if ('define' in project && project.define !== undefined) {277    if (Array.isArray(project.define)) {278      project.define.forEach((item, index) => {279        validateDefine(file, item, `${title}.define[${index}]`);280      });281    } else {282      validateDefine(file, project.define, `${title}.define`);283    }284  }285  if ('name' in project && project.name !== undefined) {286    if (typeof project.name !== 'string') throw (0, _util.errorWithFile)(file, `${title}.name must be a string`);287  }288  if ('outputDir' in project && project.outputDir !== undefined) {289    if (typeof project.outputDir !== 'string') throw (0, _util.errorWithFile)(file, `${title}.outputDir must be a string`);290  }291  if ('repeatEach' in project && project.repeatEach !== undefined) {292    if (typeof project.repeatEach !== 'number' || project.repeatEach < 0) throw (0, _util.errorWithFile)(file, `${title}.repeatEach must be a non-negative number`);293  }294  if ('retries' in project && project.retries !== undefined) {295    if (typeof project.retries !== 'number' || project.retries < 0) throw (0, _util.errorWithFile)(file, `${title}.retries must be a non-negative number`);296  }297  if ('testDir' in project && project.testDir !== undefined) {298    if (typeof project.testDir !== 'string') throw (0, _util.errorWithFile)(file, `${title}.testDir must be a string`);299  }300  for (const prop of ['testIgnore', 'testMatch']) {301    if (prop in project && project[prop] !== undefined) {302      const value = project[prop];303      if (Array.isArray(value)) {304        value.forEach((item, index) => {305          if (typeof item !== 'string' && !(0, _util.isRegExp)(item)) throw (0, _util.errorWithFile)(file, `${title}.${prop}[${index}] must be a string or a RegExp`);306        });307      } else if (typeof value !== 'string' && !(0, _util.isRegExp)(value)) {308        throw (0, _util.errorWithFile)(file, `${title}.${prop} must be a string or a RegExp`);309      }310    }311  }312  if ('timeout' in project && project.timeout !== undefined) {313    if (typeof project.timeout !== 'number' || project.timeout < 0) throw (0, _util.errorWithFile)(file, `${title}.timeout must be a non-negative number`);314  }315  if ('use' in project && project.use !== undefined) {316    if (!project.use || typeof project.use !== 'object') throw (0, _util.errorWithFile)(file, `${title}.use must be an object`);317  }318}319function validateDefine(file, define, title) {320  if (!define || typeof define !== 'object' || !define.test || !define.fixtures) throw (0, _util.errorWithFile)(file, `${title} must be an object with "test" and "fixtures" properties`);321}322const baseFullConfig = {323  forbidOnly: false,324  globalSetup: null,325  globalTeardown: null,326  globalTimeout: 0,327  grep: /.*/,328  grepInvert: null,329  maxFailures: 0,330  preserveOutput: 'always',331  projects: [],332  reporter: [['list']],333  reportSlowTests: null,334  rootDir: path.resolve(process.cwd()),335  quiet: false,336  shard: null,337  updateSnapshots: 'missing',338  workers: 1,339  webServer: null340};341function resolveReporters(reporters, rootDir) {342  var _toReporters;343  return (_toReporters = toReporters(reporters)) === null || _toReporters === void 0 ? void 0 : _toReporters.map(([id, arg]) => {344    if (_runner.builtInReporters.includes(id)) return [id, arg];345    return [require.resolve(id, {346      paths: [rootDir]347    }), arg];348  });349}350function resolveScript(id, rootDir) {351  const localPath = path.resolve(rootDir, id);352  if (fs.existsSync(localPath)) return localPath;353  return require.resolve(id, {354    paths: [rootDir]355  });..._install_package.js
Source:_install_package.js  
1"use strict";2Object.defineProperty(exports, "__esModule", {3  value: true4});5exports._installPackage = _installPackage;6var _common = require("../../../../common");7var _constants = require("../../../constants");8var _install = require("../elasticsearch/template/install");9var _ingest_pipeline = require("../elasticsearch/ingest_pipeline/");10var _install2 = require("../elasticsearch/ilm/install");11var _install3 = require("../kibana/assets/install");12var _template = require("../elasticsearch/template/template");13var _install4 = require("../elasticsearch/transform/install");14var _ml_model = require("../elasticsearch/ml_model/");15var _install5 = require("../elasticsearch/datastream_ilm/install");16var _storage = require("../archive/storage");17var _errors = require("../../../errors");18var _ = require("../..");19var _install6 = require("./install");20var _remove = require("./remove");21/*22 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one23 * or more contributor license agreements. Licensed under the Elastic License24 * 2.0; you may not use this file except in compliance with the Elastic License25 * 2.0.26 */27// this is only exported for testing28// use a leading underscore to indicate it's not the supported path29// only the more explicit `installPackage*` functions should be used30async function _installPackage({31  savedObjectsClient,32  savedObjectsImporter,33  esClient,34  logger,35  installedPkg,36  paths,37  packageInfo,38  installType,39  installSource,40  spaceId41}) {42  const {43    name: pkgName,44    version: pkgVersion45  } = packageInfo;46  try {47    // if some installation already exists48    if (installedPkg) {49      // if the installation is currently running, don't try to install50      // instead, only return already installed assets51      if (installedPkg.attributes.install_status === 'installing' && Date.now() - Date.parse(installedPkg.attributes.install_started_at) < _common.MAX_TIME_COMPLETE_INSTALL) {52        throw new _errors.ConcurrentInstallOperationError(`Concurrent installation or upgrade of ${pkgName || 'unknown'}-${pkgVersion || 'unknown'} detected, aborting.`);53      } else {54        // if no installation is running, or the installation has been running longer than MAX_TIME_COMPLETE_INSTALL55        // (it might be stuck) update the saved object and proceed56        await savedObjectsClient.update(_constants.PACKAGES_SAVED_OBJECT_TYPE, pkgName, {57          install_version: pkgVersion,58          install_status: 'installing',59          install_started_at: new Date().toISOString(),60          install_source: installSource61        });62      }63    } else {64      await (0, _install6.createInstallation)({65        savedObjectsClient,66        packageInfo,67        installSource,68        spaceId69      });70    }71    const kibanaAssets = await (0, _install3.getKibanaAssets)(paths);72    if (installedPkg) await (0, _remove.deleteKibanaSavedObjectsAssets)({73      savedObjectsClient,74      installedPkg75    }); // save new kibana refs before installing the assets76    const installedKibanaAssetsRefs = await (0, _install6.saveKibanaAssetsRefs)(savedObjectsClient, pkgName, kibanaAssets);77    await (0, _install3.installKibanaAssets)({78      logger,79      savedObjectsImporter,80      pkgName,81      kibanaAssets82    }); // the rest of the installation must happen in sequential order83    // currently only the base package has an ILM policy84    // at some point ILM policies can be installed/modified85    // per data stream and we should then save them86    await (0, _install2.installILMPolicy)(packageInfo, paths, esClient, logger);87    const installedDataStreamIlm = await (0, _install5.installIlmForDataStream)(packageInfo, paths, esClient, savedObjectsClient, logger); // installs ml models88    const installedMlModel = await (0, _ml_model.installMlModel)(packageInfo, paths, esClient, savedObjectsClient, logger); // installs versionized pipelines without removing currently installed ones89    const installedPipelines = await (0, _ingest_pipeline.installPipelines)(packageInfo, paths, esClient, savedObjectsClient, logger); // install or update the templates referencing the newly installed pipelines90    const installedTemplates = await (0, _install.installTemplates)(packageInfo, esClient, logger, paths, savedObjectsClient); // update current backing indices of each data stream91    await (0, _template.updateCurrentWriteIndices)(esClient, logger, installedTemplates);92    const installedTransforms = await (0, _install4.installTransform)(packageInfo, paths, esClient, savedObjectsClient, logger); // If this is an update or retrying an update, delete the previous version's pipelines93    // Top-level pipeline assets will not be removed on upgrade as of ml model package addition which requires previous94    // assets to remain installed. This is a temporary solution - more robust solution tracked here https://github.com/elastic/kibana/issues/11503595    if (paths.filter(path => (0, _ingest_pipeline.isTopLevelPipeline)(path)).length === 0 && (installType === 'update' || installType === 'reupdate') && installedPkg) {96      await (0, _ingest_pipeline.deletePreviousPipelines)(esClient, savedObjectsClient, pkgName, installedPkg.attributes.version);97    } // pipelines from a different version may have installed during a failed update98    if (installType === 'rollback' && installedPkg) {99      await (0, _ingest_pipeline.deletePreviousPipelines)(esClient, savedObjectsClient, pkgName, installedPkg.attributes.install_version);100    }101    const installedTemplateRefs = (0, _install.getAllTemplateRefs)(installedTemplates);102    const packageAssetResults = await (0, _storage.saveArchiveEntries)({103      savedObjectsClient,104      paths,105      packageInfo,106      installSource107    });108    const packageAssetRefs = packageAssetResults.saved_objects.map(result => ({109      id: result.id,110      type: _common.ASSETS_SAVED_OBJECT_TYPE111    })); // update to newly installed version when all assets are successfully installed112    if (installedPkg) await (0, _install6.updateVersion)(savedObjectsClient, pkgName, pkgVersion);113    const updatedPackage = await savedObjectsClient.update(_constants.PACKAGES_SAVED_OBJECT_TYPE, pkgName, {114      install_version: pkgVersion,115      install_status: 'installed',116      package_assets: packageAssetRefs117    }); // If the package is flagged with the `keep_policies_up_to_date` flag, upgrade its118    // associated package policies after installation119    if (updatedPackage.attributes.keep_policies_up_to_date) {120      const policyIdsToUpgrade = await _.packagePolicyService.listIds(savedObjectsClient, {121        page: 1,122        perPage: _common.SO_SEARCH_LIMIT,123        kuery: `${_common.PACKAGE_POLICY_SAVED_OBJECT_TYPE}.package.name:${pkgName}`124      });125      await _.packagePolicyService.upgrade(savedObjectsClient, esClient, policyIdsToUpgrade.items);126    }127    return [...installedKibanaAssetsRefs, ...installedPipelines, ...installedDataStreamIlm, ...installedTemplateRefs, ...installedTransforms, ...installedMlModel];128  } catch (err) {129    if (savedObjectsClient.errors.isConflictError(err)) {130      throw new _errors.ConcurrentInstallOperationError(`Concurrent installation or upgrade of ${pkgName || 'unknown'}-${pkgVersion || 'unknown'} detected, aborting. Original error: ${err.message}`);131    } else {132      throw err;133    }134  }...transform.js
Source:transform.js  
...50  const hash = crypto.createHash('sha1').update(content).update(filePath).update(String(version)).digest('hex');51  const fileName = path.basename(filePath, path.extname(filePath)).replace(/\W/g, '') + '_' + hash;52  return path.join(cacheDir, hash[0] + hash[1], fileName);53}54function installTransform() {55  return pirates.addHook((code, filename) => {56    const cachePath = calculateCachePath(code, filename);57    const codePath = cachePath + '.js';58    const sourceMapPath = cachePath + '.map';59    sourceMaps.set(filename, sourceMapPath);60    if (fs.existsSync(codePath)) return fs.readFileSync(codePath, 'utf8'); // We don't use any browserslist data, but babel checks it anyway.61    // Silence the annoying warning.62    process.env.BROWSERSLIST_IGNORE_OLD_DATA = 'true';63    const babel = require('@babel/core');64    const result = babel.transformFileSync(filename, {65      babelrc: false,66      configFile: false,67      assumptions: {68        // Without this, babel defines a top level function that...install.js
Source:install.js  
1"use strict";2Object.defineProperty(exports, "__esModule", {3  value: true4});5exports.isTransform = exports.installTransform = void 0;6var _elasticsearch = require("@elastic/elasticsearch");7var _install = require("../../packages/install");8var _archive = require("../../archive");9var _models = require("../../../../../common/types/models");10var _packages = require("../../packages");11var _meta = require("../meta");12var _retry = require("../retry");13var _remove = require("./remove");14var _common = require("./common");15/*16 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one17 * or more contributor license agreements. Licensed under the Elastic License18 * 2.0; you may not use this file except in compliance with the Elastic License19 * 2.0.20 */21const installTransform = async (installablePackage, paths, esClient, savedObjectsClient, logger) => {22  const installation = await (0, _packages.getInstallation)({23    savedObjectsClient,24    pkgName: installablePackage.name25  });26  let previousInstalledTransformEsAssets = [];27  if (installation) {28    previousInstalledTransformEsAssets = installation.installed_es.filter(({29      type,30      id31    }) => type === _models.ElasticsearchAssetType.transform);32    if (previousInstalledTransformEsAssets.length) {33      logger.info(`Found previous transform references:\n ${JSON.stringify(previousInstalledTransformEsAssets)}`);34    }35  } // delete all previous transform36  await (0, _remove.deleteTransforms)(esClient, previousInstalledTransformEsAssets.map(asset => asset.id));37  const installNameSuffix = `${installablePackage.version}`;38  const transformPaths = paths.filter(path => isTransform(path));39  let installedTransforms = [];40  if (transformPaths.length > 0) {41    const transformRefs = transformPaths.reduce((acc, path) => {42      acc.push({43        id: getTransformNameForInstallation(installablePackage, path, installNameSuffix),44        type: _models.ElasticsearchAssetType.transform45      });46      return acc;47    }, []); // get and save transform refs before installing transforms48    await (0, _install.saveInstalledEsRefs)(savedObjectsClient, installablePackage.name, transformRefs);49    const transforms = transformPaths.map(path => {50      const content = JSON.parse((0, _common.getAsset)(path).toString('utf-8'));51      content._meta = (0, _meta.getESAssetMetadata)({52        packageName: installablePackage.name53      });54      return {55        installationName: getTransformNameForInstallation(installablePackage, path, installNameSuffix),56        content57      };58    });59    const installationPromises = transforms.map(async transform => {60      return handleTransformInstall({61        esClient,62        logger,63        transform64      });65    });66    installedTransforms = await Promise.all(installationPromises).then(results => results.flat());67  }68  if (previousInstalledTransformEsAssets.length > 0) {69    const currentInstallation = await (0, _packages.getInstallation)({70      savedObjectsClient,71      pkgName: installablePackage.name72    }); // remove the saved object reference73    await (0, _remove.deleteTransformRefs)(savedObjectsClient, (currentInstallation === null || currentInstallation === void 0 ? void 0 : currentInstallation.installed_es) || [], installablePackage.name, previousInstalledTransformEsAssets.map(asset => asset.id), installedTransforms.map(installed => installed.id));74  }75  return installedTransforms;76};77exports.installTransform = installTransform;78const isTransform = path => {79  const pathParts = (0, _archive.getPathParts)(path);80  return !path.endsWith('/') && pathParts.type === _models.ElasticsearchAssetType.transform;81};82exports.isTransform = isTransform;83async function handleTransformInstall({84  esClient,85  logger,86  transform87}) {88  try {89    await (0, _retry.retryTransientEsErrors)(() => // defer validation on put if the source index is not available90    esClient.transform.putTransform({91      transform_id: transform.installationName,92      defer_validation: true,93      body: transform.content94    }), {95      logger96    });97  } catch (err) {98    var _err$body, _err$body$error; // swallow the error if the transform already exists.99    const isAlreadyExistError = err instanceof _elasticsearch.errors.ResponseError && (err === null || err === void 0 ? void 0 : (_err$body = err.body) === null || _err$body === void 0 ? void 0 : (_err$body$error = _err$body.error) === null || _err$body$error === void 0 ? void 0 : _err$body$error.type) === 'resource_already_exists_exception';100    if (!isAlreadyExistError) {101      throw err;102    }103  }104  await esClient.transform.startTransform({105    transform_id: transform.installationName106  }, {107    ignore: [409]108  });109  return {110    id: transform.installationName,111    type: _models.ElasticsearchAssetType.transform112  };113}114const getTransformNameForInstallation = (installablePackage, path, suffix) => {115  var _pathPaths$pop;116  const pathPaths = path.split('/');117  const filename = pathPaths === null || pathPaths === void 0 ? void 0 : (_pathPaths$pop = pathPaths.pop()) === null || _pathPaths$pop === void 0 ? void 0 : _pathPaths$pop.split('.')[0];118  const folderName = pathPaths === null || pathPaths === void 0 ? void 0 : pathPaths.pop();119  return `${installablePackage.name}.${folderName}-${filename}-${suffix}`;...test.js
Source:test.js  
...65	t.is(module.code, 'foobar');66});67test('a system > provides convenience method for installing transforms', t => {68	const system = new MockSystem({'/foo.js': 'foo'});69	system.installTransform((code, filename) => {70		t.is(code, 'foo');71		t.is(filename, '/foo.js');72		return 'bar';73	});74	const module = system.load('/foo.js');75	t.is(module.code, 'bar');76});77test('convenience transform plays nice with transforms added after', t => {78	const system = new MockSystem({'/foo.js': 'foo'});79	system.installTransform(code => code + ' bar');80	// Install a hook that append "bar"81	const originalHook = system.extensions['.js'];82	system.extensions['.js'] = function (module, filename) {83		const originalCompile = module._compile;84		module._compile = function (code, filename) {85			code = code.toUpperCase();86			module._compile = originalCompile;87			module._compile(code, filename);88		};89		originalHook(module, filename);90	};91	const module = system.load('/foo.js');92	t.is(module.code, 'FOO BAR');93});94test('convenience transform plays nice with transforms added before', t => {95	const system = new MockSystem({'/foo.js': 'foo'});96	// Install a hook that append "bar"97	const originalHook = system.extensions['.js'];98	system.extensions['.js'] = function (module, filename) {99		const originalCompile = module._compile;100		module._compile = function (code, filename) {101			code = code.toUpperCase();102			module._compile = originalCompile;103			module._compile(code, filename);104		};105		originalHook(module, filename);106	};107	system.installTransform(code => code + ' bar');108	const module = system.load('/foo.js');109	t.is(module.code, 'FOO bar');110});111test('convenience transform throws if transform fails to return a string', t => {112	const system = new MockSystem({'/foo.js': 'foo'});113	system.installTransform(code => null);114	t.throws(() => system.load('/foo.js'));115});116test('one module can require another', t => {117	const system = new MockSystem({118		'/foo.js': 'require("/bar.js")',119		'/bar.js': 'this is bar'120	});121	var foo = system.load('/foo.js');122	t.is(foo.required['/bar.js'].code, 'this is bar');123});124test('circular requires', t => {125	const system = new MockSystem({126		'/foo.js': 'require("/bar.js")',127		'/bar.js': 'require("/foo.js")'...package_service.js
Source:package_service.js  
1"use strict";2var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");3Object.defineProperty(exports, "__esModule", {4  value: true5});6exports.PackageServiceImpl = void 0;7var _classPrivateMethodGet2 = _interopRequireDefault(require("@babel/runtime/helpers/classPrivateMethodGet"));8var _security = require("../../routes/security");9var _errors = require("../../errors");10var _install = require("./elasticsearch/transform/install");11var _registry = require("./registry");12var _packages = require("./packages");13function _classPrivateMethodInitSpec(obj, privateSet) {14  _checkPrivateRedeclaration(obj, privateSet);15  privateSet.add(obj);16}17function _checkPrivateRedeclaration(obj, privateCollection) {18  if (privateCollection.has(obj)) {19    throw new TypeError("Cannot initialize the same private elements twice on an object");20  }21}22class PackageServiceImpl {23  constructor(internalEsClient, internalSoClient, logger) {24    this.internalEsClient = internalEsClient;25    this.internalSoClient = internalSoClient;26    this.logger = logger;27  }28  asScoped(request) {29    const preflightCheck = () => {30      if (!(0, _security.checkSuperuser)(request)) {31        throw new _errors.FleetUnauthorizedError(`User does not have adequate permissions to access Fleet packages.`);32      }33    };34    return new PackageClientImpl(this.internalEsClient, this.internalSoClient, this.logger, preflightCheck);35  }36  get asInternalUser() {37    return new PackageClientImpl(this.internalEsClient, this.internalSoClient, this.logger);38  }39}40exports.PackageServiceImpl = PackageServiceImpl;41var _reinstallTransforms = /*#__PURE__*/new WeakSet();42var _runPreflight = /*#__PURE__*/new WeakSet();43class PackageClientImpl {44  constructor(internalEsClient, internalSoClient, logger, preflightCheck) {45    _classPrivateMethodInitSpec(this, _runPreflight);46    _classPrivateMethodInitSpec(this, _reinstallTransforms);47    this.internalEsClient = internalEsClient;48    this.internalSoClient = internalSoClient;49    this.logger = logger;50    this.preflightCheck = preflightCheck;51  }52  async getInstallation(pkgName) {53    await (0, _classPrivateMethodGet2.default)(this, _runPreflight, _runPreflight2).call(this);54    return (0, _packages.getInstallation)({55      pkgName,56      savedObjectsClient: this.internalSoClient57    });58  }59  async ensureInstalledPackage(options) {60    await (0, _classPrivateMethodGet2.default)(this, _runPreflight, _runPreflight2).call(this);61    return (0, _packages.ensureInstalledPackage)({ ...options,62      esClient: this.internalEsClient,63      savedObjectsClient: this.internalSoClient64    });65  }66  async fetchFindLatestPackage(packageName) {67    await (0, _classPrivateMethodGet2.default)(this, _runPreflight, _runPreflight2).call(this);68    return (0, _registry.fetchFindLatestPackageOrThrow)(packageName);69  }70  async getRegistryPackage(packageName, packageVersion) {71    await (0, _classPrivateMethodGet2.default)(this, _runPreflight, _runPreflight2).call(this);72    return (0, _registry.getRegistryPackage)(packageName, packageVersion);73  }74  async reinstallEsAssets(packageInfo, assetPaths) {75    await (0, _classPrivateMethodGet2.default)(this, _runPreflight, _runPreflight2).call(this);76    let installedAssets = [];77    const transformPaths = assetPaths.filter(_install.isTransform);78    if (transformPaths.length !== assetPaths.length) {79      throw new Error('reinstallEsAssets is currently only implemented for transform assets');80    }81    if (transformPaths.length) {82      const installedTransformAssets = await (0, _classPrivateMethodGet2.default)(this, _reinstallTransforms, _reinstallTransforms2).call(this, packageInfo, transformPaths);83      installedAssets = [...installedAssets, ...installedTransformAssets];84    }85    return installedAssets;86  }87}88function _reinstallTransforms2(packageInfo, paths) {89  return (0, _install.installTransform)(packageInfo, paths, this.internalEsClient, this.internalSoClient, this.logger);90}91function _runPreflight2() {92  if (this.preflightCheck) {93    return this.preflightCheck();94  }...index.js
Source:index.js  
1'use strict';2var path = require('path');3var matchRequire = require('match-require');4function MockModule(system) {5	if (!(this instanceof MockModule)) {6		return new MockModule(system);7	}8	this._compiled = false;9	this._system = system;10}11MockModule.prototype._compile = function (code, file) {12	if (this._compiled) {13		throw new Error('compiled twice');14	}15	this._compiled = true;16	this.code = code;17	this.file = file;18	this.required = {};19	var required = matchRequire.findAll(code);20	if (!(required && required.length)) {21		return;22	}23	if (!this._system) {24		throw new Error('System not set: code can not use require');25	}26	required.forEach(function (name) {27		this.required[name] = this._system.load(name);28	}, this);29};30module.exports = MockModule;31function MockSystem(content) {32	if (!(this instanceof MockSystem)) {33		return new MockSystem(content);34	}35	var self = this;36	this.content = content || {};37	this.cache = {};38	this.Module = MockModule;39	function defaultExtension(module, filename) {40		module._compile(self.content[filename], filename);41	}42	this.extensions = {43		'.js': defaultExtension44	};45	this.load = function (filename) {46		if (self.cache[filename]) {47			return self.cache[filename];48		}49		var module = self.cache[filename] = new MockModule(self);50		var extension = path.extname(filename);51		try {52			self.extensions[extension](module, filename);53		} catch (e) {54			delete self.cache[filename];55			throw e;56		}57		return module;58	};59	this.installTransform = function (transformFn, ext) {60		ext = ext || '.js';61		var oldExtension = self.extensions[ext];62		self.extensions[ext] = function (module, filename) {63			var oldCompile = module._compile;64			module._compile = function (code, filename) {65				module._compile = oldCompile;66				code = transformFn(code, filename);67				if (typeof code !== 'string') {68					throw new Error('transformFn must always return a string');69				}70				module._compile(code, filename);71			};72			oldExtension(module, filename);73		};74	};75}76module.exports = MockSystem;...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
