@things-factory/figure-service 10.1.278 → 10.1.279

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 (149) hide show
  1. package/package.json +23 -8
  2. package/coverage/clover.xml +0 -6
  3. package/coverage/coverage-final.json +0 -1
  4. package/coverage/lcov-report/base.css +0 -224
  5. package/coverage/lcov-report/block-navigation.js +0 -87
  6. package/coverage/lcov-report/favicon.png +0 -0
  7. package/coverage/lcov-report/index.html +0 -101
  8. package/coverage/lcov-report/prettify.css +0 -1
  9. package/coverage/lcov-report/prettify.js +0 -2
  10. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  11. package/coverage/lcov-report/sorter.js +0 -210
  12. package/coverage/lcov.info +0 -0
  13. package/dist-server/index.js.map +0 -1
  14. package/dist-server/migrations/index.js.map +0 -1
  15. package/dist-server/routers/figure-mesh-router.js.map +0 -1
  16. package/dist-server/routers/figure-package-router.js.map +0 -1
  17. package/dist-server/routers/figure-thumbnail-router.js.map +0 -1
  18. package/dist-server/routes.js.map +0 -1
  19. package/dist-server/service/figure/event-subscriber.js.map +0 -1
  20. package/dist-server/service/figure/figure-ai-scenarios-run.js.map +0 -1
  21. package/dist-server/service/figure/figure-ai-scenarios.js.map +0 -1
  22. package/dist-server/service/figure/figure-categories.js.map +0 -1
  23. package/dist-server/service/figure/figure-context.js.map +0 -1
  24. package/dist-server/service/figure/figure-format.js.map +0 -1
  25. package/dist-server/service/figure/figure-glb.js.map +0 -1
  26. package/dist-server/service/figure/figure-history.js.map +0 -1
  27. package/dist-server/service/figure/figure-llm-provider.js.map +0 -1
  28. package/dist-server/service/figure/figure-mesh-store.js.map +0 -1
  29. package/dist-server/service/figure/figure-mutation.js.map +0 -1
  30. package/dist-server/service/figure/figure-namespace-entity.js.map +0 -1
  31. package/dist-server/service/figure/figure-namespace-resolver.js.map +0 -1
  32. package/dist-server/service/figure/figure-namespace.js.map +0 -1
  33. package/dist-server/service/figure/figure-package-export.js.map +0 -1
  34. package/dist-server/service/figure/figure-proposal-record.js.map +0 -1
  35. package/dist-server/service/figure/figure-proposal.js.map +0 -1
  36. package/dist-server/service/figure/figure-propose-steps.js.map +0 -1
  37. package/dist-server/service/figure/figure-propose-type.js.map +0 -1
  38. package/dist-server/service/figure/figure-public.js.map +0 -1
  39. package/dist-server/service/figure/figure-query.js.map +0 -1
  40. package/dist-server/service/figure/figure-rename.js.map +0 -1
  41. package/dist-server/service/figure/figure-replaced-draft.js.map +0 -1
  42. package/dist-server/service/figure/figure-revert.js.map +0 -1
  43. package/dist-server/service/figure/figure-subject.js.map +0 -1
  44. package/dist-server/service/figure/figure-thumbnail-reader.js.map +0 -1
  45. package/dist-server/service/figure/figure-thumbnail-store.js.map +0 -1
  46. package/dist-server/service/figure/figure-thumbnail-upgrade.js.map +0 -1
  47. package/dist-server/service/figure/figure-tools.js.map +0 -1
  48. package/dist-server/service/figure/figure-type.js.map +0 -1
  49. package/dist-server/service/figure/figure-write.js.map +0 -1
  50. package/dist-server/service/figure/figure.js.map +0 -1
  51. package/dist-server/service/figure/index.js.map +0 -1
  52. package/dist-server/service/figure-recipe/figure-recipe-resolver.js.map +0 -1
  53. package/dist-server/service/figure-recipe/figure-recipe-templates.js.map +0 -1
  54. package/dist-server/service/figure-recipe/figure-recipe-type.js.map +0 -1
  55. package/dist-server/service/figure-recipe/index.js.map +0 -1
  56. package/dist-server/service/index.js.map +0 -1
  57. package/dist-server/tsconfig.tsbuildinfo +0 -1
  58. package/logs/.08636eb59927f12972f6774f5947c8507b3564c2-audit.json +0 -15
  59. package/logs/application-2026-09-14-23.log +0 -0
  60. package/logs/figure-ai-scenarios/2026-11-03T09-31-35-151Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -1167
  61. package/logs/figure-ai-scenarios/2026-11-03T09-39-05-265Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -904
  62. package/logs/figure-ai-scenarios/2026-11-03T09-41-49-107Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -1629
  63. package/logs/figure-ai-scenarios/2026-11-03T09-58-26-681Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4412
  64. package/logs/figure-ai-scenarios/2026-11-03T10-16-46-212Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4513
  65. package/logs/figure-ai-scenarios/2026-11-03T10-21-07-872Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4202
  66. package/logs/figure-ai-scenarios/2026-11-03T10-25-21-721Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -1665
  67. package/logs/figure-ai-scenarios/2026-11-09T01-28-51-664Z-agent_hatiolab_ChatGPT-openai-gpt-5.4-mini.json +0 -4484
  68. package/scripts/build-templates.mts +0 -64
  69. package/scripts/figure-ai-scenarios-agent.cjs +0 -98
  70. package/scripts/rename-figures-to-full-names.mjs +0 -211
  71. package/scripts/templates.test.mts +0 -112
  72. package/server/index.ts +0 -46
  73. package/server/migrations/index.ts +0 -9
  74. package/server/routers/figure-mesh-router.ts +0 -63
  75. package/server/routers/figure-package-router.ts +0 -53
  76. package/server/routers/figure-thumbnail-router.ts +0 -159
  77. package/server/routes.ts +0 -30
  78. package/server/service/figure/catalog-db.test.ts +0 -162
  79. package/server/service/figure/event-subscriber.ts +0 -66
  80. package/server/service/figure/figure-ai-scenarios-run.ts +0 -127
  81. package/server/service/figure/figure-ai-scenarios.live.test.ts +0 -59
  82. package/server/service/figure/figure-ai-scenarios.test.ts +0 -109
  83. package/server/service/figure/figure-ai-scenarios.ts +0 -798
  84. package/server/service/figure/figure-blueprint-query.test.ts +0 -536
  85. package/server/service/figure/figure-catalog-seen-db.test.ts +0 -153
  86. package/server/service/figure/figure-categories.ts +0 -50
  87. package/server/service/figure/figure-category-db.test.ts +0 -127
  88. package/server/service/figure/figure-context.test.ts +0 -402
  89. package/server/service/figure/figure-context.ts +0 -510
  90. package/server/service/figure/figure-deprecation-db.test.ts +0 -218
  91. package/server/service/figure/figure-format.test.ts +0 -423
  92. package/server/service/figure/figure-format.ts +0 -783
  93. package/server/service/figure/figure-glb.test.ts +0 -112
  94. package/server/service/figure/figure-glb.ts +0 -251
  95. package/server/service/figure/figure-history.ts +0 -192
  96. package/server/service/figure/figure-inspect-db.test.ts +0 -131
  97. package/server/service/figure/figure-llm-provider.ts +0 -20
  98. package/server/service/figure/figure-llm-smoke.test.ts +0 -95
  99. package/server/service/figure/figure-mesh-db.test.ts +0 -246
  100. package/server/service/figure/figure-mesh-store.ts +0 -91
  101. package/server/service/figure/figure-mutation.ts +0 -656
  102. package/server/service/figure/figure-namespace-db.test.ts +0 -315
  103. package/server/service/figure/figure-namespace-entity.ts +0 -67
  104. package/server/service/figure/figure-namespace-resolver.ts +0 -54
  105. package/server/service/figure/figure-namespace.ts +0 -156
  106. package/server/service/figure/figure-package-export.ts +0 -136
  107. package/server/service/figure/figure-proposal-db.test.ts +0 -117
  108. package/server/service/figure/figure-proposal-record.ts +0 -38
  109. package/server/service/figure/figure-proposal.ts +0 -41
  110. package/server/service/figure/figure-propose-clips.test.ts +0 -69
  111. package/server/service/figure/figure-propose-steps.test.ts +0 -324
  112. package/server/service/figure/figure-propose-steps.ts +0 -354
  113. package/server/service/figure/figure-propose-type.ts +0 -46
  114. package/server/service/figure/figure-public-db.test.ts +0 -288
  115. package/server/service/figure/figure-public.ts +0 -60
  116. package/server/service/figure/figure-query.ts +0 -511
  117. package/server/service/figure/figure-release-check.test.ts +0 -63
  118. package/server/service/figure/figure-release-record-db.test.ts +0 -153
  119. package/server/service/figure/figure-release-size-db.test.ts +0 -156
  120. package/server/service/figure/figure-rename-db.test.ts +0 -237
  121. package/server/service/figure/figure-rename.test.ts +0 -117
  122. package/server/service/figure/figure-rename.ts +0 -143
  123. package/server/service/figure/figure-replaced-draft.ts +0 -99
  124. package/server/service/figure/figure-revert-db.test.ts +0 -163
  125. package/server/service/figure/figure-revert-race.pg.test.ts +0 -168
  126. package/server/service/figure/figure-revert.ts +0 -186
  127. package/server/service/figure/figure-subject.test.ts +0 -41
  128. package/server/service/figure/figure-subject.ts +0 -21
  129. package/server/service/figure/figure-thumbnail-db.test.ts +0 -279
  130. package/server/service/figure/figure-thumbnail-reader.ts +0 -20
  131. package/server/service/figure/figure-thumbnail-store.ts +0 -111
  132. package/server/service/figure/figure-thumbnail-upgrade.pg.test.ts +0 -93
  133. package/server/service/figure/figure-thumbnail-upgrade.ts +0 -70
  134. package/server/service/figure/figure-tool-doors.test.ts +0 -127
  135. package/server/service/figure/figure-tools-door-db.test.ts +0 -227
  136. package/server/service/figure/figure-tools.test.ts +0 -817
  137. package/server/service/figure/figure-tools.ts +0 -611
  138. package/server/service/figure/figure-type.ts +0 -241
  139. package/server/service/figure/figure-write.test.ts +0 -15
  140. package/server/service/figure/figure-write.ts +0 -131
  141. package/server/service/figure/figure.ts +0 -241
  142. package/server/service/figure/index.ts +0 -13
  143. package/server/service/figure-recipe/figure-recipe-resolver.ts +0 -38
  144. package/server/service/figure-recipe/figure-recipe-templates.test.ts +0 -47
  145. package/server/service/figure-recipe/figure-recipe-templates.ts +0 -70
  146. package/server/service/figure-recipe/figure-recipe-type.ts +0 -31
  147. package/server/service/figure-recipe/index.ts +0 -3
  148. package/server/service/index.ts +0 -34
  149. package/tsconfig.json +0 -14
