From eecb14667d35c58b6c3ae068007c5ea8cb773498 Mon Sep 17 00:00:00 2001 From: Antonio Nuno Monteiro Date: Mon, 28 Feb 2022 12:50:17 -0800 Subject: [PATCH] feat: inject netlify graph environment variables during `ntl build` (#4363) * feat: inject netlify graph environment variables during `ntl build` * fix: honor `--offline` --- src/commands/build/build.js | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/commands/build/build.js b/src/commands/build/build.js index c6799924f67..3813c9eae38 100644 --- a/src/commands/build/build.js +++ b/src/commands/build/build.js @@ -1,6 +1,6 @@ // @ts-check const { getBuildOptions, runBuild } = require('../../lib/build') -const { error, exit, getToken } = require('../../utils') +const { error, exit, generateNetlifyGraphJWT, getToken } = require('../../utils') /** * @param {import('../../lib/build').BuildConfig} options @@ -15,6 +15,32 @@ const checkOptions = ({ cachedConfig: { siteInfo = {} }, token }) => { } } +const injectNetlifyGraphEnv = async function (command, { api, buildOptions, site }) { + const siteData = await api.getSite({ siteId: site.id }) + const authlifyTokenId = siteData && siteData.authlify_token_id + + if (authlifyTokenId) { + const netlifyToken = await command.authenticate() + // Only inject the authlify config if a token ID exists. This prevents + // calling command.authenticate() (which opens a browser window) if the + // user hasn't enabled API Authentication + const netlifyGraphConfig = { + netlifyToken, + authlifyTokenId, + siteId: site.id, + } + + const netlifyGraphJWT = generateNetlifyGraphJWT(netlifyGraphConfig) + + if (netlifyGraphJWT != null) { + // XXX(anmonteiro): this name is deprecated. Delete after 3/31/2022 + const varData = { sources: ['general'], value: netlifyGraphJWT } + buildOptions.cachedConfig.env.ONEGRAPH_AUTHLIFY_TOKEN = varData + buildOptions.cachedConfig.env.NETLIFY_GRAPH_TOKEN = varData + } + } +} + /** * The build command * @param {import('commander').OptionValues} options @@ -34,6 +60,8 @@ const build = async (options, command) => { if (!options.offline) { checkOptions(buildOptions) + const { api, site } = command.netlify + await injectNetlifyGraphEnv(command, { api, site, buildOptions }) } const { exitCode } = await runBuild(buildOptions)