full site update

This commit is contained in:
2025-07-24 18:46:24 +02:00
parent bfe2b90d8d
commit 37a6e0ab31
6912 changed files with 540482 additions and 361712 deletions

View File

@@ -1,6 +1,6 @@
import type { BooleanField, BooleanFieldInput, EnumField, EnumFieldInput, NumberField, NumberFieldInput, StringField, StringFieldInput } from './schema.js';
/**
* Return a valid env field to use in this Astro config for `experimental.env.schema`.
* Return a valid env field to use in this Astro config for `env.schema`.
*/
export declare const envField: {
string: (options: StringFieldInput) => StringField;

View File

@@ -6,4 +6,3 @@ export declare const VIRTUAL_MODULES_IDS: {
export declare const VIRTUAL_MODULES_IDS_VALUES: Set<string>;
export declare const ENV_TYPES_FILE = "env.d.ts";
export declare const MODULE_TEMPLATE_URL: URL;
export declare const TYPES_TEMPLATE_URL: URL;

View File

@@ -6,12 +6,10 @@ const VIRTUAL_MODULES_IDS = {
const VIRTUAL_MODULES_IDS_VALUES = new Set(Object.values(VIRTUAL_MODULES_IDS));
const ENV_TYPES_FILE = "env.d.ts";
const PKG_BASE = new URL("../../", import.meta.url);
const MODULE_TEMPLATE_URL = new URL("templates/env/module.mjs", PKG_BASE);
const TYPES_TEMPLATE_URL = new URL("templates/env/types.d.ts", PKG_BASE);
const MODULE_TEMPLATE_URL = new URL("templates/env.mjs", PKG_BASE);
export {
ENV_TYPES_FILE,
MODULE_TEMPLATE_URL,
TYPES_TEMPLATE_URL,
VIRTUAL_MODULES_IDS,
VIRTUAL_MODULES_IDS_VALUES
};

6
node_modules/astro/dist/env/env-loader.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import type { AstroConfig } from '../types/public/index.js';
export declare const createEnvLoader: (mode: string, config: AstroConfig, useRawValues: boolean) => {
get: () => Record<string, string>;
getPrivateEnv: () => Record<string, string>;
};
export type EnvLoader = ReturnType<typeof createEnvLoader>;

47
node_modules/astro/dist/env/env-loader.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
import { fileURLToPath } from "node:url";
import { loadEnv } from "vite";
const isValidIdentifierRe = /^[_$a-zA-Z][\w$]*$/;
function getPrivateEnv(fullEnv, astroConfig, useRawValues) {
const viteConfig = astroConfig.vite;
let envPrefixes = ["PUBLIC_"];
if (viteConfig.envPrefix) {
envPrefixes = Array.isArray(viteConfig.envPrefix) ? viteConfig.envPrefix : [viteConfig.envPrefix];
}
const privateEnv = {};
for (const key in fullEnv) {
if (isValidIdentifierRe.test(key) && envPrefixes.every((prefix) => !key.startsWith(prefix))) {
if (typeof process.env[key] !== "undefined") {
let value = process.env[key];
if (typeof value !== "string") {
value = `${value}`;
}
if (!useRawValues && (value === "0" || value === "1" || value === "true" || value === "false")) {
privateEnv[key] = value;
} else {
privateEnv[key] = `process.env.${key}`;
}
} else {
privateEnv[key] = JSON.stringify(fullEnv[key]);
}
}
}
return privateEnv;
}
function getEnv(mode, config, useRawValues) {
const loaded = loadEnv(mode, config.vite.envDir ?? fileURLToPath(config.root), "");
const privateEnv = getPrivateEnv(loaded, config, useRawValues);
return { loaded, privateEnv };
}
const createEnvLoader = (mode, config, useRawValues) => {
let { loaded, privateEnv } = getEnv(mode, config, useRawValues);
return {
get: () => {
({ loaded, privateEnv } = getEnv(mode, config, useRawValues));
return loaded;
},
getPrivateEnv: () => privateEnv
};
};
export {
createEnvLoader
};

View File

@@ -1,9 +1,9 @@
import { AstroError } from '../core/errors/index.js';
import type { ValidationResultInvalid } from './validators.js';
export { validateEnvVariable, getEnvFieldType } from './validators.js';
export { getEnvFieldType, validateEnvVariable } from './validators.js';
export type GetEnv = (key: string) => string | undefined;
type OnSetGetEnv = (reset: boolean) => void;
export declare function setGetEnv(fn: GetEnv, reset?: boolean): void;
type OnSetGetEnv = () => void;
export declare function setGetEnv(fn: GetEnv): void;
export declare function setOnSetGetEnv(fn: OnSetGetEnv): void;
export declare function getEnv(...args: Parameters<GetEnv>): string | undefined;
export declare function createInvalidVariablesError(key: string, type: string, result: ValidationResultInvalid): AstroError;

View File

@@ -1,10 +1,10 @@
import { AstroError, AstroErrorData } from "../core/errors/index.js";
import { invalidVariablesToError } from "./errors.js";
import { validateEnvVariable, getEnvFieldType } from "./validators.js";
import { getEnvFieldType, validateEnvVariable } from "./validators.js";
let _getEnv = (key) => process.env[key];
function setGetEnv(fn, reset = false) {
function setGetEnv(fn) {
_getEnv = fn;
_onSetGetEnv(reset);
_onSetGetEnv();
}
let _onSetGetEnv = () => {
};

View File

@@ -16,22 +16,22 @@ declare const StringSchema: z.ZodObject<{
includes?: string | undefined;
endsWith?: string | undefined;
startsWith?: string | undefined;
default?: string | undefined;
url?: boolean | undefined;
optional?: boolean | undefined;
min?: number | undefined;
url?: boolean | undefined;
default?: string | undefined;
max?: number | undefined;
min?: number | undefined;
}, {
type: "string";
length?: number | undefined;
includes?: string | undefined;
endsWith?: string | undefined;
startsWith?: string | undefined;
default?: string | undefined;
url?: boolean | undefined;
optional?: boolean | undefined;
min?: number | undefined;
url?: boolean | undefined;
default?: string | undefined;
max?: number | undefined;
min?: number | undefined;
}>;
export type StringSchema = z.infer<typeof StringSchema>;
declare const NumberSchema: z.ZodObject<{
@@ -45,19 +45,19 @@ declare const NumberSchema: z.ZodObject<{
int: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: "number";
default?: number | undefined;
optional?: boolean | undefined;
min?: number | undefined;
default?: number | undefined;
max?: number | undefined;
min?: number | undefined;
gt?: number | undefined;
lt?: number | undefined;
int?: boolean | undefined;
}, {
type: "number";
default?: number | undefined;
optional?: boolean | undefined;
min?: number | undefined;
default?: number | undefined;
max?: number | undefined;
min?: number | undefined;
gt?: number | undefined;
lt?: number | undefined;
int?: boolean | undefined;
@@ -69,12 +69,12 @@ declare const BooleanSchema: z.ZodObject<{
default: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: "boolean";
default?: boolean | undefined;
optional?: boolean | undefined;
default?: boolean | undefined;
}, {
type: "boolean";
default?: boolean | undefined;
optional?: boolean | undefined;
default?: boolean | undefined;
}>;
declare const EnumSchema: z.ZodObject<{
type: z.ZodLiteral<"enum">;
@@ -82,15 +82,15 @@ declare const EnumSchema: z.ZodObject<{
optional: z.ZodOptional<z.ZodBoolean>;
default: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}>;
export type EnumSchema = z.infer<typeof EnumSchema>;
declare const EnvFieldType: z.ZodUnion<[z.ZodObject<{
@@ -110,22 +110,22 @@ declare const EnvFieldType: z.ZodUnion<[z.ZodObject<{
includes?: string | undefined;
endsWith?: string | undefined;
startsWith?: string | undefined;
default?: string | undefined;
url?: boolean | undefined;
optional?: boolean | undefined;
min?: number | undefined;
url?: boolean | undefined;
default?: string | undefined;
max?: number | undefined;
min?: number | undefined;
}, {
type: "string";
length?: number | undefined;
includes?: string | undefined;
endsWith?: string | undefined;
startsWith?: string | undefined;
default?: string | undefined;
url?: boolean | undefined;
optional?: boolean | undefined;
min?: number | undefined;
url?: boolean | undefined;
default?: string | undefined;
max?: number | undefined;
min?: number | undefined;
}>, z.ZodObject<{
type: z.ZodLiteral<"number">;
optional: z.ZodOptional<z.ZodBoolean>;
@@ -137,19 +137,19 @@ declare const EnvFieldType: z.ZodUnion<[z.ZodObject<{
int: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: "number";
default?: number | undefined;
optional?: boolean | undefined;
min?: number | undefined;
default?: number | undefined;
max?: number | undefined;
min?: number | undefined;
gt?: number | undefined;
lt?: number | undefined;
int?: boolean | undefined;
}, {
type: "number";
default?: number | undefined;
optional?: boolean | undefined;
min?: number | undefined;
default?: number | undefined;
max?: number | undefined;
min?: number | undefined;
gt?: number | undefined;
lt?: number | undefined;
int?: boolean | undefined;
@@ -159,95 +159,113 @@ declare const EnvFieldType: z.ZodUnion<[z.ZodObject<{
default: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: "boolean";
default?: boolean | undefined;
optional?: boolean | undefined;
default?: boolean | undefined;
}, {
type: "boolean";
default?: boolean | undefined;
optional?: boolean | undefined;
default?: boolean | undefined;
}>, z.ZodEffects<z.ZodObject<{
type: z.ZodLiteral<"enum">;
values: z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">;
optional: z.ZodOptional<z.ZodBoolean>;
default: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}>, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}>]>;
export type EnvFieldType = z.infer<typeof EnvFieldType>;
declare const EnvFieldMetadata: z.ZodUnion<[z.ZodObject<{
context: z.ZodLiteral<"client">;
access: z.ZodLiteral<"public">;
}, "strip", z.ZodTypeAny, {
declare const EnvFieldMetadata: z.ZodEffects<z.ZodType<{
context: "client";
access: "public";
}, {
} | {
context: "server";
access: "public";
} | {
context: "server";
access: "secret";
}, z.ZodTypeDef, {
context: "client";
access: "public";
}>, z.ZodObject<{
context: z.ZodLiteral<"server">;
access: z.ZodLiteral<"public">;
}, "strip", z.ZodTypeAny, {
} | {
context: "server";
access: "public";
}, {
} | {
context: "server";
access: "secret";
}>, {
context: "client";
access: "public";
} | {
context: "server";
access: "public";
}>, z.ZodObject<{
context: z.ZodLiteral<"server">;
access: z.ZodLiteral<"secret">;
}, "strip", z.ZodTypeAny, {
} | {
context: "server";
access: "secret";
}, {
context: "server";
access: "secret";
}>]>;
export declare const EnvSchema: z.ZodRecord<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, z.ZodIntersection<z.ZodUnion<[z.ZodObject<{
context: z.ZodLiteral<"client">;
access: z.ZodLiteral<"public">;
}, "strip", z.ZodTypeAny, {
context: "client";
access: "public";
} | {
context: "server";
access: "public";
} | {
context: "server";
access: "secret";
}>;
export declare const EnvSchema: z.ZodRecord<z.ZodEffects<z.ZodEffects<z.ZodString, string, string>, string, string>, z.ZodIntersection<z.ZodEffects<z.ZodType<{
context: "client";
access: "public";
} | {
context: "server";
access: "public";
} | {
context: "server";
access: "secret";
}, z.ZodTypeDef, {
context: "client";
access: "public";
} | {
context: "server";
access: "public";
} | {
context: "server";
access: "secret";
}>, {
context: "client";
access: "public";
} | {
context: "server";
access: "public";
} | {
context: "server";
access: "secret";
}, {
context: "client";
access: "public";
}>, z.ZodObject<{
context: z.ZodLiteral<"server">;
access: z.ZodLiteral<"public">;
}, "strip", z.ZodTypeAny, {
} | {
context: "server";
access: "public";
}, {
context: "server";
access: "public";
}>, z.ZodObject<{
context: z.ZodLiteral<"server">;
access: z.ZodLiteral<"secret">;
}, "strip", z.ZodTypeAny, {
} | {
context: "server";
access: "secret";
}, {
context: "server";
access: "secret";
}>]>, z.ZodUnion<[z.ZodObject<{
}>, z.ZodUnion<[z.ZodObject<{
type: z.ZodLiteral<"string">;
optional: z.ZodOptional<z.ZodBoolean>;
default: z.ZodOptional<z.ZodString>;
@@ -264,22 +282,22 @@ export declare const EnvSchema: z.ZodRecord<z.ZodEffects<z.ZodEffects<z.ZodStrin
includes?: string | undefined;
endsWith?: string | undefined;
startsWith?: string | undefined;
default?: string | undefined;
url?: boolean | undefined;
optional?: boolean | undefined;
min?: number | undefined;
url?: boolean | undefined;
default?: string | undefined;
max?: number | undefined;
min?: number | undefined;
}, {
type: "string";
length?: number | undefined;
includes?: string | undefined;
endsWith?: string | undefined;
startsWith?: string | undefined;
default?: string | undefined;
url?: boolean | undefined;
optional?: boolean | undefined;
min?: number | undefined;
url?: boolean | undefined;
default?: string | undefined;
max?: number | undefined;
min?: number | undefined;
}>, z.ZodObject<{
type: z.ZodLiteral<"number">;
optional: z.ZodOptional<z.ZodBoolean>;
@@ -291,19 +309,19 @@ export declare const EnvSchema: z.ZodRecord<z.ZodEffects<z.ZodEffects<z.ZodStrin
int: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: "number";
default?: number | undefined;
optional?: boolean | undefined;
min?: number | undefined;
default?: number | undefined;
max?: number | undefined;
min?: number | undefined;
gt?: number | undefined;
lt?: number | undefined;
int?: boolean | undefined;
}, {
type: "number";
default?: number | undefined;
optional?: boolean | undefined;
min?: number | undefined;
default?: number | undefined;
max?: number | undefined;
min?: number | undefined;
gt?: number | undefined;
lt?: number | undefined;
int?: boolean | undefined;
@@ -313,37 +331,37 @@ export declare const EnvSchema: z.ZodRecord<z.ZodEffects<z.ZodEffects<z.ZodStrin
default: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
type: "boolean";
default?: boolean | undefined;
optional?: boolean | undefined;
default?: boolean | undefined;
}, {
type: "boolean";
default?: boolean | undefined;
optional?: boolean | undefined;
default?: boolean | undefined;
}>, z.ZodEffects<z.ZodObject<{
type: z.ZodLiteral<"enum">;
values: z.ZodArray<z.ZodEffects<z.ZodString, string, string>, "many">;
optional: z.ZodOptional<z.ZodBoolean>;
default: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}>, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}, {
type: "enum";
values: string[];
default?: string | undefined;
type: "enum";
optional?: boolean | undefined;
default?: string | undefined;
}>]>>>;
type Prettify<T> = {
[K in keyof T]: T[K];

View File

@@ -64,11 +64,30 @@ const SecretServerEnvFieldMetadata = z.object({
context: z.literal("server"),
access: z.literal("secret")
});
const EnvFieldMetadata = z.union([
const _EnvFieldMetadata = z.union([
PublicClientEnvFieldMetadata,
PublicServerEnvFieldMetadata,
SecretServerEnvFieldMetadata
]);
const EnvFieldMetadata = z.custom().superRefine((data, ctx) => {
const result = _EnvFieldMetadata.safeParse(data);
if (result.success) {
return;
}
for (const issue of result.error.issues) {
if (issue.code === z.ZodIssueCode.invalid_union) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `**Invalid combination** of "access" and "context" options:
Secret client variables are not supported. Please review the configuration of \`env.schema.${ctx.path.at(-1)}\`.
Learn more at https://docs.astro.build/en/guides/environment-variables/#variable-types`,
path: ["context", "access"]
});
} else {
ctx.addIssue(issue);
}
}
});
const EnvSchemaKey = z.string().min(1).refine(([firstChar]) => isNaN(Number.parseInt(firstChar)), {
message: "A valid variable name cannot start with a number."
}).refine((str) => /^[A-Z0-9_]+$/.test(str), {

View File

@@ -1 +1 @@
export { setGetEnv, type GetEnv } from './runtime.js';
export { type GetEnv, setGetEnv } from './runtime.js';

View File

@@ -1,3 +1,2 @@
import fsMod from 'node:fs';
import type { AstroSettings } from '../@types/astro.js';
export declare function syncAstroEnv(settings: AstroSettings, fs?: typeof fsMod): void;
import type { AstroSettings } from '../types/astro.js';
export declare function syncAstroEnv(settings: AstroSettings): void;

34
node_modules/astro/dist/env/sync.js generated vendored
View File

@@ -1,15 +1,10 @@
import fsMod from "node:fs";
import { TYPES_TEMPLATE_URL } from "./constants.js";
import { ENV_TYPES_FILE } from "./constants.js";
import { getEnvFieldType } from "./validators.js";
function syncAstroEnv(settings, fs = fsMod) {
if (!settings.config.experimental.env) {
return;
}
const schema = settings.config.experimental.env.schema ?? {};
function syncAstroEnv(settings) {
let client = "";
let server = "";
for (const [key, options] of Object.entries(schema)) {
const str = `export const ${key}: ${getEnvFieldType(options)};
for (const [key, options] of Object.entries(settings.config.env.schema)) {
const str = ` export const ${key}: ${getEnvFieldType(options)};
`;
if (options.context === "client") {
client += str;
@@ -17,12 +12,21 @@ function syncAstroEnv(settings, fs = fsMod) {
server += str;
}
}
const template = fs.readFileSync(TYPES_TEMPLATE_URL, "utf-8");
const content = template.replace("// @@CLIENT@@", client).replace("// @@SERVER@@", server);
settings.injectedTypes.push({
filename: "astro/env.d.ts",
content
});
let content = "";
if (client !== "") {
content = `declare module 'astro:env/client' {
${client}}`;
}
if (server !== "") {
content += `declare module 'astro:env/server' {
${server}}`;
}
if (content !== "") {
settings.injectedTypes.push({
filename: ENV_TYPES_FILE,
content
});
}
}
export {
syncAstroEnv

View File

@@ -1,11 +1,10 @@
import type fsMod from 'node:fs';
import { type Plugin } from 'vite';
import type { AstroSettings } from '../@types/astro.js';
interface AstroEnvVirtualModPluginParams {
import type { Plugin } from 'vite';
import type { AstroSettings } from '../types/astro.js';
import type { EnvLoader } from './env-loader.js';
interface AstroEnvPluginParams {
settings: AstroSettings;
mode: 'dev' | 'build' | string;
fs: typeof fsMod;
sync: boolean;
envLoader: EnvLoader;
}
export declare function astroEnv({ settings, mode, fs, sync, }: AstroEnvVirtualModPluginParams): Plugin | undefined;
export declare function astroEnv({ settings, sync, envLoader }: AstroEnvPluginParams): Plugin;
export {};

View File

@@ -1,5 +1,4 @@
import { fileURLToPath } from "node:url";
import { loadEnv } from "vite";
import { readFileSync } from "node:fs";
import { AstroError, AstroErrorData } from "../core/errors/index.js";
import {
MODULE_TEMPLATE_URL,
@@ -8,41 +7,41 @@ import {
} from "./constants.js";
import { invalidVariablesToError } from "./errors.js";
import { getEnvFieldType, validateEnvVariable } from "./validators.js";
function astroEnv({
settings,
mode,
fs,
sync
}) {
if (!settings.config.experimental.env) {
return;
}
const schema = settings.config.experimental.env.schema ?? {};
function astroEnv({ settings, sync, envLoader }) {
const { schema, validateSecrets } = settings.config.env;
let isDev;
let templates = null;
return {
name: "astro-env-plugin",
enforce: "pre",
buildStart() {
const loadedEnv = loadEnv(
mode === "dev" ? "development" : "production",
fileURLToPath(settings.config.root),
""
);
function ensureTemplateAreLoaded() {
if (templates !== null) {
return;
}
const loadedEnv = envLoader.get();
if (!isDev) {
for (const [key, value] of Object.entries(loadedEnv)) {
if (value !== void 0) {
process.env[key] = value;
}
}
const validatedVariables = validatePublicVariables({
schema,
loadedEnv,
validateSecrets: settings.config.experimental.env?.validateSecrets ?? false,
sync
});
templates = {
...getTemplates(schema, fs, validatedVariables),
internal: `export const schema = ${JSON.stringify(schema)};`
};
}
const validatedVariables = validatePublicVariables({
schema,
loadedEnv,
validateSecrets,
sync
});
templates = {
...getTemplates(schema, validatedVariables, isDev ? loadedEnv : null),
internal: `export const schema = ${JSON.stringify(schema)};`
};
}
return {
name: "astro-env-plugin",
enforce: "pre",
config(_, { command }) {
isDev = command !== "build";
},
buildStart() {
ensureTemplateAreLoaded();
},
buildEnd() {
templates = null;
@@ -54,11 +53,13 @@ function astroEnv({
},
load(id, options) {
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.client)) {
return templates.client;
ensureTemplateAreLoaded();
return { code: templates.client };
}
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.server)) {
if (options?.ssr) {
return templates.server;
ensureTemplateAreLoaded();
return { code: templates.server };
}
throw new AstroError({
...AstroErrorData.ServerOnlyModule,
@@ -66,7 +67,8 @@ function astroEnv({
});
}
if (id === resolveVirtualModuleId(VIRTUAL_MODULES_IDS.internal)) {
return templates.internal;
ensureTemplateAreLoaded();
return { code: templates.internal };
}
}
};
@@ -103,9 +105,9 @@ function validatePublicVariables({
}
return valid;
}
function getTemplates(schema, fs, validatedVariables) {
function getTemplates(schema, validatedVariables, loadedEnv) {
let client = "";
let server = fs.readFileSync(MODULE_TEMPLATE_URL, "utf-8");
let server = readFileSync(MODULE_TEMPLATE_URL, "utf-8");
let onSetGetEnv = "";
for (const { key, value, context } of validatedVariables) {
const str = `export const ${key} = ${JSON.stringify(value)};`;
@@ -121,10 +123,15 @@ function getTemplates(schema, fs, validatedVariables) {
}
server += `export let ${key} = _internalGetSecret(${JSON.stringify(key)});
`;
onSetGetEnv += `${key} = reset ? undefined : _internalGetSecret(${JSON.stringify(key)});
onSetGetEnv += `${key} = _internalGetSecret(${JSON.stringify(key)});
`;
}
server = server.replace("// @@ON_SET_GET_ENV@@", onSetGetEnv);
if (loadedEnv) {
server = server.replace("// @@GET_ENV@@", `return (${JSON.stringify(loadedEnv)})[key];`);
} else {
server = server.replace("// @@GET_ENV@@", "return _getEnv(key);");
}
return {
client,
server

View File

@@ -0,0 +1,7 @@
import type * as vite from 'vite';
import type { EnvLoader } from './env-loader.js';
interface EnvPluginOptions {
envLoader: EnvLoader;
}
export declare function importMetaEnv({ envLoader }: EnvPluginOptions): vite.Plugin;
export {};

View File

@@ -0,0 +1,114 @@
import { transform } from "esbuild";
import MagicString from "magic-string";
import { createFilter, isCSSRequest } from "vite";
const importMetaEnvOnlyRe = /\bimport\.meta\.env\b(?!\.)/;
function getReferencedPrivateKeys(source, privateEnv) {
const references = /* @__PURE__ */ new Set();
for (const key in privateEnv) {
if (source.includes(key)) {
references.add(key);
}
}
return references;
}
async function replaceDefine(code, id, define, config) {
const replacementMarkers = {};
const env = define["import.meta.env"];
if (env) {
const marker = `__astro_import_meta_env${"_".repeat(
env.length - 23
)}`;
replacementMarkers[marker] = env;
define = { ...define, "import.meta.env": marker };
}
const esbuildOptions = config.esbuild || {};
const result = await transform(code, {
loader: "js",
charset: esbuildOptions.charset ?? "utf8",
platform: "neutral",
define,
sourcefile: id,
sourcemap: config.command === "build" ? !!config.build.sourcemap : true
});
for (const marker in replacementMarkers) {
result.code = result.code.replaceAll(marker, replacementMarkers[marker]);
}
return {
code: result.code,
map: result.map || null
};
}
function importMetaEnv({ envLoader }) {
let privateEnv;
let defaultDefines;
let isDev;
let devImportMetaEnvPrepend;
let viteConfig;
const filter = createFilter(null, ["**/*.html", "**/*.htm", "**/*.json"]);
return {
name: "astro:vite-plugin-env",
config(_, { command }) {
isDev = command !== "build";
},
configResolved(resolvedConfig) {
viteConfig = resolvedConfig;
const viteDefinePluginIndex = resolvedConfig.plugins.findIndex(
(p) => p.name === "vite:define"
);
if (viteDefinePluginIndex !== -1) {
const myPluginIndex = resolvedConfig.plugins.findIndex(
(p) => p.name === "astro:vite-plugin-env"
);
if (myPluginIndex !== -1) {
const myPlugin = resolvedConfig.plugins[myPluginIndex];
resolvedConfig.plugins.splice(viteDefinePluginIndex, 0, myPlugin);
resolvedConfig.plugins.splice(myPluginIndex, 1);
}
}
},
transform(source, id, options) {
if (!options?.ssr || !source.includes("import.meta.env") || !filter(id) || isCSSRequest(id) || viteConfig.assetsInclude(id)) {
return;
}
privateEnv ??= envLoader.getPrivateEnv();
if (isDev) {
const s = new MagicString(source);
if (!devImportMetaEnvPrepend) {
devImportMetaEnvPrepend = `Object.assign(import.meta.env,{`;
for (const key in privateEnv) {
devImportMetaEnvPrepend += `${key}:${privateEnv[key]},`;
}
devImportMetaEnvPrepend += "});";
}
s.prepend(devImportMetaEnvPrepend);
return {
code: s.toString(),
map: s.generateMap({ hires: "boundary" })
};
}
if (!defaultDefines) {
defaultDefines = {};
for (const key in privateEnv) {
defaultDefines[`import.meta.env.${key}`] = privateEnv[key];
}
}
let defines = defaultDefines;
if (importMetaEnvOnlyRe.test(source)) {
const references = getReferencedPrivateKeys(source, privateEnv);
let replacement = `(Object.assign(import.meta.env,{`;
for (const key of references.values()) {
replacement += `${key}:${privateEnv[key]},`;
}
replacement += "}))";
defines = {
...defaultDefines,
"import.meta.env": replacement
};
}
return replaceDefine(source, id, defines, viteConfig);
}
};
}
export {
importMetaEnv
};