kasaframe 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (338) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +146 -0
  3. package/README.md +77 -2
  4. package/app/package.json +12 -0
  5. package/app/server/engine.ts +415 -0
  6. package/app/server/main.ts +205 -0
  7. package/app/web/env.d.ts +2 -0
  8. package/app/web/icons.ts +31 -0
  9. package/app/web/index.html +21 -0
  10. package/app/web/main.ts +1013 -0
  11. package/app/web/style.css +430 -0
  12. package/bin/hooks.mjs +51 -0
  13. package/bin/kf.mjs +14 -0
  14. package/docs/AGENTS.md +238 -0
  15. package/music/README.md +13 -0
  16. package/package.json +44 -4
  17. package/packages/adapters/package.json +36 -0
  18. package/packages/adapters/src/css.ts +11 -0
  19. package/packages/adapters/src/gsap.ts +26 -0
  20. package/packages/adapters/src/index.ts +9 -0
  21. package/packages/adapters/src/lottie.ts +22 -0
  22. package/packages/adapters/src/media.ts +59 -0
  23. package/packages/adapters/src/page.ts +229 -0
  24. package/packages/adapters/src/project.ts +214 -0
  25. package/packages/adapters/src/react.ts +36 -0
  26. package/packages/adapters/src/svelte.ts +22 -0
  27. package/packages/adapters/src/three.ts +18 -0
  28. package/packages/adapters/src/vue.ts +27 -0
  29. package/packages/check/package.json +19 -0
  30. package/packages/check/src/check.ts +273 -0
  31. package/packages/check/src/cli.ts +70 -0
  32. package/packages/check/src/image.ts +146 -0
  33. package/packages/check/src/index.ts +9 -0
  34. package/packages/check/src/ocr.swift +37 -0
  35. package/packages/check/src/probe.ts +328 -0
  36. package/packages/check/src/report.ts +44 -0
  37. package/packages/check/src/rules/assets.ts +42 -0
  38. package/packages/check/src/rules/beats.ts +212 -0
  39. package/packages/check/src/rules/camera.ts +217 -0
  40. package/packages/check/src/rules/captions.ts +49 -0
  41. package/packages/check/src/rules/flash.ts +235 -0
  42. package/packages/check/src/rules/frames.ts +135 -0
  43. package/packages/check/src/rules/layout.ts +257 -0
  44. package/packages/check/src/rules/page.ts +87 -0
  45. package/packages/check/src/rules/runs.ts +20 -0
  46. package/packages/check/src/rules/text.ts +326 -0
  47. package/packages/check/src/scan.ts +240 -0
  48. package/packages/check/src/serve.ts +67 -0
  49. package/packages/check/src/types.ts +80 -0
  50. package/packages/check/src/video.ts +137 -0
  51. package/packages/cli/package.json +29 -0
  52. package/packages/cli/src/blur.ts +68 -0
  53. package/packages/cli/src/browser.ts +203 -0
  54. package/packages/cli/src/command.ts +44 -0
  55. package/packages/cli/src/commands/app.ts +25 -0
  56. package/packages/cli/src/commands/beats.ts +36 -0
  57. package/packages/cli/src/commands/blender.ts +270 -0
  58. package/packages/cli/src/commands/check.ts +25 -0
  59. package/packages/cli/src/commands/doctor.ts +22 -0
  60. package/packages/cli/src/commands/gen.ts +173 -0
  61. package/packages/cli/src/commands/look.ts +39 -0
  62. package/packages/cli/src/commands/lyrics.ts +111 -0
  63. package/packages/cli/src/commands/make.ts +542 -0
  64. package/packages/cli/src/commands/new.ts +176 -0
  65. package/packages/cli/src/commands/preview.ts +43 -0
  66. package/packages/cli/src/commands/render.ts +216 -0
  67. package/packages/cli/src/commands/setup.ts +63 -0
  68. package/packages/cli/src/commands/sheet.ts +114 -0
  69. package/packages/cli/src/commands/skill.ts +43 -0
  70. package/packages/cli/src/commands/still.ts +40 -0
  71. package/packages/cli/src/commands/theme.ts +85 -0
  72. package/packages/cli/src/commands/transitions.ts +40 -0
  73. package/packages/cli/src/deps.ts +122 -0
  74. package/packages/cli/src/ffmpeg.ts +81 -0
  75. package/packages/cli/src/index.ts +8 -0
  76. package/packages/cli/src/kf.ts +53 -0
  77. package/packages/cli/src/lock.ts +72 -0
  78. package/packages/cli/src/out.ts +13 -0
  79. package/packages/cli/src/serve.ts +124 -0
  80. package/packages/clock/package.json +14 -0
  81. package/packages/clock/src/index.ts +25 -0
  82. package/packages/clock/src/install.ts +351 -0
  83. package/packages/clock/src/types.ts +45 -0
  84. package/packages/core/package.json +9 -0
  85. package/packages/core/src/beats.ts +283 -0
  86. package/packages/core/src/ease.ts +87 -0
  87. package/packages/core/src/frame.ts +99 -0
  88. package/packages/core/src/index.ts +27 -0
  89. package/packages/core/src/project.ts +146 -0
  90. package/packages/core/src/rand.ts +56 -0
  91. package/packages/core/src/spring.ts +52 -0
  92. package/packages/core/src/style.ts +100 -0
  93. package/packages/core/src/time.ts +88 -0
  94. package/packages/gen/PROVIDERS.md +55 -0
  95. package/packages/gen/package.json +9 -0
  96. package/packages/gen/src/generate.ts +204 -0
  97. package/packages/gen/src/image/og.ts +133 -0
  98. package/packages/gen/src/index.ts +18 -0
  99. package/packages/gen/src/keys.ts +60 -0
  100. package/packages/gen/src/media.ts +150 -0
  101. package/packages/gen/src/plan.ts +106 -0
  102. package/packages/gen/src/registry.ts +51 -0
  103. package/packages/gen/src/seam.ts +103 -0
  104. package/packages/gen/src/types.ts +86 -0
  105. package/packages/gen/src/video/fal.ts +140 -0
  106. package/packages/gen/src/video/h3.ts +107 -0
  107. package/packages/gen/src/video/http.ts +44 -0
  108. package/packages/gen/src/video/ltx.ts +60 -0
  109. package/packages/gen/src/video/minimax.ts +55 -0
  110. package/packages/gen/src/video/veo.ts +71 -0
  111. package/packages/jizura/package.json +16 -0
  112. package/packages/jizura/src/deny.ts +73 -0
  113. package/packages/jizura/src/index.ts +7 -0
  114. package/packages/jizura/src/install.ts +226 -0
  115. package/packages/jizura/src/layer.ts +282 -0
  116. package/packages/jizura/src/lyrics.ts +81 -0
  117. package/packages/jizura/src/pin.ts +5 -0
  118. package/packages/jizura/src/vite.ts +36 -0
  119. package/packages/motion/README.md +142 -0
  120. package/packages/motion/package.json +29 -0
  121. package/packages/motion/src/camera.ts +97 -0
  122. package/packages/motion/src/captions.ts +479 -0
  123. package/packages/motion/src/enter.ts +128 -0
  124. package/packages/motion/src/hangul.ts +129 -0
  125. package/packages/motion/src/impact.ts +100 -0
  126. package/packages/motion/src/index.ts +17 -0
  127. package/packages/motion/src/moves/brushWipe.ts +90 -0
  128. package/packages/motion/src/moves/cloneArray.ts +111 -0
  129. package/packages/motion/src/moves/curtains.ts +81 -0
  130. package/packages/motion/src/moves/echoStack.ts +70 -0
  131. package/packages/motion/src/moves/fit.ts +34 -0
  132. package/packages/motion/src/moves/flood.ts +61 -0
  133. package/packages/motion/src/moves/ghostStack.ts +79 -0
  134. package/packages/motion/src/moves/gridFloor.ts +100 -0
  135. package/packages/motion/src/moves/imageSwarm.ts +109 -0
  136. package/packages/motion/src/moves/index.ts +19 -0
  137. package/packages/motion/src/moves/irisBlades.ts +113 -0
  138. package/packages/motion/src/moves/karaokeLine.ts +94 -0
  139. package/packages/motion/src/moves/ledBoard.ts +94 -0
  140. package/packages/motion/src/moves/liquidTab.ts +72 -0
  141. package/packages/motion/src/moves/markerWrite.ts +63 -0
  142. package/packages/motion/src/moves/morphBox.ts +96 -0
  143. package/packages/motion/src/moves/neonSign.ts +77 -0
  144. package/packages/motion/src/moves/panelPop.ts +78 -0
  145. package/packages/motion/src/moves/paperTear.ts +75 -0
  146. package/packages/motion/src/moves/path.ts +64 -0
  147. package/packages/motion/src/moves/pathText.ts +107 -0
  148. package/packages/motion/src/moves/pointSphere.ts +109 -0
  149. package/packages/motion/src/moves/ransomLetters.ts +73 -0
  150. package/packages/motion/src/moves/shapeMorph.ts +143 -0
  151. package/packages/motion/src/moves/slamWords.ts +89 -0
  152. package/packages/motion/src/moves/sparkTrail.ts +114 -0
  153. package/packages/motion/src/moves/speedLines.ts +91 -0
  154. package/packages/motion/src/moves/splitFlap.ts +147 -0
  155. package/packages/motion/src/moves/stepWords.ts +117 -0
  156. package/packages/motion/src/moves/strikeOut.ts +98 -0
  157. package/packages/motion/src/moves/sunburst.ts +58 -0
  158. package/packages/motion/src/moves/tickerRows.ts +87 -0
  159. package/packages/motion/src/moves/tokenPicker.ts +114 -0
  160. package/packages/motion/src/moves/truchet.ts +85 -0
  161. package/packages/motion/src/moves/wordWall.ts +76 -0
  162. package/packages/motion/src/moves/worldRoll.ts +31 -0
  163. package/packages/motion/src/particles.ts +102 -0
  164. package/packages/motion/src/react/index.tsx +21 -0
  165. package/packages/motion/src/react/parts.tsx +431 -0
  166. package/packages/motion/src/react/time.tsx +97 -0
  167. package/packages/motion/src/text.ts +103 -0
  168. package/packages/motion/src/transition.ts +82 -0
  169. package/packages/motion/src/transition3d/cards.ts +65 -0
  170. package/packages/motion/src/transition3d/chain.ts +84 -0
  171. package/packages/motion/src/transition3d/dive.ts +181 -0
  172. package/packages/motion/src/transition3d/fold.ts +110 -0
  173. package/packages/motion/src/transition3d/gl.ts +219 -0
  174. package/packages/motion/src/transition3d/index.ts +228 -0
  175. package/packages/motion/src/transition3d/live.ts +70 -0
  176. package/packages/motion/src/transition3d/portal.ts +115 -0
  177. package/packages/motion/src/transition3d/react.tsx +29 -0
  178. package/packages/motion/src/transition3d/rig.ts +502 -0
  179. package/packages/motion/src/transition3d/shatter.ts +101 -0
  180. package/packages/motion/src/transition3d/whip.ts +65 -0
  181. package/packages/motion/src/transition3d/world.ts +683 -0
  182. package/packages/motion/src/transition3d/zoomOut.ts +114 -0
  183. package/packages/motion/src/transitions2d/catalog.ts +127 -0
  184. package/packages/motion/src/transitions2d/css.d.ts +2 -0
  185. package/packages/motion/src/transitions2d/cult-ui/LICENSE.md +9 -0
  186. package/packages/motion/src/transitions2d/cult-ui/RollingNumber.tsx +43 -0
  187. package/packages/motion/src/transitions2d/gl-transitions/LICENSE +25 -0
  188. package/packages/motion/src/transitions2d/gl-transitions/shaders.ts +1931 -0
  189. package/packages/motion/src/transitions2d/index.ts +2 -0
  190. package/packages/motion/src/transitions2d/kokonutui/LICENSE +21 -0
  191. package/packages/motion/src/transitions2d/kokonutui/MatrixText.css +16 -0
  192. package/packages/motion/src/transitions2d/kokonutui/MatrixText.tsx +94 -0
  193. package/packages/motion/src/transitions2d/magicui/HyperText.css +15 -0
  194. package/packages/motion/src/transitions2d/magicui/HyperText.tsx +115 -0
  195. package/packages/motion/src/transitions2d/magicui/LICENSE.md +21 -0
  196. package/packages/motion/src/transitions2d/magicui/MorphingText.css +25 -0
  197. package/packages/motion/src/transitions2d/magicui/MorphingText.tsx +130 -0
  198. package/packages/motion/src/transitions2d/magicui/WordRotate.tsx +42 -0
  199. package/packages/motion/src/transitions2d/react.ts +13 -0
  200. package/packages/motion/src/transitions2d/skiper-ui/ClipDiv.css +39 -0
  201. package/packages/motion/src/transitions2d/skiper-ui/ClipDiv.tsx +32 -0
  202. package/packages/motion/src/transitions2d/smoothui/LICENSE +21 -0
  203. package/packages/motion/src/transitions2d/smoothui/SharedAxisY.tsx +50 -0
  204. package/packages/motion/src/transitions2d/smoothui/TextMorph.tsx +90 -0
  205. package/packages/motion/src/transitions2d/smoothui/shaders.ts +223 -0
  206. package/packages/motion/src/transitions2d/unlumen/LICENSE +21 -0
  207. package/packages/motion/src/transitions2d/unlumen/ScrambleText.tsx +114 -0
  208. package/packages/motion/src/transitions2d/vengeance-ui/LICENSE +21 -0
  209. package/packages/motion/src/transitions2d/vengeance-ui/MorphText.css +69 -0
  210. package/packages/motion/src/transitions2d/vengeance-ui/MorphText.tsx +45 -0
  211. package/packages/motion/src/type.ts +131 -0
  212. package/packages/motion/src/ui.ts +172 -0
  213. package/packages/plan/package.json +15 -0
  214. package/packages/plan/src/brief.ts +254 -0
  215. package/packages/plan/src/captions.ts +75 -0
  216. package/packages/plan/src/detect.ts +93 -0
  217. package/packages/plan/src/index.ts +23 -0
  218. package/packages/plan/src/layout.ts +176 -0
  219. package/packages/plan/src/llm.ts +110 -0
  220. package/packages/plan/src/look.ts +220 -0
  221. package/packages/plan/src/plan.ts +125 -0
  222. package/packages/plan/src/request.ts +55 -0
  223. package/packages/plan/src/studio.ts +53 -0
  224. package/packages/plan/src/templates.ts +42 -0
  225. package/packages/plan/src/themes.ts +48 -0
  226. package/packages/plan/src/types.ts +106 -0
  227. package/packages/studio/package.json +12 -0
  228. package/packages/studio/src/index.ts +1 -0
  229. package/packages/studio/src/plugin.ts +236 -0
  230. package/packages/studio/src/ui/main.ts +503 -0
  231. package/packages/studio/src/ui/studio.css +165 -0
  232. package/packages/studio/src/ui/timeline.ts +317 -0
  233. package/packages/themes/kit/THEME-MAKE.md +68 -0
  234. package/packages/themes/kit/THEME.md +30 -0
  235. package/packages/themes/kit/briefs/og-intro-15s/brief.json +16 -0
  236. package/packages/themes/kit/briefs/og-intro-15s/facts.ts +29 -0
  237. package/packages/themes/kit/briefs/og-intro-15s/logo.svg +12 -0
  238. package/packages/themes/kit/effects.ts +5 -0
  239. package/packages/themes/kit/sample/index.html +11 -0
  240. package/packages/themes/kit/sample/main.ts +9 -0
  241. package/packages/themes/kit/sample/scenes/scene.ts +15 -0
  242. package/packages/themes/package.json +16 -0
  243. package/packages/themes/src/factory.ts +296 -0
  244. package/packages/themes/src/fx.ts +14 -0
  245. package/packages/themes/src/index.ts +105 -0
  246. package/packages/themes/src/stage3d.ts +177 -0
  247. package/packages/themes/src/types.ts +58 -0
  248. package/presets/kawaii-pastel.json +94 -0
  249. package/presets/neutral-dark.json +82 -0
  250. package/presets/og.json +98 -0
  251. package/skills/kasaframe/SKILL.md +32 -0
  252. package/templates/_shared/project/index.html +11 -0
  253. package/templates/_shared/project/lib/react.ts +22 -0
  254. package/templates/_shared/project/lib/stage.ts +272 -0
  255. package/templates/_shared/project/main.ts +9 -0
  256. package/templates/_shared/scenes/default.ts +18 -0
  257. package/templates/_shared/scenes/drop.ts +30 -0
  258. package/templates/_shared/scenes/end.ts +23 -0
  259. package/templates/_shared/scenes/hook.ts +16 -0
  260. package/templates/_shared/scenes/seam.ts +41 -0
  261. package/templates/_shared/scenes/step.ts +40 -0
  262. package/templates/ad/preview.png +0 -0
  263. package/templates/ad/template.json +132 -0
  264. package/templates/demo/preview.png +0 -0
  265. package/templates/demo/template.json +130 -0
  266. package/templates/explainer/preview.png +0 -0
  267. package/templates/explainer/template.json +142 -0
  268. package/templates/launch/preview.png +0 -0
  269. package/templates/launch/template.json +130 -0
  270. package/templates/mv/preview.png +0 -0
  271. package/templates/mv/scenes/default.ts +95 -0
  272. package/templates/mv/template.json +176 -0
  273. package/templates/promo/preview.png +0 -0
  274. package/templates/promo/template.json +144 -0
  275. package/templates/shorts/preview.png +0 -0
  276. package/templates/shorts/scenes/hook.ts +34 -0
  277. package/templates/shorts/template.json +127 -0
  278. package/templates/square/preview.png +0 -0
  279. package/templates/square/template.json +113 -0
  280. package/themes/debug-hud/THEME.md +39 -0
  281. package/themes/debug-hud/effects.ts +389 -0
  282. package/themes/debug-hud/sample/assets/og/logo.svg +12 -0
  283. package/themes/debug-hud/sample/beats.json +1 -0
  284. package/themes/debug-hud/sample/index.html +11 -0
  285. package/themes/debug-hud/sample/kf.json +59 -0
  286. package/themes/debug-hud/sample/lib/hudkit.ts +49 -0
  287. package/themes/debug-hud/sample/lib/og.ts +29 -0
  288. package/themes/debug-hud/sample/main.ts +9 -0
  289. package/themes/debug-hud/sample/scenes/end.ts +62 -0
  290. package/themes/debug-hud/sample/scenes/gather.ts +67 -0
  291. package/themes/debug-hud/sample/scenes/models.ts +70 -0
  292. package/themes/debug-hud/sample/scenes/price.ts +79 -0
  293. package/themes/debug-hud/sample/style.json +91 -0
  294. package/themes/debug-hud/still.png +0 -0
  295. package/themes/debug-hud/style.json +91 -0
  296. package/themes/debug-hud/theme.json +68 -0
  297. package/themes/og-measure/THEME.md +47 -0
  298. package/themes/og-measure/effects.ts +432 -0
  299. package/themes/og-measure/sample/assets/brand/og-logo-full.svg +12 -0
  300. package/themes/og-measure/sample/assets/brand/og-logo.svg +12 -0
  301. package/themes/og-measure/sample/assets/data/measure.json +353 -0
  302. package/themes/og-measure/sample/beats.json +1 -0
  303. package/themes/og-measure/sample/index.html +11 -0
  304. package/themes/og-measure/sample/kf.json +66 -0
  305. package/themes/og-measure/sample/lib/data.ts +62 -0
  306. package/themes/og-measure/sample/main.ts +9 -0
  307. package/themes/og-measure/sample/measure.ts +78 -0
  308. package/themes/og-measure/sample/scenes/end.ts +47 -0
  309. package/themes/og-measure/sample/scenes/gather.ts +51 -0
  310. package/themes/og-measure/sample/scenes/models.ts +34 -0
  311. package/themes/og-measure/sample/scenes/one.ts +39 -0
  312. package/themes/og-measure/sample/scenes/price.ts +56 -0
  313. package/themes/og-measure/sample/style.json +97 -0
  314. package/themes/og-measure/still.png +0 -0
  315. package/themes/og-measure/style.json +97 -0
  316. package/themes/og-measure/theme.json +79 -0
  317. package/themes/riso-zine/THEME.md +43 -0
  318. package/themes/riso-zine/effects.ts +321 -0
  319. package/themes/riso-zine/sample/assets/og/logo.svg +12 -0
  320. package/themes/riso-zine/sample/beats.json +1 -0
  321. package/themes/riso-zine/sample/index.html +11 -0
  322. package/themes/riso-zine/sample/kf.json +59 -0
  323. package/themes/riso-zine/sample/lib/og.ts +29 -0
  324. package/themes/riso-zine/sample/lib/shot.ts +86 -0
  325. package/themes/riso-zine/sample/lib/zine.ts +42 -0
  326. package/themes/riso-zine/sample/main.ts +9 -0
  327. package/themes/riso-zine/sample/scenes/end.ts +61 -0
  328. package/themes/riso-zine/sample/scenes/gather.ts +62 -0
  329. package/themes/riso-zine/sample/scenes/models.ts +52 -0
  330. package/themes/riso-zine/sample/scenes/price.ts +82 -0
  331. package/themes/riso-zine/sample/style.json +99 -0
  332. package/themes/riso-zine/still.png +0 -0
  333. package/themes/riso-zine/style.json +99 -0
  334. package/themes/riso-zine/theme.json +75 -0
  335. package/tools/beats/beats.py +372 -0
  336. package/tools/beats/requirements.txt +3 -0
  337. package/tools/lyrics/align.py +164 -0
  338. package/tools/lyrics/requirements.txt +9 -0
