Skip to content

Commit

Permalink
set env vars before postbuild analysis - closes #8646 (#8647)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Jan 21, 2023
1 parent 357e70b commit acc667e
Show file tree
Hide file tree
Showing 16 changed files with 56 additions and 29 deletions.
5 changes: 5 additions & 0 deletions .changeset/rotten-walls-itch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@sveltejs/kit': patch
---

fix: set environment variables before postbuild analysis
2 changes: 1 addition & 1 deletion packages/kit/src/core/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function create_dynamic_module(type, dev_values) {
);
return `export const env = {\n${keys.join(',\n')}\n}`;
}
return `export { env } from '${runtime_base}/env-${type}.js';`;
return `export { ${type}_env as env } from '${runtime_base}/shared.js';`;
}

/**
Expand Down
9 changes: 8 additions & 1 deletion packages/kit/src/core/postbuild/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
import { load_config } from '../config/index.js';
import { prerender } from './prerender.js';

const [, , client_out_dir, manifest_path, results_path, verbose, env] = process.argv;
const [, , client_out_dir, manifest_path, results_path, verbose, env_json] = process.argv;
const env = JSON.parse(env_json);

/** @type {import('types').SSRManifest} */
const manifest = (await import(pathToFileURL(manifest_path).href)).manifest;
Expand All @@ -33,6 +34,12 @@ const { Server } = await import(pathToFileURL(`${server_root}/server/index.js`).
// essential we do this before analysing the code
internal.set_building(true);

// set env, in case it's used in initialisation
const entries = Object.entries(env);
const prefix = config.env.publicPrefix;
internal.set_private_env(Object.fromEntries(entries.filter(([k]) => !k.startsWith(prefix))));
internal.set_public_env(Object.fromEntries(entries.filter(([k]) => k.startsWith(prefix))));

// analyse routes
for (const route of manifest._.routes) {
if (route.endpoint) {
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/core/postbuild/prerender.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const REDIRECT = 3;
* prerender_map: import('types').PrerenderMap;
* client_out_dir: string;
* verbose: string;
* env: string;
* env: Record<string, string>;
* }} opts
* @returns
*/
Expand Down Expand Up @@ -92,7 +92,7 @@ export async function prerender({
internal.set_paths(config.paths);

const server = new Server(manifest);
await server.init({ env: JSON.parse(env) });
await server.init({ env });

const handle_http_error = normalise_error_handler(
log,
Expand Down
4 changes: 2 additions & 2 deletions packages/kit/src/core/sync/write_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const server_template = ({
error_page
}) => `
import root from './root.svelte';
import { set_building, set_paths, set_version } from '${runtime_directory}/shared.js';
import { set_building, set_paths, set_private_env, set_public_env, set_version } from '${runtime_directory}/shared.js';
set_paths(${s(config.kit.paths)});
set_version(${s(config.kit.version.name)});
Expand Down Expand Up @@ -57,7 +57,7 @@ export function get_hooks() {
return ${hooks ? `import(${s(hooks)})` : '{}'};
}
export { set_building, set_paths };
export { set_building, set_paths, set_private_env, set_public_env };
`;

// TODO need to re-run this whenever src/app.html or src/error.html are
Expand Down
3 changes: 1 addition & 2 deletions packages/kit/src/runtime/client/start.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { DEV } from 'esm-env';
import { create_client } from './client.js';
import { init } from './singletons.js';
import { set_paths, set_version } from '../shared.js';
import { set_public_env } from '../env-public.js';
import { set_paths, set_version, set_public_env } from '../shared.js';

/**
* @param {{
Expand Down
6 changes: 0 additions & 6 deletions packages/kit/src/runtime/env-private.js

This file was deleted.

7 changes: 0 additions & 7 deletions packages/kit/src/runtime/env-public.js

This file was deleted.

2 changes: 1 addition & 1 deletion packages/kit/src/runtime/env/dynamic/private.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { env } from '../../env-private.js';
export { private_env as env } from '../../shared.js';
2 changes: 1 addition & 1 deletion packages/kit/src/runtime/env/dynamic/public.js
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { env } from '../../env-public.js';
export { public_env as env } from '../../shared.js';
3 changes: 1 addition & 2 deletions packages/kit/src/runtime/server/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { respond } from './respond.js';
import { set_private_env } from '../env-private.js';
import { set_public_env } from '../env-public.js';
import { set_private_env, set_public_env } from '../shared.js';
import { options, get_hooks } from '__GENERATED__/server-internal.js';

export class Server {
Expand Down
7 changes: 3 additions & 4 deletions packages/kit/src/runtime/server/page/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ import { s } from '../../../utils/misc.js';
import { Csp } from './csp.js';
import { uneval_action_response } from './actions.js';
import { clarify_devalue_error } from '../utils.js';
import { assets, base, version } from '../../shared.js';
import { env } from '../../env-public.js';
import { assets, base, version, public_env } from '../../shared.js';
import { text } from '../../../exports/index.js';

// TODO rename this function/module
Expand Down Expand Up @@ -258,7 +257,7 @@ export async function render_response({

if (page_config.csr) {
const opts = [
`env: ${s(env)}`,
`env: ${s(public_env)}`,
`paths: ${s({ assets, base })}`,
`target: document.querySelector('[data-sveltekit-hydrate="${target}"]').parentNode`,
`version: ${s(version)}`
Expand Down Expand Up @@ -368,7 +367,7 @@ export async function render_response({
body,
assets: resolved_assets,
nonce: /** @type {string} */ (csp.nonce),
env
env: public_env
});

// TODO flush chunks as early as we can
Expand Down
16 changes: 16 additions & 0 deletions packages/kit/src/runtime/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ export let base = '';
export let building = false;
export let version = '';

/** @type {Record<string, string>} */
export let private_env = {};

/** @type {Record<string, string>} */
export let public_env = {};

/** @param {string} stack */
export let fix_stack_trace = (stack) => stack;

Expand All @@ -17,6 +23,16 @@ export function set_building(value) {
building = value;
}

/** @type {(environment: Record<string, string>) => void} */
export function set_private_env(environment) {
private_env = environment;
}

/** @type {(environment: Record<string, string>) => void} */
export function set_public_env(environment) {
public_env = environment;
}

/** @param {string} value */
export function set_version(value) {
version = value;
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/test/apps/basics/.env
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ PUBLIC_STATIC="accessible anywhere/replaced at build time"
PUBLIC_DYNAMIC="accessible anywhere/evaluated at run time"

PUBLIC_THEME="groovy"

SOME_JSON='{"answer":42}'
11 changes: 11 additions & 0 deletions packages/kit/test/apps/basics/src/routes/+layout.server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
import { error, redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { SOME_JSON } from '$env/static/private';

// https://github.com/sveltejs/kit/issues/8646
if (JSON.parse(SOME_JSON).answer !== 42) {
throw new Error('failed to parse env var');
}

if (JSON.parse(env.SOME_JSON).answer !== 42) {
throw new Error('failed to parse env var');
}

/** @type {import('./$types').LayoutServerLoad} */
export async function load({ cookies }) {
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/types/internal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export interface ServerModule {
export interface ServerInternalModule {
set_building(building: boolean): void;
set_paths(paths: { base: string; assets: string }): void;
set_private_env(environment: Record<string, string>): void;
set_public_env(environment: Record<string, string>): void;
set_version(version: string): void;
set_fix_stack_trace(fix_stack_trace: (stack: string) => string): void;
}
Expand Down

0 comments on commit acc667e

Please sign in to comment.