@netlify/config 19.0.0-rc → 19.0.0

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 (100) 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/{src → lib}/base.js +10 -18
  6. package/lib/bin/flags.js +173 -0
  7. package/lib/bin/main.js +59 -0
  8. package/{src → lib}/build_dir.js +11 -15
  9. package/{src → lib}/cached_config.js +14 -17
  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/{src → lib}/functions_config.js +36 -52
  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/{src → lib}/log/messages.js +56 -95
  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/{src → lib}/merge.js +25 -35
  31. package/lib/merge_normalize.js +24 -0
  32. package/lib/mutations/apply.js +66 -0
  33. package/{src → lib}/mutations/config_prop_name.js +6 -8
  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/{src → lib}/options/feature_flags.js +7 -10
  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/{src → lib}/utils/group.js +5 -6
  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/{src → lib}/validate/identical.js +8 -12
  54. package/lib/validate/main.js +99 -0
  55. package/lib/validate/validations.js +275 -0
  56. package/package.json +21 -12
  57. package/src/api/build_settings.js +0 -41
  58. package/src/api/client.js +0 -15
  59. package/src/api/site_info.js +0 -67
  60. package/src/bin/flags.js +0 -181
  61. package/src/bin/main.js +0 -73
  62. package/src/case.js +0 -37
  63. package/src/context.js +0 -99
  64. package/src/default.js +0 -31
  65. package/src/env/envelope.js +0 -24
  66. package/src/env/git.js +0 -23
  67. package/src/env/main.js +0 -198
  68. package/src/error.js +0 -36
  69. package/src/events.js +0 -22
  70. package/src/files.js +0 -107
  71. package/src/headers.js +0 -30
  72. package/src/inline_config.js +0 -9
  73. package/src/log/cleanup.js +0 -92
  74. package/src/log/logger.js +0 -47
  75. package/src/log/main.js +0 -48
  76. package/src/log/options.js +0 -43
  77. package/src/log/serialize.js +0 -5
  78. package/src/log/theme.js +0 -14
  79. package/src/main.js +0 -285
  80. package/src/merge_normalize.js +0 -31
  81. package/src/mutations/apply.js +0 -78
  82. package/src/mutations/update.js +0 -117
  83. package/src/normalize.js +0 -36
  84. package/src/options/base.js +0 -66
  85. package/src/options/branch.js +0 -34
  86. package/src/options/main.js +0 -111
  87. package/src/options/repository_root.js +0 -21
  88. package/src/origin.js +0 -38
  89. package/src/parse.js +0 -69
  90. package/src/path.js +0 -52
  91. package/src/redirects.js +0 -29
  92. package/src/simplify.js +0 -103
  93. package/src/utils/remove_falsy.js +0 -18
  94. package/src/utils/set.js +0 -33
  95. package/src/utils/toml.js +0 -23
  96. package/src/validate/context.js +0 -57
  97. package/src/validate/example.js +0 -37
  98. package/src/validate/helpers.js +0 -31
  99. package/src/validate/main.js +0 -143
  100. package/src/validate/validations.js +0 -289
@@ -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
+ };
@@ -1,23 +1,16 @@
1
- import isPlainObj from 'is-plain-obj'
2
-
3
- import { isDefined } from './utils/remove_falsy.js'
4
-
5
- export const bundlers = ['esbuild', 'nft', 'zisi']
6
- export const WILDCARD_ALL = '*'
7
-
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 = '*';
8
5
  // Removing the legacy `functions` from the `build` block.
9
6
  // Looking for a default directory in the `functions` block, separating it
10
7
  // from the rest of the configuration if it exists.
