@deepseek-ai/cordis-plugin-loader 1.0.1-rc.1

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.
@@ -0,0 +1,166 @@
1
+ import { composeError, Context } from '@deepseek-ai/cordis'
2
+ import { isNonNullable, type Dict } from '@deepseek-ai/cosmokit'
3
+ import { Entry, type EntryOptions } from './entry.ts'
4
+ import { EntryGroup } from './group.ts'
5
+
6
+ /** Mutable tree of loader entries. Persistence is supplied by subclasses. */
7
+ export abstract class EntryTree {
8
+ static readonly sep = ':'
9
+
10
+ public ctx: Context
11
+ public enableLogs?: boolean
12
+ public root: EntryGroup
13
+ public store: Dict<Entry> = Object.create(null)
14
+
15
+ constructor(ctx: Context) {
16
+ this.ctx = ctx.extend({ baseUrl: ctx.baseUrl })
17
+ this.root = new EntryGroup(this.ctx, this)
18
+ const entry = this.ctx.fiber.entry
19
+ if (entry) entry.subtree = this
20
+ }
21
+
22
+ get context(): Context {
23
+ return this.ctx
24
+ }
25
+
26
+ /** Iterate entries in this tree and any nested subtrees. */
27
+ * entries(): Generator<Entry, void, void> {
28
+ for (const entry of Object.values(this.store)) {
29
+ yield entry
30
+ if (!entry.subtree) continue
31
+ yield* entry.subtree.entries()
32
+ }
33
+ }
34
+
35
+ /** Return pending import and lifecycle tasks owned by this tree. */
36
+ getTasks() {
37
+ return [...this.entries()]
38
+ .map(entry => entry._initTask || entry.fiber?.inertia)
39
+ .filter(isNonNullable)
40
+ }
41
+
42
+ /**
43
+ * Wait until this tree has no active import or lifecycle tasks.
44
+ * @throws a settled fiber failure, or an aggregate when several fibers failed.
45
+ */
46
+ async await() {
47
+ while (true) {
48
+ const tasks = this.getTasks()
49
+ if (tasks.length) {
50
+ await Promise.allSettled(tasks)
51
+ continue
52
+ }
53
+ const outcomes = await Promise.allSettled(
54
+ [...this.entries()].map(entry => entry._await()),
55
+ )
56
+ const failures = outcomes
57
+ .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')
58
+ .map(outcome => outcome.reason)
59
+ if (failures.length === 1) throw failures[0]
60
+ if (failures.length > 1) throw new AggregateError(failures, 'loader fibers failed')
61
+ this.ctx.reflect.notify(['loader'])
62
+ if (!this.getTasks().length) return
63
+ }
64
+ }
65
+
66
+ ensureId(options: Partial<EntryOptions>) {
67
+ if (!options.id) {
68
+ do {
69
+ options.id = Math.random().toString(16).slice(2, 10)
70
+ } while (this.store[options.id])
71
+ }
72
+ return options.id!
73
+ }
74
+
75
+ /** Resolve an entry by id, including nested ids separated by `EntryTree.sep`. */
76
+ resolve(id: string) {
77
+ const parts = id.split(EntryTree.sep)
78
+ let tree: EntryTree | undefined = this
79
+ const final = parts.pop()!
80
+ for (const part of parts) {
81
+ tree = tree.store[part]?.subtree
82
+ if (!tree) throw new Error(`cannot resolve entry ${id}`)
83
+ }
84
+ const entry = tree.store[final]
85
+ if (!entry) throw new Error(`cannot resolve entry ${id}`)
86
+ return entry
87
+ }
88
+
89
+ resolveGroup(id: string | null) {
90
+ if (!id) return this.root
91
+ const entry = this.resolve(id)
92
+ if (!entry.subgroup) throw new Error(`entry ${id} is not a group`)
93
+ return entry.subgroup
94
+ }
95
+
96
+ /** Create an entry in the root group or a nested group. */
97
+ async create(options: Omit<EntryOptions, 'id'>, parent: string | null = null, position = Infinity) {
98
+ const group = this.resolveGroup(parent)
99
+ const id = await group.create(options)
100
+ const entry = this.resolve(id)
101
+ group.data.splice(position, 0, entry.options)
102
+ group.tree.write()
103
+ return id
104
+ }
105
+
106
+ /** Stop and remove an entry from its parent group. */
107
+ async remove(id: string) {
108
+ const entry = this.resolve(id)
109
+ await entry.parent.remove(id)
110
+ entry.parent.tree.write()
111
+ }
112
+
113
+ /** Update an entry and optionally move it to another group. */
114
+ async update(id: string, options: Omit<EntryOptions, 'id' | 'name'>, parent?: string | null, position?: number) {
115
+ const entry = this.resolve(id)
116
+ const source = entry.parent
117
+ const sourceIndex = source.data.indexOf(entry.options)
118
+ let target = source
119
+ if (parent !== undefined) {
120
+ target = this.resolveGroup(parent)
121
+ source.unlink(entry.options)
122
+ target.data.splice(position ?? Infinity, 0, entry.options)
123
+ entry.parent = target
124
+ }
125
+ try {
126
+ await entry.update(options, false, true)
127
+ } catch (error) {
128
+ if (parent !== undefined) {
129
+ target.unlink(entry.options)
130
+ source.data.splice(sourceIndex < 0 ? source.data.length : sourceIndex, 0, entry.options)
131
+ entry.parent = source
132
+ try {
133
+ await entry.update({}, false, true)
134
+ } catch (rollbackError) {
135
+ throw new AggregateError([error, rollbackError], `failed to roll back loader entry move ${id}`)
136
+ }
137
+ }
138
+ throw error
139
+ }
140
+ source.tree.write()
141
+ if (target !== source) target.tree.write()
142
+ }
143
+
144
+ /** Import a plugin module from a specifier or `cordis:` builtin. */
145
+ import(name: string, getOuterStack?: () => string[]) {
146
+ if (name.startsWith('cordis:')) {
147
+ return this.ctx.loader.builtins[name.slice(7)]
148
+ }
149
+ return composeError(async (info) => {
150
+ // ModuleJob.run
151
+ // onImport.tracePromise.__proto__
152
+ // internal.import
153
+ info.offset += 3
154
+ if (this.ctx.loader.internal) {
155
+ return await this.ctx.loader.internal.import(name, this.ctx.baseUrl!, {})
156
+ } else if (name.startsWith('.')) {
157
+ return await import(/* @vite-ignore */new URL(name, this.ctx.baseUrl).href)
158
+ } else {
159
+ return await import(/* @vite-ignore */name)
160
+ }
161
+ }, getOuterStack)
162
+ }
163
+
164
+ /** Persist current tree state. In-memory trees may implement this as a no-op. */
165
+ abstract write(): void
166
+ }
@@ -0,0 +1,32 @@
1
+ import { valueMap } from '@deepseek-ai/cosmokit'
2
+
3
+ // eslint-disable-next-line no-new-func
4
+ /** Evaluate a JavaScript expression against a loader context scope. */
5
+ export const evaluate = new Function('ctx', 'expr', `
6
+ with (ctx) {
7
+ return eval(expr)
8
+ }
9
+ `) as ((ctx: object, expr: string) => any)
10
+
11
+ /** Recursively replace YAML `!js` expression nodes with evaluated values. */
12
+ export function interpolate(ctx: object, value: any) {
13
+ if (isJsExpr(value)) {
14
+ return evaluate(ctx, value.__jsExpr)
15
+ } else if (!value || typeof value !== 'object') {
16
+ return value
17
+ } else if (Array.isArray(value)) {
18
+ return value.map(item => interpolate(ctx, item))
19
+ } else {
20
+ return valueMap(value, item => interpolate(ctx, item))
21
+ }
22
+ }
23
+
24
+ /** Return true when a value is a serialized loader JavaScript expression. */
25
+ export function isJsExpr(value: any): value is JsExpr {
26
+ return value instanceof Object && '__jsExpr' in value
27
+ }
28
+
29
+ /** Serialized JavaScript expression produced by the include YAML tag. */
30
+ export interface JsExpr {
31
+ __jsExpr: string
32
+ }
package/src/index.ts ADDED
@@ -0,0 +1,205 @@
1
+ import { Context, FiberState, Inject, Service, type Fiber } from '@deepseek-ai/cordis'
2
+ import { defineProperty, isNullable, type Dict } from '@deepseek-ai/cosmokit'
3
+ import { ModuleLoader } from './internal.ts'
4
+ import {
5
+ Entry,
6
+ EntryConfigResolver,
7
+ type EntryConfigResolver as ConfigResolver,
8
+ type EntryOptions,
9
+ } from './config/entry.ts'
10
+ import { EntryGroup } from './config/group.ts'
11
+ import isolate from './config/isolate.ts'
12
+ import { EntryTree } from './config/tree.ts'
13
+ import { interpolate } from './config/utils.ts'
14
+
15
+ /** Re-export entry node APIs. */
16
+ export * from './config/entry.ts'
17
+ /** Re-export nested entry group APIs. */
18
+ export * from './config/group.ts'
19
+ /** Re-export service isolation helpers. */
20
+ export * from './config/isolate.ts'
21
+ /** Re-export entry tree persistence APIs. */
22
+ export * from './config/tree.ts'
23
+ /** Re-export loader config expression helpers. */
24
+ export * from './config/utils.ts'
25
+ /** Re-export Node internal module loader compatibility types. */
26
+ export * from './internal.ts'
27
+
28
+ declare module '@deepseek-ai/cordis' {
29
+ interface Events {
30
+ 'exit'(signal: NodeJS.Signals): Promise<void>
31
+ 'loader/config-update'(): void
32
+ 'loader/entry-init'(entry: Entry): void
33
+ 'loader/partial-dispose'(entry: Entry, legacy: Partial<EntryOptions>, active: boolean): void
34
+ 'loader/patch-context'(entry: Entry, next: () => void | Promise<void>): void | Promise<void>
35
+ }
36
+
37
+ interface Context {
38
+ loader: Loader
39
+ }
40
+
41
+ interface EnvData {
42
+ startTime?: number
43
+ }
44
+
45
+ interface Fiber {
46
+ entry?: Entry
47
+ }
48
+ }
49
+
50
+ /** Loader config and dependency intercept namespace. */
51
+ export namespace Loader {
52
+ /** Root loader configuration. */
53
+ export interface Config {
54
+ /** Base URL used to resolve relative plugin specifiers and config paths. */
55
+ baseUrl?: string
56
+ }
57
+
58
+ /** Intercept config used when other plugins depend on `loader`. */
59
+ export interface Intercept {
60
+ /** Keep dependent plugins pending while loader entries are still loading. */
61
+ await?: boolean
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Service that owns a loader entry tree and imports configured plugins.
67
+ *
68
+ * Subclasses provide persistence by implementing `write()` on `EntryTree`.
69
+ */
70
+ export class Loader extends EntryTree {
71
+ declare [Service.config]: Loader.Intercept
72
+
73
+ public envData = process.env.CORDIS_SHARED
74
+ ? JSON.parse(process.env.CORDIS_SHARED)
75
+ : { startTime: Date.now() }
76
+
77
+ public name = 'loader'
78
+ public internal = ModuleLoader.fromInternal()
79
+
80
+ public builtins: Dict<any> = Object.create(null)
81
+
82
+ constructor(ctx: Context, public config: Loader.Config = {}) {
83
+ super(ctx)
84
+ if (config.baseUrl) {
85
+ this.ctx.baseUrl = config.baseUrl
86
+ }
87
+ const self = this
88
+
89
+ defineProperty(this, Service.tracker, {
90
+ associate: 'loader',
91
+ property: 'ctx',
92
+ noShadow: true,
93
+ })
94
+
95
+ ctx.reflect.provide('loader', this, this[Service.check])
96
+
97
+ ctx.on('internal/config', function (this: Fiber, _config, next) {
98
+ const config = next()
99
+ if (!this.entry || this.parent.fiber?.entry === this.entry) return config
100
+ const plugin = this.runtime?.callback as Record<PropertyKey, unknown> | undefined
101
+ if (plugin?.[EntryGroup.key]) return config
102
+ const resolve = plugin?.[EntryConfigResolver] as ConfigResolver | undefined
103
+ return resolve ? resolve(this.ctx, config) : interpolate(this.ctx, config)
104
+ }, { global: true })
105
+
106
+ ctx.on('internal/update', async function (config, noSave, next) {
107
+ if (!this.entry || noSave || this.parent.fiber?.entry === this.entry) return next()
108
+ await next()
109
+ const unparse = this.runtime?.Config?.['simplify']
110
+ this.entry.options.config = unparse ? unparse(config) : config
111
+ this.entry.parent.tree.write()
112
+ }, { global: true, prepend: true })
113
+
114
+ ctx.on('internal/update', function (config, _, next) {
115
+ if (!this.entry || this.parent.fiber?.entry === this.entry) return next()
116
+ self.showLog(this.entry, 'reload')
117
+ return next()
118
+ }, { global: true })
119
+
120
+ ctx.on('internal/plugin', (fiber) => {
121
+ // 1. set `fiber.entry`
122
+ if (fiber.parent[Entry.key] && !fiber.entry) {
123
+ fiber.entry = fiber.parent[Entry.key]
124
+ // FIXME merge config
125
+ Inject.resolve(fiber.entry!.options.inject, fiber.inject)
126
+ }
127
+
128
+ // 2. handle self-dispose
129
+ // We only care about `ctx.fiber.dispose()`, so we need to filter out other cases.
130
+
131
+ // case 1: fiber is created
132
+ if (fiber.uid) return
133
+
134
+ // case 2: fiber is not tracked by loader
135
+ if (!fiber.entry) return
136
+
137
+ // case 3: fiber is a child plugin under the entry (not the entry's root fiber)
138
+ if (fiber.parent.fiber?.entry === fiber.entry) return
139
+
140
+ // case 4: fiber is disposed on behalf of plugin deletion (such as plugin hmr)
141
+ // self-dispose: ctx.fiber.dispose() -> fiber / runtime dispose -> delete(plugin)
142
+ // plugin hmr: delete(plugin) -> runtime dispose -> fiber dispose
143
+ if (!ctx.registry.has(fiber.runtime!.callback)) return
144
+
145
+ // case 5: the entry's tree is being disposed
146
+ const treeOwner = fiber.entry.parent.tree.ctx.fiber
147
+ if (!treeOwner.uid || treeOwner.state === FiberState.UNLOADING) return
148
+
149
+ // case 6: Loader is replacing or removing this exact fiber
150
+ if (fiber.entry._disposing) return
151
+
152
+ this.showLog(fiber.entry, 'unload')
153
+
154
+ // case 7: fiber is disposed by loader behavior
155
+ // such as inject checker, config file update, ancestor group disable
156
+ if (fiber.entry.disabled) return
157
+
158
+ fiber.entry.options.disabled = true
159
+ fiber.entry.parent.tree.write()
160
+ })
161
+
162
+ ctx.plugin(isolate)
163
+ }
164
+
165
+ write() {
166
+ // Loader's root tree is in-memory; writes are no-ops.
167
+ }
168
+
169
+ [Service.check]() {
170
+ const config: Loader.Intercept = Service.prototype[Service.resolveConfig].call(this)
171
+ if (config.await && this.getTasks().length) return false
172
+ return true
173
+ }
174
+
175
+ showLog(entry: Entry, type: string) {
176
+ if (entry.options.group || !entry.parent.tree.enableLogs) return
177
+ this.ctx.root.logger?.('loader').info('%s plugin %C', type, entry.options.name)
178
+ }
179
+
180
+ /** Return the loader entry id that owns `fiber`, if any. */
181
+ locate(fiber = this.ctx.fiber) {
182
+ while (1) {
183
+ if (fiber.entry) return fiber.entry.id
184
+ const next = fiber.parent.fiber
185
+ if (fiber === next) return
186
+ fiber = next
187
+ }
188
+ }
189
+
190
+ /** Hook for hosts that can restart the process on full-reload requests. */
191
+ exit() {
192
+ }
193
+
194
+ /** Normalize ESM/CJS/default export shapes before applying a plugin. */
195
+ unwrapExports(exports: any) {
196
+ if (isNullable(exports)) return exports
197
+ exports = exports.default ?? exports
198
+ // https://github.com/evanw/esbuild/issues/2623
199
+ // https://esbuild.github.io/content-types/#default-interop
200
+ if (!exports.__esModule) return exports
201
+ return exports.default ?? exports
202
+ }
203
+ }
204
+
205
+ export default Loader
@@ -0,0 +1,132 @@
1
+ import { createRequire, type LoadHookContext } from 'node:module'
2
+ import type { Dict } from '@deepseek-ai/cosmokit'
3
+
4
+ /** Node internal module format names handled by loader hooks. */
5
+ export type ModuleFormat = 'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
6
+ /** Source payload accepted by Node internal module load hooks. */
7
+ export type ModuleSource = string | ArrayBuffer
8
+
9
+ /** Result returned by a Node internal resolve hook. */
10
+ export interface ResolveResult {
11
+ format: ModuleFormat
12
+ url: string
13
+ }
14
+
15
+ /** Result returned by a Node internal load hook. */
16
+ export interface LoadResult {
17
+ format: ModuleFormat
18
+ source?: ModuleSource
19
+ }
20
+
21
+ type LoadCacheData = ModuleJob // | Function
22
+
23
+ /** @see https://github.com/nodejs/node/blob/main/lib/internal/modules/esm/module_map.js */
24
+ interface LoadCache extends Omit<Map<string, Dict<LoadCacheData>>, 'get' | 'set' | 'has'> {
25
+ get(url: string, type?: string): LoadCacheData | undefined
26
+ set(url: string, type?: string, job?: LoadCacheData): this
27
+ has(url: string, type?: string): boolean
28
+ }
29
+
30
+ /** Minimal Node internal ModuleWrap surface used by HMR helpers. */
31
+ export interface ModuleWrap {
32
+ url: string
33
+ getNamespace(): any
34
+ }
35
+
36
+ /** @see https://github.com/nodejs/node/blob/main/lib/internal/modules/esm/module_job.js */
37
+ export interface ModuleJob {
38
+ url: string
39
+ loader: ModuleLoader
40
+ module?: ModuleWrap
41
+ importAttributes: ImportAttributes
42
+ linked: Promise<ModuleJob[]>
43
+ instantiate(): Promise<void>
44
+ run(): Promise<{ module: ModuleWrap }>
45
+ }
46
+
47
+ /**
48
+ * Node 22/23 ModuleLoader interface.
49
+ *
50
+ * Key methods:
51
+ * - getModuleJobForImport(specifier, parentURL, importAttributes)
52
+ * - resolve(specifier, parentURL, importAttributes) → Promise<ResolveResult>
53
+ * - resolveSync(specifier, parentURL, importAttributes) → ResolveResult
54
+ */
55
+ export interface ModuleLoaderV1 {
56
+ version: 'v1'
57
+ loadCache: LoadCache
58
+ import(specifier: string, parentURL: string, importAttributes: ImportAttributes): Promise<any>
59
+ register(specifier: string | URL, parentURL?: string | URL, data?: any, transferList?: any[]): void
60
+ getModuleJobForImport(specifier: string, parentURL: string, importAttributes: ImportAttributes): Promise<ModuleJob>
61
+ resolve(specifier: string, parentURL: string, importAttributes: ImportAttributes): Promise<ResolveResult>
62
+ resolveSync(specifier: string, parentURL: string, importAttributes: ImportAttributes): ResolveResult
63
+ load(specifier: string, context: Pick<LoadHookContext, 'format' | 'importAttributes'>): Promise<LoadResult>
64
+ }
65
+
66
+ /** Node 24+ module request object. */
67
+ export interface ModuleRequest {
68
+ specifier: string
69
+ attributes?: ImportAttributes
70
+ phase?: ModulePhase
71
+ }
72
+
73
+ /** @see https://github.com/nodejs/node/blob/main/src/module_wrap.h */
74
+ export const enum ModulePhase {
75
+ Source = 1,
76
+ Evaluation = 2,
77
+ }
78
+
79
+ /** Opaque Node internal module request type marker. */
80
+ export type ModuleRequestType = unknown // internal symbols
81
+
82
+ /**
83
+ * Node 24+ ModuleLoader interface.
84
+ *
85
+ * Breaking changes from v1:
86
+ * - getModuleJobForImport removed → getOrCreateModuleJob(parentURL, request, requestType)
87
+ * - resolve removed (became private #resolve) → resolveSync(parentURL, request)
88
+ * - Parameter order reversed for resolveSync, request object { specifier, attributes }
89
+ * - LoadCache became typed Map<url, { [type]: ModuleJob }> with delete only setting undefined
90
+ */
91
+ export interface ModuleLoaderV2 {
92
+ version: 'v2'
93
+ loadCache: LoadCache
94
+ import(specifier: string, parentURL: string, importAttributes: ImportAttributes, phase?: ModulePhase, isEntryPoint?: boolean): Promise<any>
95
+ register(specifier: string | URL, parentURL?: string | URL, data?: any, transferList?: any[], isInternal?: boolean): void
96
+ getOrCreateModuleJob(parentURL: string, request: ModuleRequest, requestType?: ModuleRequestType): Promise<ModuleJob>
97
+ resolveSync(parentURL: string, request: ModuleRequest): ResolveResult
98
+ load(url: string, context: Pick<LoadHookContext, 'format' | 'importAttributes'>): Promise<LoadResult>
99
+ }
100
+
101
+ /** Supported Node internal ESM loader shapes. */
102
+ export type ModuleLoader = ModuleLoaderV1 | ModuleLoaderV2
103
+
104
+ /** Helpers for locating the current Node internal module loader. */
105
+ export namespace ModuleLoader {
106
+ let _cachedLoader: ModuleLoader | undefined
107
+
108
+ function requireInternal(id: string): any {
109
+ const require = createRequire(import.meta.url)
110
+ if (process.execArgv.includes('--expose-internals')) {
111
+ try {
112
+ return require(id)
113
+ } catch {}
114
+ }
115
+ try {
116
+ return require('node-addon-require-builtin').requireBuiltin(id)
117
+ } catch {}
118
+ }
119
+
120
+ export function fromInternal(): ModuleLoader | undefined {
121
+ if (_cachedLoader) return _cachedLoader
122
+ const [major] = process.versions.node.split('.').map(Number)
123
+
124
+ if (major >= 24) {
125
+ const raw = requireInternal('internal/modules/esm/loader')?.getOrInitializeCascadedLoader()
126
+ if (raw) return _cachedLoader = Object.assign(raw, { version: 'v2' })
127
+ } else if (major >= 22) {
128
+ const raw = requireInternal('internal/modules/esm/loader')?.getOrInitializeCascadedLoader()
129
+ if (raw) return _cachedLoader = Object.assign(raw, { version: 'v1' })
130
+ }
131
+ }
132
+ }