@baojiliu/iris-plugin-client 0.0.0-stage → 0.1.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,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # @baojiliu/iris-plugin-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Iris 前端插件与宿主共用的契约。插件从这里导入 `Context`,不在插件里再声明一份。宿主实现 `slots`、`sidebar` 和 `locale`,并在 `inject` 列出的服务就绪后调用 `apply(ctx)`。
4
+
5
+ `@baojiliu/iris-plugin-client/vite` 导出 `irisPlugin()`。插件构建用它把 `react`、`react-dom`、`react/jsx-runtime` 换成宿主提供的同一份,并按 `peerDependencies` 写入口上的 `peers`。
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@baojiliu/iris-plugin-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Iris 前端插件与宿主共用的契约,以及插件构建时使用的 Vite 插件。",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/dsers/iris-plugin-client.git"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./src/index.ts",
14
+ "default": "./src/index.ts"
15
+ },
16
+ "./vite": {
17
+ "types": "./src/vite.ts",
18
+ "default": "./src/vite.ts"
19
+ }
20
+ },
21
+ "files": [
22
+ "src",
23
+ "README.md"
24
+ ],
25
+ "scripts": {
26
+ "test": "node --test src/sharedRuntime.test.ts src/vite.test.ts"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "devDependencies": {
32
+ "@types/react": "^19.0.0",
33
+ "@types/react-dom": "^19.0.0",
34
+ "@vitejs/plugin-react": "^4.3.4",
35
+ "react": "^19.0.0",
36
+ "react-dom": "^19.0.0",
37
+ "vite": "^6.0.0"
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Contract shared by the Iris host and frontend plugins.
3
+ * Plugins depend on this package; they do not declare Context themselves.
4
+ */
5
+
6
+ export type Dispose = () => void
7
+
8
+ /** Services a plugin may list in `inject`. The loader waits until each one exists. */
9
+ export const serviceNames = ["slots", "sidebar", "locale"] as const
10
+
11
+ export type ServiceName = (typeof serviceNames)[number]
12
+
13
+ export type Translate = (key: string) => string
14
+
15
+ export interface LocaleMessages {
16
+ zh: Record<string, string>
17
+ en: Record<string, string>
18
+ }
19
+
20
+ export interface Locale {
21
+ register(namespace: string, messages: LocaleMessages): Dispose
22
+ bind(namespace: string): Translate
23
+ }
24
+
25
+ export interface MainPanelProps {
26
+ pinned: boolean
27
+ t: Translate
28
+ }
29
+
30
+ export interface MainSlotMeta {
31
+ name: "main"
32
+ key: string
33
+ locale: string
34
+ inject: () => Record<string, never>
35
+ }
36
+
37
+ export interface SidebarSlotMeta {
38
+ name: "sidebar.panellist"
39
+ id: string
40
+ order?: number
41
+ locale: string
42
+ /** Host calls this on each sidebar render. */
43
+ label: () => string
44
+ }
45
+
46
+ export interface SidebarIconProps {
47
+ size: number
48
+ }
49
+
50
+ export interface SidebarPinEvent {
51
+ id: string
52
+ pinned: boolean
53
+ }
54
+
55
+ /**
56
+ * React slots. `inject` waits until the host has declared the slot, then runs `register`.
57
+ * The function returned from `register` removes that contribution.
58
+ */
59
+ export interface Slots {
60
+ inject(name: MainSlotMeta["name"] | SidebarSlotMeta["name"], register: () => Dispose): Dispose
61
+ register(meta: MainSlotMeta, render: (props: MainPanelProps) => unknown): Dispose
62
+ register(meta: SidebarSlotMeta, render: (props: SidebarIconProps) => unknown): Dispose
63
+ }
64
+
65
+ /** Read-only view of sidebar pin state. Changes arrive through `ctx.on("sidebar/pin")`. */
66
+ export interface Sidebar {
67
+ pinned(id: string): boolean
68
+ }
69
+
70
+ export interface Context {
71
+ slots: Slots
72
+ sidebar: Sidebar
73
+ locale: Locale
74
+ on(name: "sidebar/pin", handler: (event: SidebarPinEvent) => void): Dispose
75
+ /** Runs `setup` now. If `setup` returns a function, the host calls it when the plugin unloads. */
76
+ effect(setup: () => void | Dispose): void
77
+ }
78
+
79
+ export interface PluginModule {
80
+ inject: readonly ServiceName[]
81
+ apply(ctx: Context): void
82
+ peers?: Record<string, string>
83
+ }
@@ -0,0 +1,54 @@
1
+ import assert from "node:assert/strict"
2
+ import test from "node:test"
3
+
4
+ import {
5
+ appendPeersExport,
6
+ peersExportSource,
7
+ sharedModuleSource,
8
+ sourceExportsPeers,
9
+ } from "./sharedRuntime.ts"
10
+
11
+ test("react virtual module reads the react field and exports its own names", () => {
12
+ const source = sharedModuleSource("react", ["useState", "default", "__esModule"])
13
+ assert.match(source, /runtime\.react/)
14
+ assert.match(source, /export const useState = api\.useState/)
15
+ assert.match(source, /export default api/)
16
+ assert.doesNotMatch(source, /__esModule/)
17
+ assert.match(source, /iris plugin shared runtime missing/)
18
+ })
19
+
20
+ test("react-dom virtual module does not export useState", () => {
21
+ const source = sharedModuleSource("reactDOM", ["version", "createPortal"])
22
+ assert.match(source, /runtime\.reactDOM/)
23
+ assert.match(source, /export const version = api\.version/)
24
+ assert.match(source, /export const createPortal = api\.createPortal/)
25
+ assert.doesNotMatch(source, /useState/)
26
+ })
27
+
28
+ test("peers export keeps only string ranges", () => {
29
+ const source = peersExportSource({
30
+ react: "^19.0.0",
31
+ "react-dom": "^19.0.0",
32
+ skipped: 1,
33
+ })
34
+ assert.equal(
35
+ source,
36
+ 'export const peers = {"react":"^19.0.0","react-dom":"^19.0.0"}',
37
+ )
38
+ })
39
+
40
+ test("missing peerDependencies produces no export", () => {
41
+ assert.equal(peersExportSource(undefined), null)
42
+ })
43
+
44
+ test("appendPeersExport adds the statement to the entry", () => {
45
+ const next = appendPeersExport("export const apply = () => {}", 'export const peers = {"react":"^19.0.0"}')
46
+ assert.match(next, /export const apply/)
47
+ assert.match(next, /export const peers/)
48
+ })
49
+
50
+ test("sourceExportsPeers detects an existing peers export", () => {
51
+ assert.equal(sourceExportsPeers("export const peers = {}"), true)
52
+ assert.equal(sourceExportsPeers("export { peers }"), true)
53
+ assert.equal(sourceExportsPeers("export const apply = () => {}"), false)
54
+ })
@@ -0,0 +1,41 @@
1
+ export type SharedField = "react" | "reactDOM" | "jsxRuntime"
2
+
3
+ const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
4
+
5
+ export function sharedModuleSource(field: SharedField, exportNames: readonly string[]): string {
6
+ const named = exportNames
7
+ .filter((name) => name !== "default" && name !== "__esModule" && identifier.test(name))
8
+ .map((name) => `export const ${name} = api.${name}`)
9
+ .join("\n")
10
+ return [
11
+ "const runtime = globalThis.__IRIS_PLUGIN_SHARED__",
12
+ `if (!runtime || runtime.${field} == null) {`,
13
+ ' throw new Error("iris plugin shared runtime missing")',
14
+ "}",
15
+ `const api = runtime.${field}`,
16
+ named,
17
+ "export default api",
18
+ "",
19
+ ].join("\n")
20
+ }
21
+
22
+ export function peersExportSource(peerDependencies: unknown): string | null {
23
+ if (peerDependencies == null) return null
24
+ if (typeof peerDependencies !== "object" || Array.isArray(peerDependencies)) return null
25
+ const peers: Record<string, string> = {}
26
+ for (const [key, value] of Object.entries(peerDependencies)) {
27
+ if (typeof value === "string") peers[key] = value
28
+ }
29
+ return `export const peers = ${JSON.stringify(peers)}`
30
+ }
31
+
32
+ export function appendPeersExport(code: string, peersSource: string): string {
33
+ return `${code.trimEnd()}\n${peersSource}\n`
34
+ }
35
+
36
+ export function sourceExportsPeers(code: string): boolean {
37
+ return (
38
+ /export\s+(?:const|let|var|function|class)\s+peers\b/.test(code) ||
39
+ /export\s*\{[^}]*\bpeers\b/.test(code)
40
+ )
41
+ }
@@ -0,0 +1,109 @@
1
+ import assert from "node:assert/strict"
2
+ import fs from "node:fs/promises"
3
+ import os from "node:os"
4
+ import path from "node:path"
5
+ import test from "node:test"
6
+ import { fileURLToPath } from "node:url"
7
+
8
+ import react from "@vitejs/plugin-react"
9
+ import { build } from "vite"
10
+
11
+ import { irisPlugin } from "./vite.ts"
12
+
13
+ const packageRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..")
14
+
15
+ test("irisPlugin resolves the three shared specifiers", () => {
16
+ const plugin = irisPlugin()
17
+ assert.equal(plugin.name, "iris-shared-runtime")
18
+ assert.equal(plugin.resolveId("react"), "\0iris-shared:react")
19
+ assert.equal(plugin.resolveId("react-dom"), "\0iris-shared:react-dom")
20
+ assert.equal(plugin.resolveId("react/jsx-runtime"), "\0iris-shared:react/jsx-runtime")
21
+ assert.equal(plugin.resolveId("camelcase"), null)
22
+ assert.equal(plugin.enforce, "pre")
23
+ })
24
+
25
+ test("irisPlugin build externalizes React via shared runtime", async () => {
26
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "iris-vite-plugin-"))
27
+ const entryFile = path.join(root, "entry.tsx")
28
+ const pkgPath = path.join(root, "package.json")
29
+ const outDir = path.join(root, "dist")
30
+
31
+ await fs.writeFile(
32
+ pkgPath,
33
+ JSON.stringify(
34
+ {
35
+ name: "iris-plugin-fixture",
36
+ type: "module",
37
+ peerDependencies: {
38
+ react: "^19.0.0",
39
+ "react-dom": "^19.0.0",
40
+ },
41
+ },
42
+ null,
43
+ 2,
44
+ ),
45
+ )
46
+ await fs.writeFile(
47
+ entryFile,
48
+ [
49
+ 'import { useState } from "react"',
50
+ "",
51
+ "export function Widget() {",
52
+ " const [n, setN] = useState(0)",
53
+ " return <button type=\"button\" onClick={() => setN(n + 1)}>{n}</button>",
54
+ "}",
55
+ "",
56
+ ].join("\n"),
57
+ )
58
+ await fs.symlink(path.join(packageRoot, "node_modules"), path.join(root, "node_modules"))
59
+
60
+ try {
61
+ await build({
62
+ root,
63
+ logLevel: "silent",
64
+ plugins: [react(), irisPlugin()],
65
+ build: {
66
+ lib: {
67
+ entry: entryFile,
68
+ formats: ["es"],
69
+ fileName: "plugin",
70
+ },
71
+ minify: false,
72
+ modulePreload: false,
73
+ preserveEntrySignatures: "exports-only",
74
+ outDir,
75
+ rollupOptions: {
76
+ input: entryFile,
77
+ },
78
+ },
79
+ })
80
+
81
+ const bundle = await readJsBundle(outDir)
82
+
83
+ assert.match(bundle, /__IRIS_PLUGIN_SHARED__/)
84
+ assert.match(
85
+ bundle,
86
+ /(?:export const peers\s*=|const peers\s*=\s*\{[^}]*\};\s*export\s*\{[^}]*\bpeers\b)/,
87
+ )
88
+ assert.match(bundle, /"react"\s*:\s*"\^19\.0\.0"/)
89
+ assert.match(bundle, /"react-dom"\s*:\s*"\^19\.0\.0"/)
90
+ assert.doesNotMatch(bundle, /react\.production\.js/)
91
+ } finally {
92
+ await fs.rm(root, { recursive: true, force: true })
93
+ }
94
+ })
95
+
96
+ async function readJsBundle(dir: string): Promise<string> {
97
+ const files: string[] = []
98
+ async function walk(current: string) {
99
+ const entries = await fs.readdir(current, { withFileTypes: true })
100
+ for (const entry of entries) {
101
+ const fullPath = path.join(current, entry.name)
102
+ if (entry.isDirectory()) await walk(fullPath)
103
+ else if (entry.name.endsWith(".js")) files.push(fullPath)
104
+ }
105
+ }
106
+ await walk(dir)
107
+ const chunks = await Promise.all(files.map((file) => fs.readFile(file, "utf8")))
108
+ return chunks.join("\n")
109
+ }
package/src/vite.ts ADDED
@@ -0,0 +1,80 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import { pathToFileURL } from "node:url"
4
+
5
+ import {
6
+ appendPeersExport,
7
+ peersExportSource,
8
+ sharedModuleSource,
9
+ sourceExportsPeers,
10
+ type SharedField,
11
+ } from "./sharedRuntime.ts"
12
+
13
+ const sharedFields = {
14
+ react: "react",
15
+ "react-dom": "reactDOM",
16
+ "react/jsx-runtime": "jsxRuntime",
17
+ } as const satisfies Record<string, SharedField>
18
+
19
+ const prefix = "\0iris-shared:"
20
+
21
+ type ResolveFn = (
22
+ source: string,
23
+ importer?: string,
24
+ options?: { skipSelf?: boolean },
25
+ ) => Promise<{ id: string } | null>
26
+
27
+ export function irisPlugin() {
28
+ let entryFile = ""
29
+ let peersSource: string | null = null
30
+
31
+ return {
32
+ name: "iris-shared-runtime",
33
+ enforce: "pre" as const,
34
+ configResolved(config: {
35
+ root: string
36
+ build: { rollupOptions: { input?: unknown } }
37
+ }) {
38
+ const input = config.build.rollupOptions.input
39
+ if (typeof input !== "string") {
40
+ throw new Error("irisPlugin requires rollupOptions.input to be a string")
41
+ }
42
+ entryFile = input
43
+ const pkgPath = path.join(config.root, "package.json")
44
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8")) as {
45
+ peerDependencies?: unknown
46
+ }
47
+ peersSource = peersExportSource(pkg.peerDependencies)
48
+ },
49
+ resolveId(id: string) {
50
+ if (Object.prototype.hasOwnProperty.call(sharedFields, id)) return prefix + id
51
+ return null
52
+ },
53
+ async load(this: { resolve: ResolveFn }, id: string) {
54
+ if (!id.startsWith(prefix)) return null
55
+ const specifier = id.slice(prefix.length)
56
+ const field = sharedFields[specifier as keyof typeof sharedFields]
57
+ if (!field) return null
58
+ const resolved = await this.resolve(specifier, entryFile, { skipSelf: true })
59
+ if (!resolved) {
60
+ throw new Error(`iris plugin cannot resolve shared module ${specifier}`)
61
+ }
62
+ const nested = (
63
+ resolved as { meta?: { commonjs?: { resolved?: { id?: string } } } }
64
+ ).meta?.commonjs?.resolved?.id
65
+ const fileId = (nested ?? resolved.id).replace(/^\0/, "").split("?")[0]
66
+ const mod = (await import(pathToFileURL(fileId).href)) as Record<string, unknown>
67
+ const names = Object.keys(mod)
68
+ return sharedModuleSource(field, names)
69
+ },
70
+ transform(this: { error: (message: string) => never }, code: string, id: string) {
71
+ const clean = id.split("?")[0]
72
+ if (!entryFile || path.resolve(clean) !== path.resolve(entryFile)) return null
73
+ if (sourceExportsPeers(code)) {
74
+ this.error("plugin source already exports peers")
75
+ }
76
+ if (!peersSource) return null
77
+ return appendPeersExport(code, peersSource)
78
+ },
79
+ }
80
+ }