@variant-forge/unplugin 0.1.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,20 +1,16 @@
1
- # Variant Forge Unplugin
1
+ # @variant-forge/unplugin
2
2
 
3
- This package provides a unified build plugin (for Vite, Webpack, Rollup, and esbuild) that evaluates feature flags and configurations from Variant Forge **at build time**.
4
-
5
- It uses the Node SDK to fetch and evaluate rules during the build process, then injects the evaluated values into your application as a virtual module (`virtual:variant-forge`). This allows you to bundle specific static configurations or feature flags directly into your client bundle, avoiding the need for an initial network request on the client.
3
+ `@variant-forge/unplugin` is a build-time plugin for Variant Forge supporting Vite, Webpack, Rollup, and esbuild. During `buildStart`, it fetches the environment ruleset once through `@variant-forge/sdk-server`, evaluates the requested keys against an optional static context, exposes them through the `virtual:variant-forge` module, and optionally generates TypeScript declarations. Because values are emitted as static constants, bundlers can eliminate unreachable branches when a flag evaluates to `false`.
6
4
 
7
5
  ## Installation
8
6
 
9
7
  ```bash
10
- npm install @variant-forge/unplugin -D
8
+ pnpm add -D @variant-forge/unplugin
11
9
  ```
12
10
 
13
- ## Usage
14
-
15
- ### 1. Configure the Plugin
11
+ ## Bundler setup
16
12
 
17
- Add the plugin to your bundler configuration. Below is an example for **Vite**:
13
+ Subpath exports are available for `@variant-forge/unplugin/vite`, `@variant-forge/unplugin/webpack`, `@variant-forge/unplugin/rollup`, and `@variant-forge/unplugin/esbuild`.
18
14
 
19
15
  ```typescript
20
16
  // vite.config.ts
@@ -24,92 +20,53 @@ import variantForge from '@variant-forge/unplugin/vite';
24
20
  export default defineConfig({
25
21
  plugins: [
26
22
  variantForge({
27
- // Your Server SDK key
28
- sdkKey: process.env.VARIANT_SERVER_KEY,
29
- apiUrl: 'http://localhost:3000',
30
-
31
- // The keys of configs/flags to fetch and bundle
32
- configs: ['max_retries', 'new_ui_v2'],
33
-
34
- // Optional: A static context to use for evaluation at build time
23
+ sdkKey: process.env.VARIANT_FORGE_SERVER_KEY!,
24
+ apiUrl: process.env.VARIANT_FORGE_API_URL || 'http://localhost:8000',
25
+ configs: ['ENABLE_DASHBOARD', 'API_URL'],
35
26
  context: { platform: 'web', env: 'production' },
27
+ schema: './app/schema.ts',
36
28
  }),
37
29
  ],
38
30
  });
39
31
  ```
40
32
 
41
- _Note: You can import from `@variant-forge/unplugin/webpack`, `/rollup`, or `/esbuild` depending on your bundler._
33
+ ## Options
42
34
 
43
- ### 2. Add TypeScript Definitions
35
+ `VariantUnpluginOptions`:
44
36
 
45
- If you are using TypeScript, you need to tell it about the virtual module. You can add the provided definitions to your `tsconfig.json` or `vite-env.d.ts` (or similar file):
37
+ - `sdkKey` (required): A `server` SDK key used to call `GET /ruleset` once during `buildStart`.
38
+ - `configs` (required): Array of configuration or feature flag keys to evaluate and expose in `virtual:variant-forge`.
39
+ - `apiUrl` (optional): Base URL of the Variant Forge Edge Functions. Defaults to `process.env.VARIANT_FORGE_API_URL`, then `http://localhost:8000`.
40
+ - `context` (optional): Static evaluation context (`Record<string, string | number | boolean | null>`) passed to targeting evaluation. Defaults to `{}`.
41
+ - `dts` (optional): Path for generated TypeScript declarations, or `false` to disable generation. Defaults to `'variant-forge.d.ts'`.
42
+ - `schema` (optional): Relative path to a schema module (for example `'./app/schema.ts'`). When set alongside declaration generation, the generated `.d.ts` file appends a `@variant-forge/sdk-client` `Register` augmentation referencing the module's `appSchema` export.
43
+ - `injectEnv` (optional): Enables bundler `define` hooks in Vite (`import.meta.env` and `process.env`) and Webpack (`DefinePlugin` for `process.env`). Because Vite `config()` and Webpack plugin setup execute before `buildStart()`, use `virtual:variant-forge` for static build-time injection in real builds.
44
+ - `envPrefix` (optional): Prefix used when `injectEnv` is enabled. Defaults to `'VARIANT_'`.
46
45
 
