Skip to content

Commit

Permalink
feat: experiment
Browse files Browse the repository at this point in the history
  • Loading branch information
florian-lefebvre committed Nov 6, 2024
1 parent 94f4fe8 commit 80edd81
Show file tree
Hide file tree
Showing 11 changed files with 46 additions and 51 deletions.
3 changes: 3 additions & 0 deletions examples/ssr/src/pages/index.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import Container from '../components/Container.astro';
import ProductListing from '../components/ProductListing.astro';
import { getProducts } from '../api';
import '../styles/common.css';
import { getSecret } from 'astro:env/server'
console.log(getSecret('NODE_ENV'))
const products = await getProducts(Astro.request);
---
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/app/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export class AppPipeline extends Pipeline {
undefined,
undefined,
undefined,
false,
defaultRoutes,
);
pipeline.#manifestData = manifestData;
Expand Down
10 changes: 1 addition & 9 deletions packages/astro/src/core/base-pipeline.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { setGetEnv } from '../env/runtime.js';
import { createI18nMiddleware } from '../i18n/middleware.js';
import type { ComponentInstance } from '../types/astro.js';
import type { MiddlewareHandler, RewritePayload } from '../types/public/common.js';
Expand Down Expand Up @@ -56,7 +55,6 @@ export abstract class Pipeline {
* Used for `Astro.site`.
*/
readonly site = manifest.site ? new URL(manifest.site) : undefined,
readonly callSetGetEnv = true,
/**
* Array of built-in, internal, routes.
* Used to find the route module
Expand All @@ -70,13 +68,7 @@ export abstract class Pipeline {
createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat),
);
}
// In SSR, getSecret should fail by default. Setting it here will run before the
// adapter override.
if (callSetGetEnv && manifest.envGetSecretEnabled) {
setGetEnv(() => {
throw new AstroError(AstroErrorData.EnvUnsupportedGetSecret);
}, true);
}
// TODO: what to do about manifest.envGetSecretEnabled
}

abstract headElements(routeData: RouteData): Promise<HeadElements> | HeadElements;
Expand Down
5 changes: 5 additions & 0 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil
delete globalThis?.astroAsset?.addStaticImage;
}

console.log('build done')
// TODO: replace env virtual module
// throw new AstroError(AstroErrorData.EnvUnsupportedGetSecret);
// check vue code

await runHookBuildGenerated({ settings: options.settings, logger });
}

Expand Down
4 changes: 4 additions & 0 deletions packages/astro/src/core/build/plugins/plugin-chunks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export function vitePluginChunks(): VitePlugin {
if (id.includes('astro/dist/runtime')) {
return 'astro';
}
console.log(id)
if (id === 'virtual:astro:env/get') {
return 'thisiscustom'
}
},
});
},
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/env/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ export const VIRTUAL_MODULES_IDS = {
client: 'astro:env/client',
server: 'astro:env/server',
internal: 'virtual:astro:env/internal',
getEnv: 'virtual:astro:env/get'
};
export const VIRTUAL_MODULES_IDS_VALUES = new Set(Object.values(VIRTUAL_MODULES_IDS));

export const ENV_TYPES_FILE = 'env.d.ts';

const PKG_BASE = new URL('../../', import.meta.url);
export const MODULE_TEMPLATE_URL = new URL('templates/env.mjs', PKG_BASE);

export const INTERNAL_ENV_KEY = "__astro_env"
1 change: 0 additions & 1 deletion packages/astro/src/env/runtime-constants.ts

This file was deleted.

25 changes: 0 additions & 25 deletions packages/astro/src/env/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,8 @@
import { AstroError, AstroErrorData } from '../core/errors/index.js';
import { invalidVariablesToError } from './errors.js';
import { ENV_SYMBOL } from './runtime-constants.js';
import type { ValidationResultInvalid } from './validators.js';
export { validateEnvVariable, getEnvFieldType } from './validators.js';

export type GetEnv = (key: string) => string | undefined;
type OnSetGetEnv = (reset: boolean) => void;

let _getEnv: GetEnv = (key) => {
const env = (globalThis as any)[ENV_SYMBOL] ?? {};
return env[key];
};

export function setGetEnv(fn: GetEnv, reset = false) {
_getEnv = fn;

_onSetGetEnv(reset);
}

let _onSetGetEnv: OnSetGetEnv = () => {};

export function setOnSetGetEnv(fn: OnSetGetEnv) {
_onSetGetEnv = fn;
}

export function getEnv(...args: Parameters<GetEnv>) {
return _getEnv(...args);
}

export function createInvalidVariablesError(
key: string,
type: string,
Expand Down
5 changes: 4 additions & 1 deletion packages/astro/src/env/setup.ts
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
export { setGetEnv, type GetEnv } from './runtime.js';
// TODO: remove file
export const setGetEnv = () => {};

export type GetEnv = any
31 changes: 25 additions & 6 deletions packages/astro/src/env/vite-plugin-env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { type Plugin, loadEnv } from 'vite';
import { AstroError, AstroErrorData } from '../core/errors/index.js';
import type { AstroSettings } from '../types/astro.js';
import {
INTERNAL_ENV_KEY,
MODULE_TEMPLATE_URL,
VIRTUAL_MODULES_IDS,
VIRTUAL_MODULES_IDS_VALUES,
} from './constants.js';
import { type InvalidVariable, invalidVariablesToError } from './errors.js';
import { ENV_SYMBOL } from './runtime-constants.js';
import type { EnvSchema } from './schema.js';
import { getEnvFieldType, validateEnvVariable } from './validators.js';

Expand All @@ -22,14 +22,14 @@ interface AstroEnvPluginParams {
export function astroEnv({ settings, mode, sync }: AstroEnvPluginParams): Plugin {
const { schema, validateSecrets } = settings.config.env;

let templates: { client: string; server: string; internal: string } | null = null;
let templates: { client: string; server: string; internal: string; getEnv: string } | null = null;

return {
name: 'astro-env-plugin',
enforce: 'pre',
buildStart() {
const loadedEnv = loadEnv(mode, fileURLToPath(settings.config.root), '');
(globalThis as any)[ENV_SYMBOL] = loadedEnv;
(globalThis as any)[INTERNAL_ENV_KEY] = loadedEnv;

const validatedVariables = validatePublicVariables({
schema,
Expand All @@ -41,6 +41,7 @@ export function astroEnv({ settings, mode, sync }: AstroEnvPluginParams): Plugin
templates = {
...getTemplates(schema, validatedVariables),
internal: `export const schema = ${JSON.stringify(schema)};`,
getEnv: `export const getEnv = (key) => (globalThis[${JSON.stringify(INTERNAL_ENV_KEY)}] ?? {})[key];`,
};
},
buildEnd() {
Expand All @@ -67,6 +68,24 @@ export function astroEnv({ settings, mode, sync }: AstroEnvPluginParams): Plugin
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.internal)) {
return templates!.internal;
}
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.getEnv)) {
return templates!.getEnv;
}
},
writeBundle(_, bundle) {
for (const [chunkName, chunk] of Object.entries(bundle)) {
// if (chunk.type !== 'asset' && chunk.facadeModuleId === VIRTUAL_MODULES_IDS.server) {
// console.log(chunk);
// }
if (chunk.type !== 'asset') {
// console.log({
// chunkName,
// name: chunk.name,
// facadeModuleId: chunk.facadeModuleId,
// fileName: chunk.fileName,
// });
}
}
},
};
}
Expand Down Expand Up @@ -122,7 +141,7 @@ function getTemplates(
) {
let client = '';
let server = readFileSync(MODULE_TEMPLATE_URL, 'utf-8');
let onSetGetEnv = '';
// let onSetGetEnv = '';

for (const { key, value, context } of validatedVariables) {
const str = `export const ${key} = ${JSON.stringify(value)};`;
Expand All @@ -139,10 +158,10 @@ function getTemplates(
}

server += `export let ${key} = _internalGetSecret(${JSON.stringify(key)});\n`;
onSetGetEnv += `${key} = reset ? undefined : _internalGetSecret(${JSON.stringify(key)});\n`;
// onSetGetEnv += `${key} = reset ? undefined : _internalGetSecret(${JSON.stringify(key)});\n`;
}

server = server.replace('// @@ON_SET_GET_ENV@@', onSetGetEnv);
// server = server.replace('// @@ON_SET_GET_ENV@@', onSetGetEnv);

return {
client,
Expand Down
9 changes: 1 addition & 8 deletions packages/astro/templates/env.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
import { schema } from 'virtual:astro:env/internal';
import {
createInvalidVariablesError,
getEnv,
getEnvFieldType,
setOnSetGetEnv,
validateEnvVariable,
} from 'astro/env/runtime';
import { getEnv } from 'virtual:astro:env/get'

export const getSecret = (key) => {
return getEnv(key);
Expand All @@ -25,9 +24,3 @@ const _internalGetSecret = (key) => {
throw createInvalidVariablesError(key, type, result);
};

// used while generating the virtual module
// biome-ignore lint/correctness/noUnusedFunctionParameters: `reset` is used by the generated code
// biome-ignore lint/correctness/noUnusedVariables: `reset` is used by the generated code
setOnSetGetEnv((reset) => {
// @@ON_SET_GET_ENV@@
});

0 comments on commit 80edd81

Please sign in to comment.