@@ -1,131 +0,0 @@
1
- /*
2
- * The inspect doors, read against a real row.
3
- *
4
- * `inspectSource` is tested on its own in figure-format.test.ts, and that is where the temporary-type refusal was
5
- * first pinned. It still did not reach the release panel: `inspectFigure` selected only `id` and `source`, so the row's
6
- * `type` arrived as `undefined` and the refusal never ran. The panel enabled 「발행하기」 and the release mutation —
7
- * which loads the whole row — refused on the press (2026-09-24). A test of the function could not see that; this
8
- * one goes through the resolvers and the database.
9
- */
10
- import type { DataSource } from 'typeorm'
11
- import {
12
- addFigureBox,
13
- applyFigureAuthoring,
14
- createFigureAsset,
15
- placeholderType,
16
- serializeFigureAsset
17
- } from '@hatiolab/figure-model'
18
-
19
- const { DataSource: TypeOrmDataSource } = require('typeorm')
20
- const shell = require('@things-factory/shell')
21
- const authBase = require('@things-factory/auth-base')
22
-
23
- let dataSource: DataSource | null = null
24
- let Figure: any
25
- let FigureHistory: any
26
- let FigureQuery: any
27
- let domain: any
28
-
29
- function loadCompiled(modulePath: string): any {
30
- const { existsSync } = require('fs')
31
- const { join } = require('path')
32
- const resolved = join(__dirname, '..', '..', '..', 'dist-server', `${modulePath}.js`)
33
- if (!existsSync(resolved)) {
34
- throw new Error(`figure-service 산출물이 없다: ${resolved}\n yarn workspace @things-factory/figure-service build:server`)
35
- }
36
- return require(resolved)
37
- }
38
-
39
- /** A figure that passes the gate on its own: a box standing on the floor. */
40
- function sound(): string {
41
- let asset = createFigureAsset('Probe')
42
- asset = addFigureBox(asset, { id: 'body', size: { x: 100, y: 100, z: 100 }, position: { x: 0, y: 50, z: 0 } })
43
- asset = applyFigureAuthoring(asset, { kind: 'set-placement', placement: 'floor' })
44
- return serializeFigureAsset(asset)
45
- }
46
-
47
- beforeAll(async () => {
48
- Figure = loadCompiled('service/figure/figure').Figure
49
- FigureHistory = loadCompiled('service/figure/figure-history').FigureHistory
50
- FigureQuery = loadCompiled('service/figure/figure-query').FigureQuery
51
-
52
- dataSource = new TypeOrmDataSource({
53
- type: 'sqlite',
54
- database: ':memory:',
55
- synchronize: true,
56
- dropSchema: true,
57
- namingStrategy: new shell.NamingStrategy(),
58
- entities: [...shell.entities, ...authBase.entities, Figure, FigureHistory],
59
- logging: false
60
- })
61
- await dataSource.initialize()
62
- shell.addDataSource('default', dataSource)
63
- shell.addDataSource('tx', dataSource)
64
- })
65
-
66
- beforeEach(async () => {
67
- await dataSource!.synchronize(true)
68
- domain = await dataSource!.getRepository(shell.Domain).save({ name: 'inspect', subdomain: 'inspect' })
69
- })
70
-
71
- afterAll(async () => {
72
- if (!dataSource) return
73
- shell.removeDataSource('default')
74
- shell.removeDataSource('tx')
75
- await dataSource.destroy()
76
- dataSource = null
77
- })
78
-
79
- const context = () => ({ state: { domain, user: { id: 'u' } } }) as any
80
- const save = (type: string, source = sound()) =>
81
- dataSource!.getRepository(Figure).save({ domain, type, name: 'probe', state: 'draft', source, version: 0 })
82
-
83
- describe('inspectFigure — the release panel', () => {
84
- it('refuses a figure still under its temporary type — the type comes from the row', async () => {
85
- const figure = await save(placeholderType())
86
-
87
- const inspection = await new FigureQuery().inspectFigure(figure.id, context())
88
-
89
- expect(inspection.blocked).toBe(true)
90
- expect(inspection.findings.map((f: any) => f.code)).toContain('type-is-placeholder')
91
- })
92
-
93
- it('lets the same figure through once it is named', async () => {
94
- const figure = await save('ROLLER_CONVEYOR')
95
-
96
- expect((await new FigureQuery().inspectFigure(figure.id, context())).blocked).toBe(false)
97
- })
98
- })
99
-
100
- describe('inspectFigureDraft — the verdict while editing', () => {
101
- it('judges the unsaved source, not the stored one, and still reads the row type', async () => {
102
- const figure = await save(placeholderType())
103
- let edited = createFigureAsset('Probe')
104
- edited = addFigureBox(edited, { id: 'body', size: { x: 100, y: 100, z: 100 }, position: { x: 0, y: 150, z: 0 } })
105
- /* Its bottom named as the face it is mounted on, 100 mm above the floor: a finding the stored one does not have. */
106
- edited = applyFigureAuthoring(edited, { kind: 'set-mounting-face', part: 'body', face: 'bottom' })
107
-
108
- const inspection = await new FigureQuery().inspectFigureDraft(serializeFigureAsset(edited), context(), figure.id)
109
- const codes = inspection.findings.map((f: any) => f.code)
110
-
111
- expect(codes).toContain('parts-off-placement-face')
112
- expect(codes).toContain('type-is-placeholder')
113
- })
114
-
115
- it('a figure never saved has no row type to refuse', async () => {
116
- const inspection = await new FigureQuery().inspectFigureDraft(sound(), context())
117
-
118
- expect(inspection.blocked).toBe(false)
119
- })
120
-
121
- it('declares the same permission as inspectFigure', () => {
122
- const { readFileSync } = require('fs')
123
- const { join } = require('path')
124
- const source = readFileSync(join(__dirname, 'figure-query.ts'), 'utf-8')
125
- const at = source.indexOf('async inspectFigureDraft')
126
- const preceding = source.slice(0, at)
127
- const declaration = preceding.slice(preceding.lastIndexOf("@Directive('@privilege("))
128
-
129
- expect(declaration).toContain('category: "figure", privilege: "query"')
130
- })
131
- })
@@ -1,20 +0,0 @@
1
- /**
2
- * Which provider a live figure-AI run asks (the smoke test, the scenarios): the one `FIGURE_LLM_PROVIDER` names, or the
3
- * first whose key is set. Its model is `FIGURE_LLM_MODEL`, or the adapter's default. Undefined: no key, nothing runs.
4
- */
5
- export type FigureLLMProvider = 'anthropic' | 'gemini' | 'openai'
6
-
7
- export function figureLLMProvider(env: NodeJS.ProcessEnv = process.env): { provider: FigureLLMProvider; apiKey: string; model?: string } | undefined {
8
- const requested = env.FIGURE_LLM_PROVIDER as FigureLLMProvider | undefined
9
- const candidates: Array<{ provider: FigureLLMProvider; keys: string[] }> = [
10
- { provider: 'anthropic', keys: ['ANTHROPIC_API_KEY'] },
11
- { provider: 'gemini', keys: ['GEMINI_API_KEY', 'GOOGLE_API_KEY'] },
12
- { provider: 'openai', keys: ['OPENAI_API_KEY'] }
13
- ]
14
- const usable = requested ? candidates.filter(candidate => candidate.provider === requested) : candidates
15
- for (const candidate of usable) {
16
- const apiKey = candidate.keys.map(key => env[key]).find(Boolean)
17
- if (apiKey) return { provider: candidate.provider, apiKey, ...(env.FIGURE_LLM_MODEL ? { model: env.FIGURE_LLM_MODEL } : {}) }
18
- }
19
- return undefined
20
- }
@@ -1,95 +0,0 @@
1
- /**
2
- * 실제 LLM Figure 후보 생성 smoke test (기본 비활성).
3
- *
4
- * 결정적 시험은 프롬프트·도구·검사 배선을 고정하지만, 실제 모델이 명령 목록(ADR-0094)을 써서 게이트를
5
- * 지나는 피규어를 만드는지는 대신할 수 없다. 이 시험은 `RUN_FIGURE_LLM_SMOKE=1`과 공급자 API 키가 모두 있을 때만 실행한다.
6
- * DB·GraphQL·Figure 저장을 건드리지 않고 후보 생성 함수만 호출하므로, 외부 영향은 API 비용뿐이다.
7
- *
8
- * 실행:
9
- * RUN_FIGURE_LLM_SMOKE=1 OPENAI_API_KEY=... yarn test:figure-llm-smoke
10
- * 선택: FIGURE_LLM_PROVIDER=anthropic|gemini|openai, FIGURE_LLM_MODEL=<model id>
11
- */
12
- import { createAIClient, type AIClient } from '@things-factory/ai-client-base'
13
-
14
- import { inspectFigureAsset } from '@hatiolab/figure-model'
15
-
16
- import { mixerDraft, portRevisionMisses } from './figure-ai-scenarios'
17
- import { figureLLMProvider } from './figure-llm-provider'
18
- import { judgeFigureAnswer, proposeFigureSteps } from './figure-propose-steps'
19
-
20
- // Provider modules register themselves on import. Keep this separate from the deterministic tests.
21
- import '@things-factory/ai-client-base'
22
-
23
- /* The check above, held to answers whose verdict is known - so it is seen to fail a wrong revision without a provider. */
24
- describe('the revision check of the smoke test', () => {
25
- const draft = mixerDraft()
26
- const answer = (steps: unknown[]) => {
27
- const judged = judgeFigureAnswer(draft, { steps }, true)
28
- if (!judged.source) throw new Error(judged.reasons.join('\n'))
29
- return judged.source
30
- }
31
- const accent = { kind: 'set-material', target: 'port', material: { token: 'palette.accent' }, palette: { 'palette.accent': '#d08a2c' } }
32
-
33
- it('passes the revision asked for', () => {
34
- expect(portRevisionMisses(draft, answer([{ kind: 'set-section', part: 'port', across: { x: 160 } }, accent]))).toEqual([])
35
- })
36
-
37
- it('fails a revision that left the width, or widened the body instead, or kept the colour', () => {
38
- expect(portRevisionMisses(draft, answer([accent]))).toEqual(['port width 80, asked 160'])
39
- expect(portRevisionMisses(draft, answer([{ kind: 'set-section', part: 'port', across: { x: 160 } }, { kind: 'set-section', part: 'body', across: { x: 320 } }, accent]))).toEqual(
40
- expect.arrayContaining(['body x changed to 320'])
41
- )
42
- expect(portRevisionMisses(draft, answer([{ kind: 'set-section', part: 'port', across: { x: 160 } }]))).toEqual([`port colour still ${draft.palette!['palette.primary']}`])
43
- })
44
-
45
- /* A new token is not a new colour: an alias of the colour the port already had changes nothing on screen. */
46
- it('fails a new token that names the colour the port already had', () => {
47
- const same = draft.palette!['palette.primary']!
48
- const alias = { kind: 'set-material', target: 'port', material: { token: 'palette.accent' }, palette: { 'palette.accent': same.toUpperCase() } }
49
- expect(portRevisionMisses(draft, answer([{ kind: 'set-section', part: 'port', across: { x: 160 } }, alias]))).toEqual([`port colour still ${same}`])
50
- })
51
- })
52
-
53
- const picked = process.env.RUN_FIGURE_LLM_SMOKE === '1' ? figureLLMProvider() : undefined
54
- const describeIf = picked ? describe : describe.skip
55
-
56
- describeIf('Figure 실제 LLM smoke', () => {
57
- let client: AIClient
58
- beforeAll(() => {
59
- client = createAIClient(picked!)
60
- // eslint-disable-next-line no-console
61
- console.log(`[figure-llm-smoke] provider=${picked!.provider} model=${process.env.FIGURE_LLM_MODEL ?? '(adapter default)'}`)
62
- })
63
-
64
-
65
- test(
66
- '새 Figure 는 게이트를 지나는 명령 목록으로 온다',
67
- async () => {
68
- const result = await proposeFigureSteps({
69
- client,
70
- prompt: 'two cylindrical rollers inside a simple rectangular press frame; make the rollers visually distinct',
71
- name: 'Roll press'
72
- })
73
-
74
- expect(result.steps.length).toBeGreaterThan(0)
75
- expect(inspectFigureAsset(result.source).violations).toEqual([])
76
- expect(result.cost.triangles).toBeGreaterThan(0)
77
- // eslint-disable-next-line no-console
78
- console.log(`[figure-llm-smoke] new: ${result.steps.length} steps, ${result.attempts} attempt(s)`)
79
- },
80
- 120_000
81
- )
82
-
83
- test(
84
- '고치는 제안은 요청한 것만 바꾼다 — 포트 폭 두 배, 새 색, 몸통은 그대로',
85
- async () => {
86
- const draft = mixerDraft()
87
- const result = await proposeFigureSteps({ client, prompt: 'make the port twice as wide and give it an accent colour', base: draft })
88
-
89
- expect(portRevisionMisses(draft, result.source)).toEqual([])
90
- // eslint-disable-next-line no-console
91
- console.log(`[figure-llm-smoke] revise: ${JSON.stringify(result.steps)}`)
92
- },
93
- 120_000
94
- )
95
- })
@@ -1,246 +0,0 @@
1
- /**
2
- * A mesh part's file on the authoring server (ADR-0129 decisions 5, 6 and 8), on sqlite through the real doors: kept
3
- * once per content per domain after it is read, refused by name when a board cannot draw it, required by every save
4
- * that names it, served behind the figure permission from this domain or its parent, and carried by a package.
5
- * The files go to a map instead of the configured storage.
6
- */
7
- import type { DataSource } from 'typeorm'
8
-
9
- const { DataSource: TypeOrmDataSource } = require('typeorm')
10
- const shell = require('@things-factory/shell')
11
- const authBase = require('@things-factory/auth-base')
12
- const attachmentBase = require('@things-factory/attachment-base')
13
- const settingBase = require('@things-factory/setting-base')
14
- const JSZip = require('jszip')
15
- const { createFigureAsset, addFigurePrimitive, serializeFigureAsset, readFigurePackage } = require('@hatiolab/figure-model')
16
-
17
- let FigureNamespace: any
18
- let dataSource: DataSource | null = null
19
- let Figure: any, FigureHistory: any, FigureReplacedDraft: any, FigureMutation: any
20
- let keepMesh: any, useThumbnailFiles: any, sha256Of: any, sendFigureMesh: any, figurePackageOf: any
21
-
22
- function loadCompiled(modulePath: string): any {
23
- const { existsSync } = require('fs')
24
- const { join } = require('path')
25
- const resolved = join(__dirname, '..', '..', '..', 'dist-server', `${modulePath}.js`)
26
- if (!existsSync(resolved))
27
- throw new Error(`figure-service 산출물이 없다: ${resolved}\n먼저 빌드할 것:\n yarn workspace @things-factory/figure-service build:server`)
28
- return require(resolved)
29
- }
30
-
31
- function mapFiles() {
32
- const kept = new Map<string, Buffer>()
33
- let n = 0
34
- return {
35
- kept,
36
- async put(bytes: Buffer, _mimetype: string, name: string) {
37
- const id = `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`
38
- const path = `${id}.${name.split('.').pop()}`
39
- kept.set(path, bytes)
40
- return { id, path, size: bytes.length }
41
- },
42
- async send(koa: any, path: string) {
43
- koa.body = kept.get(path)
44
- },
45
- async read(path: string) {
46
- return kept.get(path)!
47
- }
48
- }
49
- }
50
-
51
- /** A GLB of one box, 2 m along X: its JSON, padded, and an empty binary chunk. `tag` makes another file of it. */
52
- function glb(tag = 'crane', over: Record<string, unknown> = {}): Buffer {
53
- let text = JSON.stringify({
54
- asset: { version: '2.0', generator: tag },
55
- scenes: [{ nodes: [0] }],
56
- nodes: [{ name: 'body', mesh: 0 }],
57
- meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],
58
- accessors: [{ count: 24, min: [-1, 0, -0.2], max: [1, 0.5, 0.2] }, { count: 36 }],
59
- buffers: [{ byteLength: 0 }],
60
- ...over
61
- })
62
- while (text.length % 4) text += ' '
63
- const body = Buffer.from(text)
64
- const out = Buffer.alloc(28 + body.length)
65
- out.writeUInt32LE(0x46546c67, 0)
66
- out.writeUInt32LE(2, 4)
67
- out.writeUInt32LE(out.length, 8)
68
- out.writeUInt32LE(body.length, 12)
69
- out.writeUInt32LE(0x4e4f534a, 16)
70
- body.copy(out, 20)
71
- out.writeUInt32LE(0, 20 + body.length)
72
- out.writeUInt32LE(0x004e4942, 24 + body.length)
73
- return out
74
- }
75
-
76
- const sourceWith = (hash: string) =>
77
- serializeFigureAsset(
78
- addFigurePrimitive(createFigureAsset('Crane'), {
79
- id: 'body',
80
- kind: 'mesh',
81
- dimensions: { size: 2000 },
82
- mesh: { asset: hash, format: 'glb', unit: 'm', bounds: { min: { x: -1000, y: 0, z: -200 }, max: { x: 1000, y: 500, z: 200 } }, triangles: 12, primitives: 1 },
83
- position: { x: 0, y: 0, z: 0 }
84
- })
85
- )
86
-
87
- let files: ReturnType<typeof mapFiles>
88
- let restore: any
89
- beforeAll(async () => {
90
- Figure = loadCompiled('service/figure/figure').Figure
91
- FigureNamespace = loadCompiled('service/figure/figure-namespace-entity').FigureNamespace
92
- FigureHistory = loadCompiled('service/figure/figure-history').FigureHistory
93
- FigureReplacedDraft = loadCompiled('service/figure/figure-replaced-draft').FigureReplacedDraft
94
- FigureMutation = loadCompiled('service/figure/figure-mutation').FigureMutation
95
- ;({ keepMesh } = loadCompiled('service/figure/figure-mesh-store'))
96
- ;({ useThumbnailFiles, sha256Of } = loadCompiled('service/figure/figure-thumbnail-store'))
97
- ;({ sendFigureMesh } = loadCompiled('routers/figure-mesh-router'))
98
- ;({ figurePackageOf } = loadCompiled('service/figure/figure-package-export'))
99
- dataSource = new TypeOrmDataSource({
100
- type: 'sqlite',
101
- database: ':memory:',
102
- synchronize: true,
103
- dropSchema: true,
104
- namingStrategy: new shell.NamingStrategy(),
105
- entities: [...shell.entities, ...authBase.entities, ...attachmentBase.entities, ...settingBase.entities, Figure, FigureHistory, FigureReplacedDraft, FigureNamespace],
106
- logging: false
107
- })
108
- await dataSource.initialize()
109
- shell.addDataSource('default', dataSource)
110
- shell.addDataSource('tx', dataSource)
111
- })
112
-
113
- afterAll(async () => {
114
- shell.removeDataSource('default')
115
- shell.removeDataSource('tx')
116
- await dataSource?.destroy()
117
- dataSource = null
118
- })
119
-
120
- beforeEach(() => {
121
- files = mapFiles()
122
- restore = useThumbnailFiles(files)
123
- })
124
- afterEach(() => useThumbnailFiles(restore))
125
-
126
- let seq = 0
127
- const newDomain = async (parent?: any) => {
128
- const name = `mesh-${++seq}`
129
- const saved = await dataSource!.getRepository(shell.Domain).save({ name, subdomain: name, ...(parent ? { parent } : {}) })
130
- const domain = await dataSource!.getRepository(shell.Domain).findOneOrFail({ where: { id: saved.id } })
131
- await dataSource!.getRepository(FigureNamespace).save({ domain, name: domain.subdomain, state: 'active', isDefault: true })
132
- return domain
133
- }
134
- const meshRows = (domainId: string) => dataSource!.getRepository(attachmentBase.Attachment).find({ where: { refType: 'figure-mesh', domain: { id: domainId } } })
135
- const upload = (domain: any, bytes: Buffer) =>
136
- dataSource!.transaction(tx =>
137
- new FigureMutation().uploadFigureMesh(Promise.resolve({ createReadStream: () => require('stream').Readable.from([bytes]) }), { state: { domain, user: undefined, tx } })
138
- )
139
- const save = (domain: any, source: string) =>
140
- dataSource!.transaction(tx =>
141
- new FigureMutation().saveFigure(source, { state: { domain, user: undefined, tx } }, undefined, undefined, require('crypto').randomUUID())
142
- )
143
- const koa = () => ({ status: 404, type: '', body: undefined as any, headers: {} as Record<string, string>, set(k: string, v: string) { this.headers[k] = v }, fresh: false })
144
-
145
- describe('keeping a GLB', () => {
146
- it('reads it, keeps it once per content in a domain, and answers its hash and what it holds', async () => {
147
- const domain = await newDomain()
148
- const first = await upload(domain, glb())
149
- const again = await upload(domain, glb())
150
- expect(first.hash).toBe(sha256Of(glb()))
151
- expect(again.hash).toBe(first.hash)
152
- expect(first.summary).toMatchObject({ triangles: 12, primitives: 1, bounds: { min: { x: -1000, y: 0, z: -200 }, max: { x: 1000, y: 500, z: 200 } } })
153
- expect(await meshRows(domain.id)).toHaveLength(1)
154
- expect(files.kept.size).toBe(1)
155
- })
156
-
157
- it('refuses a file a board cannot draw, by its reason, and keeps nothing', async () => {
158
- const domain = await newDomain()
159
- await expect(upload(domain, glb('draco', { extensionsRequired: ['KHR_draco_mesh_compression'] }))).rejects.toMatchObject({
160
- code: 'figure-mesh-extension',
161
- params: { extensions: 'KHR_draco_mesh_compression' }
162
- })
163
- await expect(upload(domain, Buffer.from('not a model'))).rejects.toMatchObject({ code: 'figure-mesh-not-glb' })
164
- expect(await meshRows(domain.id)).toHaveLength(0)
165
- expect(files.kept.size).toBe(0)
166
- })
167
- })
168
-
169
- describe('a save names only files the domain holds', () => {
170
- it('refuses a figure whose mesh file was never kept here, and saves it once it is', async () => {
171
- const domain = await newDomain()
172
- const hash = sha256Of(glb())
173
- await expect(save(domain, sourceWith(hash))).rejects.toMatchObject({ code: 'figure-mesh-missing' })
174
- expect(await dataSource!.getRepository(Figure).count({ where: { domain: { id: domain.id } } })).toBe(0)
175
- await upload(domain, glb())
176
- const saved = await save(domain, sourceWith(hash))
177
- expect(saved.id).toBeTruthy()
178
- })
179
-
180
- it("a child domain may name its parent's files, and not another domain's", async () => {
181
- const parent = await newDomain()
182
- const child = await newDomain(parent)
183
- const stranger = await newDomain()
184
- const hash = (await upload(parent, glb())).hash
185
- await expect(save(child, sourceWith(hash))).resolves.toBeTruthy()
186
- await expect(save(stranger, sourceWith(hash))).rejects.toMatchObject({ code: 'figure-mesh-missing' })
187
- })
188
- })
189
-
190
- describe('serving a mesh file', () => {
191
- it("serves it from this domain or its parent, with its hash as its tag, and never another domain's", async () => {
192
- const parent = await newDomain()
193
- const child = await newDomain(parent)
194
- const stranger = await newDomain()
195
- const hash = (await upload(parent, glb())).hash
196
- const asked = async (domain: any) => {
197
- const k = koa()
198
- await sendFigureMesh(k, async () => {}, hash, domain, files)
199
- return k
200
- }
201
- const ok = await asked(child)
202
- expect(ok.status).toBe(200)
203
- expect(ok.type).toBe('model/gltf-binary')
204
- expect(ok.headers.ETag).toBe(`"${hash}"`)
205
- expect(Buffer.compare(ok.body, glb())).toBe(0)
206
- expect((await asked(stranger)).status).toBe(404)
207
- const k = koa()
208
- await sendFigureMesh(k, async () => {}, '../etc/passwd', child, files)
209
- expect(k.status).toBe(404)
210
- })
211
- })
212
-
213
- describe('a package carries the files its releases draw from', () => {
214
- const release = async (domain: any, hash: string) => {
215
- const figure = await save(domain, sourceWith(hash))
216
- await dataSource!.getRepository(Figure).update({ id: figure.id }, { namespace: 'system', type: 'crane' })
217
- await dataSource!.getRepository(FigureHistory).save({
218
- originalId: figure.id, version: 1, type: 'crane', name: 'Crane', source: sourceWith(hash), state: 'released', domain
219
- })
220
- }
221
- const unpack = async (bytes: Buffer) => {
222
- const zip = await JSZip.loadAsync(bytes)
223
- const out = new Map<string, Uint8Array>()
224
- for (const name of Object.keys(zip.files)) out.set(name, await zip.files[name].async('uint8array'))
225
- return readFigurePackage(out, (b: Uint8Array) => sha256Of(Buffer.from(b)))
226
- }
227
-
228
- it('writes the GLB as a mesh blob a board reads back whole', async () => {
229
- const domain = await newDomain()
230
- const hash = (await upload(domain, glb())).hash
231
- await release(domain, hash)
232
- const packed = await figurePackageOf({ refs: ['system/crane@1'], domain, exportedBy: null, sourceUrl: 'https://figure.example', files })
233
- const read = await unpack(packed.bytes)
234
- expect(read.problems).toEqual([])
235
- expect(read.refused).toEqual([])
236
- expect(read.blobs.get(hash)?.contentType).toBe('model/gltf-binary')
237
- })
238
-
239
- it('refuses a package whose release draws from a file that is gone', async () => {
240
- const domain = await newDomain()
241
- const hash = (await upload(domain, glb())).hash
242
- await release(domain, hash)
243
- files.kept.clear()
244
- await expect(figurePackageOf({ refs: ['system/crane@1'], domain, exportedBy: null, sourceUrl: 'u', files })).rejects.toMatchObject({ code: 'figure-package-mesh-missing' })
245
- })
246
- })
@@ -1,91 +0,0 @@
1
- import { In } from 'typeorm'
2
-
3
- import { Attachment } from '@things-factory/attachment-base'
4
- import { figureFilesOf } from '@hatiolab/figure-model'
5
- import { Refusal } from '@things-factory/shell'
6
-
7
- import { GLB_MIMETYPE, readGlb, type GlbSummary } from './figure-glb.js'
8
- import { sha256Of, thumbnailFiles, type ThumbnailFiles } from './figure-thumbnail-store.js'
9
-
10
- /*
11
- * A mesh part's file (ADR-0129 decision 6), kept as a thumbnail is (ADR-0104 decision 6): by attachment-base's storage,
12
- * one attachment per (domain, content), refType `figure-mesh`, refBy the SHA-256 of the bytes. A figure's source names
13
- * it by that hash and nothing else; the bytes are served only through `/figure-mesh/:hash`, behind the figure query
14
- * permission.
15
- *
16
- * A file is read before it is kept (`readGlb`): one a board cannot draw is refused by name, never kept under a hash.
17
- * The file is written before the row that names it, as a picture is: a file cannot be rolled back.
18
- */
19
-
20
- export const MESH_REF_TYPE = 'figure-mesh'
21
-
22
- type Tx = { getRepository: (target: any) => any }
23
-
24
- /** The attachment holding this file in one of these domains -- the asker's first, then its parent's -- or undefined. */
25
- export async function meshAttachmentOf(tx: Tx, domainIds: readonly string[], hash: string): Promise<Attachment | undefined> {
26
- const found: Attachment[] = await tx.getRepository(Attachment).find({
27
- where: { domain: { id: In([...domainIds]) }, refType: MESH_REF_TYPE, refBy: hash },
28
- relations: { domain: true }
29
- })
30
- return domainIds.map(id => found.find(a => a.domain?.id === id)).find(Boolean)
31
- }
32
-
33
- /** Keeps a GLB and gives its hash and what it holds. Refused, by the reader's code, when a board cannot draw it. */
34
- export async function keepMesh(
35
- tx: Tx,
36
- domain: { id: string },
37
- user: unknown,
38
- bytes: Buffer,
39
- files: ThumbnailFiles = thumbnailFiles()
40
- ): Promise<{ hash: string; summary: GlbSummary }> {
41
- const summary = readGlb(bytes)
42
- const hash = sha256Of(bytes)
43
- if (await meshAttachmentOf(tx, [domain.id], hash)) return { hash, summary }
44
- const name = `${hash}.glb`
45
- /* The file first: it cannot be rolled back. The row that names it comes after, in the caller's transaction. */
46
- const put = await files.put(bytes, GLB_MIMETYPE, name, { state: { domain, user, tx } })
47
- await tx.getRepository(Attachment).save({
48
- domain,
49
- creator: user,
50
- updater: user,
51
- id: put.id,
52
- name,
53
- mimetype: GLB_MIMETYPE,
54
- encoding: 'binary',
55
- refType: MESH_REF_TYPE,
56
- refBy: hash,
57
- category: 'model',
58
- size: String(put.size),
59
- path: put.path,
60
- ...(put.contents ? { contents: put.contents } : {})
61
- })
62
- return { hash, summary }
63
- }
64
-
65
- /** What a kept file holds, read again from its bytes: the modeller asks when it reopens a figure. */
66
- export async function meshSummaryOf(
67
- tx: Tx,
68
- domain: { id: string; parentId?: string | null },
69
- hash: string,
70
- files: ThumbnailFiles = thumbnailFiles()
71
- ): Promise<GlbSummary | undefined> {
72
- const kept = await meshAttachmentOf(tx, [domain.id, domain.parentId].filter(Boolean) as string[], hash)
73
- return kept ? readGlb(await files.read(kept.path!)) : undefined
74
- }
75
-
76
- /**
77
- * A source may name only files this domain holds (or its parent, whose figures it reads): a figure that names a file
78
- * nobody kept cannot be drawn anywhere, and is refused when it is saved, not when a board finds out.
79
- */
80
- export async function requireMeshFiles(tx: Tx, domain: { id: string; parentId?: string | null }, source: string): Promise<void> {
81
- let parsed: unknown
82
- try {
83
- parsed = JSON.parse(source)
84
- } catch {
85
- return /* the format check refuses it, with its own words */
86
- }
87
- const ids = [domain.id, domain.parentId].filter(Boolean) as string[]
88
- for (const hash of figureFilesOf(parsed))
89
- if (!(await meshAttachmentOf(tx, ids, hash)))
90
- throw new Refusal('figure-mesh-missing', { hash }, 'the figure names a mesh file this domain does not hold: {hash}. Upload the file again.')
91
- }