Updated js-yaml to v4 (#190678)

## Summary
Updated `js-yaml` to `4.1.0`.

This PR also introduces a type override for the `js-yaml` load function
to maintain compatibility across the codebase. Specifically, updated
type definition of the load function looks as follows:

```typescript
function load<T = any>(str: string, opts?: jsyaml.LoadOptions): T;
```

The original type definition of the load function in `js-yaml` changed
from `any` to `unknown`. This change would require extensive type
updates throughout the entire repository to accommodate the `unknown`
type. To avoid widespread type changes and potential issues in the
codebase, the type is overriden back to `any` for now.
This is a temporary measure, we plan to address the necessary type
changes in subsequent PRs, where teams will gradually update the
codebase to work with the `unknown` type.


### Checklist

- [x] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios

## Release note
Updated `js-yaml` to `4.1.0`.

---------

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Maxim Palenov <maxim.palenov@elastic.co>
This commit is contained in:
Elena Shostak 2024-09-19 12:25:03 +02:00 committed by GitHub
parent eabb102281
commit 28aa274f66
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
130 changed files with 514 additions and 490 deletions

View file

@ -38,7 +38,6 @@ async function main() {
const preamble = locationFileLines.slice(0, 1); const preamble = locationFileLines.slice(0, 1);
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
const locationObj = jsYaml.load( const locationObj = jsYaml.load(
locationFileLines.slice(1).join('\n') locationFileLines.slice(1).join('\n')
) as BackstageLocationResource; ) as BackstageLocationResource;
@ -46,7 +45,6 @@ async function main() {
(fileName) => `${resourceDefinitionsBaseUrl}/${fileName}` (fileName) => `${resourceDefinitionsBaseUrl}/${fileName}`
); );
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
const locationYaml = jsYaml.dump(locationObj, { lineWidth: 400 }); const locationYaml = jsYaml.dump(locationObj, { lineWidth: 400 });
fs.writeFileSync(locationFile, `${preamble.join('\n')}\n${locationYaml}`); fs.writeFileSync(locationFile, `${preamble.join('\n')}\n${locationYaml}`);

View file

@ -7,7 +7,6 @@
* License v3.0 only", or the "Server Side Public License, v 1". * License v3.0 only", or the "Server Side Public License, v 1".
*/ */
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
import { dump } from 'js-yaml'; import { dump } from 'js-yaml';
import { BuildkiteClient, BuildkiteCommandStep } from './buildkite'; import { BuildkiteClient, BuildkiteCommandStep } from './buildkite';

View file

@ -10,7 +10,6 @@
import axios, { AxiosInstance } from 'axios'; import axios, { AxiosInstance } from 'axios';
import { execSync, ExecSyncOptions } from 'child_process'; import { execSync, ExecSyncOptions } from 'child_process';
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
import { dump } from 'js-yaml'; import { dump } from 'js-yaml';
import { parseLinkHeader } from './parse_link_header'; import { parseLinkHeader } from './parse_link_header';

View file

@ -12,7 +12,6 @@ import * as Fs from 'fs';
import * as globby from 'globby'; import * as globby from 'globby';
import minimatch from 'minimatch'; import minimatch from 'minimatch';
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
import { load as loadYaml } from 'js-yaml'; import { load as loadYaml } from 'js-yaml';
import { BuildkiteClient, BuildkiteStep } from '../buildkite'; import { BuildkiteClient, BuildkiteStep } from '../buildkite';

View file

@ -1130,7 +1130,7 @@
"jquery": "^3.5.0", "jquery": "^3.5.0",
"js-search": "^1.4.3", "js-search": "^1.4.3",
"js-sha256": "^0.9.0", "js-sha256": "^0.9.0",
"js-yaml": "^3.14.1", "js-yaml": "^4.1.0",
"json-schema-to-ts": "^2.9.1", "json-schema-to-ts": "^2.9.1",
"json-stable-stringify": "^1.0.1", "json-stable-stringify": "^1.0.1",
"json-stringify-pretty-compact": "1.2.0", "json-stringify-pretty-compact": "1.2.0",
@ -1560,7 +1560,7 @@
"@types/jest": "^29.5.3", "@types/jest": "^29.5.3",
"@types/jquery": "^3.3.31", "@types/jquery": "^3.3.31",
"@types/js-search": "^1.4.0", "@types/js-search": "^1.4.0",
"@types/js-yaml": "^3.11.1", "@types/js-yaml": "^4.0.9",
"@types/jsdom": "^20.0.1", "@types/jsdom": "^20.0.1",
"@types/json-schema": "^7", "@types/json-schema": "^7",
"@types/json-stable-stringify": "^1.0.32", "@types/json-stable-stringify": "^1.0.32",

View file

@ -8,7 +8,7 @@
*/ */
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { set } from '@kbn/safer-lodash-set'; import { set } from '@kbn/safer-lodash-set';
import { ensureDeepObject } from '@kbn/std'; import { ensureDeepObject } from '@kbn/std';
@ -16,7 +16,7 @@ import { isPlainObject } from 'lodash';
const readYaml = (path: string) => { const readYaml = (path: string) => {
try { try {
return safeLoad(readFileSync(path, 'utf8')); return load(readFileSync(path, 'utf8'));
} catch (e) { } catch (e) {
/* tslint:disable:no-empty */ /* tslint:disable:no-empty */
} }

View file

@ -8,13 +8,13 @@
*/ */
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { set } from '@kbn/safer-lodash-set'; import { set } from '@kbn/safer-lodash-set';
import { isPlainObject } from 'lodash'; import { isPlainObject } from 'lodash';
import { ensureValidObjectPath } from '@kbn/std'; import { ensureValidObjectPath } from '@kbn/std';
import { splitKey, getUnsplittableKey, replaceEnvVarRefs } from './utils'; import { splitKey, getUnsplittableKey, replaceEnvVarRefs } from './utils';
const readYaml = (path: string) => safeLoad(readFileSync(path, 'utf8')); const readYaml = (path: string) => load(readFileSync(path, 'utf8'));
interface YamlEntry { interface YamlEntry {
path: string[]; path: string[];
@ -76,7 +76,7 @@ export const getConfigFromFiles = (configFiles: readonly string[]) => {
for (const configFile of configFiles) { for (const configFile of configFiles) {
const yaml = readYaml(configFile); const yaml = readYaml(configFile);
if (yaml !== null) { if (yaml) {
yamlEntries.push(...listEntries(yaml)); yamlEntries.push(...listEntries(yaml));
} }
} }

View file

@ -38,7 +38,7 @@ export async function getAllDocFileIds(outputDir: string) {
let fm; let fm;
try { try {
fm = Yaml.safeLoad(fmYaml.slice(0, fmEnd.index)); fm = Yaml.load(fmYaml.slice(0, fmEnd.index));
if (typeof fm !== 'object' || fm === null) { if (typeof fm !== 'object' || fm === null) {
throw new Error('expected yaml to produce an object'); throw new Error('expected yaml to produce an object');
} }

View file

@ -9,6 +9,7 @@
}, },
"include": [ "include": [
"**/*.ts", "**/*.ts",
"../../typings/**/*"
], ],
"exclude": [ "exclude": [
"**/__fixtures__/**", "**/__fixtures__/**",

View file

@ -9,7 +9,7 @@
import fs from 'fs'; import fs from 'fs';
import { extname } from 'path'; import { extname } from 'path';
import { safeLoad as loadYaml } from 'js-yaml'; import { load as loadYaml } from 'js-yaml';
export const readRolesFromResource = (resourcePath: string) => { export const readRolesFromResource = (resourcePath: string) => {
if (!fs.existsSync(resourcePath) || extname(resourcePath) !== '.yml') { if (!fs.existsSync(resourcePath) || extname(resourcePath) !== '.yml') {

View file

@ -314,7 +314,6 @@ module.exports = {
'@kbn/eslint/no_constructor_args_in_property_initializers': 'error', '@kbn/eslint/no_constructor_args_in_property_initializers': 'error',
'@kbn/eslint/no_this_in_property_initializers': 'error', '@kbn/eslint/no_this_in_property_initializers': 'error',
'@kbn/eslint/no_unsafe_console': 'error', '@kbn/eslint/no_unsafe_console': 'error',
'@kbn/eslint/no_unsafe_js_yaml': 'error',
'@kbn/imports/no_unresolvable_imports': 'error', '@kbn/imports/no_unresolvable_imports': 'error',
'@kbn/imports/uniform_imports': 'error', '@kbn/imports/uniform_imports': 'error',
'@kbn/imports/no_unused_imports': 'error', '@kbn/imports/no_unused_imports': 'error',

View file

@ -51,7 +51,7 @@ export class ServerlessAuthProvider implements AuthProvider {
} }
getSupportedRoleDescriptors(): Record<string, unknown> { getSupportedRoleDescriptors(): Record<string, unknown> {
return readRolesDescriptorsFromResource(this.rolesDefinitionPath); return readRolesDescriptorsFromResource(this.rolesDefinitionPath) as Record<string, unknown>;
} }
getDefaultRole(): string { getDefaultRole(): string {
return getDefaultServerlessRole(this.projectType); return getDefaultServerlessRole(this.projectType);

View file

@ -19,7 +19,7 @@ import {
export class StatefulAuthProvider implements AuthProvider { export class StatefulAuthProvider implements AuthProvider {
private readonly rolesDefinitionPath = resolve(REPO_ROOT, STATEFUL_ROLES_ROOT_PATH, 'roles.yml'); private readonly rolesDefinitionPath = resolve(REPO_ROOT, STATEFUL_ROLES_ROOT_PATH, 'roles.yml');
getSupportedRoleDescriptors(): Record<string, unknown> { getSupportedRoleDescriptors(): Record<string, unknown> {
return readRolesDescriptorsFromResource(this.rolesDefinitionPath); return readRolesDescriptorsFromResource(this.rolesDefinitionPath) as Record<string, unknown>;
} }
getDefaultRole() { getDefaultRole() {
return 'editor'; return 'editor';

View file

@ -9,6 +9,7 @@
}, },
"include": [ "include": [
"**/*.ts", "**/*.ts",
"../../typings/**/*"
], ],
"kbn_references": [ "kbn_references": [
"@kbn/core-saved-objects-server", "@kbn/core-saved-objects-server",

View file

@ -8,7 +8,7 @@
*/ */
import chalk from 'chalk'; import chalk from 'chalk';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { isPlainObjectType } from './is_plain_object_type'; import { isPlainObjectType } from './is_plain_object_type';
/** /**
@ -33,7 +33,7 @@ export function extractByJsonPointer(document: unknown, pointer: string): unknow
throw new Error( throw new Error(
`JSON Pointer ${chalk.bold(pointer)} resolution failure. Expected ${chalk.magenta( `JSON Pointer ${chalk.bold(pointer)} resolution failure. Expected ${chalk.magenta(
path.join('/') path.join('/')
)} to be a plain object but it has type "${typeof target}" in \n\n${safeDump(document, { )} to be a plain object but it has type "${typeof target}" in \n\n${dump(document, {
skipInvalid: true, skipInvalid: true,
})}` })}`
); );
@ -69,7 +69,7 @@ export function extractObjectByJsonPointer(
throw new Error( throw new Error(
`JSON Pointer resolution failure. Expected ${chalk.magenta( `JSON Pointer resolution failure. Expected ${chalk.magenta(
pointer pointer
)} to be a plain object in \n\n${safeDump(document, { skipInvalid: true })}` )} to be a plain object in \n\n${dump(document, { skipInvalid: true })}`
); );
} }

View file

@ -9,7 +9,7 @@
import fs from 'fs/promises'; import fs from 'fs/promises';
import { basename, extname } from 'path'; import { basename, extname } from 'path';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import chalk from 'chalk'; import chalk from 'chalk';
import { logger } from '../logger'; import { logger } from '../logger';
import { isPlainObjectType } from './is_plain_object_type'; import { isPlainObjectType } from './is_plain_object_type';
@ -43,15 +43,32 @@ async function readFile(filePath: string): Promise<unknown> {
} }
async function readYamlFile(filePath: string): Promise<Record<string, unknown>> { async function readYamlFile(filePath: string): Promise<Record<string, unknown>> {
// Typing load's result to Record<string, unknown> is optimistic as we can't be sure const fileContent = await fs.readFile(filePath, { encoding: 'utf8' });
// there is object inside a yaml file. We don't have this validation layer so far const maybeObject = load(fileContent);
// but using JSON Schemas here should mitigate this problem.
return safeLoad(await fs.readFile(filePath, { encoding: 'utf8' })); if (!isPlainObjectType(maybeObject)) {
throw new Error(
`Expected ${chalk.bold(filePath)} to contain an object but got ${typeof maybeObject}`
);
}
return maybeObject;
} }
async function readJsonFile(filePath: string): Promise<Record<string, unknown>> { async function readJsonFile(filePath: string): Promise<Record<string, unknown>> {
// Typing load's result to Record<string, unknown> is optimistic as we can't be sure const fileContent = await fs.readFile(filePath, { encoding: 'utf8' });
// there is object inside a yaml file. We don't have this validation layer so far
// but using JSON Schemas here should mitigate this problem. try {
return await JSON.parse(await fs.readFile(filePath, { encoding: 'utf8' })); const maybeObject = JSON.parse(fileContent);
if (!isPlainObjectType(maybeObject)) {
throw new Error(
`Expected ${chalk.bold(filePath)} to contain an object but got ${typeof maybeObject}`
);
}
return maybeObject;
} catch {
throw new Error(`Unable to parse ${chalk.bold(filePath)}`);
}
} }

View file

@ -8,7 +8,7 @@
*/ */
import fs from 'fs/promises'; import fs from 'fs/promises';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { dirname } from 'path'; import { dirname } from 'path';
export async function writeYamlDocument(filePath: string, document: unknown): Promise<void> { export async function writeYamlDocument(filePath: string, document: unknown): Promise<void> {
@ -26,14 +26,14 @@ function stringifyToYaml(document: unknown): string {
try { try {
// Disable YAML Anchors https://yaml.org/spec/1.2.2/#3222-anchors-and-aliases // Disable YAML Anchors https://yaml.org/spec/1.2.2/#3222-anchors-and-aliases
// It makes YAML much more human readable // It makes YAML much more human readable
return safeDump(document, { return dump(document, {
noRefs: true, noRefs: true,
sortKeys: sortYamlKeys, sortKeys: sortYamlKeys,
skipInvalid: true, // Skip invalid types like `undefined` skipInvalid: true, // Skip invalid types like `undefined`
}); });
} catch (e) { } catch (e) {
// Try to stringify with YAML Anchors enabled // Try to stringify with YAML Anchors enabled
return safeDump(document, { noRefs: false, sortKeys: sortYamlKeys, skipInvalid: true }); return dump(document, { noRefs: false, sortKeys: sortYamlKeys, skipInvalid: true });
} }
} }

View file

@ -17,7 +17,7 @@ import {
unlinkSync, unlinkSync,
writeFileSync, writeFileSync,
} from 'fs'; } from 'fs';
import { safeDump, safeLoad } from 'js-yaml'; import { dump, load } from 'js-yaml';
import { OpenAPIV3 } from 'openapi-types'; import { OpenAPIV3 } from 'openapi-types';
import { bundle, BundlerConfig } from '../../src/openapi_bundler'; import { bundle, BundlerConfig } from '../../src/openapi_bundler';
@ -59,7 +59,7 @@ function dumpSpecs(folderPath: string, oasSpecs: Record<string, OpenAPIV3.Docume
for (const [fileName, oasSpec] of Object.entries(oasSpecs)) { for (const [fileName, oasSpec] of Object.entries(oasSpecs)) {
writeFileSync( writeFileSync(
join(folderPath, `${fileName}.schema.yaml`), join(folderPath, `${fileName}.schema.yaml`),
safeDump(oasSpec, { skipInvalid: true }) // Skip invalid types like `undefined` dump(oasSpec, { skipInvalid: true }) // Skip invalid types like `undefined`
); );
} }
} }
@ -70,7 +70,7 @@ export function readBundledSpecs(folderPath: string): Record<string, OpenAPIV3.D
for (const fileName of readdirSync(folderPath)) { for (const fileName of readdirSync(folderPath)) {
const yaml = readFileSync(join(folderPath, fileName), { encoding: 'utf8' }); const yaml = readFileSync(join(folderPath, fileName), { encoding: 'utf8' });
bundledSpecs[fileName] = safeLoad(yaml); bundledSpecs[fileName] = load(yaml) as OpenAPIV3.Document;
} }
return bundledSpecs; return bundledSpecs;

View file

@ -8,7 +8,7 @@
*/ */
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { join } from 'path'; import { join } from 'path';
import { bundleFolder, readBundledSpecs } from './bundle_specs'; import { bundleFolder, readBundledSpecs } from './bundle_specs';
@ -26,7 +26,7 @@ describe('OpenAPI Bundler - specs with multiple modifications', () => {
const [bundledSpec] = Object.values(readBundledSpecs(outputFolderPath)); const [bundledSpec] = Object.values(readBundledSpecs(outputFolderPath));
const expected = safeLoad( const expected = load(
readFileSync(join(folderToBundlePath, 'expected.yaml'), { encoding: 'utf8' }) readFileSync(join(folderToBundlePath, 'expected.yaml'), { encoding: 'utf8' })
); );

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1". * License v3.0 only", or the "Server Side Public License, v 1".
*/ */
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { OpenAPIV3 } from 'openapi-types'; import { OpenAPIV3 } from 'openapi-types';
import { bundleSpecs } from './bundle_specs'; import { bundleSpecs } from './bundle_specs';
import { createOASDocument } from '../create_oas_document'; import { createOASDocument } from '../create_oas_document';
@ -49,8 +49,7 @@ describe('OpenAPI Bundler - circular specs', () => {
}) })
); );
expect(safeDump(bundledSpec.paths['/api/some_api']!.get!.responses['200'])) expect(dump(bundledSpec.paths['/api/some_api']!.get!.responses['200'])).toMatchInlineSnapshot(`
.toMatchInlineSnapshot(`
"content: "content:
application/json: application/json:
schema: &ref_0 schema: &ref_0

View file

@ -17,7 +17,7 @@ import {
unlinkSync, unlinkSync,
writeFileSync, writeFileSync,
} from 'fs'; } from 'fs';
import { safeDump, safeLoad } from 'js-yaml'; import { dump, load } from 'js-yaml';
import { OpenAPIV3 } from 'openapi-types'; import { OpenAPIV3 } from 'openapi-types';
import { merge, MergerConfig } from '../../src/openapi_merger'; import { merge, MergerConfig } from '../../src/openapi_merger';
@ -59,7 +59,7 @@ function dumpSpecs(folderPath: string, oasSpecs: Record<string, OpenAPIV3.Docume
for (const [fileName, oasSpec] of Object.entries(oasSpecs)) { for (const [fileName, oasSpec] of Object.entries(oasSpecs)) {
writeFileSync( writeFileSync(
join(folderPath, `${fileName}.schema.yaml`), join(folderPath, `${fileName}.schema.yaml`),
safeDump(oasSpec, { skipInvalid: true }) dump(oasSpec, { skipInvalid: true })
); );
} }
} }
@ -70,7 +70,7 @@ export function readMergedSpecs(folderPath: string): Record<string, OpenAPIV3.Do
for (const fileName of readdirSync(folderPath)) { for (const fileName of readdirSync(folderPath)) {
const yaml = readFileSync(join(folderPath, fileName), { encoding: 'utf8' }); const yaml = readFileSync(join(folderPath, fileName), { encoding: 'utf8' });
mergedSpecs[fileName] = safeLoad(yaml); mergedSpecs[fileName] = load(yaml);
} }
return mergedSpecs; return mergedSpecs;

View file

@ -5,6 +5,6 @@
}, },
"exclude": ["target/**/*"], "exclude": ["target/**/*"],
"extends": "../../tsconfig.base.json", "extends": "../../tsconfig.base.json",
"include": ["**/*.ts"], "include": ["**/*.ts", "../../typings/**/*"],
"kbn_references": ["@kbn/tooling-log"] "kbn_references": ["@kbn/tooling-log"]
} }

View file

@ -32,7 +32,7 @@ export function readLimits(path: string): Limits {
} }
} }
return yaml ? Yaml.safeLoad(yaml) : {}; return yaml ? Yaml.load(yaml) : {};
} }
export function validateLimitsForAllBundles( export function validateLimitsForAllBundles(
@ -136,6 +136,6 @@ export function updateBundleLimits({
pageLoadAssetSize, pageLoadAssetSize,
}; };
Fs.writeFileSync(limitsPath, Yaml.safeDump(newLimits)); Fs.writeFileSync(limitsPath, Yaml.dump(newLimits));
log.success(`wrote updated limits to ${limitsPath}`); log.success(`wrote updated limits to ${limitsPath}`);
} }

View file

@ -8,7 +8,8 @@
] ]
}, },
"include": [ "include": [
"**/*.ts" "**/*.ts",
"../../typings/**/*"
], ],
"exclude": [ "exclude": [
"**/__fixtures__/**/*", "**/__fixtures__/**/*",

View file

@ -4,7 +4,7 @@ info:
title: Security Solution Endpoint Exceptions API (Elastic Cloud and self-hosted) title: Security Solution Endpoint Exceptions API (Elastic Cloud and self-hosted)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
@ -369,7 +369,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -505,7 +505,7 @@ components:
type: string type: string
ExceptionListHumanId: ExceptionListHumanId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
description: 'Human readable string identifier, e.g. `trusted-linux-processes`' description: Human readable string identifier, e.g. `trusted-linux-processes`
ExceptionListId: ExceptionListId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
ExceptionListItem: ExceptionListItem:

View file

@ -4,7 +4,7 @@ info:
title: Security Solution Endpoint Exceptions API (Elastic Cloud Serverless) title: Security Solution Endpoint Exceptions API (Elastic Cloud Serverless)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
@ -369,7 +369,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -505,7 +505,7 @@ components:
type: string type: string
ExceptionListHumanId: ExceptionListHumanId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
description: 'Human readable string identifier, e.g. `trusted-linux-processes`' description: Human readable string identifier, e.g. `trusted-linux-processes`
ExceptionListId: ExceptionListId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
ExceptionListItem: ExceptionListItem:

View file

@ -7,14 +7,14 @@ info:
title: Security Solution Exceptions API (Elastic Cloud and self-hosted) title: Security Solution Exceptions API (Elastic Cloud and self-hosted)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
port: port:
default: '5601' default: '5601'
paths: paths:
'/api/detection_engine/rules/{id}/exceptions': /api/detection_engine/rules/{id}/exceptions:
post: post:
description: Create exception items that apply to a single detection rule. description: Create exception items that apply to a single detection rule.
operationId: CreateRuleExceptionListItems operationId: CreateRuleExceptionListItems
@ -584,7 +584,7 @@ paths:
required: false required: false
schema: schema:
type: string type: string
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -1146,7 +1146,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -1490,7 +1490,7 @@ components:
type: string type: string
ExceptionListHumanId: ExceptionListHumanId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
description: 'Human readable string identifier, e.g. `trusted-linux-processes`' description: Human readable string identifier, e.g. `trusted-linux-processes`
ExceptionListId: ExceptionListId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
ExceptionListItem: ExceptionListItem:

View file

@ -7,14 +7,14 @@ info:
title: Security Solution Exceptions API (Elastic Cloud Serverless) title: Security Solution Exceptions API (Elastic Cloud Serverless)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
port: port:
default: '5601' default: '5601'
paths: paths:
'/api/detection_engine/rules/{id}/exceptions': /api/detection_engine/rules/{id}/exceptions:
post: post:
description: Create exception items that apply to a single detection rule. description: Create exception items that apply to a single detection rule.
operationId: CreateRuleExceptionListItems operationId: CreateRuleExceptionListItems
@ -584,7 +584,7 @@ paths:
required: false required: false
schema: schema:
type: string type: string
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -1146,7 +1146,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -1490,7 +1490,7 @@ components:
type: string type: string
ExceptionListHumanId: ExceptionListHumanId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
description: 'Human readable string identifier, e.g. `trusted-linux-processes`' description: Human readable string identifier, e.g. `trusted-linux-processes`
ExceptionListId: ExceptionListId:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
ExceptionListItem: ExceptionListItem:

View file

@ -1,10 +1,10 @@
openapi: 3.0.3 openapi: 3.0.3
info: info:
description: 'Lists API allows you to manage lists of keywords, IPs or IP ranges items.' description: Lists API allows you to manage lists of keywords, IPs or IP ranges items.
title: Security Solution Lists API (Elastic Cloud and self-hosted) title: Security Solution Lists API (Elastic Cloud and self-hosted)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
@ -375,7 +375,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -622,7 +622,7 @@ paths:
- Security Solution Lists API - Security Solution Lists API
/api/lists/items: /api/lists/items:
delete: delete:
description: 'Delete a list item using its `id`, or its `list_id` and `value` fields.' description: Delete a list item using its `id`, or its `list_id` and `value` fields.
operationId: DeleteListItem operationId: DeleteListItem
parameters: parameters:
- description: Required if `list_id` and `value` are not specified - description: Required if `list_id` and `value` are not specified
@ -1078,7 +1078,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -1562,5 +1562,5 @@ components:
security: security:
- BasicAuth: [] - BasicAuth: []
tags: tags:
- description: 'Lists API allows you to manage lists of keywords, IPs or IP ranges items.' - description: Lists API allows you to manage lists of keywords, IPs or IP ranges items.
name: Security Solution Lists API name: Security Solution Lists API

View file

@ -1,10 +1,10 @@
openapi: 3.0.3 openapi: 3.0.3
info: info:
description: 'Lists API allows you to manage lists of keywords, IPs or IP ranges items.' description: Lists API allows you to manage lists of keywords, IPs or IP ranges items.
title: Security Solution Lists API (Elastic Cloud Serverless) title: Security Solution Lists API (Elastic Cloud Serverless)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
@ -375,7 +375,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -622,7 +622,7 @@ paths:
- Security Solution Lists API - Security Solution Lists API
/api/lists/items: /api/lists/items:
delete: delete:
description: 'Delete a list item using its `id`, or its `list_id` and `value` fields.' description: Delete a list item using its `id`, or its `list_id` and `value` fields.
operationId: DeleteListItem operationId: DeleteListItem
parameters: parameters:
- description: Required if `list_id` and `value` are not specified - description: Required if `list_id` and `value` are not specified
@ -1078,7 +1078,7 @@ paths:
required: false required: false
schema: schema:
$ref: '#/components/schemas/NonEmptyString' $ref: '#/components/schemas/NonEmptyString'
- description: 'Determines the sort order, which can be `desc` or `asc`' - description: Determines the sort order, which can be `desc` or `asc`
in: query in: query
name: sort_order name: sort_order
required: false required: false
@ -1562,5 +1562,5 @@ components:
security: security:
- BasicAuth: [] - BasicAuth: []
tags: tags:
- description: 'Lists API allows you to manage lists of keywords, IPs or IP ranges items.' - description: Lists API allows you to manage lists of keywords, IPs or IP ranges items.
name: Security Solution Lists API name: Security Solution Lists API

View file

@ -45,9 +45,9 @@ export const getAllFtrConfigsAndManifests = () => {
const allFtrConfigs: string[] = []; const allFtrConfigs: string[] = [];
for (const manifestRelPath of manifestPaths.all) { for (const manifestRelPath of manifestPaths.all) {
const manifest: FtrConfigsManifest = JsYaml.safeLoad( const manifest = JsYaml.load(
Fs.readFileSync(Path.resolve(REPO_ROOT, manifestRelPath), 'utf8') Fs.readFileSync(Path.resolve(REPO_ROOT, manifestRelPath), 'utf8')
); ) as FtrConfigsManifest;
const ftrConfigsInManifest = [ const ftrConfigsInManifest = [
Object.values(manifest.enabled ?? []), Object.values(manifest.enabled ?? []),

View file

@ -20,7 +20,7 @@ var allManifestPaths = Object.values(manifestsSource).flat();
try { try {
for (var manifestRelPath of allManifestPaths) { for (var manifestRelPath of allManifestPaths) {
var manifest = yaml.safeLoad(fs.readFileSync(manifestRelPath, 'utf8')); var manifest = yaml.load(fs.readFileSync(manifestRelPath, 'utf8'));
if (manifest.enabled) { if (manifest.enabled) {
manifest.enabled.forEach(function (x) { manifest.enabled.forEach(function (x) {
console.log(x); console.log(x);

View file

@ -15,7 +15,7 @@ import Del from 'del';
import * as Rx from 'rxjs'; import * as Rx from 'rxjs';
import { map, filter, take } from 'rxjs'; import { map, filter, take } from 'rxjs';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { getConfigFromFiles } from '@kbn/config'; import { getConfigFromFiles } from '@kbn/config';
const configFileLogConsole = follow( const configFileLogConsole = follow(
@ -65,7 +65,7 @@ function createConfigManager(configPath: string) {
return { return {
modify(fn: (input: Record<string, any>) => Record<string, any>) { modify(fn: (input: Record<string, any>) => Record<string, any>) {
const oldContent = getConfigFromFiles([configPath]); const oldContent = getConfigFromFiles([configPath]);
const yaml = safeDump(fn(oldContent)); const yaml = dump(fn(oldContent));
Fs.writeFileSync(configPath, yaml); Fs.writeFileSync(configPath, yaml);
}, },
}; };

View file

@ -11,12 +11,12 @@ import crypto from 'crypto';
import { join } from 'path'; import { join } from 'path';
import { get } from 'lodash'; import { get } from 'lodash';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { getConfigDirectory } from '@kbn/utils'; import { getConfigDirectory } from '@kbn/utils';
export class EncryptionConfig { export class EncryptionConfig {
#config = safeLoad(readFileSync(join(getConfigDirectory(), 'kibana.yml'))); #config = load(readFileSync(join(getConfigDirectory(), 'kibana.yml')));
#encryptionKeyPaths = [ #encryptionKeyPaths = [
'xpack.encryptedSavedObjects.encryptionKey', 'xpack.encryptedSavedObjects.encryptionKey',
'xpack.reporting.encryptionKey', 'xpack.reporting.encryptionKey',

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1". * License v3.0 only", or the "Server Side Public License, v 1".
*/ */
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
import { interactive } from './interactive'; import { interactive } from './interactive';
import { Logger } from '../cli/logger'; import { Logger } from '../cli/logger';
@ -33,7 +33,7 @@ export async function generate(encryptionConfig, command) {
await interactive(keys, encryptionConfig.docs({ comment: true }), logger); await interactive(keys, encryptionConfig.docs({ comment: true }), logger);
} else { } else {
if (!command.quiet) logger.log('Settings:'); if (!command.quiet) logger.log('Settings:');
logger.log(safeDump(keys)); logger.log(dump(keys));
} }
} }
} }

View file

@ -11,7 +11,7 @@ import { writeFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { confirm, question } from '../cli/keystore/utils'; import { confirm, question } from '../cli/keystore/utils';
import { getConfigDirectory } from '@kbn/utils'; import { getConfigDirectory } from '@kbn/utils';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
export async function interactive(keys, docs, logger) { export async function interactive(keys, docs, logger) {
const settings = Object.keys(keys); const settings = Object.keys(keys);
@ -37,10 +37,10 @@ export async function interactive(keys, docs, logger) {
`What filename should be used for the sample Kibana config file? [${defaultSaveLocation}])` `What filename should be used for the sample Kibana config file? [${defaultSaveLocation}])`
); );
const saveLocation = promptedSaveLocation || defaultSaveLocation; const saveLocation = promptedSaveLocation || defaultSaveLocation;
writeFileSync(saveLocation, docs + safeDump(setKeys)); writeFileSync(saveLocation, docs + dump(setKeys));
logger.log(`Wrote configuration to ${saveLocation}`); logger.log(`Wrote configuration to ${saveLocation}`);
} else { } else {
logger.log('\nSettings:'); logger.log('\nSettings:');
logger.log(safeDump(setKeys)); logger.log(dump(setKeys));
} }
} }

View file

@ -11,7 +11,7 @@ import Fsp from 'fs/promises';
import Path from 'path'; import Path from 'path';
import JSON5 from 'json5'; import JSON5 from 'json5';
import { safeLoad, safeDump } from 'js-yaml'; import { load, dump } from 'js-yaml';
import { asyncForEach } from '@kbn/std'; import { asyncForEach } from '@kbn/std';
import { ToolingLog } from '@kbn/tooling-log'; import { ToolingLog } from '@kbn/tooling-log';
@ -88,10 +88,10 @@ export async function bundleFleetPackages(pkgDir: string, log: ToolingLog, confi
return; return;
} }
const manifestYml = await safeLoad(manifestEntry.buffer.toString('utf8')); const manifestYml = await load(manifestEntry.buffer.toString('utf8'));
manifestYml.version = stackVersion; manifestYml.version = stackVersion;
const newManifestYml = safeDump(manifestYml); const newManifestYml = dump(manifestYml);
manifestEntry.buffer = Buffer.from(newManifestYml, 'utf8'); manifestEntry.buffer = Buffer.from(newManifestYml, 'utf8');
// Update all paths to use the new version // Update all paths to use the new version

View file

@ -9,7 +9,7 @@
import { readFileSync, writeFileSync } from 'fs'; import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path'; import { resolve } from 'path';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { Build, Config, mkdirp } from '../../lib'; import { Build, Config, mkdirp } from '../../lib';
export async function createOSPackageKibanaYML(config: Config, build: Build) { export async function createOSPackageKibanaYML(config: Config, build: Build) {
@ -25,7 +25,7 @@ export async function createOSPackageKibanaYML(config: Config, build: Build) {
[/#pid.file:.*/g, 'pid.file: /run/kibana/kibana.pid'], [/#pid.file:.*/g, 'pid.file: /run/kibana/kibana.pid'],
[ [
/#logging.appenders.default:.*kibana\.log\n/gs, /#logging.appenders.default:.*kibana\.log\n/gs,
safeDump({ dump({
logging: { logging: {
appenders: { appenders: {
file: { file: {

View file

@ -142,7 +142,7 @@ async function rewriteFile(ymlPath: string, log: ToolingLog) {
let file = await readFile(resolve(REPO_ROOT, ymlPath), 'utf-8'); let file = await readFile(resolve(REPO_ROOT, ymlPath), 'utf-8');
log.info('Loading: ' + ymlPath); log.info('Loading: ' + ymlPath);
const doc = yaml.safeLoad(file); const doc = yaml.load(file);
if (!doc.steps) { if (!doc.steps) {
log.info('No steps, skipping: ' + ymlPath); log.info('No steps, skipping: ' + ymlPath);
@ -153,7 +153,7 @@ async function rewriteFile(ymlPath: string, log: ToolingLog) {
if (isQueueTargetingRule(step) && !step.agents.queue.startsWith('kb-static')) { if (isQueueTargetingRule(step) && !step.agents.queue.startsWith('kb-static')) {
log.info('Rewriting: ' + ymlPath, step); log.info('Rewriting: ' + ymlPath, step);
file = editYmlInPlace(file, ['agents:', `queue: ${step.agents.queue}`], () => { file = editYmlInPlace(file, ['agents:', `queue: ${step.agents.queue}`], () => {
return yaml.safeDump({ agents: getFullAgentTargetingRule(step.agents.queue) }).split('\n'); return yaml.dump({ agents: getFullAgentTargetingRule(step.agents.queue) }).split('\n');
}); });
} }
} }

View file

@ -121,6 +121,7 @@ export const IGNORE_DIRECTORY_GLOBS = [
'x-pack/dev-tools', 'x-pack/dev-tools',
'packages/kbn-optimizer/src/__fixtures__/mock_repo/x-pack', 'packages/kbn-optimizer/src/__fixtures__/mock_repo/x-pack',
'typings/*', 'typings/*',
'typings/**/*',
]; ];
/** /**

View file

@ -9,13 +9,13 @@
import stylelint from 'stylelint'; import stylelint from 'stylelint';
import path from 'path'; import path from 'path';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import fs from 'fs'; import fs from 'fs';
import { createFailError } from '@kbn/dev-cli-errors'; import { createFailError } from '@kbn/dev-cli-errors';
// load the include globs from .stylelintrc and convert them to regular expressions for filtering files // load the include globs from .stylelintrc and convert them to regular expressions for filtering files
const stylelintPath = path.resolve(__dirname, '..', '..', '..', '.stylelintrc'); const stylelintPath = path.resolve(__dirname, '..', '..', '..', '.stylelintrc');
const styleLintConfig = safeLoad(fs.readFileSync(stylelintPath)); const styleLintConfig = load(fs.readFileSync(stylelintPath));
/** /**
* Lints a list of files with eslint. eslint reports are written to the log * Lints a list of files with eslint. eslint reports are written to the log

View file

@ -6,6 +6,7 @@
"include": [ "include": [
"**/*.js", "**/*.js",
"**/*.ts", "**/*.ts",
"../../typings/**/*"
], ],
"exclude": [ "exclude": [
"target/**/*", "target/**/*",

View file

@ -165,10 +165,12 @@ describe('KibanaConfigWriter', () => {
serviceAccountToken: { name: 'some-token', value: 'some-value' }, serviceAccountToken: { name: 'some-token', value: 'some-value' },
}) })
).rejects.toMatchInlineSnapshot(` ).rejects.toMatchInlineSnapshot(`
[YAMLException: duplicated mapping key at line 2, column 1: [YAMLException: duplicated mapping key (2:1)
foo: baz
^] 1 | foo: bar
`); 2 | foo: baz
-----^]
`);
expect(mockWriteFile).not.toHaveBeenCalled(); expect(mockWriteFile).not.toHaveBeenCalled();
}); });

View file

@ -118,14 +118,14 @@ export class KibanaConfigWriter {
); );
const existingCommentedConfig = KibanaConfigWriter.commentOutKibanaConfig(existingConfig.raw); const existingCommentedConfig = KibanaConfigWriter.commentOutKibanaConfig(existingConfig.raw);
configToWrite = `${existingCommentedConfig}\n\n# This section was automatically generated during setup.\n${yaml.safeDump( configToWrite = `${existingCommentedConfig}\n\n# This section was automatically generated during setup.\n${yaml.dump(
{ ...existingConfig.parsed, ...config }, { ...existingConfig.parsed, ...config },
{ flowLevel: 1 } { flowLevel: 1 }
)}\n`; )}\n`;
} else { } else {
configToWrite = `${ configToWrite = `${
existingConfig.raw existingConfig.raw
}\n\n# This section was automatically generated during setup.\n${yaml.safeDump(config, { }\n\n# This section was automatically generated during setup.\n${yaml.dump(config, {
flowLevel: 1, flowLevel: 1,
})}\n`; })}\n`;
} }
@ -172,7 +172,7 @@ export class KibanaConfigWriter {
let parsedConfig: Record<string, unknown>; let parsedConfig: Record<string, unknown>;
try { try {
parsedConfig = getFlattenedObject(yaml.safeLoad(rawConfig) ?? {}); parsedConfig = getFlattenedObject(yaml.load(rawConfig) ?? {});
} catch (err) { } catch (err) {
this.logger.error(`Failed to parse configuration file: ${getDetailedErrorMessage(err)}.`); this.logger.error(`Failed to parse configuration file: ${getDetailedErrorMessage(err)}.`);
throw err; throw err;

View file

@ -8,7 +8,7 @@
*/ */
import { accessSync, constants, readFileSync, statSync } from 'fs'; import { accessSync, constants, readFileSync, statSync } from 'fs';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { dirname, join } from 'path'; import { dirname, join } from 'path';
import { Observable, firstValueFrom } from 'rxjs'; import { Observable, firstValueFrom } from 'rxjs';
import { ensureDeepObject } from '@kbn/std'; import { ensureDeepObject } from '@kbn/std';
@ -55,7 +55,7 @@ export async function readTelemetryFile<T extends object>(
try { try {
if (isFileReadable(configPath)) { if (isFileReadable(configPath)) {
const yaml = readFileSync(configPath); const yaml = readFileSync(configPath);
const data = safeLoad(yaml.toString()); const data = load(yaml.toString());
// don't bother returning empty objects // don't bother returning empty objects
if (Object.keys(data).length) { if (Object.keys(data).length) {

12
typings/@types/js-yaml/index.d.ts vendored Normal file
View file

@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
declare namespace jsyaml {
function load<T = any>(str: string, opts?: jsyaml.LoadOptions): T;
}

View file

@ -14,7 +14,7 @@ import { DEFAULTS } from '../constants';
export async function readConfig(filePath: string): Promise<PartialConfig> { export async function readConfig(filePath: string): Promise<PartialConfig> {
const data = await promises.readFile(filePath); const data = await promises.readFile(filePath);
const decodedPartialConfig = PartialConfigRT.decode(yaml.safeLoad(data.toString())); const decodedPartialConfig = PartialConfigRT.decode(yaml.load(data.toString()));
if (isLeft(decodedPartialConfig)) { if (isLeft(decodedPartialConfig)) {
throw new Error( throw new Error(
`Could not validate config: ${PathReporter.report(decodedPartialConfig).join('\n')}` `Could not validate config: ${PathReporter.report(decodedPartialConfig).join('\n')}`

View file

@ -4,7 +4,7 @@ info:
title: Security AI Assistant API (Elastic Cloud & self-hosted) title: Security AI Assistant API (Elastic Cloud & self-hosted)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
@ -309,7 +309,7 @@ paths:
tags: tags:
- Security AI Assistant API - Security AI Assistant API
- Conversations API - Conversations API
'/api/security_ai_assistant/current_user/conversations/{id}': /api/security_ai_assistant/current_user/conversations/{id}:
delete: delete:
description: Delete an existing conversation using the conversation ID. description: Delete an existing conversation using the conversation ID.
operationId: DeleteConversation operationId: DeleteConversation
@ -1213,13 +1213,13 @@ components:
type: object type: object
properties: properties:
traceId: traceId:
description: 'Could be any string, not necessarily a UUID' description: Could be any string, not necessarily a UUID
type: string type: string
transactionId: transactionId:
description: 'Could be any string, not necessarily a UUID' description: Could be any string, not necessarily a UUID
type: string type: string
User: User:
description: 'Could be any string, not necessarily a UUID' description: Could be any string, not necessarily a UUID
type: object type: object
properties: properties:
id: id:

View file

@ -4,7 +4,7 @@ info:
title: Security AI Assistant API (Elastic Cloud Serverless) title: Security AI Assistant API (Elastic Cloud Serverless)
version: '2023-10-31' version: '2023-10-31'
servers: servers:
- url: 'http://{kibana_host}:{port}' - url: http://{kibana_host}:{port}
variables: variables:
kibana_host: kibana_host:
default: localhost default: localhost
@ -309,7 +309,7 @@ paths:
tags: tags:
- Security AI Assistant API - Security AI Assistant API
- Conversations API - Conversations API
'/api/security_ai_assistant/current_user/conversations/{id}': /api/security_ai_assistant/current_user/conversations/{id}:
delete: delete:
description: Delete an existing conversation using the conversation ID. description: Delete an existing conversation using the conversation ID.
operationId: DeleteConversation operationId: DeleteConversation
@ -1213,13 +1213,13 @@ components:
type: object type: object
properties: properties:
traceId: traceId:
description: 'Could be any string, not necessarily a UUID' description: Could be any string, not necessarily a UUID
type: string type: string
transactionId: transactionId:
description: 'Could be any string, not necessarily a UUID' description: Could be any string, not necessarily a UUID
type: string type: string
User: User:
description: 'Could be any string, not necessarily a UUID' description: Could be any string, not necessarily a UUID
type: object type: object
properties: properties:
id: id:

View file

@ -48,7 +48,7 @@ export function getSelectorsAndResponsesFromYaml(configuration: string): {
let responses: Response[] = []; let responses: Response[] = [];
try { try {
const result = yaml.safeLoad(configuration); const result = yaml.load(configuration);
if (result) { if (result) {
// iterate selector/response types // iterate selector/response types
@ -107,5 +107,5 @@ export function getYamlFromSelectorsAndResponses(selectors: Selector[], response
return current; return current;
}, schema); }, schema);
return yaml.safeDump(schema); return yaml.dump(schema);
} }

View file

@ -44,7 +44,7 @@ describe('<ControlGeneralView />', () => {
const configuration = input?.vars?.configuration?.value; const configuration = input?.vars?.configuration?.value;
try { try {
const json = yaml.safeLoad(configuration); const json = yaml.load(configuration);
expect(json.file.selectors.length).toBe(getAllByTestId('cloud-defend-selector').length); expect(json.file.selectors.length).toBe(getAllByTestId('cloud-defend-selector').length);
expect(json.file.responses.length).toBe(getAllByTestId('cloud-defend-file-response').length); expect(json.file.responses.length).toBe(getAllByTestId('cloud-defend-file-response').length);
@ -69,7 +69,7 @@ describe('<ControlGeneralView />', () => {
const configuration = input?.vars?.configuration?.value; const configuration = input?.vars?.configuration?.value;
try { try {
const json = yaml.safeLoad(configuration); const json = yaml.load(configuration);
expect(json.file.selectors.length).toBe(getAllByTestId('cloud-defend-selector').length); expect(json.file.selectors.length).toBe(getAllByTestId('cloud-defend-selector').length);
} catch (err) { } catch (err) {
@ -91,7 +91,7 @@ describe('<ControlGeneralView />', () => {
const configuration = input?.vars?.configuration?.value; const configuration = input?.vars?.configuration?.value;
try { try {
const json = yaml.safeLoad(configuration); const json = yaml.load(configuration);
expect(json.file.responses.length).toBe(getAllByTestId('cloud-defend-file-response').length); expect(json.file.responses.length).toBe(getAllByTestId('cloud-defend-file-response').length);
} catch (err) { } catch (err) {
@ -113,7 +113,7 @@ describe('<ControlGeneralView />', () => {
const configuration = input?.vars?.configuration?.value; const configuration = input?.vars?.configuration?.value;
try { try {
const json = yaml.safeLoad(configuration); const json = yaml.load(configuration);
expect(json.process.responses.length).toBe( expect(json.process.responses.length).toBe(
getAllByTestId('cloud-defend-process-response').length getAllByTestId('cloud-defend-process-response').length
@ -166,7 +166,7 @@ describe('<ControlGeneralView />', () => {
const configuration = input?.vars?.configuration?.value; const configuration = input?.vars?.configuration?.value;
try { try {
const json = yaml.safeLoad(configuration); const json = yaml.load(configuration);
expect(json.file.responses[0].match).toHaveLength(1); expect(json.file.responses[0].match).toHaveLength(1);
} catch (err) { } catch (err) {
@ -205,7 +205,7 @@ describe('<ControlGeneralView />', () => {
const configuration = input?.vars?.configuration?.value; const configuration = input?.vars?.configuration?.value;
try { try {
const json = yaml.safeLoad(configuration); const json = yaml.load(configuration);
expect(json.file.selectors).toHaveLength(4); expect(json.file.selectors).toHaveLength(4);
expect(json.file.selectors[3].name).toEqual(json.file.selectors[0].name + '1'); expect(json.file.selectors[3].name).toEqual(json.file.selectors[0].name + '1');

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import type { safeDump } from 'js-yaml'; import type { dump } from 'js-yaml';
import type { FullAgentConfigMap } from '../types/models/agent_cm'; import type { FullAgentConfigMap } from '../types/models/agent_cm';
@ -13,7 +13,7 @@ const CM_KEYS_ORDER = ['apiVersion', 'kind', 'metadata', 'data'];
export const fullAgentConfigMapToYaml = ( export const fullAgentConfigMapToYaml = (
policy: FullAgentConfigMap, policy: FullAgentConfigMap,
toYaml: typeof safeDump toYaml: typeof dump
): string => { ): string => {
return toYaml(policy, { return toYaml(policy, {
skipInvalid: true, skipInvalid: true,

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import type { safeDump } from 'js-yaml'; import type { dump } from 'js-yaml';
import type { FullAgentPolicy } from '../types'; import type { FullAgentPolicy } from '../types';
@ -30,7 +30,7 @@ const POLICY_KEYS_ORDER = [
export const fullAgentPolicyToYaml = ( export const fullAgentPolicyToYaml = (
policy: FullAgentPolicy, policy: FullAgentPolicy,
toYaml: typeof safeDump, toYaml: typeof dump,
apiKey?: string apiKey?: string
): string => { ): string => {
const yaml = toYaml(policy, { const yaml = toYaml(policy, {

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { import {
getAllowedOutputTypeForPolicy, getAllowedOutputTypeForPolicy,
@ -56,13 +56,13 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
it('returns true when reserved key is present', () => { it('returns true when reserved key is present', () => {
const configYml = `queue.mem.events: 1000`; const configYml = `queue.mem.events: 1000`;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true);
}); });
it('returns false when no reserved key is present', () => { it('returns false when no reserved key is present', () => {
const configYml = `some.random.key: 1000`; const configYml = `some.random.key: 1000`;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false);
}); });
}); });
@ -74,7 +74,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
events: 1000 events: 1000
`; `;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true);
}); });
it('returns false when no reserved key is present', () => { it('returns false when no reserved key is present', () => {
@ -84,7 +84,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
key: 1000 key: 1000
`; `;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false);
}); });
}); });
@ -92,13 +92,13 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
it('returns true when reserved key is present', () => { it('returns true when reserved key is present', () => {
const configYml = `bulk_max_size`; const configYml = `bulk_max_size`;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true);
}); });
it('returns false when no reserved key is present', () => { it('returns false when no reserved key is present', () => {
const configYml = `just a string`; const configYml = `just a string`;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false);
}); });
}); });
@ -106,7 +106,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
it('returns false when reserved key is present only in a comment', () => { it('returns false when reserved key is present only in a comment', () => {
const configYml = `true`; const configYml = `true`;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false);
}); });
}); });
@ -114,7 +114,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
it('returns false when YML is empty', () => { it('returns false when YML is empty', () => {
const configYml = ``; const configYml = ``;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false); expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false);
}); });
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { installationStatuses } from '../constants'; import { installationStatuses } from '../constants';
import type { PackageInfo, NewPackagePolicy, RegistryPolicyTemplate } from '../types'; import type { PackageInfo, NewPackagePolicy, RegistryPolicyTemplate } from '../types';
@ -380,13 +380,13 @@ describe('Fleet - validatePackagePolicy()', () => {
}; };
it('returns no errors for valid package policy', () => { it('returns no errors for valid package policy', () => {
expect(validatePackagePolicy(validPackagePolicy, mockPackage, safeLoad)).toEqual( expect(validatePackagePolicy(validPackagePolicy, mockPackage, load)).toEqual(
noErrorsValidationResults noErrorsValidationResults
); );
}); });
it('returns errors for invalid package policy', () => { it('returns errors for invalid package policy', () => {
expect(validatePackagePolicy(invalidPackagePolicy, mockPackage, safeLoad)).toEqual({ expect(validatePackagePolicy(invalidPackagePolicy, mockPackage, load)).toEqual({
name: ['Name is required'], name: ['Name is required'],
description: null, description: null,
namespace: null, namespace: null,
@ -433,11 +433,7 @@ describe('Fleet - validatePackagePolicy()', () => {
enabled: false, enabled: false,
})); }));
expect( expect(
validatePackagePolicy( validatePackagePolicy({ ...validPackagePolicy, inputs: disabledInputs }, mockPackage, load)
{ ...validPackagePolicy, inputs: disabledInputs },
mockPackage,
safeLoad
)
).toEqual(noErrorsValidationResults); ).toEqual(noErrorsValidationResults);
}); });
@ -454,7 +450,7 @@ describe('Fleet - validatePackagePolicy()', () => {
validatePackagePolicy( validatePackagePolicy(
{ ...invalidPackagePolicy, inputs: inputsWithDisabledStreams }, { ...invalidPackagePolicy, inputs: inputsWithDisabledStreams },
mockPackage, mockPackage,
safeLoad load
) )
).toEqual({ ).toEqual({
name: ['Name is required'], name: ['Name is required'],
@ -507,7 +503,7 @@ describe('Fleet - validatePackagePolicy()', () => {
...mockPackage, ...mockPackage,
policy_templates: undefined, policy_templates: undefined,
}, },
safeLoad load
) )
).toEqual({ ).toEqual({
name: null, name: null,
@ -523,7 +519,7 @@ describe('Fleet - validatePackagePolicy()', () => {
...mockPackage, ...mockPackage,
policy_templates: [], policy_templates: [],
}, },
safeLoad load
) )
).toEqual({ ).toEqual({
name: null, name: null,
@ -542,7 +538,7 @@ describe('Fleet - validatePackagePolicy()', () => {
...mockPackage, ...mockPackage,
policy_templates: [{} as RegistryPolicyTemplate], policy_templates: [{} as RegistryPolicyTemplate],
}, },
safeLoad load
) )
).toEqual({ ).toEqual({
name: null, name: null,
@ -558,7 +554,7 @@ describe('Fleet - validatePackagePolicy()', () => {
...mockPackage, ...mockPackage,
policy_templates: [{ inputs: [] } as unknown as RegistryPolicyTemplate], policy_templates: [{ inputs: [] } as unknown as RegistryPolicyTemplate],
}, },
safeLoad load
) )
).toEqual({ ).toEqual({
name: null, name: null,
@ -595,7 +591,7 @@ describe('Fleet - validatePackagePolicy()', () => {
], ],
}, },
mockPackage, mockPackage,
safeLoad load
) )
).toEqual({ ).toEqual({
name: null, name: null,
@ -725,7 +721,7 @@ describe('Fleet - validatePackagePolicy()', () => {
}, },
], ],
}, },
safeLoad load
) )
).toEqual({ ).toEqual({
description: null, description: null,
@ -756,7 +752,7 @@ describe('Fleet - validatePackagePolicy()', () => {
validatePackagePolicy( validatePackagePolicy(
INVALID_AWS_POLICY as NewPackagePolicy, INVALID_AWS_POLICY as NewPackagePolicy,
AWS_PACKAGE as unknown as PackageInfo, AWS_PACKAGE as unknown as PackageInfo,
safeLoad load
) )
).toMatchSnapshot(); ).toMatchSnapshot();
}); });
@ -767,7 +763,7 @@ describe('Fleet - validatePackagePolicy()', () => {
validatePackagePolicy( validatePackagePolicy(
VALID_AWS_POLICY as NewPackagePolicy, VALID_AWS_POLICY as NewPackagePolicy,
AWS_PACKAGE as unknown as PackageInfo, AWS_PACKAGE as unknown as PackageInfo,
safeLoad load
) )
) )
).toBe(false); ).toBe(false);
@ -888,7 +884,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'integer', type: 'integer',
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toEqual(['Invalid integer']); expect(res).toEqual(['Invalid integer']);
@ -905,7 +901,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'integer', type: 'integer',
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toBeNull(); expect(res).toBeNull();
@ -923,7 +919,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
multi: true, multi: true,
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toEqual(['Invalid integer']); expect(res).toEqual(['Invalid integer']);
@ -941,7 +937,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
multi: true, multi: true,
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toBeNull(); expect(res).toBeNull();
@ -964,7 +960,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
], ],
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toEqual(['Invalid value for select type']); expect(res).toEqual(['Invalid value for select type']);
@ -985,7 +981,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
], ],
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toEqual(['Invalid value for select type']); expect(res).toEqual(['Invalid value for select type']);
@ -1006,7 +1002,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
], ],
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toBeNull(); expect(res).toBeNull();
@ -1027,7 +1023,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
], ],
}, },
'myvariable', 'myvariable',
safeLoad load
); );
expect(res).toBeNull(); expect(res).toBeNull();
@ -1043,7 +1039,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
secret: true, secret: true,
}, },
'secret_variable', 'secret_variable',
safeLoad load
); );
expect(res).toBeNull(); expect(res).toBeNull();
@ -1059,7 +1055,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
secret: true, secret: true,
}, },
'secret_variable', 'secret_variable',
safeLoad load
); );
expect(res).toEqual(['Secret reference is invalid, id must be a string']); expect(res).toEqual(['Secret reference is invalid, id must be a string']);
@ -1075,7 +1071,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
secret: true, secret: true,
}, },
'secret_variable', 'secret_variable',
safeLoad load
); );
expect(res).toEqual(['Secret reference is invalid, id must be a string']); expect(res).toEqual(['Secret reference is invalid, id must be a string']);
@ -1096,7 +1092,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'text', type: 'text',
}, },
'data_stream.dataset', 'data_stream.dataset',
safeLoad, load,
'input' 'input'
); );
}; };
@ -1142,7 +1138,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'text', type: 'text',
}, },
'data_stream.dataset', 'data_stream.dataset',
safeLoad, load,
'input' 'input'
); );
@ -1160,7 +1156,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'text', type: 'text',
}, },
'data_stream.dataset', 'data_stream.dataset',
safeLoad, load,
'integration' 'integration'
); );
@ -1178,7 +1174,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'text', type: 'text',
}, },
'test_field', 'test_field',
safeLoad, load,
'input' 'input'
); );
@ -1196,7 +1192,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'text', type: 'text',
}, },
'data_stream.dataset', 'data_stream.dataset',
safeLoad, load,
'input' 'input'
); );
@ -1214,7 +1210,7 @@ describe('Fleet - validatePackagePolicyConfig', () => {
type: 'text', type: 'text',
}, },
'data_stream.dataset', 'data_stream.dataset',
safeLoad, load,
'input' 'input'
); );

