mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 19:34:38 +00:00
refactor(monorepo): decouple api and webui into workspaces packages
This commit is contained in:
@@ -18,7 +18,7 @@ import {
|
||||
AssetUserInfo,
|
||||
} from '@shumai/dtos'
|
||||
import { type Asset, AssetStatus, AssetType, Prisma, type StorageKey } from '@shumai/db'
|
||||
import { logger } from '@/logger'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import * as dotenv from 'dotenv'
|
||||
import { expand as dotenvExpand } from 'dotenv-expand'
|
||||
|
||||
export type Env = { [key: string]: string | undefined }
|
||||
export type LoadedEnvFiles = Array<{
|
||||
path: string
|
||||
contents: string
|
||||
env: Env
|
||||
}>
|
||||
|
||||
let initialEnv: Env | undefined = undefined
|
||||
let combinedEnv: Env | undefined = undefined
|
||||
let cachedLoadedEnvFiles: LoadedEnvFiles = []
|
||||
|
||||
type Log = {
|
||||
info: (...args: unknown[]) => void
|
||||
error: (...args: unknown[]) => void
|
||||
}
|
||||
|
||||
function replaceProcessEnv(sourceEnv: Env) {
|
||||
Object.keys(process.env).forEach((key) => {
|
||||
if (sourceEnv[key] === undefined || sourceEnv[key] === '') {
|
||||
delete process.env[key]
|
||||
}
|
||||
})
|
||||
|
||||
Object.entries(sourceEnv).forEach(([key, value]) => {
|
||||
process.env[key] = value
|
||||
})
|
||||
}
|
||||
|
||||
export function processEnv(loadedEnvFiles: LoadedEnvFiles, dir?: string, log: Log = console) {
|
||||
if (!initialEnv) {
|
||||
initialEnv = Object.assign({}, process.env)
|
||||
}
|
||||
|
||||
const origEnv = Object.assign({}, initialEnv)
|
||||
const parsed: dotenv.DotenvParseOutput = {}
|
||||
|
||||
for (const envFile of loadedEnvFiles) {
|
||||
try {
|
||||
const result: dotenv.DotenvConfigOutput = {}
|
||||
result.parsed = dotenv.parse(envFile.contents)
|
||||
|
||||
const expandResult = dotenvExpand(result)
|
||||
const parsedResult = expandResult.parsed
|
||||
if (parsedResult) {
|
||||
for (const key of Object.keys(parsedResult)) {
|
||||
if (typeof parsed[key] === 'undefined' && typeof origEnv[key] === 'undefined') {
|
||||
parsed[key] = parsedResult[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
envFile.env = result.parsed || {}
|
||||
} catch (err) {
|
||||
log.error(`Failed to load env from ${path.join(dir || '', envFile.path)}`, err)
|
||||
}
|
||||
}
|
||||
|
||||
return Object.assign(process.env, parsed)
|
||||
}
|
||||
|
||||
export function loadEnvConfig(
|
||||
dir: string,
|
||||
dev?: boolean,
|
||||
log: Log = console,
|
||||
): {
|
||||
combinedEnv: Env
|
||||
loadedEnvFiles: LoadedEnvFiles
|
||||
} {
|
||||
if (!initialEnv) {
|
||||
initialEnv = Object.assign({}, process.env)
|
||||
}
|
||||
|
||||
if (combinedEnv) {
|
||||
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
|
||||
}
|
||||
|
||||
replaceProcessEnv(initialEnv)
|
||||
cachedLoadedEnvFiles = []
|
||||
|
||||
const isTest = process.env.NODE_ENV === 'test'
|
||||
const mode = isTest ? 'test' : dev ? 'development' : 'production'
|
||||
const dotenvFiles = [
|
||||
`.env.${mode}.local`,
|
||||
mode !== 'test' && `.env.local`,
|
||||
`.env.${mode}`,
|
||||
'.env',
|
||||
].filter(Boolean) as string[]
|
||||
|
||||
for (const envFile of dotenvFiles) {
|
||||
const dotEnvPath = path.join(dir, envFile)
|
||||
|
||||
try {
|
||||
const stats = fs.statSync(dotEnvPath)
|
||||
|
||||
if (!stats.isFile() && !stats.isFIFO()) {
|
||||
continue
|
||||
}
|
||||
|
||||
const contents = fs.readFileSync(dotEnvPath, 'utf8')
|
||||
cachedLoadedEnvFiles.push({
|
||||
path: envFile,
|
||||
contents,
|
||||
env: {},
|
||||
})
|
||||
} catch (err: unknown) {
|
||||
if (err && typeof err === 'object' && 'code' in err && err.code !== 'ENOENT') {
|
||||
log.error(`Failed to load env from ${envFile}`, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
combinedEnv = processEnv(cachedLoadedEnvFiles, dir, log)
|
||||
|
||||
return { combinedEnv, loadedEnvFiles: cachedLoadedEnvFiles }
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
import pino from 'pino'
|
||||
|
||||
const LOG_LEVEL = process.env.LOG_LEVEL || 'info'
|
||||
const LOG_FORMAT = process.env.LOG_FORMAT || 'json'
|
||||
|
||||
const transport =
|
||||
LOG_FORMAT === 'console'
|
||||
? {
|
||||
target: 'pino-pretty',
|
||||
options: {
|
||||
colorize: true,
|
||||
},
|
||||
}
|
||||
: undefined
|
||||
|
||||
export const logger = pino({
|
||||
level: LOG_LEVEL,
|
||||
transport,
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import { teamService } from '@shumai/core/src/team/team'
|
||||
import { providerService } from './provider'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { builtinProviders } from '@/generated/providers.generated'
|
||||
import { builtinProviders } from '@shumai/core/src/generated/providers.generated'
|
||||
import { z } from 'zod'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
|
||||
import { builtinProviders } from '@/generated/providers.generated'
|
||||
import { builtinProviders } from '@shumai/core/src/generated/providers.generated'
|
||||
import { z } from 'zod'
|
||||
|
||||
type ProviderModel = z.infer<typeof providerModelSchema>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AssetService, assetService } from '@shumai/core/src/asset/asset'
|
||||
import { AssetInfo } from '@shumai/dtos'
|
||||
import { SearchRequest } from '@shumai/dtos'
|
||||
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
|
||||
import { generateSearchNgrams } from '@/utils/ngram'
|
||||
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { SqlQueryBuilder } from './sql-query-builder'
|
||||
|
||||
@@ -4,7 +4,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as crypto from 'crypto'
|
||||
import { ulid } from 'ulid'
|
||||
import { parseFrontmatter } from '@/utils/frontmatter'
|
||||
import { parseFrontmatter } from '@shumai/core/src/utils/frontmatter'
|
||||
|
||||
interface SkillFrontmatter extends Record<string, unknown> {
|
||||
name?: string
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseFrontmatter } from './frontmatter'
|
||||
|
||||
describe('frontmatter parser', () => {
|
||||
it('should parse content with frontmatter', () => {
|
||||
const content = `---
|
||||
name: test-skill
|
||||
description: simple skill
|
||||
---
|
||||
# Body
|
||||
Hello world`
|
||||
const { frontmatter, body } = parseFrontmatter<{ name: string; description: string }>(content)
|
||||
expect(frontmatter.name).toBe('test-skill')
|
||||
expect(frontmatter.description).toBe('simple skill')
|
||||
expect(body).toBe('# Body\nHello world')
|
||||
})
|
||||
|
||||
it('should handle content without frontmatter', () => {
|
||||
const content = '# No Frontmatter\nJust text'
|
||||
const { frontmatter, body } = parseFrontmatter(content)
|
||||
expect(frontmatter).toEqual({})
|
||||
expect(body).toBe(content)
|
||||
})
|
||||
|
||||
it('should handle invalid frontmatter delimiters', () => {
|
||||
const content = `---
|
||||
no-end-delimiter
|
||||
# Body`
|
||||
const { frontmatter, body } = parseFrontmatter(content)
|
||||
expect(frontmatter).toEqual({})
|
||||
expect(body).toBe(content)
|
||||
})
|
||||
|
||||
it('should normalize newlines', () => {
|
||||
const content = '---\r\nname: win\r\n---\r\n# Body'
|
||||
const { frontmatter, body } = parseFrontmatter<{ name: string }>(content)
|
||||
expect(frontmatter.name).toBe('win')
|
||||
expect(body).toBe('# Body')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { parse } from 'yaml'
|
||||
|
||||
export type ParsedFrontmatter<T extends Record<string, unknown>> = {
|
||||
frontmatter: T
|
||||
body: string
|
||||
}
|
||||
|
||||
const normalizeNewlines = (value: string): string =>
|
||||
value.replace(/\r\n/g, '\n').replace(/\r/g, '\n')
|
||||
|
||||
const extractFrontmatter = (content: string): { yamlString: string | null; body: string } => {
|
||||
const normalized = normalizeNewlines(content)
|
||||
|
||||
if (!normalized.startsWith('---')) {
|
||||
return { yamlString: null, body: normalized }
|
||||
}
|
||||
|
||||
const endIndex = normalized.indexOf('\n---', 3)
|
||||
if (endIndex === -1) {
|
||||
return { yamlString: null, body: normalized }
|
||||
}
|
||||
|
||||
return {
|
||||
yamlString: normalized.slice(4, endIndex),
|
||||
body: normalized.slice(endIndex + 4).trim(),
|
||||
}
|
||||
}
|
||||
|
||||
export const parseFrontmatter = <T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
content: string,
|
||||
): ParsedFrontmatter<T> => {
|
||||
const { yamlString, body } = extractFrontmatter(content)
|
||||
if (!yamlString) {
|
||||
return { frontmatter: {} as T, body }
|
||||
}
|
||||
const parsed = parse(yamlString)
|
||||
return { frontmatter: (parsed ?? {}) as T, body }
|
||||
}
|
||||
|
||||
export const stripFrontmatter = (content: string): string => parseFrontmatter(content).body
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { detectSupportedMimeType } from './mime'
|
||||
|
||||
describe('detectSupportedMimeType', () => {
|
||||
it('should detect JPEG', () => {
|
||||
const buffer = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/jpeg')
|
||||
})
|
||||
|
||||
it('should detect PNG', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
|
||||
0x52,
|
||||
])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/png')
|
||||
})
|
||||
|
||||
it('should detect GIF', () => {
|
||||
const buffer = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/gif')
|
||||
})
|
||||
|
||||
it('should detect WEBP', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50,
|
||||
])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('image/webp')
|
||||
})
|
||||
|
||||
it('should detect MP4', () => {
|
||||
const buffer = new Uint8Array([
|
||||
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x69, 0x73, 0x6f, 0x6d,
|
||||
])
|
||||
expect(detectSupportedMimeType(buffer)).toBe('video/mp4')
|
||||
})
|
||||
|
||||
it('should return null for unknown type', () => {
|
||||
const buffer = new Uint8Array([0x00, 0x00, 0x00, 0x00])
|
||||
expect(detectSupportedMimeType(buffer)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
|
||||
|
||||
export function detectSupportedMimeType(buffer: Uint8Array): string | null {
|
||||
if (startsWith(buffer, [0xff, 0xd8, 0xff])) {
|
||||
return buffer[3] === 0xf7 ? null : 'image/jpeg'
|
||||
}
|
||||
if (startsWith(buffer, PNG_SIGNATURE)) {
|
||||
return isPng(buffer) && !isAnimatedPng(buffer) ? 'image/png' : null
|
||||
}
|
||||
if (startsWithAscii(buffer, 0, 'GIF')) {
|
||||
return 'image/gif'
|
||||
}
|
||||
if (startsWithAscii(buffer, 0, 'RIFF') && startsWithAscii(buffer, 8, 'WEBP')) {
|
||||
return 'image/webp'
|
||||
}
|
||||
if (startsWithAscii(buffer, 4, 'ftyp')) {
|
||||
return 'video/mp4'
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function isPng(buffer: Uint8Array): boolean {
|
||||
return (
|
||||
buffer.length >= 16 &&
|
||||
readUint32Be(buffer, PNG_SIGNATURE.length) === 13 &&
|
||||
startsWithAscii(buffer, 12, 'IHDR')
|
||||
)
|
||||
}
|
||||
|
||||
function isAnimatedPng(buffer: Uint8Array): boolean {
|
||||
let offset = PNG_SIGNATURE.length
|
||||
while (offset + 8 <= buffer.length) {
|
||||
const chunkLength = readUint32Be(buffer, offset)
|
||||
const chunkTypeOffset = offset + 4
|
||||
if (startsWithAscii(buffer, chunkTypeOffset, 'acTL')) return true
|
||||
if (startsWithAscii(buffer, chunkTypeOffset, 'IDAT')) return false
|
||||
|
||||
const nextOffset = offset + 8 + chunkLength + 4
|
||||
if (nextOffset <= offset || nextOffset > buffer.length) return false
|
||||
offset = nextOffset
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
function readUint32Be(buffer: Uint8Array, offset: number): number {
|
||||
return (
|
||||
(buffer[offset] ?? 0) * 0x1000000 +
|
||||
((buffer[offset + 1] ?? 0) << 16) +
|
||||
((buffer[offset + 2] ?? 0) << 8) +
|
||||
(buffer[offset + 3] ?? 0)
|
||||
)
|
||||
}
|
||||
|
||||
function startsWith(buffer: Uint8Array, bytes: number[]): boolean {
|
||||
if (buffer.length < bytes.length) return false
|
||||
return bytes.every((byte, index) => buffer[index] === byte)
|
||||
}
|
||||
|
||||
function startsWithAscii(buffer: Uint8Array, offset: number, text: string): boolean {
|
||||
if (buffer.length < offset + text.length) return false
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
if (buffer[offset + index] !== text.charCodeAt(index)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { generateNgrams } from './ngram'
|
||||
|
||||
describe('generateNgrams', () => {
|
||||
it('should generate 1-3 grams for simple English words', () => {
|
||||
const tokens = generateNgrams('apple')
|
||||
const expected = ['a', 'p', 'l', 'e', 'ap', 'pp', 'pl', 'le', 'app', 'ppl', 'ple']
|
||||
expect(tokens.sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('should handle multiple words and separators as single stream', () => {
|
||||
const tokens = generateNgrams('foo-bar')
|
||||
// f, o, o, -, b, a, r
|
||||
// fo, oo, o-, -b, ba, ar
|
||||
// foo, oo-, o-b, -ba, bar
|
||||
const expected = [
|
||||
'f',
|
||||
'o',
|
||||
'-',
|
||||
'b',
|
||||
'a',
|
||||
'r',
|
||||
'fo',
|
||||
'oo',
|
||||
'o-',
|
||||
'-b',
|
||||
'ba',
|
||||
'ar',
|
||||
'foo',
|
||||
'oo-',
|
||||
'o-b',
|
||||
'-ba',
|
||||
'bar',
|
||||
]
|
||||
expect(tokens.sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('should handle CJK characters correctly', () => {
|
||||
const tokens = generateNgrams('北京大学')
|
||||
// 北, 京, 大, 学
|
||||
// 北京, 京大, 大学
|
||||
// 北京大, 京大学
|
||||
const expected = ['北', '京', '大', '学', '北京', '京大', '大学', '北京大', '京大学']
|
||||
expect(tokens.sort()).toEqual(expected.sort())
|
||||
})
|
||||
|
||||
it('should be case-insensitive', () => {
|
||||
const tokens = generateNgrams('Apple')
|
||||
expect(tokens).toEqual(generateNgrams('apple'))
|
||||
})
|
||||
|
||||
it('should NOT ignore non-alphanumeric characters', () => {
|
||||
const tokens = generateNgrams('apple!!!')
|
||||
expect(tokens).toContain('e!!')
|
||||
expect(tokens).toContain('!!!')
|
||||
})
|
||||
|
||||
it('should return empty array for empty input', () => {
|
||||
expect(generateNgrams('')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Generates 1-gram, 2-gram, and 3-gram tokens for a given text.
|
||||
* Used for optimizing substring searches (especially for CJK characters).
|
||||
*
|
||||
* Examples:
|
||||
* "apple" -> a, p, l, e, ap, pp, pl, le, app, ppl, ple
|
||||
* "foo-bar" -> f, o, -, b, a, r, fo, oo, o-, -b, ba, ar, foo, oo-, o-b, -ba, bar
|
||||
*/
|
||||
export function generateNgrams(text: string): string[] {
|
||||
if (!text) return []
|
||||
|
||||
const normalized = text.toLowerCase()
|
||||
const tokens = new Set<string>()
|
||||
const chars = Array.from(normalized) // Unicode-aware character splitting
|
||||
|
||||
for (let i = 0; i < chars.length; i++) {
|
||||
// 1-gram
|
||||
tokens.add(chars[i])
|
||||
|
||||
// 2-gram
|
||||
if (i + 1 < chars.length) {
|
||||
tokens.add(chars[i] + chars[i + 1])
|
||||
}
|
||||
|
||||
// 3-gram
|
||||
if (i + 2 < chars.length) {
|
||||
tokens.add(chars[i] + chars[i + 1] + chars[i + 2])
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(tokens)
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates only the longest possible n-grams for a search query.
|
||||
* If the word is 3+ chars, only return 3-grams.
|
||||
* If 2 chars, return 2-grams.
|
||||
* If 1 char, return 1-grams.
|
||||
*
|
||||
* This significantly improves search performance by reducing GIN index intersection overhead.
|
||||
*/
|
||||
export function generateSearchNgrams(text: string): string[] {
|
||||
if (!text) return []
|
||||
|
||||
const normalized = text.toLowerCase()
|
||||
const tokens = new Set<string>()
|
||||
const chars = Array.from(normalized)
|
||||
const len = chars.length
|
||||
|
||||
if (len >= 3) {
|
||||
for (let i = 0; i <= len - 3; i++) {
|
||||
tokens.add(chars[i] + chars[i + 1] + chars[i + 2])
|
||||
}
|
||||
} else if (len === 2) {
|
||||
tokens.add(chars[0] + chars[1])
|
||||
} else if (len === 1) {
|
||||
tokens.add(chars[0])
|
||||
}
|
||||
|
||||
return Array.from(tokens)
|
||||
}
|
||||
Reference in New Issue
Block a user