@netlify/config 18.2.5-rc → 18.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/bin.js +5 -0
  2. package/lib/api/build_settings.js +28 -0
  3. package/lib/api/client.js +12 -0
  4. package/lib/api/site_info.js +59 -0
  5. package/lib/base.js +26 -0
  6. package/lib/bin/flags.js +173 -0
  7. package/lib/bin/main.js +59 -0
  8. package/lib/build_dir.js +22 -0
  9. package/lib/cached_config.js +26 -0
  10. package/lib/case.js +18 -0
  11. package/lib/context.js +86 -0
  12. package/lib/default.js +27 -0
  13. package/lib/env/envelope.js +24 -0
  14. package/lib/env/git.js +23 -0
  15. package/lib/env/main.js +150 -0
  16. package/lib/error.js +28 -0
  17. package/lib/events.js +21 -0
  18. package/lib/files.js +83 -0
  19. package/lib/functions_config.js +67 -0
  20. package/lib/headers.js +20 -0
  21. package/lib/inline_config.js +8 -0
  22. package/lib/log/cleanup.js +64 -0
  23. package/lib/log/logger.js +36 -0
  24. package/lib/log/main.js +39 -0
  25. package/lib/log/messages.js +87 -0
  26. package/lib/log/options.js +29 -0
  27. package/lib/log/serialize.js +4 -0
  28. package/lib/log/theme.js +13 -0
  29. package/lib/main.js +210 -0
  30. package/lib/merge.js +43 -0
  31. package/lib/merge_normalize.js +24 -0
  32. package/lib/mutations/apply.js +66 -0
  33. package/lib/mutations/config_prop_name.js +14 -0
  34. package/lib/mutations/update.js +98 -0
  35. package/lib/normalize.js +32 -0
  36. package/lib/options/base.js +54 -0
  37. package/lib/options/branch.js +31 -0
  38. package/lib/options/feature_flags.js +12 -0
  39. package/lib/options/main.js +91 -0
  40. package/lib/options/repository_root.js +16 -0
  41. package/lib/origin.js +31 -0
  42. package/lib/parse.js +56 -0
  43. package/lib/path.js +41 -0
  44. package/lib/redirects.js +19 -0
  45. package/lib/simplify.js +77 -0
  46. package/lib/utils/group.js +9 -0
  47. package/lib/utils/remove_falsy.js +14 -0
  48. package/lib/utils/set.js +27 -0
  49. package/lib/utils/toml.js +20 -0
  50. package/lib/validate/context.js +38 -0
  51. package/lib/validate/example.js +30 -0
  52. package/lib/validate/helpers.js +25 -0
  53. package/lib/validate/identical.js +16 -0
  54. package/lib/validate/main.js +99 -0
  55. package/lib/validate/validations.js +275 -0
  56. package/package.json +14 -8
