@things-factory/figure-service 10.1.277 → 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 (128) hide show
  1. package/package.json +23 -8
  2. package/dist-server/index.js.map +0 -1
  3. package/dist-server/migrations/index.js.map +0 -1
  4. package/dist-server/routers/figure-mesh-router.js.map +0 -1
  5. package/dist-server/routers/figure-package-router.js.map +0 -1
  6. package/dist-server/routers/figure-thumbnail-router.js.map +0 -1
  7. package/dist-server/routes.js.map +0 -1
  8. package/dist-server/service/figure/event-subscriber.js.map +0 -1
  9. package/dist-server/service/figure/figure-ai-scenarios-run.js.map +0 -1
  10. package/dist-server/service/figure/figure-ai-scenarios.js.map +0 -1
  11. package/dist-server/service/figure/figure-categories.js.map +0 -1
  12. package/dist-server/service/figure/figure-context.js.map +0 -1
  13. package/dist-server/service/figure/figure-format.js.map +0 -1
  14. package/dist-server/service/figure/figure-glb.js.map +0 -1
  15. package/dist-server/service/figure/figure-history.js.map +0 -1
  16. package/dist-server/service/figure/figure-llm-provider.js.map +0 -1
  17. package/dist-server/service/figure/figure-mesh-store.js.map +0 -1
  18. package/dist-server/service/figure/figure-mutation.js.map +0 -1
  19. package/dist-server/service/figure/figure-namespace-entity.js.map +0 -1
  20. package/dist-server/service/figure/figure-namespace-resolver.js.map +0 -1
  21. package/dist-server/service/figure/figure-namespace.js.map +0 -1
  22. package/dist-server/service/figure/figure-package-export.js.map +0 -1
  23. package/dist-server/service/figure/figure-proposal-record.js.map +0 -1
  24. package/dist-server/service/figure/figure-proposal.js.map +0 -1
  25. package/dist-server/service/figure/figure-propose-steps.js.map +0 -1
  26. package/dist-server/service/figure/figure-propose-type.js.map +0 -1
  27. package/dist-server/service/figure/figure-public.js.map +0 -1
  28. package/dist-server/service/figure/figure-query.js.map +0 -1
  29. package/dist-server/service/figure/figure-rename.js.map +0 -1
  30. package/dist-server/service/figure/figure-replaced-draft.js.map +0 -1
  31. package/dist-server/service/figure/figure-revert.js.map +0 -1
  32. package/dist-server/service/figure/figure-subject.js.map +0 -1
  33. package/dist-server/service/figure/figure-thumbnail-reader.js.map +0 -1
  34. package/dist-server/service/figure/figure-thumbnail-store.js.map +0 -1
  35. package/dist-server/service/figure/figure-thumbnail-upgrade.js.map +0 -1
  36. package/dist-server/service/figure/figure-tools.js.map +0 -1
  37. package/dist-server/service/figure/figure-type.js.map +0 -1
  38. package/dist-server/service/figure/figure-write.js.map +0 -1
  39. package/dist-server/service/figure/figure.js.map +0 -1
  40. package/dist-server/service/figure/index.js.map +0 -1
  41. package/dist-server/service/figure-recipe/figure-recipe-resolver.js.map +0 -1
  42. package/dist-server/service/figure-recipe/figure-recipe-templates.js.map +0 -1
  43. package/dist-server/service/figure-recipe/figure-recipe-type.js.map +0 -1
  44. package/dist-server/service/figure-recipe/index.js.map +0 -1
  45. package/dist-server/service/index.js.map +0 -1
  46. package/dist-server/tsconfig.tsbuildinfo +0 -1
  47. package/scripts/build-templates.mts +0 -64
  48. package/scripts/figure-ai-scenarios-agent.cjs +0 -98
  49. package/scripts/rename-figures-to-full-names.mjs +0 -211
  50. package/scripts/templates.test.mts +0 -112
  51. package/server/index.ts +0 -46
  52. package/server/migrations/index.ts +0 -9
  53. package/server/routers/figure-mesh-router.ts +0 -63
  54. package/server/routers/figure-package-router.ts +0 -53
  55. package/server/routers/figure-thumbnail-router.ts +0 -159
  56. package/server/routes.ts +0 -30
  57. package/server/service/figure/catalog-db.test.ts +0 -162
  58. package/server/service/figure/event-subscriber.ts +0 -66
  59. package/server/service/figure/figure-ai-scenarios-run.ts +0 -127
  60. package/server/service/figure/figure-ai-scenarios.live.test.ts +0 -59
  61. package/server/service/figure/figure-ai-scenarios.test.ts +0 -109
  62. package/server/service/figure/figure-ai-scenarios.ts +0 -798
  63. package/server/service/figure/figure-blueprint-query.test.ts +0 -536
  64. package/server/service/figure/figure-catalog-seen-db.test.ts +0 -153
  65. package/server/service/figure/figure-categories.ts +0 -50
  66. package/server/service/figure/figure-category-db.test.ts +0 -127
  67. package/server/service/figure/figure-context.test.ts +0 -402
  68. package/server/service/figure/figure-context.ts +0 -510
  69. package/server/service/figure/figure-deprecation-db.test.ts +0 -218
  70. package/server/service/figure/figure-format.test.ts +0 -423
  71. package/server/service/figure/figure-format.ts +0 -783
  72. package/server/service/figure/figure-glb.test.ts +0 -112
  73. package/server/service/figure/figure-glb.ts +0 -251
  74. package/server/service/figure/figure-history.ts +0 -192
  75. package/server/service/figure/figure-inspect-db.test.ts +0 -131
  76. package/server/service/figure/figure-llm-provider.ts +0 -20
  77. package/server/service/figure/figure-llm-smoke.test.ts +0 -95
  78. package/server/service/figure/figure-mesh-db.test.ts +0 -246
  79. package/server/service/figure/figure-mesh-store.ts +0 -91
  80. package/server/service/figure/figure-mutation.ts +0 -656
  81. package/server/service/figure/figure-namespace-db.test.ts +0 -315
  82. package/server/service/figure/figure-namespace-entity.ts +0 -67
  83. package/server/service/figure/figure-namespace-resolver.ts +0 -54
  84. package/server/service/figure/figure-namespace.ts +0 -156
  85. package/server/service/figure/figure-package-export.ts +0 -136
  86. package/server/service/figure/figure-proposal-db.test.ts +0 -117
  87. package/server/service/figure/figure-proposal-record.ts +0 -38
  88. package/server/service/figure/figure-proposal.ts +0 -41
  89. package/server/service/figure/figure-propose-clips.test.ts +0 -69
  90. package/server/service/figure/figure-propose-steps.test.ts +0 -324
  91. package/server/service/figure/figure-propose-steps.ts +0 -354
  92. package/server/service/figure/figure-propose-type.ts +0 -46
  93. package/server/service/figure/figure-public-db.test.ts +0 -288
  94. package/server/service/figure/figure-public.ts +0 -60
  95. package/server/service/figure/figure-query.ts +0 -511
  96. package/server/service/figure/figure-release-check.test.ts +0 -63
  97. package/server/service/figure/figure-release-record-db.test.ts +0 -153
  98. package/server/service/figure/figure-release-size-db.test.ts +0 -156
  99. package/server/service/figure/figure-rename-db.test.ts +0 -237
  100. package/server/service/figure/figure-rename.test.ts +0 -117
  101. package/server/service/figure/figure-rename.ts +0 -143
  102. package/server/service/figure/figure-replaced-draft.ts +0 -99
  103. package/server/service/figure/figure-revert-db.test.ts +0 -163
  104. package/server/service/figure/figure-revert-race.pg.test.ts +0 -168
  105. package/server/service/figure/figure-revert.ts +0 -186
  106. package/server/service/figure/figure-subject.test.ts +0 -41
  107. package/server/service/figure/figure-subject.ts +0 -21
  108. package/server/service/figure/figure-thumbnail-db.test.ts +0 -279
  109. package/server/service/figure/figure-thumbnail-reader.ts +0 -20
  110. package/server/service/figure/figure-thumbnail-store.ts +0 -111
  111. package/server/service/figure/figure-thumbnail-upgrade.pg.test.ts +0 -93
  112. package/server/service/figure/figure-thumbnail-upgrade.ts +0 -70
  113. package/server/service/figure/figure-tool-doors.test.ts +0 -127
  114. package/server/service/figure/figure-tools-door-db.test.ts +0 -227
  115. package/server/service/figure/figure-tools.test.ts +0 -817
  116. package/server/service/figure/figure-tools.ts +0 -611
  117. package/server/service/figure/figure-type.ts +0 -241
  118. package/server/service/figure/figure-write.test.ts +0 -15
  119. package/server/service/figure/figure-write.ts +0 -131
  120. package/server/service/figure/figure.ts +0 -241
  121. package/server/service/figure/index.ts +0 -13
  122. package/server/service/figure-recipe/figure-recipe-resolver.ts +0 -38
  123. package/server/service/figure-recipe/figure-recipe-templates.test.ts +0 -47
  124. package/server/service/figure-recipe/figure-recipe-templates.ts +0 -70
  125. package/server/service/figure-recipe/figure-recipe-type.ts +0 -31
  126. package/server/service/figure-recipe/index.ts +0 -3
  127. package/server/service/index.ts +0 -34
  128. package/tsconfig.json +0 -14
