Merge pull request #8504 from deepseek-harness/feat/client-config-live-update

feat(client): sync volatile plugin config to the browser
This commit is contained in:
imccyu authored and GitHub committed 2026-11-17 16:08:14 +08:00
1 parent 4c74abdbad
commit bd1d6dcd0c
175 files changed
+3691 -779

No files matched your search

@@ -7,6 +7,7 @@ import type { BootManifest, ClientModuleLoader } from './manifest.ts'
import { ReleaseChangeGate, type ClientReleaseChange } from './release-change.ts'
import { notifySubscribers } from './notify.ts'
import { tearDownEntryFiber } from './entry-lifecycle.ts'
import { SyncedConfigEntry } from './synced-config.ts'
/** Page-local failures do not change the Host's bundle enablement. */
export interface ClientEntryState {
@@ -51,6 +52,8 @@ export class ClientEntries {
/** Admits only Host graphs of the page's boot release. */
private readonly release: ReleaseChangeGate
private readonly managed = new Map<string, Entry>()
/** Latest synced values per package that has appeared in the graph, and the Config object of its current activation. */
private readonly synced = new Map<string, SyncedConfigEntry>()
private readonly revisions = new Map<string, string>()
private loader: Loader | undefined
private queue: Promise<void> = Promise.resolve()
@@ -90,6 +93,29 @@ export class ClientEntries {
if (this.loader !== undefined) throw new Error('client-modules: entries already started')
this.loader = loader
this.desired = manifest
this.applyConfig(manifest)
// Prepended so the Loader's interpolation runs inside this listener and cannot copy the returned object.
loader.ctx.on('internal/config', (fiber, next) => {
const config: unknown = next()
// As the Loader's own listener does, skip fibers that are not an entry's root plugin (a child plugin inherits
// its parent's entry) and keep their explicit config.
if (fiber.entry === undefined || fiber.parent.fiber.entry === fiber.entry) return config
const id = fiber.entry.options.name
const synced = this.synced.get(id)
if (synced === undefined) return config
// A Client face with its own schema keeps Cordis's ordinary configuration; it must not also receive synced values.
if (fiber.runtime?.Config === undefined) {
// Resolving a candidate for the running instance (as `fiber.update()` does) keeps its object, as the Host keeps
// an active instance's volatile references; only an activation receives a new one.
if (synced.config !== undefined && fiber.effectiveConfig === synced.config) return synced.config
const activation = synced.activate()
// However the instance unloads (replacement, removal, a withdrawn dependency), its object stops receiving values.
fiber.ctx.effect(() => () => { synced.release(activation) }, 'client-modules: synced configuration activation')
return activation
}
if (synced.empty) return config
throw new Error(`client-modules: the Client face of ${id} exports a Config schema; synced configuration requires the Host schema alone`)
}, { prepend: true })
loader.ctx.effect(() => () => {
this.stopped = true
this.generation++
@@ -116,6 +142,8 @@ export class ClientEntries {
const manifest = parseBootManifest(graph)
if (entryTargets(manifest) !== entryTargets(this.desired)) this.generation++
this.desired = manifest
// Configuration is not code: it applies at once, before queued entry work creates or replaces any entry.
if (this.loader !== undefined) this.applyConfig(manifest)
const generation = this.generation
return this.enqueue(() => this.reconcile(generation))
}
@@ -159,6 +187,34 @@ export class ClientEntries {
}, id)
}
/**
* The synced Config object of a package's current plugin activation, as that activation's `apply` received it.
* Each activation receives a new object, so the result changes when the plugin is replaced.
* @param packageName - graph row id.
* @returns the object, or undefined while no activation of the package is running.
*/
resolveConfigByPackage(packageName: string): object | undefined {
return this.synced.get(packageName)?.config
}
/** An activation's teardown begins: like a Host fiber that is no longer active, it receives no later values. */
private releaseConfig(id: string): void {
this.synced.get(id)?.release()
}
/**
* Write each row's values into its package's current activation. A row absent from the graph keeps its values: its
* entry is being removed, and removal releases the activation without writing to it.
*/
private applyConfig(manifest: BootManifest): void {
for (const row of manifest.plugins) {
const values = row.config ?? {}
const synced = this.synced.get(row.id)
if (synced === undefined) this.synced.set(row.id, new SyncedConfigEntry(values))
else synced.update(values)
}
}
private publish(snapshot: ClientEntryState): void {
this.snapshot = snapshot
notifySubscribers(this.listeners, 'synchronization')
@@ -195,6 +251,7 @@ export class ClientEntries {
this.index.invalidateForReplacement(id, rev)
await this.modules.prefetch(id)
if (!this.current(generation)) return
this.releaseConfig(id)
await tearDownEntryFiber(entry)
this.index.releaseReplaced(id)
if (!this.current(generation)) return
@@ -218,6 +275,7 @@ export class ClientEntries {
for (const [id, entry] of this.managed) {
if (wanted.has(id)) continue
const fiber = entry.fiber
this.releaseConfig(id)
loader.remove(entry.id)
this.managed.delete(id)
this.revisions.delete(id)
+7 -2
View File
@@ -14,6 +14,7 @@ import type { Context } from '@deepseek-ai/cordis'
import type { Loader } from '@deepseek-ai/cordis-plugin-loader'
import { ClientModuleSystem } from './system.ts'
import { parseBootManifest } from './manifest.ts'
import type { SyncedConfig, SyncedConfigService } from '@deepseek-ai/dsh-client-config/types'
import type {
ClientBootstrapModule, ClientModuleCreateOptions, ClientModuleLoader, ClientModuleLoaderTarget,
} from './manifest.ts'
@@ -52,11 +53,11 @@ export function createClientModuleSystem(
})
}
/** Required service: the Loader whose internal module system this plugin publishes. */
/** Required service: the Loader whose internal module system and synced configuration this plugin publishes. */
export const inject = ['loader']
/**
* Enroll the kernel-built module system as `ctx.modules`.
* Enroll the kernel-built module system as `ctx.modules` and its synced configuration lookup as `ctx.config`.
* @param ctx - client root context.
*/
export function apply(ctx: Context): void {
@@ -66,4 +67,8 @@ export function apply(ctx: Context): void {
throw new Error('client-modules: the Loader has no client module system')
}
ctx.reflect.provide('modules', modules)
const config: SyncedConfigService = {
resolveConfigByPackage: <C>(packageName: string) => modules.entries.resolveConfigByPackage(packageName) as SyncedConfig<C> | undefined,
}
ctx.reflect.provide('config', config)
}
@@ -28,6 +28,7 @@
* composes the wire.
*/
import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
import type {} from '@deepseek-ai/cordis'
import type {
DshClientManifest, ClientModuleMetaFactory,
@@ -69,6 +70,8 @@ export interface WebBootEntry {
immediately?: boolean
/** Non-baseline module specifiers this row requests; omitted when it requests none. */
external?: string[]
/** Browser-synced values of the plugin's top-level volatile Config fields, secrets removed; omitted when it has none. */
config?: SyncedConfigValues
}
/** Initial scheduling phase for one revisioned combo script. */
@@ -134,6 +137,8 @@ export interface BootPluginRow {
inject: string[]
/** Stage-one prefetch tier (false when the wire omits it). */
immediately: boolean
/** Synced Config values; undefined when the row has none. */
config?: SyncedConfigValues
}
/** The parsed boot manifest: one wire, two consumer views. */
@@ -275,10 +280,14 @@ export function parseBootManifest(wire: unknown): BootManifest {
inject: inject === undefined ? [] : [...inject],
external: external === undefined ? [] : [...external],
})
if (row.config !== undefined && (typeof row.config !== 'object' || row.config === null || Array.isArray(row.config))) {
throw new Error(`client-modules: boot manifest entry ${where} config must be an object`)
}
plugins.push({
id: row.id,
inject: inject === undefined ? [] : [...inject],
immediately: row.immediately === true,
...(row.config === undefined ? {} : { config: row.config as SyncedConfigValues }),
})
}
@@ -0,0 +1,160 @@
/**
* Browser-synced plugin configuration. Each plugin activation receives its own Config object of
* `SyncedConfigRef`s, as a Host activation resolves its own volatile references; only the page's entry
* controller writes values, and it stops writing to an activation once that activation's teardown begins.
*/
import type { VolatileSnapshot } from '@deepseek-ai/cordis'
import type { SyncedConfigRef, SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
import { notifySubscribers } from './notify.ts'
/** Controller-side access to one reference: set without notifying, then notify once every field is set. */
interface RefPort {
set(value: unknown): void
notify(): void
}
/** The page's implementation of one {@link SyncedConfigRef}; only the activation that created it writes, through its port. */
class SyncedConfigReference<T> implements SyncedConfigRef<T> {
#value: VolatileSnapshot<T>
readonly #listeners = new Set<() => void>()
/**
* @param value - frozen initial value.
* @param attach - receives the controller's port; called once during construction.
*/
constructor(value: VolatileSnapshot<T>, attach: (port: RefPort) => void) {
this.#value = value
attach({
set: (next) => { this.#value = next as VolatileSnapshot<T> },
notify: () => { notifySubscribers(this.#listeners, 'synced configuration') },
})
}
/** @returns the current frozen value; undefined when the Host sends none. */
readonly get: () => VolatileSnapshot<T> = () => this.#value
/** @returns the same value as {@link get}. */
readonly getSnapshot: () => VolatileSnapshot<T> = () => this.#value
/**
* Observe value changes; every changed field of one update is set before any subscriber runs.
* @param listener - called after each change.
* @returns the disposer.
*/
readonly subscribe: (listener: () => void) => () => void = (listener) => {
this.#listeners.add(listener)
return () => { this.#listeners.delete(listener) }
}
}
/** Structural equality of JSON values; object key order does not matter. */
function sameJson(left: unknown, right: unknown): boolean {
if (left === right) return true
if (typeof left !== 'object' || typeof right !== 'object' || left === null || right === null) return false
if (Array.isArray(left) !== Array.isArray(right)) return false
const leftKeys = Object.keys(left)
return leftKeys.length === Object.keys(right).length
&& leftKeys.every(key => Object.hasOwn(right, key) && sameJson(Reflect.get(left, key), Reflect.get(right, key)))
}
function freeze(value: unknown): unknown {
if (value !== null && typeof value === 'object') {
for (const child of Object.values(value)) freeze(child)
Object.freeze(value)
}
return value
}
/** The Config object of one plugin activation. */
class SyncedConfigActivation {
private values: SyncedConfigValues
private readonly ports = new Map<string, RefPort>()
private readonly refs = new Map<string, SyncedConfigReference<unknown>>()
/** Read-only object whose properties create field references on first access. */
readonly config: object
constructor(values: SyncedConfigValues) {
this.values = values
// An extensible empty target keeps the Proxy invariants satisfied for fields that appear later.
this.config = new Proxy({}, {
set: () => false,
defineProperty: () => false,
deleteProperty: () => false,
get: (_target, property) => typeof property === 'string' ? this.ref(property) : undefined,
has: (_target, property) => typeof property === 'string' && Object.hasOwn(this.values, property),
ownKeys: () => Object.keys(this.values),
getOwnPropertyDescriptor: (_target, property) => typeof property === 'string' && Object.hasOwn(this.values, property)
? { configurable: true, enumerable: true, value: this.ref(property) }
: undefined,
})
}
/** Set every changed field, then notify the changed fields' subscribers. */
write(values: SyncedConfigValues): void {
const previous = this.values
const changed = [...new Set([...Object.keys(previous), ...Object.keys(values)])]
.filter(field => !sameJson(previous[field], values[field]))
if (changed.length === 0) return
this.values = values
const ports = changed.flatMap((field) => {
const port = this.ports.get(field)
return port === undefined ? [] : [{ port, value: values[field] }]
})
for (const { port, value } of ports) port.set(value)
for (const { port } of ports) port.notify()
}
private ref(field: string): SyncedConfigReference<unknown> {
let ref = this.refs.get(field)
if (ref === undefined) {
ref = new SyncedConfigReference<unknown>(this.values[field], (port) => { this.ports.set(field, port) })
this.refs.set(field, ref)
}
return ref
}
}
/** Latest synced values of one package and the Config object of its current plugin activation. */
export class SyncedConfigEntry {
private values: SyncedConfigValues
private current: SyncedConfigActivation | undefined
/** @param values - Host-validated values; they are frozen and not checked against any schema. */
constructor(values: SyncedConfigValues) {
this.values = freeze(structuredClone(values)) as SyncedConfigValues
}
/** Whether no field currently has a value. */
get empty(): boolean {
return Object.keys(this.values).length === 0
}
/** The current activation's Config object; undefined between a teardown and the next activation. */
get config(): object | undefined {
return this.current?.config
}
/**
* Start an activation: a new Config object holding the latest values; the previous activation stops receiving writes.
* @returns the object to hand to the activation's `apply`.
*/
activate(): object {
this.current = new SyncedConfigActivation(this.values)
return this.current.config
}
/**
* An activation's teardown has begun; later values wait for the next activation.
* @param config - the ending activation's object; omitted, the current activation ends.
*/
release(config?: object): void {
if (config === undefined || this.current?.config === config) this.current = undefined
}
/**
* Replace the values; the current activation receives the changed fields, if one is running.
* @param values - the package's complete values; absent fields read undefined.
*/
update(values: SyncedConfigValues): void {
this.values = freeze(structuredClone(values)) as SyncedConfigValues
this.current?.write(this.values)
}
}
@@ -0,0 +1,120 @@
/**
* Projection of one running plugin's Config onto the values the browser may receive: top-level volatile fields only,
* with every `role('secret')` position removed, including positions inside volatile objects, dictionaries, and arrays.
*/
import { isDeepStrictEqual } from 'node:util'
import type { Volatile } from '@deepseek-ai/cordis'
import type { JsonValue } from '@deepseek-ai/dsh-util-values'
import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
/** Schemastery node fields the projection reads; a Schemastery schema satisfies it structurally. */
export interface SchemaNode {
type: string
meta: { role?: unknown; volatile?: unknown }
dict?: Record<string, SchemaNode>
inner?: SchemaNode
list?: SchemaNode[]
}
/** A volatile field of a parsed Config is a reference; detected structurally so this package needs no Cosmokit copy. */
function isReference(value: unknown): value is Volatile<unknown> {
return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'get') === 'function'
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Read a child field Schemastery always sets for the node types that use it.
* @param node - schema node.
* @param key - `dict` for objects, `inner` for dictionaries, arrays, and transforms, `list` for unions and intersections.
* @returns the field.
*/
function part<K extends 'dict' | 'inner' | 'list'>(node: SchemaNode, key: K): NonNullable<SchemaNode[K]> {
const value = node[key]
/* v8 ignore next -- Schemastery constructs every object, dict, array, transform, union, and intersect node with this field. */
if (value === undefined) throw new TypeError(`client-modules: ${node.type} schema has no ${key}`)
return value
}
/** Every union branch is applied, so a field any branch declares secret is removed. */
function stripSecrets(node: SchemaNode, value: unknown): unknown {
if (value === undefined || node.meta.role === 'secret') return undefined
switch (node.type) {
case 'object': {
if (!isRecord(value)) return value
// As the settings redaction does, keys this branch does not declare stay, so union and intersection members do not
// drop each other's fields.
const dict = part(node, 'dict')
const undeclared = Object.entries(value).filter(([key]) => !(key in dict))
return { ...Object.fromEntries(undeclared), ...collect(Object.entries(dict).map(([key, child]) => [key, child, value[key]])) }
}
case 'dict': {
const inner = part(node, 'inner')
return isRecord(value) ? collect(Object.entries(value).map(([key, entry]) => [key, inner, entry])) : value
}
case 'array':
// A secret array item is dropped from the list rather than replaced by a placeholder.
return Array.isArray(value) ? value.map(entry => stripSecrets(part(node, 'inner'), entry)).filter(entry => entry !== undefined) : value
case 'union':
case 'intersect':
return part(node, 'list').reduce<unknown>((current, child) => stripSecrets(child, current), value)
case 'transform':
return stripSecrets(part(node, 'inner'), value)
default:
return value
}
}
/** Rebuild an object from stripped properties, omitting those that strip to undefined. */
function collect(properties: [string, SchemaNode, unknown][]): Record<string, unknown> {
const rebuilt: Record<string, unknown> = {}
for (const [key, child, entry] of properties) {
const stripped = stripSecrets(child, entry)
if (stripped !== undefined) rebuilt[key] = stripped
}
return rebuilt
}
/** Top-level object fields of a Config schema; intersections contribute the fields of each object member. */
function topFields(node: SchemaNode): [string, SchemaNode][] {
if (node.type === 'object') return Object.entries(part(node, 'dict'))
if (node.type === 'intersect') return part(node, 'list').flatMap(topFields)
return []
}
/**
* Whether a Config schema declares a top-level volatile field, the only fields synced to the browser.
* @param schema - the plugin's Host Config schema.
* @returns true when at least one top-level field is volatile.
*/
export function hasSyncedFields(schema: SchemaNode): boolean {
return topFields(schema).some(([, node]) => node.meta.volatile === true)
}
/**
* Project a running plugin's effective Config onto its browser-synced values.
* @param schema - the plugin's Host Config schema.
* @param effective - the fiber's effective Config, whose volatile fields are references.
* @param id - package name, used in diagnostics.
* @returns the synced values, or undefined when the schema declares no top-level volatile field.
* @throws TypeError when a synced value is not lossless JSON.
*/
export function syncedValues(schema: SchemaNode, effective: unknown, id: string): SyncedConfigValues | undefined {
const fields = topFields(schema).filter(([, node]) => node.meta.volatile === true)
if (fields.length === 0) return undefined
const source = isRecord(effective) ? effective : {}
const values: Record<string, JsonValue> = {}
for (const [key, node] of fields) {
const raw = source[key]
const stripped = stripSecrets(node, isReference(raw) ? raw.get() : raw)
if (stripped === undefined) continue
const json = JSON.parse(JSON.stringify(stripped)) as JsonValue
if (!isDeepStrictEqual(json, stripped)) {
throw new TypeError(`client-modules: ${id} Config field ${key} is not lossless JSON and cannot be synced to the browser`)
}
values[key] = json
}
return values
}
+160
View File
@@ -0,0 +1,160 @@
/**
* Host-side publication of browser-synced plugin configuration: each graph row carries the projected volatile values
* of its Loader entry's plugin, and a change of those values republishes the graph.
*/
import { isDeepStrictEqual } from 'node:util'
import { FiberState } from '@deepseek-ai/cordis'
import type { Context, Fiber } from '@deepseek-ai/cordis'
import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
import type z from '@deepseek-ai/schemastery'
import type { SyncedConfigValues } from '@deepseek-ai/dsh-client-config/types'
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
import type { WebBootEntry, WebBootGraph } from './client/manifest.ts'
import { hasSyncedFields, syncedValues } from './config-projection.ts'
/** Synced values per graph row, owned by the client module registry. */
export class SyncedConfigPublisher {
/** Last published values per row; undefined for a plugin without top-level volatile fields. */
private readonly values = new Map<string, SyncedConfigValues | undefined>()
/**
* Values the row's schema resolves from an empty Config, served to every non-owner Peer; undefined when the schema
* declares no top-level volatile field or cannot resolve an empty Config.
*/
private readonly defaults = new Map<string, SyncedConfigValues | undefined>()
/** Loader entry name per row of the last composed graph. */
private rows = new Map<string, string>()
/** Current root plugin fiber per Loader entry name; of entries sharing a name, the one seen last. */
private readonly fibers = new Map<string, Fiber>()
/** `loader/volatile-update` listener disposer per Loader entry name. */
private readonly watches = new Map<string, () => void>()
/**
* @param ctx - the registry's context; the publisher's listeners leave with it.
* @param entries - the Loader entries present when the registry starts.
* @param changed - recomposes and republishes the graph after a row's values change.
*/
constructor(private readonly ctx: Context, entries: Iterable<Entry>, private readonly changed: () => void) {
for (const entry of entries) if (entry.fiber !== undefined) this.track(entry.options.name, entry.fiber.ctx.fiber)
// A new plugin instance (install, upgrade, code reload) is seen at creation, so the graph that announces its code
// already carries values its schema resolves; a status change re-reads values after a (re)start.
const seen = (fiber: Fiber): void => {
const entry = fiber.entry
// Only an entry's live root plugin, by the Loader's own test: a child plugin inherits its parent's entry, and a
// replaced instance (its uid cleared at disposal) may report its teardown after its successor exists. The
// successor is not yet `entry.fiber` here, because the Loader assigns that after construction returns.
if (entry === undefined || fiber.parent.fiber.entry === entry) return
const name = entry.options.name
if (fiber.uid === null) {
if (this.fibers.get(name) !== fiber) return
// The selected instance is gone; a live entry of the same name, sharing its source, supplies the values.
const live = [...ctx.loader.entries()]
.map(candidate => candidate.options.name === name ? candidate.fiber?.ctx.fiber : undefined)
.find(candidate => candidate !== undefined && candidate.uid !== null)
if (live === undefined) return
fiber = live
}
this.track(name, fiber)
this.republish(name)
}
ctx.on('internal/plugin', seen)
ctx.on('internal/status', seen)
ctx.effect(() => () => {
for (const dispose of this.watches.values()) dispose()
this.watches.clear()
}, 'client-modules: synced configuration watches')
}
/**
* Attach current synced values to composed rows, and drop the values of rows that left the graph.
* @param entries - composed rows.
* @param records - the registry table, keyed by row id, naming the Loader entry that supplies each row.
* @returns the rows, each with its values when it has any.
*/
apply(entries: WebBootEntry[], records: ReadonlyMap<string, { readonly loaderName: string }>): WebBootEntry[] {
this.rows = new Map([...records].map(([id, record]) => [id, record.loaderName]))
for (const id of this.values.keys()) if (!this.rows.has(id)) this.values.delete(id)
for (const id of this.defaults.keys()) if (!this.rows.has(id)) this.defaults.delete(id)
for (const [id, loaderName] of this.rows) this.refresh(id, loaderName)
return entries.map(({ config: _published, ...row }) => {
const config = this.values.get(row.id)
return config === undefined ? row : { ...row, config }
})
}
/**
* The graph one Peer receives, at first render and in every plugin-events frame. The owner receives the configured
* values; every other Peer receives each row's schema defaults instead, so the owner's values stay on the Host.
* @param graph - the composed graph.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph itself for the owner, otherwise a copy whose row values are the schema defaults.
*/
graphFor(graph: WebBootGraph, principal: Principal | undefined): WebBootGraph {
/* oxlint-disable typescript/no-unnecessary-condition -- other packages merge non-owner principal kinds into the map
this program sees with only the owner kind. */
if (principal === undefined || principal.kind === 'owner') return graph
/* oxlint-enable typescript/no-unnecessary-condition */
return {
...graph,
entries: graph.entries.map(({ config: _config, ...row }) => {
const config = this.defaults.get(row.id)
return config === undefined ? row : { ...row, config }
}),
}
}
private track(name: string, fiber: Fiber): void {
this.fibers.set(name, fiber)
// `loader/volatile-update` reaches only listeners on the updated fiber's own context, and a listener there lasts one
// activation, so each activation registers it again. Prepended: the graph frame carrying the new values is queued
// before the plugin's own listeners can push data that depends on them.
if (fiber.state !== FiberState.ACTIVE) return
this.watches.get(name)?.()
this.watches.set(name, fiber.ctx.on('loader/volatile-update', () => { this.republish(name) }, { prepend: true }))
}
private republish(name: string): void {
let changed = false
for (const [id, loaderName] of this.rows) if (loaderName === name && this.refresh(id, loaderName)) changed = true
if (changed) this.changed()
}
/**
* Recompute one row's values; equal values (deep equality) change nothing.
* @returns whether the row's values changed.
*/
private refresh(id: string, loaderName: string): boolean {
const fiber = this.fibers.get(loaderName)
/* v8 ignore next -- a table row comes from a Loader entry whose root fiber was tracked at startup or creation. */
if (fiber === undefined) return false
const runtimeSchema = fiber.runtime?.Config
// A plugin without synced fields is never resolved here.
const schema = runtimeSchema !== undefined && 'toJSON' in runtimeSchema && hasSyncedFields(runtimeSchema as z)
? runtimeSchema as z
: undefined
this.defaults.set(id, schema === undefined ? undefined : this.defaultValues(schema, fiber, id))
let values: SyncedConfigValues | undefined
try {
// Before activation there is no effective Config; resolving the raw config with the instance's own schema gives
// the object activation will receive.
values = schema === undefined ? undefined : syncedValues(schema, fiber.effectiveConfig ?? fiber.resolveConfig(fiber.rawConfig), id)
} catch (error) {
// Containment: one plugin's unsyncable value keeps its last published values and leaves the other rows intact.
this.ctx.logger.error(error)
return false
}
if (isDeepStrictEqual(this.values.get(id), values)) return false
this.values.set(id, values)
return true
}
private defaultValues(schema: z, fiber: Fiber, id: string): SyncedConfigValues | undefined {
try {
return syncedValues(schema, fiber.resolveConfig({}), id)
} catch (error) {
// A schema with a required field that has no default rejects an empty Config; such a row then carries no values
// for a non-owner Peer, and its plugin reads every field as absent there.
this.ctx.logger.debug(error)
return undefined
}
}
}
+33 -10
View File
@@ -39,8 +39,10 @@ import { Service } from '@deepseek-ai/cordis'
import type { Context } from '@deepseek-ai/cordis'
import type { Entry } from '@deepseek-ai/cordis-plugin-loader'
import type { IndexInjection } from '@deepseek-ai/dsh-host-webserver'
import type { Principal } from '@deepseek-ai/dsh-typert-protocol'
import { PACKAGE_ASSET_SEGMENT, packageAssetMediaType } from './assets.ts'
import { exactPackageSpecifier, parseDshClient, stripClientSuffix } from './client/manifest.ts'
import { SyncedConfigPublisher } from './config-sync.ts'
import type { WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph, WebBootRelease } from './client/manifest.ts'
export { stripClientSuffix } from './client/manifest.ts'
@@ -662,6 +664,7 @@ export class ClientModuleRegistry extends Service {
private previousBatchResponses = new Map<string, LazyResponse>()
private flushQueued = false
private composed: WebBootGraph
private readonly syncedConfig: SyncedConfigPublisher
/**
* Build the service: subscribe, seed, and run the activation flush.
@@ -692,7 +695,14 @@ export class ClientModuleRegistry extends Service {
// Activation pass: the initial scan IS the incremental path over the
// current entries, flushed synchronously (nothing async between subscribe,
// seed, and flush).
for (const entry of ctx.loader.entries()) this.dirty.add(entry.options.name)
const entries = [...ctx.loader.entries()]
for (const entry of entries) this.dirty.add(entry.options.name)
this.syncedConfig = new SyncedConfigPublisher(ctx, entries, () => {
// Only rows and rev change: the batch artifacts and the prior batch generation stay.
const rows = this.syncedConfig.apply(this.composed.entries, this.table)
this.composed = { ...this.composed, entries: rows, rev: shortHash(JSON.stringify({ entries: rows, batches: this.composed.batches })) }
this.notifyGraphChanged()
})
this.composed = this.compose()
const failures: Error[] = []
this.flush(err => failures.push(err))
@@ -707,19 +717,29 @@ export class ClientModuleRegistry extends Service {
)
}
ctx.inject(['webServer'], registerWebCarrier)
ctx.on('webserver/index-inject', (table) => {
table.push(...bootInjections(this.composed))
ctx.on('webserver/index-inject', (table, peer) => {
table.push(...bootInjections(this.graphFor(peer.principal)))
})
}
/**
* Current composed entry graph (stable object between changes).
* @returns the graph served as `window.__DSH_BOOT__`.
* Current composed entry graph (stable object between changes), carrying the configured synced values.
* @returns the graph served as the owner's `window.__DSH_BOOT__`.
*/
graph(): WebBootGraph {
return this.composed
}
/**
* The current graph as one Peer may see it: the owner receives the configured synced values, and every other Peer
* receives each row's schema defaults in their place.
* @param principal - the Peer's principal; undefined for the owner or an in-process caller.
* @returns the graph served to that Peer at first render and in plugin-events frames.
*/
graphFor(principal: Principal | undefined): WebBootGraph {
return this.syncedConfig.graphFor(this.composed, principal)
}
/**
* Absolute path of an entry's client bundle.
* @param id - entry id (package name).
@@ -808,8 +828,10 @@ export class ClientModuleRegistry extends Service {
}
/**
* Fires after any flush that recomposed the graph (row added/removed, or a
* rebuilt rev change). Pull model: listeners re-read {@link graph}.
* Fires after the graph's rows or rev change: a flush that recomposed the
* graph (row added/removed, or a rebuilt rev change), or a republication of
* synced configuration alone, which leaves the batch artifacts unchanged.
* Pull model: listeners re-read {@link graph}.
* @param listener - notified with no payload.
* @returns the unsubscriber.
*/
@@ -868,10 +890,11 @@ export class ClientModuleRegistry extends Service {
this.batchResponses = batchResponses
this.responses = responses
const batches = artifacts.map(artifact => artifact.descriptor)
const rows = this.syncedConfig.apply(entries, this.table)
return {
rev: shortHash(JSON.stringify({ entries, batches })),
rev: shortHash(JSON.stringify({ entries: rows, batches })),
release: this.release,
entries,
entries: rows,
batches,
}
}
@@ -1289,7 +1312,7 @@ export class ClientModuleRegistry extends Service {
}
}
// Anything else under /plugins (including unadvertised combinations and
// /plugins/events when the HMR row is absent) is an unknown resource.
// an unknown path) is an unknown resource.
return { status: 404 }
}
+5
View File
@@ -0,0 +1,5 @@
/** Web client graph types shared by the Host and Client faces and by Remote wire declarations. */
export type {
BootManifest, BootModuleRow, BootPluginRow, WebBootBatch, WebBootBatchPhase, WebBootEntry, WebBootGraph,
WebBootRelease,
} from './client/manifest.ts'