View file

@ -244,7 +244,7 @@ const loginViaConfig = () => {
// read the login details from `kibana.dev.yaml` // read the login details from `kibana.dev.yaml`
cy.readFile(KIBANA_DEV_YML_PATH).then((kibanaDevYml) => { cy.readFile(KIBANA_DEV_YML_PATH).then((kibanaDevYml) => {
const config = yaml.safeLoad(kibanaDevYml); const config = yaml.load(kibanaDevYml);
// programmatically authenticate without interacting with the Kibana login page // programmatically authenticate without interacting with the Kibana login page
request({ request({
@ -278,7 +278,7 @@ export const getEnvAuth = (): User => {
} else { } else {
let user: User = { username: '', password: '' }; let user: User = { username: '', password: '' };
cy.readFile(KIBANA_DEV_YML_PATH).then((devYml) => { cy.readFile(KIBANA_DEV_YML_PATH).then((devYml) => {
const config = yaml.safeLoad(devYml); const config = yaml.load(devYml);
user = { username: config.elasticsearch.username, password: config.elasticsearch.password }; user = { username: config.elasticsearch.username, password: config.elasticsearch.password };
}); });

View file

@ -2,7 +2,8 @@
"extends": "../../../../tsconfig.base.json", "extends": "../../../../tsconfig.base.json",
"include": [ "include": [
"**/*", "**/*",
"../cypress.config.ts" "../cypress.config.ts",
"../../../../typings/**/*"
], ],
"exclude": [ "exclude": [
"target/**/*" "target/**/*"

View file

@ -8,7 +8,7 @@
import React, { memo } from 'react'; import React, { memo } from 'react';
import styled from 'styled-components'; import styled from 'styled-components';
import { FormattedMessage } from '@kbn/i18n-react'; import { FormattedMessage } from '@kbn/i18n-react';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { import {
EuiCodeBlock, EuiCodeBlock,
EuiFlexGroup, EuiFlexGroup,
@ -62,7 +62,7 @@ export const AgentPolicyYamlFlyout = memo<{ policyId: string; onClose: () => voi
) : ( ) : (
<> <>
<EuiCodeBlock language="yaml" isCopyable fontSize="m" whiteSpace="pre"> <EuiCodeBlock language="yaml" isCopyable fontSize="m" whiteSpace="pre">
{fullAgentPolicyToYaml(yamlData!.item, safeDump)} {fullAgentPolicyToYaml(yamlData!.item, dump)}
</EuiCodeBlock> </EuiCodeBlock>
</> </>
); );

View file

@ -7,7 +7,7 @@
import React from 'react'; import React from 'react';
import { act, fireEvent, waitFor } from '@testing-library/react'; import { act, fireEvent, waitFor } from '@testing-library/react';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import type { TestRenderer } from '../../../../../../../mock'; import type { TestRenderer } from '../../../../../../../mock';
import { createFleetTestRendererMock } from '../../../../../../../mock'; import { createFleetTestRendererMock } from '../../../../../../../mock';
@ -30,7 +30,7 @@ describe('StepConfigurePackage', () => {
let testRenderer: TestRenderer; let testRenderer: TestRenderer;
let renderResult: ReturnType<typeof testRenderer.render>; let renderResult: ReturnType<typeof testRenderer.render>;
const render = () => { const render = () => {
const validationResults = validatePackagePolicy(packagePolicy, packageInfo, safeLoad); const validationResults = validatePackagePolicy(packagePolicy, packageInfo, load);
renderResult = testRenderer.render( renderResult = testRenderer.render(
<StepConfigurePackagePolicy <StepConfigurePackagePolicy

View file

@ -8,7 +8,7 @@
import React, { useCallback, useState, useEffect, useMemo } from 'react'; import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { FormattedMessage } from '@kbn/i18n-react'; import { FormattedMessage } from '@kbn/i18n-react';
import { EuiSpacer, EuiButtonEmpty, EuiFlexItem, EuiFlexGroup } from '@elastic/eui'; import { EuiSpacer, EuiButtonEmpty, EuiFlexItem, EuiFlexGroup } from '@elastic/eui';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
@ -105,7 +105,7 @@ export const AddIntegrationPageStep: React.FC<MultiPageStepLayoutProps> = (props
const newValidationResult = validatePackagePolicy( const newValidationResult = validatePackagePolicy(
{ ...packagePolicy, ...newPackagePolicy }, { ...packagePolicy, ...newPackagePolicy },
packageInfo, packageInfo,
safeLoad load
); );
setValidationResults(newValidationResult); setValidationResults(newValidationResult);
// eslint-disable-next-line no-console // eslint-disable-next-line no-console

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import type { PackagePolicyConfigRecord, RegistryVarsEntry } from '../../../../types'; import type { PackagePolicyConfigRecord, RegistryVarsEntry } from '../../../../types';
@ -28,7 +28,7 @@ export const hasInvalidButRequiredVar = (
packagePolicyVars[registryVar.name], packagePolicyVars[registryVar.name],
registryVar, registryVar,
registryVar.name, registryVar.name,
safeLoad load
)?.length) )?.length)
) )
) )

View file

@ -7,7 +7,7 @@
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState } from 'react';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { isEqual } from 'lodash'; import { isEqual } from 'lodash';
@ -205,7 +205,7 @@ export function useOnSubmit({
const newValidationResult = validatePackagePolicy( const newValidationResult = validatePackagePolicy(
newPackagePolicy || packagePolicy, newPackagePolicy || packagePolicy,
packageInfo, packageInfo,
safeLoad, load,
spaceSettings spaceSettings
); );
setValidationResults(newValidationResult); setValidationResults(newValidationResult);

View file

@ -6,7 +6,7 @@
*/ */
import { useCallback, useEffect, useState } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import deepEqual from 'fast-deep-equal'; import deepEqual from 'fast-deep-equal';
import { pick } from 'lodash'; import { pick } from 'lodash';
@ -115,7 +115,7 @@ export function usePackagePolicyWithRelatedData(
const newValidationResult = validatePackagePolicy( const newValidationResult = validatePackagePolicy(
newPackagePolicy || packagePolicy, newPackagePolicy || packagePolicy,
packageInfo, packageInfo,
safeLoad load
); );
setValidationResults(newValidationResult); setValidationResults(newValidationResult);
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@ -314,7 +314,7 @@ export function usePackagePolicyWithRelatedData(
const newValidationResults = validatePackagePolicy( const newValidationResults = validatePackagePolicy(
newPackagePolicy, newPackagePolicy,
packageData.item, packageData.item,
safeLoad load
); );
setValidationResults(newValidationResults); setValidationResults(newValidationResults);

View file

@ -8,7 +8,7 @@ import React, { useCallback, useState, useMemo } from 'react';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react'; import { FormattedMessage } from '@kbn/i18n-react';
import { safeDump, safeLoad } from 'js-yaml'; import { dump, load } from 'js-yaml';
import { import {
sendPostFleetProxy, sendPostFleetProxy,
@ -57,7 +57,7 @@ function validateUrl(value: string) {
function validateProxyHeaders(value: string) { function validateProxyHeaders(value: string) {
if (value && value !== '') { if (value && value !== '') {
const res = safeLoad(value); const res = load(value);
if ( if (
typeof res !== 'object' || typeof res !== 'object' ||
Object.values(res).some((val) => { Object.values(res).some((val) => {
@ -94,7 +94,7 @@ export function useFleetProxyForm(fleetProxy: FleetProxy | undefined, onSuccess:
const nameInput = useInput(fleetProxy?.name ?? '', validateName, isEditDisabled); const nameInput = useInput(fleetProxy?.name ?? '', validateName, isEditDisabled);
const urlInput = useInput(fleetProxy?.url ?? '', validateUrl, isEditDisabled); const urlInput = useInput(fleetProxy?.url ?? '', validateUrl, isEditDisabled);
const proxyHeadersInput = useInput( const proxyHeadersInput = useInput(
fleetProxy?.proxy_headers ? safeDump(fleetProxy.proxy_headers) : '', fleetProxy?.proxy_headers ? dump(fleetProxy.proxy_headers) : '',
validateProxyHeaders, validateProxyHeaders,
isEditDisabled isEditDisabled
); );
@ -143,8 +143,7 @@ export function useFleetProxyForm(fleetProxy: FleetProxy | undefined, onSuccess:
const data = { const data = {
name: nameInput.value, name: nameInput.value,
url: urlInput.value, url: urlInput.value,
proxy_headers: proxy_headers: proxyHeadersInput.value === '' ? undefined : load(proxyHeadersInput.value),
proxyHeadersInput.value === '' ? undefined : safeLoad(proxyHeadersInput.value),
certificate_authorities: certificateAuthoritiesInput.value, certificate_authorities: certificateAuthoritiesInput.value,
certificate: certificateInput.value, certificate: certificateInput.value,
certificate_key: certificateKeyInput.value, certificate_key: certificateKeyInput.value,

View file

@ -7,7 +7,7 @@
import React, { useMemo, useState } from 'react'; import React, { useMemo, useState } from 'react';
import { FormattedMessage } from '@kbn/i18n-react'; import { FormattedMessage } from '@kbn/i18n-react';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { import {
EuiFlyout, EuiFlyout,
@ -440,7 +440,7 @@ export const EditOutputFlyout: React.FunctionComponent<EditOutputFlyoutProps> =
inputs.presetInput.props.disabled || inputs.presetInput.props.disabled ||
outputYmlIncludesReservedPerformanceKey( outputYmlIncludesReservedPerformanceKey(
inputs.additionalYamlConfigInput.value, inputs.additionalYamlConfigInput.value,
safeLoad load
) )
} }
options={[ options={[
@ -457,7 +457,7 @@ export const EditOutputFlyout: React.FunctionComponent<EditOutputFlyoutProps> =
{supportsPresets && {supportsPresets &&
outputYmlIncludesReservedPerformanceKey( outputYmlIncludesReservedPerformanceKey(
inputs.additionalYamlConfigInput.value, inputs.additionalYamlConfigInput.value,
safeLoad load
) && ( ) && (
<> <>
<EuiSpacer size="s" /> <EuiSpacer size="s" />
@ -508,7 +508,7 @@ export const EditOutputFlyout: React.FunctionComponent<EditOutputFlyoutProps> =
<YamlCodeEditorWithPlaceholder <YamlCodeEditorWithPlaceholder
value={inputs.additionalYamlConfigInput.value} value={inputs.additionalYamlConfigInput.value}
onChange={(value) => { onChange={(value) => {
if (outputYmlIncludesReservedPerformanceKey(value, safeLoad)) { if (outputYmlIncludesReservedPerformanceKey(value, load)) {
inputs.presetInput.setValue('custom'); inputs.presetInput.setValue('custom');
} }

View file

@ -6,8 +6,8 @@
*/ */
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { safeLoad } from 'js-yaml';
import type { EuiComboBoxOptionOption } from '@elastic/eui'; import type { EuiComboBoxOptionOption } from '@elastic/eui';
import { load } from 'js-yaml';
const toSecretValidator = const toSecretValidator =
(validator: (value: string) => string[] | undefined) => (validator: (value: string) => string[] | undefined) =>
@ -219,7 +219,7 @@ export function validateLogstashHosts(value: string[]) {
export function validateYamlConfig(value: string) { export function validateYamlConfig(value: string) {
try { try {
safeLoad(value); load(value);
return; return;
} catch (error) { } catch (error) {
return [ return [

View file

@ -8,7 +8,7 @@
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import type { EuiComboBoxOptionOption } from '@elastic/eui'; import type { EuiComboBoxOptionOption } from '@elastic/eui';
@ -262,7 +262,7 @@ export function useOutputForm(onSucess: () => void, output?: Output, defaultOupu
); );
const presetInput = useInput( const presetInput = useInput(
output?.preset ?? getDefaultPresetForEsOutput(output?.config_yaml ?? '', safeLoad), output?.preset ?? getDefaultPresetForEsOutput(output?.config_yaml ?? '', load),
() => undefined, () => undefined,
isDisabled('preset') isDisabled('preset')
); );
@ -297,7 +297,7 @@ export function useOutputForm(onSucess: () => void, output?: Output, defaultOupu
shipper: shipper:
enabled: false enabled: false
*/ */
const configJs = output?.config_yaml ? safeLoad(output?.config_yaml) : {}; const configJs = output?.config_yaml ? load(output?.config_yaml) : {};
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
const diskQueueEnabledInput = useSwitchInput(output?.shipper?.disk_queue_enabled ?? false); const diskQueueEnabledInput = useSwitchInput(output?.shipper?.disk_queue_enabled ?? false);

View file

@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import semverGte from 'semver/functions/gte'; import semverGte from 'semver/functions/gte';
import semverLte from 'semver/functions/lte'; import semverLte from 'semver/functions/lte';
@ -26,7 +26,7 @@ export const filterYamlChangelog = (
latestVersion: string, latestVersion: string,
currentVersion?: string currentVersion?: string
) => { ) => {
const parsedChangelog: ChangeLogParams[] = changelogText ? safeLoad(changelogText) : []; const parsedChangelog: ChangeLogParams[] = changelogText ? load(changelogText) : [];
if (!currentVersion) return parsedChangelog.filter((e) => semverLte(e.version, latestVersion)); if (!currentVersion) return parsedChangelog.filter((e) => semverLte(e.version, latestVersion));

View file

@ -9,7 +9,7 @@ import crypto from 'crypto';
import { useState, useEffect, useMemo, useCallback } from 'react'; import { useState, useEffect, useMemo, useCallback } from 'react';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import type { PackagePolicy, AgentPolicy } from '../../types'; import type { PackagePolicy, AgentPolicy } from '../../types';
import { import {
@ -289,7 +289,7 @@ export function useFetchFullPolicy(agentPolicy: AgentPolicy | undefined, isK8s?:
if (typeof fullAgentPolicy === 'string') { if (typeof fullAgentPolicy === 'string') {
return; return;
} }
setYaml(fullAgentPolicyToYaml(fullAgentPolicy, safeDump, apiKey)); setYaml(fullAgentPolicyToYaml(fullAgentPolicy, dump, apiKey));
} }
}, [apiKey, fullAgentPolicy, isK8s]); }, [apiKey, fullAgentPolicy, isK8s]);

View file

@ -8,7 +8,7 @@
import type { TypeOf } from '@kbn/config-schema'; import type { TypeOf } from '@kbn/config-schema';
import type { KibanaRequest, RequestHandler, ResponseHeaders } from '@kbn/core/server'; import type { KibanaRequest, RequestHandler, ResponseHeaders } from '@kbn/core/server';
import pMap from 'p-map'; import pMap from 'p-map';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { isEmpty } from 'lodash'; import { isEmpty } from 'lodash';
@ -590,7 +590,7 @@ export const downloadFullAgentPolicy: FleetRequestHandler<
standalone: request.query.standalone === true, standalone: request.query.standalone === true,
}); });
if (fullAgentPolicy) { if (fullAgentPolicy) {
const body = fullAgentPolicyToYaml(fullAgentPolicy, safeDump); const body = fullAgentPolicyToYaml(fullAgentPolicy, dump);
const headers: ResponseHeaders = { const headers: ResponseHeaders = {
'content-type': 'text/x-yaml', 'content-type': 'text/x-yaml',
'content-disposition': `attachment; filename="elastic-agent.yml"`, 'content-disposition': `attachment; filename="elastic-agent.yml"`,

View file

@ -8,7 +8,7 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import type { SavedObjectsClientContract } from '@kbn/core/server'; import type { SavedObjectsClientContract } from '@kbn/core/server';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import deepMerge from 'deepmerge'; import deepMerge from 'deepmerge';
import { set } from '@kbn/safer-lodash-set'; import { set } from '@kbn/safer-lodash-set';
@ -393,7 +393,7 @@ export function transformOutputToFullPolicyOutput(
preset, preset,
} = output; } = output;
const configJs = config_yaml ? safeLoad(config_yaml) : {}; const configJs = config_yaml ? load(config_yaml) : {};
// build logic to read config_yaml and transform it with the new shipper data // build logic to read config_yaml and transform it with the new shipper data
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
@ -544,7 +544,7 @@ export function transformOutputToFullPolicyOutput(
} }
if (outputTypeSupportPresets(output.type)) { if (outputTypeSupportPresets(output.type)) {
newOutput.preset = preset ?? getDefaultPresetForEsOutput(config_yaml ?? '', safeLoad); newOutput.preset = preset ?? getDefaultPresetForEsOutput(config_yaml ?? '', load);
} }
return newOutput; return newOutput;

View file

@ -7,7 +7,7 @@
import { chunk, groupBy, isEqual, keyBy, omit, pick } from 'lodash'; import { chunk, groupBy, isEqual, keyBy, omit, pick } from 'lodash';
import { v5 as uuidv5 } from 'uuid'; import { v5 as uuidv5 } from 'uuid';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import pMap from 'p-map'; import pMap from 'p-map';
import { lt } from 'semver'; import { lt } from 'semver';
import type { import type {
@ -1427,7 +1427,7 @@ class AgentPolicyService {
}, },
}; };
const configMapYaml = fullAgentConfigMapToYaml(fullAgentConfigMap, safeDump); const configMapYaml = fullAgentConfigMapToYaml(fullAgentConfigMap, dump);
const updateManifestVersion = elasticAgentStandaloneManifest.replace('VERSION', agentVersion); const updateManifestVersion = elasticAgentStandaloneManifest.replace('VERSION', agentVersion);
const fixedAgentYML = configMapYaml.replace('agent.yml:', 'agent.yml: |-'); const fixedAgentYML = configMapYaml.replace('agent.yml:', 'agent.yml: |-');
return [fixedAgentYML, updateManifestVersion].join('\n'); return [fixedAgentYML, updateManifestVersion].join('\n');

View file

@ -6,7 +6,7 @@
*/ */
import Handlebars from 'handlebars'; import Handlebars from 'handlebars';
import { safeLoad, safeDump } from 'js-yaml'; import { load, dump } from 'js-yaml';
import type { Logger } from '@kbn/core/server'; import type { Logger } from '@kbn/core/server';
import type { PackagePolicyConfigRecord } from '../../../../common/types'; import type { PackagePolicyConfigRecord } from '../../../../common/types';
@ -28,10 +28,10 @@ export function compileTemplate(variables: PackagePolicyConfigRecord, templateSt
} }
compiledTemplate = replaceRootLevelYamlVariables(yamlValues, compiledTemplate); compiledTemplate = replaceRootLevelYamlVariables(yamlValues, compiledTemplate);
const yamlFromCompiledTemplate = safeLoad(compiledTemplate, {}); const yamlFromCompiledTemplate = load(compiledTemplate, {});
// Hack to keep empty string ('') values around in the end yaml because // Hack to keep empty string ('') values around in the end yaml because
// `safeLoad` replaces empty strings with null // `load` replaces empty strings with null
const patchedYamlFromCompiledTemplate = Object.entries(yamlFromCompiledTemplate).reduce( const patchedYamlFromCompiledTemplate = Object.entries(yamlFromCompiledTemplate).reduce(
(acc, [key, value]) => { (acc, [key, value]) => {
if (value === null && typeof vars[key] === 'string' && vars[key].trim() === '') { if (value === null && typeof vars[key] === 'string' && vars[key].trim() === '') {
@ -98,7 +98,7 @@ function buildTemplateVariables(logger: Logger, variables: PackagePolicyConfigRe
if (recordEntry.type && recordEntry.type === 'yaml') { if (recordEntry.type && recordEntry.type === 'yaml') {
const yamlKeyPlaceholder = `##${key}##`; const yamlKeyPlaceholder = `##${key}##`;
varPart[lastKeyPart] = recordEntry.value ? `"${yamlKeyPlaceholder}"` : null; varPart[lastKeyPart] = recordEntry.value ? `"${yamlKeyPlaceholder}"` : null;
yamlValues[yamlKeyPlaceholder] = recordEntry.value ? safeLoad(recordEntry.value) : null; yamlValues[yamlKeyPlaceholder] = recordEntry.value ? load(recordEntry.value) : null;
} else if (recordEntry.value && recordEntry.value.isSecretRef) { } else if (recordEntry.value && recordEntry.value.isSecretRef) {
varPart[lastKeyPart] = toCompiledSecretRef(recordEntry.value.id); varPart[lastKeyPart] = toCompiledSecretRef(recordEntry.value.id);
} else { } else {
@ -165,7 +165,7 @@ function replaceRootLevelYamlVariables(yamlVariables: { [k: string]: any }, yaml
let patchedTemplate = yamlTemplate; let patchedTemplate = yamlTemplate;
Object.entries(yamlVariables).forEach(([key, val]) => { Object.entries(yamlVariables).forEach(([key, val]) => {
patchedTemplate = patchedTemplate.replace(new RegExp(`^"${key}"`, 'gm'), () => patchedTemplate = patchedTemplate.replace(new RegExp(`^"${key}"`, 'gm'), () =>
val ? safeDump(val) : '' val ? dump(val) : ''
); );
}); });

View file

@ -231,7 +231,7 @@ export function parseAndVerifyArchive(
let manifest: ArchivePackage; let manifest: ArchivePackage;
try { try {
logger.debug(`Verifying archive - loading yaml`); logger.debug(`Verifying archive - loading yaml`);
manifest = yaml.safeLoad(manifestBuffer.toString()); manifest = yaml.load(manifestBuffer.toString());
} catch (error) { } catch (error) {
throw new PackageInvalidArchiveError( throw new PackageInvalidArchiveError(
`Could not parse top-level package manifest at top-level directory ${toplevelDir}: ${error}.` `Could not parse top-level package manifest at top-level directory ${toplevelDir}: ${error}.`
@ -311,7 +311,7 @@ export function parseAndVerifyArchive(
if (paths.includes(tagsFile) || tagsBuffer) { if (paths.includes(tagsFile) || tagsBuffer) {
let tags: PackageSpecTags[]; let tags: PackageSpecTags[];
try { try {
tags = yaml.safeLoad(tagsBuffer.toString()); tags = yaml.load(tagsBuffer.toString());
logger.debug(`Parsing archive - parsing kibana/tags.yml file`); logger.debug(`Parsing archive - parsing kibana/tags.yml file`);
if (tags.length) { if (tags.length) {
parsed.asset_tags = tags; parsed.asset_tags = tags;
@ -369,7 +369,7 @@ export function parseAndVerifyDataStreams(opts: {
let manifest; let manifest;
try { try {
manifest = yaml.safeLoad(manifestBuffer.toString()); manifest = yaml.load(manifestBuffer.toString());
} catch (error) { } catch (error) {
throw new PackageInvalidArchiveError( throw new PackageInvalidArchiveError(
`Could not parse package manifest for data stream '${dataStreamPath}': ${error}.` `Could not parse package manifest for data stream '${dataStreamPath}': ${error}.`
@ -382,7 +382,7 @@ export function parseAndVerifyDataStreams(opts: {
let dataStreamRoutingRules: RegistryDataStreamRoutingRules[] | undefined; let dataStreamRoutingRules: RegistryDataStreamRoutingRules[] | undefined;
if (routingRulesBuffer) { if (routingRulesBuffer) {
try { try {
dataStreamRoutingRules = yaml.safeLoad(routingRulesBuffer.toString()); dataStreamRoutingRules = yaml.load(routingRulesBuffer.toString());
} catch (error) { } catch (error) {
throw new PackageInvalidArchiveError( throw new PackageInvalidArchiveError(
`Could not parse routing rules for data stream '${dataStreamPath}': ${error}.` `Could not parse routing rules for data stream '${dataStreamPath}': ${error}.`
@ -395,7 +395,7 @@ export function parseAndVerifyDataStreams(opts: {
let dataStreamLifecyle: RegistryDataStreamLifecycle | undefined; let dataStreamLifecyle: RegistryDataStreamLifecycle | undefined;
if (lifecyleBuffer) { if (lifecyleBuffer) {
try { try {
dataStreamLifecyle = yaml.safeLoad(lifecyleBuffer.toString()); dataStreamLifecyle = yaml.load(lifecyleBuffer.toString());
} catch (error) { } catch (error) {
throw new PackageInvalidArchiveError( throw new PackageInvalidArchiveError(
`Could not parse lifecycle for data stream '${dataStreamPath}': ${error}.` `Could not parse lifecycle for data stream '${dataStreamPath}': ${error}.`

View file

@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { safeDump, safeLoad } from 'js-yaml'; import { dump, load } from 'js-yaml';
import { ElasticsearchAssetType } from '../../../../types'; import { ElasticsearchAssetType } from '../../../../types';
import type { RegistryDataStream } from '../../../../types'; import type { RegistryDataStream } from '../../../../types';
@ -127,7 +127,7 @@ export function addCustomPipelineAndLocalRoutingRulesProcessor(
})); }));
if (pipeline.extension === 'yml') { if (pipeline.extension === 'yml') {
const parsedPipelineContent = safeLoad(pipeline.contentForInstallation); const parsedPipelineContent = load(pipeline.contentForInstallation);
customPipelineProcessors.forEach((processor) => customPipelineProcessors.forEach((processor) =>
mutatePipelineContentWithNewProcessor(parsedPipelineContent, processor) mutatePipelineContentWithNewProcessor(parsedPipelineContent, processor)
); );
@ -136,7 +136,7 @@ export function addCustomPipelineAndLocalRoutingRulesProcessor(
); );
return { return {
...pipeline, ...pipeline,
contentForInstallation: `---\n${safeDump(parsedPipelineContent)}`, contentForInstallation: `---\n${dump(parsedPipelineContent)}`,
}; };
} }

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad, safeDump } from 'js-yaml'; import { load, dump } from 'js-yaml';
import type { ESAssetMetadata } from '../../../../common/types'; import type { ESAssetMetadata } from '../../../../common/types';
@ -44,12 +44,12 @@ export function appendMetadataToIngestPipeline({
if (pipeline.extension === 'yml') { if (pipeline.extension === 'yml') {
// Convert the YML content to JSON, append the `_meta` value, then convert it back to // Convert the YML content to JSON, append the `_meta` value, then convert it back to
// YML and return the resulting YML // YML and return the resulting YML
const parsedPipelineContent = safeLoad(pipeline.contentForInstallation); const parsedPipelineContent = load(pipeline.contentForInstallation);
parsedPipelineContent._meta = meta; parsedPipelineContent._meta = meta;
return { return {
...pipeline, ...pipeline,
contentForInstallation: `---\n${safeDump(parsedPipelineContent)}`, contentForInstallation: `---\n${dump(parsedPipelineContent)}`,
}; };
} }

View file

@ -8,7 +8,7 @@
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import path from 'path'; import path from 'path';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { loggerMock } from '@kbn/logging-mocks'; import { loggerMock } from '@kbn/logging-mocks';
import { elasticsearchServiceMock } from '@kbn/core/server/mocks'; import { elasticsearchServiceMock } from '@kbn/core/server/mocks';
@ -265,7 +265,7 @@ describe('EPM template', () => {
it('tests loading base.yml', () => { it('tests loading base.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/base.yml'); const ymlPath = path.join(__dirname, '../../fields/tests/base.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8'); const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML); const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
@ -276,7 +276,7 @@ describe('EPM template', () => {
it('tests loading coredns.logs.yml', () => { it('tests loading coredns.logs.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/coredns.logs.yml'); const ymlPath = path.join(__dirname, '../../fields/tests/coredns.logs.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8'); const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML); const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
@ -287,7 +287,7 @@ describe('EPM template', () => {
it('tests loading system.yml', () => { it('tests loading system.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/system.yml'); const ymlPath = path.join(__dirname, '../../fields/tests/system.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8'); const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML); const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
@ -298,7 +298,7 @@ describe('EPM template', () => {
it('tests loading cockroachdb_dynamic_templates.yml', () => { it('tests loading cockroachdb_dynamic_templates.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/cockroachdb_dynamic_templates.yml'); const ymlPath = path.join(__dirname, '../../fields/tests/cockroachdb_dynamic_templates.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8'); const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML); const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
@ -320,7 +320,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(longWithIndexFalseYml); const fields: Field[] = load(longWithIndexFalseYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(longWithIndexFalseMapping); expect(mappings).toEqual(longWithIndexFalseMapping);
@ -340,7 +340,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithIndexFalseYml); const fields: Field[] = load(keywordWithIndexFalseYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithIndexFalseMapping); expect(mappings).toEqual(keywordWithIndexFalseMapping);
@ -360,7 +360,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(textWithStoreTrueYml); const fields: Field[] = load(textWithStoreTrueYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(textWithStoreTrueMapping); expect(mappings).toEqual(textWithStoreTrueMapping);
@ -392,7 +392,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(textWithMultiFieldsLiteralYml); const fields: Field[] = load(textWithMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(textWithMultiFieldsMapping); expect(mappings).toEqual(textWithMultiFieldsMapping);
@ -426,7 +426,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); const fields: Field[] = load(keywordWithMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithMultiFieldsMapping); expect(mappings).toEqual(keywordWithMultiFieldsMapping);
@ -458,7 +458,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithAnalyzedMultiFieldsLiteralYml); const fields: Field[] = load(keywordWithAnalyzedMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithAnalyzedMultiFieldsMapping); expect(mappings).toEqual(keywordWithAnalyzedMultiFieldsMapping);
@ -489,7 +489,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithNormalizedMultiFieldsLiteralYml); const fields: Field[] = load(keywordWithNormalizedMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithNormalizedMultiFieldsMapping); expect(mappings).toEqual(keywordWithNormalizedMultiFieldsMapping);
@ -518,7 +518,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); const fields: Field[] = load(keywordWithMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithMultiFieldsMapping); expect(mappings).toEqual(keywordWithMultiFieldsMapping);
@ -547,7 +547,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); const fields: Field[] = load(keywordWithMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithMultiFieldsMapping); expect(mappings).toEqual(keywordWithMultiFieldsMapping);
@ -568,7 +568,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(dateWithFormatYml); const fields: Field[] = load(dateWithFormatYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(dateWithMapping); expect(mappings).toEqual(dateWithMapping);
@ -602,7 +602,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(keywordWithMultiFieldsLiteralYml); const fields: Field[] = load(keywordWithMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(keywordWithMultiFieldsMapping); expect(mappings).toEqual(keywordWithMultiFieldsMapping);
@ -630,7 +630,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(wildcardWithMultiFieldsLiteralYml); const fields: Field[] = load(wildcardWithMultiFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(wildcardWithMultiFieldsMapping); expect(mappings).toEqual(wildcardWithMultiFieldsMapping);
@ -648,7 +648,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldLiteralYml); const fields: Field[] = load(objectFieldLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldMapping); expect(mappings).toEqual(objectFieldMapping);
@ -668,7 +668,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldEnabledFalseLiteralYml); const fields: Field[] = load(objectFieldEnabledFalseLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldEnabledFalseMapping); expect(mappings).toEqual(objectFieldEnabledFalseMapping);
@ -688,7 +688,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldDynamicFalseLiteralYml); const fields: Field[] = load(objectFieldDynamicFalseLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldDynamicFalseMapping); expect(mappings).toEqual(objectFieldDynamicFalseMapping);
@ -708,7 +708,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldDynamicTrueLiteralYml); const fields: Field[] = load(objectFieldDynamicTrueLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldDynamicTrueMapping); expect(mappings).toEqual(objectFieldDynamicTrueMapping);
@ -728,7 +728,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldDynamicStrictLiteralYml); const fields: Field[] = load(objectFieldDynamicStrictLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldDynamicStrictMapping); expect(mappings).toEqual(objectFieldDynamicStrictMapping);
@ -753,7 +753,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldWithPropertyLiteralYml); const fields: Field[] = load(objectFieldWithPropertyLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldWithPropertyMapping); expect(mappings).toEqual(objectFieldWithPropertyMapping);
@ -780,7 +780,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldWithPropertyReversedLiteralYml); const fields: Field[] = load(objectFieldWithPropertyReversedLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldWithPropertyReversedMapping); expect(mappings).toEqual(objectFieldWithPropertyReversedMapping);
@ -819,7 +819,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldWithPropertyReversedLiteralYml); const fields: Field[] = load(objectFieldWithPropertyReversedLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldWithPropertyReversedMapping); expect(mappings).toEqual(objectFieldWithPropertyReversedMapping);
@ -858,7 +858,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(objectFieldWithPropertyReversedLiteralYml); const fields: Field[] = load(objectFieldWithPropertyReversedLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(objectFieldWithPropertyReversedMapping); expect(mappings).toEqual(objectFieldWithPropertyReversedMapping);
@ -886,7 +886,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(nestedYaml); const fields: Field[] = load(nestedYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -914,7 +914,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(nestedYaml); const fields: Field[] = load(nestedYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -949,7 +949,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(nestedYaml); const fields: Field[] = load(nestedYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -978,7 +978,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(nestedYaml); const fields: Field[] = load(nestedYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1014,7 +1014,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(nestedYaml); const fields: Field[] = load(nestedYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1042,7 +1042,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(nestedYaml); const fields: Field[] = load(nestedYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1060,7 +1060,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(constantKeywordLiteralYaml); const fields: Field[] = load(constantKeywordLiteralYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(JSON.stringify(mappings)).toEqual(JSON.stringify(constantKeywordMapping)); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(constantKeywordMapping));
@ -1080,7 +1080,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(constantKeywordLiteralYaml); const fields: Field[] = load(constantKeywordLiteralYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(JSON.stringify(mappings)).toEqual(JSON.stringify(constantKeywordMapping)); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(constantKeywordMapping));
@ -1104,7 +1104,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(literalYml); const fields: Field[] = load(literalYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1127,7 +1127,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(literalYml); const fields: Field[] = load(literalYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, false); const mappings = generateMappings(processedFields, false);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1151,7 +1151,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(literalYml); const fields: Field[] = load(literalYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1185,7 +1185,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(literalYml); const fields: Field[] = load(literalYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1218,7 +1218,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(literalYml); const fields: Field[] = load(literalYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, false); const mappings = generateMappings(processedFields, false);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1245,7 +1245,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(literalYml); const fields: Field[] = load(literalYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(expectedMapping); expect(mappings).toEqual(expectedMapping);
@ -1267,7 +1267,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(metaFieldLiteralYaml); const fields: Field[] = load(metaFieldLiteralYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(JSON.stringify(mappings)).toEqual(JSON.stringify(metaFieldMapping)); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(metaFieldMapping));
@ -1306,7 +1306,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(metaFieldLiteralYaml); const fields: Field[] = load(metaFieldLiteralYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(JSON.stringify(mappings)).toEqual(JSON.stringify(metaFieldMapping)); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(metaFieldMapping));
@ -1328,7 +1328,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(fieldLiteralYaml); const fields: Field[] = load(fieldLiteralYaml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(JSON.stringify(mappings)).toEqual(JSON.stringify(fieldMapping)); expect(JSON.stringify(mappings)).toEqual(JSON.stringify(fieldMapping));
@ -1348,7 +1348,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1373,7 +1373,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1403,7 +1403,7 @@ describe('EPM template', () => {
}, },
}, },
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1434,7 +1434,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1466,7 +1466,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1499,7 +1499,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1531,7 +1531,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1563,7 +1563,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1597,7 +1597,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields); const mappings = generateMappings(processedFields);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1652,7 +1652,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1709,7 +1709,7 @@ describe('EPM template', () => {
}, },
], ],
}; };
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
const processedFields = processFields(fields); const processedFields = processFields(fields);
const mappings = generateMappings(processedFields, true); const mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(runtimeFieldMapping); expect(mappings).toEqual(runtimeFieldMapping);
@ -1721,7 +1721,7 @@ describe('EPM template', () => {
type: object type: object
object_type: constant_keyword object_type: constant_keyword
`; `;
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml); const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
expect(() => { expect(() => {
const processedFields = processFields(fields); const processedFields = processFields(fields);
generateMappings(processedFields); generateMappings(processedFields);

View file

@ -7,7 +7,7 @@
import type { ElasticsearchClient, Logger, SavedObjectsClientContract } from '@kbn/core/server'; import type { ElasticsearchClient, Logger, SavedObjectsClientContract } from '@kbn/core/server';
import { errors } from '@elastic/elasticsearch'; import { errors } from '@elastic/elasticsearch';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { isPopulatedObject } from '@kbn/ml-is-populated-object'; import { isPopulatedObject } from '@kbn/ml-is-populated-object';
import { uniqBy } from 'lodash'; import { uniqBy } from 'lodash';
@ -179,7 +179,7 @@ const processTransformAssetsPerModule = (
} }
const packageAssets = transformsSpecifications.get(transformModuleId); const packageAssets = transformsSpecifications.get(transformModuleId);
const content = safeLoad(getAssetFromAssetsMap(assetsMap, path).toString('utf-8')); const content = load(getAssetFromAssetsMap(assetsMap, path).toString('utf-8'));
// Handling fields.yml and all other files within 'fields' folder // Handling fields.yml and all other files within 'fields' folder
if (fileName === TRANSFORM_SPECS_TYPES.FIELDS || isFields(path)) { if (fileName === TRANSFORM_SPECS_TYPES.FIELDS || isFields(path)) {

View file

@ -9,7 +9,7 @@ import { readFileSync } from 'fs';
import path from 'path'; import path from 'path';
import globby from 'globby'; import globby from 'globby';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { getField, processFields, processFieldsWithWildcard } from './field'; import { getField, processFields, processFieldsWithWildcard } from './field';
import type { Field, Fields } from './field'; import type { Field, Fields } from './field';
@ -30,7 +30,7 @@ test('tests loading fields.yml', () => {
const files = globby.sync(path.join(__dirname, '/tests/*.yml')); const files = globby.sync(path.join(__dirname, '/tests/*.yml'));
for (const file of files) { for (const file of files) {
const fieldsYML = readFileSync(file, 'utf-8'); const fieldsYML = readFileSync(file, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML); const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields); const processedFields = processFields(fields);
// Check that content file and generated file are equal // Check that content file and generated file are equal
@ -778,8 +778,8 @@ describe('processFields', () => {
Total swap memory. Total swap memory.
`; `;
const noWildcardFields: Field[] = safeLoad(noWildcardYml); const noWildcardFields: Field[] = load(noWildcardYml);
const wildcardWithObjectTypeFields: Field[] = safeLoad(wildcardWithObjectTypeYml); const wildcardWithObjectTypeFields: Field[] = load(wildcardWithObjectTypeYml);
test('Does not add object type when object_type field when is already defined and name has wildcard', () => { test('Does not add object type when object_type field when is already defined and name has wildcard', () => {
expect(processFieldsWithWildcard(wildcardWithObjectTypeFields)).toMatchInlineSnapshot(` expect(processFieldsWithWildcard(wildcardWithObjectTypeFields)).toMatchInlineSnapshot(`

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import type { PackageInstallContext } from '../../../../common/types'; import type { PackageInstallContext } from '../../../../common/types';
import { getAssetsDataFromAssetsMap } from '../packages/assets'; import { getAssetsDataFromAssetsMap } from '../packages/assets';
@ -322,8 +322,8 @@ export const loadDatastreamsFieldsFromYaml = (
return fieldDefinitionFiles.reduce<Field[]>((acc, file) => { return fieldDefinitionFiles.reduce<Field[]>((acc, file) => {
// Make sure it is defined as it is optional. Should never happen. // Make sure it is defined as it is optional. Should never happen.
if (file.buffer) { if (file.buffer) {
const tmpFields = safeLoad(file.buffer.toString()); const tmpFields = load(file.buffer.toString());
// safeLoad() returns undefined for empty files, we don't want that // load() returns undefined for empty files, we don't want that
if (tmpFields) { if (tmpFields) {
acc = acc.concat(tmpFields); acc = acc.concat(tmpFields);
} }
@ -345,8 +345,8 @@ export const loadTransformFieldsFromYaml = (
return fieldDefinitionFiles.reduce<Field[]>((acc, file) => { return fieldDefinitionFiles.reduce<Field[]>((acc, file) => {
// Make sure it is defined as it is optional. Should never happen. // Make sure it is defined as it is optional. Should never happen.
if (file.buffer) { if (file.buffer) {
const tmpFields = safeLoad(file.buffer.toString()); const tmpFields = load(file.buffer.toString());
// safeLoad() returns undefined for empty files, we don't want that // load() returns undefined for empty files, we don't want that
if (tmpFields) { if (tmpFields) {
acc = acc.concat(tmpFields); acc = acc.concat(tmpFields);
} }

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
// NOTE: The install methods will take care of adding a reference to a @custom pipeline. We don't need to add one here. // NOTE: The install methods will take care of adding a reference to a @custom pipeline. We don't need to add one here.
export const createDefaultPipeline = (dataset: string, type: string) => { export const createDefaultPipeline = (dataset: string, type: string) => {
@ -25,5 +25,5 @@ export const createDefaultPipeline = (dataset: string, type: string) => {
managed: true, managed: true,
}, },
}; };
return safeDump(pipeline); return dump(pipeline);
}; };

View file

@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { convertStringToTitle } from '../../utils'; import { convertStringToTitle } from '../../utils';
import type { AssetOptions } from '../generate'; import type { AssetOptions } from '../generate';
@ -17,5 +17,5 @@ export const createDatasetManifest = (dataset: string, assetOptions: AssetOption
title: convertStringToTitle(dataset), title: convertStringToTitle(dataset),
type, type,
}; };
return safeDump(manifest); return dump(manifest);
}; };

View file

@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import type { AssetOptions } from './generate'; import type { AssetOptions } from './generate';
@ -34,5 +34,5 @@ export const createManifest = (assetOptions: AssetOptions) => {
}, },
}; };
return safeDump(manifest); return dump(manifest);
}; };

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import pMap from 'p-map'; import pMap from 'p-map';
import minimatch from 'minimatch'; import minimatch from 'minimatch';
import type { import type {
@ -378,7 +378,7 @@ export async function getInstalledPackageManifests(
const parsedManifests = result.saved_objects.reduce<Map<string, PackageSpecManifest>>( const parsedManifests = result.saved_objects.reduce<Map<string, PackageSpecManifest>>(
(acc, asset) => { (acc, asset) => {
acc.set(asset.attributes.asset_path, safeLoad(asset.attributes.data_utf8)); acc.set(asset.attributes.asset_path, load(asset.attributes.data_utf8));
return acc; return acc;
}, },
new Map() new Map()

View file

@ -7,7 +7,7 @@
import type { SavedObjectsClientContract } from '@kbn/core/server'; import type { SavedObjectsClientContract } from '@kbn/core/server';
import { merge } from 'lodash'; import { merge } from 'lodash';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import { packageToPackagePolicy } from '../../../../common/services/package_to_package_policy'; import { packageToPackagePolicy } from '../../../../common/services/package_to_package_policy';
import { getInputsWithStreamIds, _compilePackagePolicyInputs } from '../../package_policy'; import { getInputsWithStreamIds, _compilePackagePolicyInputs } from '../../package_policy';
@ -121,7 +121,7 @@ export async function getTemplateInputs(
if (format === 'json') { if (format === 'json') {
return { inputs }; return { inputs };
} else if (format === 'yml') { } else if (format === 'yml') {
const yaml = safeDump( const yaml = dump(
{ inputs }, { inputs },
{ {
skipInvalid: true, skipInvalid: true,

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import type { AssetsMap } from '../../../../common/types'; import type { AssetsMap } from '../../../../common/types';
@ -14,7 +14,7 @@ import type { RegistryDataStream } from '../../../../common';
import { resolveDataStreamFields } from './utils'; import { resolveDataStreamFields } from './utils';
describe('resolveDataStreamFields', () => { describe('resolveDataStreamFields', () => {
const statusAssetYml = safeDump([ const statusAssetYml = dump([
{ {
name: 'apache.status', name: 'apache.status',
type: 'group', type: 'group',

View file

@ -9,7 +9,7 @@ import { withSpan } from '@kbn/apm-utils';
import type { FieldMetadataPlain } from '@kbn/fields-metadata-plugin/common'; import type { FieldMetadataPlain } from '@kbn/fields-metadata-plugin/common';
import type { ExtractedDatasetFields } from '@kbn/fields-metadata-plugin/server'; import type { ExtractedDatasetFields } from '@kbn/fields-metadata-plugin/server';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import type { RegistryDataStream } from '../../../../common'; import type { RegistryDataStream } from '../../../../common';
import type { AssetsMap } from '../../../../common/types'; import type { AssetsMap } from '../../../../common/types';
@ -90,7 +90,7 @@ export const resolveDataStreamFields = ({
const fieldsAssetBuffer = assetsMap.get(fieldsAssetPath); const fieldsAssetBuffer = assetsMap.get(fieldsAssetPath);
if (fieldsAssetBuffer) { if (fieldsAssetBuffer) {
const fieldsAssetJSON = safeLoad(fieldsAssetBuffer.toString('utf8')); const fieldsAssetJSON = load(fieldsAssetBuffer.toString('utf8'));
const normalizedFields = normalizeFields(fieldsAssetJSON); const normalizedFields = normalizeFields(fieldsAssetJSON);
Object.assign(dataStreamFields, normalizedFields); Object.assign(dataStreamFields, normalizedFields);
} }

View file

@ -6,7 +6,7 @@
*/ */
import { v5 as uuidv5 } from 'uuid'; import { v5 as uuidv5 } from 'uuid';
import { omit } from 'lodash'; import { omit } from 'lodash';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import deepEqual from 'fast-deep-equal'; import deepEqual from 'fast-deep-equal';
import { indexBy } from 'lodash/fp'; import { indexBy } from 'lodash/fp';
@ -524,7 +524,7 @@ class OutputService {
if (outputTypeSupportPresets(data.type)) { if (outputTypeSupportPresets(data.type)) {
if ( if (
data.preset === 'balanced' && data.preset === 'balanced' &&
outputYmlIncludesReservedPerformanceKey(output.config_yaml ?? '', safeLoad) outputYmlIncludesReservedPerformanceKey(output.config_yaml ?? '', load)
) { ) {
throw new OutputInvalidError( throw new OutputInvalidError(
`preset cannot be balanced when config_yaml contains one of ${RESERVED_CONFIG_YML_KEYS.join( `preset cannot be balanced when config_yaml contains one of ${RESERVED_CONFIG_YML_KEYS.join(
@ -600,11 +600,11 @@ class OutputService {
} }
if (!data.preset && data.type === outputType.Elasticsearch) { if (!data.preset && data.type === outputType.Elasticsearch) {
data.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', safeLoad); data.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', load);
} }
if (output.config_yaml) { if (output.config_yaml) {
const configJs = safeLoad(output.config_yaml); const configJs = load(output.config_yaml);
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
if (isShipperDisabled && output.shipper) { if (isShipperDisabled && output.shipper) {
@ -876,7 +876,7 @@ class OutputService {
if (updateData.type && outputTypeSupportPresets(updateData.type)) { if (updateData.type && outputTypeSupportPresets(updateData.type)) {
if ( if (
updateData.preset === 'balanced' && updateData.preset === 'balanced' &&
outputYmlIncludesReservedPerformanceKey(updateData.config_yaml ?? '', safeLoad) outputYmlIncludesReservedPerformanceKey(updateData.config_yaml ?? '', load)
) { ) {
throw new OutputInvalidError( throw new OutputInvalidError(
`preset cannot be balanced when config_yaml contains one of ${RESERVED_CONFIG_YML_KEYS.join( `preset cannot be balanced when config_yaml contains one of ${RESERVED_CONFIG_YML_KEYS.join(
@ -1064,7 +1064,7 @@ class OutputService {
} }
if (!data.preset && data.type === outputType.Elasticsearch) { if (!data.preset && data.type === outputType.Elasticsearch) {
updateData.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', safeLoad); updateData.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', load);
} }
// Remove the shipper data if the shipper is not enabled from the yaml config // Remove the shipper data if the shipper is not enabled from the yaml config
@ -1072,7 +1072,7 @@ class OutputService {
updateData.shipper = null; updateData.shipper = null;
} }
if (data.config_yaml) { if (data.config_yaml) {
const configJs = safeLoad(data.config_yaml); const configJs = load(data.config_yaml);
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false; const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
if (isShipperDisabled && data.shipper) { if (isShipperDisabled && data.shipper) {
@ -1150,7 +1150,7 @@ class OutputService {
await pMap( await pMap(
outputs.items.filter((output) => outputTypeSupportPresets(output.type) && !output.preset), outputs.items.filter((output) => outputTypeSupportPresets(output.type) && !output.preset),
async (output) => { async (output) => {
const preset = getDefaultPresetForEsOutput(output.config_yaml ?? '', safeLoad); const preset = getDefaultPresetForEsOutput(output.config_yaml ?? '', load);
await outputService.update( await outputService.update(
soClient, soClient,

View file

@ -22,7 +22,7 @@ import type {
} from '@kbn/core/server'; } from '@kbn/core/server';
import { SavedObjectsUtils } from '@kbn/core/server'; import { SavedObjectsUtils } from '@kbn/core/server';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants'; import { DEFAULT_SPACE_ID } from '@kbn/spaces-plugin/common/constants';
@ -2287,7 +2287,7 @@ class PackagePolicyClientWithAuthz extends PackagePolicyClientImpl {
} }
function validatePackagePolicyOrThrow(packagePolicy: NewPackagePolicy, pkgInfo: PackageInfo) { function validatePackagePolicyOrThrow(packagePolicy: NewPackagePolicy, pkgInfo: PackageInfo) {
const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, safeLoad); const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, load);
if (validationHasErrors(validationResults)) { if (validationHasErrors(validationResults)) {
const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults)) const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults))
.map(([key, value]) => ({ .map(([key, value]) => ({
@ -2784,7 +2784,7 @@ export function updatePackageInputs(
inputs, inputs,
}; };
const validationResults = validatePackagePolicy(resultingPackagePolicy, packageInfo, safeLoad); const validationResults = validatePackagePolicy(resultingPackagePolicy, packageInfo, load);
if (validationHasErrors(validationResults)) { if (validationHasErrors(validationResults)) {
const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults)) const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults))

View file

@ -9,7 +9,7 @@ import crypto from 'crypto';
import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server'; import type { ElasticsearchClient, SavedObjectsClientContract } from '@kbn/core/server';
import { isEqual } from 'lodash'; import { isEqual } from 'lodash';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import type { import type {
PreconfiguredOutput, PreconfiguredOutput,
@ -82,7 +82,7 @@ export async function createOrUpdatePreconfiguredOutputs(
const { id, config, ...outputData } = output; const { id, config, ...outputData } = output;
const configYaml = config ? safeDump(config) : undefined; const configYaml = config ? dump(config) : undefined;
const data: NewOutput = { const data: NewOutput = {
...outputData, ...outputData,

View file

@ -17,7 +17,7 @@ export const readKibanaConfig = () => {
const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml');
const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml');
const loadedKibanaConfig = (yaml.safeLoad( const loadedKibanaConfig = (yaml.load(
fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8')
) || {}) as {}; ) || {}) as {};

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { Environment, FileSystemLoader } from 'nunjucks'; import { Environment, FileSystemLoader } from 'nunjucks';
import { join as joinPath } from 'path'; import { join as joinPath } from 'path';
import { Pipeline, ESProcessorItem } from '../../../common'; import { Pipeline, ESProcessorItem } from '../../../common';
@ -191,7 +191,7 @@ export function createPipeline(state: EcsMappingState): IngestPipeline {
}); });
const template = env.getTemplate('pipeline.yml.njk'); const template = env.getTemplate('pipeline.yml.njk');
const renderedTemplate = template.render(mappedValues); const renderedTemplate = template.render(mappedValues);
let ingestPipeline = safeLoad(renderedTemplate) as Pipeline; let ingestPipeline = load(renderedTemplate) as Pipeline;
if (state.additionalProcessors.length > 0) { if (state.additionalProcessors.length > 0) {
ingestPipeline = combineProcessors(ingestPipeline, state.additionalProcessors); ingestPipeline = combineProcessors(ingestPipeline, state.additionalProcessors);
} }

View file

@ -252,7 +252,7 @@ describe('renderPackageManifestYAML', () => {
const manifestContent = renderPackageManifestYAML(integration); const manifestContent = renderPackageManifestYAML(integration);
// The manifest content must be parseable as YAML. // The manifest content must be parseable as YAML.
const manifest = yaml.safeLoad(manifestContent); const manifest = yaml.load(manifestContent) as Record<string, unknown>;
expect(manifest).toBeDefined(); expect(manifest).toBeDefined();
expect(manifest.title).toBe(integration.title); expect(manifest.title).toBe(integration.title);

View file

@ -9,7 +9,7 @@ import AdmZip from 'adm-zip';
import nunjucks from 'nunjucks'; import nunjucks from 'nunjucks';
import { getDataPath } from '@kbn/utils'; import { getDataPath } from '@kbn/utils';
import { join as joinPath } from 'path'; import { join as joinPath } from 'path';
import { safeDump } from 'js-yaml'; import { dump } from 'js-yaml';
import type { DataStream, Integration } from '../../common'; import type { DataStream, Integration } from '../../common';
import { createSync, ensureDirSync, generateUniqueId, removeDirSync } from '../util'; import { createSync, ensureDirSync, generateUniqueId, removeDirSync } from '../util';
import { createAgentInput } from './agent'; import { createAgentInput } from './agent';
@ -228,7 +228,7 @@ export function renderPackageManifestYAML(integration: Integration): string {
uniqueInputsList // inputs uniqueInputsList // inputs
); );
return safeDump(packageData); return dump(packageData);
} }
function createPackageManifest(packageDir: string, integration: Integration): void { function createPackageManifest(packageDir: string, integration: Integration): void {

View file

@ -11,6 +11,6 @@ import { createSync } from '../util';
export function createPipeline(specificDataStreamDir: string, pipeline: object): void { export function createPipeline(specificDataStreamDir: string, pipeline: object): void {
const filePath = joinPath(specificDataStreamDir, 'elasticsearch/ingest_pipeline/default.yml'); const filePath = joinPath(specificDataStreamDir, 'elasticsearch/ingest_pipeline/default.yml');
const yamlContent = `---\n${yaml.safeDump(pipeline, { sortKeys: false })}`; const yamlContent = `---\n${yaml.dump(pipeline, { sortKeys: false })}`;
createSync(filePath, yamlContent); createSync(filePath, yamlContent);
} }

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { safeLoad } from 'js-yaml'; import { load } from 'js-yaml';
import { join as joinPath } from 'path'; import { join as joinPath } from 'path';
import { Environment, FileSystemLoader } from 'nunjucks'; import { Environment, FileSystemLoader } from 'nunjucks';
import { deepCopy } from './util'; import { deepCopy } from './util';
@ -44,7 +44,7 @@ function createAppendProcessors(processors: SimplifiedProcessors): ESProcessorIt
}); });
const template = env.getTemplate('append.yml.njk'); const template = env.getTemplate('append.yml.njk');
const renderedTemplate = template.render({ processors }); const renderedTemplate = template.render({ processors });
const appendProcessors = safeLoad(renderedTemplate) as ESProcessorItem[]; const appendProcessors = load(renderedTemplate) as ESProcessorItem[];
return appendProcessors; return appendProcessors;
} }
@ -57,7 +57,7 @@ export function createGrokProcessor(grokPatterns: string[]): ESProcessorItem {
}); });
const template = env.getTemplate('grok.yml.njk'); const template = env.getTemplate('grok.yml.njk');
const renderedTemplate = template.render({ grokPatterns }); const renderedTemplate = template.render({ grokPatterns });
const grokProcessor = safeLoad(renderedTemplate) as ESProcessorItem; const grokProcessor = load(renderedTemplate) as ESProcessorItem;
return grokProcessor; return grokProcessor;
} }
@ -74,6 +74,6 @@ export function createKVProcessor(kvInput: KVProcessor, state: KVState): ESProce
packageName: state.packageName, packageName: state.packageName,
dataStreamName: state.dataStreamName, dataStreamName: state.dataStreamName,
}); });
const kvProcessor = safeLoad(renderedTemplate) as ESProcessorItem; const kvProcessor = load(renderedTemplate) as ESProcessorItem;
return kvProcessor; return kvProcessor;
} }

View file

@ -160,7 +160,7 @@ export function generateFields(mergedDocs: string): string {
.filter((key) => !ecsTopKeysSet.has(key)) .filter((key) => !ecsTopKeysSet.has(key))
.map((key) => recursiveParse(doc[key], [key])); .map((key) => recursiveParse(doc[key], [key]));
return yaml.safeDump(fieldsStructure, { sortKeys: false }); return yaml.dump(fieldsStructure, { sortKeys: false });
} }
export function merge( export function merge(

View file

@ -205,7 +205,7 @@ function decodeDiscoveryRulesYaml(
defaultDiscoveryRules: IDiscoveryRule[] = [] defaultDiscoveryRules: IDiscoveryRule[] = []
): IDiscoveryRule[] { ): IDiscoveryRule[] {
try { try {
const parsedYaml: DiscoveryRulesParsedYaml = yaml.safeLoad(discoveryRulesYaml) ?? []; const parsedYaml = (yaml.load(discoveryRulesYaml) as DiscoveryRulesParsedYaml) ?? [];
if (parsedYaml.length === 0) { if (parsedYaml.length === 0) {
return defaultDiscoveryRules; return defaultDiscoveryRules;
@ -232,5 +232,5 @@ function encodeDiscoveryRulesYaml(discoveryRules: IDiscoveryRule[]): string {
[`${operation}-${type}`]: probe, [`${operation}-${type}`]: probe,
}) })
); );
return yaml.safeDump(mappedDiscoveryRules); return yaml.dump(mappedDiscoveryRules);
} }

View file

@ -17,7 +17,7 @@ export const readKibanaConfig = () => {
const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml'); const kibanaDevConfig = path.join(kibanaConfigDir, 'kibana.dev.yml');
const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml'); const kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml');
const loadedKibanaConfig = (yaml.safeLoad( const loadedKibanaConfig = (yaml.load(
fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8') fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8')
) || {}) as {}; ) || {}) as {};

View file

@ -99,7 +99,7 @@ function ensureValidMultiText(textMultiValue: string[] | undefined) {
function escapeInvalidYamlString(yamlString: string) { function escapeInvalidYamlString(yamlString: string) {
try { try {
yaml.safeLoad(yamlString); yaml.load(yamlString);
} catch (error) { } catch (error) {
if (error instanceof yaml.YAMLException) { if (error instanceof yaml.YAMLException) {
return `"${yamlString}"`; return `"${yamlString}"`;

Some files were not shown because too many files have changed in this diff Show more