compose-stack.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /**
  2. * The profile patch stack composed with tree-wide row-id ownership. Entry ids
  3. * are unique per Loader tree, and the vendored group `create()` re-parents an
  4. * existing id instead of rejecting it, so a shared id namespace needs its
  5. * check before anything mounts: built-in and boot-staged layers claim their
  6. * ids first and a duplicate among or inside them fails loud; an external
  7. * bundle whose id is already claimed, or which declares one of its own ids
  8. * twice, is skipped whole and recorded as a conflict; a user layer's insert
  9. * of a claimed id drops that row and records it. One composition yields the
  10. * patches, the owner of every id, and the conflicts, and each contained
  11. * layer is rendered once. Boot, live recomposition, and the config dump all
  12. * compose through here, so they agree.
  13. * @module @deepseek-ai/dsh-app-boot/compose-stack
  14. */
  15. import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
  16. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  17. import { composeExternalLayer, isContainedLayer, type ComposedExternalLayer } from './external-bundles.ts'
  18. import { visitPatchRows, visitRowTree } from './patch-rows.ts'
  19. import type { ProfileLayer } from './profile.ts'
  20. /** One user-owned patch list in the stack: the profile file, the home file, or a `--patch` overlay. */
  21. export interface StackUserLayer {
  22. /** How diagnostics name the layer (a file path or the flag that supplied it). */
  23. readonly label: string
  24. /** The layer's patches, as parsed from disk. */
  25. readonly patches: PatchOptions[]
  26. }
  27. /** One row a layer could not mount because its id is already declared. */
  28. export interface RowConflict {
  29. /** The id declared more than once. */
  30. readonly rowId: string
  31. /** The module the losing row named. */
  32. readonly moduleName: string
  33. /** The layer that lost: a bundle's package name or a user layer's label. */
  34. readonly layer: string
  35. /** The external bundle that lost, when the loser is one; its whole layer is left out. */
  36. readonly packageName?: string
  37. /**
  38. * The layer that already declares the id: a bundle's package name or a user
  39. * layer's label, or the losing layer itself when it declares the id twice.
  40. */
  41. readonly declaredBy: string
  42. /** The reason as diagnostics and the plugin list state it, without the layer that lost. */
  43. readonly message: string
  44. }
  45. /** The stack as the root include should mount it, with what it left out. */
  46. export interface ComposedStack {
  47. /** Patches in application order: bundle layers in manifest order, then the user layers as given. */
  48. readonly patches: PatchOptions[]
  49. /** The same patches per layer, labelled by package name or user-layer label; a skipped bundle has no entry. */
  50. readonly layers: StackUserLayer[]
  51. /** The bundle layer that owns each id a bundle layer introduces; rows user layers insert are not listed. */
  52. readonly owners: ReadonlyMap<string, ProfileLayer>
  53. /** Every row left out, in stack order. */
  54. readonly conflicts: RowConflict[]
  55. /** External bundles left out because a row id was already claimed or repeated. */
  56. readonly skippedBundles: string[]
  57. }
  58. /** Row-id ownership across the bundle layers: who owns each id, which external bundles lost, and how the rest mount. */
  59. export interface LayerOwnership {
  60. /** The layer that owns each id a bundle layer introduces. */
  61. readonly owners: Map<string, ProfileLayer>
  62. /** The conflicts of each external bundle left out, by package name. */
  63. readonly skipped: Map<string, RowConflict[]>
  64. /** The composition of each contained layer that owns its ids, by package name; rendered once and mounted as is. */
  65. readonly composed: Map<string, ComposedExternalLayer>
  66. }
  67. /** One conflict with its message: the id's other declarer, or the losing layer itself declaring it twice. */
  68. function rowConflict(fields: Omit<RowConflict, 'message'>): RowConflict {
  69. const id = JSON.stringify(fields.rowId)
  70. const message = fields.declaredBy === fields.layer
  71. ? `row ${id} is declared twice by ${fields.layer}`
  72. : `row ${id} is already declared by ${fields.declaredBy}`
  73. return { ...fields, message }
  74. }
  75. /** The ids one inserted row carries: its own and, for a group, its children's. */
  76. function rowIds(row: EntryOptions): string[] {
  77. const ids: string[] = []
  78. visitRowTree(row, (entry) => {
  79. if (typeof entry.id === 'string') ids.push(entry.id)
  80. })
  81. return ids
  82. }
  83. /**
  84. * Decide row-id ownership across the bundle layers. A layer introduces the
  85. * rows it inserts and the rows its config overrides set as a group's
  86. * children. Built-in and boot-staged layers claim first, in manifest order;
  87. * an id two of them declare, or one inserts twice, is a defect of the shipped
  88. * composition and throws, while a config override restating a row the same
  89. * layer declared is that layer keeping its own child. Contained external
  90. * layers then claim in manifest order, each rendered once here; one whose id
  91. * is already owned, or which declares an id twice, is left out whole.
  92. * @param layers - the profile's bundle layers, in manifest order.
  93. * @returns the owner of every claimed id, the conflicts of each skipped bundle, and the composition of each mounted one.
  94. * @throws when two built-in or boot-staged layers declare the same id, or one of them declares an id twice.
  95. */
  96. export function claimLayerIds(layers: readonly ProfileLayer[]): LayerOwnership {
  97. const owners = new Map<string, ProfileLayer>()
  98. for (const layer of layers) {
  99. if (isContainedLayer(layer)) continue
  100. visitPatchRows(layer.patches, (row, source) => {
  101. if (typeof row.id !== 'string') return
  102. const owner = owners.get(row.id)
  103. if (owner === layer) {
  104. if (source === 'insert') throw new Error(`row ${JSON.stringify(row.id)} is declared twice by ${layer.packageName}`)
  105. return
  106. }
  107. if (owner !== undefined) {
  108. throw new Error(`row ${JSON.stringify(row.id)} is declared by both ${owner.packageName} and ${layer.packageName}`)
  109. }
  110. owners.set(row.id, layer)
  111. })
  112. }
  113. const skipped = new Map<string, RowConflict[]>()
  114. const composed = new Map<string, ComposedExternalLayer>()
  115. for (const layer of layers) {
  116. if (!isContainedLayer(layer)) continue
  117. const { packageName } = layer
  118. const composition = composeExternalLayer(layer)
  119. const conflicts: RowConflict[] = composition.duplicates.map(({ rowId, moduleName }) => (
  120. rowConflict({ rowId, moduleName, layer: packageName, packageName, declaredBy: packageName })
  121. ))
  122. for (const [rowId, moduleName] of composition.rows) {
  123. const owner = owners.get(rowId)
  124. if (owner !== undefined) {
  125. conflicts.push(rowConflict({ rowId, moduleName, layer: packageName, packageName, declaredBy: owner.packageName }))
  126. }
  127. }
  128. if (conflicts.length > 0) {
  129. skipped.set(packageName, conflicts)
  130. continue
  131. }
  132. for (const id of composition.rows.keys()) owners.set(id, layer)
  133. composed.set(packageName, composition)
  134. }
  135. return { owners, skipped, composed }
  136. }
  137. /**
  138. * Compose the stack the root include mounts: every bundle layer that owns its
  139. * ids, in manifest order, then the user layers with any insert of an already
  140. * owned id dropped. Patches are passed by reference; callers that mount them
  141. * clone, because the include pushes inserted rows into the tree as they are.
  142. * @param binName - the diagnostic prefix on a thrown built-in duplicate.
  143. * @param layers - the profile's bundle layers, in manifest order.
  144. * @param userLayers - the user-owned layers, in application order.
  145. * @returns the patches to mount, the owner of every bundle id, the conflicts, and the bundles left out.
  146. * @throws when two built-in or boot-staged layers declare the same id, or one of them declares an id twice.
  147. */
  148. export function composeProfileStack(
  149. binName: string, layers: readonly ProfileLayer[], userLayers: readonly StackUserLayer[],
  150. ): ComposedStack {
  151. let ownership: LayerOwnership
  152. try {
  153. ownership = claimLayerIds(layers)
  154. } catch (error) {
  155. throw new Error(`${binName}: ${(error as Error).message}`)
  156. }
  157. const composedLayers: StackUserLayer[] = []
  158. const conflicts: RowConflict[] = []
  159. const skippedBundles: string[] = []
  160. for (const layer of layers) {
  161. const lost = ownership.skipped.get(layer.packageName)
  162. if (lost !== undefined) {
  163. conflicts.push(...lost)
  164. skippedBundles.push(layer.packageName)
  165. continue
  166. }
  167. const composition = ownership.composed.get(layer.packageName)
  168. composedLayers.push({ label: layer.packageName, patches: composition === undefined ? layer.patches : composition.patches })
  169. }
  170. const claimed = new Map<string, string>()
  171. for (const [id, layer] of ownership.owners) claimed.set(id, layer.packageName)
  172. for (const userLayer of userLayers) {
  173. const patches: PatchOptions[] = []
  174. for (const patch of userLayer.patches) {
  175. if (patch.insert === undefined) {
  176. patches.push(patch)
  177. continue
  178. }
  179. const kept: EntryOptions[] = []
  180. for (const row of patch.insert) {
  181. const ids = rowIds(row)
  182. const taken = ids.map(id => [id, claimed.get(id)] as const).find(([, owner]) => owner !== undefined)
  183. if (taken?.[1] !== undefined) {
  184. conflicts.push(rowConflict({ rowId: taken[0], moduleName: row.name, layer: userLayer.label, declaredBy: taken[1] }))
  185. continue
  186. }
  187. for (const id of ids) claimed.set(id, userLayer.label)
  188. kept.push(row)
  189. }
  190. if (kept.length === patch.insert.length) patches.push(patch)
  191. else if (kept.length > 0) patches.push({ ...patch, insert: kept })
  192. }
  193. composedLayers.push({ label: userLayer.label, patches })
  194. }
  195. return {
  196. patches: composedLayers.flatMap(layer => layer.patches),
  197. layers: composedLayers,
  198. owners: ownership.owners,
  199. conflicts,
  200. skippedBundles,
  201. }
  202. }
  203. /**
  204. * One diagnostic line for a conflict, as boot and the config dump print it.
  205. * @param conflict - the conflict to describe.
  206. * @returns the line, without a binary-name prefix.
  207. */
  208. export function formatRowConflict(conflict: RowConflict): string {
  209. return conflict.packageName === undefined
  210. ? `${conflict.layer}: insert of ${conflict.moduleName} skipped — ${conflict.message}`
  211. : `bundle ${conflict.packageName} left out — ${conflict.message}`
  212. }