Skip to content

import.meta.env respects morphed envs#227

Merged
yamcodes merged 1 commit intomainfrom
226-importmetaenv-does-not-respect-morphed-environment-variables
Oct 13, 2025
Merged

import.meta.env respects morphed envs#227
yamcodes merged 1 commit intomainfrom
226-importmetaenv-does-not-respect-morphed-environment-variables

Conversation

@yamcodes
Copy link
Owner

@yamcodes yamcodes commented Oct 13, 2025

  • Updated unit tests to mock environment variable creation and validate transformed values.
  • Added tests for handling various data types, including null, undefined, and special characters.
  • Improved the plugin's configuration hook to expose transformed environment variables through Vite's define option.

These changes enhance the robustness of the Vite plugin and ensure accurate handling of environment variables.

Closes #226

Summary by CodeRabbit

  • Bug Fixes

    • import.meta.env now correctly exposes transformed environment variables at build time, preserving schema defaults and type transformations.
    • Ensures consistent handling of strings, numbers, booleans, null, undefined, empty values, and exact key names.
  • Tests

    • Added comprehensive unit tests covering environment transformation, define mapping, empty environments, key preservation, and error propagation.
  • Chores

    • Updated changelog for a patch release.

- Updated unit tests to mock environment variable creation and validate transformed values.
- Added tests for handling various data types, including null, undefined, and special characters.
- Improved the plugin's configuration hook to expose transformed environment variables through Vite's define option.

These changes enhance the robustness of the Vite plugin and ensure accurate handling of environment variables.
@yamcodes yamcodes linked an issue Oct 13, 2025 that may be closed by this pull request
@changeset-bot
Copy link

changeset-bot bot commented Oct 13, 2025

🦋 Changeset detected

Latest commit: 1635a99

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@arkenv/vite-plugin Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel
Copy link

vercel bot commented Oct 13, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
arkenv Ready Ready Preview Comment Oct 13, 2025 3:06pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 13, 2025

Walkthrough

The Vite plugin’s config hook now collects transformed env values from createEnv and returns a Vite define mapping to expose them under import.meta.env.KEY. Added unit tests verify define serialization, key preservation, empty/env edge cases, and error propagation. A changeset entry documents the patch release.

Changes

Cohort / File(s) Summary
Changelog entry
\.changeset/tidy-worlds-fetch.md
Adds a patch changelog describing that morphed env values are now exposed via Vite’s define option.
Vite plugin implementation
packages/vite-plugin/src/index.ts
Updates config hook to call createEnv(...), build a define object mapping import.meta.env.KEY to JSON-stringified values, and return { define }.
Vite plugin tests
packages/vite-plugin/src/index.test.ts
Adds tests covering invocation of createEnv, define mapping of various types, key preservation, empty env behavior, and error propagation through the config hook.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Dev as vite.config.ts
  participant Vite as Vite Build
  participant Plugin as @arkenv/vite-plugin
  participant Ark as createEnv()

  Dev->>Vite: start build / dev
  Vite->>Plugin: config(config, env)
  Plugin->>Ark: createEnv(mode, schema, loaders)
  Ark-->>Plugin: transformedEnv
  Plugin->>Vite: return { define: { "import.meta.env.KEY": JSON.stringify(value), ... } }
  Note right of Vite: Vite inlines define mappings
  Vite-->>Dev: import.meta.env.KEY available with morphed values
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

@arkenv/vite-plugin, tests

Poem

A rabbit tweaks the Vitey breeze,
Morphs and maps with hopping ease.
Env keys shine, their types aligned,
In define’s warren, neatly signed.
Now burrows build without a fret—
import.meta knows what it should get. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly summarizes the main change by indicating that import.meta.env now respects morphed environment variables, which aligns precisely with the core objective of integrating createEnv transformations into Vite’s environment interface.
Linked Issues Check ✅ Passed The updated plugin config hook now returns a define object populated with JSON-stringified transformed values from createEnv, and the new unit tests validate type conversions, default values, custom logic, key preservation, empty environment handling, and error propagation, satisfying all coding objectives outlined in issue #226.
Out of Scope Changes Check ✅ Passed All modifications, including the added changelog entry, plugin code updates, and new unit tests, directly support the goal of exposing morphed environment variables through import.meta.env and do not introduce any unrelated or out-of-scope changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 226-importmetaenv-does-not-respect-morphed-environment-variables

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added docs Improvements or additions to documentation @arkenv/vite-plugin Issues or Pull Requests involving the Vite plugin for ArkEnv tests This issue or PR is about adding, removing or changing tests labels Oct 13, 2025
@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 13, 2025

