# Migrating extensions to Freelens v2
Freelens v2 breaks compatibility with the v1 extension API on purpose. This
guide is for authors of third-party extensions moving from v1 to v2.
It is the developer-facing half of the v2 extension specification. The
normative half — what the host guarantees, and what happens when a guarantee is
violated — is [`docs/extensions/api.md`](./api.md), with the
binary side in [`docs/extensions/binaries.md`](./binaries.md). Where this
guide says "the host does X", that document says why and what breaks otherwise.
Every v1 namespace path that moved or was removed is listed in the
[v1→v2 rename table](#v1v2-rename-table), with a link to the section that
explains the replacement.
How an extension is built, type-checked, tested and released is up to its
author, and outside the contract; this guide says what each of them has to
achieve, not how to wire it up. The reference template for those patterns —
the bundler configuration, the type-check programs, the test setup and the CI
workflows — is
[freelens-example-extension](https://github.com/freelensapp/freelens-example-extension).
Start from it rather than rediscovering them.
To port with a coding agent, the template ships the
[`port-freelens-extension-to-v2`](https://github.com/freelensapp/freelens-example-extension/blob/main/skills/port-freelens-extension-to-v2/SKILL.md)
skill, in the [Agent Skills](https://agentskills.io/specification) format.
Install it into the extension's repository:
```sh
npx skills add freelensapp/freelens-example-extension --skill port-freelens-extension-to-v2
```
The skill holds the workflow of the port and follows this guide, which it links
to for every API change; it does not replace it. For a new extension, the
template's
[`create-freelens-extension`](https://github.com/freelensapp/freelens-example-extension/blob/main/skills/create-freelens-extension/SKILL.md)
skill starts one from a copy of the template.
## Step one: bump `engines.freelens`
Before anything else:
```json
{ "engines": { "freelens": "^2.0.0" } }
```
**Until you do this, the host refuses your extension at discovery and the rest
of your work is invisible.** The gate is not advisory: `extensionApiVersion`
comes from the application version, so an extension declaring
`engines.freelens: "^1.6.2"` yields the range `>=1.6.0 <2.0.0-0`, which 2.0.0
does not satisfy. Every extension published for v1 is `isCompatible: false` on
v2 without a line of code being written.
## What changed, and why
- **ESM-first.** The application main process, renderer, and the extension API
are all ES modules. A **main** entry may be authored as ESM or CommonJS —
both are accepted, and both load from a real file path. A **renderer** entry
is ESM, and the host loads it by URL from a privileged scheme rather than
from disk.
- **No package manager is involved.** An extension vendors or bundles
everything it needs apart from what the host provides, so installing one is
downloading a tarball and extracting it. There are no dependencies to
resolve, which is why the dependency rules below are rules rather than
suggestions — nothing will hoist a missing package into place for you.
- **One published package.** `@freelensapp/extensions` is the only published
package. Every other `@freelensapp/*` package is `private` and is consumed by
the app as TypeScript source. Extensions must not depend on internal
`@freelensapp/*` packages directly.
- **Runtime-global API.** The app assigns the API object to a global at startup
in each process:
```ts
// main process (freelens/src/main/index.ts)
globalThis.FreelensExtensionApi = { Common, Main, ...mainExtensionApiSingletons };
// renderer (freelens/src/renderer/index.ts)
globalThis.FreelensExtensionApi = { Common, Renderer, ...rendererExtensionApiSingletons };
```
The host-provided libraries ride on that same object, next to the
namespaces — see below.
`@freelensapp/extensions` is a thin shim that re-exports that global. At
runtime the members resolve to the global whether your bundle inlines the
shim or marks it external.
## Import changes
The import specifier is unchanged — you still import from
`@freelensapp/extensions`:
```ts
import { Common, Main, Renderer } from "@freelensapp/extensions";
```
What changed is what those names resolve to at runtime:
- In the **main** process, `Common` and `Main` are defined; `Renderer` is
`undefined`.
- In the **renderer**, `Common` and `Renderer` are defined; `Main` is
`undefined`.
Only touch the namespace for the process your code runs in — this matches v1
behaviour, where a `Main`-only extension entrypoint never reached renderer APIs.
The published types still expose the full surface (`Common` / `Main` /
`Renderer`) so authoring against all three in a single-package extension keeps
type-checking, even though the wrong-process namespace is `undefined` at
runtime.
## `package.json` for an extension
- Set `engines.freelens` to `^2.0.0` (see [Step one](#step-one-bump-enginesfreelens)).
- Declare `@freelensapp/extensions` in **`devDependencies`**. Freelens installs
no dependencies of an extension — the installer only extracts your tarball —
so whatever your code needs at runtime and the host does not provide must
already be in your bundle. The package provides the types and a small shim
that reads the host's runtime global, and your bundler inlines that shim.
- Author your main entry as ESM or CommonJS. If you ship ESM, set
`"type": "module"` (or use `.mjs`). Your renderer entry must be ESM.
- Do not add any other `@freelensapp/*` package as a dependency — they are
private in v2 and are not published.
- Add **`electron`** as a `devDependency` for its types, at the version the
host runs. It is an _optional_ peer of `@freelensapp/extensions`: a required
`>=43.0.0` peer would be installed automatically at the newest Electron
major, not the host's.
### The host-provided libraries, and how to mark them external
These module ids must resolve to the host's instance rather than to a copy in
your bundle. You declare them in **`devDependencies`** — for compilation only —
and your bundler rewrites the bare id to a property of the host's global:
| Module id | Global |
| ------------------- | -------------------------------------- |
| `react` | `FreelensExtensionApi.React` |
| `react-dom` | `FreelensExtensionApi.ReactDom` |
| `react/jsx-runtime` | `FreelensExtensionApi.ReactJsxRuntime` |
| `mobx` | `FreelensExtensionApi.Mobx` |
| `mobx-react` | `FreelensExtensionApi.MobxReact` |
| `monaco-editor` | `FreelensExtensionApi.MonacoEditor` |
The global names follow a mechanical rule — strip the scope, split on `-`, `/`
and `.`, upper-case each segment — so a bundler plugin can _derive_ each name
instead of being handed a map. Note `ReactDom`, not `ReactDOM`.
Declare a listed package also when you never import it yourself but use a host
component whose props name its types. **`monaco-editor` is the one to watch.**
`Renderer.Component.MonacoEditor` takes its `options`, and the arguments of
`onChange` and its other callbacks, from `monaco-editor`'s types, and
`@freelensapp/extensions` declares `monaco-editor` only as an optional peer, so
nothing installs it for you. Without it in your `devDependencies`, those props
are `any`, and the type check does not say so, because `skipLibCheck` hides the
import that does not resolve. An extension that renders `MonacoEditor` declares
`monaco-editor` at the version the host runs, as it does `react` and `mobx`.
**Each process publishes the set it has.** The renderer publishes the whole
table; the main process publishes `Mobx` and nothing else, because a code editor
and a DOM renderer have no place in a process with no window. Map
in your main entry point only what main publishes — the rest is `undefined`
there, and marking it external gets you no error, only a later surprise.
Everything else may be bundled freely: `chart.js`, `react-select`, `conf`,
`immer`, `rfc6902`, `type-fest`, and a dependency-injection library of your own
(see [Dependency injection](#dependency-injection-bundle-your-own)). A bundled
`react-select` still gets the host's React, because that copy's own
`import "react"` is rewritten too.
Two ids that **leave** the v1 externals map, and both fail at runtime rather
than at build time if you keep them:
- **`@freelensapp/extensions`** — mapped in v1, when it was a fat re-export of
core. The v2 package is a thin shim that already reads the global, so
bundling it is correct.
- **`react-router-dom`** — no longer part of the host. Mapping it now yields
`undefined`.
If your v1 build used a Vite or Rolldown plugin that rewrote these ids to
`global.React` and friends, keep the plugin and change the target: the host
publishes them on `globalThis.FreelensExtensionApi`, not as top-level globals.
The v1 top-level globals are gone. What put them there was webpack's
`libraryTarget: "global"`, which assigned each process entry's exports onto
`global`; electron-vite emits an app bundle for the renderer and an ESM library
bundle for main, and neither assigns anything to `globalThis`. Nothing is a
top-level global in v2, in either process.
## React version (host-provided, must match majors)
Freelens v2 ships **React 19**. React is **host-provided**: the running app
publishes a single React instance on `globalThis.FreelensExtensionApi`, and
extensions must render through that shared instance.
There is no `Renderer.React` and no `Renderer.ReactDOM`. React reaches you
through the externals map in
[the section above](#the-host-provided-libraries-and-how-to-mark-them-external).
- **Do not bundle your own React.** Two copies of React in the same renderer
break the [Rules of Hooks](https://react.dev/warnings/invalid-hook-call-warning):
any hook (including those inside host components you render) throws an
"invalid hook call" at runtime. This fails only at runtime, not at build
time, so it is easy to miss.
- Declare `react`, `react-dom` and `@types/react*` as **`devDependencies`** and
mark them external. Not peer dependencies: a peer range would still install a
real React into your tree for your bundler to find, which is the mistake this
is trying to prevent. The `@freelensapp/extensions` types pin the React 19
major, so authoring against them keeps type-checking honest.
- Keep those devDependencies at the versions the host runs.
`@freelensapp/extensions` declares `react`, `react-dom`, `@types/react` and
`@types/react-dom` as optional peers, so its declaration compiles against your
copies and your package manager reports a version outside the host's range.
pnpm does that as a warning; set `strictPeerDependencies: true` to make it fail
the install.
- **A v1 extension starts from React 17.** Freelens 1.x ran React 17, so a v1
extension was type-checked against `@types/react` 17, and it moves two majors
to 19, because host-provided React and any React the extension bundles must
share the same major (see the invalid-hook-call trap above). Extensions
relying on host-provided React move with the host once their devDependencies
are at 19; extensions that bundled their own React need a matching bump.
React 18 and 19 removed long-deprecated APIs (for example `ReactDOM.render` /
`findDOMNode` and legacy string refs), so audit for those while upgrading.
Two changes between the React 17 and 19 types fail the type check of most v1
extensions. Neither changes what the host renders:
- **`children` is no longer implicit.** The React 17 types added `children` to
the props of every component; the React 19 types accept only the props a
component declares. Passing children to a host component whose props do not
declare them fails with TS2322. `Renderer.Component.LinkToObject` is the
common case: it renders its `content`, or the object's name without one, and
never rendered its children, so drop them, or pass the text as `content`:
```diff
-{ref.name}
+
```
In your own components, declare `children` in the props, or wrap them in
`PropsWithChildren
`.
- **`JSX` is no longer a global namespace.** `JSX.Element` fails with TS2503;
write `React.JSX.Element`, or `import type { JSX } from "react"`.
## Dependency injection: bundle your own
The host's dependency-injection library, `@ogre-tools/injectable` and
`@ogre-tools/injectable-react`, is **not** part of the extension API. The host
does not publish either on `FreelensExtensionApi`, the API exposes no container
and no injection token, and the host may move to another major — or another
library — in any release. A shared copy would give an extension nothing to work
with anyway: an injectable it created could not be registered in the host's
container, and it has no injectable of the host's to inject.
What to do instead:
- **Stop mapping `@ogre-tools/*` to `FreelensExtensionApi`.** Remove
`@ogre-tools/injectable` and `@ogre-tools/injectable-react` from the externals
of your bundler. A mapping left in place reads `undefined` at runtime, and the
build does not warn you.
- **If your extension uses dependency injection for its own code, bundle the
library** as an ordinary `dependency`, at whatever version you like, or use
another library altogether. With ogre-tools, create your own container with
`createContainer`, register your own injectables in it, and, if you use
`withInjectables` in the renderer, wrap your components in your own
`DiContextProvider` with that container. Your container is separate from the
host's: it holds none of the host's injectables, and the host never reads from
it.
- **Contribute to the host through the declarative fields** of your
`LensExtension` subclass (see
[Registering things: declarative fields](#registering-things-declarative-fields)),
not through injectables. That is the only route into the host's container.
## MobX 7 and mobx-react 10 (standard decorators only)
The host provides **mobx 7** and **mobx-react 10**. An extension uses the
host's copies through the externals map, so it moves with them whatever its own
`package.json` says. MobX 7 supports only **standard (TC39) decorators**; the
legacy, `experimentalDecorators` ones are gone, and so are the namespaced
annotations:
- Compile without `"experimentalDecorators"`. An extension compiled with it
hands the legacy call shape to mobx 7, and none of the resulting errors
mentions decorators. Recognise them by the message:
| Message | Cause |
| ---------------------------------------------------------------------------- | ------------------------------------------ |
| `TypeError: Cannot use 'in' operator to search for 'constructor' in ` | a legacy `@observable` field |
| ``[MobX] Invalid arguments for `action` `` | a legacy `@action` method |
| `TypeError: Reflect.ownKeys called on non-object` | `makeObservable(this)` without annotations |
The first two throw while the module is evaluated, when the class is
defined, so the extension never loads. The third throws when the class is
first instantiated. The `action` check exists only in mobx's development
build: under the production build, and with a legacy `@computed` in any
build, nothing throws and the member silently stays a plain method or
getter.
- A decorated field becomes an **auto-accessor**, and the constructor no longer
calls `makeObservable(this)`:
```ts
// v1
class Store {
@observable items: string[] = [];
@observable.ref selected: Item | undefined;
@computed get count() { return this.items.length; }
@action add(item: string) { this.items.push(item); }
constructor() {
makeObservable(this);
}
}
// v2
class Store {
@observable accessor items: string[] = [];
@observableRef accessor selected: Item | undefined;
@computed get count() { return this.items.length; }
@action add(item: string) { this.items.push(item); }
}
```
**Do not drop the `accessor`.** `@observable enabled = false;` on a plain
field still type-checks and builds, because mobx types its decorators as
field decorators too. The development build of mobx throws
``Please use `@observable accessor enabled` instead of `@observable enabled` ``
when the class is defined; the production build skips anything that is not
an accessor and leaves the field unobservable, so nothing reacts to it, and a
store whose `toJSON()` the host watches is never saved.
- `observable.ref`, `observable.shallow`, `observable.deep`,
`observable.struct`, `computed.struct`, `action.bound` and `flow.bound`
become `observableRef`, `observableShallow`, `observableDeep`,
`observableStruct`, `computedStruct`, `actionBound` and `flowBound`; the
`comparer.*` members become `compareIdentity`, `compareDefault`,
`compareStructural` and `compareShallow`. All of them are named exports of
`mobx`, and they work both as decorators and as `makeObservable` annotations.
- An auto-accessor lives on the prototype, so `toJS()`, `JSON.stringify`, spread
and structured cloning no longer see a decorated field. A class whose
instances are serialized, a catalog entity for example, keeps plain fields and
annotates them with `makeObservable(this, { … })` instead.
- Your bundler has to lower standard decorators: no Node or Electron release
runs them natively yet. See
[Lowering standard decorators](#lowering-standard-decorators) below.
- mobx-react 10 removed `Provider`, `inject`, `MobXProviderContext`,
`disposeOnUnmount`, `PropTypes`, `useObserver`, `useLocalStore`,
`useAsObservableSource`, `useStaticRendering`, the batching imports and
`observer(fn, { forwardRef: true })`. Use `React.createContext`, cleanup in
`componentWillUnmount` or `useEffect`, `useLocalObservable`,
`enableStaticRendering`, and `observer(React.forwardRef(…))`.
- **`this.props` of an `@observer` class component is not observable.** Its own
`render()` may read `this.props` and `this.state`; any other derivation that
reads them throws
`[mobx-react] Cannot read "MyPage.props" in a reactive context, as it isn't observable`.
That covers a `@computed` getter of the component, which could read
`this.props` under mobx-react 7 with `makeObservable(this)`. It also covers a
plain method the host calls from a derivation of its own: `getItems` and
`customizeHeader` of `KubeObjectListLayout` run inside the host's computed
values and in the render of another observer component. The type check, the
build and unit tests outside a renderer all pass; the page crashes when it
renders.
Read `this.props` only in `render()`, and hand a callback the host calls the
values it needs from there:
```tsx
// v1: throws under mobx-react 10 when the host calls getItems
@observer
class MyPage extends React.Component {
@computed get failed() {
return this.props.store.items.filter((item) => item.isFailed());
}
render() {
return this.failed} /* … */ />;
}
}
// v2
@observer
class MyPage extends React.Component {
render() {
const { store } = this.props;
return store.items.filter((item) => item.isFailed())} /* … */ />;
}
}
```
Or make it a function component, `observer((props: MyPageProps) => …)`,
whose props are a plain argument.
### Lowering standard decorators
The build must turn every standard decorator, and the `accessor` field it sits
on, into plain JavaScript, because the host's Node and Chromium cannot run them.
How depends on the bundler:
- **esbuild** lowers them itself. Mark decorators as unsupported, so that it
lowers them whatever `target` says, and compile without
`experimentalDecorators`:
```js
await esbuild.build({
// …
supported: { decorators: false },
tsconfigRaw: { compilerOptions: { experimentalDecorators: false } },
});
```
- **Babel** lowers them with `@babel/plugin-proposal-decorators` set to
`{ version: "2023-11" }`.
- **Vite 8, Rolldown and Vitest** transpile TypeScript with Oxc, which lowers
only legacy decorators and passes standard ones through untouched. Add a
plugin that runs before Oxc and hands each module with a decorator to esbuild.
Freelens builds itself this way, with
[`scripts/vite-plugin-standard-decorators.mjs`](../../scripts/vite-plugin-standard-decorators.mjs),
which you may copy under the MIT license:
```js
import { transform } from "esbuild";
const typeScriptModule = /\.[cm]?tsx?$/;
const decoratorAtLineStart = /^\s*@[A-Za-z_$]/m;
export function standardDecorators() {
return {
name: "standard-decorators",
enforce: "pre",
async transform(code, id) {
const path = id.split("?", 1)[0];
if (!typeScriptModule.test(path) || path.includes("/node_modules/") || !decoratorAtLineStart.test(code)) {
return null;
}
const result = await transform(code, {
loader: path.endsWith("x") ? "tsx" : "ts",
jsx: "preserve",
target: "esnext",
supported: { decorators: false },
sourcefile: path,
sourcemap: "external",
tsconfigRaw: {
compilerOptions: {
experimentalDecorators: false,
useDefineForClassFields: true,
verbatimModuleSyntax: false,
},
},
});
return { code: result.code, map: result.map };
},
};
}
```
Add `standardDecorators()` to the `plugins` of `vite.config` (and of
`vitest.config`, if the tests import decorated classes), and `esbuild` to your
`devDependencies`. The plugin lowers only the decorators and leaves JSX and
everything else to Oxc, so the rest of the build is unchanged.
A decorator that reaches the host unlowered is a syntax error when the module
is evaluated, so the extension fails to load.
## `tsconfig.json` for an extension
The bundled `extension-api.d.ts` sets these floors for consumer compilers:
- TypeScript 4.9 or newer — the declaration has `accessor` fields (on
`ItemStore`, `KubeApi` and `LensExtension`, among others), which older
compilers fail to parse with `TS1434: Unexpected keyword or identifier`.
`skipLibCheck` does not help, because it skips type checking, not parsing.
An extension that writes standard decorators itself needs TypeScript 5.0.
- `"skipLibCheck": true` — the type dependency graph is not guaranteed to be
clean under `skipLibCheck: false`, and checking it is not your job.
- `"lib"` with `ES2024` (or newer) — the mobx types reference
`ReadonlySetLike`, which first appears in the ES2024 lib. `DOM` and
`DOM.Iterable` belong in the renderer's config only; see
[Source layout](#source-layout-one-tsconfig-per-runtime-environment).
`"moduleResolution": "bundler"` (or `node16`/`nodenext`) both resolve the
package's `exports`.
The API namespaces work in type positions exactly as in v1:
```ts
import { Common, Renderer } from "@freelensapp/extensions";
const manifest: Common.PackageJson = { name: "my-extension", version: "1.0.0" };
function renderIcon(props: Renderer.Component.IconProps) {
/* ... */
}
```
## Source layout: one tsconfig per runtime environment
An extension has code for two runtime environments in one project. The main
entry point runs in Node, under Electron; the renderer entry point runs in a
browser page, which gets no Node and no Electron
([C4](./api.md#c4-module-format-and-loading)). One `tsconfig.json`
with both the DOM lib and `@types/node` cannot tell which APIs are valid where:
`import fs from "node:fs"`, `Buffer` and `process.env` compile in renderer code,
`document` and `window` compile in main code, and the mistake shows at runtime
instead. Give each environment its own directory and its own `tsconfig.json`,
and the type checker knows which environment it is checking:
```text
tsconfig.base.json options shared by the three configs below
src/
main/ main entry point: lib ES only, types ["node"]
tsconfig.json
renderer/ renderer entry point: lib ES + DOM, types []
tsconfig.json
common/ code both entry points import: lib ES + WebWorker, types []
tsconfig.json
```
The shared options carry the floors of the previous section, among them
`skipLibCheck`:
```json
{
"compilerOptions": {
"target": "ES2024",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"isolatedModules": true,
"skipLibCheck": true,
"noUncheckedSideEffectImports": true,
"noEmit": true
}
}
```
`src/main/tsconfig.json` has Node and no DOM:
```json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2024"],
"types": ["node"]
},
"include": ["./**/*", "../common/**/*"]
}
```
`src/renderer/tsconfig.json` has the DOM and no Node:
```json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2024", "DOM", "DOM.Iterable"],
"types": [],
"jsx": "react-jsx"
},
"include": ["./**/*", "../common/**/*"]
}
```
`src/common/tsconfig.json` has neither:
```json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"lib": ["ES2024", "WebWorker"],
"types": []
},
"include": ["./**/*"]
}
```
Type-check all three, in the script your build runs:
```json
"type:check": "tsc -p src/main && tsc -p src/renderer && tsc -p src/common"
```
Some settings here are required, and some are easy to lose:
- **`skipLibCheck: true` is required.** `extension-api.d.ts` is one declaration
for every process. It names DOM types that the main config does not have, and
`Main.Ipc` names the global `Electron` namespace, which only a config with
Electron types has. Checking it under any one environment reports errors in
the declaration, not in your code.
- **`@types/node` is yours to declare.** `"types": ["node"]` in the main config
needs it as a development dependency of the extension. `@freelensapp/extensions`
does not bring it, because its declaration names nothing of Node.
- **Electron types are optional in main.** Without them the `event` parameter of
a `Main.Ipc` handler is untyped. For a typed one, add `electron` as a
development dependency (for its types; it is never bundled) and write
`"types": ["node", "electron"]`.
- **Write `types` and `noUncheckedSideEffectImports` explicitly.** Both values
above are the defaults from TypeScript 6 on. An older compiler loads every
`@types` package it finds in `node_modules`, `@types/node` included, whatever
installed it, and does not check a side-effect import like `import "node:fs"`
at all.
- **The split does not cover the API namespaces.** The declaration exposes
`Main` and `Renderer` to every process, so `Main.Util.fetch` still compiles in
renderer code and is `undefined` when it runs
([C2](./api.md#c2-the-runtime-global-api)). Use `Common` in
common code.
Each entry point bundles its own copy of `src/common/`. Build the renderer for
the browser and the main entry for Node, keeping the builtins external in main
only, as
[Node and Electron in the renderer](#node-and-electron-in-the-renderer)
describes. With Vite 8 or Rolldown, building main for Node means
`platform: "node"` (`build.rolldownOptions.platform` in Vite) in the main run
only; the renderer run stays on `browser`, the default of a Vite build. A main
bundle with CommonJS in it throws when Freelens loads it otherwise, and the
build and the type check do not notice.
### What `common` may use
Common code runs in both processes, so it may use only what both have: the
ECMAScript library plus the web globals Node shares with a browser page —
`globalThis.crypto`, `TextEncoder` / `TextDecoder`, `URL` /
`URLSearchParams`, `AbortController`, `structuredClone`, and the timers
`setTimeout`, `clearTimeout` and `queueMicrotask`. Write `globalThis.` where
there is any doubt which global a name means, as for
[`crypto`](#node-and-electron-in-the-renderer). Keep a timer handle opaque: it
is a number in a browser and an object in Node, so annotating it as either
breaks the other.
That rule is checked twice, and it takes both:
- **The main and renderer configs include `src/common/`.** Compiled with main's
settings, common code fails on the DOM; compiled with the renderer's, it fails
on Node. What passes both is exactly what is valid in both, by construction,
and this is the check that decides.
- **`src/common/` has its own config for the editor.** An editor gives a file
to one config only: the nearest `tsconfig.json` that includes it. Without one
in `src/common/`, that is whatever `tsconfig.json` sits further up the tree,
if any, which checks common code as neither environment, or with the settings
of both at once. The `WebWorker` lib is the closest single match: a worker has
`crypto`, `fetch`, `URL`, `TextEncoder` and the timers, and no DOM and no
Node. It is an approximation. `self`, `postMessage`, `location` and
`importScripts` exist in a worker and not in Node, so the editor accepts them
and the main program rejects them.
A config that compiles does not yet prove that it separates anything. To keep
it honest, compile a file of lines that must fail with each config, each line
under a `// @ts-expect-error`: a config that starts accepting one of them fails
with an unused directive instead. With the renderer config, for example:
```ts
// @ts-expect-error a Node builtin
export { readFileSync } from "node:fs";
// @ts-expect-error a Node global
export const buffer = Buffer.from("text");
```
Export what each line declares, so that a line cannot go on failing for the
wrong reason, such as an unused import, once the config lets its API through.
**Compile that file together with your sources**, not on its own. `types` and
`lib` alone do not keep an environment pure: a declaration file with
`/// ` loads all of `@types/node` into any program
that reaches it, whatever `types` says, and one with
`/// ` loads the DOM. Such a declaration enters a
program only when a source file imports the package it belongs to, so a file
of probes compiled alone never reaches it and goes on passing while your
renderer code compiles against Node. A config that extends the source config,
keeps its `include` and adds the probes under `files` compiles both:
```json
{
"extends": "../src/renderer/tsconfig.json",
"files": ["node-apis.ts"]
}
```
When one of them catches a leak, keep the leak out rather than relax the probe.
For Node in the renderer, point `typeRoots` of the renderer config at a
directory with an empty `node` package, which a reference directive resolves to
first; for the DOM in main, remove the directive from the declaration with
`pnpm patch` or your package manager's equivalent.
The in-repo fixture extension checks its own configs this way, in
[`packages/fixture-extension/environment-tests/`](../../packages/fixture-extension/environment-tests).
### Optional: lint builtin imports in the renderer
A lint rule catches builtin imports as well, independently of which config an
editor picked. With Biome, apply `noNodejsModules` to the trees that must not
import them:
```json
{
"overrides": [
{
"includes": ["src/renderer/**", "src/common/**"],
"linter": {
"rules": {
"correctness": {
"noNodejsModules": "error"
}
}
}
}
]
}
```
It reports `node:fs` and a bare `fs` alike. It sees imports only, not
globals such as `Buffer` and `process`; the tsconfig split covers those.
## API namespace reorganization
Because compatibility is already broken, the API namespaces are reorganized
once, at this point. If your v1 extension reached into a specific
namespace path, re-check it against the current type surface; a symbol may have
moved between `Common`, `Main`, and `Renderer`.
This is what each namespace provides in v2:
| Namespace | Members |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Common` | `App`, `Catalog`, `Clusters`, `EventBus`, `Proxy`, `Store`, `Types`, `Util`, `logger`; types `InstalledExtension`, `LensExtension`, `LensExtensionManifest`, `Logger`, `PackageJson` |
| `Main` | `Catalog`, `Ipc`, `K8s`, `K8sApi`, `LensExtension`, `Navigation`, `Power`, `Shell`, `Util` |
| `Renderer` | `Catalog`, `Component`, `Ipc`, `K8s`, `K8sApi`, `LensExtension`, `Navigation`, `Theme`, `Util` |
**If a symbol is not reachable through one of those, it is not reachable at
all.** Every other `@freelensapp/*` package is private and is inlined into the
bundled declaration, so there is nothing left for you to install and a type-only
import fails at module resolution with no `@types/` fallback. If you hit a
missing re-export, that is a bug in the API surface worth reporting rather than
something to work around.
### `@freelensapp/kube-object` imports move into `K8sApi`
In v1 an extension could add `@freelensapp/kube-object` to its dependencies and
import the Kubernetes spec types from it. In v2 that package is private, so
**the whole of it is re-exported from `K8sApi`** — in `Common`, `Main` and
`Renderer` alike. Drop the dependency and read the types off the namespace:
```diff
-import type { Condition, LabelSelector, LocalObjectReference } from "@freelensapp/kube-object";
+import { Renderer } from "@freelensapp/extensions";
+
+type Condition = Renderer.K8sApi.Condition;
+type LabelSelector = Renderer.K8sApi.LabelSelector;
+type LocalObjectReference = Renderer.K8sApi.LocalObjectReference;
```
Everything the package exports is there, not a curated subset: the concrete kube
objects, the shared spec vocabulary (`Affinity`, `Capabilities`, `ContainerPort`,
`Probe`, `ResourceRequirements`, `Toleration`, …), the `types/` directory, the
JSON-API guards. The same applies to the kube APIs: the option and descriptor
types that appear in their signatures — `KubeApiOptions`,
`DerivedKubeApiOptions`, `KubeObjectStoreOptions`, `KubeApiListOptions`,
`KubeApiQueryParams`, `DeleteOptions`, `PropagationPolicy`, `ResourceDescriptor`,
`IKubeWatchEvent` — are exported too, along with `parseKubeApi` and
`createKubeApiURL`. You no longer need
`ConstructorParameters[0]` to name an options
type.
Two names to watch:
- **`KubeObjectStatus` is unchanged**: it is still the status-registration type
you register providers against, `{ level, text, timestamp? }`. The Kubernetes
status shape of the same name — `{ conditions?: BaseKubeObjectCondition[] }`,
the base that `DeploymentStatus`, `JobStatus` and the rest extend — is exported
as **`BaseKubeObjectStatus`**.
- **`Condition` and `ObjectReference` are now top-level names in `K8sApi`.** If
you flatten the namespace anywhere — `const { Condition } = Renderer.K8sApi`,
or a barrel that re-exports it alongside your own declarations — a local type
of the same name now collides. This is type-only: it surfaces as a compile
error in your extension, never as a runtime break, and renaming your own type
or qualifying the namespace member fixes it.
### v1→v2 rename table
The table compares the **published v1 declaration** of `@freelensapp/extensions`
with the v2 one, path by path: every value and type reachable through `Common`,
`Main` and `Renderer`, and the members of the classes, interfaces and object
types among them (written `Path#member`). A v1 path that is not listed is still
there under the same name. Names that are new in v2 are not listed; the names
`K8sApi` gained are covered [above](#freelensappkube-object-imports-move-into-k8sapi),
including `BaseKubeObjectStatus` and the `Condition` and `ObjectReference`
collisions to watch for.
The comparison covers the whole surface, not only the symbols one ported
extension happened to use. The in-repo fixture extension names every v2 path
of the first table in a type position and compiles against the built
declaration, so each replacement is proven reachable under real build
conditions rather than merely present in a `.d.ts`.
#### Renamed or moved
| v1 | v2 | Notes |
| -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `Renderer.Component.getDetailsUrl` | `Renderer.Navigation.getDetailsUrl` | same function |
| `Renderer.Component.showDetails` | `Renderer.Navigation.showDetails` | same function |
| `Renderer.Theme.getActiveTheme()` | `Renderer.Theme.activeTheme.get()` | `activeTheme` is a mobx computed, so reading it inside a reaction tracks theme changes |
| `new Main.K8sApi.ResourceStack(cluster, name)` | `Main.K8sApi.createResourceStack(cluster, name)` | same `kubectlApplyFolder` / `kubectlDeleteFolder`; name the type as `ReturnType` |
| `new Renderer.K8sApi.ResourceStack(cluster, name)` | `Renderer.K8sApi.createResourceStack(cluster, name)` | as for `Main` |
| `Renderer.Component.InputValidators.isExtensionNameInstallRegex.isMatch(value)` | `Renderer.Component.InputValidators.isExtensionNameInstallRegex.test(value)` | the regex is a plain `RegExp` now |
| `Renderer.Component.InputValidators.isExtensionNameInstallRegex.captures(value)` | `Renderer.Component.InputValidators.extensionNameInstallCaptures(value)` | same `{ name, version? } \| undefined` result |
#### Removed
Each entry is marked _value_, _type_, _class_ (a value and a type) or _member_.
`Common`:
- `Common.Types.IpcMainEvent`, `IpcMainInvokeEvent`, `IpcRendererEvent`,
`MenuRegistration`, `TrayMenuRegistration` (_type_) — see
[Unused members removed](#unused-members-removed).
- `Common.Util.base64`, `isBuffer`, `isChildProcessError`, `isErrnoException`,
`isExecException`, `isExecFileException`, `isRequestError`, `listTarEntries`,
`openBrowser`, `openExternal`, `readFileFromTar`, `unionPATHs` (_value_) —
see [`Util` members that need Node removed](#util-members-that-need-node-removed).
- `Common.PackageJson.Person`, `BugsLocation`, `Dependency`,
`DirectoryLocations`, `ExportCondition`, `Exports`, `JSPMConfiguration`,
`NonStandardEntryPoints`, `Scripts`, `TypeScriptConfiguration`,
`WorkspaceConfig`, `WorkspacePattern`, `YarnConfiguration` (_type_) —
`Common.PackageJson` itself stays, but no longer carries type-fest's
namespace of the same name. Import `PackageJson` from `type-fest` in your
own `devDependencies` if you need its members.
- `Common.App.slackUrl` (_value_) — it was always `""`.
- `Common.InstalledExtension#isBundled`, `Common.LensExtension#isBundled`
(_member_) — no replacement.
`Main`:
- `Main.K8sApi.forRemoteCluster` (_value_), `Main.K8sApi.IRemoteKubeApiConfig`
(_type_) — see [`K8sApi.forRemoteCluster` removed](#k8sapiforremotecluster-removed).
- `Main.K8sApi.isAllowedResource` (_value_) — in main it always returned
`false`. `Renderer.K8sApi.isAllowedResource`, which does answer, is unchanged
and renderer-only.
- `Main.K8sApi.IKubeApiCluster`, `Main.K8sApi.IgnoredKubeApiOptions` (_type_) —
both were deprecated and had no effect; drop them, and drop the ignored
`objectConstructor`, `kind`, `isNamespaces` and `apiBase` options from what
you pass to the `*Api` constructors.
- `Main.LensExtension#appMenus`, `Main.LensExtension#trayMenus` (_member_) — see
[Unused members removed](#unused-members-removed).
- `Main.LensExtension#isBundled` (_member_) — no replacement.
`Renderer`:
- `Renderer.Component.List` (_value_), `ListProps`, `SearchFilter` (_type_) —
see [`Renderer.Component.List` removed](#renderercomponentlist-removed).
- `Renderer.Component.VirtualList` (_value_), `VirtualListProps`,
`VirtualListRef`, `RowProps` (_type_) — see
[Unused members removed](#unused-members-removed).
- `Renderer.Component.NamespaceSelectBadgeNonInjected` (_value_),
`Renderer.Component.Dependencies` (_type_) — see
[`NamespaceSelectBadgeNonInjected` is gone with them](#namespaceselectbadgenoninjected-is-gone-with-them).
- `Renderer.Component.SliderProps`: the members it inherited from MUI's
`SliderProps` — `sx`, `slots`, `slotProps`, `marks`, `track`,
`valueLabelFormat` and the rest, and the HTML and ARIA attributes (_member_).
`SliderProps` now declares only `className`, `min`, `max`, `step`, `value`,
`disabled`, `orientation`, `valueLabelDisplay`, `onChange` and
`onChangeCommitted`.
- `Renderer.K8sApi` store classes (_class_): `ClusterRoleBindingStore`,
`ClusterRoleStore`, `ConfigMapStore` / `ConfigMapsStore`, `CronJobStore`,
`CustomResourceDefinitionStore` / `CRDStore`, `CustomResourceStore` /
`CRDResourceStore`, `DaemonSetStore`, `DeploymentStore`, `EndpointSliceStore`,
`EndpointsStore` / `EndpointStore`, `EventStore`,
`HorizontalPodAutoscalerStore` / `HPAStore`, `IngressClassStore`,
`IngressStore`, `JobStore`, `LimitRangeStore` / `LimitRangesStore`,
`NamespaceStore`, `NetworkPolicyStore`, `NodeStore` / `NodesStore`,
`PersistentVolumeClaimStore` / `VolumeClaimStore`, `PersistentVolumeStore` /
`PersistentVolumesStore`, `PodDisruptionBudgetStore` /
`PodDisruptionBudgetsStore`, `PodStore` / `PodsStore`, `PriorityClassStore` /
`PriorityClassStoreStore`, `ReplicaSetStore`, `ResourceQuotaStore` /
`ResourceQuotasStore`, `RoleBindingStore` / `RoleBindingsStore`, `RoleStore` /
`RolesStore`, `SecretStore` / `SecretsStore`, `ServiceAccountStore` /
`ServiceAccountsStore`, `ServiceStore`, `StatefulSetStore`,
`StorageClassStore`, `VerticalPodAutoscalerStore` — see
[`Renderer.K8sApi` concrete store classes removed](#rendererk8sapi-concrete-store-classes-removed).
- `Renderer.K8sApi.forRemoteCluster` (_value_),
`Renderer.K8sApi.IRemoteKubeApiConfig` (_type_) — see
[`K8sApi.forRemoteCluster` removed](#k8sapiforremotecluster-removed).
- `Renderer.K8sApi.IKubeApiCluster`, `Renderer.K8sApi.IgnoredKubeApiOptions`
(_type_) — as for `Main`.
- `Renderer.LensExtension#isBundled` (_member_) — no replacement.
## Registering things: declarative fields
Your extension contributes by **setting fields on your `LensExtension`
subclass**. The host reads them and translates each into its own registrations;
there is no registration API to call and no `Renderer.Registrations` namespace.
On `LensRendererExtension`: `globalPages`, `clusterPages`, `clusterPageMenus`,
`clusterFrameComponents`, `appPreferences`, `appPreferenceTabs`,
`entitySettings`, `statusBarItems`, `kubeObjectDetailItems`,
`kubeObjectMenuItems`, `kubeWorkloadsOverviewItems`, `commands`, `welcomeMenus`,
`catalogEntityDetailItems`, `topBarItems`, `additionalCategoryColumns`,
`customCategoryViews`, `kubeObjectHandlers`, `customResources`.
On `LensMainExtension`: `terminalShellEnvModifier`, which the host calls with
the environment of every terminal it opens. `appMenus` and `trayMenus` are gone
(see [Unused members removed](#unused-members-removed)).
On both: `protocolHandlers`, plus the `onActivate()` / `onDeactivate()` hooks.
A field you leave at its default contributes nothing, silently, so a
registration that never appears is usually a typo in a field name.
A registered component is typed with the props the host renders it with. A
page component receives only `params` (`Common.Types.PageComponentProps`), a
`kubeObjectMenuItems` `MenuItem` only `object` and `toolbar`, and the
`appPreferences` `Hint` and `Input` and a `clusterFrameComponents` `Component`
nothing. In v1 these accepted any component, so one that required more, such as
the extension instance, compiled and got `undefined` for it; in v2 it does not
compile. Pass what the component needs from the registration instead:
`Page: () => `.
A `kubeObjectDetailItems` `Details` or a `kubeObjectMenuItems` `MenuItem` may
be typed for the resource it is registered for, such as
`Renderer.Component.KubeObjectDetailsProps` or the props
of your own `Renderer.K8sApi.LensExtensionKubeObject` subclass. Register it with
`Renderer.K8sApi.detailsFor` or `Renderer.K8sApi.menuItemFor`, which take the
model class instead of `kind` and `apiVersions`:
```tsx
import { Renderer } from "@freelensapp/extensions";
export default class MyExtension extends Renderer.LensExtension {
kubeObjectDetailItems = [Renderer.K8sApi.detailsFor(Gateway, { priority: 10, Details: GatewayDetails })];
kubeObjectMenuItems = [Renderer.K8sApi.menuItemFor(Gateway, { MenuItem: GatewayMenuItem })];
}
```
The helpers return the plain registrations, with `kind` from the class's static
`kind` and `apiVersions` from its `crd.apiVersions` or, for a built-in class,
its `apiBase`. They type the component's `object` as an instance of the class,
so a component written for another kind does not compile. A plain registration,
with `kind`, `apiVersions` and `components` written out, still works, but
nothing ties its component to its `kind`: one registered under the wrong `kind`
compiles and gets an object whose `spec` and `status` are not the ones it reads.
Pass `apiVersions` to the helper when the cluster may serve the resource under
a version the class does not name, as it does for `HorizontalPodAutoscaler`,
`Ingress` and `IngressClass`; an object read under another version does not
match the registration. A class without a `kind`, or without any source of
`apiVersions`, makes the helper throw, and your extension fails to load with
that error.
The check compares the models' shapes, and declared `spec` and `status` types
do not make two models different enough for it: specs that differ only in
optional fields, as those of two versions of one kind usually do, are each
assignable to the other, and a component written for one version compiles
against the class of the other. Declare the instance `kind` and `apiVersion` of
your model class as literal types, matching its static `kind` and
`crd.apiVersions`, with a union of literals for a class that serves several
versions:
```ts
export class Example extends Renderer.K8sApi.LensExtensionKubeObject<
Renderer.K8sApi.NamespaceScopedMetadata,
ExampleStatus,
ExampleSpec
> {
declare kind: "Example";
declare apiVersion: "example.freelens.app/v1alpha1";
static readonly kind = "Example";
static readonly crd = {
apiVersions: ["example.freelens.app/v1alpha1"],
plural: "examples",
singular: "example",
};
// …
}
```
Then a component written for another version, or another kind, does not
compile against the class. `declare` emits nothing, so the class behaves at
runtime as before; keep it, because under standard class-field semantics a
field written without it (`kind!: "Example"`) resets the value the base class
assigned. See
[C6](./api.md#c6-registration-and-the-extension-instance) for the details.
`customResources` is new in v2. List in it the model classes of the custom
resources your extension presents with a sidebar entry and pages of its own:
```ts
export default class MyExtension extends Renderer.LensExtension {
customResources = [Kustomization, HelmRelease];
}
```
The host reads the group and plural of each from its `crd.apiVersions` and
`crd.plural`, or, for a class without a `crd`, from its `apiBase`, and while
your extension is enabled it leaves those resources out of the **Custom
Resources** tree of the cluster sidebar, where they would otherwise be listed a
second time under their API group. Their definitions stay in the
**Definitions** list, and the host's own list and details stay reachable by URL
and from the command palette. Leave out a model you only decorate with detail
or menu items and give no page of its own: registered, it would leave the tree
with nothing in its place. The classes of two versions of one resource name the
same group and plural, so listing both is harmless. A class without a `kind`,
without a `crd` or `apiBase` the group and plural can be read from, or naming a
resource of the core group, is rejected with an error in the log naming it, and
its resource stays in the tree.
A page that typed its parameters by name, such as
`PageComponentProps<{ query: string }>` or `{ params?: { query: PageParam } }`,
no longer fits `Page`, because the host knows the names only at runtime, from
the registration. Take `Common.Types.PageComponentProps` instead and read
`params.`, a `Renderer.Navigation.PageParam` whose `get()` returns the
current value; a name the registration's `params` does not declare is
`undefined`:
```tsx
const MyPage = ({ params }: Common.Types.PageComponentProps) =>