Skip to content

Keep track of original proxies for keys, so handling can be passed back to them #316

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@
"editor.defaultFormatter": "biomejs.biome"
},
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.experimental.useTsgo": true,
// "typescript.experimental.useTsgo": true,
"typescript.enablePromptUseWorkspaceTsdk": true
}
37 changes: 37 additions & 0 deletions packages/core/src/GlobalValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/** biome-ignore-all lint/suspicious/noExplicitAny: <explanation> */

/**
* The `GlobalValue` module ensures that a single instance of a value is created globally,
* even when modules are imported multiple times (e.g., due to mixing CommonJS and ESM builds)
* or during hot-reloading in development environments like Next.js or Remix.
*
* It achieves this by using a versioned global store, identified by a unique `Symbol` tied to
* the current version of the `effect` library. The store holds values that are keyed by an identifier,
* allowing the reuse of previously computed instances across imports or reloads.
*
* This pattern is particularly useful in scenarios where frequent reloading can cause services or
* single-instance objects to be recreated unnecessarily, such as in development environments with hot-reloading.
*
* @license MIT Copyright (c) 2023 Effectful Technologies Inc
* @source https://github.com/Effect-TS/effect/blob/main/packages/effect/src/GlobalValue.ts
* @since 2.0.0
*/
import { version } from "../package.json";

const globalStoreId = `effect/GlobalValue/globalStoreId/${version}`;

let globalStore: Map<unknown, any>;

export const globalValue = <A>(id: symbol, compute: (id: symbol) => A): A => {
if (!globalStore) {
// @ts-expect-error
globalThis[globalStoreId] ??= new Map();
// @ts-expect-error
globalStore = globalThis[globalStoreId] as Map<unknown, any>;
}
if (!globalStore.has(id)) {
globalStore.set(id, compute(id));
}
// biome-ignore lint/style/noNonNullAssertion: <explanation>
return globalStore.get(id)!;
};
39 changes: 35 additions & 4 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
* It contains the `createEnv` function that you can use to create your schema.
* @module
*/

import { globalValue } from "./GlobalValue.ts";
import type { StandardSchemaDictionary, StandardSchemaV1 } from "./standard.ts";
import { ensureSynchronous, parseWithDictionary } from "./standard.ts";

Expand Down Expand Up @@ -315,9 +317,11 @@
Simplify<Reduce<[StandardSchemaV1.InferOutput<TFinalSchema>, ...TExtends]>>
>;

/**
* Create a new environment variable schema.
*/
const serverKeysProp = globalValue(Symbol.for("t3-env/serverKeys"), (id) => ({
matches: (prop: string | symbol) => prop === id,
getValue: (obj: Record<PropertyKey, unknown>) => obj[id] as string[],
}));

export function createEnv<
TPrefix extends TPrefixFormat,
TServer extends TServerFormat = NonNullable<unknown>,
Expand Down Expand Up @@ -363,6 +367,7 @@
..._client,
..._shared,
};
const ownKeys = new Set(Object.keys(finalSchemaShape));

const parsed =
opts
Expand All @@ -382,7 +387,7 @@
const onInvalidAccess =
opts.onInvalidAccess ??
(() => {
throw new Error(

Check failure on line 390 in packages/core/src/index.ts

View workflow job for this annotation

GitHub Actions / test

packages/core/test/smoke-zod4.test.ts > client access on shared preset

Error: ❌ Attempted to access a server-side environment variable on the client ❯ onInvalidAccess packages/core/src/index.ts:390:13 ❯ Object.get packages/core/src/index.ts:445:46 ❯ packages/core/src/index.ts:420:18 ❯ createEnv packages/core/src/index.ts:415:44 ❯ packages/core/test/smoke-zod4.test.ts:850:15
"❌ Attempted to access a server-side environment variable on the client",
);
});
Expand All @@ -402,14 +407,40 @@
return prop === "__esModule" || prop === "$$typeof";
};

const serverKeys = isServer ? undefined : Object.keys(_server);

// a map of keys to the preset we got them from
const presetsByKey: Record<string, TExtendsFormat[number] | undefined> = {};

const extendedObj = (opts.extends ?? []).reduce((acc, curr) => {
return Object.assign(acc, curr);
for (const key in curr) {
if (!ownKeys.has(key)) {
presetsByKey[key] = curr;
}
acc[key] = curr[key];
}
const presetServerKeys = serverKeysProp.getValue(curr);
if (presetServerKeys) {
// these are keys that the proxy should handle but won't be exposed on the client
for (const key of presetServerKeys) {
if (!ownKeys.has(key)) {
presetsByKey[key] = curr;
}
}
}
return acc;
}, {});

const fullObj = Object.assign(extendedObj, parsed.value);