Open in StackBlitz

npm i https://pkg.pr.new/arkenv@227
npm i https://pkg.pr.new/@arkenv/vite-plugin@227

commit: 1635a99

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/vite-plugin/src/index.ts (1)

20-22: Filter out undefined values in Vite define entries
Vite’s define option passes values to esbuild and requires valid expressions or JSON-serializable values; JSON.stringify(undefined) yields undefined (not a string), producing invalid replacements. Exclude undefined entries:

const define = Object.fromEntries(
-  Object.entries(<Record<string, unknown>>env).map(([key, value]) => [
-    `import.meta.env.${key}`,
-    JSON.stringify(value),
-  ]),
+  Object.entries(<Record<string, unknown>>env)
+    .filter(([, value]) => value !== undefined)
+    .map(([key, value]) => [
+      `import.meta.env.${key}`,
+      JSON.stringify(value),
+    ]),
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 469729a and 1635a99.

📒 Files selected for processing (3)
  • .changeset/tidy-worlds-fetch.md (1 hunks)
  • packages/vite-plugin/src/index.test.ts (3 hunks)
  • packages/vite-plugin/src/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.test.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.test.ts: Place tests alongside source files and use the .test.ts suffix (e.g., create-env.test.ts, types.test.ts, errors.test.ts, utils.test.ts)
Use Vitest's describe/it structure in tests
Test both success and failure cases for environment validation and utilities
Mock process.env to cover different environment scenarios in tests
In tests, save and restore process.env in setup/teardown (beforeEach/afterEach) to avoid leakage between cases
Verify both runtime behavior and TypeScript types in tests

Files:

  • packages/vite-plugin/src/index.test.ts
🧠 Learnings (2)
📚 Learning: 2025-09-12T06:23:45.463Z
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : Mock process.env to cover different environment scenarios in tests

Applied to files:

  • packages/vite-plugin/src/index.test.ts
📚 Learning: 2025-09-12T06:23:45.463Z
Learnt from: CR
PR: yamcodes/arkenv#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-09-12T06:23:45.463Z
Learning: Applies to **/*.test.ts : Test both success and failure cases for environment validation and utilities

Applied to files:

  • packages/vite-plugin/src/index.test.ts
🧬 Code graph analysis (2)
packages/vite-plugin/src/index.ts (2)
packages/arkenv/src/create-env.ts (1)
  • createEnv (21-34)
packages/arkenv/src/index.ts (1)
  • createEnv (13-13)
packages/vite-plugin/src/index.test.ts (1)
packages/vite-plugin/src/index.ts (1)
  • config (15-27)
🔇 Additional comments (9)
packages/vite-plugin/src/index.ts (1)

16-26: LGTM! The implementation correctly exposes morphed environment variables.

The config hook now properly integrates createEnv results with Vite's define option, ensuring schema transformations are respected in import.meta.env.

packages/vite-plugin/src/index.test.ts (7)

42-43: LGTM! Proper mock setup for fixture test.

The mock correctly returns the environment variables from the fixture configuration.


102-133: LGTM! Thorough test of createEnv invocation during config hook.

The test properly verifies that createEnv is called with the expected schema and environment object, using a complete mock context.


135-182: LGTM! Comprehensive test of define object generation.

The test thoroughly verifies that transformed values are correctly serialized and exposed through the define object with proper import.meta.env keys.


184-230: LGTM! Excellent coverage of edge cases.

The test thoroughly covers various data types including edge cases like null, undefined, empty string, zero, and false. The explicit expectation at line 225 that JSON.stringify(undefined) returns undefined documents the current behavior.

Note: This test confirms the undefined behavior I flagged in the implementation. Consider adding a comment or integration test to verify that Vite handles undefined values in the define object correctly.


232-259: LGTM! Good edge case coverage.

The test correctly verifies that an empty environment object produces an empty define object.


261-304: LGTM! Thorough test of key name preservation.

The test ensures that various key formats (uppercase, lowercase, numeric prefixes, special characters) are preserved exactly in the define output.


306-338: LGTM! Proper error propagation test.

The test correctly verifies that errors thrown by createEnv are propagated through the config hook, ensuring failures are not silently swallowed.

Based on learnings: The test follows the coding guideline to "Test both success and failure cases for environment validation and utilities."

.changeset/tidy-worlds-fetch.md (1)

1-11: LGTM! Clear and accurate changelog entry.

The changeset properly documents the fix, explaining both the previous problematic behavior and the new solution using Vite's define option to expose morphed environment variables.

@yamcodes yamcodes merged commit d41878f into main Oct 13, 2025
18 checks passed
@yamcodes yamcodes deleted the 226-importmetaenv-does-not-respect-morphed-environment-variables branch October 13, 2025 15:12
@arkenv-bot arkenv-bot bot mentioned this pull request Oct 13, 2025
yamcodes pushed a commit that referenced this pull request Oct 13, 2025
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## @arkenv/vite-plugin@0.0.14

### Patch Changes

- #### Support array defaults using `type().default()` syntax
_[`#224`](#224)
[`ecf9b64`](ecf9b64)
[@yamcodes](https://github.com/yamcodes)_

Fix to an issue where `type("array[]").default(() => [...])` syntax was
not accepted by the plugin due to overly restrictive type constraints.
The plugin now accepts any string-keyed record while still maintaining
type safety through ArkType's validation system.

    ##### New Features

- Array defaults to empty using `type("string[]").default(() => [])`
syntax
    -   Support for complex array types with defaults
    -   Mixed schemas combining string-based and type-based defaults

    ##### Example

    ```typescript
    // vite.config.ts
    import arkenv from "@arkenv/vite-plugin";
    import { type } from "arkenv";

    export default defineConfig({
      plugins: [
        arkenv({
ALLOWED_ORIGINS: type("string[]").default(() => ["localhost"]),
          FEATURE_FLAGS: type("string[]").default(() => []),
          PORT: "number.port",
        }),
      ],
    });
    ```

    > [!NOTE]
> This is the same fix as in [`arkenv@0.7.2` (the core
library)](https://github.com/yamcodes/arkenv/releases/tag/arkenv%400.7.2),
but for the Vite plugin.

- #### Fix `import.meta.env` not respecting morphed environment
variables _[`#227`](#227)
[`d41878f`](d41878f)
[@yamcodes](https://github.com/yamcodes)_

The Vite plugin now properly exposes transformed environment variables
through `import.meta.env`.

Previously, type transformations (`string → number`, `string → boolean`)
and default values were lost because the plugin only called
`createEnv()` without integrating the results with Vite's environment
system.

Now the plugin uses Vite's `define` option to expose the morphed values,
ensuring all schema transformations are respected.

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
yamcodes pushed a commit that referenced this pull request Nov 10, 2025
This PR contains the following updates:

| Package | Change | Age | Confidence |
|---|---|---|---|
| [@arkenv/vite-plugin](https://arkenv.js.org)
([source](https://redirect.github.com/yamcodes/arkenv)) | [`^0.0.10` ->
`^0.0.14`](https://renovatebot.com/diffs/npm/@arkenv%2fvite-plugin/0.0.10/0.0.14)
|
[![age](https://developer.mend.io/api/mc/badges/age/npm/@arkenv%2fvite-plugin/0.0.14?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/@arkenv%2fvite-plugin/0.0.10/0.0.14?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>yamcodes/arkenv (@&#8203;arkenv/vite-plugin)</summary>

###
[`v0.0.14`](https://redirect.github.com/yamcodes/arkenv/releases/tag/%40arkenv/vite-plugin%400.0.14)

[Compare
Source](https://redirect.github.com/yamcodes/arkenv/compare/@arkenv/vite-plugin@0.0.13...@arkenv/vite-plugin@0.0.14)

##### Patch Changes

- #### Support array defaults using `type().default()` syntax
*[`#224`](https://redirect.github.com/yamcodes/arkenv/pull/224)
[`ecf9b64`](https://redirect.github.com/yamcodes/arkenv/commit/ecf9b64a680d3af5c5786b288fda35608590f7a9)
[@&#8203;yamcodes](https://redirect.github.com/yamcodes)*

Fix to an issue where `type("array[]").default(() => [...])` syntax was
not accepted by the plugin due to overly restrictive type constraints.
The plugin now accepts any string-keyed record while still maintaining
type safety through ArkType's validation system.

  ##### New Features

- Array defaults to empty using `type("string[]").default(() => [])`
syntax
  - Support for complex array types with defaults
  - Mixed schemas combining string-based and type-based defaults

  ##### Example

  ```typescript
  // vite.config.ts
  import arkenv from "@&#8203;arkenv/vite-plugin";
  import { type } from "arkenv";

  export default defineConfig({
    plugins: [
      arkenv({
        ALLOWED_ORIGINS: type("string[]").default(() => ["localhost"]),
        FEATURE_FLAGS: type("string[]").default(() => []),
        PORT: "number.port",
      }),
    ],
  });
  ```

  > \[!NOTE]
> This is the same fix as in [`arkenv@0.7.2` (the core
library)](https://redirect.github.com/yamcodes/arkenv/releases/tag/arkenv%400.7.2),
but for the Vite plugin.

- #### Fix `import.meta.env` not respecting morphed environment
variables
*[`#227`](https://redirect.github.com/yamcodes/arkenv/pull/227)
[`d41878f`](https://redirect.github.com/yamcodes/arkenv/commit/d41878fe9cc2524f06ac2f0ef35f2f5ba58ee06b)
[@&#8203;yamcodes](https://redirect.github.com/yamcodes)*

The Vite plugin now properly exposes transformed environment variables
through `import.meta.env`.

Previously, type transformations (`string → number`, `string → boolean`)
and default values were lost because the plugin only called
`createEnv()` without integrating the results with Vite's environment
system.

Now the plugin uses Vite's `define` option to expose the morphed values,
ensuring all schema transformations are respected.

###
[`v0.0.13`](https://redirect.github.com/yamcodes/arkenv/releases/tag/%40arkenv/vite-plugin%400.0.13)

[Compare
Source](https://redirect.github.com/yamcodes/arkenv/compare/@arkenv/vite-plugin@0.0.12...@arkenv/vite-plugin@0.0.13)

##### Patch Changes

- #### Support Vite 2.x
*[`#212`](https://redirect.github.com/yamcodes/arkenv/pull/212)
[`bfe08f6`](https://redirect.github.com/yamcodes/arkenv/commit/bfe08f6d9f21352186420f0f68611840e164da52)
[@&#8203;yamcodes](https://redirect.github.com/yamcodes)*

Extended the supported Vite versions to include **2.9.18** through
**7.x** (inclusive).

Also, we've added the `vite-plugin` keyword to the `package.json`, and a
section in the `README.md` explaining why this plugin is a Vite only
plugin (and not a Rollup plugin).

<details><summary>Updated 1 dependency</summary>

<small>


[`e554e2b`](https://redirect.github.com/yamcodes/arkenv/commit/e554e2b41aab1b8e29d873982ea587c069f4732d)

</small>

- `arkenv@0.7.3`

</details>

###
[`v0.0.12`](https://redirect.github.com/yamcodes/arkenv/releases/tag/%40arkenv/vite-plugin%400.0.12)

[Compare
Source](https://redirect.github.com/yamcodes/arkenv/compare/@arkenv/vite-plugin@0.0.11...@arkenv/vite-plugin@0.0.12)

##### Patch Changes

<details><summary>Updated 1 dependency</summary>

<small>


[`e50dba1`](https://redirect.github.com/yamcodes/arkenv/commit/e50dba1f19418f8fc007dc786df1172067e3d07c)

</small>

- `arkenv@0.7.2`

</details>

###
[`v0.0.11`](https://redirect.github.com/yamcodes/arkenv/releases/tag/%40arkenv/vite-plugin%400.0.11)

[Compare
Source](https://redirect.github.com/yamcodes/arkenv/compare/@arkenv/vite-plugin@0.0.10...@arkenv/vite-plugin@0.0.11)

##### Patch Changes

<details><summary>Updated 1 dependency</summary>

<small>


[`221f9ef`](https://redirect.github.com/yamcodes/arkenv/commit/221f9efdef65691b0c5155b12ec460404dddbe82)
[`221f9ef`](https://redirect.github.com/yamcodes/arkenv/commit/221f9efdef65691b0c5155b12ec460404dddbe82)

</small>

- `arkenv@0.7.1`

</details>

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "on friday" (UTC), Automerge - At any
time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR was generated by [Mend Renovate](https://mend.io/renovate/).
View the [repository job
log](https://developer.mend.io/github/yamcodes/arkenv).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MS4xNzMuMSIsInVwZGF0ZWRJblZlciI6IjQxLjE3My4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

@arkenv/vite-plugin Issues or Pull Requests involving the Vite plugin for ArkEnv docs Improvements or additions to documentation tests This issue or PR is about adding, removing or changing tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

import.meta.env does not respect morphed environment variables

1 participant