zelos-recad 0.1.0 → 0.2.0

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 (166) hide show
  1. package/README.md +18 -5
  2. package/UPSTREAM-LICENSE +21 -21
  3. package/build-info.json +26 -0
  4. package/mcp/index.js +2 -1
  5. package/package.json +22 -10
  6. package/protocol/src/bundle.d.ts +7 -1
  7. package/protocol/src/contracts.d.ts +18 -6
  8. package/protocol/src/contracts.js +20 -7
  9. package/protocol/src/native-evidence.d.ts +20 -0
  10. package/service/app.js +4 -2
  11. package/service/options.d.ts +2 -1
  12. package/service/options.js +2 -1
  13. package/shared/build-identity.d.mts +6 -0
  14. package/shared/build-identity.mjs +63 -0
  15. package/shared/client.d.mts +1 -0
  16. package/shared/client.mjs +9 -0
  17. package/shared/command.d.mts +1 -0
  18. package/shared/command.mjs +22 -4
  19. package/shared/contracts/src/paths.d.ts +3 -0
  20. package/shared/contracts/src/paths.js +31 -0
  21. package/shared/mcp.d.mts +1 -0
  22. package/shared/service-storage/src/capacity.d.ts +36 -0
  23. package/shared/service-storage/src/capacity.js +71 -0
  24. package/shared/service-storage/src/consumption.d.ts +15 -0
  25. package/shared/service-storage/src/consumption.js +27 -0
  26. package/shared/service-storage/src/documents.d.ts +43 -0
  27. package/shared/service-storage/src/documents.js +210 -0
  28. package/shared/service-storage/src/downloads.d.ts +10 -0
  29. package/shared/service-storage/src/downloads.js +58 -0
  30. package/shared/service-storage/src/files.d.ts +18 -0
  31. package/shared/service-storage/src/files.js +118 -0
  32. package/shared/service-storage/src/footprint.d.ts +14 -0
  33. package/shared/service-storage/src/footprint.js +72 -0
  34. package/shared/service-storage/src/process-temp.d.ts +22 -0
  35. package/shared/service-storage/src/process-temp.js +181 -0
  36. package/shared/service-storage/src/quota.d.ts +30 -0
  37. package/shared/service-storage/src/quota.js +166 -0
  38. package/shared/service-storage/src/retention.d.ts +38 -0
  39. package/shared/service-storage/src/retention.js +148 -0
  40. package/shared/service-storage/src/staging.d.ts +15 -0
  41. package/shared/service-storage/src/staging.js +116 -0
  42. package/source/README.md +1 -3
  43. package/source/mcp/index.ts +2 -1
  44. package/source/package.json +4 -2
  45. package/source/protocol/src/contracts.ts +20 -7
  46. package/source/protocol/src/native-evidence.ts +21 -0
  47. package/source/rebuild.mjs +12 -4
  48. package/source/service/app.ts +6 -2
  49. package/source/service/options.ts +3 -2
  50. package/source/shared/build-identity.d.mts +6 -0
  51. package/source/shared/build-identity.mjs +63 -0
  52. package/source/shared/client.d.mts +1 -0
  53. package/source/shared/client.mjs +9 -0
  54. package/source/shared/command.d.mts +1 -0
  55. package/source/shared/command.mjs +22 -4
  56. package/source/shared/contracts/src/paths.ts +33 -0
  57. package/source/shared/mcp.d.mts +1 -0
  58. package/source/shared/service-storage/src/capacity.ts +101 -0
  59. package/source/shared/service-storage/src/consumption.ts +45 -0
  60. package/source/shared/service-storage/src/documents.ts +262 -0
  61. package/source/shared/service-storage/src/downloads.ts +62 -0
  62. package/source/shared/service-storage/src/files.ts +135 -0
  63. package/source/shared/service-storage/src/footprint.ts +78 -0
  64. package/source/shared/service-storage/src/process-temp.ts +205 -0
  65. package/source/shared/service-storage/src/quota.ts +198 -0
  66. package/source/shared/service-storage/src/retention.ts +180 -0
  67. package/source/shared/service-storage/src/staging.ts +106 -0
  68. package/source/src/application-objects.ts +2 -2
  69. package/source/src/assets.ts +15 -0
  70. package/source/src/block-clip.ts +1 -1
  71. package/source/src/block-metadata.ts +12 -5
  72. package/source/src/build-info.ts +15 -0
  73. package/source/src/cad-engine.ts +18 -8
  74. package/source/src/command.ts +2 -2
  75. package/source/src/constraints.ts +2 -2
  76. package/source/src/conversion.ts +2 -0
  77. package/source/src/dwg-fallback.ts +2 -0
  78. package/source/src/dwg.ts +7 -0
  79. package/source/src/dxf-export.ts +3 -3
  80. package/source/src/dxf.ts +7 -4
  81. package/source/src/native-evidence.ts +33 -1
  82. package/source/src/native-segmented-path.ts +22 -35
  83. package/source/src/point-dictionaries.ts +65 -0
  84. package/source/src/readback.ts +7 -6
  85. package/source/src/reader.ts +19 -10
  86. package/source/src/render-operation.ts +39 -7
  87. package/source/src/runner.ts +5 -4
  88. package/source/src/runtime/documents.ts +23 -142
  89. package/source/src/runtime/index.ts +71 -17
  90. package/source/src/runtime/jobs.ts +176 -153
  91. package/source/src/runtime/managed-worker.ts +37 -0
  92. package/source/src/runtime/storage-policy.ts +39 -0
  93. package/source/src/runtime/storage.ts +9 -44
  94. package/source/src/source-scene.ts +125 -23
  95. package/source/src/text/glyphs.ts +63 -0
  96. package/source/src/text/ink-bounds.ts +7 -36
  97. package/source/src/text/scene-geometry.ts +92 -0
  98. package/source/src/text/source-fonts.ts +31 -0
  99. package/source/src/vendor-object-data.ts +265 -0
  100. package/source/src/xref.ts +4 -3
  101. package/source/tsconfig.json +4 -2
  102. package/src/application-objects.js +2 -2
  103. package/src/assets.d.ts +9 -0
  104. package/src/assets.js +14 -0
  105. package/src/block-clip.js +1 -1
  106. package/src/block-metadata.js +11 -5
  107. package/src/build-info.d.ts +2 -0
  108. package/src/build-info.js +14 -0
  109. package/src/cad-engine.js +19 -8
  110. package/src/command.js +2 -2
  111. package/src/constraints.js +2 -2
  112. package/src/conversion.d.ts +2 -0
  113. package/src/conversion.js +2 -0
  114. package/src/dwg-fallback.d.ts +1 -0
  115. package/src/dwg-fallback.js +2 -0
  116. package/src/dwg.d.ts +3 -0
  117. package/src/dwg.js +7 -0
  118. package/src/dxf-export.js +3 -3
  119. package/src/dxf.d.ts +14 -1
  120. package/src/dxf.js +7 -3
  121. package/src/native-evidence.d.ts +33 -1
  122. package/src/native-evidence.js +33 -0
  123. package/src/native-segmented-path.js +1 -3
  124. package/src/point-dictionaries.d.ts +12 -0
  125. package/src/point-dictionaries.js +88 -0
  126. package/src/readback.d.ts +12 -4
  127. package/src/readback.js +7 -6
  128. package/src/reader.d.ts +12 -1
  129. package/src/reader.js +22 -11
  130. package/src/render-operation.js +36 -7
  131. package/src/runner.js +5 -4
  132. package/src/runtime/documents.d.ts +8 -20
  133. package/src/runtime/documents.js +17 -116
  134. package/src/runtime/index.d.ts +41 -4
  135. package/src/runtime/index.js +72 -18
  136. package/src/runtime/jobs.d.ts +21 -2
  137. package/src/runtime/jobs.js +120 -100
  138. package/src/runtime/managed-worker.d.ts +8 -0
  139. package/src/runtime/managed-worker.js +29 -0
  140. package/src/runtime/storage-policy.d.ts +25 -0
  141. package/src/runtime/storage-policy.js +29 -0
  142. package/src/runtime/storage.d.ts +1 -7
  143. package/src/runtime/storage.js +1 -38
  144. package/src/source-scene.d.ts +4 -2
  145. package/src/source-scene.js +136 -20
  146. package/src/text/glyphs.d.ts +12 -0
  147. package/src/text/glyphs.js +53 -0
  148. package/src/text/ink-bounds.d.ts +2 -1
  149. package/src/text/ink-bounds.js +6 -34
  150. package/src/text/scene-geometry.d.ts +21 -0
  151. package/src/text/scene-geometry.js +70 -0
  152. package/src/text/source-fonts.d.ts +7 -0
  153. package/src/text/source-fonts.js +30 -0
  154. package/src/vendor-object-data.d.ts +19 -0
  155. package/src/vendor-object-data.js +241 -0
  156. package/src/xref.js +3 -3
  157. package/vendor/libredwg/COPYING +674 -674
  158. package/vendor/libredwg/Dockerfile +2 -0
  159. package/vendor/libredwg/README.md +41 -28
  160. package/vendor/libredwg/build-local.sh +1 -1
  161. package/vendor/libredwg/libredwg-web.wasm +0 -0
  162. package/vendor/libredwg/manifest.json +5 -3
  163. package/vendor/libredwg/opaque-object-binding.patch +29 -0
  164. package/vendor/libredwg/rebuild.mjs +2 -1
  165. package/source/service/README.md +0 -152
  166. package/source/src/text/UPSTREAM.md +0 -26
