| 1 | import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' |
| 2 | import { type Dict, omit } from '@deepseek-ai/cosmokit' |
| 3 | import { applyChanges, detach, flatten, type Journal, place } from './journal.ts' |
| 4 | |
| 5 | export interface PatchOptions { |
| 6 | id?: string |
| 7 | insert?: EntryOptions[] |
| 8 | name?: string |
| 9 | config?: any |
| 10 | group?: boolean | null |
| 11 | disabled?: boolean | null |
| 12 | inject?: any |
| 13 | intercept?: any |
| 14 | isolate?: any |
| 15 | [key: string]: any |
| 16 | } |
| 17 | |
| 18 | export type Warn = (format: string, ...args: any[]) => void |
| 19 | |
| 20 | function randomId(used: (id: string) => boolean) { |
| 21 | let id: string |
| 22 | do { |
| 23 | id = Math.random().toString(16).slice(2, 10) |
| 24 | } while (used(id)) |
| 25 | return id |
| 26 | } |
| 27 | |
| 28 | /** Give every entry (nested groups included) an id, in place. */ |
| 29 | export function ensureIds(entries: EntryOptions[], used: (id: string) => boolean) { |
| 30 | for (const entry of entries) { |
| 31 | if (!entry.id) entry.id = randomId(used) |
| 32 | if (entry.group && Array.isArray(entry.config)) ensureIds(entry.config, used) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /** Runtime changes are routed back to an inserted entry by its id, so every insert needs one. */ |
| 37 | export function ensureInsertIds(patches: PatchOptions[] | undefined, used: (id: string) => boolean) { |
| 38 | for (const patch of patches ?? []) { |
| 39 | if (patch.insert) ensureIds(patch.insert, used) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Overlay `patches` onto a fresh clone of `data`. Inserted entries are cloned |
| 45 | * too, so the tree owns every object it mounts. |
| 46 | */ |
| 47 | export function applyPatches(data: EntryOptions[], patches: PatchOptions[] | undefined, warn: Warn): EntryOptions[] { |
| 48 | data = structuredClone(data) |
| 49 | if (!patches?.length) return data |
| 50 | |
| 51 | const entryMap = new Map<string, EntryOptions>() |
| 52 | const buildMap = (entries: EntryOptions[]) => { |
| 53 | for (const entry of entries) { |
| 54 | if (entry.id) entryMap.set(entry.id, entry) |
| 55 | if (entry.group && Array.isArray(entry.config)) { |
| 56 | buildMap(entry.config) |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | buildMap(data) |
| 61 | |
| 62 | for (const patch of patches) { |
| 63 | const { id, insert, name, ...overrides } = patch |
| 64 | |
| 65 | if (insert) { |
| 66 | const clone = structuredClone(insert) |
| 67 | if (id) { |
| 68 | const target = entryMap.get(id) |
| 69 | if (!target) { |
| 70 | warn('patch insert: entry %C not found', id) |
| 71 | continue |
| 72 | } |
| 73 | if (!target.group) { |
| 74 | warn('patch insert: entry %C is not a group', id) |
| 75 | continue |
| 76 | } |
| 77 | if (!Array.isArray(target.config)) target.config = [] |
| 78 | target.config.push(...clone) |
| 79 | } else { |
| 80 | data.push(...clone) |
| 81 | } |
| 82 | buildMap(clone) |
| 83 | continue |
| 84 | } |
| 85 | |
| 86 | if (!id) { |
| 87 | warn('patch: id is required for non-insert patches') |
| 88 | continue |
| 89 | } |
| 90 | |
| 91 | const target = entryMap.get(id) |
| 92 | if (!target) { |
| 93 | warn('patch: entry %C not found', id) |
| 94 | continue |
| 95 | } |
| 96 | |
| 97 | if (name && name !== target.name) { |
| 98 | warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) |
| 99 | continue |
| 100 | } |
| 101 | |
| 102 | for (const [key, value] of Object.entries(overrides)) { |
| 103 | if (key === 'id') continue |
| 104 | (target as unknown as Record<string, unknown>)[key] = value |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | return data |
| 109 | } |
| 110 | |
| 111 | /** |
| 112 | * Who owns an entry, or one key of it, in the patched tree: the file, a patch |
| 113 | * that overrides that key (the last one wins), or the patch that inserted the |
| 114 | * whole entry. |
| 115 | */ |
| 116 | export type EntryOwner = EntryOwner.File | EntryOwner.Patch | EntryOwner.Insert |
| 117 | |
| 118 | export namespace EntryOwner { |
| 119 | export interface File { |
| 120 | type: 'file' |
| 121 | } |
| 122 | |
| 123 | export interface Patch { |
| 124 | type: 'patch' |
| 125 | /** Index into the patch list. */ |
| 126 | index: number |
| 127 | } |
| 128 | |
| 129 | export interface Insert { |
| 130 | type: 'insert' |
| 131 | /** Index into the patch list. */ |
| 132 | index: number |
| 133 | /** The insert list (or nested group config) holding the entry. */ |
| 134 | list: EntryOptions[] |
| 135 | options: EntryOptions |
| 136 | /** The group the entry is inserted into (`null` for the root). */ |
| 137 | parent: string | null |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | export class PatchIndex { |
| 142 | private keys = new Map<string, Map<string, number>>() |
| 143 | private inserts = new Map<string, EntryOwner.Insert>() |
| 144 | |
| 145 | constructor(public patches: PatchOptions[]) { |
| 146 | patches.forEach((patch, index) => { |
| 147 | const { id, insert } = patch |
| 148 | if (insert) { |
| 149 | const walk = (list: EntryOptions[], parent: string | null) => { |
| 150 | for (const options of list) { |
| 151 | this.inserts.set(options.id, { type: 'insert', index, list, options, parent }) |
| 152 | if (options.group && Array.isArray(options.config)) walk(options.config, options.id) |
| 153 | } |
| 154 | } |
| 155 | walk(insert, id ?? null) |
| 156 | return |
| 157 | } |
| 158 | if (!id) return |
| 159 | const keys = this.keys.get(id) ?? new Map<string, number>() |
| 160 | for (const key of Object.keys(omit(patch, ['id', 'insert', 'name']))) { |
| 161 | keys.set(key, index) |
| 162 | } |
| 163 | this.keys.set(id, keys) |
| 164 | }) |
| 165 | } |
| 166 | |
| 167 | /** Owner of the entry as a whole. */ |
| 168 | entry(id: string | null): EntryOwner { |
| 169 | if (id === null) return { type: 'file' } |
| 170 | return this.inserts.get(id) ?? { type: 'file' } |
| 171 | } |
| 172 | |
| 173 | /** Owner of one key of an entry. */ |
| 174 | key(id: string, key: string): EntryOwner { |
| 175 | const insert = this.inserts.get(id) |
| 176 | if (insert) return insert |
| 177 | const index = this.keys.get(id)?.get(key) |
| 178 | return index === undefined ? { type: 'file' } : { type: 'patch', index } |
| 179 | } |
| 180 | |
| 181 | fileOwned(id: string, key: string | null) { |
| 182 | return (key === null ? this.entry(id) : this.key(id, key)).type === 'file' |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * Route a journal to its owners: file-owned changes are applied to `data`, |
| 188 | * patch-owned ones to `patches`. Both are mutated in place, so pass clones. |
| 189 | * Returns whether any patch changed. |
| 190 | */ |
| 191 | export function routeJournal(journal: Journal, data: EntryOptions[], patches: PatchOptions[], warn: Warn) { |
| 192 | const index = new PatchIndex(patches) |
| 193 | let patched = false |
| 194 | |
| 195 | const insertList = (owner: EntryOwner.Insert) => owner.options.config ??= [] |
| 196 | |
| 197 | const placeAt = (options: EntryOptions, parent: string | null, position: number) => { |
| 198 | const owner = index.entry(parent) |
| 199 | if (owner.type === 'insert') { |
| 200 | const list = insertList(owner) |
| 201 | list.splice(Math.min(position, list.length), 0, options) |
| 202 | patched = true |
| 203 | } else if (!place(data, options, parent, position)) { |
| 204 | warn('cannot place entry %C: group %C not found', options.id, parent) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | for (const [id, record] of journal) { |
| 209 | const owner = index.entry(id) |
| 210 | if (record.kind === 'remove') { |
| 211 | if (owner.type === 'insert') { |
| 212 | owner.list.splice(owner.list.indexOf(owner.options), 1) |
| 213 | patched = true |
| 214 | } else { |
| 215 | detach(data, id) |
| 216 | } |
| 217 | continue |
| 218 | } |
| 219 | |
| 220 | const current = owner.type === 'insert' ? owner : flatten(data).get(id) |
| 221 | if (!current) { |
| 222 | const options = { id } as EntryOptions |
| 223 | applyChanges(options, record.changes) |
| 224 | placeAt(options, record.parent ?? null, record.position) |
| 225 | continue |
| 226 | } |
| 227 | |
| 228 | if (record.parent !== undefined && current.parent !== record.parent) { |
| 229 | // moving across owners: carry the full options over |
| 230 | if (owner.type === 'insert') { |
| 231 | owner.list.splice(owner.list.indexOf(owner.options), 1) |
| 232 | patched = true |
| 233 | } else { |
| 234 | detach(data, id) |
| 235 | } |
| 236 | applyChanges(current.options, record.changes) |
| 237 | placeAt(current.options, record.parent, record.position) |
| 238 | continue |
| 239 | } |
| 240 | |
| 241 | if (owner.type === 'insert') { |
| 242 | applyChanges(current.options, record.changes) |
| 243 | patched = true |
| 244 | continue |
| 245 | } |
| 246 | |
| 247 | const patchChanges: Dict<Dict> = {} |
| 248 | applyChanges(current.options, record.changes, (key) => { |
| 249 | const keyOwner = index.key(id, key) |
| 250 | if (keyOwner.type !== 'patch') return true |
| 251 | ;(patchChanges[keyOwner.index] ??= {})[key] = record.changes[key] |
| 252 | return false |
| 253 | }) |
| 254 | for (const [i, changes] of Object.entries(patchChanges)) { |
| 255 | applyChanges((patches as unknown as Record<string, PatchOptions>)[i] as any, changes) |
| 256 | patched = true |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | return patched |
| 261 | } |
| 262 |