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);
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
const locationObj = jsYaml.load(
locationFileLines.slice(1).join('\n')
) as BackstageLocationResource;
@ -46,7 +45,6 @@ async function main() {
(fileName) => `${resourceDefinitionsBaseUrl}/${fileName}`
);
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
const locationYaml = jsYaml.dump(locationObj, { lineWidth: 400 });
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".
*/
// eslint-disable-next-line @kbn/eslint/no_unsafe_js_yaml
import { dump } from 'js-yaml';
import { BuildkiteClient, BuildkiteCommandStep } from './buildkite';

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -9,7 +9,7 @@
import fs from 'fs';
import { extname } from 'path';
import { safeLoad as loadYaml } from 'js-yaml';
import { load as loadYaml } from 'js-yaml';
export const readRolesFromResource = (resourcePath: string) => {
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_this_in_property_initializers': 'error',
'@kbn/eslint/no_unsafe_console': 'error',
'@kbn/eslint/no_unsafe_js_yaml': 'error',
'@kbn/imports/no_unresolvable_imports': 'error',
'@kbn/imports/uniform_imports': 'error',
'@kbn/imports/no_unused_imports': 'error',

View file

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

View file

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

View file

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

View file

@ -8,7 +8,7 @@
*/
import chalk from 'chalk';
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import { isPlainObjectType } from './is_plain_object_type';
/**
@ -33,7 +33,7 @@ export function extractByJsonPointer(document: unknown, pointer: string): unknow
throw new Error(
`JSON Pointer ${chalk.bold(pointer)} resolution failure. Expected ${chalk.magenta(
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,
})}`
);
@ -69,7 +69,7 @@ export function extractObjectByJsonPointer(
throw new Error(
`JSON Pointer resolution failure. Expected ${chalk.magenta(
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 { basename, extname } from 'path';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import chalk from 'chalk';
import { logger } from '../logger';
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>> {
// Typing load's result to Record<string, unknown> is optimistic as we can't be sure
// 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.
return safeLoad(await fs.readFile(filePath, { encoding: 'utf8' }));
const fileContent = await fs.readFile(filePath, { encoding: 'utf8' });
const maybeObject = load(fileContent);
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>> {
// Typing load's result to Record<string, unknown> is optimistic as we can't be sure
// 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.
return await JSON.parse(await fs.readFile(filePath, { encoding: 'utf8' }));
const fileContent = await fs.readFile(filePath, { encoding: 'utf8' });
try {
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 { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import { dirname } from 'path';
export async function writeYamlDocument(filePath: string, document: unknown): Promise<void> {
@ -26,14 +26,14 @@ function stringifyToYaml(document: unknown): string {
try {
// Disable YAML Anchors https://yaml.org/spec/1.2.2/#3222-anchors-and-aliases
// It makes YAML much more human readable
return safeDump(document, {
return dump(document, {
noRefs: true,
sortKeys: sortYamlKeys,
skipInvalid: true, // Skip invalid types like `undefined`
});
} catch (e) {
// 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,
writeFileSync,
} from 'fs';
import { safeDump, safeLoad } from 'js-yaml';
import { dump, load } from 'js-yaml';
import { OpenAPIV3 } from 'openapi-types';
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)) {
writeFileSync(
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)) {
const yaml = readFileSync(join(folderPath, fileName), { encoding: 'utf8' });
bundledSpecs[fileName] = safeLoad(yaml);
bundledSpecs[fileName] = load(yaml) as OpenAPIV3.Document;
}
return bundledSpecs;

View file

@ -8,7 +8,7 @@
*/
import { readFileSync } from 'fs';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import { join } from 'path';
import { bundleFolder, readBundledSpecs } from './bundle_specs';
@ -26,7 +26,7 @@ describe('OpenAPI Bundler - specs with multiple modifications', () => {
const [bundledSpec] = Object.values(readBundledSpecs(outputFolderPath));
const expected = safeLoad(
const expected = load(
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".
*/
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import { OpenAPIV3 } from 'openapi-types';
import { bundleSpecs } from './bundle_specs';
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']))
.toMatchInlineSnapshot(`
expect(dump(bundledSpec.paths['/api/some_api']!.get!.responses['200'])).toMatchInlineSnapshot(`
"content:
application/json:
schema: &ref_0

View file

@ -17,7 +17,7 @@ import {
unlinkSync,
writeFileSync,
} from 'fs';
import { safeDump, safeLoad } from 'js-yaml';
import { dump, load } from 'js-yaml';
import { OpenAPIV3 } from 'openapi-types';
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)) {
writeFileSync(
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)) {
const yaml = readFileSync(join(folderPath, fileName), { encoding: 'utf8' });
mergedSpecs[fileName] = safeLoad(yaml);
mergedSpecs[fileName] = load(yaml);
}
return mergedSpecs;

View file

@ -5,6 +5,6 @@
},
"exclude": ["target/**/*"],
"extends": "../../tsconfig.base.json",
"include": ["**/*.ts"],
"include": ["**/*.ts", "../../typings/**/*"],
"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(
@ -136,6 +136,6 @@ export function updateBundleLimits({
pageLoadAssetSize,
};
Fs.writeFileSync(limitsPath, Yaml.safeDump(newLimits));
Fs.writeFileSync(limitsPath, Yaml.dump(newLimits));
log.success(`wrote updated limits to ${limitsPath}`);
}

View file

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

View file

@ -4,7 +4,7 @@ info:
title: Security Solution Endpoint Exceptions API (Elastic Cloud and self-hosted)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
@ -369,7 +369,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -505,7 +505,7 @@ components:
type: string
ExceptionListHumanId:
$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:
$ref: '#/components/schemas/NonEmptyString'
ExceptionListItem:

View file

@ -4,7 +4,7 @@ info:
title: Security Solution Endpoint Exceptions API (Elastic Cloud Serverless)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
@ -369,7 +369,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -505,7 +505,7 @@ components:
type: string
ExceptionListHumanId:
$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:
$ref: '#/components/schemas/NonEmptyString'
ExceptionListItem:

View file

@ -7,14 +7,14 @@ info:
title: Security Solution Exceptions API (Elastic Cloud and self-hosted)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
port:
default: '5601'
paths:
'/api/detection_engine/rules/{id}/exceptions':
/api/detection_engine/rules/{id}/exceptions:
post:
description: Create exception items that apply to a single detection rule.
operationId: CreateRuleExceptionListItems
@ -584,7 +584,7 @@ paths:
required: false
schema:
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
name: sort_order
required: false
@ -1146,7 +1146,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -1490,7 +1490,7 @@ components:
type: string
ExceptionListHumanId:
$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:
$ref: '#/components/schemas/NonEmptyString'
ExceptionListItem:

View file

@ -7,14 +7,14 @@ info:
title: Security Solution Exceptions API (Elastic Cloud Serverless)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
port:
default: '5601'
paths:
'/api/detection_engine/rules/{id}/exceptions':
/api/detection_engine/rules/{id}/exceptions:
post:
description: Create exception items that apply to a single detection rule.
operationId: CreateRuleExceptionListItems
@ -584,7 +584,7 @@ paths:
required: false
schema:
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
name: sort_order
required: false
@ -1146,7 +1146,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -1490,7 +1490,7 @@ components:
type: string
ExceptionListHumanId:
$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:
$ref: '#/components/schemas/NonEmptyString'
ExceptionListItem:

View file

@ -1,10 +1,10 @@
openapi: 3.0.3
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)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
@ -375,7 +375,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -622,7 +622,7 @@ paths:
- Security Solution Lists API
/api/lists/items:
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
parameters:
- description: Required if `list_id` and `value` are not specified
@ -1078,7 +1078,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -1562,5 +1562,5 @@ components:
security:
- BasicAuth: []
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

View file

@ -1,10 +1,10 @@
openapi: 3.0.3
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)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
@ -375,7 +375,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -622,7 +622,7 @@ paths:
- Security Solution Lists API
/api/lists/items:
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
parameters:
- description: Required if `list_id` and `value` are not specified
@ -1078,7 +1078,7 @@ paths:
required: false
schema:
$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
name: sort_order
required: false
@ -1562,5 +1562,5 @@ components:
security:
- BasicAuth: []
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

View file

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

View file

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

View file

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

View file

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

View file

@ -7,7 +7,7 @@
* 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 { interactive } from './interactive';
import { Logger } from '../cli/logger';
@ -33,7 +33,7 @@ export async function generate(encryptionConfig, command) {
await interactive(keys, encryptionConfig.docs({ comment: true }), logger);
} else {
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 { confirm, question } from '../cli/keystore/utils';
import { getConfigDirectory } from '@kbn/utils';
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
export async function interactive(keys, docs, logger) {
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}])`
);
const saveLocation = promptedSaveLocation || defaultSaveLocation;
writeFileSync(saveLocation, docs + safeDump(setKeys));
writeFileSync(saveLocation, docs + dump(setKeys));
logger.log(`Wrote configuration to ${saveLocation}`);
} else {
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 JSON5 from 'json5';
import { safeLoad, safeDump } from 'js-yaml';
import { load, dump } from 'js-yaml';
import { asyncForEach } from '@kbn/std';
import { ToolingLog } from '@kbn/tooling-log';
@ -88,10 +88,10 @@ export async function bundleFleetPackages(pkgDir: string, log: ToolingLog, confi
return;
}
const manifestYml = await safeLoad(manifestEntry.buffer.toString('utf8'));
const manifestYml = await load(manifestEntry.buffer.toString('utf8'));
manifestYml.version = stackVersion;
const newManifestYml = safeDump(manifestYml);
const newManifestYml = dump(manifestYml);
manifestEntry.buffer = Buffer.from(newManifestYml, 'utf8');
// Update all paths to use the new version

View file

@ -9,7 +9,7 @@
import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import { Build, Config, mkdirp } from '../../lib';
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'],
[
/#logging.appenders.default:.*kibana\.log\n/gs,
safeDump({
dump({
logging: {
appenders: {
file: {

View file

@ -142,7 +142,7 @@ async function rewriteFile(ymlPath: string, log: ToolingLog) {
let file = await readFile(resolve(REPO_ROOT, ymlPath), 'utf-8');
log.info('Loading: ' + ymlPath);
const doc = yaml.safeLoad(file);
const doc = yaml.load(file);
if (!doc.steps) {
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')) {
log.info('Rewriting: ' + ymlPath, step);
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',
'packages/kbn-optimizer/src/__fixtures__/mock_repo/x-pack',
'typings/*',
'typings/**/*',
];
/**

View file

@ -9,13 +9,13 @@
import stylelint from 'stylelint';
import path from 'path';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import fs from 'fs';
import { createFailError } from '@kbn/dev-cli-errors';
// load the include globs from .stylelintrc and convert them to regular expressions for filtering files
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

View file

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

View file

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

View file

@ -118,14 +118,14 @@ export class KibanaConfigWriter {
);
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 },
{ flowLevel: 1 }
)}\n`;
} else {
configToWrite = `${
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,
})}\n`;
}
@ -172,7 +172,7 @@ export class KibanaConfigWriter {
let parsedConfig: Record<string, unknown>;
try {
parsedConfig = getFlattenedObject(yaml.safeLoad(rawConfig) ?? {});
parsedConfig = getFlattenedObject(yaml.load(rawConfig) ?? {});
} catch (err) {
this.logger.error(`Failed to parse configuration file: ${getDetailedErrorMessage(err)}.`);
throw err;

View file

@ -8,7 +8,7 @@
*/
import { accessSync, constants, readFileSync, statSync } from 'fs';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import { dirname, join } from 'path';
import { Observable, firstValueFrom } from 'rxjs';
import { ensureDeepObject } from '@kbn/std';
@ -55,7 +55,7 @@ export async function readTelemetryFile<T extends object>(
try {
if (isFileReadable(configPath)) {
const yaml = readFileSync(configPath);
const data = safeLoad(yaml.toString());
const data = load(yaml.toString());
// don't bother returning empty objects
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> {
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)) {
throw new Error(
`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)
version: '2023-10-31'
servers:
- url: 'http://{kibana_host}:{port}'
- url: http://{kibana_host}:{port}
variables:
kibana_host:
default: localhost
@ -309,7 +309,7 @@ paths:
tags:
- Security AI Assistant API
- Conversations API
'/api/security_ai_assistant/current_user/conversations/{id}':
/api/security_ai_assistant/current_user/conversations/{id}:
delete:
description: Delete an existing conversation using the conversation ID.
operationId: DeleteConversation
@ -1213,13 +1213,13 @@ components:
type: object
properties:
traceId:
description: 'Could be any string, not necessarily a UUID'
description: Could be any string, not necessarily a UUID
type: string
transactionId:
description: 'Could be any string, not necessarily a UUID'
description: Could be any string, not necessarily a UUID
type: string
User:
description: 'Could be any string, not necessarily a UUID'
description: Could be any string, not necessarily a UUID
type: object
properties:
id:

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import {
getAllowedOutputTypeForPolicy,
@ -56,13 +56,13 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
it('returns true when reserved key is present', () => {
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', () => {
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
`;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(true);
expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(true);
});
it('returns false when no reserved key is present', () => {
@ -84,7 +84,7 @@ describe('outputYmlIncludesReservedPerformanceKey', () => {
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', () => {
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', () => {
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', () => {
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', () => {
const configYml = ``;
expect(outputYmlIncludesReservedPerformanceKey(configYml, safeLoad)).toBe(false);
expect(outputYmlIncludesReservedPerformanceKey(configYml, load)).toBe(false);
});
});
});

View file

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

View file

@ -244,7 +244,7 @@ const loginViaConfig = () => {
// read the login details from `kibana.dev.yaml`
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
request({
@ -278,7 +278,7 @@ export const getEnvAuth = (): User => {
} else {
let user: User = { username: '', password: '' };
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 };
});

View file

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

View file

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

View file

@ -7,7 +7,7 @@
import React from '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 { createFleetTestRendererMock } from '../../../../../../../mock';
@ -30,7 +30,7 @@ describe('StepConfigurePackage', () => {
let testRenderer: TestRenderer;
let renderResult: ReturnType<typeof testRenderer.render>;
const render = () => {
const validationResults = validatePackagePolicy(packagePolicy, packageInfo, safeLoad);
const validationResults = validatePackagePolicy(packagePolicy, packageInfo, load);
renderResult = testRenderer.render(
<StepConfigurePackagePolicy

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -8,7 +8,7 @@
import { useCallback, useState } from 'react';
import { i18n } from '@kbn/i18n';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import type { EuiComboBoxOptionOption } from '@elastic/eui';
@ -262,7 +262,7 @@ export function useOutputForm(onSucess: () => void, output?: Output, defaultOupu
);
const presetInput = useInput(
output?.preset ?? getDefaultPresetForEsOutput(output?.config_yaml ?? '', safeLoad),
output?.preset ?? getDefaultPresetForEsOutput(output?.config_yaml ?? '', load),
() => undefined,
isDisabled('preset')
);
@ -297,7 +297,7 @@ export function useOutputForm(onSucess: () => void, output?: Output, defaultOupu
shipper:
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 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.
*/
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import semverGte from 'semver/functions/gte';
import semverLte from 'semver/functions/lte';
@ -26,7 +26,7 @@ export const filterYamlChangelog = (
latestVersion: 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));

View file

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

View file

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

View file

@ -8,7 +8,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { SavedObjectsClientContract } from '@kbn/core/server';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import deepMerge from 'deepmerge';
import { set } from '@kbn/safer-lodash-set';
@ -393,7 +393,7 @@ export function transformOutputToFullPolicyOutput(
preset,
} = 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
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
@ -544,7 +544,7 @@ export function transformOutputToFullPolicyOutput(
}
if (outputTypeSupportPresets(output.type)) {
newOutput.preset = preset ?? getDefaultPresetForEsOutput(config_yaml ?? '', safeLoad);
newOutput.preset = preset ?? getDefaultPresetForEsOutput(config_yaml ?? '', load);
}
return newOutput;

View file

@ -7,7 +7,7 @@
import { chunk, groupBy, isEqual, keyBy, omit, pick } from 'lodash';
import { v5 as uuidv5 } from 'uuid';
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import pMap from 'p-map';
import { lt } from 'semver';
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 fixedAgentYML = configMapYaml.replace('agent.yml:', 'agent.yml: |-');
return [fixedAgentYML, updateManifestVersion].join('\n');

View file

@ -6,7 +6,7 @@
*/
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 { PackagePolicyConfigRecord } from '../../../../common/types';
@ -28,10 +28,10 @@ export function compileTemplate(variables: PackagePolicyConfigRecord, templateSt
}
compiledTemplate = replaceRootLevelYamlVariables(yamlValues, compiledTemplate);
const yamlFromCompiledTemplate = safeLoad(compiledTemplate, {});
const yamlFromCompiledTemplate = load(compiledTemplate, {});
// 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(
(acc, [key, value]) => {
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') {
const yamlKeyPlaceholder = `##${key}##`;
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) {
varPart[lastKeyPart] = toCompiledSecretRef(recordEntry.value.id);
} else {
@ -165,7 +165,7 @@ function replaceRootLevelYamlVariables(yamlVariables: { [k: string]: any }, yaml
let patchedTemplate = yamlTemplate;
Object.entries(yamlVariables).forEach(([key, val]) => {
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;
try {
logger.debug(`Verifying archive - loading yaml`);
manifest = yaml.safeLoad(manifestBuffer.toString());
manifest = yaml.load(manifestBuffer.toString());
} catch (error) {
throw new PackageInvalidArchiveError(
`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) {
let tags: PackageSpecTags[];
try {
tags = yaml.safeLoad(tagsBuffer.toString());
tags = yaml.load(tagsBuffer.toString());
logger.debug(`Parsing archive - parsing kibana/tags.yml file`);
if (tags.length) {
parsed.asset_tags = tags;
@ -369,7 +369,7 @@ export function parseAndVerifyDataStreams(opts: {
let manifest;
try {
manifest = yaml.safeLoad(manifestBuffer.toString());
manifest = yaml.load(manifestBuffer.toString());
} catch (error) {
throw new PackageInvalidArchiveError(
`Could not parse package manifest for data stream '${dataStreamPath}': ${error}.`
@ -382,7 +382,7 @@ export function parseAndVerifyDataStreams(opts: {
let dataStreamRoutingRules: RegistryDataStreamRoutingRules[] | undefined;
if (routingRulesBuffer) {
try {
dataStreamRoutingRules = yaml.safeLoad(routingRulesBuffer.toString());
dataStreamRoutingRules = yaml.load(routingRulesBuffer.toString());
} catch (error) {
throw new PackageInvalidArchiveError(
`Could not parse routing rules for data stream '${dataStreamPath}': ${error}.`
@ -395,7 +395,7 @@ export function parseAndVerifyDataStreams(opts: {
let dataStreamLifecyle: RegistryDataStreamLifecycle | undefined;
if (lifecyleBuffer) {
try {
dataStreamLifecyle = yaml.safeLoad(lifecyleBuffer.toString());
dataStreamLifecyle = yaml.load(lifecyleBuffer.toString());
} catch (error) {
throw new PackageInvalidArchiveError(
`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.
*/
import { safeDump, safeLoad } from 'js-yaml';
import { dump, load } from 'js-yaml';
import { ElasticsearchAssetType } from '../../../../types';
import type { RegistryDataStream } from '../../../../types';
@ -127,7 +127,7 @@ export function addCustomPipelineAndLocalRoutingRulesProcessor(
}));
if (pipeline.extension === 'yml') {
const parsedPipelineContent = safeLoad(pipeline.contentForInstallation);
const parsedPipelineContent = load(pipeline.contentForInstallation);
customPipelineProcessors.forEach((processor) =>
mutatePipelineContentWithNewProcessor(parsedPipelineContent, processor)
);
@ -136,7 +136,7 @@ export function addCustomPipelineAndLocalRoutingRulesProcessor(
);
return {
...pipeline,
contentForInstallation: `---\n${safeDump(parsedPipelineContent)}`,
contentForInstallation: `---\n${dump(parsedPipelineContent)}`,
};
}

View file

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

View file

@ -8,7 +8,7 @@
import { readFileSync } from 'fs';
import path from 'path';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import { loggerMock } from '@kbn/logging-mocks';
import { elasticsearchServiceMock } from '@kbn/core/server/mocks';
@ -265,7 +265,7 @@ describe('EPM template', () => {
it('tests loading base.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/base.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML);
const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields);
const mappings = generateMappings(processedFields);
@ -276,7 +276,7 @@ describe('EPM template', () => {
it('tests loading coredns.logs.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/coredns.logs.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML);
const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields);
const mappings = generateMappings(processedFields);
@ -287,7 +287,7 @@ describe('EPM template', () => {
it('tests loading system.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/system.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML);
const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields);
const mappings = generateMappings(processedFields);
@ -298,7 +298,7 @@ describe('EPM template', () => {
it('tests loading cockroachdb_dynamic_templates.yml', () => {
const ymlPath = path.join(__dirname, '../../fields/tests/cockroachdb_dynamic_templates.yml');
const fieldsYML = readFileSync(ymlPath, 'utf-8');
const fields: Field[] = safeLoad(fieldsYML);
const fields: Field[] = load(fieldsYML);
const processedFields = processFields(fields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields, false);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields, false);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields);
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 mappings = generateMappings(processedFields, true);
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 mappings = generateMappings(processedFields, true);
expect(mappings).toEqual(runtimeFieldMapping);
@ -1721,7 +1721,7 @@ describe('EPM template', () => {
type: object
object_type: constant_keyword
`;
const fields: Field[] = safeLoad(textWithRuntimeFieldsLiteralYml);
const fields: Field[] = load(textWithRuntimeFieldsLiteralYml);
expect(() => {
const processedFields = processFields(fields);
generateMappings(processedFields);

View file

@ -7,7 +7,7 @@
import type { ElasticsearchClient, Logger, SavedObjectsClientContract } from '@kbn/core/server';
import { errors } from '@elastic/elasticsearch';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import { isPopulatedObject } from '@kbn/ml-is-populated-object';
import { uniqBy } from 'lodash';
@ -179,7 +179,7 @@ const processTransformAssetsPerModule = (
}
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
if (fileName === TRANSFORM_SPECS_TYPES.FIELDS || isFields(path)) {

View file

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

View file

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

View file

@ -5,7 +5,7 @@
* 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.
export const createDefaultPipeline = (dataset: string, type: string) => {
@ -25,5 +25,5 @@ export const createDefaultPipeline = (dataset: string, type: string) => {
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.
*/
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import { convertStringToTitle } from '../../utils';
import type { AssetOptions } from '../generate';
@ -17,5 +17,5 @@ export const createDatasetManifest = (dataset: string, assetOptions: AssetOption
title: convertStringToTitle(dataset),
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.
*/
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
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.
*/
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import pMap from 'p-map';
import minimatch from 'minimatch';
import type {
@ -378,7 +378,7 @@ export async function getInstalledPackageManifests(
const parsedManifests = result.saved_objects.reduce<Map<string, PackageSpecManifest>>(
(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;
},
new Map()

View file

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

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import type { AssetsMap } from '../../../../common/types';
@ -14,7 +14,7 @@ import type { RegistryDataStream } from '../../../../common';
import { resolveDataStreamFields } from './utils';
describe('resolveDataStreamFields', () => {
const statusAssetYml = safeDump([
const statusAssetYml = dump([
{
name: 'apache.status',
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 { ExtractedDatasetFields } from '@kbn/fields-metadata-plugin/server';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import type { RegistryDataStream } from '../../../../common';
import type { AssetsMap } from '../../../../common/types';
@ -90,7 +90,7 @@ export const resolveDataStreamFields = ({
const fieldsAssetBuffer = assetsMap.get(fieldsAssetPath);
if (fieldsAssetBuffer) {
const fieldsAssetJSON = safeLoad(fieldsAssetBuffer.toString('utf8'));
const fieldsAssetJSON = load(fieldsAssetBuffer.toString('utf8'));
const normalizedFields = normalizeFields(fieldsAssetJSON);
Object.assign(dataStreamFields, normalizedFields);
}

View file

@ -6,7 +6,7 @@
*/
import { v5 as uuidv5 } from 'uuid';
import { omit } from 'lodash';
import { safeLoad } from 'js-yaml';
import { load } from 'js-yaml';
import deepEqual from 'fast-deep-equal';
import { indexBy } from 'lodash/fp';
@ -524,7 +524,7 @@ class OutputService {
if (outputTypeSupportPresets(data.type)) {
if (
data.preset === 'balanced' &&
outputYmlIncludesReservedPerformanceKey(output.config_yaml ?? '', safeLoad)
outputYmlIncludesReservedPerformanceKey(output.config_yaml ?? '', load)
) {
throw new OutputInvalidError(
`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) {
data.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', safeLoad);
data.preset = getDefaultPresetForEsOutput(data.config_yaml ?? '', load);
}
if (output.config_yaml) {
const configJs = safeLoad(output.config_yaml);
const configJs = load(output.config_yaml);
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
if (isShipperDisabled && output.shipper) {
@ -876,7 +876,7 @@ class OutputService {
if (updateData.type && outputTypeSupportPresets(updateData.type)) {
if (
updateData.preset === 'balanced' &&
outputYmlIncludesReservedPerformanceKey(updateData.config_yaml ?? '', safeLoad)
outputYmlIncludesReservedPerformanceKey(updateData.config_yaml ?? '', load)
) {
throw new OutputInvalidError(
`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) {
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
@ -1072,7 +1072,7 @@ class OutputService {
updateData.shipper = null;
}
if (data.config_yaml) {
const configJs = safeLoad(data.config_yaml);
const configJs = load(data.config_yaml);
const isShipperDisabled = !configJs?.shipper || configJs?.shipper?.enabled === false;
if (isShipperDisabled && data.shipper) {
@ -1150,7 +1150,7 @@ class OutputService {
await pMap(
outputs.items.filter((output) => outputTypeSupportPresets(output.type) && !output.preset),
async (output) => {
const preset = getDefaultPresetForEsOutput(output.config_yaml ?? '', safeLoad);
const preset = getDefaultPresetForEsOutput(output.config_yaml ?? '', load);
await outputService.update(
soClient,

View file

@ -22,7 +22,7 @@ import type {
} from '@kbn/core/server';
import { SavedObjectsUtils } from '@kbn/core/server';
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';
@ -2287,7 +2287,7 @@ class PackagePolicyClientWithAuthz extends PackagePolicyClientImpl {
}
function validatePackagePolicyOrThrow(packagePolicy: NewPackagePolicy, pkgInfo: PackageInfo) {
const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, safeLoad);
const validationResults = validatePackagePolicy(packagePolicy, pkgInfo, load);
if (validationHasErrors(validationResults)) {
const responseFormattedValidationErrors = Object.entries(getFlattenedObject(validationResults))
.map(([key, value]) => ({
@ -2784,7 +2784,7 @@ export function updatePackageInputs(
inputs,
};
const validationResults = validatePackagePolicy(resultingPackagePolicy, packageInfo, safeLoad);
const validationResults = validatePackagePolicy(resultingPackagePolicy, packageInfo, load);
if (validationHasErrors(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 { isEqual } from 'lodash';
import { safeDump } from 'js-yaml';
import { dump } from 'js-yaml';
import type {
PreconfiguredOutput,
@ -82,7 +82,7 @@ export async function createOrUpdatePreconfiguredOutputs(
const { id, config, ...outputData } = output;
const configYaml = config ? safeDump(config) : undefined;
const configYaml = config ? dump(config) : undefined;
const data: NewOutput = {
...outputData,

View file

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

View file

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

View file

@ -252,7 +252,7 @@ describe('renderPackageManifestYAML', () => {
const manifestContent = renderPackageManifestYAML(integration);
// 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.title).toBe(integration.title);

View file

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

View file

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

View file

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

View file

@ -205,7 +205,7 @@ function decodeDiscoveryRulesYaml(
defaultDiscoveryRules: IDiscoveryRule[] = []
): IDiscoveryRule[] {
try {
const parsedYaml: DiscoveryRulesParsedYaml = yaml.safeLoad(discoveryRulesYaml) ?? [];
const parsedYaml = (yaml.load(discoveryRulesYaml) as DiscoveryRulesParsedYaml) ?? [];
if (parsedYaml.length === 0) {
return defaultDiscoveryRules;
@ -232,5 +232,5 @@ function encodeDiscoveryRulesYaml(discoveryRules: IDiscoveryRule[]): string {
[`${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 kibanaConfig = path.join(kibanaConfigDir, 'kibana.yml');
const loadedKibanaConfig = (yaml.safeLoad(
const loadedKibanaConfig = (yaml.load(
fs.readFileSync(fs.existsSync(kibanaDevConfig) ? kibanaDevConfig : kibanaConfig, 'utf8')
) || {}) as {};

View file

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

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