@@ -0,0 +1,39 @@
1
+ import { capacityPolicy } from '../../shared/service-storage/src/capacity.ts'
2
+ import { workerStorageBytes, type ServiceCapacityOptions } from '../../shared/service-storage/src/quota.ts'
3
+ import { DEFAULT_RETENTION_MS } from '../../shared/service-storage/src/retention.ts'
4
+ import { CadError } from '../contracts.ts'
5
+
6
+ export interface StorageSettings {
7
+ retentionMs?: number
8
+ maxStorageBytes?: number
9
+ workerStorageBytes?: number
10
+ storageCapacity?: ServiceCapacityOptions
11
+ minimumFreeBytes?: number
12
+ resumeExtraBytes?: number
13
+ storageEstimateFactor?: number
14
+ }
15
+
16
+ /** One set of defaults for services and managed one-shot work; explicit options take precedence. */
17
+ export function recadStorageOptions(options: StorageSettings = {}, env: NodeJS.ProcessEnv = process.env) {
18
+ const number = (name: string, factor: number, minimum: number) => {
19
+ const raw = env[name]
20
+ if (raw === undefined || raw === '') return undefined
21
+ const value = Number(raw)
22
+ if (!Number.isFinite(value) || value < minimum || value * factor > Number.MAX_SAFE_INTEGER)
23
+ throw new CadError('CONFIG', name + ' is outside its supported range')
24
+ return factor === 1 ? value : Math.ceil(value * factor)
25
+ }
26
+ const selected = options.storageCapacity?.policy
27
+ const policy = {
28
+ ...capacityPolicy, ...selected,
29
+ safetyBytes: options.minimumFreeBytes ?? selected?.safetyBytes ?? number('RECAD_MIN_FREE_GIB', 1024 ** 3, 0) ?? capacityPolicy.safetyBytes,
30
+ resumeExtraBytes: options.resumeExtraBytes ?? selected?.resumeExtraBytes ?? number('RECAD_RESUME_EXTRA_GIB', 1024 ** 3, 0) ?? capacityPolicy.resumeExtraBytes,
31
+ estimateFactor: options.storageEstimateFactor ?? selected?.estimateFactor ?? number('RECAD_STORAGE_ESTIMATE_FACTOR', 1, 1) ?? capacityPolicy.estimateFactor,
32
+ }
33
+ return {
34
+ retentionMs: options.retentionMs ?? number('RECAD_RETENTION_DAYS', 86400000, 0.001) ?? DEFAULT_RETENTION_MS,
35
+ maxStorageBytes: options.maxStorageBytes ?? number('RECAD_MAX_STORAGE_MIB', 1024 ** 2, 0),
36
+ workerStorageBytes: options.workerStorageBytes ?? number('RECAD_WORKER_STORAGE_MIB', 1024 ** 2, 0.001) ?? workerStorageBytes,
37
+ storageCapacity: { ...options.storageCapacity, policy },
38
+ }
39
+ }
@@ -1,44 +1,9 @@
1
- import { lstatSync, readdirSync, realpathSync, rmSync } from 'node:fs'
2
- import path from 'node:path'
3
- import { CadError } from '../contracts.ts'
4
-
5
- export const jobIdPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
6
- export function checkedId(id: unknown): string {
7
- if (typeof id !== 'string' || !jobIdPattern.test(id))
8
- throw new CadError('JOB_ID', '任务标识必须是小写 UUID')
9
- return id
10
- }
11
- export { writeJson as atomicJson } from '../io.ts'
12
- /** Reject links before measuring or removing a service-owned job directory. */
13
- export function directoryBytes(directory: string): number {
14
- const stat = lstatSync(directory)
15
- if (stat.isSymbolicLink()) throw new CadError('STORAGE_LINK', '任务目录包含链接,拒绝自动清理')
16
- if (!stat.isDirectory()) return stat.size
17
- return readdirSync(directory).reduce(
18
- (sum, name) => sum + directoryBytes(path.join(directory, name)),
19
- 0,
20
- )
21
- }
22
- export function removeJobDirectory(data: string, id: string) {
23
- checkedId(id)
24
- const root = realpathSync(data),
25
- target = path.resolve(root, id)
26
- if (
27
- path.dirname(target) !== root ||
28
- lstatSync(target).isSymbolicLink() ||
29
- realpathSync(target) !== target
30
- )
31
- throw new CadError('STORAGE_PATH', '清理目标不在服务任务目录中')
32
- directoryBytes(target)
33
- rmSync(target, { recursive: true })
34
- }
35
- export function canonical(value: any): any {
36
- if (Array.isArray(value)) return value.map(canonical)
37
- if (value && typeof value === 'object')
38
- return Object.fromEntries(
39
- Object.keys(value)
40
- .sort()
41
- .map((k) => [k, canonical(value[k])]),
42
- )
43
- return value
44
- }
1
+ export {
2
+ atomicJson,
3
+ canonical,
4
+ checkedId,
5
+ directoryBytes,
6
+ idPattern as jobIdPattern,
7
+ removeJob as removeJobDirectory,
8
+ dataRoot,
9
+ } from '../../shared/service-storage/src/files.ts'
@@ -27,37 +27,105 @@ const union = (boxes: Box[]) => extent(boxes.flatMap(rectangle))
27
27
  const contains = (a: Box, b: Box, t = 0) =>