const env = new Proxy(fullObj, {
get(target, prop) {
// we need to expose these on the client side so we know to pass them off to the right proxy
if (serverKeysProp.matches(prop)) return serverKeys;
if (typeof prop !== "string") return undefined;
// pass off handling to the original proxy from the preset
const preset = presetsByKey[prop];
if (preset && !ownKeys.has(prop)) return preset[prop];
if (ignoreProp(prop)) return undefined;
if (!isValidServerAccess(prop)) return onInvalidAccess(prop);
return Reflect.get(target, prop);
Expand Down
39 changes: 32 additions & 7 deletions packages/core/test/smoke-valibot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,9 @@ describe("extending presets", () => {
});
describe("single preset", () => {
const processEnv = {
PRESET_ENV: "preset",
PRESET_SERVER_ENV: "server_preset",
PRESET_SHARED_ENV: "shared_preset",
PRESET_CLIENT_ENV: "client_preset",
SHARED_ENV: "shared",
SERVER_ENV: "server",
CLIENT_ENV: "client",
Expand All @@ -473,7 +475,19 @@ describe("extending presets", () => {
function lazyCreateEnv() {
const preset = createEnv({
server: {
PRESET_ENV: v.picklist(["preset"]),
PRESET_SERVER_ENV: v.literal("server_preset"),
},
clientPrefix: "PRESET_CLIENT_",
shared: {
PRESET_SHARED_ENV: v.string(),
},
client: {
PRESET_CLIENT_ENV: v.string(),
},
onInvalidAccess(variable) {
throw new Error(
`Attempted to access preset variable ${variable} on the client`,
);
},
runtimeEnv: processEnv,
});
Expand All @@ -489,6 +503,11 @@ describe("extending presets", () => {
client: {
CLIENT_ENV: v.string(),
},
onInvalidAccess(variable) {
throw new Error(
`Attempted to access variable ${variable} on the client`,
);
},
extends: [preset],
runtimeEnv: processEnv,
});
Expand All @@ -499,7 +518,9 @@ describe("extending presets", () => {
SERVER_ENV: string;
SHARED_ENV: string;
CLIENT_ENV: string;
PRESET_ENV: "preset";
PRESET_SERVER_ENV: "server_preset";
PRESET_SHARED_ENV: string;
PRESET_CLIENT_ENV: string;
}>
>();

Expand All @@ -513,7 +534,9 @@ describe("extending presets", () => {
SERVER_ENV: "server",
SHARED_ENV: "shared",
CLIENT_ENV: "client",
PRESET_ENV: "preset",
PRESET_SERVER_ENV: "server_preset",
PRESET_SHARED_ENV: "shared_preset",
PRESET_CLIENT_ENV: "client_preset",
});

globalThis.window = window;
Expand All @@ -526,13 +549,15 @@ describe("extending presets", () => {
const env = lazyCreateEnv();

expect(() => env.SERVER_ENV).toThrow(
"Attempted to access a server-side environment variable on the client",
"Attempted to access variable SERVER_ENV on the client",
);
expect(() => env.PRESET_ENV).toThrow(
"Attempted to access a server-side environment variable on the client",
expect(() => env.PRESET_SERVER_ENV).toThrow(
"Attempted to access preset variable PRESET_SERVER_ENV on the client",
);
expect(env.SHARED_ENV).toBe("shared");
expect(env.CLIENT_ENV).toBe("client");
expect(env.PRESET_SHARED_ENV).toBe("shared_preset");
expect(env.PRESET_CLIENT_ENV).toBe("client_preset");

globalThis.window = window;
});
Expand Down
39 changes: 32 additions & 7 deletions packages/core/test/smoke-zod3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,9 @@ describe("extending presets", () => {
});
describe("single preset", () => {
const processEnv = {
PRESET_ENV: "preset",
PRESET_SERVER_ENV: "server_preset",
PRESET_SHARED_ENV: "shared_preset",
PRESET_CLIENT_ENV: "client_preset",
SHARED_ENV: "shared",
SERVER_ENV: "server",
CLIENT_ENV: "client",
Expand All @@ -472,7 +474,19 @@ describe("extending presets", () => {
function lazyCreateEnv() {
const preset = createEnv({
server: {
PRESET_ENV: z.enum(["preset"]),
PRESET_SERVER_ENV: z.literal("server_preset"),
},
shared: {
PRESET_SHARED_ENV: z.string(),
},
clientPrefix: "PRESET_CLIENT_",
client: {
PRESET_CLIENT_ENV: z.string(),
},
onInvalidAccess(variable) {
throw new Error(
`Attempted to access preset variable ${variable} on the client`,
);
},
runtimeEnv: processEnv,
});
Expand All @@ -488,6 +502,11 @@ describe("extending presets", () => {
client: {
CLIENT_ENV: z.string(),
},
onInvalidAccess(variable) {
throw new Error(
`Attempted to access variable ${variable} on the client`,
);
},
extends: [preset],
runtimeEnv: processEnv,
});
Expand All @@ -498,7 +517,9 @@ describe("extending presets", () => {
SERVER_ENV: string;
SHARED_ENV: string;
CLIENT_ENV: string;
PRESET_ENV: "preset";
PRESET_SERVER_ENV: "server_preset";
PRESET_SHARED_ENV: string;
PRESET_CLIENT_ENV: string;
}>
>();

Expand All @@ -512,7 +533,9 @@ describe("extending presets", () => {
SERVER_ENV: "server",
SHARED_ENV: "shared",
CLIENT_ENV: "client",
PRESET_ENV: "preset",
PRESET_SERVER_ENV: "server_preset",
PRESET_SHARED_ENV: "shared_preset",
PRESET_CLIENT_ENV: "client_preset",
});

globalThis.window = window;
Expand All @@ -525,13 +548,15 @@ describe("extending presets", () => {
const env = lazyCreateEnv();

expect(() => env.SERVER_ENV).toThrow(
"Attempted to access a server-side environment variable on the client",
"Attempted to access variable SERVER_ENV on the client",
);
expect(() => env.PRESET_ENV).toThrow(
"Attempted to access a server-side environment variable on the client",
expect(() => env.PRESET_SERVER_ENV).toThrow(
"Attempted to access preset variable PRESET_SERVER_ENV on the client",
);
expect(env.SHARED_ENV).toBe("shared");
expect(env.CLIENT_ENV).toBe("client");
expect(env.PRESET_SHARED_ENV).toBe("shared_preset");
expect(env.PRESET_CLIENT_ENV).toBe("client_preset");

globalThis.window = window;
});
Expand Down
Loading
Loading