@deepseek-ai/dsh-cordis-client-runner 0.2.2-alpha.3 → 0.2.2-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +2411 -7959
- package/lib/client.js.map +1 -0
- package/lib/types/client/api-catalog.d.ts.map +1 -0
- package/lib/types/client/api-catalog.js.map +1 -0
- package/lib/types/client/evaluator.d.ts.map +1 -0
- package/lib/types/client/evaluator.js.map +1 -0
- package/lib/types/client/guard.d.ts.map +1 -0
- package/lib/types/client/guard.js.map +1 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/index.js.map +1 -0
- package/lib/types/client/inspect-registry.d.ts.map +1 -0
- package/lib/types/client/inspect-registry.js.map +1 -0
- package/lib/types/client/orchestrator.d.ts.map +1 -0
- package/lib/types/client/orchestrator.js.map +1 -0
- package/lib/types/client/providers.d.ts.map +1 -0
- package/lib/types/client/providers.js.map +1 -0
- package/lib/types/client/runtime.d.ts.map +1 -0
- package/lib/types/client/runtime.js.map +1 -0
- package/lib/types/client/slot-catalog.d.ts +6 -2
- package/lib/types/client/slot-catalog.d.ts.map +1 -0
- package/lib/types/client/slot-catalog.js.map +1 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/package.json +14 -11
- package/src/client/api-catalog.ts +1208 -0
- package/src/client/evaluator.ts +222 -0
- package/src/client/guard.ts +245 -0
- package/src/client/index.ts +308 -0
- package/src/client/inspect-registry.ts +150 -0
- package/src/client/orchestrator.ts +458 -0
- package/src/client/providers.ts +263 -0
- package/src/client/runtime.ts +512 -0
- package/src/client/slot-catalog.ts +5782 -0
- package/src/index.ts +9 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-half closure evaluation: the package source runs as the body of an
|
|
3
|
+
* async function whose parameters ARE the symbol surface. Shadowing parameters
|
|
4
|
+
* (setTimeout/fetch/require/…) turn the ambient browser globals into teaching
|
|
5
|
+
* redirects without touching the page. The host syntax-prechecked the source at
|
|
6
|
+
* define time; SyntaxError handling here is the engine-divergence fallback and
|
|
7
|
+
* reaches the model through the load report.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import * as React from 'react'
|
|
11
|
+
import type { CordisDynamicPluginId } from '@deepseek-ai/dsh-api-remotes/client'
|
|
12
|
+
|
|
13
|
+
/** A mountable plugin as the closure must return it (FUNCTION or OBJECT form). */
|
|
14
|
+
export interface DynamicCordisEvaluatedPlugin {
|
|
15
|
+
/** Optional plugin name; the runner overwrites it with the module id. */
|
|
16
|
+
name?: string
|
|
17
|
+
/** Services the browser half declares; the runner overwrites it from the dispatched row. */
|
|
18
|
+
inject?: string[]
|
|
19
|
+
/** Plugin body receiving the guard facade. */
|
|
20
|
+
apply: (ctx: unknown, config?: unknown) => unknown
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** What the evaluator needs from the runner to build one package's closure. */
|
|
24
|
+
export interface DynamicCordisClosureEnv {
|
|
25
|
+
/** Route `host.call` to this package's host half over the wire. */
|
|
26
|
+
invoke(method: string, args: unknown): Promise<unknown>
|
|
27
|
+
/** Mirror one runtime error text into the load report (console.error copies). */
|
|
28
|
+
noteError(message: string): void
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const TIMER_REDIRECT
|
|
32
|
+
= 'browser timer globals are unavailable in dynamic packages. Declare inject: [\'timer\'] on the returned plugin, '
|
|
33
|
+
+ 'query Client Service.listService for the exact API, and close over that plugin ctx. In React, create timers '
|
|
34
|
+
+ 'from an event handler or React.useEffect and return callback-form disposers from the effect cleanup.'
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Where each withheld browser global sends the author instead. One home for two
|
|
38
|
+
* consumers: the closure traps below throw these, and a render crash whose
|
|
39
|
+
* message names one of them gets the same redirect appended — a package that
|
|
40
|
+
* reached the global some other way (`window.setInterval`) crashes with the
|
|
41
|
+
* engine's own bare text, and the author needs the redirect either way.
|
|
42
|
+
*/
|
|
43
|
+
export const DYNAMIC_CLIENT_REDIRECTS: Readonly<Record<string, string>> = {
|
|
44
|
+
setTimeout: TIMER_REDIRECT,
|
|
45
|
+
setInterval: TIMER_REDIRECT,
|
|
46
|
+
clearTimeout: TIMER_REDIRECT,
|
|
47
|
+
clearInterval: TIMER_REDIRECT,
|
|
48
|
+
fetch:
|
|
49
|
+
'network belongs to the HOST half: register a handler there with harness.handle(method, fn) and call it here via host.call(method, args).',
|
|
50
|
+
require:
|
|
51
|
+
'modules cannot be imported here. React arrives as the `React` closure symbol; everything else goes through ctx services or host.call.',
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Callable teaching traps shadowing the ambient globals the closure must not reach. */
|
|
55
|
+
function closureTraps(): Record<string, () => never> {
|
|
56
|
+
const traps: Record<string, () => never> = {}
|
|
57
|
+
for (const [name, redirect] of Object.entries(DYNAMIC_CLIENT_REDIRECTS)) {
|
|
58
|
+
traps[name] = (): never => {
|
|
59
|
+
throw new Error(`${name} is not available in a dynamic client half — ${redirect}`)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return traps
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The `harness` seat exists only host-side; any touch teaches the split. */
|
|
66
|
+
function harnessTrap(): unknown {
|
|
67
|
+
return new Proxy({}, {
|
|
68
|
+
get(_target, prop) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
`harness.${String(prop)} belongs to the HOST half (\`code\`): register handlers there with harness.handle(method, fn); `
|
|
71
|
+
+ 'the browser half calls them via host.call(method, args).',
|
|
72
|
+
)
|
|
73
|
+
},
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Per-package style-tag bookkeeping behind the `styles.insert` symbol. */
|
|
78
|
+
export class DynamicCordisStyles {
|
|
79
|
+
private readonly tags = new Set<HTMLStyleElement>()
|
|
80
|
+
|
|
81
|
+
/** @param pluginId - owning Plugin ID, stamped as `data-dyn` on every tag. */
|
|
82
|
+
constructor(private readonly pluginId: CordisDynamicPluginId) {}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Inject one stylesheet, removed automatically on package unload.
|
|
86
|
+
* @param css - raw CSS text.
|
|
87
|
+
* @returns disposer removing this one tag early.
|
|
88
|
+
*/
|
|
89
|
+
insert(css: string): () => void {
|
|
90
|
+
if (typeof css !== 'string') throw new Error('styles.insert(css) needs a CSS string')
|
|
91
|
+
const tag = document.createElement('style')
|
|
92
|
+
tag.dataset.dyn = this.pluginId
|
|
93
|
+
tag.textContent = css
|
|
94
|
+
document.head.append(tag)
|
|
95
|
+
this.tags.add(tag)
|
|
96
|
+
return () => {
|
|
97
|
+
this.tags.delete(tag)
|
|
98
|
+
tag.remove()
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Live tag count (load-report contribution summary). */
|
|
103
|
+
get count(): number {
|
|
104
|
+
return this.tags.size
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Remove every tag this package still owns (unload path). */
|
|
108
|
+
dispose(): void {
|
|
109
|
+
for (const tag of this.tags) tag.remove()
|
|
110
|
+
this.tags.clear()
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Stringify one console argument for the error mirror. */
|
|
115
|
+
function errorText(arg: unknown): string {
|
|
116
|
+
if (arg instanceof Error) return arg.message
|
|
117
|
+
if (typeof arg === 'string') return arg
|
|
118
|
+
if (arg === undefined) return 'undefined'
|
|
119
|
+
try {
|
|
120
|
+
return JSON.stringify(arg)
|
|
121
|
+
} catch {
|
|
122
|
+
// A circular or otherwise non-serializable console argument: the mirror
|
|
123
|
+
// carries the message, and nothing else here can fail.
|
|
124
|
+
return '[unserializable console argument]'
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Tagged write-through console; error lines additionally copy into the load report. */
|
|
129
|
+
function taggedConsole(pluginId: CordisDynamicPluginId, noteError: (message: string) => void): Console {
|
|
130
|
+
const tag = `[cordis:${pluginId}]`
|
|
131
|
+
const forward = (level: 'log' | 'info' | 'warn' | 'error' | 'debug') => (...args: unknown[]): void => {
|
|
132
|
+
console[level](tag, ...args)
|
|
133
|
+
if (level !== 'error') return
|
|
134
|
+
noteError(args.map(errorText).join(' ').slice(0, 500))
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
...console,
|
|
138
|
+
log: forward('log'),
|
|
139
|
+
info: forward('info'),
|
|
140
|
+
warn: forward('warn'),
|
|
141
|
+
error: forward('error'),
|
|
142
|
+
debug: forward('debug'),
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Narrow a closure return value to a mountable plugin (host guard mirror).
|
|
148
|
+
* @param value - whatever the closure returned.
|
|
149
|
+
* @returns whether the value is mountable.
|
|
150
|
+
*/
|
|
151
|
+
export function isDynamicCordisPlugin(value: unknown): value is DynamicCordisEvaluatedPlugin | ((ctx: unknown) => unknown) {
|
|
152
|
+
if (typeof value === 'function') return true
|
|
153
|
+
return typeof value === 'object' && value !== null
|
|
154
|
+
&& typeof (value as { apply?: unknown }).apply === 'function'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Evaluate one package's browser half and return the (un-guarded) plugin.
|
|
159
|
+
* @param pluginId - stable Plugin ID (console tag and style ownership).
|
|
160
|
+
* @param clientCode - the browser half's source: an async function body returning a plugin.
|
|
161
|
+
* @param env - runner wiring for `host.call` and error mirroring.
|
|
162
|
+
* @param styles - the package's style bookkeeping (owned by the caller so unload can dispose it).
|
|
163
|
+
* @returns the plugin the closure returned.
|
|
164
|
+
* @throws teaching errors for syntax failures and non-plugin returns.
|
|
165
|
+
*/
|
|
166
|
+
export async function evaluateClientHalf(
|
|
167
|
+
pluginId: CordisDynamicPluginId,
|
|
168
|
+
clientCode: string,
|
|
169
|
+
env: DynamicCordisClosureEnv,
|
|
170
|
+
styles: DynamicCordisStyles,
|
|
171
|
+
): Promise<DynamicCordisEvaluatedPlugin | ((ctx: unknown) => unknown)> {
|
|
172
|
+
const traps = closureTraps()
|
|
173
|
+
const parameters = ['React', 'console', 'styles', 'host', 'harness', ...Object.keys(traps), 'process', 'Buffer']
|
|
174
|
+
let closure: (...args: unknown[]) => Promise<unknown>
|
|
175
|
+
try {
|
|
176
|
+
// The wrapper mirrors the host precheck exactly, so line offsets match.
|
|
177
|
+
// Evaluating a definition's browser half IS this package's product: the
|
|
178
|
+
// source arrived from a host process that accepted and prechecked it.
|
|
179
|
+
// oxlint-disable-next-line typescript/no-implied-eval -- see above
|
|
180
|
+
const factory = new Function(...parameters, `return (async () => {\n${clientCode}\n})()`)
|
|
181
|
+
closure = factory as (...args: unknown[]) => Promise<unknown>
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (!(error instanceof SyntaxError)) throw error
|
|
184
|
+
// Engine-divergence fallback: the host precheck already carried the
|
|
185
|
+
// line/caret teaching; browsers give only the message.
|
|
186
|
+
throw new Error(
|
|
187
|
+
`client half failed to parse in this browser: ${error.message}\n`
|
|
188
|
+
+ 'The browser half is plain JavaScript (no JSX, no TypeScript); build elements with React.createElement.',
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
const host = {
|
|
192
|
+
/**
|
|
193
|
+
* Call a host-half handler of THIS package (harness.handle pairing). A call
|
|
194
|
+
* with nothing to pass omits the argument: it arrives at the handler as
|
|
195
|
+
* `null`, because the wire carries JSON and `undefined` is not JSON —
|
|
196
|
+
* requiring `host.call('m', {})` would be a ritual, and defaulting to `{}`
|
|
197
|
+
* would invent an empty argument the caller never wrote.
|
|
198
|
+
*/
|
|
199
|
+
call: (method: string, args: unknown = null): Promise<unknown> => env.invoke(method, args),
|
|
200
|
+
}
|
|
201
|
+
const returned = await closure(
|
|
202
|
+
React,
|
|
203
|
+
taggedConsole(pluginId, (message) => { env.noteError(message) }),
|
|
204
|
+
styles,
|
|
205
|
+
host,
|
|
206
|
+
harnessTrap(),
|
|
207
|
+
...Object.values(traps),
|
|
208
|
+
undefined, // process: undefined keeps `typeof process` probes safe
|
|
209
|
+
undefined, // Buffer
|
|
210
|
+
)
|
|
211
|
+
if (!isDynamicCordisPlugin(returned)) {
|
|
212
|
+
if (returned === undefined) {
|
|
213
|
+
throw new Error(
|
|
214
|
+
'client half returned `undefined` — did you forget `return`?\n'
|
|
215
|
+
+ ' ✓ return (ctx) => { … }\n'
|
|
216
|
+
+ ' ✓ return { name: \'…\', inject: [\'slots\'], apply(ctx) { … } }',
|
|
217
|
+
)
|
|
218
|
+
}
|
|
219
|
+
throw new Error('client half must `return` a plugin: a function, or an object with an `apply(ctx)` method')
|
|
220
|
+
}
|
|
221
|
+
return returned
|
|
222
|
+
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The browser twin of the tool-cordis context facade: a whitelist of
|
|
3
|
+
* lifecycle-safe verbs plus optional `ctx.get()` lookup and declared-service
|
|
4
|
+
* property access, with
|
|
5
|
+
* framework internals withheld and Context-valued returns denied. Two seats
|
|
6
|
+
* carry extra machinery: `slots`, where the registration proxy assigns any
|
|
7
|
+
* shadowing priority and ledgers ordinary entries or Factory definitions — invoking the service with
|
|
8
|
+
* the traced receiver so the effect lands on the CALLING plugin's fiber
|
|
9
|
+
* (SlotRegistry.register must stay a prototype method for exactly that
|
|
10
|
+
* reason) — and `theme`, whose override source is pinned to the package id.
|
|
11
|
+
*
|
|
12
|
+
* This is API discipline, not a security boundary: a dynamic package's code is
|
|
13
|
+
* as trusted as the host process that accepted its definition.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
17
|
+
import type { DynamicCordisPackage } from '@deepseek-ai/dsh-api-remotes/client'
|
|
18
|
+
import type { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
|
19
|
+
import type { ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client'
|
|
20
|
+
|
|
21
|
+
/** Facade verbs beyond declared services (host CTX_VERBS twin). */
|
|
22
|
+
const CTX_VERBS = new Set([
|
|
23
|
+
'effect', 'on', 'once', 'provide', 'timeout', 'interval', 'setTimeout', 'setInterval', 'throttle', 'debounce',
|
|
24
|
+
])
|
|
25
|
+
const TIMER_VERBS = new Set(['timeout', 'interval', 'setTimeout', 'setInterval', 'throttle', 'debounce'])
|
|
26
|
+
|
|
27
|
+
/** One package's Slot or Factory registration ledger row (contribution projection source). */
|
|
28
|
+
export interface DynamicCordisSlotLedgerRow {
|
|
29
|
+
/** Target Slot name, or `factory:<name>` for a Factory definition. */
|
|
30
|
+
slot: string
|
|
31
|
+
/** The assigned shadowing priority (globally unique — how winners are matched back to packages). */
|
|
32
|
+
priority: number | undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What the facade needs beyond the real ctx to govern one package. */
|
|
36
|
+
export interface DynamicCordisGuardEnv {
|
|
37
|
+
/** The dispatched Package row. */
|
|
38
|
+
pkg: DynamicCordisPackage
|
|
39
|
+
/** Ledger sink: every Slot or Factory registration this package makes. */
|
|
40
|
+
ledger: DynamicCordisSlotLedgerRow[]
|
|
41
|
+
/**
|
|
42
|
+
* Ownership index sink: the component object seated in a slot, so a later
|
|
43
|
+
* render crash reported against the stored entry can be attributed back to
|
|
44
|
+
* this package. Identity is the key — the registry stores the component
|
|
45
|
+
* verbatim — which is why nothing else has to be remembered about the entry.
|
|
46
|
+
* @param component - whatever the package passed as its component.
|
|
47
|
+
*/
|
|
48
|
+
claim(component: unknown): void
|
|
49
|
+
/** Allocate one page-local shadowing rank; later registrations sort first. */
|
|
50
|
+
allocatePriority(): number
|
|
51
|
+
/** Report one post-activation guard rejection to the owning Agent. */
|
|
52
|
+
reportFailure(error: Error): void
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Reject any service return that is a cordis Context (host guard twin). */
|
|
56
|
+
function denyContext(value: unknown, service: string, env: DynamicCordisGuardEnv): unknown {
|
|
57
|
+
if (value instanceof Context) {
|
|
58
|
+
return rejectGuard(env,
|
|
59
|
+
`service "${service}" returned a cordis Context, which the dynamic facade does not expose. `
|
|
60
|
+
+ 'Operate through your own plugin ctx and the services you declared — never another context.',
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
return value
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Forward service methods with the traced service as receiver — `this.ctx`
|
|
68
|
+
* inside prototype methods (slots.register) must stay the CALLER's ctx so
|
|
69
|
+
* effects land on the calling plugin's fiber — while denying Context returns.
|
|
70
|
+
*/
|
|
71
|
+
function guardedService(service: object, name: string, env: DynamicCordisGuardEnv): unknown {
|
|
72
|
+
return new Proxy(service, {
|
|
73
|
+
get(target, prop) {
|
|
74
|
+
const value: unknown = Reflect.get(target, prop, target)
|
|
75
|
+
if (typeof value !== 'function') return denyContext(value, name, env)
|
|
76
|
+
return (...args: unknown[]): unknown => {
|
|
77
|
+
const result: unknown = Reflect.apply(value, target, args)
|
|
78
|
+
if (result instanceof Promise) return result.then(resolved => denyContext(resolved, name, env))
|
|
79
|
+
return denyContext(result, name, env)
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Erased register options as this facade reads and rewrites them. */
|
|
86
|
+
interface ErasedSlotOptions {
|
|
87
|
+
name?: string
|
|
88
|
+
priority?: number
|
|
89
|
+
[key: string]: unknown
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The slots seat: automatic shadowing priority and ledger recording around the
|
|
94
|
+
* traced service's own Slot and Factory registration methods.
|
|
95
|
+
*/
|
|
96
|
+
function guardedSlots(slots: SlotRegistry, env: DynamicCordisGuardEnv): unknown {
|
|
97
|
+
return new Proxy(slots, {
|
|
98
|
+
get(target, prop) {
|
|
99
|
+
const value: unknown = Reflect.get(target, prop, target)
|
|
100
|
+
if (prop !== 'register' && prop !== 'registerFactory') {
|
|
101
|
+
if (typeof value !== 'function') return denyContext(value, 'slots', env)
|
|
102
|
+
return (...args: unknown[]): unknown => denyContext(Reflect.apply(value, target, args), 'slots', env)
|
|
103
|
+
}
|
|
104
|
+
return (rawOptions: unknown, component: unknown): unknown => {
|
|
105
|
+
if (typeof rawOptions !== 'object' || rawOptions === null) {
|
|
106
|
+
return rejectGuard(env, 'slots.register(options, component) needs an options object with a `name`')
|
|
107
|
+
}
|
|
108
|
+
const options = { ...rawOptions as ErasedSlotOptions }
|
|
109
|
+
const slot = options.name
|
|
110
|
+
if (typeof slot !== 'string' || slot.length === 0) {
|
|
111
|
+
return rejectGuard(env, `slots.${prop} options need a string \`name\``)
|
|
112
|
+
}
|
|
113
|
+
if (prop === 'registerFactory') {
|
|
114
|
+
const dispose = Reflect.apply(value as (...args: unknown[]) => unknown, target, [options, component])
|
|
115
|
+
env.ledger.push({ slot: `factory:${slot}`, priority: undefined })
|
|
116
|
+
env.claim(component)
|
|
117
|
+
return dispose
|
|
118
|
+
}
|
|
119
|
+
if (slot === 'tool.view.cordis') {
|
|
120
|
+
if (options.key !== 'self') {
|
|
121
|
+
return rejectGuard(env, 'tool.view.cordis only accepts key "self"; the runtime binds it to this Package')
|
|
122
|
+
}
|
|
123
|
+
options.key = `${env.pkg.pluginId}.${env.pkg.packageId}`
|
|
124
|
+
}
|
|
125
|
+
// Shadowing kinds get a page-local rank. Later registrations sort first;
|
|
126
|
+
// chain slots keep their own election (select order) untouched.
|
|
127
|
+
const spec = (slots.spec as (key: string) => { kind?: string } | undefined)(slot)
|
|
128
|
+
let priority = options.priority
|
|
129
|
+
if (spec === undefined || spec.kind !== 'chain') {
|
|
130
|
+
priority = env.allocatePriority()
|
|
131
|
+
options.priority = priority
|
|
132
|
+
}
|
|
133
|
+
const register = Reflect.get(target, 'register', target) as (opts: object, comp: unknown) => () => void
|
|
134
|
+
const dispose = register.call(target, options, component)
|
|
135
|
+
env.ledger.push({ slot, priority })
|
|
136
|
+
// After the registry accepted it: a rejected registration seats no entry,
|
|
137
|
+
// so claiming one would index a component no crash can ever name.
|
|
138
|
+
env.claim(component)
|
|
139
|
+
return dispose
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The theme seat: `overrideTokens`' source is FORCED to the package id — a
|
|
147
|
+
* dynamic package can never impersonate (or evict) another source's layer, and
|
|
148
|
+
* its own layers converge under one identity unload can reason about. The
|
|
149
|
+
* layer's disposer is additionally hung on the calling fiber, because the
|
|
150
|
+
* documented contract is "unload restores" and model code cannot be trusted to
|
|
151
|
+
* keep the returned handle (slots parity — register hangs its own cleanup).
|
|
152
|
+
* Everything else forwards through the generic guard.
|
|
153
|
+
*/
|
|
154
|
+
function guardedTheme(theme: ThemeRuntime, env: DynamicCordisGuardEnv, ctx: Context): unknown {
|
|
155
|
+
return new Proxy(theme, {
|
|
156
|
+
get(target, prop) {
|
|
157
|
+
if (prop !== 'overrideTokens') {
|
|
158
|
+
const value: unknown = Reflect.get(target, prop, target)
|
|
159
|
+
if (typeof value !== 'function') return denyContext(value, 'theme', env)
|
|
160
|
+
return (...args: unknown[]): unknown => {
|
|
161
|
+
const result: unknown = Reflect.apply(value, target, args)
|
|
162
|
+
if (result instanceof Promise) return result.then(resolved => denyContext(resolved, 'theme', env))
|
|
163
|
+
return denyContext(result, 'theme', env)
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return (source: unknown, tokens: unknown): unknown => {
|
|
167
|
+
// Two-argument shape preserved so the facade matches the documented
|
|
168
|
+
// service signature; the source VALUE is replaced, never trusted.
|
|
169
|
+
if (tokens === undefined && typeof source === 'object' && source !== null) {
|
|
170
|
+
return rejectGuard(env,
|
|
171
|
+
'theme.overrideTokens(source, tokens) takes two arguments; source is replaced with your package id, '
|
|
172
|
+
+ 'so pass any string first and the token map second: overrideTokens(\'mine\', { \'--dsw-alias-…\': { light: \'…\', dark: \'…\' } })',
|
|
173
|
+
)
|
|
174
|
+
}
|
|
175
|
+
const method = Reflect.get(target, 'overrideTokens', target)
|
|
176
|
+
const dispose = Reflect.apply(method, target, [`${env.pkg.pluginId}.${env.pkg.packageId}`, tokens]) as () => void
|
|
177
|
+
// Fiber-owned lifetime; the returned handle stays valid for early
|
|
178
|
+
// removal (the service disposer is idempotent per layer identity).
|
|
179
|
+
ctx.effect(() => dispose, 'cordis-client-runner: dynamic theme override layer')
|
|
180
|
+
return dispose
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Build the facade one dynamic plugin's `apply` receives (host sandboxContext
|
|
188
|
+
* twin, browser seats). `ctx.get(name)` performs optional lookup; direct
|
|
189
|
+
* `ctx.serviceName` access is gated by the fiber's `inject` declaration.
|
|
190
|
+
* @param ctx - the plugin's real fiber ctx (loader-created).
|
|
191
|
+
* @param env - package row + ledger sink.
|
|
192
|
+
* @returns the whitelisting proxy standing in for ctx.
|
|
193
|
+
*/
|
|
194
|
+
export function dynamicCordisContext(ctx: Context, env: DynamicCordisGuardEnv): Context {
|
|
195
|
+
const declared = new Set(Object.keys(ctx.fiber.inject))
|
|
196
|
+
const denyRead = (prop: string): never => {
|
|
197
|
+
if (ctx.get(prop) !== undefined) {
|
|
198
|
+
return rejectGuard(env,
|
|
199
|
+
`service "${prop}" is not declared by your plugin. Declare it on the plugin you return: `
|
|
200
|
+
+ `{ inject: ['${prop}', …], apply(ctx) { … } } — a plain \`function\` has no declaration site, `
|
|
201
|
+
+ 'so use the object form. The runtime then parks the package if the provider unloads.',
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
return rejectGuard(env,
|
|
205
|
+
`dynamic ctx does not expose "${prop}". Available: ctx.on / ctx.provide / timer helpers after injecting timer, and any service your `
|
|
206
|
+
+ 'returned plugin declared in inject (slots and theme are the usual UI seats). Framework internals are withheld '
|
|
207
|
+
+ 'by design.',
|
|
208
|
+
)
|
|
209
|
+
}
|
|
210
|
+
const readService = (name: string, requireDeclaration: boolean): unknown => {
|
|
211
|
+
if (requireDeclaration && !declared.has(name)) return denyRead(name)
|
|
212
|
+
const service = denyContext(ctx.get(name), name, env)
|
|
213
|
+
if (service === null || (typeof service !== 'object' && typeof service !== 'function')) return service
|
|
214
|
+
if (name === 'slots') return guardedSlots(service as SlotRegistry, env)
|
|
215
|
+
if (name === 'theme') return guardedTheme(service as ThemeRuntime, env, ctx)
|
|
216
|
+
return guardedService(service, name, env)
|
|
217
|
+
}
|
|
218
|
+
return new Proxy({}, {
|
|
219
|
+
get(_target, prop) {
|
|
220
|
+
if (prop === 'get') return (name: string): unknown => readService(name, false)
|
|
221
|
+
if (typeof prop !== 'string') return undefined
|
|
222
|
+
// Lazy verb forwarder (host twin): resolve ctx[verb] only when called.
|
|
223
|
+
if (CTX_VERBS.has(prop)) {
|
|
224
|
+
return (...args: unknown[]): unknown => {
|
|
225
|
+
if (TIMER_VERBS.has(prop) && !declared.has('timer')) return denyRead('timer')
|
|
226
|
+
const method = ctx[prop as keyof Context]
|
|
227
|
+
return Reflect.apply(method as (...a: unknown[]) => unknown, ctx, args)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return readService(prop, true)
|
|
231
|
+
},
|
|
232
|
+
set(_target, prop) {
|
|
233
|
+
return rejectGuard(env, `dynamic ctx is read-only; cannot assign "${String(prop)}"`)
|
|
234
|
+
},
|
|
235
|
+
has: (_target, prop) => prop === 'get'
|
|
236
|
+
|| (typeof prop === 'string'
|
|
237
|
+
&& ((CTX_VERBS.has(prop) && (!TIMER_VERBS.has(prop) || declared.has('timer'))) || declared.has(prop))),
|
|
238
|
+
}) as Context
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function rejectGuard(env: DynamicCordisGuardEnv, message: string): never {
|
|
242
|
+
const error = new Error(message)
|
|
243
|
+
env.reportFailure(error)
|
|
244
|
+
throw error
|
|
245
|
+
}
|