mono/packages/kbot/src/variables.ts
2025-02-21 09:06:09 +01:00

65 lines
2.0 KiB
TypeScript

import * as path from 'node:path'
import { pathInfoEx } from '@polymech/commons'
import { DEFAULT_ROOTS, DEFAULT_VARS } from '@polymech/commons'
import { IKBotTask } from '@polymech/ai-tools'
export const variables = (options: IKBotTask) => {
const { model, router,baseURL } = options
let ret = {
model,
router,
baseURL,
...DEFAULT_ROOTS,
...DEFAULT_VARS({})
}
if (options?.include?.length === 1) {
const [include] = options.include
const { } = pathInfoEx(include)
const srcParts = path.parse(include)
const srcVariables: Record<string, string> = {}
srcVariables.SRC_NAME = srcParts.name
srcVariables.SRC_DIR = srcParts.dir
srcVariables.SRC_EXT = srcParts.ext
if (srcVariables.ROOT) {
srcVariables.SRC_REL = path.relative(srcVariables.ROOT, srcParts.dir)
}
const dashed = srcParts.name.split('-')
if (dashed.length > 1) {
for (let i = 0; i < dashed.length; i++) {
srcVariables[`SRC_NAME-${i}`] = dashed[i]
}
}
const dotted = srcParts.name.split('.')
if (dotted.length > 1) {
for (let i = 0; i < dotted.length; i++) {
srcVariables[`SRC_NAME.${i}`] = dotted[i]
}
}
const underscored = srcParts.name.split('_')
if (underscored.length > 1) {
for (let i = 0; i < underscored.length; i++) {
srcVariables[`SRC_NAME_${i}`] = underscored[i]
}
}
ret = { ...ret, ...srcVariables }
}
// CLI argv variables
let variables = Object.assign({}, ...Object.keys(options).filter((k) => k.startsWith('var-')).map((k) => {
return {
[k.replace('var-', '')]: options[k]
}
}))
ret = Object.keys(ret).reduce((acc, key) => {
acc[key.toUpperCase()] = ret[key];
return acc;
}, {});
return { ...ret, ...variables }
}