11
- export const normalizeFunctionsProps = function (
12
- { functions: v1FunctionsDirectory, ...build },
13
- { [WILDCARD_ALL]: wildcardProps, ...functions },
14
- ) {
15
- const functionsA = Object.entries(functions).reduce(normalizeFunctionsProp, { [WILDCARD_ALL]: wildcardProps })
16
- const { directory: functionsDirectory, functions: functionsB } = extractFunctionsDirectory(functionsA)
17
- const functionsDirectoryProps = getFunctionsDirectoryProps({ functionsDirectory, v1FunctionsDirectory })
18
- return { build, functions: functionsB, functionsDirectoryProps }
19
- }
20
-
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
+ };
21
14
  // Normalizes a functions configuration object, so that the first level of keys
22
15
  // represents function expressions mapped to a configuration object.
23
16
  //
@@ -37,47 +30,38 @@ export const normalizeFunctionsProps = function (
37
30
  // that to be the case if the value is an object where all keys are also
38
31
  // config properties. If not, it's simply a function with the same name
39
32
  // as one of the config properties.
40
- const normalizeFunctionsProp = (functions, [propName, propValue]) =>
41
- isConfigProperty(propName) && !isConfigLeaf(propValue)
33
+ const normalizeFunctionsProp = (functions, [propName, propValue]) => isConfigProperty(propName) && !isConfigLeaf(propValue)
42
34
  ? { ...functions, [WILDCARD_ALL]: { [propName]: propValue, ...functions[WILDCARD_ALL] } }
43
- : { ...functions, [propName]: propValue }
44
-
45
- const isConfigLeaf = (functionConfig) =>
46
- isPlainObj(functionConfig) && Object.keys(functionConfig).every(isConfigProperty)
47
-
48
- const isConfigProperty = (propName) => FUNCTION_CONFIG_PROPERTIES.has(propName)
49
-
35
+ : { ...functions, [propName]: propValue };
36
+ const isConfigLeaf = (functionConfig) => isPlainObj(functionConfig) && Object.keys(functionConfig).every(isConfigProperty);
37
+ const isConfigProperty = (propName) => FUNCTION_CONFIG_PROPERTIES.has(propName);
50
38
  export const FUNCTION_CONFIG_PROPERTIES = new Set([
51
- 'directory',
52
- 'external_node_modules',
53
- 'ignored_node_modules',
54
- 'included_files',
55
- 'node_bundler',
56
- 'schedule',
57
- ])
58
-
39
+ 'directory',
40
+ 'external_node_modules',
41
+ 'ignored_node_modules',
42
+ 'included_files',
43
+ 'node_bundler',
44
+ 'schedule',
45
+ ]);
59
46
  // Takes a functions configuration object and looks for the functions directory
60
47
  // definition, returning it under the `directory` key. The rest of the config
61
48
  // object is returned under the `functions` key.
62
49
  const extractFunctionsDirectory = ({ [WILDCARD_ALL]: { directory, ...wildcardFunctionsConfig }, ...functions }) => ({
63
- directory,
64
- functions: { ...functions, [WILDCARD_ALL]: wildcardFunctionsConfig },
65
- })
66
-
50
+ directory,
51
+ functions: { ...functions, [WILDCARD_ALL]: wildcardFunctionsConfig },
52
+ });
67
53
  const getFunctionsDirectoryProps = ({ functionsDirectory, v1FunctionsDirectory }) => {
68
- if (isDefined(functionsDirectory)) {
69
- return {
70
- functionsDirectory,
71
- functionsDirectoryOrigin: 'config',
54
+ if (isDefined(functionsDirectory)) {
55
+ return {
56
+ functionsDirectory,
57
+ functionsDirectoryOrigin: 'config',
58
+ };
72
59
  }
73
- }
74
-
75
- if (isDefined(v1FunctionsDirectory)) {
76
- return {
77
- functionsDirectory: v1FunctionsDirectory,
78
- functionsDirectoryOrigin: 'config-v1',
60
+ if (isDefined(v1FunctionsDirectory)) {
61
+ return {
62
+ functionsDirectory: v1FunctionsDirectory,
63
+ functionsDirectoryOrigin: 'config-v1',
64
+ };
79
65
  }
80
- }
81
-
82
- return {}
83
- }
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
+ };