47
- ```typescript
48
- /// <reference types="@variant-forge/unplugin/client" />
49
- ```
46
+ ## Build-time security guard
50
47
 
51
- ### 3. Consume in your Application
48
+ Before finishing `buildStart`, the plugin inspects the fetched ruleset for every key listed in `configs`. If any requested key has `visibility: 'secret'`, the plugin closes the client and throws `[Variant Forge Security Guard] Build aborted!`, preventing confidential backend secrets from being compiled into client bundles. Keys with `plain` or `restricted` visibility pass the check.
52
49
 
53
- You can now import the virtual module directly in your application code. The module will contain the evaluated configurations and flags exactly as they were resolved during the build.
50
+ ## Consuming `virtual:variant-forge`
54
51
 
55
- ```typescript
56
- // Import all configurations as a default export
57
- import variantConfig from 'virtual:variant-forge';
58
-
59
- console.log(variantConfig.max_retries);
60
- console.log(variantConfig.new_ui_v2);
61
-
62
- // Or import specific keys as named exports
63
- import { max_retries, new_ui_v2 } from 'virtual:variant-forge';
64
-
65
- if (new_ui_v2) {
66
- console.log('Running the new UI!');
67
- }
68
- ```
69
-
70
- ### Tree-Shaking Support
71
-
72
- Because the virtual module exports static constants, modern bundlers (Vite, Rollup, Webpack) will automatically perform **tree-shaking (dead code elimination)** on unreachable branches.
52
+ Import named constants or the default object from `virtual:variant-forge`:
73
53
 
74
54
  ```typescript
75
- import { NEW_DASHBOARD } from 'virtual:variant-forge';
55
+ import variantConfig, { ENABLE_DASHBOARD, API_URL } from 'virtual:variant-forge';
76
56
 
77
- if (NEW_DASHBOARD) {
78
- // If NEW_DASHBOARD is evaluated as false during build time,
79
- // this code is stripped out completely from your bundle!
80
- initNewDashboard();
57
+ if (ENABLE_DASHBOARD) {
58
+ renderNewDashboard(API_URL);
81
59
  }
82
- ```
83
60
 
84
- ### Global Environment Variables (Optional)
61
+ console.log(variantConfig.API_URL);
62
+ ```
85
63
 
86
- If you prefer to use global variables instead of importing a virtual module, you can enable `injectEnv`. This will inject the fetched configurations directly into the bundler's global definitions.
64
+ ## TypeScript definitions
87
65
 
88
- ```typescript
89
- variantForge({
90
- sdkKey: process.env.VARIANT_SERVER_KEY,
91
- apiUrl: 'http://localhost:3000',
92
- configs: ['NEW_DASHBOARD'],
93
-
94
- // Inject into process.env / import.meta.env
95
- injectEnv: true,
96
- // Optional prefix (defaults to 'VARIANT_')
97
- envPrefix: 'APP_',
98
- });
99
- ```
66
+ By default, the plugin writes `variant-forge.d.ts` in the working directory with inferred primitive types (`boolean`, `number`, `string`, or `unknown`) for both named exports and the default export of `virtual:variant-forge`.
100
67
 
101
- Once enabled, you can access the variables directly in your code without any imports:
68
+ If you set `dts: false`, you can include the fallback client declaration shipped with the package (which types the default export as `Record<string, unknown>`):
102
69
 
103
70
  ```typescript
