|
| 1 | +import { defineNovaPlugin } from '@gtc-nova/kit/runtime' |
| 2 | +import { spellRegistry } from '../utils/registry' |
| 3 | +import { useRuntimeConfig } from 'nitro/runtime' |
| 4 | +import type { SpellFeatures } from '../../features' |
| 5 | +import { getVirtualSpells } from '../exports' |
| 6 | +import { readGraphFromJSON, writeGraphToJSON } from '@magickml/behave-graph' |
| 7 | +import type { Spell, SerializedSpell } from '../../types' |
| 8 | +import fs from 'fs/promises' |
| 9 | +import path from 'path' |
| 10 | + |
| 11 | +export default defineNovaPlugin<SpellFeatures, any, any, any, any>({ |
| 12 | + useRuntimeConfig, |
| 13 | + initialize: (nitro, config) => { |
| 14 | + const spellOptions = config.spells || {} |
| 15 | + return { spellOptions } |
| 16 | + }, |
| 17 | + before: async (nitro, br) => {}, |
| 18 | + runtimeSetup: { |
| 19 | + spells: { |
| 20 | + getVirtualHandlers: getVirtualSpells, |
| 21 | + initFeatureHandlers: async (nitro, handlers) => { |
| 22 | + for (const handler of handlers) { |
| 23 | + const spellDefinition = (await handler.handler()).default |
| 24 | + console.log('feature spell scanned:', spellDefinition) |
| 25 | + } |
| 26 | + // const spellsDir = path.join(process.cwd(), 'server', 'spells'); |
| 27 | + // await loadSpellsFromDirectory(spellsDir); |
| 28 | + // for (const handler of handlers) { |
| 29 | + // const spellDefinition = (await handler.handler()).default; |
| 30 | + // spellRegistry.add(spellDefinition); |
| 31 | + // } |
| 32 | + }, |
| 33 | + }, |
| 34 | + }, |
| 35 | + after: (nitro, br) => { |
| 36 | + // @ts-ignore todo: declare |
| 37 | + nitro.spellRegistry = spellRegistry |
| 38 | + console.info( |
| 39 | + 'Spell module initialized. Use nitro.spellRegistry to access spells.' |
| 40 | + ) |
| 41 | + }, |
| 42 | +}) |
| 43 | + |
| 44 | +async function loadSpellsFromDirectory(directory: string) { |
| 45 | + try { |
| 46 | + const files = await fs.readdir(directory) |
| 47 | + for (const file of files) { |
| 48 | + if (path.extname(file) === '.json') { |
| 49 | + const filePath = path.join(directory, file) |
| 50 | + const content = await fs.readFile(filePath, 'utf-8') |
| 51 | + const serializedSpell: SerializedSpell = JSON.parse(content) |
| 52 | + const spell: Spell = { |
| 53 | + ...serializedSpell, |
| 54 | + graph: readGraphFromJSON({ |
| 55 | + graphJson: serializedSpell.graph, |
| 56 | + registry: useRuntimeConfig().registry, |
| 57 | + }), |
| 58 | + } |
| 59 | + spellRegistry.add(spell) |
| 60 | + } |
| 61 | + } |
| 62 | + } catch (error) { |
| 63 | + console.error('Error loading spells from directory:', error) |
| 64 | + } |
| 65 | +} |
0 commit comments