28
28
  a[0] - t <= b[0] && a[1] - t <= b[1] && a[2] + t >= b[2] && a[3] + t >= b[3]
29
29
 
30
+ /** Size the scene's plain JSON tree without allocating an oversized UTF-16 string. */
31
+ export function sceneJsonBytes(value: unknown): number {
32
+ function size(value: any): number | undefined {
33
+ if (value === null || typeof value !== 'object') {
34
+ const encoded = JSON.stringify(value)
35
+ return encoded === undefined ? undefined : Buffer.byteLength(encoded)
36
+ }
37
+ if (Array.isArray(value))
38
+ return 2 + Math.max(0, value.length - 1) + value.reduce((sum, item) => sum + (size(item) ?? 4), 0)
39
+ let bytes = 2, comma = 0
40
+ for (const [key, item] of Object.entries(value)) {
41
+ const count = size(item)
42
+ if (count === undefined) continue
43
+ bytes += comma + Buffer.byteLength(JSON.stringify(key)) + 1 + count
44
+ comma = 1
45
+ }
46
+ return bytes
47
+ }
48
+ return size(value)!
49
+ }
50
+
30
51
  /** Same sheet policy as XDTerminal: outer rectangular frames, reading order,
31
52
  * intact overlapping frames and a separate page for every unassigned object.
32
53
  * Bounds of clipped/specialized objects remain conservative and are labelled. */
