| 1 | import { Context, Fiber, Inject } from '@deepseek-ai/cordis' |
| 2 | import { deepEqual, isNullable, updateVolatile, volatileEntries, type Volatile } from '@deepseek-ai/cosmokit' |
| 3 | import { Loader } from '../index.ts' |
| 4 | import { EntryGroup } from './group.ts' |
| 5 | import { EntryTree } from './tree.ts' |
| 6 | import { evaluate, isJsExpr } from './utils.ts' |
| 7 | import { equalExceptVolatile } from './diff.ts' |
| 8 | import { FiberState } from '../../../../fiber-state.ts' |
| 9 | |
| 10 | /** Serialized plugin entry options stored in loader config files. */ |
| 11 | export interface EntryOptions { |
| 12 | /** Stable id inside the containing entry tree. */ |
| 13 | id: string |
| 14 | /** Module specifier imported by the entry tree. */ |
| 15 | name: string |
| 16 | /** Config passed to the plugin. */ |
| 17 | config?: any |
| 18 | /** Marks this entry as a nested group. */ |
| 19 | group?: boolean | null |
| 20 | /** Prevents this entry and descendants from running. */ |
| 21 | disabled?: boolean | null |
| 22 | /** Required services or service intercept config for this entry. */ |
| 23 | inject?: Inject | null |
| 24 | } |
| 25 | |
| 26 | function takeEntries(object: {}, keys: string[]) { |
| 27 | const indexed = object as Record<string, unknown> |
| 28 | const result: [string, any][] = [] |
| 29 | for (const key of keys) { |
| 30 | if (!(key in object)) continue |
| 31 | result.push([key, indexed[key]]) |
| 32 | delete indexed[key] |
| 33 | } |
| 34 | return result |
| 35 | } |
| 36 | |
| 37 | function sortKeys<T extends {}>(object: T, prepend = ['id', 'name'], append = ['config']): T { |
| 38 | const part1 = takeEntries(object, prepend) |
| 39 | const part2 = takeEntries(object, append) |
| 40 | const rest = takeEntries(object, Object.keys(object)).sort(([a], [b]) => a.localeCompare(b)) |
| 41 | return Object.assign(object, Object.fromEntries([...part1, ...rest, ...part2])) |
| 42 | } |
| 43 | |
| 44 | /** One configured plugin node inside an `EntryTree`. */ |
| 45 | export class Entry { |
| 46 | static readonly key = Symbol.for('cordis.entry') |
| 47 | |
| 48 | public ctx: Context |
| 49 | public fiber?: Fiber |
| 50 | /** Raw import result before export normalization; HMR updates it after a successful reload. */ |
| 51 | public moduleNamespace: unknown |
| 52 | public parent!: EntryGroup |
| 53 | // safety: call `entry.update()` immediately after creating an entry |
| 54 | public options = {} as EntryOptions |
| 55 | public subgroup?: EntryGroup |
| 56 | public subtree?: EntryTree |
| 57 | |
| 58 | _initTask?: Promise<void> |
| 59 | |
| 60 | constructor(public loader: Loader) { |
| 61 | this.ctx = loader.ctx.extend({ [Entry.key]: this }) |
| 62 | this.context.emit('loader/entry-init', this) |
| 63 | } |
| 64 | |
| 65 | get context(): Context { |
| 66 | return this.ctx |
| 67 | } |
| 68 | |
| 69 | get id() { |
| 70 | let id = this.options.id |
| 71 | if (this.parent.tree.ctx.fiber.entry) { |
| 72 | id = this.parent.tree.ctx.fiber.entry.id + EntryTree.sep + id |
| 73 | } |
| 74 | return id |
| 75 | } |
| 76 | |
| 77 | /** True when this entry or any owning parent entry is disabled. */ |
| 78 | get disabled() { |
| 79 | // group is always enabled |
| 80 | if (this.options.group) return false |
| 81 | let entry: Entry | undefined = this |
| 82 | do { |
| 83 | if (this._resolveDisabled(entry.options)) return true |
| 84 | entry = entry.parent.ctx.fiber.entry |
| 85 | } while (entry) |
| 86 | return false |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * Effective disabled state: a `!!js` expression evaluates against the loader |
| 91 | * context. The raw node stays in the options, so write-back keeps the form. |
| 92 | */ |
| 93 | private _resolveDisabled(options: EntryOptions): boolean { |
| 94 | return isJsExpr(options.disabled) |
| 95 | ? Boolean(this.evaluate(options.disabled.__jsExpr)) |
| 96 | : Boolean(options.disabled) |
| 97 | } |
| 98 | |
| 99 | evaluate(expr: string) { |
| 100 | return evaluate(this.ctx, expr) |
| 101 | } |
| 102 | |
| 103 | private async _patchContext(diff: string[]) { |
| 104 | await this.context.waterfall('loader/patch-context', this, async () => { |
| 105 | Object.setPrototypeOf(this.ctx, this.parent.ctx) |
| 106 | |
| 107 | if (this.fiber?.uid && (diff.includes('config') || this.options.group)) { |
| 108 | // A simultaneous context/config edit must restart against the new dependencies. |
| 109 | const fiber = this.fiber.ctx.fiber |
| 110 | for (const name of Object.keys(fiber.inject)) fiber._checkImpl(name) |
| 111 | await fiber.update(this.options.config, true) |
| 112 | } |
| 113 | }) |
| 114 | } |
| 115 | |
| 116 | async refresh() { |
| 117 | if (this.fiber) return |
| 118 | if (this.disabled) return |
| 119 | await this.init() |
| 120 | } |
| 121 | |
| 122 | /** Merge new options, restart as needed, and persist through the parent tree. */ |
| 123 | async update(options: Partial<EntryOptions>, create = false, force = false) { |
| 124 | const legacy = { ...this.options } |
| 125 | |
| 126 | // step 1: update options |
| 127 | if (create) { |
| 128 | this.options = options as EntryOptions |
| 129 | } else { |
| 130 | for (const [key, value] of Object.entries(options)) { |
| 131 | if (isNullable(value)) { |
| 132 | delete (this.options as unknown as Record<string, unknown>)[key] |
| 133 | } else { |
| 134 | (this.options as unknown as Record<string, unknown>)[key] = value |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | sortKeys(this.options) |
| 139 | |
| 140 | // step 2: execute |
| 141 | if (this.disabled) { |
| 142 | await this.fiber?.dispose() |
| 143 | return |
| 144 | } |
| 145 | |
| 146 | // step 3: check if options are changed |
| 147 | if (this.fiber?.uid) { |
| 148 | const changes = Object.keys({ ...this.options, ...legacy }) |
| 149 | .filter(key => !deepEqual( |
| 150 | (this.options as unknown as Record<string, unknown>)[key], |
| 151 | (legacy as unknown as Record<string, unknown>)[key], |
| 152 | key === 'config', |
| 153 | )) |
| 154 | // Only an active fiber in an unchanged context takes volatile-only config changes without a remount. |
| 155 | const volatileOnly = changes.length === 1 && changes[0] === 'config' |
| 156 | && this.fiber.state === FiberState.ACTIVE && Object.getPrototypeOf(this.ctx) === this.parent.ctx |
| 157 | && equalExceptVolatile(legacy.config, this.options.config, this.fiber.runtime?.Config) |
| 158 | if (volatileOnly) this.fiber.rawConfig = this.options.config |
| 159 | const pending = volatileOnly && this._commitVolatile() ? [] : changes |
| 160 | if (!pending.length && !force) return |
| 161 | this.context.emit('loader/partial-dispose', this, legacy, true) |
| 162 | await this._patchContext(pending) |
| 163 | } else { |
| 164 | await this.init() |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /** |
| 169 | * Parse a volatile-only raw config change and commit its values into the running fiber's references. |
| 170 | * An invalid candidate is logged and leaves the running references unchanged; the raw config stays retained for the next activation. |
| 171 | * @returns `false` when an ordinary effective value changed, so the caller applies the ordinary update lifecycle. |
| 172 | */ |
| 173 | private _commitVolatile(): boolean { |
| 174 | const fiber = this.fiber!.ctx.fiber |
| 175 | const refs = volatileEntries(fiber.effectiveConfig) |
| 176 | if (!refs.length) return true |
| 177 | const raw = this.options.config |
| 178 | let candidate: unknown |
| 179 | try { |
| 180 | candidate = fiber.resolveConfig(raw) |
| 181 | } catch (error) { |
| 182 | this.ctx.logger.warn('volatile config update failed for %C', this.options.id) |
| 183 | this.ctx.logger.warn(error) |
| 184 | return true |
| 185 | } |
| 186 | if (!deepEqual(fiber.effectiveConfig, candidate, true)) { |
| 187 | this.ctx.logger.debug('ordinary config values of %C changed with its volatile values; applying the ordinary update', this.options.id) |
| 188 | return false |
| 189 | } |
| 190 | const paths = refs.flatMap(({ path, ref }) => { |
| 191 | const source = path.reduce<unknown>((value, key) => Reflect.get(value as object, key), candidate) as Volatile<unknown> |
| 192 | if (deepEqual(ref.get(), source.get(), true)) return [] |
| 193 | updateVolatile(ref, source) |
| 194 | return [path] |
| 195 | }) |
| 196 | if (!paths.length) return true |
| 197 | const self: Context = Object.create(fiber.ctx) |
| 198 | Reflect.set(self, Context.filter, (owner: Context) => owner.fiber === fiber) |
| 199 | try { |
| 200 | fiber.ctx.emit(self, 'loader/volatile-update', paths) |
| 201 | } catch (error) { |
| 202 | // A listener failure must not fail the entry update; every value is already committed. |
| 203 | this.ctx.logger.warn(error) |
| 204 | } |
| 205 | return true |
| 206 | } |
| 207 | |
| 208 | getOuterStack = () => { |
| 209 | let entry: Entry | undefined = this |
| 210 | const result: string[] = [] |
| 211 | do { |
| 212 | result.push(` at ${entry.parent.tree.ctx.baseUrl}#${entry.options.id}`) |
| 213 | entry = entry.parent.ctx.fiber.entry |
| 214 | } while (entry) |
| 215 | return result |
| 216 | } |
| 217 | |
| 218 | /** Import and start the configured plugin if it is not already running. */ |
| 219 | async init() { |
| 220 | try { |
| 221 | await (this._initTask ??= this._init()) |
| 222 | } finally { |
| 223 | this._initTask = undefined |
| 224 | } |
| 225 | this.fiber?.await().catch(() => {}).finally(() => { |
| 226 | if (this.loader.getTasks().length) return |
| 227 | this.ctx.reflect.notify(['loader']) |
| 228 | }) |
| 229 | } |
| 230 | |
| 231 | private async _init() { |
| 232 | let moduleNamespace: unknown |
| 233 | try { |
| 234 | moduleNamespace = await this.parent.tree.import(this.options.name, this.getOuterStack) |
| 235 | } catch (error) { |
| 236 | this.ctx.logger.error(error) |
| 237 | return |
| 238 | } |
| 239 | const plugin = this.loader.unwrapExports(moduleNamespace) |
| 240 | await this._patchContext([]) |
| 241 | this.loader.showLog(this, 'apply') |
| 242 | this.fiber = this.ctx.registry.plugin(plugin, this.options.config, this.getOuterStack) |
| 243 | this.moduleNamespace = moduleNamespace |
| 244 | } |
| 245 | } |
| 246 |