104
- // With Vite:
105
- if (import.meta.env.APP_NEW_DASHBOARD) {
106
- console.log('New dashboard enabled!');
107
- }
108
-
109
- // With Webpack or Vite:
110
- if (process.env.APP_NEW_DASHBOARD) {
111
- console.log('New dashboard enabled!');
112
- }
71
+ /// <reference types="@variant-forge/unplugin/client" />
113
72
  ```
114
-
115
- _Note: Tree-shaking applies to global variables as well._
@@ -0,0 +1,138 @@
1
+ // src/index.ts
2
+ import { createUnplugin } from "unplugin";
3
+ import { VariantServerClient } from "@variant-forge/sdk-server";
4
+ import fs from "fs";
5
+ import path from "path";
6
+ var virtualModuleId = "virtual:variant-forge";
7
+ var resolvedVirtualModuleId = "\0" + virtualModuleId;
8
+ var unplugin = createUnplugin((options) => {
9
+ if (!options || !options.sdkKey) {
10
+ throw new Error("Variant Forge unplugin requires sdkKey");
11
+ }
12
+ const envApiUrl = typeof process !== "undefined" && process.env?.VARIANT_FORGE_API_URL ? process.env.VARIANT_FORGE_API_URL : void 0;
13
+ const apiUrl = (options.apiUrl || envApiUrl || "http://localhost:8000").replace(/\/+$/, "");
14
+ const fetchedConfigs = {};
15
+ return {
16
+ name: "variant-forge-unplugin",
17
+ async buildStart() {
18
+ const client = new VariantServerClient({
19
+ sdkKey: options.sdkKey,
20
+ apiUrl
21
+ });
22
+ await client.sync();
23
+ const context = options.context || {};
24
+ for (const key of options.configs || []) {
25
+ fetchedConfigs[key] = client.getConfig(key, context);
26
+ if (fetchedConfigs[key] === null) {
27
+ fetchedConfigs[key] = client.isFeatureEnabled(key, context);
28
+ }
29
+ }
30
+ const ruleset = client.getRuleset();
31
+ const secretLeaks = (options.configs || []).filter((key) => {
32
+ const item = ruleset.find((r) => r.name === key);
33
+ return item?.visibility === "secret";
34
+ });
35
+ if (secretLeaks.length > 0) {
36
+ client.close();
37
+ throw new Error(
38
+ `[Variant Forge Security Guard] Build aborted! Attempted to bundle secret configs into client bundle: ${secretLeaks.join(
39
+ ", "
40
+ )}. Configurations with visibility 'secret' must never be bundled into public client applications.`
41
+ );
42
+ }
43
+ if (options.dts !== false) {
44
+ const dtsFileName = typeof options.dts === "string" ? options.dts : "variant-forge.d.ts";
45
+ let dtsContent = `/* eslint-disable */
46
+ // Auto-generated by @variant-forge/unplugin
47
+ `;
48
+ dtsContent += `declare module '${virtualModuleId}' {
49
+ `;
50
+ for (const [key, value] of Object.entries(fetchedConfigs)) {
51
+ const typeStr = typeof value === "boolean" ? "boolean" : typeof value === "number" ? "number" : typeof value === "string" ? "string" : "unknown";
52
+ dtsContent += ` export const ${key}: ${typeStr};
53
+ `;
54
+ }
55
+ dtsContent += ` const defaultExport: {
56
+ `;
57
+ for (const [key, value] of Object.entries(fetchedConfigs)) {
58
+ const typeStr = typeof value === "boolean" ? "boolean" : typeof value === "number" ? "number" : typeof value === "string" ? "string" : "unknown";
59
+ dtsContent += ` ${key}: ${typeStr};
60
+ `;
61
+ }
62
+ dtsContent += ` };
63
+ export default defaultExport;
64
+ }
65
+ `;
66
+ if (options.schema) {
67
+ const importPath = options.schema.replace(/\.tsx?$/, "");
68
+ dtsContent += `
69
+ declare module '@variant-forge/sdk-client' {
70
+ interface Register {
71
+ schema: typeof import('${importPath}').appSchema;
72
+ }
73
+ }
74
+ `;
75
+ }
76
+ try {
77
+ fs.writeFileSync(path.resolve(process.cwd(), dtsFileName), dtsContent, "utf-8");
78
+ } catch {
79
+ }
80
+ }
81
+ client.close();
82
+ },
83
+ resolveId(id) {
84
+ if (id === virtualModuleId) {
85
+ return resolvedVirtualModuleId;
86
+ }
87
+ return null;
88
+ },
89
+ load(id) {
90
+ if (id === resolvedVirtualModuleId) {
91
+ let code = "";
92
+ for (const [key, value] of Object.entries(fetchedConfigs)) {
93
+ code += `export const ${key} = ${JSON.stringify(value)};
94
+ `;
95
+ }
96
+ code += `export default {
97
+ `;
98
+ for (const key of Object.keys(fetchedConfigs)) {
99
+ code += ` ${key},
100
+ `;
101
+ }
102
+ code += `};
103
+ `;
104
+ return code;
105
+ }
106
+ return null;
107
+ },
108
+ vite: {
109
+ config() {
110
+ if (!options.injectEnv) return;
111
+ const prefix = options.envPrefix ?? "VARIANT_";
112
+ const defines = {};
113
+ for (const [key, value] of Object.entries(fetchedConfigs)) {
114
+ defines[`import.meta.env.${prefix}${key}`] = JSON.stringify(value);
115
+ defines[`process.env.${prefix}${key}`] = JSON.stringify(value);
116
+ }
117
+ return { define: defines };
118
+ }
119
+ },
120
+ webpack(compiler) {
121
+ if (!options.injectEnv) return;
122
+ const prefix = options.envPrefix ?? "VARIANT_";
123
+ const defines = {};
124
+ for (const [key, value] of Object.entries(fetchedConfigs)) {
125
+ defines[`process.env.${prefix}${key}`] = JSON.stringify(value);
126
+ }
127
+ if (compiler.webpack && compiler.webpack.DefinePlugin) {
128
+ compiler.options.plugins.push(new compiler.webpack.DefinePlugin(defines));
129
+ }
130
+ }
131
+ };
132
+ });
133
+ var index_default = unplugin;
134
+
135
+ export {
136
+ unplugin,
137
+ index_default
138
+ };
package/dist/esbuild.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unplugin
3
- } from "./chunk-VDS3W3XK.js";
3
+ } from "./chunk-ERIRH75T.js";
4
4
 
5
5
  // src/esbuild.ts
6
6
  var esbuild_default = unplugin.esbuild;
package/dist/index.d.ts CHANGED
@@ -5,7 +5,11 @@ interface VariantUnpluginOptions {
5
5
  * The Server SDK Key for your environment.
6
6
  */
7
7
  sdkKey: string;
8
- apiUrl: string;
8
+ /**
9
+ * The Variant Forge API base URL.
10
+ * If omitted, falls back to process.env.VARIANT_FORGE_API_URL or the default URL.
11
+ */
12
+ apiUrl?: string;
9
13
  /**
10
14
  * A list of config or feature flag keys you want to fetch and bundle at build time.
11
15
  */
@@ -23,6 +27,16 @@ interface VariantUnpluginOptions {
23
27
  * Prefix used for injected environment variables. Defaults to 'VARIANT_'.
24
28
  */
25
29
  envPrefix?: string;
30
+ /**
31
+ * File path to generate TypeScript declarations for virtual:variant-forge and schema registration.
32
+ * Set to false to disable. Defaults to 'variant-forge.d.ts'.
33
+ */
34
+ dts?: boolean | string;
35
+ /**
36
+ * Optional relative path to your Valibot schema file (e.g. './app/schema.ts').
37
+ * If specified, automatically generates global type registration for @variant-forge/sdk-client.
38
+ */
39
+ schema?: string;
26
40
  }
27
41
  declare const unplugin: unplugin$1.UnpluginInstance<VariantUnpluginOptions, boolean>;
28
42
 
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  index_default,
3
3
  unplugin
4
- } from "./chunk-VDS3W3XK.js";
4
+ } from "./chunk-ERIRH75T.js";
5
5
  export {
6
6
  index_default as default,
7
7
  unplugin
package/dist/rollup.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unplugin
3
- } from "./chunk-VDS3W3XK.js";
3
+ } from "./chunk-ERIRH75T.js";
4
4
 
5
5
  // src/rollup.ts
6
6
  var rollup_default = unplugin.rollup;
package/dist/vite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unplugin
3
- } from "./chunk-VDS3W3XK.js";
3
+ } from "./chunk-ERIRH75T.js";
4
4
 
5
5
  // src/vite.ts
6
6
  var vite_default = unplugin.vite;
package/dist/webpack.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  unplugin
3
- } from "./chunk-VDS3W3XK.js";
3
+ } from "./chunk-ERIRH75T.js";
4
4
 
5
5
  // src/webpack.ts
6
6
  var webpack_default = unplugin.webpack;
package/package.json CHANGED
@@ -1,31 +1,11 @@
1
1
  {
2
2
  "name": "@variant-forge/unplugin",
3
- "version": "0.1.7",
3
+ "version": "0.3.0",
4
+ "description": "Build-time plugin for Variant Forge feature flags and configurations",
5
+ "license": "MIT",
4
6
  "type": "module",
5
7
  "main": "./dist/index.js",
6
8
  "types": "./dist/index.d.ts",
7
- "files": [
8
- "dist",
9
- "client.d.ts"
10
- ],
11
- "dependencies": {
12
- "unplugin": "^3.4.0",
13
- "@variant-forge/sdk-node": "0.1.6"
14
- },
15
- "devDependencies": {
16
- "@types/node": "^22.15.3",
17
- "eslint": "^9.39.1",
18
- "tsup": "^8.4.0",
19
- "typescript": "5.9.2",
20
- "@package/typescript-config": "0.0.0",
21
- "@package/eslint-config": "0.0.0"
22
- },
23
- "scripts": {
24
- "build": "tsup src/index.ts src/vite.ts src/webpack.ts src/rollup.ts src/esbuild.ts --format esm --dts-resolve --clean",
25
- "lint": "eslint . --max-warnings 0",
26
- "check-types": "tsc --noEmit",
27
- "release": "pnpm run build && pnpm publish --access public"
28
- },
29
9
  "exports": {
30
10
  ".": {
31
11
  "types": "./dist/index.d.ts",
@@ -51,6 +31,36 @@
51
31
  "types": "./dist/esbuild.d.ts",
52
32
  "import": "./dist/esbuild.js",
53
33
  "default": "./dist/esbuild.js"
34
+ },
35
+ "./client": {
36
+ "types": "./client.d.ts"
54
37
  }
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "client.d.ts"
45
+ ],
46
+ "dependencies": {
47
+ "unplugin": "^3.4.0",
48
+ "@variant-forge/sdk-server": "0.3.0"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^22.15.3",
52
+ "eslint": "^9.39.1",
53
+ "tsup": "^8.4.0",
54
+ "typescript": "5.9.2",
55
+ "vitest": "^4.1.11",
56
+ "@package/typescript-config": "0.0.0",
57
+ "@package/eslint-config": "0.0.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsup src/index.ts src/vite.ts src/webpack.ts src/rollup.ts src/esbuild.ts --format esm --dts-resolve --clean",
61
+ "lint": "eslint . --max-warnings 0",
62
+ "check-types": "tsc --noEmit",
63
+ "test": "vitest run",
64
+ "release": "pnpm run build && pnpm publish --access public"
55
65
  }
56
66
  }
@@ -1,83 +0,0 @@
1
- // src/index.ts
2
- import { createUnplugin } from "unplugin";
3
- import { VariantNodeClient } from "@variant-forge/sdk-node";
4
- var virtualModuleId = "virtual:variant-forge";
5
- var resolvedVirtualModuleId = "\0" + virtualModuleId;
6
- var unplugin = createUnplugin((options) => {
7
- if (!options || !options.sdkKey || !options.apiUrl) {
8
- throw new Error("Variant Forge unplugin requires sdkKey and apiUrl");
9
- }
10
- const fetchedConfigs = {};
11
- return {
12
- name: "variant-forge-unplugin",
13
- async buildStart() {
14
- const client = new VariantNodeClient({
15
- sdkKey: options.sdkKey,
16
- apiUrl: options.apiUrl
17
- });
18
- await client.sync();
19
- const context = options.context || {};
20
- for (const key of options.configs || []) {
21
- fetchedConfigs[key] = client.getConfig(key, context);
22
- if (fetchedConfigs[key] === null) {
23
- fetchedConfigs[key] = client.isFeatureEnabled(key, context);
24
- }
25
- }
26
- client.close();
27
- },
28
- resolveId(id) {
29
- if (id === virtualModuleId) {
30
- return resolvedVirtualModuleId;
31
- }
32
- return null;
33
- },
34
- load(id) {
35
- if (id === resolvedVirtualModuleId) {
36
- let code = "";
37
- for (const [key, value] of Object.entries(fetchedConfigs)) {
38
- code += `export const ${key} = ${JSON.stringify(value)};
39
- `;
40
- }
41
- code += `export default {
42
- `;
43
- for (const key of Object.keys(fetchedConfigs)) {
44
- code += ` ${key},
45
- `;
46
- }
47
- code += `};
48
- `;
49
- return code;
50
- }
51
- return null;
52
- },
53
- vite: {
54
- config() {
55
- if (!options.injectEnv) return;
56
- const prefix = options.envPrefix ?? "VARIANT_";
57
- const defines = {};
58
- for (const [key, value] of Object.entries(fetchedConfigs)) {
59
- defines[`import.meta.env.${prefix}${key}`] = JSON.stringify(value);
60
- defines[`process.env.${prefix}${key}`] = JSON.stringify(value);
61
- }
62
- return { define: defines };
63
- }
64
- },
65
- webpack(compiler) {
66
- if (!options.injectEnv) return;
67
- const prefix = options.envPrefix ?? "VARIANT_";
68
- const defines = {};
69
- for (const [key, value] of Object.entries(fetchedConfigs)) {
70
- defines[`process.env.${prefix}${key}`] = JSON.stringify(value);
71
- }
72
- if (compiler.webpack && compiler.webpack.DefinePlugin) {
73
- compiler.options.plugins.push(new compiler.webpack.DefinePlugin(defines));
74
- }
75
- }
76
- };
77
- });
78
- var index_default = unplugin;
79
-
80
- export {
81
- unplugin,
82
- index_default
83
- };