33
- export function splitSourceSheets(entities: any[]) {
54
+ export function splitSourceSheets(entities: any[], mode: 'auto' | 'single' = 'auto') {
34
55
  if (!entities.length) throw new CadError('EMPTY_SCENE', '模型空间没有场景图元')
35
56
  const total = union(entities.map((e) => e.bounds))
57
+ if (mode === 'single') return [{ box: total, entityIds: entities.map(e => e.id), frame: false, issues: [] }]
36
58
  const span = Math.max(total[2] - total[0], total[3] - total[1])
59
+ // A long row/column grows only one dimension; each real sheet remains
60
+ // comparable to the short axis of the occupied drawing area.
61
+ const frameSpan = Math.min(total[2] - total[0], total[3] - total[1])
37
62
  const tolerance = Math.max(span * 1e-5, 1e-5)
38
63
  const horizontal = new Map<string, number[][]>(),
39
- vertical: number[][] = []
64
+ sourceSegments = new Map<string, {horizontal:number[][];vertical:number[][]}>()
40
65
  let work = 0
41
66
  const step = () => {
42
67
  if (++work > 2_000_000) throw new CadError('SHEET_LIMIT', '自动分图几何搜索超过预算')
43
68
  }
44
69
  for (const entity of entities) {
45
70
  if (entity.kind !== 'path' || entity.clips.length) continue
71
+ const root = entity.instancePath?.[0] || (entity.closed ? entity.id : 'unscoped')
72
+ if(!sourceSegments.has(root))sourceSegments.set(root,{horizontal:[],vertical:[]})
73
+ const segments=sourceSegments.get(root)!
46
74
  const ps = entity.closed ? [...entity.points, entity.points[0]] : entity.points
47
75
  for (let i = 1; i < ps.length; i++) {
48
76
  step()
49
77
  const a = ps[i - 1],
50
78
  b = ps[i]
51
- if (Math.abs(a.y - b.y) <= tolerance && Math.abs(a.x - b.x) >= span * 0.12) {
52
- const x0 = Math.min(a.x, b.x),
53
- x1 = Math.max(a.x, b.x)
54
- const key = Math.round(x0 / tolerance) + ':' + Math.round(x1 / tolerance)
55
- if (!horizontal.has(key)) horizontal.set(key, [])
56
- horizontal.get(key)!.push([x0, x1, (a.y + b.y) / 2])
79
+ if (Math.abs(a.y - b.y) <= tolerance && Math.abs(a.x - b.x) > tolerance) {
80
+ segments.horizontal.push([(a.y + b.y) / 2, Math.min(a.x, b.x), Math.max(a.x, b.x)])
57
81
  } else if (Math.abs(a.x - b.x) <= tolerance)
58
- vertical.push([(a.x + b.x) / 2, Math.min(a.y, b.y), Math.max(a.y, b.y)])
82
+ segments.vertical.push([(a.x + b.x) / 2, Math.min(a.y, b.y), Math.max(a.y, b.y)])
59
83
  }
60
84
  }
85
+ // CAD frames are often split at grid labels or block boundaries. Join only
86
+ // touching collinear intervals for frame search; source strokes stay intact.
87
+ const merge = (segments: number[][]) => {
88
+ const groups: number[][][] = []
89
+ for (const segment of segments.sort((a,b)=>a[0]!-b[0]! || a[1]!-b[1]!)) {
90
+ const group=groups.at(-1)
91
+ if(group && segment[0]!-group[0]![0]!<=tolerance)group.push(segment)
92
+ else groups.push([segment])
93
+ }
94
+ const joined:number[][]=[]
95
+ for(const group of groups) {
96
+ let current:number[]|undefined
97
+ for(const segment of group.sort((a,b)=>a[1]!-b[1]!)) {
98
+ if(current && segment[1]!<=current[2]!+tolerance)current[2]=Math.max(current[2]!,segment[2]!)
99
+ else {current=[group[0]![0]!,segment[1]!,segment[2]!];joined.push(current)}
100
+ }
101
+ }
102
+ return joined
103
+ }
104
+ for(const source of sourceSegments.values())for(const [y,x0,x1] of merge(source.horizontal))if(x1!-x0!>=frameSpan*.12) {
105
+ const key=Math.round(x0!/tolerance)+':'+Math.round(x1!/tolerance)
106
+ if(!horizontal.has(key))horizontal.set(key,[])
107
+ horizontal.get(key)!.push([x0!,x1!,y!])
108
+ }
109
+ const vertical=[...sourceSegments.values()].flatMap(source=>merge(source.vertical))
110
+ // Restrict side searches to the relevant x coordinate. Dense wiring sheets
111
+ // contain many short vertical strokes unrelated to any candidate frame.
112
+ vertical.sort((a, b) => a[0]! - b[0]!)
113
+ const spans = (x: number, y0: number, y1: number) => {
114
+ let lo = 0, hi = vertical.length
115
+ while (lo < hi) {
116
+ step()
117
+ const mid = (lo + hi) >>> 1
118
+ if (vertical[mid]![0]! < x - tolerance) lo = mid + 1
119
+ else hi = mid
120
+ }
121
+ for (let i = lo; i < vertical.length && vertical[i]![0]! <= x + tolerance; i++) {
122
+ step()
123
+ const v = vertical[i]!
124
+ if (Math.abs(v[0]! - x) <= tolerance && v[1]! <= y0 + tolerance && v[2]! >= y1 - tolerance)
125
+ return true
126
+ }
127
+ return false
128
+ }
61
129
  const frames: Box[] = []
62
130
  for (const edges of horizontal.values()) {
63
131
  edges.sort((a, b) => a[2]! - b[2]!)
@@ -67,18 +135,9 @@ export function splitSourceSheets(entities: any[]) {
67
135
  const [x0, x1, y0] = edges[i]!,
68
136
  y1 = edges[j]![2]!,
69
137
  ratio = (x1! - x0!) / (y1 - y0!)
70
- if (ratio < 0.4 || ratio > 2.6 || y1 - y0! < span * 0.12) continue
138
+ if (ratio < 0.4 || ratio > 2.6 || y1 - y0! < frameSpan * 0.12) continue
71
139
  if (
72
- [x0!, x1!].every((x) =>
73
- vertical.some((v) => {
74
- step()
75
- return (
76
- Math.abs(v[0]! - x) <= tolerance &&
77
- v[1]! <= y0! + tolerance &&
78
- v[2]! >= y1 - tolerance
79
- )
80
- }),
81
- )
140
+ [x0!, x1!].every((x) => spans(x, y0!, y1))
82
141
  )
83
142
  frames.push([x0!, y0!, x1!, y1])
84
143
  }
@@ -108,7 +167,15 @@ export function splitSourceSheets(entities: any[]) {
108
167
  if (!outer.length) return [sheet(total, entities, false, ['frame-not-found'])]
109
168
  const assigned = new Set<string>(),
110
169
  result = []
170
+ const rows: Box[][] = []
111
171
  for (const box of outer.sort((a, b) => b[3] - a[3] || a[0] - b[0])) {
172
+ const row = rows.at(-1)
173
+ const aligned = row && (row[0]![3] - box[3] <= tolerance ||
174
+ Math.min(row[0]![3],box[3])-Math.max(row[0]![1],box[1]) >= .9*Math.min(row[0]![3]-row[0]![1],box[3]-box[1]))
175
+ if (aligned) row!.push(box)
176
+ else rows.push([box])
177
+ }
178
+ for (const box of rows.flatMap(row => row.sort((a, b) => a[0] - b[0]))) {
112
179
  const selected = entities.filter((e) => contains(box, e.bounds, tolerance))
113
180
  if (!selected.length) continue
114
181
  selected.forEach((e) => assigned.add(e.id))
@@ -130,13 +197,15 @@ export function sourceScene(
130
197
  textInk: TextInkBounds,
131
198
  provenance: any,
132
199
  native?: import('./native-evidence.ts').NativeCapture,
200
+ textGeometry?: ReturnType<typeof import('./text/scene-geometry.ts').textSceneGeometry>,
133
201
  ) {
134
202
  const layers = new Map<string, any>(
135
203
  [...db.tables.layerTable.newIterator()].map((l: any) => [l.name.toLowerCase(), l]),
136
204
  )
137
205
  const entities: any[] = [],
138
206
  issues: any[] = []
139
- const nativeInstances: import('zelos-recad/protocol/native-evidence').CadNativeInstance[] = []
207
+ const textShapes: any[] = []
208
+ const nativeInstances: import('../protocol/src/native-evidence.ts').CadNativeInstance[] = []
140
209
  const nativeHandles = new Map<string, string>()
141
210
  if (native)
142
211
  for (const [record, id] of native.references)
@@ -150,6 +219,7 @@ export function sourceScene(
150
219
  path: string[],
151
220
  clips: Point[][],
152
221
  textParent = false,
222
+ textOwner?: any,
153
223
  ) {
154
224
  if (++nodes > 1_000_000 || path.length > 64)
155
225
  throw new CadError('SCENE_LIMIT', '场景实例数量或深度超过预算')
@@ -213,6 +283,25 @@ export function sourceScene(
213
283
  instance?.sceneEntityIds.push(String(entities.length))
214
284
  }
215
285
  const actual = String(node.actualText || '')
286
+ if (
287
+ textGeometry &&
288
+ !textOwner &&
289
+ !textParent &&
290
+ (actual || node._ops.some((op: any) => op.kind === 'text'))
291
+ ) {
292
+ textOwner = {
293
+ ...common,
294
+ ...(instance ? { nativeRecordId: recordId, nativeInstanceId: instance.id } : {}),
295
+ text:
296
+ actual ||
297
+ node._ops
298
+ .filter((op: any) => op.kind === 'text')
299
+ .map((op: any) => op.text)
300
+ .join(''),
301
+ primitives: [],
302
+ }
303
+ textShapes.push(textOwner)
304
+ }
216
305
  if (actual && !textParent) {
217
306
  const quad = node.userData?.xdtraceTextQuad
218
307
  if (quad)
@@ -237,6 +326,7 @@ export function sourceScene(
237
326
  }
238
327
  }
239
328
  for (const op of node._ops) {
329
+ if (textGeometry && textOwner) textOwner.primitives.push(...textGeometry(op, map))
240
330
  // Glyph strokes stay in the PDF; scene consumers use their native text.
241
331
  if (actual || textParent) continue
242
332
  if (op.kind === 'stroke') {
@@ -259,8 +349,16 @@ export function sourceScene(
259
349
  } else {
260
350
  const b = node.box,
261
351
  ps = rectangle([b.min.x, b.min.y, b.max.x, b.max.y])
352
+ // Preserve the actual POINT marker operation separately from its native
353
+ // zero-dimensional record. Consumers retain POINT and replay this paint.
354
+ const nativePoint = op.kind === 'circle' && db.getObjectById(common.handle)?.dxfTypeName === 'POINT'
355
+ ? { version: 1, displayMode: db.pdmode, displaySize: db.pdsize,
356
+ center: map({ x: op.x, y: op.y }),
357
+ axisX: { x: (m?.[0] ?? 1) * op.r, y: (m?.[1] ?? 0) * op.r },
358
+ axisY: { x: (m?.[4] ?? 0) * op.r, y: (m?.[5] ?? 1) * op.r }, style: op.style }
359
+ : undefined
262
360
  if (ps.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y)))
263
- add('specialized', ps, { operation: op.kind, boundsPolicy: 'conservative-world-box' })
361
+ add('specialized', ps, { operation: op.kind, boundsPolicy: 'conservative-world-box', ...(nativePoint ? { nativePoint } : {}) })
264
362
  issues.push({
265
363
  code: 'scene-specialized-bounds',
266
364
  handle: common.handle,
@@ -277,6 +375,7 @@ export function sourceScene(
277
375
  [...path, `${i}:${node.childAt(i).objectId || ''}`],
278
376
  clips,
279
377
  textParent || !!actual,
378
+ textOwner,
280
379
  )
281
380
  }
282
381
  roots.forEach((root, i) => visit(root, undefined, '0', [`${i}:${root.objectId || ''}`], []))
@@ -298,6 +397,9 @@ export function sourceScene(
298
397
  ...provenance,
299
398
  paperLayouts,
300
399
  entities,
400
+ ...(textGeometry
401
+ ? { textGeometry: { version: 1, coordinateSystem: 'cad-world-y-up-v1', groups: textShapes } }
402
+ : {}),
301
403
  ...(native
302
404
  ? {
303
405
  nativeEvidence: {
@@ -315,6 +417,6 @@ export function sourceScene(
315
417
  }
316
418
  : {}),
317
419
  issues,
318
- sheets: splitSourceSheets(entities),
420
+ sheets: splitSourceSheets(entities, provenance.sheetMode || 'auto'),
319
421
  }
320
422
  }
@@ -0,0 +1,63 @@
1
+ import { CadError } from '../contracts.ts'
2
+
3
+ export type GlyphPoint = { x: number; y: number }
4
+ export interface PlacedGlyph {
5
+ glyph: any
6
+ place: (x: number, y: number) => GlyphPoint
7
+ }
8
+ export type TextGlyphs = (op: any) => PlacedGlyph[]
9
+
10
+ /** Follow the pinned PDF writer's shaped glyph order, tracking and text matrix.
11
+ * Bounds and optional outline export share this placement; CAD layout stays upstream. */
12
+ export function textGlyphs(fonts: any): TextGlyphs {
13
+ const cache = new WeakMap<object, PlacedGlyph[]>()
14
+ return (op: any) => {
15
+ const cached = cache.get(op)
16
+ if (cached) return cached
17
+ const loaded = fonts._loaded.get(op.font),
18
+ font = loaded?.fk,
19
+ units = font?.unitsPerEm
20
+ if (!font || !Number.isFinite(units) || units <= 0)
21
+ throw new CadError('FONT_INVALID', '文字字形缺少有效字体:' + op.font)
22
+ const rad = (op.angleDeg * Math.PI) / 180,
23
+ c = Math.cos(rad),
24
+ s = Math.sin(rad)
25
+ const shear = Math.tan(((op.obliqueDeg || 0) * Math.PI) / 180)
26
+ const flip = op.flipX === true ? -1 : 1,
27
+ tracking = op.tracking ?? 1
28
+ const extra = ((tracking - 1) / loaded.scaleFactor) * units
29
+ let pen = 0
30
+ const result: PlacedGlyph[] = []
31
+ const add = (glyph: any) => {
32
+ if (result.length >= 250_000) throw new CadError('SCENE_LIMIT', '单段文字字形数量超过预算')
33
+ if (!Number.isFinite(glyph.advanceWidth))
34
+ throw new CadError('FONT_INVALID', '文字字距无效:' + op.font)
35
+ const offset = pen
36
+ result.push({
37
+ glyph,
38
+ place(x, y) {
39
+ x += offset
40
+ const p = {
41
+ x: op.x + (op.size / units) * (x * op.hScale * flip * c + y * (shear * c - s)),
42
+ y: op.y + (op.size / units) * (x * op.hScale * flip * s + y * (shear * s + c)),
43
+ }
44
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y))
45
+ throw new CadError('FONT_INVALID', '文字字形坐标无效:' + op.font)
46
+ return p
47
+ },
48
+ })
49
+ pen += glyph.advanceWidth
50
+ }
51
+ for (const glyph of font.layout(op.text).glyphs) {
52
+ if (tracking === 1) add(glyph)
53
+ else {
54
+ // The PDF writer encodes each shaped glyph's code points again for tracking.
55
+ for (const encoded of font.layout(String.fromCodePoint(...glyph.codePoints)).glyphs)
56
+ add(encoded)
57
+ pen += extra
58
+ }
59
+ }
60
+ cache.set(op, result)
61
+ return result
62
+ }
63
+ }
@@ -1,4 +1,5 @@
1
1
  import { CadError } from '../contracts.ts'
2
+ import type { TextGlyphs } from './glyphs.ts'
2
3
 
3
4
  type Point = { x: number; y: number }
4
5
  export type TextInkBounds = (op: any) => Point[][]
@@ -7,56 +8,26 @@ export type TextInkBounds = (op: any) => Point[][]
7
8
  * layout box can omit capitals, descenders, shear and later MTEXT lines.
8
9
  * Follow pdf-renderer 1.7.4 / pdf-lib's actual glyph advances and text matrix;
9
10
  * this does not change layout, encoding, or PDF painting. */
10
- export function textInkBounds(fonts: any): TextInkBounds {
11
+ export function textInkBounds(glyphs: TextGlyphs): TextInkBounds {
11
12
  const cache = new WeakMap<object, Point[][]>()
12
13
  return (op: any) => {
13
14
  const cached = cache.get(op)
14
15
  if (cached) return cached
15
- // Reuse the exact normalized face loaded by the pinned PDF font manager.
16
- const loaded = fonts._loaded.get(op.font)
17
- const font = loaded?.fk,
18
- units = font?.unitsPerEm
19
- if (!font || !Number.isFinite(units) || units <= 0)
20
- throw new CadError('FONT_INVALID', '文字范围缺少有效字体:' + op.font)
21
- const rad = (op.angleDeg * Math.PI) / 180,
22
- c = Math.cos(rad),
23
- s = Math.sin(rad)
24
- const shear = Math.tan(((op.obliqueDeg || 0) * Math.PI) / 180)
25
- const flip = op.flipX === true ? -1 : 1
26
- const tracking = op.tracking ?? 1
27
- const extra = ((tracking - 1) / loaded.scaleFactor) * units
28
- let pen = 0
29
16
  const loops: Point[][] = []
30
- const place = (x: number, y: number): Point => ({
31
- x: op.x + (op.size / units) * (x * op.hScale * flip * c + y * (shear * c - s)),
32
- y: op.y + (op.size / units) * (x * op.hScale * flip * s + y * (shear * s + c)),
33
- })
34
- const add = (glyph: any) => {
17
+ for (const { glyph, place } of glyphs(op)) {
35
18
  const box = glyph.bbox
36
19
  if ([box.minX, box.minY, box.maxX, box.maxY].every(Number.isFinite)) {
37
20
  const loop = [
38
- place(pen + box.minX, box.minY),
39
- place(pen + box.maxX, box.minY),
40
- place(pen + box.maxX, box.maxY),
41
- place(pen + box.minX, box.maxY),
21
+ place(box.minX, box.minY),
22
+ place(box.maxX, box.minY),
23
+ place(box.maxX, box.maxY),
24
+ place(box.minX, box.maxY),
42
25
  ]
43
26
  if (!loop.every((p) => Number.isFinite(p.x) && Number.isFinite(p.y)))
44
27
  throw new CadError('FONT_INVALID', '文字字形范围无效:' + op.font)
45
28
  loops.push(loop)
46
29
  } else if (glyph.path.commands.length)
47
30
  throw new CadError('FONT_INVALID', '文字字形范围无效:' + op.font)
48
- if (!Number.isFinite(glyph.advanceWidth))
49
- throw new CadError('FONT_INVALID', '文字字距无效:' + op.font)
50
- pen += glyph.advanceWidth
51
- }
52
- for (const glyph of font.layout(op.text).glyphs) {
53
- if (tracking === 1) add(glyph)
54
- else {
55
- // Tracking's embedOp encodes each shaped glyph's code points again.
56
- for (const encoded of font.layout(String.fromCodePoint(...glyph.codePoints)).glyphs)
57
- add(encoded)
58
- pen += extra
59
- }
60
31
  }
61
32
  cache.set(op, loops)
62
33
  return loops
@@ -0,0 +1,92 @@
1
+ import { CadError } from '../contracts.ts'
2
+ import type { TextGlyphs, GlyphPoint } from './glyphs.ts'
3
+
4
+ export interface TextScenePrimitive {
5
+ paint: 'fill' | 'stroke'
6
+ path: string
7
+ fillRule?: 'nonzero' | 'evenodd'
8
+ font?: string
9
+ style: {
10
+ rgb: { r: number; g: number; b: number }
11
+ opacity: number
12
+ lineWidth?: number
13
+ dashArray?: number[]
14
+ exactWidth?: boolean
15
+ }
16
+ }
17
+ export type TextSceneGeometry = (
18
+ op: any,
19
+ map: (p: GlyphPoint) => GlyphPoint,
20
+ ) => TextScenePrimitive[]
21
+
22
+ const commands: Record<string, [string, number]> = {
23
+ moveTo: ['M', 2],
24
+ lineTo: ['L', 2],
25
+ quadraticCurveTo: ['Q', 4],
26
+ bezierCurveTo: ['C', 6],
27
+ closePath: ['Z', 0],
28
+ }
29
+
30
+ /** Serialize actual CAD draw operations without introducing a second layout engine. */
31
+ export function textSceneGeometry(glyphs: TextGlyphs): TextSceneGeometry {
32
+ let count = 0,
33
+ work = 0
34
+ const step = () => {
35
+ if (++work > 2_000_000) throw new CadError('SCENE_LIMIT', '文字轮廓指令超过预算')
36
+ }
37
+ const point = (p: GlyphPoint) => {
38
+ if (++count > 1_000_000) throw new CadError('SCENE_LIMIT', '文字轮廓控制点超过预算')
39
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y))
40
+ throw new CadError('FONT_INVALID', '文字轮廓坐标无效')
41
+ return p.x + ' ' + p.y
42
+ }
43
+ return (op: any, map: (p: GlyphPoint) => GlyphPoint) => {
44
+ if (op.kind === 'text') {
45
+ const paths: string[] = []
46
+ for (const { glyph, place } of glyphs(op)) {
47
+ step()
48
+ const d: string[] = []
49
+ for (const command of glyph.path.commands) {
50
+ step()
51
+ const spec = commands[command.command]
52
+ if (!spec || command.args.length !== spec[1])
53
+ throw new CadError('FONT_INVALID', '字体轮廓指令尚未支持:' + command.command)
54
+ d.push(spec[0])
55
+ for (let i = 0; i < command.args.length; i += 2)
56
+ d.push(point(map(place(command.args[i], command.args[i + 1]))))
57
+ }
58
+ if (d.length) paths.push(d.join(' '))
59
+ }
60
+ return paths.length
61
+ ? [
62
+ {
63
+ paint: 'fill',
64
+ path: paths.join(' '),
65
+ fillRule: 'nonzero',
66
+ font: op.font,
67
+ style: op.style,
68
+ },
69
+ ]
70
+ : []
71
+ }
72
+ if (op.kind === 'stroke') {
73
+ const d = op.points
74
+ .map((p: GlyphPoint, i: number) => (i ? 'L ' : 'M ') + point(map(p)))
75
+ .join(' ')
76
+ return d ? [{ paint: 'stroke', path: d + (op.closed ? ' Z' : ''), style: op.style }] : []
77
+ }
78
+ if (op.kind === 'fill') {
79
+ const d = op.loops
80
+ .filter((loop: GlyphPoint[]) => loop.length)
81
+ .map(
82
+ (loop: GlyphPoint[]) =>
83
+ loop.map((p, i) => (i ? 'L ' : 'M ') + point(map(p))).join(' ') + ' Z',
84
+ )
85
+ .join(' ')
86
+ return d
87
+ ? [{ paint: 'fill', path: d, fillRule: op.fillRule || 'nonzero', style: op.style }]
88
+ : []
89
+ }
90
+ throw new CadError('TEXT_GEOMETRY_UNSUPPORTED', '文字绘制指令需要专项适配:' + op.kind)
91
+ }
92
+ }
@@ -0,0 +1,31 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { writeFileSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import type { FontResource } from './fonts.ts'
5
+
6
+ /** Export the renderer's resolved aliases and effective bytes, including extracted TTC faces. */
7
+ export function sourceFontResources(fonts: Map<string, FontResource>, used: Set<string>, output: string) {
8
+ const sha = (bytes: Buffer) => createHash('sha256').update(bytes).digest('hex')
9
+ const artifacts: {name:string;sha256:string;bytes:number}[] = []
10
+ const entries = new Map<string, {file:string;sha256:string;sourceSha256:string;fileName:string;names:string[];faceIndex?:number}>()
11
+ for (const [alias, font] of fonts) {
12
+ if (!used.has(font.canonical) || font.kind === 'shape') continue
13
+ const digest = sha(font.bytes), key = font.canonical
14
+ let entry = entries.get(key)
15
+ if (!entry) {
16
+ const extension = font.faceIndex === undefined ? path.extname(font.file).toLowerCase() : '.ttf'
17
+ const file = `font-${digest}${extension}`
18
+ if (!artifacts.some(a => a.name === file)) {
19
+ writeFileSync(path.join(output, file), font.bytes)
20
+ artifacts.push({name:file,sha256:digest,bytes:font.bytes.length})
21
+ }
22
+ entry = {file,sha256:digest,sourceSha256:font.sha256,fileName:font.faceIndex === undefined ? path.basename(font.file) : path.parse(font.file).name + '.ttf',names:[],...(font.faceIndex === undefined ? {} : {faceIndex:font.faceIndex})}
23
+ entries.set(key, entry)
24
+ }
25
+ entry.names.push(alias)
26
+ }
27
+ const bytes = Buffer.from(JSON.stringify({version:'source-font-resources/1',fonts:[...entries.values()]}))
28
+ writeFileSync(path.join(output, 'font-resources.json'), bytes)
29
+ artifacts.push({name:'font-resources.json',sha256:sha(bytes),bytes:bytes.length})
30
+ return artifacts
31
+ }