History

Spec-driven plugin loading (#476)

* init plugin * Spec-driven plugin loading Single source of truth for the plugin list lives in `executor.config.ts` (local + cloud). Each plugin's spec contributes its own HttpApiGroup, late-binding handlers Layer, and a Service tag the host satisfies — at boot for local, per request for cloud. New SDK helpers compose them: composePluginApi(plugins) composePluginHandlers(plugins, executor) // local: eager binding composePluginHandlerLayer(plugins) // cloud: leave Tag unbound providePluginExtensions(plugins)(executor) // cloud: per-request Frontend mirrors the same shape: `defineClientPlugin` declares pages, widgets, slot components, plus optional `sourcePlugin` / `secretProviderPlugin` contributions. The new `@executor-js/vite-plugin` reads `executor.config.ts` and emits a `virtual:executor/plugins-client` module from each plugin's `./client` export. The host wraps once with `<ExecutorPluginsProvider>` at the route root; pages call `useSourcePlugins()` / `useSecretProviderPlugins()` / `useClientPlugins()` instead of importing from any per-app aggregator. The SDK ships re-exports of Effect, Schema, HttpApi*, plus reactive primitives on the client side, so plugin authors can stay within `@executor-js/sdk` and `@executor-js/sdk/client` without reaching for `effect/*` directly. Each plugin declares two strings: `id` for runtime ergonomics (`executor.openapi.foo()`) and `packageName` for build-time resolution (`${packageName}/client`). No transforms, no scope conventions, no fallback magic. The Vite plugin warns loudly if `packageName` is set but unresolvable so typos fail visibly. Six existing plugins migrated (openapi, mcp, graphql, google-discovery, onepassword, workos-vault). New plugin-example serves as a canary — shared HttpApiGroup, server with extension/routes/handlers, client contributing a navbar page through the catch-all `/plugins/$pluginId/$` route. Local + cloud servers no longer manually wire each plugin's `*Group` / `*Handlers` / `*ExtensionService`; cloud retains a few type-only `*ExtensionService` imports for the per-request middleware's `provides` clause (framework requires static Tag identifiers there). Routes/shells/pages have zero plugin imports. Adding a plugin is a single edit to `executor.config.ts` plus a Vite restart. * Address PR feedback: derive types from plugin tuple, drop fanout - composePluginApi<TPlugins> now returns precisely typed HttpApi<"executor", CoreGroups | PluginGroups<TPlugins>> via a new TGroup generic on PluginSpec — cloud no longer imports OpenApiGroup, McpGroup, GraphqlGroup as types just to recover the API shape. - Cloud middleware provides clauses use PluginExtensionServices<typeof cloudPlugins> instead of importing each plugin's *ExtensionService type directly. Single tuple drives both runtime and types. - createPluginAtomClient reads plugin id from group.identifier — no more pluginId duplication at every call site. - defineExecutorConfig infers TDeps from the factory parameter, so apps annotate their deps inline (interface CloudPluginDeps {...} on the factory) instead of declare-module-augmenting a global ConfigPluginDeps interface. - cloud-plugins.ts holds the single executorConfig.plugins({}) call shared by protected-layers, protected, and the test harness. - Restore the apps/local blob table (accidental delete). * PR feedback round 2: optional deps, generic collapse, client test - ExecutorPluginsFactory takes `deps?` so the schema-gen CLI and Vite plugin call `config.plugins()` (not `config.plugins({})`). Apps annotate their deps inline with `({…}: Deps = {})`. - PluginSpec / Plugin defaults are now `any` for the wide slots so `AnyPlugin = Plugin<string>` covers any concrete plugin without a cascade of `any, any, any, …` at every callsite. PluginExtensions drops the same cascade. - Add `client.test.ts` covering the pluginId-from-group.identifier change: Service Tag key ("Plugin_<id>Client"), distinct keys per group, atom factories reachable. * Fix CI: lint, typecheck, and empty-test-suite failures - Add `passWithNoTests: true` vitest configs for the new vite-plugin and example plugin packages — they have no tests yet and were exiting non-zero on `vitest run`. - Add `bun-types` devDep to plugin-example so its tsconfig (`types: ["bun-types", "node"]`) resolves on CI. - Fix `aBody`/`bBody` `unknown` typecheck error in cloud/api.request-scope.node.test.ts (pre-existing on main). - Annotate the three `Layer.empty as unknown as …` widenings in plugin-routes.ts with `oxlint-disable-next-line executor/no-double-cast` + a one-line reason — TS can't witness that `Layer.empty` matches the computed merged-handler type through Layer's variance markers. - Suppress react/forbid-elements on the example plugin's raw `<input>` / `<button>` (the example demonstrates the SDK without depending on `@executor-js/react`'s component lib) and pass an explicit empty `reactivityKeys: []` on the demo mutation to satisfy the require-reactivity-keys rule. * Fix Cloudflare cloud build: pre-build vite-plugin via turbo Cloudflare's `vite build` runs through Node, which externalizes the workspace `@executor-js/vite-plugin` dep and then can't load its `./src/index.ts` source (Node ESM rejects `.ts`). Two coordinated fixes: - vite-plugin's exports are now condition-aware: `bun` keeps the TS source path (zero-build dev/test loop in Bun), `default` falls back to `./dist/index.js` for any non-Bun resolver (Node, the Cloudflare build). - cloud's `build` script now runs `turbo run build --filter @executor-js/vite-plugin && vite build` so the dist/ exists by the time vite resolves the import. Turbo caches the build, so repeated invocations are no-ops. * Pre-build vite-plugin for the local app's preview tarball build The CI's Build-preview-binary job runs `bunx --bun vite build` on `apps/local`. With vite-plugin's new condition-aware exports, Vite falls back to `default → ./dist/index.js`, which doesn't exist without a build. Mirror the cloud app's fix: prefix the build with `turbo run build --filter @executor-js/vite-plugin`. Turbo caches the artifact, so re-runs are no-ops. * Stop loading the example plugin in the local app The plugin package itself stays in the workspace as a reference implementation; just unwiring it from `apps/local/executor.config.ts` + dropping the workspace dep so it's no longer bundled into the local app's frontend.

Rhys Sullivan committed 6 months ago

Commit 48b1c7d1 parent b60caa594 files · +3053 −576Browse files

Showing the changes to packages/plugins/example/src (3 of 94 files). Show all

Unified · Split

3 files
  1. packages/plugins/example/src/client.tsx +88 −0
  2. packages/plugins/example/src/server.ts +75 −0
  3. packages/plugins/example/src/shared.ts +25 −0
packages/plugins/example/src/client.tsx+88−0
@@ -0,0 +1,88 @@
1+// ---------------------------------------------------------------------------
2+// @executor-js/plugin-example/client
3+//
4+// Frontend half: a single page that calls the plugin's `greet` mutation
5+// and renders the response. Demonstrates the typed reactive client
6+// pattern — `ExampleClient.mutation(...)` is fully typed against
7+// `ExampleApi` from `./shared` with no codegen.
8+//
9+// Server-only deps (Effect, Node, executor.config) MUST NOT be imported
10+// here — the Vite plugin bundles this entry into the frontend.
11+// ---------------------------------------------------------------------------
12+
13+import { useState } from "react";
14+import {
15+ defineClientPlugin,
16+ createPluginAtomClient,
17+ useAtomSet,
18+} from "@executor-js/sdk/client";
19+
20+import { ExampleApi } from "./shared";
21+
22+const ExampleClient = createPluginAtomClient(ExampleApi);
23+
24+const greetAtom = ExampleClient.mutation("example", "greet");
25+
26+function ExamplePage() {
27+ const [name, setName] = useState("world");
28+ const [result, setResult] = useState<string>();
29+ const doGreet = useAtomSet(greetAtom, { mode: "promise" });
30+
31+ return (
32+ <div style={{ maxWidth: 480, margin: "2rem auto", padding: "1rem" }}>
33+ <h1 style={{ fontSize: "1.25rem", marginBottom: "1rem" }}>Example plugin</h1>
34+ <div style={{ display: "flex", gap: 8 }}>
35+ {/* The example plugin demonstrates the SDK in isolation, so it
36+ uses raw HTML controls instead of `@executor-js/react`'s
37+ wrapped components — third-party plugin authors don't have
38+ to depend on the host's component library. */}
39+ {/* oxlint-disable-next-line react/forbid-elements */}
40+ <input
41+ value={name}
42+ onChange={(e) => setName(e.target.value)}
43+ style={{
44+ flex: 1,
45+ padding: "0.5rem 0.75rem",
46+ border: "1px solid #ccc",
47+ borderRadius: 6,
48+ }}
49+ />
50+ {/* oxlint-disable-next-line react/forbid-elements */}
51+ <button
52+ type="button"
53+ onClick={async () => {
54+ // Mutation has no shared state to invalidate — explicit
55+ // empty `reactivityKeys` documents the intent for the
56+ // `require-reactivity-keys` rule.
57+ const g = await doGreet({ payload: { name }, reactivityKeys: [] });
58+ setResult(`${g.message} (#${g.count})`);
59+ }}
60+ style={{
61+ padding: "0.5rem 0.75rem",
62+ border: "1px solid #ccc",
63+ borderRadius: 6,
64+ cursor: "pointer",
65+ }}
66+ >
67+ Greet
68+ </button>
69+ </div>
70+ {result && (
71+ <pre style={{ marginTop: "1rem", padding: "0.5rem", background: "#f5f5f5" }}>
72+ {result}
73+ </pre>
74+ )}
75+ </div>
76+ );
77+}
78+
79+export default defineClientPlugin({
80+ id: "example" as const,
81+ pages: [
82+ {
83+ path: "/",
84+ component: ExamplePage,
85+ nav: { label: "Example" },
86+ },
87+ ],
88+});
packages/plugins/example/src/server.ts+75−0
@@ -0,0 +1,75 @@
1+// ---------------------------------------------------------------------------
2+// @executor-js/plugin-example/server
3+//
4+// The server half of the example plugin. Demonstrates:
5+// - extension methods that hold the canonical implementation
6+// - an HttpApiGroup contributed via `routes`
7+// - a late-binding `handlers` Layer that consumes the plugin's
8+// extension via a Service tag (`ExampleExtensionService`); the host
9+// binds the tag at boot for local or per request for cloud
10+//
11+// React and other browser-only deps live in `./client` — never here.
12+// ---------------------------------------------------------------------------
13+
14+import {
15+ Context,
16+ definePlugin,
17+ Effect,
18+ HttpApi,
19+ HttpApiBuilder,
20+} from "@executor-js/sdk";
21+
22+import { ExampleApi } from "./shared";
23+
24+// Bundle the group into a single-group HttpApi for typing purposes only.
25+// The runtime composition uses group identity to merge into the host's
26+// FullApi, so this bundle never touches the host's wiring.
27+const ExampleApiBundle = HttpApi.make("example").add(ExampleApi);
28+
29+interface ExampleExtension {
30+ readonly greet: (
31+ name: string,
32+ ) => Effect.Effect<{ readonly message: string; readonly count: number }>;
33+}
34+
35+export class ExampleExtensionService extends Context.Service<
36+ ExampleExtensionService,
37+ ExampleExtension
38+>()("ExampleExtensionService") {}
39+
40+const ExampleHandlers = HttpApiBuilder.group(ExampleApiBundle, "example", (h) =>
41+ h.handle("greet", ({ payload }) =>
42+ Effect.gen(function* () {
43+ const ext = yield* ExampleExtensionService;
44+ return yield* ext.greet(payload.name);
45+ }),
46+ ),
47+);
48+
49+export const examplePlugin = definePlugin(() => ({
50+ id: "example" as const,
51+ packageName: "@executor-js/plugin-example",
52+
53+ // No DB schema — the counter lives in plugin storage (in-memory) so
54+ // the example plugin doesn't pull in migration plumbing.
55+ storage: () => ({ count: 0 }),
56+
57+ // Canonical implementation. CLI/tests/embedded callers and the HTTP
58+ // handler all hit this same code path.
59+ extension: (ctx): ExampleExtension => ({
60+ greet: (name: string) =>
61+ Effect.sync(() => {
62+ ctx.storage.count += 1;
63+ return {
64+ message: `hello ${name}`,
65+ count: ctx.storage.count,
66+ };
67+ }),
68+ }),
69+
70+ routes: () => ExampleApi,
71+ handlers: () => ExampleHandlers,
72+ extensionService: ExampleExtensionService,
73+}));
74+
75+export default examplePlugin;
packages/plugins/example/src/shared.ts+25−0
@@ -0,0 +1,25 @@
1+// ---------------------------------------------------------------------------
2+// @executor-js/plugin-example/shared
3+//
4+// Schemas and the HttpApiGroup definition shared between the server and
5+// client halves. Both `./server` and `./client` import from here so the
6+// frontend's typed reactive client and the backend's handlers see the
7+// exact same payload/response/error contracts.
8+//
9+// No React or Node imports here — server and client both import this.
10+// ---------------------------------------------------------------------------
11+
12+import { HttpApiEndpoint, HttpApiGroup, Schema } from "@executor-js/sdk";
13+
14+export const Greeting = Schema.Struct({
15+ message: Schema.String,
16+ count: Schema.Number,
17+});
18+export type Greeting = typeof Greeting.Type;
19+
20+export const ExampleApi = HttpApiGroup.make("example").add(
21+ HttpApiEndpoint.post("greet", "/greet", {
22+ payload: Schema.Struct({ name: Schema.String }),
23+ success: Greeting,
24+ }),
25+);

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t