@@ -0,0 +1,150 @@
1
+ import omit from 'omit.js';
2
+ import { removeFalsy } from '../utils/remove_falsy.js';
3
+ import { getEnvelope } from './envelope.js';
4
+ import { getGitEnv } from './git.js';
5
+ // Retrieve this site's environment variable. Also take into account team-wide
6
+ // environment variables and addons.
7
+ // The buildbot already has the right environment variables. This is mostly
8
+ // meant so that local builds can mimic production builds
9
+ // TODO: add `netlify.toml` `build.environment`, after normalization
10
+ // TODO: add `CONTEXT` and others
11
+ export const getEnv = async function ({ api, mode, config, siteInfo, accounts, addons, buildDir, branch, deployId, buildId, context, }) {
12
+ if (mode === 'buildbot') {
13
+ return {};
14
+ }
15
+ const generalEnv = await getGeneralEnv({ siteInfo, buildDir, branch, deployId, buildId, context });
16
+ const [accountEnv, addonsEnv, uiEnv, configFileEnv] = await getUserEnv({ api, config, siteInfo, accounts, addons });
17
+ // Sources of environment variables, in descending order of precedence.
18
+ const sources = [
19
+ { key: 'configFile', values: configFileEnv },
20
+ { key: 'ui', values: uiEnv },
21
+ { key: 'addons', values: addonsEnv },
22
+ { key: 'account', values: accountEnv },
23
+ { key: 'general', values: generalEnv },
24
+ ];
25
+ // A hash mapping names of environment variables to objects containing the following properties:
26
+ // - sources: List of sources where the environment variable was found. The first element is the source that
27
+ // actually provided the variable (i.e. the one with the highest precedence).
28
+ // - value: The value of the environment variable.
29
+ const env = new Map();
30
+ sources.forEach((source) => {
31
+ Object.keys(source.values).forEach((key) => {
32
+ if (env.has(key)) {
33
+ const { sources: envSources, value } = env.get(key);
34
+ env.set(key, {
35
+ sources: [...envSources, source.key],
36
+ value: convertToString(value),
37
+ });
38
+ }
39
+ else {
40
+ env.set(key, {
41
+ sources: [source.key],
42
+ value: convertToString(source.values[key]),
43
+ });
44
+ }
45
+ });
46
+ });
47
+ return Object.fromEntries(env);
48
+ };
49
+ const convertToString = (value) => {
50
+ if (value === null || value === undefined) {
51
+ return value;
52
+ }
53
+ if (typeof value === 'string') {
54
+ return value;
55
+ }
56
+ return value.toString();
57
+ };
58
+ // Environment variables not set by users, but meant to mimic the production
59
+ // environment.
60
+ const getGeneralEnv = async function ({ siteInfo, siteInfo: { id, name }, buildDir, branch, deployId, buildId, context, }) {
61
+ const gitEnv = await getGitEnv(buildDir, branch);
62
+ const deployUrls = getDeployUrls({ siteInfo, branch, deployId });
63
+ return removeFalsy({
64
+ SITE_ID: id,
65
+ SITE_NAME: name,
66
+ DEPLOY_ID: deployId,
67
+ BUILD_ID: buildId,
68
+ ...deployUrls,
69
+ CONTEXT: context,
70
+ NETLIFY_LOCAL: 'true',
71
+ ...gitEnv,
72
+ // Localization
73
+ LANG: 'en_US.UTF-8',
74
+ LANGUAGE: 'en_US:en',
75
+ LC_ALL: 'en_US.UTF-8',
76
+ // Disable telemetry of some tools
77
+ GATSBY_TELEMETRY_DISABLED: '1',
78
+ NEXT_TELEMETRY_DISABLED: '1',
79
+ });
80
+ };
81
+ const getDeployUrls = function ({ siteInfo: { name = DEFAULT_SITE_NAME, ssl_url: sslUrl, build_settings: { repo_url: REPOSITORY_URL } = {} }, branch, deployId, }) {
82
+ return {
83
+ URL: sslUrl,
84
+ REPOSITORY_URL,
85
+ DEPLOY_PRIME_URL: `https://${branch}--${name}${NETLIFY_DEFAULT_DOMAIN}`,
86
+ DEPLOY_URL: `https://${deployId}--${name}${NETLIFY_DEFAULT_DOMAIN}`,
87
+ };
88
+ };
89
+ const NETLIFY_DEFAULT_DOMAIN = '.netlify.app';
90
+ // `site.name` is `undefined` when there is no token or siteId
91
+ const DEFAULT_SITE_NAME = 'site-name';
92
+ // Environment variables specified by the user
93
+ const getUserEnv = async function ({ api, config, siteInfo, accounts, addons }) {
94
+ const accountEnv = await getAccountEnv({ api, siteInfo, accounts });
95
+ const addonsEnv = getAddonsEnv(addons);
96
+ const uiEnv = getUiEnv({ siteInfo });
97
+ const configFileEnv = getConfigFileEnv({ config });
98
+ return [accountEnv, addonsEnv, uiEnv, configFileEnv].map(cleanUserEnv);
99
+ };
100
+ // Account-wide environment variables
101
+ const getAccountEnv = async function ({ api, siteInfo, accounts }) {
102
+ if (siteInfo.use_envelope) {
103
+ const envelope = await getEnvelope({ api, accountId: siteInfo.account_slug });
104
+ return envelope;
105
+ }
106
+ const { site_env: siteEnv = {} } = accounts.find(({ slug }) => slug === siteInfo.account_slug) || {};
107
+ return siteEnv;
108
+ };
109
+ // Environment variables from addons
110
+ const getAddonsEnv = function (addons) {
111
+ return Object.assign({}, ...addons.map(getAddonEnv));
112
+ };
113
+ const getAddonEnv = function ({ env }) {
114
+ return env;
115
+ };
116
+ // Site-specific environment variables set in the UI
117
+ const getUiEnv = function ({ siteInfo: { build_settings: { env = {} } = {} } }) {
118
+ return env;
119
+ };
120
+ // Site-specific environment variables set in netlify.toml
121
+ const getConfigFileEnv = function ({ config: { build: { environment = {} }, }, }) {
122
+ return environment;
123
+ };
124
+ // Some environment variables cannot be overridden by configuration
125
+ const cleanUserEnv = function (userEnv) {
126
+ return omit.default(userEnv, READONLY_ENV);
127
+ };
128
+ const READONLY_ENV = [
129
+ // Set in local builds
130
+ 'BRANCH',
131
+ 'CACHED_COMMIT_REF',
132
+ 'COMMIT_REF',
133
+ 'CONTEXT',
134
+ 'HEAD',
135
+ 'REPOSITORY_URL',
136
+ 'URL',
137
+ // CI builds set NETLIFY=true while CLI and programmatic builds set
138
+ // NETLIFY_LOCAL=true
139
+ 'NETLIFY',
140
+ 'NETLIFY_LOCAL',
141
+ // Not set in local builds because there is no CI build/deploy, incoming hooks nor PR
142
+ 'INCOMING_HOOK_BODY',
143
+ 'INCOMING_HOOK_TITLE',
144
+ 'INCOMING_HOOK_URL',
145
+ 'NETLIFY_BUILD_BASE',
146
+ 'NETLIFY_BUILD_LIFECYCLE_TRIAL',
147
+ 'NETLIFY_IMAGES_CDN_DOMAIN',
148
+ 'PULL_REQUEST',
149
+ 'REVIEW_ID',
150
+ ];
package/lib/error.js ADDED
@@ -0,0 +1,28 @@
1
+ // We distinguish between errors thrown intentionally and uncaught exceptions
2
+ // (such as bugs) with a `customErrorInfo.type` property.
3
+ export const throwUserError = function (messageOrError, error) {
4
+ const errorA = getError(messageOrError, error);
5
+ errorA[CUSTOM_ERROR_KEY] = { type: USER_ERROR_TYPE };
6
+ throw errorA;
7
+ };
8
+ // Can pass either `message`, `error` or `message, error`
9
+ const getError = function (messageOrError, error) {
10
+ if (messageOrError instanceof Error) {
11
+ return messageOrError;
12
+ }
13
+ if (error === undefined) {
14
+ return new Error(messageOrError);
15
+ }
16
+ error.message = `${messageOrError}\n${error.message}`;
17
+ return error;
18
+ };
19
+ export const isUserError = function (error) {
20
+ return (canHaveErrorInfo(error) && error[CUSTOM_ERROR_KEY] !== undefined && error[CUSTOM_ERROR_KEY].type === USER_ERROR_TYPE);
21
+ };
22
+ // Exceptions that are not objects (including `Error` instances) cannot have an
23
+ // `CUSTOM_ERROR_KEY` property
24
+ const canHaveErrorInfo = function (error) {
25
+ return error != null;
26
+ };
27
+ const CUSTOM_ERROR_KEY = 'customErrorInfo';
28
+ const USER_ERROR_TYPE = 'resolveConfig';
package/lib/events.js ADDED
@@ -0,0 +1,21 @@
1
+ // List of build plugins events
2
+ export const EVENTS = [
3
+ // Before build command
4
+ 'onPreBuild',
5
+ // After build command, before Functions bundling
6
+ 'onBuild',
7
+ // After Functions bundling
8
+ 'onPostBuild',
9
+ // After build success
10
+ 'onSuccess',
11
+ // After build error
12
+ 'onError',
13
+ // After build error or success
14
+ 'onEnd',
15
+ ];
16
+ export const DEV_EVENTS = [
17
+ // Before dev command
18
+ 'onPreDev',
19
+ // The dev command
20
+ 'onDev',
21
+ ];
package/lib/files.js ADDED
@@ -0,0 +1,83 @@
1
+ import { resolve, relative, parse } from 'path';
2
+ import { getProperty, setProperty, deleteProperty } from 'dot-prop';
3
+ import { pathExists } from 'path-exists';
4
+ import { throwUserError } from './error.js';
5
+ import { mergeConfigs } from './merge.js';
6
+ import { isTruthy } from './utils/remove_falsy.js';
7
+ // Make configuration paths relative to `buildDir` and converts them to
8
+ // absolute paths
9
+ export const resolveConfigPaths = async function ({ config, repositoryRoot, buildDir, baseRelDir }) {
10
+ const baseRel = baseRelDir ? buildDir : repositoryRoot;
11
+ const configA = resolvePaths(config, FILE_PATH_CONFIG_PROPS, baseRel, repositoryRoot);
12
+ const configB = await addDefaultPaths(configA, repositoryRoot, baseRel);
13
+ return configB;
14
+ };
15
+ // All file paths in the configuration file are are relative to `buildDir`
16
+ // (if `baseRelDir` is `true`).
17
+ const FILE_PATH_CONFIG_PROPS = ['functionsDirectory', 'build.publish', 'build.edge_functions'];
18
+ const resolvePaths = function (config, propNames, baseRel, repositoryRoot) {
19
+ return propNames.reduce((configA, propName) => resolvePathProp(configA, propName, baseRel, repositoryRoot), config);
20
+ };
21
+ const resolvePathProp = function (config, propName, baseRel, repositoryRoot) {
22
+ const path = getProperty(config, propName);
23
+ if (!isTruthy(path)) {
24
+ deleteProperty(config, propName);
25
+ return config;
26
+ }
27
+ return setProperty(config, propName, resolvePath(repositoryRoot, baseRel, path, propName));
28
+ };
29
+ export const resolvePath = function (repositoryRoot, baseRel, originalPath, propName) {
30
+ if (!isTruthy(originalPath)) {
31
+ return;
32
+ }
33
+ const path = originalPath.replace(LEADING_SLASH_REGEXP, '');
34
+ const pathA = resolve(baseRel, path);
35
+ validateInsideRoot(originalPath, pathA, repositoryRoot, propName);
36
+ return pathA;
37
+ };
38
+ // We allow paths in configuration file to start with /
39
+ // In that case, those are actually relative paths not absolute.
40
+ const LEADING_SLASH_REGEXP = /^\/+/;
41
+ // We ensure all file paths are within the repository root directory.
42
+ // However we allow file paths to be outside of the build directory, since this
43
+ // can be convenient in monorepo setups.
44
+ const validateInsideRoot = function (originalPath, path, repositoryRoot, propName) {
45
+ if (relative(repositoryRoot, path).startsWith('..') || getWindowsDrive(repositoryRoot) !== getWindowsDrive(path)) {
46
+ throwUserError(`Configuration property "${propName}" "${originalPath}" must be inside the repository root directory.`);
47
+ }
48
+ };
49
+ const getWindowsDrive = function (path) {
50
+ return parse(path).root;
51
+ };
52
+ // Some configuration properties have default values that are only set if a
53
+ // specific directory/file exists in the build directory
54
+ const addDefaultPaths = async function (config, repositoryRoot, baseRel) {
55
+ const defaultPathsConfigs = await Promise.all(DEFAULT_PATHS.map(({ defaultPath, getConfig, propName }) => addDefaultPath({ repositoryRoot, baseRel, defaultPath, getConfig, propName })));
56
+ const defaultPathsConfigsA = defaultPathsConfigs.filter(Boolean);
57
+ return mergeConfigs([...defaultPathsConfigsA, config]);
58
+ };
59
+ const DEFAULT_PATHS = [
60
+ // @todo Remove once we drop support for the legacy default functions directory.
61
+ {
62
+ getConfig: (directory) => ({ functionsDirectory: directory, functionsDirectoryOrigin: 'default-v1' }),
63
+ defaultPath: 'netlify-automatic-functions',
64
+ propName: 'functions.directory',
65
+ },
66
+ {
67
+ getConfig: (directory) => ({ functionsDirectory: directory, functionsDirectoryOrigin: 'default' }),
68
+ defaultPath: 'netlify/functions',
69
+ propName: 'functions.directory',
70
+ },
71
+ {
72
+ getConfig: (directory) => ({ build: { edge_functions: directory } }),
73
+ defaultPath: 'netlify/edge-functions',
74
+ propName: 'build.edge_functions',
75
+ },
76
+ ];
77
+ const addDefaultPath = async function ({ repositoryRoot, baseRel, defaultPath, getConfig, propName }) {
78
+ const absolutePath = resolvePath(repositoryRoot, baseRel, defaultPath, propName);
79
+ if (!(await pathExists(absolutePath))) {
80
+ return;
81
+ }
82
+ return getConfig(absolutePath);
83
+ };
@@ -0,0 +1,67 @@
1
+ import isPlainObj from 'is-plain-obj';
2
+ import { isDefined } from './utils/remove_falsy.js';
3
+ export const bundlers = ['esbuild', 'nft', 'zisi'];
4
+ export const WILDCARD_ALL = '*';
5
+ // Removing the legacy `functions` from the `build` block.
6
+ // Looking for a default directory in the `functions` block, separating it
7
+ // from the rest of the configuration if it exists.
8
+ export const normalizeFunctionsProps = function ({ functions: v1FunctionsDirectory, ...build }, { [WILDCARD_ALL]: wildcardProps, ...functions }) {
9
+ const functionsA = Object.entries(functions).reduce(normalizeFunctionsProp, { [WILDCARD_ALL]: wildcardProps });
10
+ const { directory: functionsDirectory, functions: functionsB } = extractFunctionsDirectory(functionsA);
11
+ const functionsDirectoryProps = getFunctionsDirectoryProps({ functionsDirectory, v1FunctionsDirectory });
12
+ return { build, functions: functionsB, functionsDirectoryProps };
13
+ };
14
+ // Normalizes a functions configuration object, so that the first level of keys
15
+ // represents function expressions mapped to a configuration object.
16
+ //
17
+ // Example input:
18
+ // {
19
+ // "external_node_modules": ["one"],
20
+ // "my-function": { "external_node_modules": ["two"] }
21
+ // }
22
+ //
23
+ // Example output:
24
+ // {
25
+ // "*": { "external_node_modules": ["one"] },
26
+ // "my-function": { "external_node_modules": ["two"] }
27
+ // }
28
+ // If `prop` is one of `configProperties``, we might be dealing with a
29
+ // top-level property (i.e. one that targets all functions). We consider
30
+ // that to be the case if the value is an object where all keys are also
31
+ // config properties. If not, it's simply a function with the same name
32
+ // as one of the config properties.
33
+ const normalizeFunctionsProp = (functions, [propName, propValue]) => isConfigProperty(propName) && !isConfigLeaf(propValue)
34
+ ? { ...functions, [WILDCARD_ALL]: { [propName]: propValue, ...functions[WILDCARD_ALL] } }
35
+ : { ...functions, [propName]: propValue };
36
+ const isConfigLeaf = (functionConfig) => isPlainObj(functionConfig) && Object.keys(functionConfig).every(isConfigProperty);
37
+ const isConfigProperty = (propName) => FUNCTION_CONFIG_PROPERTIES.has(propName);
38
+ export const FUNCTION_CONFIG_PROPERTIES = new Set([
39
+ 'directory',
40
+ 'external_node_modules',
41
+ 'ignored_node_modules',
42
+ 'included_files',
43
+ 'node_bundler',
44
+ 'schedule',
45
+ ]);
46
+ // Takes a functions configuration object and looks for the functions directory
47
+ // definition, returning it under the `directory` key. The rest of the config
48
+ // object is returned under the `functions` key.
49
+ const extractFunctionsDirectory = ({ [WILDCARD_ALL]: { directory, ...wildcardFunctionsConfig }, ...functions }) => ({
50
+ directory,
51
+ functions: { ...functions, [WILDCARD_ALL]: wildcardFunctionsConfig },
52
+ });
53
+ const getFunctionsDirectoryProps = ({ functionsDirectory, v1FunctionsDirectory }) => {
54
+ if (isDefined(functionsDirectory)) {
55
+ return {
56
+ functionsDirectory,
57
+ functionsDirectoryOrigin: 'config',
58
+ };
59
+ }
60
+ if (isDefined(v1FunctionsDirectory)) {
61
+ return {
62
+ functionsDirectory: v1FunctionsDirectory,
63
+ functionsDirectoryOrigin: 'config-v1',
64
+ };
65
+ }
66
+ return {};
67
+ };
package/lib/headers.js ADDED
@@ -0,0 +1,20 @@
1
+ import { resolve } from 'path';
2
+ import { parseAllHeaders } from 'netlify-headers-parser';
3
+ import { warnHeadersParsing, warnHeadersCaseSensitivity } from './log/messages.js';
4
+ // Retrieve path to `_headers` file (even if it does not exist yet)
5
+ export const getHeadersPath = function ({ build: { publish } }) {
6
+ return resolve(publish, HEADERS_FILENAME);
7
+ };
8
+ const HEADERS_FILENAME = '_headers';
9
+ // Add `config.headers`
10
+ export const addHeaders = async function ({ config: { headers: configHeaders, ...config }, headersPath, logs, featureFlags, }) {
11
+ const { headers, errors } = await parseAllHeaders({
12
+ headersFiles: [headersPath],
13
+ configHeaders,
14
+ minimal: true,
15
+ featureFlags,
16
+ });
17
+ warnHeadersParsing(logs, errors);
18
+ warnHeadersCaseSensitivity(logs, headers);
19
+ return { ...config, headers };
20
+ };
@@ -0,0 +1,8 @@
1
+ import { logInlineConfig } from './log/main.js';
2
+ import { applyMutations } from './mutations/apply.js';
3
+ // Retrieve the `--inlineConfig` CLI flag
4
+ export const getInlineConfig = function ({ inlineConfig, configMutations, logs, debug }) {
5
+ const mutatedInlineConfig = applyMutations(inlineConfig, configMutations);
6
+ logInlineConfig(mutatedInlineConfig, { logs, debug });
7
+ return mutatedInlineConfig;
8
+ };
@@ -0,0 +1,64 @@
1
+ import filterObj from 'filter-obj';
2
+ import { simplifyConfig } from '../simplify.js';
3
+ // Make sure we are not printing secret values. Use an allow list.
4
+ export const cleanupConfig = function ({ build: { base, command, commandOrigin, environment = {}, edge_functions: edgeFunctions, ignore, processing, publish, publishOrigin, } = {}, headers, headersOrigin, plugins = [], redirects, redirectsOrigin, baseRelDir, functions, functionsDirectory, }) {
5
+ const environmentA = cleanupEnvironment(environment);
6
+ const build = {
7
+ base,
8
+ command,
9
+ commandOrigin,
10
+ environment: environmentA,
11
+ edge_functions: edgeFunctions,
12
+ ignore,
13
+ processing,
14
+ publish,
15
+ publishOrigin,
16
+ };
17
+ const pluginsA = plugins.map(cleanupPlugin);
18
+ const netlifyConfig = simplifyConfig({
19
+ build,
20
+ plugins: pluginsA,
21
+ headers,
22
+ headersOrigin,
23
+ redirects,
24
+ redirectsOrigin,
25
+ baseRelDir,
26
+ functions,
27
+ functionsDirectory,
28
+ });
29
+ const netlifyConfigA = truncateArray(netlifyConfig, 'headers');
30
+ const netlifyConfigB = truncateArray(netlifyConfigA, 'redirects');
31
+ return netlifyConfigB;
32
+ };
33
+ export const cleanupEnvironment = function (environment) {
34
+ return Object.keys(environment).filter((key) => !BUILDBOT_ENVIRONMENT.has(key));
35
+ };
36
+ // Added by the buildbot. We only want to print environment variables specified
37
+ // by the user.
38
+ const BUILDBOT_ENVIRONMENT = new Set([
39
+ 'BRANCH',
40
+ 'CONTEXT',
41
+ 'DEPLOY_PRIME_URL',
42
+ 'DEPLOY_URL',
43
+ 'GO_VERSION',
44
+ 'NETLIFY_IMAGES_CDN_DOMAIN',
45
+ 'SITE_ID',
46
+ 'SITE_NAME',
47
+ 'URL',
48
+ ]);
49
+ const cleanupPlugin = function ({ package: packageName, origin, inputs = {} }) {
50
+ const inputsA = filterObj(inputs, isPublicInput);
51
+ return { package: packageName, origin, inputs: inputsA };
52
+ };
53
+ const isPublicInput = function (key, input) {
54
+ return typeof input === 'boolean';
55
+ };
56
+ // `headers` and `redirects` can be very long, which can take several minutes
57
+ // to print in the build logs. We truncate them before logging.
58
+ const truncateArray = function (netlifyConfig, propName) {
59
+ const array = netlifyConfig[propName];
60
+ return Array.isArray(array) && array.length > MAX_ARRAY_LENGTH
61
+ ? { ...netlifyConfig, [propName]: array.slice(0, MAX_ARRAY_LENGTH) }
62
+ : netlifyConfig;
63
+ };
64
+ const MAX_ARRAY_LENGTH = 100;
@@ -0,0 +1,36 @@
1
+ import figures from 'figures';
2
+ import { serializeObject } from './serialize.js';
3
+ import { THEME } from './theme.js';
4
+ // When the `buffer` option is true, we return logs instead of printing them
5
+ // on the console. The logs are accumulated in a `logs` array variable.
6
+ export const getBufferLogs = function ({ buffer }) {
7
+ if (!buffer) {
8
+ return;
9
+ }
10
+ return { stdout: [], stderr: [] };
11
+ };
12
+ // This should be used instead of `console.log()`
13
+ // Printed on stderr because stdout is reserved for the JSON output
14
+ export const log = function (logs, string, { color } = {}) {
15
+ const stringA = String(string).replace(EMPTY_LINES_REGEXP, EMPTY_LINE);
16
+ const stringB = color === undefined ? stringA : color(stringA);
17
+ if (logs !== undefined) {
18
+ // `logs` is a stateful variable
19
+ logs.stderr.push(stringB);
20
+ return;
21
+ }
22
+ console.warn(stringB);
23
+ };
24
+ // We need to add a zero width space character in empty lines. Otherwise the
25
+ // buildbot removes those due to a bug: https://github.com/netlify/buildbot/issues/595
26
+ const EMPTY_LINES_REGEXP = /^\s*$/gm;
27
+ const EMPTY_LINE = '\u{200B}';
28
+ export const logWarning = function (logs, string, opts) {
29
+ log(logs, string, { color: THEME.warningLine, ...opts });
30
+ };
31
+ export const logObject = function (logs, object, opts) {
32
+ log(logs, serializeObject(object), opts);
33
+ };
34
+ export const logSubHeader = function (logs, string, opts) {
35
+ log(logs, `\n${figures.pointer} ${string}`, { color: THEME.subHeader, ...opts });
36
+ };
@@ -0,0 +1,39 @@
1
+ import { cleanupConfig, cleanupEnvironment } from './cleanup.js';
2
+ import { logObject, logSubHeader } from './logger.js';
3
+ import { cleanupConfigOpts } from './options.js';
4
+ // Log options in debug mode.
5
+ export const logOpts = function (opts, { logs, debug, cachedConfig, cachedConfigPath }) {
6
+ // In production, print those in the first call to `@netlify/config`, not the
7
+ // second one done inside `@netlify/build`
8
+ if (!debug || cachedConfig !== undefined || cachedConfigPath !== undefined) {
9
+ return;
10
+ }
11
+ logSubHeader(logs, 'Initial build environment');
12
+ logObject(logs, cleanupConfigOpts(opts));
13
+ };
14
+ // Log `defaultConfig` option in debug mode
15
+ export const logDefaultConfig = function (defaultConfig, { logs, debug, baseRelDir }) {
16
+ if (!debug || defaultConfig === undefined) {
17
+ return;
18
+ }
19
+ logSubHeader(logs, 'UI build settings');
20
+ logObject(logs, cleanupConfig({ ...defaultConfig, baseRelDir }));
21
+ };
22
+ // Log `inlineConfig` option in debug mode
23
+ export const logInlineConfig = function (initialConfig, { logs, debug }) {
24
+ if (!debug || Object.keys(initialConfig).length === 0) {
25
+ return;
26
+ }
27
+ logSubHeader(logs, 'Configuration override');
28
+ logObject(logs, cleanupConfig(initialConfig));
29
+ };
30
+ // Log return value of `@netlify/config` in debug mode
31
+ export const logResult = function ({ configPath, buildDir, config, context, branch, env }, { logs, debug }) {
32
+ if (!debug) {
33
+ return;
34
+ }
35
+ logSubHeader(logs, 'Resolved build environment');
36
+ logObject(logs, { configPath, buildDir, context, branch, env: cleanupEnvironment(env) });
37
+ logSubHeader(logs, 'Resolved config');
38
+ logObject(logs, cleanupConfig(config));
39
+ };
@@ -0,0 +1,87 @@
1
+ import { throwUserError } from '../error.js';
2
+ import { logWarning } from './logger.js';
3
+ export const ERROR_CALL_TO_ACTION = `Double-check your login status with 'netlify status' or contact support with details of your error.`;
4
+ export const throwOnInvalidTomlSequence = function (invalidSequence) {
5
+ throwUserError(`In netlify.toml, the following backslash should be escaped: ${invalidSequence}
6
+ The following should be used instead: \\${invalidSequence}`);
7
+ };
8
+ export const warnLegacyFunctionsDirectory = ({ config = {}, logs }) => {
9
+ const { functionsDirectory, functionsDirectoryOrigin } = config;
10
+ if (functionsDirectoryOrigin !== 'config-v1') {
11
+ return;
12
+ }
13
+ logWarning(logs, `
14
+ Detected functions directory configuration in netlify.toml under [build] settings.
15
+ We recommend updating netlify.toml to set the functions directory under [functions] settings using the directory property. For example,
16
+
17
+ [functions]
18
+ directory = "${functionsDirectory}"`);
19
+ };
20
+ export const warnContextPluginConfig = function (logs, packageName, context) {
21
+ logWarning(logs, `
22
+ "${packageName}" is installed in the UI, which means that it runs in all deploy contexts, regardless of file-based configuration.
23
+ To run "${packageName}" in the ${context} context only, uninstall the plugin from the site plugins list.`);
24
+ };
25
+ export const throwContextPluginsConfig = function (packageName, context) {
26
+ throwUserError(`
27
+ "${packageName}" is installed in the UI, which means that it runs in all deploy contexts, regardless of file-based configuration.
28
+ To run "${packageName}" in the ${context} context only, uninstall the plugin from the site plugins list.
29
+ To run "${packageName}" in all contexts, please remove the following section from "netlify.toml".
30
+
31
+ [[context.${context}.plugins]]
32
+ package = "${packageName}"
33
+ `);
34
+ };
35
+ export const warnHeadersParsing = function (logs, errors) {
36
+ if (errors.length === 0) {
37
+ return;
38
+ }
39
+ const errorMessage = errors.map(getErrorMessage).join('\n\n');
40
+ logWarning(logs, `
41
+ Warning: some headers have syntax errors:
42
+
43
+ ${errorMessage}`);
44
+ };
45
+ // Headers with different cases are not currently the way users probably
46
+ // intend them to be, so we print a warning message.
47
+ // See issue at https://github.com/netlify/build/issues/2290
48
+ export const warnHeadersCaseSensitivity = function (logs, headers) {
49
+ const headersA = headers.flatMap(getHeaderNames).filter(isNotDuplicateHeaderName).map(addHeaderLowerCase);
50
+ const differentCaseHeader = headersA.find(hasHeaderCaseDuplicate);
51
+ if (differentCaseHeader === undefined) {
52
+ return;
53
+ }
54
+ const { forPath, headerName } = headersA.find((header) => isHeaderCaseDuplicate(header, differentCaseHeader));
55
+ const sameForPath = forPath === differentCaseHeader.forPath ? ` for "${forPath}"` : '';
56
+ logWarning(logs, `
57
+ Warning: the same header is set twice with different cases${sameForPath}: "${headerName}" and "${differentCaseHeader.headerName}"`);
58
+ };
59
+ const getHeaderNames = function ({ for: forPath, values = {} }) {
60
+ return Object.keys(values).map((headerName) => ({ forPath, headerName }));
61
+ };
62
+ const isNotDuplicateHeaderName = function ({ headerName }, index, headers) {
63
+ return headers.slice(index + 1).every((header) => header.headerName !== headerName);
64
+ };
65
+ const addHeaderLowerCase = function ({ forPath, headerName }) {
66
+ const lowerHeaderName = headerName.toLowerCase();
67
+ return { forPath, headerName, lowerHeaderName };
68
+ };
69
+ const hasHeaderCaseDuplicate = function ({ lowerHeaderName }, index, headers) {
70
+ return headers.slice(index + 1).some((header) => header.lowerHeaderName === lowerHeaderName);
71
+ };
72
+ const isHeaderCaseDuplicate = function ({ headerName, lowerHeaderName }, differentCaseHeader) {
73
+ return differentCaseHeader.headerName !== headerName && differentCaseHeader.lowerHeaderName === lowerHeaderName;
74
+ };
75
+ export const warnRedirectsParsing = function (logs, errors) {
76
+ if (errors.length === 0) {
77
+ return;
78
+ }
79
+ const errorMessage = errors.map(getErrorMessage).join('\n\n');
80
+ logWarning(logs, `
81
+ Warning: some redirects have syntax errors:
82
+
83
+ ${errorMessage}`);
84
+ };
85
+ const getErrorMessage = function ({ message }) {
86
+ return message;
87
+ };
@@ -0,0 +1,29 @@
1
+ import { DEFAULT_FEATURE_FLAGS } from '../options/feature_flags.js';
2
+ import { removeEmptyArray } from '../simplify.js';
3
+ import { removeFalsy } from '../utils/remove_falsy.js';
4
+ // Use an allowlist to prevent printing confidential values.
5
+ export const cleanupConfigOpts = function ({ config, cwd, context, branch, mode, repositoryRoot, siteId, baseRelDir, env = {}, featureFlags = {}, }) {
6
+ const envA = Object.keys(env);
7
+ return removeFalsy({
8
+ config,
9
+ cwd,
10
+ context,
11
+ branch,
12
+ mode,
13
+ repositoryRoot,
14
+ siteId,
15
+ baseRelDir,
16
+ ...removeEmptyArray(envA, 'env'),
17
+ featureFlags: cleanFeatureFlags(featureFlags),
18
+ });
19
+ };
20
+ // We only show feature flags related to `@netlify/config`.
21
+ // Also, we only print enabled feature flags.
22
+ const cleanFeatureFlags = function (featureFlags) {
23
+ return Object.entries(featureFlags)
24
+ .filter(shouldPrintFeatureFlag)
25
+ .map(([featureFlagName]) => featureFlagName);
26
+ };
27
+ const shouldPrintFeatureFlag = function ([featureFlagName, enabled]) {
28
+ return enabled && featureFlagName in DEFAULT_FEATURE_FLAGS;
29
+ };
@@ -0,0 +1,4 @@
1
+ import { dump } from 'js-yaml';
2
+ export const serializeObject = function (object) {
3
+ return dump(object, { noRefs: true, sortKeys: true, lineWidth: Number.POSITIVE_INFINITY }).trimEnd();
4
+ };
@@ -0,0 +1,13 @@
1
+ import chalk from 'chalk';
2
+ // Color theme. Please use this instead of requiring chalk directly, to ensure
3
+ // consistent colors.
4
+ export const THEME = {
5
+ // Single lines used as subheaders
6
+ subHeader: chalk.cyan.bold,
7
+ // Single lines used as subheaders indicating an error
8
+ errorSubHeader: chalk.red.bold,
9
+ // Same for warnings
10
+ warningLine: chalk.yellowBright,
11
+ // One of several words that should be highlighted inside a line
12
+ highlightWords: chalk.cyan,
13
+ };