@@ -0,0 +1,415 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
3
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { basename, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { listTemplates, makePlan, type Plan, type Purpose, suggestThemes } from "@kasaframe/plan";
7
+ import { loadTheme, themeCards, type ThemeStatus } from "@kasaframe/themes";
8
+ import { captionMode } from "@kasaframe/motion/captions";
9
+
10
+ // 화면과 상관없는 엔진 — HTTP 서버든 Electron 이든 컨테이너든 이걸 감싸기만 한다. 일은 전부 kf 명령을 자식 프로세스로 돌린다.
11
+
12
+ const repo = fileURLToPath(new URL("../../", import.meta.url));
13
+ const kfBin = join(repo, "packages/cli/src/kf.ts");
14
+ export const dataDir = resolve(process.env.KF_APP_DIR ?? join(repo, "out", "app"));
15
+ export const templatePreview = (id: string) => join(repo, "templates", id, "preview.png");
16
+ // 5159 는 작업실 화면의 HMR 자리
17
+ const PREVIEW_PORTS = [5151, 5152, 5153, 5154, 5155, 5156, 5157, 5158];
18
+
19
+ export type Phase = "plan" | "scaffold" | "gen" | "scenes" | "render" | "check" | "done" | "waiting" | "failed";
20
+
21
+ export interface JobInput {
22
+ request: string;
23
+ purpose?: Purpose | "auto";
24
+ music?: string;
25
+ assets?: string[]; // /api/upload 로 올린 파일 경로들 — 일 폴더 in/ 에 모아 kf make --assets 로 넘긴다
26
+ theme?: string; // 테마 id 나 "auto"
27
+ model?: string;
28
+ approve?: boolean;
29
+ title?: string;
30
+ captions?: "on" | "off"; // 화면 자막 — 안 주면 틀 기본
31
+ }
32
+
33
+ export interface Job {
34
+ id: string;
35
+ external?: boolean; // 말로 시작한 kf make 가 스스로 등록한 일 — 서버가 돌리지 않고 진행만 받는다
36
+ input: JobInput;
37
+ dir: string;
38
+ phase: Phase;
39
+ progress: number; // 렌더 진행 0..1
40
+ running: boolean;
41
+ createdAt: number;
42
+ previewUrl?: string;
43
+ log: string[];
44
+ error?: string;
45
+ checkPassed?: boolean;
46
+ }
47
+
48
+ export interface JobView extends Omit<Job, "log"> {
49
+ plan?: Plan;
50
+ kf?: unknown;
51
+ // alt — 자막을 반대로 다시 구운 판(video-자막.mp4 · video-자막없음.mp4). captions — 들릴 말(captions.json)이 있다
52
+ files: { video?: string; cover?: string; check?: string; alt?: string; captions?: string };
53
+ }
54
+
55
+ const PHASES: [RegExp, Phase][] = [
56
+ [/^용도 /, "scaffold"],
57
+ [/^생성 자산/, "gen"],
58
+ [/^계획 다듬/, "scaffold"],
59
+ [/^장면 \S+ 쓰는 중/, "scenes"],
60
+ [/^\s+\S+ \d+번째/, "scenes"],
61
+ [/^\s+\d+\/\d+ \(\d+%\)/, "render"],
62
+ [/^고치기 /, "scenes"],
63
+ [/^그림 검사/, "check"],
64
+ ];
65
+
66
+ export class Engine extends EventEmitter {
67
+ jobs = new Map<string, Job>();
68
+ private procs = new Map<string, ChildProcess>();
69
+ private previews = new Map<string, { proc: ChildProcess; port: number }>();
70
+
71
+ constructor() {
72
+ super();
73
+ mkdirSync(join(dataDir, "jobs"), { recursive: true });
74
+ for (const id of readdirSync(join(dataDir, "jobs"))) {
75
+ const f = join(dataDir, "jobs", id, "job.json");
76
+ if (!existsSync(f)) continue;
77
+ const job: Job = { ...JSON.parse(readFileSync(f, "utf8")), running: false, previewUrl: undefined };
78
+ if (!["done", "failed", "waiting"].includes(job.phase)) job.phase = "failed";
79
+ this.jobs.set(id, job);
80
+ }
81
+ }
82
+
83
+ // 틀 고르는 화면용. still 은 templates/_shared/previews.ts 가 뽑아 둔 대표 한 장
84
+ templates() {
85
+ return listTemplates().map((t) => ({
86
+ id: t.id,
87
+ label: t.label,
88
+ summary: t.summary,
89
+ aspect: t.aspect,
90
+ aspects: [t.aspect, ...Object.keys(t.variants ?? {})],
91
+ width: t.width,
92
+ height: t.height,
93
+ duration: t.duration,
94
+ music: t.music,
95
+ captions: t.captions,
96
+ deliverables: t.deliverables,
97
+ scenes: t.scenes.map((s) => s.id),
98
+ still: existsSync(templatePreview(t.id)) ? `/api/templates/${t.id}/still.png` : null,
99
+ }));
100
+ }
101
+
102
+ // 만들기 전에 보여 줄 계획 — 곡 분석 없이 길이·장면 비율만. 사람이 용도를 고르면 판별을 건너뛰고, "auto" 거나 비우면 판별한다
103
+ plan(request: string, purpose?: Purpose | "auto", theme?: string): Plan {
104
+ return makePlan({ request, purpose: purpose && purpose !== "auto" ? purpose : undefined, theme });
105
+ }
106
+
107
+ // 목록은 approved 만(SPEC 9). all 이면 review·draft 도 — 테마 만드는 사람이 견본을 보는 자리
108
+ themes(o: { all?: boolean; purpose?: string; aspect?: string } = {}) {
109
+ const status: ThemeStatus[] = o.all ? ["approved", "review", "draft"] : ["approved"];
110
+ return themeCards({ status, ...(o.purpose ? { purpose: o.purpose } : {}), ...(o.aspect ? { aspect: o.aspect } : {}) }).map((c) => ({
111
+ ...c,
112
+ still: c.still ? `/api/themes/${c.id}/still` : null,
113
+ sample: c.sample ? `/api/themes/${c.id}/sample` : null,
114
+ }));
115
+ }
116
+
117
+ themeFile(id: string, which: "still" | "sample"): string | null {
118
+ return loadTheme(id).files[which];
119
+ }
120
+
121
+ suggest(request: string, purpose: Purpose) {
122
+ return { candidates: suggestThemes(request, purpose) };
123
+ }
124
+
125
+ // 테마 공장(kf theme) — new 는 뼈대·지시서까지 만들고 그 지시서를 받을 세션 명령을 돌려준다(테마는 그 세션이 만든다).
126
+ // review 는 굽기라 무겁다 — 하나씩, 진행은 themeTask 로. approve 는 사람이 화면에서 견본을 보고 누를 때만
127
+ private themeTasks = new Map<string, { running: boolean; log: string[]; code: number | null }>();
128
+
129
+ async themeNew(o: { id: string; refs: string[]; name?: string; like?: string; threeD?: boolean }): Promise<{ ok: boolean; command: string | null; log: string[] }> {
130
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(o.id)) throw Object.assign(new Error("테마 id 는 영문 소문자·숫자·- 만"), { status: 400 });
131
+ if (!o.refs?.length) throw Object.assign(new Error("참고 자료(refs)가 하나는 있어야 한다"), { status: 400 });
132
+ const args = ["theme", "new", o.id, ...o.refs.flatMap((r) => ["--ref", r])];
133
+ if (o.name) args.push("--name", o.name);
134
+ if (o.like) args.push("--like", o.like);
135
+ if (o.threeD) args.push("--3d");
136
+ const { code, log } = await this.kf(args);
137
+ const at = log.findIndex((l) => l.includes("세션 열기"));
138
+ return { ok: code === 0, command: at >= 0 ? (log[at + 1]?.trim() ?? null) : null, log };
139
+ }
140
+
141
+ themeReview(id: string): { started: boolean } {
142
+ const cur = this.themeTasks.get(id);
143
+ if (cur?.running) throw Object.assign(new Error("이미 굽는 중"), { status: 409 });
144
+ const task = { running: true, log: [] as string[], code: null as number | null };
145
+ this.themeTasks.set(id, task);
146
+ void this.kf(["theme", "review", id, "--tabs", "2"], (l) => task.log.push(l)).then(({ code }) => {
147
+ task.running = false;
148
+ task.code = code;
149
+ });
150
+ return { started: true };
151
+ }
152
+
153
+ themeTask(id: string) {
154
+ const t = this.themeTasks.get(id);
155
+ return t ? { running: t.running, code: t.code, log: t.log.slice(-60) } : { running: false, code: null, log: [] };
156
+ }
157
+
158
+ async themeApprove(id: string) {
159
+ return this.kf(["theme", "approve", id]);
160
+ }
161
+
162
+ private kf(args: string[], onLine?: (l: string) => void): Promise<{ code: number; log: string[] }> {
163
+ return new Promise((done) => {
164
+ const log: string[] = [];
165
+ const proc = spawn(process.execPath, [kfBin, ...args], { cwd: repo, env: { ...process.env, CLAUDECODE: "" } });
166
+ for (const stream of [proc.stdout, proc.stderr]) {
167
+ let buf = "";
168
+ stream.setEncoding("utf8");
169
+ stream.on("data", (chunk: string) => {
170
+ buf += chunk;
171
+ const parts = buf.split(/\r?\n/);
172
+ buf = parts.pop() ?? "";
173
+ for (const l of parts) {
174
+ log.push(l);
175
+ onLine?.(l);
176
+ }
177
+ });
178
+ }
179
+ proc.on("close", (code) => done({ code: code ?? 1, log }));
180
+ });
181
+ }
182
+
183
+ create(input: JobInput): Job {
184
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
185
+ const job: Job = { id, input, dir: join(dataDir, "jobs", id, "project"), phase: "plan", progress: 0, running: false, createdAt: Date.now(), log: [] };
186
+ this.jobs.set(id, job);
187
+ mkdirSync(join(dataDir, "jobs", id), { recursive: true });
188
+ const args = ["make", input.request, "--out", job.dir, "--model", input.model ?? "deepseek/deepseek-v4-pro"];
189
+ if (input.purpose && input.purpose !== "auto") args.push("--purpose", input.purpose);
190
+ if (input.music) args.push("--music", input.music);
191
+ const given = (input.assets ?? []).filter((a) => existsSync(a));
192
+ if (given.length) {
193
+ const inDir = join(dataDir, "jobs", id, "in");
194
+ mkdirSync(inDir, { recursive: true });
195
+ for (const a of given) copyFileSync(a, join(inDir, basename(a).replace(/^[a-z0-9]+-/, "")));
196
+ args.push("--assets", inDir);
197
+ }
198
+ if (input.title) args.push("--title", input.title);
199
+ if (input.theme) args.push("--theme", input.theme);
200
+ if (input.approve) args.push("--yes");
201
+ if (input.captions) args.push("--captions", input.captions);
202
+ this.run(job, args);
203
+ return job;
204
+ }
205
+
206
+ // 장면 카드에서 고친 뒤: 고른 장면만 다시 쓰고 렌더·검사
207
+ rewrite(id: string, scenes: string[]): Job {
208
+ const job = this.must(id);
209
+ this.run(job, ["make", "--rewrite", job.dir, "--scenes", scenes.join(","), "--model", job.input.model ?? "deepseek/deepseek-v4-pro"]);
210
+ return job;
211
+ }
212
+
213
+ // captions 를 주면 장면을 다시 쓰지 않고 자막만 켜고(끄고) 따로 굽는다 — 원본 video.mp4 는 그대로 두고 -자막 판을 옆에
214
+ rerender(id: string, o: { captions?: "on" | "off" } = {}): Job {
215
+ const job = this.must(id);
216
+ const caps = o.captions === "on" || o.captions === "off" ? ["--captions", o.captions, "--suffix"] : [];
217
+ this.run(job, ["make", "--finish", job.dir, "--model", job.input.model ?? "deepseek/deepseek-v4-pro", "--fix", "0", ...caps]);
218
+ return job;
219
+ }
220
+
221
+ // 말로 시작한 kf make(Claude Code 등)가 스스로 등록한다 — 같은 폴더면 같은 일(--finish 가 다시 붙는다)
222
+ attach(o: { dir: string; request: string; model?: string; purpose?: Purpose }): Job {
223
+ const dir = resolve(o.dir);
224
+ const had = [...this.jobs.values()].find((j) => j.dir === dir);
225
+ if (had) return had;
226
+ const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
227
+ const job: Job = { id, external: true, input: { request: o.request, model: o.model, purpose: o.purpose }, dir, phase: "scaffold", progress: 0, running: true, createdAt: Date.now(), log: [] };
228
+ this.jobs.set(id, job);
229
+ mkdirSync(join(dataDir, "jobs", id), { recursive: true });
230
+ if (existsSync(join(dir, "kf.json"))) this.startPreview(job);
231
+ this.save(job);
232
+ this.emit("state", this.view(id));
233
+ return job;
234
+ }
235
+
236
+ progress(id: string, p: { lines?: string[]; phase?: Phase; done?: boolean; ok?: boolean }): void {
237
+ const job = this.must(id);
238
+ for (const line of p.lines ?? []) {
239
+ job.log.push(line);
240
+ for (const [re, phase] of PHASES) if (re.test(line)) job.phase = phase;
241
+ const pct = line.match(/\((\d+)%\)/);
242
+ if (pct && job.phase === "render") job.progress = Number(pct[1]) / 100;
243
+ this.emit("log", id, line);
244
+ }
245
+ if (job.log.length > 800) job.log.splice(0, job.log.length - 800);
246
+ if (p.phase) job.phase = p.phase;
247
+ job.running = !p.done;
248
+ if (p.done) {
249
+ job.checkPassed = !!p.ok;
250
+ job.phase = p.phase ?? (existsSync(join(job.dir, "out", "video.mp4")) ? "done" : "failed");
251
+ this.stopPreview(job);
252
+ } else if (!job.previewUrl && existsSync(join(job.dir, "kf.json"))) this.startPreview(job);
253
+ this.save(job);
254
+ this.emit("state", this.view(id));
255
+ }
256
+
257
+ editScene(id: string, sceneId: string, patch: { idea?: string; dur?: number }): unknown {
258
+ const job = this.must(id);
259
+ const kfPath = join(job.dir, "kf.json");
260
+ const kf = JSON.parse(readFileSync(kfPath, "utf8"));
261
+ const i = kf.scenes.findIndex((s: { id: string }) => s.id === sceneId);
262
+ if (i < 0) throw new Error(`장면 ${sceneId} 가 없다`);
263
+ if (patch.idea !== undefined) kf.scenes[i].idea = patch.idea;
264
+ // 시간표는 빈틈 없이 이어져야 한다(계약 6) — 길이를 바꾸면 다음 장면 시작이 따라 움직인다
265
+ if (patch.dur !== undefined && i < kf.scenes.length - 1) {
266
+ const next = kf.scenes[i + 1];
267
+ const end = next.from + next.dur;
268
+ const dur = Math.round(Math.max(0.5, Math.min(patch.dur, end - kf.scenes[i].from - 0.5)) * kf.fps) / kf.fps;
269
+ kf.scenes[i].dur = +dur.toFixed(4);
270
+ next.from = +(kf.scenes[i].from + dur).toFixed(4);
271
+ next.dur = +(end - next.from).toFixed(4);
272
+ }
273
+ writeFileSync(kfPath, `${JSON.stringify(kf, null, 2)}\n`);
274
+ const planPath = join(job.dir, "plan.json");
275
+ if (existsSync(planPath) && patch.idea !== undefined) {
276
+ const plan = JSON.parse(readFileSync(planPath, "utf8"));
277
+ const s = plan.scenes?.find((x: { id: string }) => x.id === sceneId);
278
+ if (s) s.idea = patch.idea;
279
+ writeFileSync(planPath, `${JSON.stringify(plan, null, 2)}\n`);
280
+ }
281
+ this.emit("state", this.view(id));
282
+ return kf;
283
+ }
284
+
285
+ view(id: string): JobView {
286
+ const job = this.must(id);
287
+ const read = (f: string) => (existsSync(join(job.dir, f)) ? JSON.parse(readFileSync(join(job.dir, f), "utf8")) : undefined);
288
+ const has = (f: string) => (existsSync(join(job.dir, f)) ? f : undefined);
289
+ const { log: _log, ...rest } = job;
290
+ const kf = read("kf.json");
291
+ const alt = has(captionMode(kf?.captions) === "on" ? "out/video-자막없음.mp4" : "out/video-자막.mp4");
292
+ return { ...rest, plan: read("plan.json"), kf, files: { video: has("out/video.mp4"), cover: has("out/cover.png"), check: has("out/check.json"), alt, captions: has("captions.json") } };
293
+ }
294
+
295
+ list(): JobView[] {
296
+ return [...this.jobs.keys()].map((id) => this.view(id)).sort((a, b) => b.createdAt - a.createdAt);
297
+ }
298
+
299
+ logOf(id: string): string[] {
300
+ return this.must(id).log;
301
+ }
302
+
303
+ stop(id: string): void {
304
+ this.procs.get(id)?.kill("SIGTERM");
305
+ }
306
+
307
+ async close(): Promise<void> {
308
+ for (const p of this.procs.values()) p.kill("SIGTERM");
309
+ for (const p of this.previews.values()) p.proc.kill("SIGTERM");
310
+ }
311
+
312
+ private must(id: string): Job {
313
+ const job = this.jobs.get(id);
314
+ if (!job) throw Object.assign(new Error(`일 ${id} 가 없다`), { status: 404 });
315
+ return job;
316
+ }
317
+
318
+ private run(job: Job, args: string[]): void {
319
+ if (job.running) throw Object.assign(new Error("이미 돌고 있다"), { status: 409 });
320
+ job.running = true;
321
+ job.error = undefined;
322
+ job.progress = 0;
323
+ const proc = spawn(process.execPath, [kfBin, ...args], { cwd: repo, env: { ...process.env, CLAUDECODE: "" } });
324
+ this.procs.set(job.id, proc);
325
+ const onLine = (line: string) => {
326
+ if (!line.trim()) return;
327
+ job.log.push(line);
328
+ if (job.log.length > 800) job.log.splice(0, job.log.length - 800);
329
+ for (const [re, phase] of PHASES) if (re.test(line)) job.phase = phase;
330
+ const pct = line.match(/\((\d+)%\)/);
331
+ if (pct && job.phase === "render") job.progress = Number(pct[1]) / 100;
332
+ if (/^검사:/.test(line)) job.phase = "check";
333
+ this.emit("log", job.id, line);
334
+ if (!job.previewUrl && existsSync(join(job.dir, "kf.json"))) this.startPreview(job);
335
+ this.emit("state", this.view(job.id));
336
+ };
337
+ for (const stream of [proc.stdout, proc.stderr]) {
338
+ let buf = "";
339
+ stream.setEncoding("utf8");
340
+ stream.on("data", (chunk: string) => {
341
+ buf += chunk;
342
+ const parts = buf.split(/\r?\n|\r/);
343
+ buf = parts.pop() ?? "";
344
+ parts.forEach(onLine);
345
+ });
346
+ }
347
+ proc.on("close", (code) => {
348
+ this.procs.delete(job.id);
349
+ job.running = false;
350
+ // 다 만들었으면 화면은 MP4 를 튼다 — 미리보기 서버는 꺼서 기계 부하를 줄인다(다시 보려면 /preview 가 다시 띄운다)
351
+ this.stopPreview(job);
352
+ job.checkPassed = code === 0;
353
+ if (code === 0) job.phase = "done";
354
+ else if (code === 3) job.phase = "waiting";
355
+ else {
356
+ job.phase = existsSync(join(job.dir, "out", "video.mp4")) ? "done" : "failed";
357
+ job.error = job.log.slice(-6).join("\n");
358
+ }
359
+ job.progress = job.phase === "done" ? 1 : job.progress;
360
+ this.save(job);
361
+ this.emit("state", this.view(job.id));
362
+ });
363
+ this.save(job);
364
+ }
365
+
366
+ // 만드는 동안 장면 파일이 쓰일 때마다 미리보기가 저절로 새로 고쳐진다(kf preview 의 감시)
367
+ private startPreview(job: Job): void {
368
+ if (this.previews.has(job.id)) return;
369
+ const used = new Set([...this.previews.values()].map((p) => p.port));
370
+ let port = PREVIEW_PORTS.find((p) => !used.has(p));
371
+ if (port === undefined) {
372
+ const [oldest] = this.previews.keys();
373
+ const old = this.previews.get(oldest)!;
374
+ old.proc.kill("SIGTERM");
375
+ this.previews.delete(oldest);
376
+ const j = this.jobs.get(oldest);
377
+ if (j) j.previewUrl = undefined;
378
+ port = old.port;
379
+ }
380
+ const proc = spawn(process.execPath, [kfBin, "preview", job.dir, "--port", String(port)], { cwd: repo, stdio: ["ignore", "pipe", "pipe"] });
381
+ this.previews.set(job.id, { proc, port });
382
+ job.previewUrl = `http://127.0.0.1:${port}/`;
383
+ const grab = (chunk: Buffer) => {
384
+ const m = chunk.toString().match(/https?:\/\/[^\s]+/);
385
+ if (m) {
386
+ job.previewUrl = m[0];
387
+ this.emit("state", this.view(job.id));
388
+ }
389
+ };
390
+ proc.stdout?.on("data", grab);
391
+ proc.stderr?.on("data", grab);
392
+ proc.on("close", () => {
393
+ if (this.previews.get(job.id)?.proc === proc) this.previews.delete(job.id);
394
+ });
395
+ }
396
+
397
+ private stopPreview(job: Job): void {
398
+ const p = this.previews.get(job.id);
399
+ if (!p) return;
400
+ p.proc.kill("SIGTERM");
401
+ this.previews.delete(job.id);
402
+ job.previewUrl = undefined;
403
+ }
404
+
405
+ previewFor(id: string): string | undefined {
406
+ const job = this.must(id);
407
+ if (!job.previewUrl && existsSync(join(job.dir, "kf.json"))) this.startPreview(job);
408
+ return job.previewUrl;
409
+ }
410
+
411
+ private save(job: Job): void {
412
+ const { previewUrl: _p, running: _r, ...rest } = job;
413
+ writeFileSync(join(dataDir, "jobs", job.id, "job.json"), `${JSON.stringify(rest, null, 2)}\n`);
414
+ }
415
+ }
@@ -0,0 +1,205 @@
1
+ import { createReadStream, createWriteStream, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
2
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
3
+ import { basename, extname, join, normalize, resolve } from "node:path";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { fileURLToPath } from "node:url";
6
+ import { createServer as createVite } from "vite";
7
+ import { dataDir, Engine, templatePreview } from "./engine.ts";
8
+
9
+ // 작업실 = 이 엔진 서버(API + SSE) + 그 API 만 쓰는 웹 화면. Electron·컨테이너로 갈 때도 이 파일만 감싼다.
10
+
11
+ const port = Number(process.env.KF_APP_PORT ?? 5150);
12
+ const host = process.env.KF_APP_HOST ?? "127.0.0.1";
13
+ const webRoot = fileURLToPath(new URL("../web/", import.meta.url));
14
+ const uploads = join(dataDir, "uploads");
15
+ // 곡 모음 — kf make 와 같은 자리(레포 music/, KF_MUSIC_DIR 이 있으면 그쪽)
16
+ const musicDir = process.env.KF_MUSIC_DIR || fileURLToPath(new URL("../../music/", import.meta.url));
17
+ mkdirSync(uploads, { recursive: true });
18
+
19
+ const engine = new Engine();
20
+ // 이 기계에서는 fs 이벤트 감시가 바뀐 파일을 못 알려 옛 모듈을 내줬다 — 작은 폴더라 훑기로 본다
21
+ const vite = await createVite({ root: webRoot, configFile: false, logLevel: "warn", clearScreen: false, server: { middlewareMode: true, hmr: { port: port + 9 }, watch: { usePolling: true, interval: 1000 } }, appType: "spa" });
22
+
23
+ const TYPES: Record<string, string> = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif", ".svg": "image/svg+xml", ".webm": "video/webm", ".m4v": "video/mp4", ".mp4": "video/mp4", ".png": "image/png", ".json": "application/json", ".srt": "text/plain; charset=utf-8", ".vtt": "text/vtt", ".mov": "video/quicktime", ".mp3": "audio/mpeg", ".wav": "audio/wav" };
24
+ const AUDIO = /\.(mp3|wav|m4a|aac|flac|ogg)$/i;
25
+ const IMAGE = /\.(png|jpe?g|webp|gif|svg)$/i;
26
+ const VIDEO = /\.(mp4|mov|webm|m4v)$/i;
27
+
28
+ function send(res: ServerResponse, status: number, body: unknown): void {
29
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
30
+ res.end(JSON.stringify(body));
31
+ }
32
+
33
+ async function body<T>(req: IncomingMessage): Promise<T> {
34
+ const chunks: Buffer[] = [];
35
+ for await (const c of req) chunks.push(c as Buffer);
36
+ return (chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {}) as T;
37
+ }
38
+
39
+ // 폰 사파리는 Range 를 못 받으면 영상을 안 튼다
40
+ function serveFile(req: IncomingMessage, res: ServerResponse, file: string): void {
41
+ const size = statSync(file).size;
42
+ const type = TYPES[extname(file).toLowerCase()] ?? "application/octet-stream";
43
+ const range = req.headers.range?.match(/bytes=(\d*)-(\d*)/);
44
+ const disposition = new URL(req.url ?? "", "http://x").searchParams.has("download") ? { "content-disposition": `attachment; filename="${basename(file)}"` } : {};
45
+ if (range) {
46
+ const start = range[1] ? Number(range[1]) : 0;
47
+ const end = range[2] ? Math.min(Number(range[2]), size - 1) : size - 1;
48
+ res.writeHead(206, { "content-type": type, "content-range": `bytes ${start}-${end}/${size}`, "accept-ranges": "bytes", "content-length": end - start + 1, ...disposition });
49
+ createReadStream(file, { start, end }).pipe(res);
50
+ return;
51
+ }
52
+ res.writeHead(200, { "content-type": type, "content-length": size, "accept-ranges": "bytes", "cache-control": "no-store", ...disposition });
53
+ createReadStream(file).pipe(res);
54
+ }
55
+
56
+ function sse(req: IncomingMessage, res: ServerResponse, jobId?: string): void {
57
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
58
+ const write = (event: string, data: unknown) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
59
+ if (jobId) {
60
+ write("state", engine.view(jobId));
61
+ for (const line of engine.logOf(jobId).slice(-200)) write("log", line);
62
+ }
63
+ const onState = (v: { id: string }) => (!jobId || v.id === jobId) && write("state", v);
64
+ const onLog = (id: string, line: string) => jobId === id && write("log", line);
65
+ engine.on("state", onState);
66
+ engine.on("log", onLog);
67
+ const ping = setInterval(() => res.write(": ping\n\n"), 15000);
68
+ req.on("close", () => {
69
+ clearInterval(ping);
70
+ engine.off("state", onState);
71
+ engine.off("log", onLog);
72
+ });
73
+ }
74
+
75
+ async function api(req: IncomingMessage, res: ServerResponse, path: string): Promise<void> {
76
+ const method = req.method ?? "GET";
77
+ const m = path.match(/^\/api\/jobs\/([\w-]+)(?:\/(.*))?$/);
78
+ if (path === "/api/templates") return send(res, 200, engine.templates());
79
+ const still = path.match(/^\/api\/templates\/([a-z]+)\/still\.png$/);
80
+ if (still) {
81
+ const f = templatePreview(still[1]);
82
+ return existsSync(f) ? serveFile(req, res, f) : send(res, 404, { error: "대표 그림이 없다 — node templates/_shared/previews.ts" });
83
+ }
84
+ if (path === "/api/plan" && method === "POST") {
85
+ const b = await body<{ request: string; purpose?: never; theme?: string }>(req);
86
+ // purpose: 틀 id 면 그 틀로, "auto" 거나 없으면 요청 글로 판별. theme: id 나 "auto"
87
+ return send(res, 200, engine.plan(b.request ?? "", b.purpose, b.theme));
88
+ }
89
+ if (path === "/api/themes" && method === "GET") {
90
+ const q = new URL(req.url ?? "", "http://x").searchParams;
91
+ return send(res, 200, engine.themes({ all: q.get("all") === "1", purpose: q.get("purpose") ?? undefined, aspect: q.get("aspect") ?? undefined }));
92
+ }
93
+ if (path === "/api/themes/suggest" && method === "POST") {
94
+ const b = await body<{ request: string; purpose: never }>(req);
95
+ return send(res, 200, engine.suggest(b.request ?? "", b.purpose));
96
+ }
97
+ if (path === "/api/themes/new" && method === "POST") return send(res, 200, await engine.themeNew(await body(req)));
98
+ const themeAct = path.match(/^\/api\/themes\/([\w-]+)\/(review|approve)$/);
99
+ if (themeAct) {
100
+ const [, id, act] = themeAct;
101
+ if (act === "review") return send(res, method === "POST" ? 202 : 200, method === "POST" ? engine.themeReview(id) : engine.themeTask(id));
102
+ if (method === "POST") return send(res, 200, await engine.themeApprove(id));
103
+ }
104
+ const themeFile = path.match(/^\/api\/themes\/([\w-]+)\/(still|sample)$/);
105
+ if (themeFile) {
106
+ const f = engine.themeFile(themeFile[1], themeFile[2] as "still" | "sample");
107
+ return f && existsSync(f) ? serveFile(req, res, f) : send(res, 404, { error: "테마 견본이 없다" });
108
+ }
109
+ if (path === "/api/events") return sse(req, res);
110
+ if (path === "/api/jobs" && method === "GET") return send(res, 200, engine.list());
111
+ if (path === "/api/jobs" && method === "POST") {
112
+ const b = await body<Parameters<Engine["create"]>[0]>(req);
113
+ if (!b.request?.trim()) return send(res, 400, { error: "요청 글이 비었다" });
114
+ return send(res, 201, engine.view(engine.create(b).id));
115
+ }
116
+ if (path === "/api/jobs/attach" && method === "POST") {
117
+ const job = engine.attach(await body(req));
118
+ return send(res, 200, { id: job.id, url: `http://${req.headers.host}/?job=${job.id}` });
119
+ }
120
+ if (path === "/api/music") {
121
+ const lib = musicDir;
122
+ // url 은 미리 듣기(Range) — 올린 곡은 /api/uploads, 곡 모음은 /api/music/<파일>
123
+ const list = (dir: string | undefined, base: string) =>
124
+ dir && existsSync(dir) ? readdirSync(dir).filter((f) => AUDIO.test(f)).map((f) => ({ name: f.replace(/^[a-z0-9]+-(?=.)/, base === "uploads" ? "" : "$&"), path: join(dir, f), url: `/api/${base}/${encodeURIComponent(f)}` })) : [];
125
+ return send(res, 200, [...list(uploads, "uploads"), ...list(lib, "music")]);
126
+ }
127
+ const song = path.match(/^\/api\/music\/(.+)$/);
128
+ if (song && method === "GET") {
129
+ const f = join(musicDir, basename(decodeURIComponent(song[1])));
130
+ return f && existsSync(f) ? serveFile(req, res, f) : send(res, 404, { error: "곡이 없다" });
131
+ }
132
+ // 올린 그림·영상 — POST /api/jobs 의 assets 로 다시 보낸다
133
+ if (path === "/api/assets") {
134
+ const list = readdirSync(uploads).filter((f) => IMAGE.test(f) || VIDEO.test(f)).map((f) => ({
135
+ name: f.replace(/^[a-z0-9]+-/, ""),
136
+ path: join(uploads, f),
137
+ kind: IMAGE.test(f) ? "image" : "video",
138
+ size: statSync(join(uploads, f)).size,
139
+ url: `/api/uploads/${encodeURIComponent(f)}`,
140
+ }));
141
+ return send(res, 200, list);
142
+ }
143
+ const up = path.match(/^\/api\/uploads\/(.+)$/);
144
+ if (up && method === "GET") {
145
+ const f = join(uploads, basename(decodeURIComponent(up[1])));
146
+ return existsSync(f) ? serveFile(req, res, f) : send(res, 404, { error: "파일이 없다" });
147
+ }
148
+ if (path === "/api/upload" && method === "POST") {
149
+ const name = basename(new URL(req.url ?? "", "http://x").searchParams.get("name") ?? "upload.bin").replace(/[^\w.\-가-힣]/g, "_");
150
+ const file = join(uploads, `${Date.now().toString(36)}-${name}`);
151
+ await pipeline(req, createWriteStream(file));
152
+ return send(res, 201, { name, path: file });
153
+ }
154
+ if (!m) return send(res, 404, { error: "없는 길" });
155
+ const [, id, rest = ""] = m;
156
+ if (!rest && method === "GET") return send(res, 200, engine.view(id));
157
+ if (rest === "events") return sse(req, res, id);
158
+ if (rest === "log") return send(res, 200, engine.logOf(id));
159
+ if (rest === "progress" && method === "POST") {
160
+ engine.progress(id, await body(req));
161
+ return send(res, 200, { ok: true });
162
+ }
163
+ if (rest === "preview") return send(res, 200, { url: engine.previewFor(id) ?? null });
164
+ if (rest === "stop" && method === "POST") {
165
+ engine.stop(id);
166
+ return send(res, 200, { ok: true });
167
+ }
168
+ if (rest === "render" && method === "POST") return send(res, 200, engine.view(engine.rerender(id, await body<{ captions?: "on" | "off" }>(req)).id));
169
+ if (rest === "rewrite" && method === "POST") {
170
+ const b = await body<{ scenes: string[] }>(req);
171
+ return send(res, 200, engine.view(engine.rewrite(id, b.scenes ?? []).id));
172
+ }
173
+ const scene = rest.match(/^scenes\/([\w-]+)$/);
174
+ if (scene && method === "PATCH") return send(res, 200, engine.editScene(id, scene[1], await body(req)));
175
+ const file = rest.match(/^files\/(.+)$/);
176
+ if (file && method === "GET") {
177
+ const dir = engine.view(id).dir;
178
+ const p = resolve(dir, normalize(decodeURIComponent(file[1])));
179
+ if (!p.startsWith(dir) || !existsSync(p) || statSync(p).isDirectory()) return send(res, 404, { error: "파일이 없다" });
180
+ return serveFile(req, res, p);
181
+ }
182
+ return send(res, 404, { error: "없는 길" });
183
+ }
184
+
185
+ const server = createServer(async (req, res) => {
186
+ const path = new URL(req.url ?? "/", "http://x").pathname;
187
+ if (!path.startsWith("/api/")) return vite.middlewares(req, res);
188
+ try {
189
+ await api(req, res, path);
190
+ } catch (e) {
191
+ const err = e as Error & { status?: number };
192
+ if (!res.headersSent) send(res, err.status ?? 500, { error: err.message });
193
+ }
194
+ });
195
+
196
+ server.listen(port, host, () => console.log(`작업실 http://${host === "0.0.0.0" ? "127.0.0.1" : host}:${port}/ (일 폴더 ${dataDir})`));
197
+
198
+ const shutdown = async () => {
199
+ await engine.close();
200
+ await vite.close();
201
+ server.close();
202
+ process.exit(0);
203
+ };
204
+ process.on("SIGINT", shutdown);
205
+ process.on("SIGTERM", shutdown);
@@ -0,0 +1,2 @@
1
+ // Vite 가 CSS 를 모듈로 가져온다
2
+ declare module "*.css";
@@ -0,0 +1,31 @@
1
+ // 선 굵기 하나(1.75)·둥근 끝으로 맞춘 24px 아이콘. 이모지 대신 쓴다.
2
+ const PATHS = {
3
+ back: '<path d="M15 6l-6 6 6 6"/>',
4
+ next: '<path d="M9 6l6 6-6 6"/>',
5
+ arrow: '<path d="M5 12h14M13 6l6 6-6 6"/>',
6
+ upload: '<path d="M12 15V4M7 9l5-5 5 5"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>',
7
+ music: '<path d="M9 18V6l11-2v12"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="17.5" cy="16" r="2.5"/>',
8
+ image: '<rect x="3.5" y="4.5" width="17" height="15" rx="2"/><circle cx="9" cy="10" r="1.75"/><path d="M20.5 15.5l-5-5-9 9"/>',
9
+ video: '<rect x="3" y="6" width="13" height="12" rx="2"/><path d="M16 10.5l5-3v9l-5-3z"/>',
10
+ play: '<path d="M8 5.5v13l10.5-6.5z" fill="currentColor" stroke="none"/>',
11
+ pause: '<path d="M7.5 5.5h3v13h-3zM13.5 5.5h3v13h-3z" fill="currentColor" stroke="none"/>',
12
+ close: '<path d="M6 6l12 12M18 6L6 18"/>',
13
+ check: '<path d="M5 12.5l4.5 4.5L19 7.5"/>',
14
+ download: '<path d="M12 4v11M7 10l5 5 5-5"/><path d="M4 18v1a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1"/>',
15
+ redo: '<path d="M20 11a8 8 0 1 0-2.3 5.6"/><path d="M20 4v7h-7"/>',
16
+ stop: '<rect x="6.5" y="6.5" width="11" height="11" rx="1.5" fill="currentColor" stroke="none"/>',
17
+ history: '<path d="M3.5 12a8.5 8.5 0 1 0 2.5-6"/><path d="M3.5 4.5V9H8"/><path d="M12 8v4.5l3 2"/>',
18
+ caption: '<rect x="3" y="5.5" width="18" height="13" rx="2"/><path d="M10 10.5a2 2 0 1 0 0 3M17 10.5a2 2 0 1 0 0 3"/>',
19
+ warn: '<path d="M12 4l9 16H3z"/><path d="M12 10v4M12 17v.5"/>',
20
+ edit: '<path d="M4 20h4L19 9l-4-4L4 16z"/><path d="M13.5 6.5l4 4"/>',
21
+ plus: '<path d="M12 5v14M5 12h14"/>',
22
+ copy: '<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>',
23
+ } as const;
24
+
25
+ export type IconName = keyof typeof PATHS;
26
+
27
+ export function icon(name: IconName, size = 18): SVGSVGElement {
28
+ const t = document.createElement("template");
29
+ t.innerHTML = `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${PATHS[name]}</svg>`;
30
+ return t.content.firstChild as SVGSVGElement;
31
+ }