oh-my-opencode/src/shared/jsonc-parser.test.ts
YeonGyu-Kim f146aeff0f
refactor: major codebase cleanup - BDD comments, file splitting, bug fixes (#1350)
* style(tests): normalize BDD comments from '// #given' to '// given'

- Replace 4,668 Python-style BDD comments across 107 test files
- Patterns changed: // #given -> // given, // #when -> // when, // #then -> // then
- Also handles no-space variants: //#given -> // given

* fix(rules-injector): prefer output.metadata.filePath over output.title

- Extract file path resolution to dedicated output-path.ts module
- Prefer metadata.filePath which contains actual file path
- Fall back to output.title only when metadata unavailable
- Fixes issue where rules weren't injected when tool output title was a label

* feat(slashcommand): add optional user_message parameter

- Add user_message optional parameter for command arguments
- Model can now call: command='publish' user_message='patch'
- Improves error messages with clearer format guidance
- Helps LLMs understand correct parameter usage

* feat(hooks): restore compaction-context-injector hook

- Restore hook deleted in cbbc7bd0 for session compaction context
- Injects 7 mandatory sections: User Requests, Final Goal, Work Completed,
  Remaining Tasks, Active Working Context, MUST NOT Do, Agent Verification State
- Re-register in hooks/index.ts and main plugin entry

* refactor(background-agent): split manager.ts into focused modules

- Extract constants.ts for TTL values and internal types (52 lines)
- Extract state.ts for TaskStateManager class (204 lines)
- Extract spawner.ts for task creation logic (244 lines)
- Extract result-handler.ts for completion handling (265 lines)
- Reduce manager.ts from 1377 to 755 lines (45% reduction)
- Maintain backward compatible exports

* refactor(agents): split prometheus-prompt.ts into subdirectory

- Move 1196-line prometheus-prompt.ts to prometheus/ subdirectory
- Organize prompt sections into separate files for maintainability
- Update agents/index.ts exports

* refactor(delegate-task): split tools.ts into focused modules

- Extract categories.ts for category definitions and routing
- Extract executor.ts for task execution logic
- Extract helpers.ts for utility functions
- Extract prompt-builder.ts for prompt construction
- Reduce tools.ts complexity with cleaner separation of concerns

* refactor(builtin-skills): split skills.ts into individual skill files

- Move each skill to dedicated file in skills/ subdirectory
- Create barrel export for backward compatibility
- Improve maintainability with focused skill modules

* chore: update import paths and lockfile

- Update prometheus import path after refactor
- Update bun.lock

* fix(tests): complete BDD comment normalization

- Fix remaining #when/#then patterns missed by initial sed
- Affected: state.test.ts, events.test.ts

---------

Co-authored-by: justsisyphus <justsisyphus@users.noreply.github.com>
2026-02-01 16:47:50 +09:00

267 lines
6.0 KiB
TypeScript

import { describe, expect, test } from "bun:test"
import { detectConfigFile, parseJsonc, parseJsoncSafe, readJsoncFile } from "./jsonc-parser"
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"
import { join } from "node:path"
describe("parseJsonc", () => {
test("parses plain JSON", () => {
// given
const json = `{"key": "value"}`
// when
const result = parseJsonc<{ key: string }>(json)
// then
expect(result.key).toBe("value")
})
test("parses JSONC with line comments", () => {
// given
const jsonc = `{
// This is a comment
"key": "value"
}`
// when
const result = parseJsonc<{ key: string }>(jsonc)
// then
expect(result.key).toBe("value")
})
test("parses JSONC with block comments", () => {
// given
const jsonc = `{
/* Block comment */
"key": "value"
}`
// when
const result = parseJsonc<{ key: string }>(jsonc)
// then
expect(result.key).toBe("value")
})
test("parses JSONC with multi-line block comments", () => {
// given
const jsonc = `{
/* Multi-line
comment
here */
"key": "value"
}`
// when
const result = parseJsonc<{ key: string }>(jsonc)
// then
expect(result.key).toBe("value")
})
test("parses JSONC with trailing commas", () => {
// given
const jsonc = `{
"key1": "value1",
"key2": "value2",
}`
// when
const result = parseJsonc<{ key1: string; key2: string }>(jsonc)
// then
expect(result.key1).toBe("value1")
expect(result.key2).toBe("value2")
})
test("parses JSONC with trailing comma in array", () => {
// given
const jsonc = `{
"arr": [1, 2, 3,]
}`
// when
const result = parseJsonc<{ arr: number[] }>(jsonc)
// then
expect(result.arr).toEqual([1, 2, 3])
})
test("preserves URLs with // in strings", () => {
// given
const jsonc = `{
"url": "https://example.com"
}`
// when
const result = parseJsonc<{ url: string }>(jsonc)
// then
expect(result.url).toBe("https://example.com")
})
test("parses complex JSONC config", () => {
// given
const jsonc = `{
// This is an example config
"agents": {
"oracle": { "model": "openai/gpt-5.2" }, // GPT for strategic reasoning
},
/* Agent overrides */
"disabled_agents": [],
}`
// when
const result = parseJsonc<{
agents: { oracle: { model: string } }
disabled_agents: string[]
}>(jsonc)
// then
expect(result.agents.oracle.model).toBe("openai/gpt-5.2")
expect(result.disabled_agents).toEqual([])
})
test("throws on invalid JSON", () => {
// given
const invalid = `{ "key": invalid }`
// when
// then
expect(() => parseJsonc(invalid)).toThrow()
})
test("throws on unclosed string", () => {
// given
const invalid = `{ "key": "unclosed }`
// when
// then
expect(() => parseJsonc(invalid)).toThrow()
})
})
describe("parseJsoncSafe", () => {
test("returns data on valid JSONC", () => {
// given
const jsonc = `{ "key": "value" }`
// when
const result = parseJsoncSafe<{ key: string }>(jsonc)
// then
expect(result.data).not.toBeNull()
expect(result.data?.key).toBe("value")
expect(result.errors).toHaveLength(0)
})
test("returns errors on invalid JSONC", () => {
// given
const invalid = `{ "key": invalid }`
// when
const result = parseJsoncSafe(invalid)
// then
expect(result.data).toBeNull()
expect(result.errors.length).toBeGreaterThan(0)
})
})
describe("readJsoncFile", () => {
const testDir = join(__dirname, ".test-jsonc")
const testFile = join(testDir, "config.jsonc")
test("reads and parses valid JSONC file", () => {
// given
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true })
const content = `{
// Comment
"test": "value"
}`
writeFileSync(testFile, content)
// when
const result = readJsoncFile<{ test: string }>(testFile)
// then
expect(result).not.toBeNull()
expect(result?.test).toBe("value")
rmSync(testDir, { recursive: true, force: true })
})
test("returns null for non-existent file", () => {
// given
const nonExistent = join(testDir, "does-not-exist.jsonc")
// when
const result = readJsoncFile(nonExistent)
// then
expect(result).toBeNull()
})
test("returns null for malformed JSON", () => {
// given
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true })
writeFileSync(testFile, "{ invalid }")
// when
const result = readJsoncFile(testFile)
// then
expect(result).toBeNull()
rmSync(testDir, { recursive: true, force: true })
})
})
describe("detectConfigFile", () => {
const testDir = join(__dirname, ".test-detect")
test("prefers .jsonc over .json", () => {
// given
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true })
const basePath = join(testDir, "config")
writeFileSync(`${basePath}.json`, "{}")
writeFileSync(`${basePath}.jsonc`, "{}")
// when
const result = detectConfigFile(basePath)
// then
expect(result.format).toBe("jsonc")
expect(result.path).toBe(`${basePath}.jsonc`)
rmSync(testDir, { recursive: true, force: true })
})
test("detects .json when .jsonc doesn't exist", () => {
// given
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true })
const basePath = join(testDir, "config")
writeFileSync(`${basePath}.json`, "{}")
// when
const result = detectConfigFile(basePath)
// then
expect(result.format).toBe("json")
expect(result.path).toBe(`${basePath}.json`)
rmSync(testDir, { recursive: true, force: true })
})
test("returns none when neither exists", () => {
// given
const basePath = join(testDir, "nonexistent")
// when
const result = detectConfigFile(basePath)
// then
expect(result.format).toBe("none")
})
})