import type { HistoireSearchResult } from '@histoire/protocol' import type { HistoireSession } from '@histoire/sdk/internal' import type { ClientCommand, ClientCommandContext } from '@histoire/shared' import type { Router } from 'vue-router' import type { StandaloneRuntimeBinding } from './runtime-binding.js' import { getHistoireTargetKey } from '@histoire/protocol' import { canOpenHistoireTargetInEditor, requestHistoireOpenInEditor } from '@histoire/sdk/internal' import { registeredCommands } from 'virtual:$histoire-commands' import { files, onUpdate } from 'virtual:$histoire-stories' import { shallowReactive, shallowRef, watch } from 'vue' import { createBuiltinCommands } from '../util/builtin-commands.js' import { mapFile } from '../util/mapping.js' import { createStandaloneClientActions } from './client-actions.js' /** Standalone plugin commands retain legacy context while story modules stay sandbox-owned. */ export function createStandaloneCommands(session: HistoireSession, router: Router, runtime?: StandaloneRuntimeBinding) { const metadata = shallowRef(files.map(file => mapFile(file))) const snapshot = shallowRef(session.getSnapshot()) const active = shallowRef(true) // Workbench-registered commands (extension plugins): reactive so search lists update live. const extensions = shallowReactive(new Map()) let executionGeneration = 0 // Visibility depends on canonical state/capabilities, not only query changes. // This publication is shared by every reactive list/context consumer. const stopSnapshot = session.subscribe(value => snapshot.value = value) let actions = createStandaloneClientActions(session) const stopRuntime = runtime ? watch(runtime.current, (owner) => { executionGeneration++ actions.close() if (owner.getSnapshot().status !== 'disposed') actions = createStandaloneClientActions(owner) }, { immediate: true, flush: 'sync' }) : () => {} // Runtime state publications may change document ownership without replacing // its session. State edits retain ownership; source/target/runtime changes do not. const stopExecutionOwner = watch(() => { const owner = runtime?.snapshot.value ?? snapshot.value return JSON.stringify([owner.status, owner.stale, owner.source?.sourceId, owner.source?.epoch, owner.source?.revision, owner.selection, owner.runtime.status, owner.runtime.runtimeId]) }, () => executionGeneration++, { flush: 'sync' }) // Virtual metadata subscriptions survive HMR, and are owned by this bootstrap. const off = onUpdate((files) => { if (active.value) metadata.value = files.map(file => mapFile(file)) }) /** showIf/getParams receive read-only state; only clientAction gets an owned editable projection. */ function context(): ClientCommandContext { const current = runtime?.snapshot.value ?? snapshot.value const collected = metadata.value.find(file => file.story.id === current.selection?.storyId)?.story const variants = collected?.variants.map(variant => Object.freeze({ ...variant, state: variant.id === current.selection?.variantId ? current.state?.value ?? Object.freeze({}) : Object.freeze({}) })) const story = collected ? Object.freeze({ ...collected, variants }) : undefined const variant = variants?.find(variant => variant.id === current.selection?.variantId) return { route: router.currentRoute.value, currentStory: story, currentVariant: variant } } /** * Reuse registered/builtin definitions; editor authority names collected target only. * Built-in and Node-backed commands need the dev server; workbench-registered commands * decide their own availability through `showIf`. */ function list(query: string): ClientCommand[] { if (!active.value) return [] const current = context() const text = query.toLowerCase() const dev = snapshot.value.source?.mode === 'dev' return [...(dev ? [...createBuiltinCommands(context, () => {}), ...registeredCommands] : []), ...extensions.values()].filter(command => (command.id === 'builtin:open-in-editor' ? canOpenHistoireTargetInEditor(snapshot.value) : !command.showIf || command.showIf(current)) && (command.label.toLowerCase().includes(text) || command.searchText?.toLowerCase().includes(text))) } /** * Adds a workbench-side command (extension plugins) to search. It runs its `clientAction` * directly: no dev-server notification and no runtime ownership guard, since the action * runner owns its scope. Disposal removes only this registration. * @param command Command with a unique id. */ function register(command: ClientCommand): () => void { if (extensions.has(command.id)) throw new Error(`Duplicate command: ${command.id}`) extensions.set(command.id, command) return () => { if (extensions.get(command.id) === command) extensions.delete(command.id) } } /** Standalone adapts successful docs activation to its existing route and preserves other query preferences. */ async function activateSearch(result: HistoireSearchResult): Promise { const current = session.getSnapshot() if (!active.value || result.kind !== 'docs' || current.status !== 'ready' || current.stale || !current.selection || getHistoireTargetKey(current.selection) !== getHistoireTargetKey(result.target)) return const route = router.currentRoute.value await router.replace({ ...route, query: { ...route.query, tab: 'docs' }, hash: result.anchor ?? '' }) } /** Only standalone publishes configured plugin commands over existing dev channel. */ function execute(command: ClientCommand, params: Record): Promise { if (extensions.get(command.id) === command) return Promise.resolve().then(() => command.clientAction?.(params, context())) if (command.id === 'builtin:open-in-editor') { const target = session.getSnapshot().selection return actions.execute({ ...command, clientAction: () => target && canOpenHistoireTargetInEditor(session.getSnapshot(), target) ? requestHistoireOpenInEditor(session, target) : undefined }, params, context()) } return actions.execute(command, params, context(), () => { if (import.meta.hot) import.meta.hot.send('histoire:dev-command', { id: command.id, params }) }) } return { context, list, register, execute, activateSearch, /** Capture actual command runtime lifetime, including same-target frame replacement. */ captureExecutionOwner() { const generation = executionGeneration return () => active.value && generation === executionGeneration }, /** Retire reactive publications and both callback/visibility subscriptions once. */ close() { if (!active.value) return active.value = false stopSnapshot() stopRuntime() stopExecutionOwner() extensions.clear() actions.close() off?.() } } }