返回 CodeWhale
group.ts
1 import { Context, Service } from '@deepseek-ai/cordis'
2 import { Entry, type EntryOptions } from './entry.ts'
3 import { EntryTree } from './tree.ts'
4
5 /** Runtime owner for a list of child loader entries. */
6 export class EntryGroup {
7 static readonly key = Symbol.for('cordis.group')
8
9 public data: EntryOptions[] = []
10
11 constructor(public ctx: Context, public tree: EntryTree) {
12 const entry = ctx.fiber.entry
13 if (entry) entry.subgroup = this
14 }
15
16 get context(): Context {
17 return this.ctx
18 }
19
20 async create(options: Omit<EntryOptions, 'id'>) {
21 const id = this.tree.ensureId(options)
22 const entry: Entry = this.tree.store[id] ??= new Entry(this.ctx.loader)
23 // Entry may be moved from another group,
24 // so we need to update the parent reference.
25 entry.parent = this
26 // Use `create: true` to replace existing entry.options.
27 await entry.update(options, true, true)
28 return entry.id
29 }
30
31 unlink(options: EntryOptions) {
32 const config = this.data
33 const index = config.indexOf(options)
34 if (index >= 0) config.splice(index, 1)
35 }
36
37 remove(id: string, isDispose = false) {
38 const entry = this.tree.store[id]
39 if (!entry || entry.parent !== this) return
40 // Unregister before disposal so Loader can distinguish removal from self-disposal.
41 delete this.tree.store[id]
42 entry.fiber?.dispose()
43 if (!isDispose) {
44 this.unlink(entry.options)
45 }
46 this.context.emit('loader/partial-dispose', entry, entry.options, false)
47 }
48
49 async update(config: EntryOptions[]) {
50 const oldConfig = this.data as EntryOptions[]
51 this.data = config
52 const oldMap = Object.fromEntries(oldConfig.map(options => [options.id, options]))
53 const newMap = Object.fromEntries(config.map(options => [options.id ?? Symbol('anonymous'), options]))
54
55 // update inner plugins
56 const ids = Reflect.ownKeys({ ...oldMap, ...newMap }) as string[]
57 await Promise.all(ids.map(async (id) => {
58 if (newMap[id]) {
59 await this.create(newMap[id]).catch((error) => {
60 this.ctx.logger.error(error)
61 })
62 } else {
63 this.remove(id)
64 }
65 }))
66 }
67
68 stop() {
69 for (const options of this.data) {
70 this.remove(options.id, true)
71 }
72 }
73 }
74
75 /** Plugin that mounts a nested loader entry group. */
76 export class Group extends EntryGroup {
77 static initial: Omit<EntryOptions, 'id'>[] = []
78 static readonly [EntryGroup.key] = true
79
80 constructor(public ctx: Context, public config: EntryOptions[]) {
81 super(ctx, ctx.fiber.entry!.parent.tree)
82 ctx.on('internal/update', config => this.update(config))
83 }
84
85 async* [Service.init]() {
86 yield () => this.stop()
87 await this.update(this.config)
88 }
89 }
90
90 lines TYPESCRIPT