@@ -1,186 +0,0 @@
1
- import { createHash } from 'crypto'
2
- import { In, type EntityManager } from 'typeorm'
3
- import { GraphQLError } from 'graphql'
4
-
5
- import { Figure } from './figure.js'
6
- import { FigureHistory } from './figure-history.js'
7
- import { FigureReplacedDraft } from './figure-replaced-draft.js'
8
- import { draftSourceOfRelease, parseSource } from './figure-format.js'
9
- import { sourceConflict } from './figure-write.js'
10
-
11
- /*
12
- * Reverting a figure to a released version, keeping the draft it writes over (ADR-0097 §5.6, designer 2026-09-27;
13
- * chief architect's ruling on the storage the same day).
14
- *
15
- * - One transaction: the draft is kept, then the figure is written over -- conditional on it being what the reverter
16
- * saw (`expectedSource`). If either fails, neither stays: the caller's transaction is rolled back.
17
- * - One request, one revert: `requestId` is unique in the domain. A retry -- the answer lost -- finds the revert it
18
- * asked for and answers with it; nothing is kept or written twice.
19
- * - An undo brings a kept draft back only while the figure still holds exactly what that revert wrote
20
- * (`WHERE id = ? AND source = ?`, as a save's compare-and-swap); edited since, it is refused and the kept draft stays.
21
- * It keeps what it replaces the same way.
22
- *
23
- * Every function here runs on the caller's transaction (`tx`); the resolvers open it (`@transaction`).
24
- */
25
-
26
- const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
27
- const hashOf = (text: string) => createHash('sha256').update(text).digest('hex')
28
- const refused = (code: string, message: string) => new GraphQLError(message, { extensions: { code } })
29
-
30
- /*
31
- * The same request arriving twice at once: the second waits on the first's requestId and then meets the unique index.
32
- * Named, not a raw database error -- asked again after the first has finished, it gets the first's answer.
33
- */
34
- async function keep(kept: { save: (row: any) => Promise<any> }, row: any) {
35
- try {
36
- return await kept.save(row)
37
- } catch (error: any) {
38
- const unique = error?.code === '23505' || error?.driverError?.code === '23505' || /UNIQUE constraint failed/.test(String(error?.message))
39
- if (unique) throw refused('FIGURE_REVERT_IN_FLIGHT', '같은 요청이 처리 중입니다. 잠시 뒤 다시 확인해 주세요.')
40
- throw error
41
- }
42
- }
43
-
44
- export interface RevertRequest {
45
- id: string
46
- version: number
47
- requestId: string
48
- /** The figure's source as the reverter saw it; the revert goes on only while the figure still holds it. */
49
- expectedSource: string
50
- }
51
-
52
- export async function revertKeepingDraft(
53
- tx: EntityManager,
54
- domain: { id: string; parentId?: string | null },
55
- user: { id: string } | undefined,
56
- request: RevertRequest
57
- ) {
58
- if (!UUID.test(request.requestId ?? '')) throw refused('FIGURE_REVERT_REQUEST', '되돌리기 요청 식별자가 필요합니다.')
59
- const figures = tx.getRepository(Figure)
60
- const kept = tx.getRepository(FigureReplacedDraft)
61
-
62
- /* The same request again: the revert it made, answered again. */
63
- const before = await kept.findOne({ where: { domain: { id: domain.id }, requestId: request.requestId } })
64
- if (before) {
65
- if (before.figureId !== request.id || before.revertedToVersion !== request.version || before.kind !== 'revert')
66
- throw refused('FIGURE_REVERT_REQUEST', '이 되돌리기 요청 식별자는 다른 되돌리기에 이미 쓰였습니다.')
67
- return { figure: await figures.findOneOrFail({ where: { id: request.id, domain: { id: domain.id } } }), violations: [], kept: before }
68
- }
69
-
70
- /* Exact tenant ownership, as a save: an inherited figure is not written from a child domain. */
71
- const figure = await figures.findOne({ where: { id: request.id, domain: { id: domain.id } } })
72
- if (!figure) throw refused('FIGURE_NOT_FOUND', `Figure ${request.id} 를 찾을 수 없습니다.`)
73
- if (figure.source !== request.expectedSource) throw sourceConflict('다른 편집에서 모델이 변경되었습니다. 최신 모델을 다시 연 뒤 되돌려 주세요.')
74
-
75
- const history = await tx.getRepository(FigureHistory).findOne({
76
- where: { domain: { id: In([domain.id, domain.parentId].filter(Boolean) as string[]) }, originalId: request.id, version: request.version }
77
- })
78
- if (!history) throw refused('FIGURE_VERSION_NOT_FOUND', `Figure '${figure.type}' 에 ${request.version} 버전이 없습니다.`)
79
- /* The format is checked again: an old version may break today's rules, and is not let in quietly. */
80
- const { source, derived, violations } = parseSource(draftSourceOfRelease(history.source!))
81
-
82
- const record = await keep(kept, {
83
- domain: { id: domain.id },
84
- figureId: figure.id,
85
- kind: 'revert' as const,
86
- source: figure.source,
87
- properties: figure.properties,
88
- thumbnail: figure.thumbnail,
89
- thumbnailHash: figure.thumbnailHash,
90
- state: figure.state,
91
- version: figure.version,
92
- revertedToVersion: request.version,
93
- writtenSource: source,
94
- writtenSourceHash: hashOf(source),
95
- requestId: request.requestId,
96
- ...(user ? { creator: { id: user.id } } : {})
97
- })
98
-
99
- const written = await figures.update(
100
- { id: figure.id, domain: { id: domain.id }, source: request.expectedSource },
101
- {
102
- source,
103
- ...derived,
104
- properties: history.properties,
105
- /* The picture goes by its hash (ADR-0104 decision 6); the release's own, as the source is. */
106
- thumbnail: null,
107
- thumbnailHash: history.thumbnailHash ?? null,
108
- thumbnailUpdatedAt: history.thumbnailHash === figure.thumbnailHash ? figure.thumbnailUpdatedAt : new Date(),
109
- state: 'draft',
110
- ...(user ? { updater: { id: user.id } } : {})
111
- }
112
- )
113
- if (written.affected !== 1) throw sourceConflict('다른 편집에서 모델이 변경되었습니다. 최신 모델을 다시 연 뒤 되돌려 주세요.')
114
-
115
- return { figure: await figures.findOneOrFail({ where: { id: figure.id, domain: { id: domain.id } } }), violations, kept: record }
116
- }
117
-
118
- /** Brings a kept draft back -- only while the figure holds exactly what that revert wrote. */
119
- export async function undoRevert(
120
- tx: EntityManager,
121
- domain: { id: string },
122
- user: { id: string } | undefined,
123
- request: { keptId: string; requestId: string }
124
- ) {
125
- if (!UUID.test(request.requestId ?? '')) throw refused('FIGURE_REVERT_REQUEST', '되돌리기 취소 요청 식별자가 필요합니다.')
126
- const figures = tx.getRepository(Figure)
127
- const kept = tx.getRepository(FigureReplacedDraft)
128
-
129
- const record = await kept.findOne({ where: { id: request.keptId, domain: { id: domain.id } } })
130
- if (!record) throw refused('FIGURE_KEPT_NOT_FOUND', '되살릴 초안을 찾을 수 없습니다.')
131
- if (record.restoredAt) {
132
- /* Asked again with the same request: the undo it made. Another request for a draft already back: refused. */
133
- if (record.restoreRequestId === request.requestId)
134
- return { figure: await figures.findOneOrFail({ where: { id: record.figureId, domain: { id: domain.id } } }), kept: record }
135
- throw refused('FIGURE_KEPT_RESTORED', '이 초안은 이미 되살렸습니다.')
136
- }
137
-
138
- const figure = await figures.findOne({ where: { id: record.figureId, domain: { id: domain.id } } })
139
- if (!figure) throw refused('FIGURE_NOT_FOUND', `Figure ${record.figureId} 를 찾을 수 없습니다.`)
140
-
141
- /* What the undo replaces is kept too -- the same rule as a revert. */
142
- const { derived } = parseSource(record.source!)
143
- await keep(kept, {
144
- domain: { id: domain.id },
145
- figureId: figure.id,
146
- kind: 'undo' as const,
147
- source: figure.source,
148
- properties: figure.properties,
149
- thumbnail: figure.thumbnail,
150
- thumbnailHash: figure.thumbnailHash,
151
- state: figure.state,
152
- version: figure.version,
153
- writtenSource: record.source,
154
- writtenSourceHash: hashOf(record.source!),
155
- requestId: request.requestId,
156
- ...(user ? { creator: { id: user.id } } : {})
157
- })
158
-
159
- const written = await figures.update(
160
- { id: figure.id, domain: { id: domain.id }, source: record.writtenSource },
161
- {
162
- source: record.source,
163
- ...derived,
164
- properties: record.properties,
165
- thumbnail: null,
166
- thumbnailHash: record.thumbnailHash ?? null,
167
- thumbnailUpdatedAt: record.thumbnailHash === figure.thumbnailHash ? figure.thumbnailUpdatedAt : new Date(),
168
- state: 'draft',
169
- ...(user ? { updater: { id: user.id } } : {})
170
- }
171
- )
172
- if (written.affected !== 1)
173
- throw sourceConflict('되돌린 뒤 모델이 다시 바뀌어 되돌리기를 취소하지 않았습니다. 보관한 초안은 그대로 남아 있습니다.')
174
-
175
- await kept.update({ id: record.id }, { restoredAt: new Date(), restoreRequestId: request.requestId })
176
- return { figure: await figures.findOneOrFail({ where: { id: figure.id, domain: { id: domain.id } } }), kept: { ...record, restoredAt: new Date(), restoreRequestId: request.requestId } }
177
- }
178
-
179
- /** The drafts reverts kept for a figure, newest first -- found again after a reload. */
180
- export async function replacedDraftsOf(tx: EntityManager, domain: { id: string }, figureId: string) {
181
- return await tx.getRepository(FigureReplacedDraft).find({
182
- where: { domain: { id: domain.id }, figureId },
183
- order: { createdAt: 'DESC' },
184
- relations: ['creator']
185
- })
186
- }
@@ -1,41 +0,0 @@
1
- /*
2
- * The modeller's open figure, named for the AI (operato-application design/ai/screen-pattern.md §2-1).
3
- */
4
- const mockFigures: any[] = [
5
- { id: 'f1', domain: 'plant-a', name: '선풍기', type: 'system/fan' },
6
- { id: 'f2', domain: 'plant-a', name: '', type: 'system/agv-lift' },
7
- { id: 'f3', domain: 'plant-b', name: '남의 피규어', type: 'other/one' }
8
- ]
9
- const mockRegistered: any[] = []
10
-
11
- jest.mock('@things-factory/shell', () => ({
12
- getRepository: (name: string) => {
13
- if (name !== 'Figure') throw new Error(`unexpected repository ${name}`)
14
- return {
15
- findOne: async ({ where }: any) => mockFigures.find(one => one.id === where.id && one.domain === where.domain.id) ?? null
16
- }
17
- }
18
- }))
19
- jest.mock('@things-factory/ai-client-base', () => ({ registerAssistantSubject: (one: any) => mockRegistered.push(one) }))
20
-
21
- /* Required after the mocks hold their lists - an import would load it before them. */
22
- const { figureSubject } = require('./figure-subject')
23
-
24
- describe('the figure the modeller has open', () => {
25
- it('★ is registered for the figure anchor when the package loads', () => {
26
- expect(mockRegistered).toEqual([figureSubject])
27
- expect(figureSubject.anchorType).toBe('figure')
28
- })
29
-
30
- it('★ is named by its name, in this domain', async () => {
31
- expect(await figureSubject.describe({ anchorId: 'f1', domain: { id: 'plant-a' } })).toEqual({ noun: 'figure', name: '선풍기' })
32
- })
33
-
34
- it('a figure with no name yet is called by its type', async () => {
35
- expect(await figureSubject.describe({ anchorId: 'f2', domain: { id: 'plant-a' } })).toEqual({ noun: 'figure', name: 'system/agv-lift' })
36
- })
37
-
38
- it('★ another domain\'s figure is not named', async () => {
39
- expect(await figureSubject.describe({ anchorId: 'f3', domain: { id: 'plant-a' } })).toBeUndefined()
40
- })
41
- })
@@ -1,21 +0,0 @@
1
- /**
2
- * The figure the modeller has open, named for the AI (operato-application design/ai/screen-pattern.md §2-1).
3
- *
4
- * A conversation in the modeller is anchored to the open figure. Each turn the door reads this to say which figure
5
- * that is, so the model starts from "the figure 선풍기 is open" and passes its id to the tools. A figure of another
6
- * domain, or one that is gone, is not named.
7
- */
8
- import { registerAssistantSubject } from '@things-factory/ai-client-base'
9
- import { getRepository } from '@things-factory/shell'
10
-
11
- /* By entity name - the entity's decorators stay out of what a test of this has to load. */
12
- export const figureSubject = {
13
- anchorType: 'figure',
14
- async describe({ anchorId, domain }: { anchorId: string; domain: { id: string } }) {
15
- const figure: any = await getRepository('Figure').findOne({ where: { id: anchorId, domain: { id: domain.id } } })
16
- if (!figure) return undefined
17
- return { noun: 'figure', name: figure.name || figure.type }
18
- }
19
- }
20
-
21
- registerAssistantSubject(figureSubject)
@@ -1,279 +0,0 @@
1
- /**
2
- * A figure's picture kept by attachment-base under its content hash (ADR-0104 decision 6; chief architect's ruling
3
- * 2026-10-02): written once per content per domain, served only behind the figure permission from the figure's own
4
- * domain, and the base64 an install already holds moved at start without losing one. On sqlite with the history
5
- * subscriber on; 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 { createFigureAsset, addFigureBox, serializeFigureAsset } = require('@hatiolab/figure-model')
14
-
15
- let dataSource: DataSource | null = null
16
- let Figure: any, FigureHistory: any, FigureReplacedDraft: any, Subscriber: any, FigureMutation: any
17
- let keepThumbnail: any, sha256Of: any, useThumbnailFiles: any, moveBase64Thumbnails: any, sendFigureThumbnail: any
18
-
19
- function loadCompiled(modulePath: string): any {
20
- const { existsSync } = require('fs')
21
- const { join } = require('path')
22
- const resolved = join(__dirname, '..', '..', '..', 'dist-server', `${modulePath}.js`)
23
- if (!existsSync(resolved))
24
- throw new Error(`figure-service 산출물이 없다: ${resolved}\n먼저 빌드할 것:\n yarn workspace @things-factory/figure-service build:server`)
25
- return require(resolved)
26
- }
27
-
28
- /** Files in a map: put keeps the bytes under a new id, send hands them back. */
29
- function mapFiles() {
30
- const kept = new Map<string, Buffer>()
31
- let n = 0
32
- return {
33
- kept,
34
- async put(bytes: Buffer, _mimetype: string, name: string) {
35
- const id = `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`
36
- const path = `${id}.${name.split('.').pop()}`
37
- kept.set(path, bytes)
38
- return { id, path, size: bytes.length }
39
- },
40
- /* As S3 does: its own tag and cache rule on the way out. */
41
- async send(koa: any, path: string) {
42
- koa.set('ETag', '"storage-md5"')
43
- koa.set('Cache-Control', 'public, max-age=31536000')
44
- koa.body = kept.get(path)
45
- },
46
- async read(path: string) {
47
- return kept.get(path)!
48
- }
49
- }
50
- }
51
-
52
- const picture = (colour: number) => `data:image/webp;base64,${Buffer.from([0x52, 0x49, 0x46, 0x46, colour, colour, 1, 2]).toString('base64')}`
53
- const bytesOf = (dataUrl: string) => Buffer.from(dataUrl.split(',')[1]!, 'base64')
54
- const SOURCE = serializeFigureAsset(addFigureBox(createFigureAsset('Probe'), { id: 'body', size: { x: 100, y: 100, z: 100 }, position: { x: 0, y: 50, z: 0 } }))
55
-
56
- beforeAll(async () => {
57
- Figure = loadCompiled('service/figure/figure').Figure
58
- FigureHistory = loadCompiled('service/figure/figure-history').FigureHistory
59
- FigureReplacedDraft = loadCompiled('service/figure/figure-replaced-draft').FigureReplacedDraft
60
- Subscriber = loadCompiled('service/figure/event-subscriber').FigureHistoryEntitySubscriber
61
- FigureMutation = loadCompiled('service/figure/figure-mutation').FigureMutation
62
- ;({ keepThumbnail, sha256Of, useThumbnailFiles } = loadCompiled('service/figure/figure-thumbnail-store'))
63
- ;({ moveBase64Thumbnails } = loadCompiled('service/figure/figure-thumbnail-upgrade'))
64
- ;({ sendFigureThumbnail } = loadCompiled('routers/figure-thumbnail-router'))
65
- dataSource = new TypeOrmDataSource({
66
- type: 'sqlite',
67
- database: ':memory:',
68
- synchronize: true,
69
- dropSchema: true,
70
- namingStrategy: new shell.NamingStrategy(),
71
- entities: [...shell.entities, ...authBase.entities, ...attachmentBase.entities, Figure, FigureHistory, FigureReplacedDraft],
72
- subscribers: [Subscriber],
73
- logging: false
74
- })
75
- await dataSource.initialize()
76
- shell.addDataSource('default', dataSource)
77
- shell.addDataSource('tx', dataSource)
78
- })
79
-
80
- afterAll(async () => {
81
- shell.removeDataSource('default')
82
- shell.removeDataSource('tx')
83
- await dataSource?.destroy()
84
- dataSource = null
85
- })
86
-
87
- let seq = 0
88
- const newDomain = async (parent?: any) => {
89
- const name = `thumb-${++seq}`
90
- const saved = await dataSource!.getRepository(shell.Domain).save({ name, subdomain: name, ...(parent ? { parent } : {}) })
91
- return dataSource!.getRepository(shell.Domain).findOneOrFail({ where: { id: saved.id } })
92
- }
93
- const attachments = (domainId?: string) =>
94
- dataSource!.getRepository(attachmentBase.Attachment).find({ where: { refType: 'figure-thumbnail', ...(domainId ? { domain: { id: domainId } } : {}) } })
95
- function koa(ifNoneMatch?: string) {
96
- const headers: Record<string, string> = {}
97
- return {
98
- status: 404,
99
- type: '',
100
- body: undefined as any,
101
- headers,
102
- set(k: string, v: string) {
103
- headers[k] = v
104
- },
105
- /* As koa: fresh only for a 2xx or 304, and only when the request's tag is the response's. */
106
- get fresh() {
107
- return ((this.status >= 200 && this.status < 300) || this.status === 304) && !!ifNoneMatch && ifNoneMatch === headers['ETag']
108
- }
109
- }
110
- }
111
-
112
- describe('a picture kept by its content', () => {
113
- it('the same picture twice in a domain is one attachment; in another domain, its own', async () => {
114
- const files = mapFiles()
115
- const a = await newDomain(),
116
- b = await newDomain()
117
- const tx = dataSource!.manager
118
- const one = await keepThumbnail(tx, a, undefined, picture(7), files)
119
- expect(await keepThumbnail(tx, a, undefined, picture(7), files)).toBe(one)
120
- expect(one).toBe(sha256Of(bytesOf(picture(7))))
121
- expect((await attachments(a.id)).length).toBe(1)
122
- await keepThumbnail(tx, b, undefined, picture(7), files)
123
- expect((await attachments(b.id)).length).toBe(1)
124
- await expect(keepThumbnail(tx, a, undefined, 'not a picture', files)).rejects.toThrow(/data URL/)
125
- })
126
-
127
- it('a save names the picture by its hash and never writes the bytes onto the row', async () => {
128
- const was = useThumbnailFiles(mapFiles())
129
- const domain = await newDomain()
130
- const context = { state: { domain, user: undefined, tx: dataSource!.manager } }
131
- const figure = await dataSource!.getRepository(Figure).save({ type: 'SAVED', name: 'saved', source: SOURCE, state: 'draft', version: 0, domain })
132
- await new FigureMutation().updateFigure(figure.id, { thumbnail: picture(9) }, context)
133
- const row = await dataSource!.getRepository(Figure).findOneOrFail({ where: { id: figure.id } })
134
- expect([row.thumbnail, row.thumbnailHash]).toEqual([null, sha256Of(bytesOf(picture(9)))])
135
- expect(row.thumbnailUpdatedAt).toBeTruthy()
136
- useThumbnailFiles(was)
137
- })
138
-
139
- it('a patch of the picture alone replaces only the picture: a released figure stays released, at its version, with no new version row', async () => {
140
- const was = useThumbnailFiles(mapFiles())
141
- const domain = await newDomain()
142
- const context = { state: { domain, user: undefined, tx: dataSource!.manager } }
143
- const figure = await dataSource!.getRepository(Figure).save({ type: 'CHOSEN', name: 'chosen', source: SOURCE, state: 'draft', version: 0, domain })
144
- await new FigureMutation().updateFigure(figure.id, { thumbnail: picture(11) }, context)
145
- /* Released as a row, without the subscriber that would copy it into a version. */
146
- await dataSource!.getRepository(Figure).createQueryBuilder().update(Figure).set({ state: 'released', version: 3 }).where('id = :id', { id: figure.id }).callListeners(false).execute()
147
- const versions = await dataSource!.getRepository(FigureHistory).count({ where: { originalId: figure.id } })
148
- const before = await dataSource!.getRepository(Figure).findOneOrFail({ where: { id: figure.id } })
149
-
150
- const { figure: chosen } = await new FigureMutation().updateFigure(figure.id, { thumbnail: picture(12) }, context)
151
- expect([chosen.state, chosen.version, chosen.source]).toEqual(['released', 3, SOURCE])
152
- expect(chosen.thumbnailHash).toBe(sha256Of(bytesOf(picture(12))))
153
- expect(chosen.thumbnailHash).not.toBe(before.thumbnailHash)
154
- expect(await dataSource!.getRepository(FigureHistory).count({ where: { originalId: figure.id } })).toBe(versions)
155
-
156
- /* The same picture again is no change: the time stays. */
157
- const { figure: again } = await new FigureMutation().updateFigure(figure.id, { thumbnail: picture(12) }, context)
158
- expect(again.thumbnailUpdatedAt).toEqual(chosen.thumbnailUpdatedAt)
159
- await expect(new FigureMutation().updateFigure(figure.id, { thumbnail: 'not a picture' }, context)).rejects.toThrow(/data URL/)
160
- useThumbnailFiles(was)
161
- })
162
- })
163
-
164
- describe('served behind the permission, from the figure\'s own domain', () => {
165
- it('an inherited figure\'s picture is the parent\'s, even when the child holds the same hash elsewhere', async () => {
166
- const files = mapFiles()
167
- const parent = await newDomain()
168
- const child = await newDomain(parent)
169
- const hash = await keepThumbnail(dataSource!.manager, parent, undefined, picture(3), files)
170
- const figure = await dataSource!.getRepository(Figure).save({ type: 'INHERITED', name: 'x', source: SOURCE, state: 'released', version: 1, thumbnailHash: hash, thumbnailUpdatedAt: new Date(), domain: parent })
171
- /* The child holds an attachment under the same hash, pointing at other bytes: it must not be picked. */
172
- files.kept.set('child-copy.webp', Buffer.from('not the parent picture'))
173
- await dataSource!.getRepository(attachmentBase.Attachment).save({ domain: child, name: 'x', mimetype: 'image/webp', encoding: 'binary', refType: 'figure-thumbnail', refBy: hash, category: 'image', size: '1', path: 'child-copy.webp' })
174
- const ctx = koa()
175
- await sendFigureThumbnail(ctx, async () => {}, figure.id, child, files)
176
- expect(ctx.status).toBe(200)
177
- expect(Buffer.compare(ctx.body, bytesOf(picture(3)))).toBe(0)
178
- expect(ctx.headers['Cache-Control']).toBe('private, max-age=31536000')
179
- expect(ctx.headers['ETag']).toBe(`"${hash}"`)
180
- const again = koa(`"${hash}"`)
181
- await sendFigureThumbnail(again, async () => {}, figure.id, child, files)
182
- expect([again.status, again.body]).toEqual([304, undefined])
183
- })
184
-
185
- it("another domain's public figure is served its latest release's picture, not the draft's on its row", async () => {
186
- const files = mapFiles()
187
- const owner = await newDomain(),
188
- reader = await newDomain()
189
- const releasedHash = await keepThumbnail(dataSource!.manager, owner, undefined, picture(21), files)
190
- const draftHash = await keepThumbnail(dataSource!.manager, owner, undefined, picture(22), files)
191
- const figure = await dataSource!.getRepository(Figure).save({ type: 'PUBLIC-PIC', name: 'x', source: SOURCE, state: 'draft', version: 1, public: true, thumbnailHash: draftHash, thumbnailUpdatedAt: new Date(), domain: owner })
192
- await dataSource!.getRepository(FigureHistory).insert({ originalId: figure.id, version: 1, type: 'PUBLIC-PIC', state: 'released', source: SOURCE, thumbnailHash: releasedHash, updatedAt: new Date(), domain: owner, action: 'updated' })
193
- const theirs = koa()
194
- await sendFigureThumbnail(theirs, async () => {}, figure.id, reader, files)
195
- expect(Buffer.compare(theirs.body, bytesOf(picture(21)))).toBe(0)
196
- const own = koa()
197
- await sendFigureThumbnail(own, async () => {}, figure.id, owner, files)
198
- expect(Buffer.compare(own.body, bytesOf(picture(22)))).toBe(0)
199
- })
200
-
201
- it('a figure with no picture, or of a domain the caller cannot read, is 404', async () => {
202
- const files = mapFiles()
203
- const mine = await newDomain(),
204
- other = await newDomain()
205
- const bare = await dataSource!.getRepository(Figure).save({ type: 'BARE', name: 'x', source: SOURCE, state: 'draft', version: 0, domain: mine })
206
- const ctx = koa()
207
- await sendFigureThumbnail(ctx, async () => {}, bare.id, mine, files)
208
- expect(ctx.status).toBe(404)
209
- const hash = await keepThumbnail(dataSource!.manager, other, undefined, picture(5), files)
210
- const theirs = await dataSource!.getRepository(Figure).save({ type: 'THEIRS', name: 'x', source: SOURCE, state: 'draft', version: 0, thumbnailHash: hash, domain: other })
211
- const denied = koa()
212
- await sendFigureThumbnail(denied, async () => {}, theirs.id, mine, files)
213
- expect(denied.status).toBe(404)
214
- })
215
- })
216
-
217
- /*
218
- * The upgrade, for every shape an install may hold: a figure with base64 only, its releases (with a domain, and an old
219
- * one without), a draft a revert kept, a row with no picture, and a picture that is not a data URL. Run twice.
220
- */
221
- describe('the base64 an install holds, moved at start without losing one', () => {
222
- it('every shape moves once; what cannot move keeps its base64; a second start changes nothing', async () => {
223
- const files = mapFiles()
224
- const domain = await newDomain()
225
- const figures = dataSource!.getRepository(Figure)
226
- const histories = dataSource!.getRepository(FigureHistory)
227
- /* Old rows are written as an install wrote them: straight to the table, no subscriber. */
228
- const insert = (entity: any, values: any) => dataSource!.createQueryBuilder().insert().into(entity).values(values).callListeners(false).execute()
229
- const figureId = '11111111-1111-4111-8111-111111111111'
230
- await insert(Figure, { id: figureId, type: 'OLD', name: 'old', source: SOURCE, state: 'draft', version: 2, thumbnail: picture(1), domain: { id: domain.id } })
231
- await insert(FigureHistory, { originalId: figureId, version: 1, type: 'OLD', state: 'released', thumbnail: picture(2), domain: { id: domain.id }, action: 'updated' })
232
- await insert(FigureHistory, { originalId: figureId, version: 2, type: 'OLD', state: 'released', thumbnail: picture(1), action: 'updated' })
233
- await insert(FigureReplacedDraft, { figureId, kind: 'revert', requestId: 'r-1', source: SOURCE, thumbnail: picture(4), state: 'draft', version: 2, writtenSource: SOURCE, writtenSourceHash: 'x', domain: { id: domain.id } })
234
- await insert(Figure, { type: 'NONE', name: 'none', source: SOURCE, state: 'draft', version: 0, domain: { id: domain.id } })
235
- await insert(Figure, { type: 'BROKEN', name: 'broken', source: SOURCE, state: 'draft', version: 0, thumbnail: 'garbage', domain: { id: domain.id } })
236
-
237
- const first = await moveBase64Thumbnails(dataSource, files)
238
- expect(first).toEqual([
239
- { table: 'figure', moved: 1, kept: 1 },
240
- { table: 'figure_history', moved: 2, kept: 0 },
241
- { table: 'figure_replaced_draft', moved: 1, kept: 0 }
242
- ])
243
- const row = await figures.findOneOrFail({ where: { id: figureId } })
244
- expect([row.thumbnail, row.thumbnailHash]).toEqual([null, sha256Of(bytesOf(picture(1)))])
245
- const releases = await histories.find({ where: { originalId: figureId }, order: { version: 'ASC' } })
246
- expect(releases.map((r: any) => [r.thumbnail, r.thumbnailHash])).toEqual([
247
- [null, sha256Of(bytesOf(picture(2)))],
248
- [null, sha256Of(bytesOf(picture(1)))]
249
- ])
250
- const [kept] = await dataSource!.getRepository(FigureReplacedDraft).find()
251
- expect([kept.thumbnail, kept.thumbnailHash]).toEqual([null, sha256Of(bytesOf(picture(4)))])
252
- expect((await figures.findOneOrFail({ where: { type: 'BROKEN' } })).thumbnail).toBe('garbage')
253
- expect((await figures.findOneOrFail({ where: { type: 'NONE' } })).thumbnailHash).toBeNull()
254
- /* Three contents, three attachments: the figure and its second release share one. */
255
- expect((await attachments(domain.id)).length).toBe(3)
256
-
257
- const second = await moveBase64Thumbnails(dataSource, files)
258
- expect(second).toEqual([
259
- { table: 'figure', moved: 0, kept: 1 },
260
- { table: 'figure_history', moved: 0, kept: 0 },
261
- { table: 'figure_replaced_draft', moved: 0, kept: 0 }
262
- ])
263
- expect((await attachments(domain.id)).length).toBe(3)
264
- })
265
- })
266
-
267
- /* ADR-0106 decision 2: by its attachment path, a figure picture opens to whoever may query figures, as by its figure. */
268
- describe('read by its attachment path', () => {
269
- it('figure registers the reader for its pictures, and it asks the figure query permission', async () => {
270
- const { figureThumbnailReader } = loadCompiled('service/figure/figure-thumbnail-reader')
271
- expect(attachmentBase.attachmentReaderOf('figure-thumbnail')).toBeDefined()
272
- const asked: any[] = []
273
- const check = async (...args: any[]) => (asked.push(args), false)
274
- const context = { state: { domain: { id: 'd' }, user: { id: 'u' }, unsafeIP: false, prohibitedPrivileges: [] } }
275
- expect(await figureThumbnailReader({}, context, check)).toBe(false)
276
- expect(asked[0][0]).toEqual({ category: 'figure', privilege: 'query', owner: true })
277
- expect(await figureThumbnailReader({}, context, async () => true)).toBe(true)
278
- })
279
- })
@@ -1,20 +0,0 @@
1
- import { registerAttachmentReader } from '@things-factory/attachment-base'
2
- import { checkPermission } from '@things-factory/auth-base'
3
-
4
- import { THUMBNAIL_REF_TYPE } from './figure-thumbnail-store.js'
5
-
6
- /*
7
- * Apart from the store, and loaded only by the server's entry: the store is read by pure modules (the save path,
8
- * figure-ui's tests), and auth-base brings shell's routers with it.
9
- */
10
- /**
11
- * Who may read a figure picture by its attachment path (ADR-0106 decision 2): whoever may query figures -- the same door
12
- * `/figure-thumbnail/:id` keeps, so the picture is no more open by its path than by its figure. attachment-base has
13
- * already checked the attachment is of the request's domain.
14
- */
15
- export async function figureThumbnailReader(_attachment: unknown, context: any, check: typeof checkPermission = checkPermission): Promise<boolean> {
16
- const { domain, user, unsafeIP, prohibitedPrivileges } = context?.state ?? {}
17
- return !!(await check({ category: 'figure', privilege: 'query', owner: true }, user, domain, unsafeIP, prohibitedPrivileges))
18
- }
19
-
20
- registerAttachmentReader(THUMBNAIL_REF_TYPE, (attachment, context) => figureThumbnailReader(attachment, context))
@@ -1,111 +0,0 @@
1
- import { createHash } from 'crypto'
2
- import { Readable } from 'stream'
3
-
4
- import { Attachment, STORAGE } from '@things-factory/attachment-base'
5
-
6
- /*
7
- * A figure's picture, kept by attachment-base and named by its content (ADR-0104 decision 6, chief architect's ruling
8
- * 2026-10-02).
9
- *
10
- * stored by attachment-base's storage (file, S3, database -- whichever the install configures), one attachment
11
- * per (domain, content): refType `figure-thumbnail`, refBy the SHA-256 of the bytes. A figure, its
12
- * releases and the drafts a revert kept carry that hash, never the bytes.
13
- * served only through `/figure-thumbnail/:id`, behind the figure query permission -- never through attachment-
14
- * base's public `/attachment/:path`, which checks nothing (a known gap, recorded in ADR-0104).
15
- * the same content twice in one domain is one attachment, read by its hash. Two writers that both find none both
16
- * write one; either serves the same bytes, so the result is the same (ruling, condition 2).
17
- *
18
- * The file is written before the row that names it: a file cannot be rolled back, so it goes first, and a row that
19
- * fails to commit leaves a file the next write of the same content writes again.
20
- */
21
-
22
- export const THUMBNAIL_REF_TYPE = 'figure-thumbnail'
23
-
24
- /** `data:image/webp;base64,....` as its type and bytes; undefined when it is not one. */
25
- export function decodeDataUrl(dataUrl: string): { type: string; bytes: Buffer } | undefined {
26
- const matched = /^data:([^;,]+);base64,(.*)$/s.exec(dataUrl)
27
- return matched ? { type: matched[1]!, bytes: Buffer.from(matched[2]!, 'base64') } : undefined
28
- }
29
-
30
- export const sha256Of = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')
31
-
32
- /** Where the bytes go: attachment-base's storage. Tests give another. */
33
- export interface ThumbnailFiles {
34
- put(bytes: Buffer, mimetype: string, name: string, context: any): Promise<{ id: string; path: string; size: number; contents?: Buffer }>
35
- send(koa: any, path: string, next: () => Promise<any>): Promise<void>
36
- /** The bytes kept at a path -- what a figure package carries. */
37
- read(path: string): Promise<Buffer>
38
- }
39
-
40
- export const attachmentFiles: ThumbnailFiles = {
41
- async put(bytes, mimetype, name, context) {
42
- const file = Promise.resolve({
43
- createReadStream: () => Readable.from([bytes]),
44
- filename: name,
45
- mimetype,
46
- encoding: 'binary'
47
- })
48
- const { id, path, size, contents } = await STORAGE.uploadFile({ file, context })
49
- return { id, path, size, contents }
50
- },
51
- send: (koa, path, next) => STORAGE.sendFile(koa, path, next),
52
- read: async path => Buffer.from(await STORAGE.readFile(path))
53
- }
54
-
55
- /*
56
- * The files in use: attachment-base's storage, unless a test gives its own. One seam for every writer and the router,
57
- * so a test of a save or a revert need not reach into each.
58
- */
59
- let inUse: ThumbnailFiles = attachmentFiles
60
- export const thumbnailFiles = (): ThumbnailFiles => inUse
61
- /** For tests: use these files until set back; returns the ones it replaced. */
62
- export function useThumbnailFiles(files: ThumbnailFiles): ThumbnailFiles {
63
- const was = inUse
64
- inUse = files
65
- return was
66
- }
67
-
68
- type Tx = { getRepository: (target: any) => any }
69
-
70
- /** The attachment holding this content in this domain, or undefined. */
71
- export async function thumbnailAttachmentOf(tx: Tx, domainId: string, hash: string): Promise<Attachment | undefined> {
72
- return (await tx.getRepository(Attachment).findOne({ where: { domain: { id: domainId }, refType: THUMBNAIL_REF_TYPE, refBy: hash } })) ?? undefined
73
- }
74
-
75
- /**
76
- * Keeps a picture and gives its hash. Refused when it is not a data URL -- a picture the server cannot read is one it
77
- * must not keep under a name.
78
- */
79
- export async function keepThumbnail(
80
- tx: Tx,
81
- domain: { id: string },
82
- user: unknown,
83
- dataUrl: string,
84
- files: ThumbnailFiles = thumbnailFiles()
85
- ): Promise<string> {
86
- const decoded = decodeDataUrl(dataUrl)
87
- if (!decoded) throw new Error('썸네일은 data URL(data:image/...;base64,...) 이어야 한다')
88
- const hash = sha256Of(decoded.bytes)
89
- if (await thumbnailAttachmentOf(tx, domain.id, hash)) return hash
90
- const ext = decoded.type.split('/')[1]?.split('+')[0] || 'bin'
91
- const name = `${hash}.${ext}`
92
- /* The file first: it cannot be rolled back. The row that names it comes after, in the caller's transaction. */
93
- const put = await files.put(decoded.bytes, decoded.type, name, { state: { domain, user, tx } })
94
- await tx.getRepository(Attachment).save({
95
- domain,
96
- creator: user,
97
- updater: user,
98
- id: put.id,
99
- name,
100
- mimetype: decoded.type,
101
- encoding: 'binary',
102
- refType: THUMBNAIL_REF_TYPE,
103
- refBy: hash,
104
- category: 'image',
105
- size: String(put.size),
106
- path: put.path,
107
- ...(put.contents ? { contents: put.contents } : {})
108
- })
109
- return hash
110
- }
111
-