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
@@ -2,41 +2,28 @@ import type { NativePathSegment } from 'zelos-recad/protocol/native-evidence'
2
2
  import { nativeArcParameters } from './native-circular-path.ts'
3
3
 
4
4
  /** Exact zero-width LWPOLYLINE edges, oriented in original vertex order. */
5
- export function nativeSegmentedPath(entity: any) {
6
- if (entity.dxfTypeName !== 'LWPOLYLINE' || entity.directBatchPrimitive !== 'lineStrip') return
7
- const count = entity.numberOfVertices
8
- if (!Number.isInteger(count) || count < 2 || count > 100000) return
9
- const parts = entity.subGetIntersectCurves(),
10
- size = count - (entity.closed ? 0 : 1)
11
- if (parts.length !== size || !parts.some((p: any) => p.kind === 'circArc')) return
12
- const vector = (p: any) => [p.x, p.y, p.z]
13
- const near = (a: number[], b: number[]) =>
14
- a.every((n, i) => Number.isFinite(n) && Number.isFinite(b[i]) && Math.abs(n - b[i]!) <= 1e-7)
15
- const segments: NativePathSegment[] = []
16
- for (let i = 0; i < size; i++) {
17
- const p = parts[i],
18
- from = vector(entity.getPoint3dAt(i)),
19
- to = vector(entity.getPoint3dAt((i + 1) % count))
20
- if (p.kind === 'line' && p.extent === 'bounded') {
21
- if (!near(from, vector(p.line.startPoint)) || !near(to, vector(p.line.endPoint))) return
22
- segments.push({ kind: 'line', from, to })
23
- } else if (p.kind === 'circArc') {
24
- const arc = nativeArcParameters(p.arc)
25
- if (!arc) return
26
- const at = (t: number) =>
27
- arc.center.map(
28
- (n, j) =>
29
- n +
30
- arc.axisX[j]! * Math.cos(arc.start + t * arc.sweep) +
31
- arc.axisY[j]! * Math.sin(arc.start + t * arc.sweep),
32
- )
33
- if (near(from, at(1)) && near(to, at(0))) {
34
- arc.start += arc.sweep
35
- arc.sweep = -arc.sweep
36
- }
37
- if (!near(from, at(0)) || !near(to, at(1))) return
38
- segments.push({ kind: 'arc', ...arc })
5
+ export function nativeSegmentedPath(entity:any) {
6
+ if(entity.dxfTypeName!=='LWPOLYLINE'||entity.directBatchPrimitive!=='lineStrip')return
7
+ const count=entity.numberOfVertices
8
+ if(!Number.isInteger(count)||count<2||count>100000)return
9
+ const parts=entity.subGetIntersectCurves(),size=count-(entity.closed?0:1)
10
+ if(parts.length!==size||!parts.some((p:any)=>p.kind==='circArc'))return
11
+ const vector=(p:any)=>[p.x,p.y,p.z]
12
+ const near=(a:number[],b:number[])=>a.every((n,i)=>Number.isFinite(n)&&Number.isFinite(b[i])&&Math.abs(n-b[i]!)<=1e-7)
13
+ const segments:NativePathSegment[]=[]
14
+ for(let i=0;i<size;i++) {
15
+ const p=parts[i],from=vector(entity.getPoint3dAt(i)),to=vector(entity.getPoint3dAt((i+1)%count))
16
+ if(p.kind==='line'&&p.extent==='bounded') {
17
+ if(!near(from,vector(p.line.startPoint))||!near(to,vector(p.line.endPoint)))return
18
+ segments.push({kind:'line',from,to})
19
+ } else if(p.kind==='circArc') {
20
+ const arc=nativeArcParameters(p.arc)
21
+ if(!arc)return
22
+ const at=(t:number)=>arc.center.map((n,j)=>n+arc.axisX[j]!*Math.cos(arc.start+t*arc.sweep)+arc.axisY[j]!*Math.sin(arc.start+t*arc.sweep))
23
+ if(near(from,at(1))&&near(to,at(0))) {arc.start+=arc.sweep;arc.sweep=-arc.sweep}
24
+ if(!near(from,at(0))||!near(to,at(1)))return
25
+ segments.push({kind:'arc',...arc})
39
26
  } else return
40
27
  }
41
- return { segments, closed: !!entity.closed }
28
+ return {segments,closed:!!entity.closed}
42
29
  }
@@ -0,0 +1,65 @@
1
+ import {createHash} from 'node:crypto'
2
+ import {CadError} from './contracts.ts'
3
+ import type {CadPointDictionaryEvidence} from 'zelos-recad/protocol/native-evidence'
4
+
5
+ type RecordEntry={handle:string;ownerHandle:string;kind:'DICTIONARY'|'XRECORD';entries?:{name:string;handle:string}[];raw:unknown}
6
+ type PointEntry={handle:string;dictionaries:string[]}
7
+ const handle=(value:unknown)=>String(value||'').toUpperCase()
8
+
9
+ /** Retain the complete owner tree as source data; no vendor electrical meaning is inferred. */
10
+ function capture(points:PointEntry[],records:RecordEntry[],sourceSha256:string):CadPointDictionaryEvidence[]{
11
+ const index=new Map(records.map(record=>[record.handle,record]))
12
+ if(index.size!==records.length)throw new CadError('POINT_DICTIONARY','POINT字典记录句柄重复')
13
+ return points.filter(point=>point.dictionaries.length).map(point=>{
14
+ const visited=new Set<string>(),closure:RecordEntry[]=[]
15
+ function visit(id:string,owner:string){
16
+ const record=index.get(id)
17
+ if(!record||record.ownerHandle!==owner||visited.has(id))throw new CadError('POINT_DICTIONARY','POINT字典闭包缺件、所属或循环引用异常',{point:point.handle,handle:id,owner})
18
+ visited.add(id);closure.push(record)
19
+ if(record.kind==='DICTIONARY')for(const entry of record.entries!)visit(entry.handle,id)
20
+ }
21
+ for(const id of point.dictionaries){
22
+ if(index.get(id)?.kind!=='DICTIONARY')throw new CadError('POINT_DICTIONARY','POINT扩展根需要字典记录',{point:point.handle,handle:id})
23
+ visit(id,point.handle)
24
+ }
25
+ const recordsJson=JSON.stringify(closure,(_key,value)=>{
26
+ if(typeof value==='number'&&!Number.isFinite(value))throw new CadError('POINT_DICTIONARY','POINT字典存在非有限数值')
27
+ return value
28
+ })
29
+ return {format:'XDTrace.NativePointDictionaryEvidence/1',sourceSha256,pointHandle:point.handle,dictionaryHandles:point.dictionaries,
30
+ semanticStatus:'uninterpreted',recordsJson,sha256:createHash('sha256').update(recordsJson).digest('hex')}
31
+ })
32
+ }
33
+
34
+ export function captureDwgPointDictionaries(model:any,sourceSha256:string){
35
+ const entities=[...model.entities,...model.tables.BLOCK_RECORD.entries.flatMap((b:any)=>b.entities)]
36
+ const points=[...new Map(entities.filter((e:any)=>e.type==='POINT').map((e:any)=>[handle(e.handle),e])).values()] as any[]
37
+ if(!points.some(e=>e.ownerDictionaryHardId&&e.ownerDictionaryHardId!=='0'))return []
38
+ const dictionaries:RecordEntry[]=model.objects.DICTIONARY.map((raw:any)=>({kind:'DICTIONARY',handle:handle(raw.handle),ownerHandle:handle(raw.ownerHandle),raw,
39
+ entries:Object.entries(raw.entries).map(([name,id])=>({name,handle:handle(id)}))}))
40
+ const records:RecordEntry[]=(model.objects.XRECORD||[]).map((raw:any)=>({kind:'XRECORD',handle:handle(raw.handle),ownerHandle:handle(raw.ownerHandle),raw}))
41
+ return capture(points.map(e=>({handle:handle(e.handle),dictionaries:e.ownerDictionaryHardId&&e.ownerDictionaryHardId!=='0'?[handle(e.ownerDictionaryHardId)]:[]})),[...dictionaries,...records],sourceSha256)
42
+ }
43
+
44
+ type DxfRecord={type:string;pairs:{code:number;value:string;rawValue?:string}[]}
45
+ export function captureDxfPointDictionaries(input:DxfRecord[],sourceSha256:string){
46
+ const value=(r:DxfRecord,code:number)=>{
47
+ let depth=0
48
+ for(const p of r.pairs){if(p.code===102){if(p.value.startsWith('{'))depth++;else if(p.value==='}')depth--;continue}if(!depth&&p.code===code)return p.value}
49
+ }
50
+ const points=input.filter(r=>r.type==='POINT').map(r=>{
51
+ const dictionaries:string[]=[];let inside=false
52
+ for(const p of r.pairs){if(p.code===102){inside=p.value==='{ACAD_XDICTIONARY';continue}if(inside&&p.code===360)dictionaries.push(handle(p.value))}
53
+ return {handle:handle(value(r,5)),dictionaries}
54
+ })
55
+ if(!points.some(p=>p.dictionaries.length))return []
56
+ const records:RecordEntry[]=input.filter(r=>r.type==='DICTIONARY'||r.type==='XRECORD').map(r=>{
57
+ const entries:{name:string;handle:string}[]=[]
58
+ if(r.type==='DICTIONARY')for(const [i,p] of r.pairs.entries())if(p.code===3){
59
+ const ref=r.pairs[i+1];if(!ref||![350,360].includes(ref.code))throw new CadError('POINT_DICTIONARY','DXF字典条目缺少句柄')
60
+ entries.push({name:p.value,handle:handle(ref.value)})
61
+ }
62
+ return {kind:r.type as RecordEntry['kind'],handle:handle(value(r,5)),ownerHandle:handle(value(r,330)),raw:r.pairs.map(({code,value,rawValue})=>({code,value:rawValue??value})),...(r.type==='DICTIONARY'?{entries}:{})}
63
+ })
64
+ return capture(points,records,sourceSha256)
65
+ }
@@ -8,7 +8,7 @@ const { AcDbDxfFiler } = createRequire(import.meta.url)('@mlightcad/data-model')
8
8
  * database writer currently allocates colliding object handles. Consumers must
9
9
  * allocate fresh handles and compare geometry and GROUP membership explicitly.
10
10
  */
11
- export function readbackSnapshot(db: any, sourceSha256: string, textSize: number) {
11
+ export function readbackSnapshot(db: any, sourceSha256: string, textSize: number, source?:{block:any;blocks:any[];layout:string}) {
12
12
  const record = (item: any, type: string) => {
13
13
  item = item.xdtraceReadbackOriginal ?? item
14
14
  const filer = new AcDbDxfFiler({ database: db, precision: 16, version: 'AC1032' })
@@ -60,21 +60,22 @@ export function readbackSnapshot(db: any, sourceSha256: string, textSize: number
60
60
  return { handle: String(item.objectId).toUpperCase(), type, dxf: filer.toString() }
61
61
  }
62
62
  const blocks = [...db.tables.blockTable.newIterator()]
63
- const model = db.tables.blockTable.modelSpace
63
+ const model = source?.block || db.tables.blockTable.modelSpace
64
64
  const modelRecords = [...model.newIterator()]
65
65
  const definitions = blocks.filter(
66
- (block: any) => block !== model && !block.name.toUpperCase().startsWith('*PAPER_SPACE'),
66
+ (block: any) => block !== model && block!==db.tables.blockTable.modelSpace && !block.name.toUpperCase().startsWith('*PAPER_SPACE') && (!source||source.blocks.includes(block)),
67
67
  )
68
68
  for (const block of blocks) {
69
- if (block.name.toUpperCase().startsWith('*PAPER_SPACE') && [...block.newIterator()].length)
69
+ if (!source && block.name.toUpperCase().startsWith('*PAPER_SPACE') && [...block.newIterator()].length)
70
70
  throw new CadError('READBACK_LAYOUT', '最终二维交付不能包含未映射的图纸空间实体')
71
- if (block.isXref || block.isUnresolvedXref)
71
+ if ((!source||source.blocks.includes(block))&&(block.isXref || block.isUnresolvedXref))
72
72
  throw new CadError('READBACK_XREF', '最终交付必须自包含,不能引用外部图纸')
73
73
  }
74
74
  return {
75
75
  format: 'XDTrace.RecadReadback',
76
76
  version: 1,
77
77
  sourceSha256,
78
+ ...(source?{sourceSelection:{layout:source.layout,handles:modelRecords.map((r:any)=>String(r.objectId).toUpperCase())}}:{}),
78
79
  header: {
79
80
  $INSUNITS: db.insunits,
80
81
  $LTSCALE: db.ltscale,
@@ -96,7 +97,7 @@ export function readbackSnapshot(db: any, sourceSha256: string, textSize: number
96
97
  ),
97
98
  styles: [...db.tables.textStyleTable.newIterator()].map((item: any) => record(item, 'STYLE')),
98
99
  },
99
- groups: [...db.objects.group.entries()].map(([name, group]: any) => ({
100
+ groups: [...db.objects.group.entries()].filter(([,group]:any)=>!source||[...group.entityIds].every(id=>modelRecords.some((r:any)=>String(r.objectId)===String(id)))).map(([name, group]: any) => ({
100
101
  ...record(group, 'GROUP'),
101
102
  name,
102
103
  description: group.name,
@@ -12,11 +12,14 @@ import { alignDwgDictionaries } from './dwg-dictionaries.ts'
12
12
  import { inspectDxf } from './dxf.ts'
13
13
  import { installReaderAdapters } from './reader-adapters.ts'
14
14
  import { captureNativeEvidence } from './native-evidence.ts'
15
+ import {captureCcObjects,validateCcOwnership} from './vendor-object-data.ts'
16
+ import {captureDwgPointDictionaries,captureDxfPointDictionaries} from './point-dictionaries.ts'
15
17
  import {
16
18
  createDwgDecoder,
17
19
  readDwgBytes,
18
20
  dwgErrorFlags,
19
21
  normalizeDwgLineweights,
22
+ normalizeDwgLayerPlotFlags,
20
23
  convertDwgWithArrays,
21
24
  } from './dwg.ts'
22
25
  import { captureDwgLineTypes } from './line-type.ts'
@@ -34,7 +37,7 @@ const { AcDbLibreDwgConverter } = require('@mlightcad/libredwg-converter')
34
37
 
35
38
  /** Read with the same independent decoder for root drawings and bundled dependencies.
36
39
  * Keep omitted source fields until all references have been rebound. */
37
- export async function readDrawing(source: string, recover = false, nativeEvidence = false) {
40
+ export async function readDrawing(source: string, recover = false, nativeEvidence = false, retainPointDictionaries = false) {
38
41
  const inputStat = statSync(source)
39
42
  if (!inputStat.isFile() || !inputStat.size || inputStat.size > CAD_INPUT_LIMITS.inputBytes)
40
43
  throw new CadError('INPUT_SIZE', 'CAD 输入必须是 1 字节至 200 MiB 的普通文件')
@@ -47,7 +50,9 @@ export async function readDrawing(source: string, recover = false, nativeEvidenc
47
50
  const isDwg = extension === '.dwg'
48
51
  if (isDwg && !/^AC10\d{2}$/.test(original.subarray(0, 6).toString('ascii')))
49
52
  throw new CadError('INPUT_FORMAT', 'DWG 文件头无效')
50
- const dxf = isDwg ? undefined : inspectDxf(original)
53
+ const retainPoints=nativeEvidence||retainPointDictionaries
54
+ const dxf = isDwg ? undefined : inspectDxf(original,retainPoints)
55
+ let pointDictionaries=dxf?.pointDictionaryRecords?captureDxfPointDictionaries(dxf.pointDictionaryRecords,sourceSha256):[]
51
56
  const bytes = dxf?.bytes || original
52
57
  let dwgStats: any
53
58
  let decodeIssues: any[] = []
@@ -107,7 +112,7 @@ export async function readDrawing(source: string, recover = false, nativeEvidenc
107
112
  throw dwgFailure
108
113
  }
109
114
  constraintGroups = captureConstraintGroups(module, pointer, sourceSha256, recover)
110
- applicationObjects = captureApplicationObjects(module, pointer, sourceSha256)
115
+ applicationObjects = [...captureApplicationObjects(module, pointer, sourceSha256),...captureCcObjects(module,pointer,original,sourceSha256,lib.dwg_get_codepage(pointer))]
111
116
  let result: ReturnType<typeof convertDwgWithArrays>
112
117
  try {
113
118
  result = convertDwgWithArrays(
@@ -124,6 +129,10 @@ export async function readDrawing(source: string, recover = false, nativeEvidenc
124
129
  })
125
130
  }
126
131
  validateApplicationOwnership(applicationObjects, result.database)
132
+ validateCcOwnership(applicationObjects,result.database)
133
+ if(retainPoints)pointDictionaries=captureDwgPointDictionaries(result.database,sourceSha256)
134
+ const retained=new Set(applicationObjects.filter(r=>r.disposition==='retained-data').map(r=>r.handle))
135
+ decodeIssues=decodeIssues.map(issue=>retained.has(issue.handle)?{...issue,retainedApplicationData:true}:issue)
127
136
  captureDwgLeaders(result.database, lib, pointer)
128
137
  dwgViewports = captureDwgViewports(result.database, lib, pointer)
129
138
  const header = result.database.header
@@ -211,6 +220,7 @@ export async function readDrawing(source: string, recover = false, nativeEvidenc
211
220
  classified.filters,
212
221
  )
213
222
  normalizeDwgLineweights(result.database)
223
+ normalizeDwgLayerPlotFlags(result.database,original.subarray(0,6).toString('ascii'))
214
224
  captureDwgTextStyles(result.database, lib, module, pointer)
215
225
  captureDwgLineTypes(result.database, lib, pointer)
216
226
  dwgImages = captureDwgImages(result.database, lib, pointer)
@@ -270,13 +280,11 @@ export async function readDrawing(source: string, recover = false, nativeEvidenc
270
280
  )
271
281
  }
272
282
  for (const item of blockMetadata.values()) item.sourceSha256 = sourceSha256
273
- const nativeCapture = nativeEvidence
274
- ? captureNativeEvidence(db, sourceSha256, {
275
- textFields: dxf?.textFields ?? dwgTextFields,
276
- expected: dxf?.expected,
277
- decodeIssues,
278
- })
279
- : undefined
283
+ const nativeCapture = nativeEvidence ? captureNativeEvidence(db, sourceSha256, {
284
+ textFields: dxf?.textFields ?? dwgTextFields, expected: dxf?.expected, decodeIssues,
285
+ }) : undefined
286
+ if(nativeCapture&&applicationObjects.length)nativeCapture.documents[0]!.applicationObjects=structuredClone(applicationObjects)
287
+ if(nativeCapture&&pointDictionaries.length)nativeCapture.documents[0]!.pointDictionaries=pointDictionaries
280
288
  return {
281
289
  db,
282
290
  nativeCapture,
@@ -288,6 +296,7 @@ export async function readDrawing(source: string, recover = false, nativeEvidenc
288
296
  decodeIssues,
289
297
  constraintGroups,
290
298
  applicationObjects,
299
+ pointDictionaries,
291
300
  dwgDecoder,
292
301
  dwgTextRecoveries,
293
302
  dwgTextWarnings,
@@ -4,7 +4,12 @@ import path from 'node:path'
4
4
  import { createRequire } from 'node:module'
5
5
  import { collectedBounds } from './layout-bounds.ts'
6
6
  import { suggestPlotRegions } from './plot-regions.ts'
7
- import { sourceScene } from './source-scene.ts'
7
+ import { sourceScene, sceneJsonBytes } from './source-scene.ts'
8
+ import { sceneNativeDocuments } from './native-evidence.ts'
9
+ import { nativeEvidenceSummary } from 'zelos-recad/protocol/native-evidence'
10
+ import { textGlyphs } from './text/glyphs.ts'
11
+ import { textSceneGeometry } from './text/scene-geometry.ts'
12
+ import { sourceFontResources } from './text/source-fonts.ts'
8
13
  import { selectedSpace, viewportRoots } from './layouts.ts'
9
14
  import { textInkBounds } from './text/ink-bounds.ts'
10
15
  import { installTextAffineWriter } from './text/affine-writer.ts'
@@ -81,8 +86,8 @@ export async function renderCad(context: RenderContext) {
81
86
  for (const entity of allRecords)
82
87
  if (!activeHandles.has(String(entity.objectId).toUpperCase()))
83
88
  entity.worldDraw = () => undefined
84
- const print =
85
- request.operation === 'render'
89
+ let print =
90
+ request.operation === 'render' && request.print !== 'auto'
86
91
  ? request.print
87
92
  : renderSchema.parse({
88
93
  paperWidthMm: 297,
@@ -90,7 +95,7 @@ export async function renderCad(context: RenderContext) {
90
95
  window: { min: { x: 0, y: 0 }, max: { x: 297, y: 210 } },
91
96
  png: false,
92
97
  })
93
- const plan = createPrintPlan(print)
98
+ let plan = createPrintPlan(print)
94
99
  installLineEndPolicy(print)
95
100
  const blockingWarnings = warnings.filter(
96
101
  (w) => !(recover && w.code === 'CONSTRAINT_SAVED_GEOMETRY'),
@@ -322,7 +327,7 @@ export async function renderCad(context: RenderContext) {
322
327
  renderer.ltscale = db.ltscale
323
328
  renderer.celtscale = db.celtscale
324
329
  renderer.showLineWeight = true
325
- renderer.configureExport({
330
+ const exportOptions = {
326
331
  paper: { widthMm: plan.nativePageMm.width, heightMm: plan.nativePageMm.height },
327
332
  fitBox: identityPaperFrame(plan),
328
333
  background: 'none',
@@ -346,7 +351,8 @@ export async function renderCad(context: RenderContext) {
346
351
  throw new CadError('SHAPE_UNSUPPORTED', 'SHX/SHAPE 字形引擎尚未接入')
347
352
  },
348
353
  },
349
- })
354
+ }
355
+ renderer.configureExport(exportOptions)
350
356
  renderer.textFontManager = fontManager
351
357
  renderer.currentBackgroundColor = 0xffffff
352
358
  renderer.changeForeground(0x000000)
@@ -428,7 +434,8 @@ export async function renderCad(context: RenderContext) {
428
434
  throw new CadError('IMAGE_LOSS', '图片未完整进入 PDF 绘制指令')
429
435
  if (!settled) throw new CadError('RENDER_UNSETTLED', '嵌套图形或字体未完成加载')
430
436
  const bounds = { min: { x: Infinity, y: Infinity }, max: { x: -Infinity, y: -Infinity } }
431
- const textInk = textInkBounds(fontManager)
437
+ const glyphs = textGlyphs(fontManager)
438
+ const textInk = textInkBounds(glyphs)
432
439
  report.layoutObjects = []
433
440
  for (const root of roots) {
434
441
  if (root.box.isEmpty()) continue
@@ -474,6 +481,8 @@ export async function renderCad(context: RenderContext) {
474
481
  report.resourcesManifestSha256 = assets.manifestSha256
475
482
  report.images = [...assets.images].map(([name, e]) => ({ name, sha256: e.sha256 }))
476
483
  if (request.operation === 'scene') {
484
+ if (request.fontResources)
485
+ report.artifacts.push(...sourceFontResources(assets.fonts, new Set(usedFonts.keys()), options.output))
477
486
  const scene = sourceScene(
478
487
  roots,
479
488
  db,
@@ -481,6 +490,7 @@ export async function renderCad(context: RenderContext) {
481
490
  {
482
491
  layout: selection.selected.name,
483
492
  space: selection.selected,
493
+ sheetMode: request.sheetMode,
484
494
  sourceSha256,
485
495
  engine: report.engine,
486
496
  resourcesManifestSha256: assets.manifestSha256,
@@ -491,8 +501,21 @@ export async function renderCad(context: RenderContext) {
491
501
  textOmissions: report.textOmissions,
492
502
  },
493
503
  drawing.nativeCapture,
504
+ request.textGeometry ? textSceneGeometry(glyphs) : undefined,
494
505
  )
495
506
  const file = path.join(options.output, 'scene.json')
507
+ const beforeBytes = sceneJsonBytes(scene)
508
+ if (beforeBytes > 160 * 1024 * 1024 && scene.nativeEvidence) {
509
+ scene.nativeEvidence.documents = sceneNativeDocuments(
510
+ scene.nativeEvidence.documents,
511
+ scene.nativeEvidence.instances.map((instance: { recordId: string }) => instance.recordId),
512
+ )
513
+ nativeEvidenceSummary(scene, sourceSha256)
514
+ if (drawing.nativeCapture) drawing.nativeCapture.documents = scene.nativeEvidence.documents
515
+ report.nativeSceneSelection = { basis: 'scene-referenced-block-closure', beforeBytes, afterBytes: sceneJsonBytes(scene) }
516
+ }
517
+ if ((report.nativeSceneSelection?.afterBytes ?? beforeBytes) > 160 * 1024 * 1024)
518
+ throw new CadError('SCENE_LIMIT', '源场景超过 160 MiB 成果预算')
496
519
  const bytes = Buffer.from(JSON.stringify(scene))
497
520
  if (bytes.length > 160 * 1024 * 1024)
498
521
  throw new CadError('SCENE_LIMIT', '源场景超过 160 MiB 成果预算')
@@ -502,6 +525,15 @@ export async function renderCad(context: RenderContext) {
502
525
  }
503
526
  return
504
527
  }
528
+ if (request.operation === 'render' && request.print === 'auto') {
529
+ print = renderSchema.parse(report.suggestedPrint.overview)
530
+ plan = createPrintPlan(print)
531
+ renderer.configureExport({ ...exportOptions,
532
+ paper: { widthMm: plan.nativePageMm.width, heightMm: plan.nativePageMm.height },
533
+ fitBox: identityPaperFrame(plan),
534
+ })
535
+ }
536
+ report.printSelection = request.operation === 'render' && request.print === 'auto' ? 'auto-overview' : 'explicit'
505
537
  const prepared = preparePlotRoots(roots, db, plan)
506
538
  report.excludedFromPlot = prepared.excluded
507
539
  const boundPlan = {
@@ -1,4 +1,5 @@
1
- import { spawn, execFile } from 'node:child_process'
1
+ import { execFile } from 'node:child_process'
2
+ import { spawnTemporary } from '../shared/service-storage/src/process-temp.ts'
2
3
  import { readFileSync, appendFileSync, mkdirSync, renameSync, statSync } from 'node:fs'
3
4
  import path from 'node:path'
4
5
  import { fileURLToPath } from 'node:url'
@@ -10,7 +11,7 @@ import { runtimePython } from './runtime-paths.ts'
10
11
  import {
11
12
  cadErrorRecord,
12
13
  classifyDwgFailure,
13
- drawingArtifacts,
14
+ isDrawingArtifact,
14
15
  type FallbackReceipt,
15
16
  type ArtifactReceipt,
16
17
  } from './dwg-fallback.ts'
@@ -140,7 +141,7 @@ export function createWorkerRunner(executePhase: WorkerExecutor = runWorkerOnce)
140
141
  unchanged()
141
142
  remaining()
142
143
  for (const artifact of result.artifacts as ArtifactReceipt[]) {
143
- if (!drawingArtifacts.includes(artifact.name))
144
+ if (!isDrawingArtifact(artifact.name))
144
145
  throw new CadError('ARTIFACT_NAME', '工作进程返回了未知成果')
145
146
  const file = path.join(readDir, artifact.name)
146
147
  if (hashFile(file) !== artifact.sha256 || statSync(file).size !== artifact.bytes)
@@ -212,7 +213,7 @@ export async function runWorkerOnce(
212
213
  const entry = fileURLToPath(
213
214
  new URL(import.meta.url.endsWith('.ts') ? './worker.ts' : './worker.js', import.meta.url),
214
215
  )
215
- const child = spawn(
216
+ const child = spawnTemporary(options.output)(
216
217
  process.execPath,
217
218
  [
218
219
  '--max-old-space-size=768',
@@ -1,153 +1,34 @@
1
- import {
2
- createWriteStream,
3
- mkdirSync,
4
- readFileSync,
5
- existsSync,
6
- lstatSync,
7
- readdirSync,
8
- rmSync,
9
- } from 'node:fs'
10
- import { createHash, randomUUID } from 'node:crypto'
11
- import { Transform, type Readable } from 'node:stream'
12
- import { pipeline } from 'node:stream/promises'
13
- import path from 'node:path'
14
- import { CadError, CAD_INPUT_LIMITS as limits } from 'zelos-recad/protocol'
15
- import { atomicJson, checkedId, directoryBytes, jobIdPattern as idPattern } from './storage.ts'
1
+ import { DocumentStore as SharedDocumentStore, type StoredDocument } from '../../shared/service-storage/src/documents.ts'
2
+ import type { StorageQuota } from '../../shared/service-storage/src/quota.ts'
3
+ import type { Readable } from 'node:stream'
4
+ import { CadError, CAD_INPUT_LIMITS } from '../contracts.ts'
16
5
 
17
- export interface StoredDocument {
18
- id: string
19
- path: string
20
- bytes: number
21
- sha256: string
22
- fileName: string
23
- accessedAt: number
24
- }
25
- export class DocumentStore {
26
- readonly root: string
6
+ export type { StoredDocument } from '../../shared/service-storage/src/documents.ts'
7
+
8
+ /** Shared document persistence; the public runtime owns upload cancellation and close. */
9
+ export class DocumentStore extends SharedDocumentStore {
27
10
  private closed = false
28
11
  private readonly uploads = new Map<Readable, Promise<StoredDocument>>()
29
- private timer: ReturnType<typeof setInterval>
30
- constructor(
31
- private data: string,
32
- private retentionMs = 2 * 86400000,
33
- private maxStorageBytes = 0,
34
- ) {
35
- this.root = path.join(data, '.documents')
36
- mkdirSync(this.root, { recursive: true })
37
- if (lstatSync(this.root).isSymbolicLink())
38
- throw new CadError('STORAGE_LINK', 'CAD 文档目录包含链接')
39
- this.timer = setInterval(() => this.cleanup(), 60000)
40
- this.timer.unref()
41
- }
42
- async close() {
43
- this.closed = true
44
- clearInterval(this.timer)
45
- for (const stream of this.uploads.keys())
46
- stream.destroy(new CadError('SERVICE_CLOSING', '文档存储正在关闭'))
47
- await Promise.allSettled(this.uploads.values())
48
- }
49
- get(id: string): StoredDocument {
50
- const folder = path.join(this.root, checkedId(id)),
51
- file = path.join(folder, 'source.bin'),
52
- receipt = path.join(folder, 'document.json')
53
- if (!existsSync(receipt)) throw new CadError('DOCUMENT_EXPIRED', 'CAD 文档已过期,请重新上传')
54
- if (
55
- [folder, file, receipt].some((p) => lstatSync(p).isSymbolicLink()) ||
56
- !lstatSync(file).isFile()
57
- )
58
- throw new CadError('STORAGE_LINK', 'CAD 文档路径包含链接')
59
- const stored = JSON.parse(readFileSync(receipt, 'utf8')) as StoredDocument
60
- if (
61
- stored.id !== id ||
62
- stored.bytes !== lstatSync(file).size ||
63
- !/^[a-f0-9]{64}$/.test(stored.sha256)
64
- )
65
- throw new CadError('DOCUMENT_CHANGED', 'CAD 文档登记不一致')
66
- stored.path = file
67
- stored.accessedAt = Date.now()
68
- atomicJson(receipt, stored)
69
- return stored
12
+
13
+ constructor(data: string, retentionMs?: number, maxStorageBytes?: number, quota?: StorageQuota) {
14
+ super(data, {
15
+ sourceName: 'source.bin', defaultName: 'source.dxf',
16
+ fileName: /^[^\\/:\x00-\x1f]{1,180}\.(dwg|dxf)$/i,
17
+ inputBytes: CAD_INPUT_LIMITS.inputBytes,
18
+ }, retentionMs, maxStorageBytes, quota)
70
19
  }
71
- upload(stream: Readable, fileName?: string) {
20
+
21
+ override upload(stream: Readable, fileName?: string) {
72
22
  if (this.closed) throw new CadError('SERVICE_CLOSING', '文档存储正在关闭')
73
- const operation = this.performUpload(stream, fileName).finally(() =>
74
- this.uploads.delete(stream),
75
- )
23
+ const operation = super.upload(stream, fileName).finally(() => this.uploads.delete(stream))
76
24
  this.uploads.set(stream, operation)
77
25
  return operation
78
26
  }
79
27
 
80
- private async performUpload(stream: Readable, fileName = 'source.dxf') {
81
- if (!/^[^\\/:\x00-\x1f]{1,180}\.(dwg|dxf)$/i.test(fileName))
82
- throw new CadError('INPUT_NAME', '请提供 CAD 文件名')
83
- const id = randomUUID(),
84
- folder = path.join(this.root, id),
85
- file = path.join(folder, 'source.bin')
86
- mkdirSync(folder)
87
- let bytes = 0
88
- const digest = createHash('sha256')
89
- const budget = this.maxStorageBytes
90
- ? this.maxStorageBytes - directoryBytes(this.data)
91
- : Infinity
92
- const counter = new Transform({
93
- transform(chunk: Buffer, _encoding, callback) {
94
- bytes += chunk.length
95
- if (bytes > limits.inputBytes)
96
- return callback(
97
- Object.assign(new CadError('INPUT_SIZE', '每个 CAD 源文件最大 200 MiB'), {
98
- statusCode: 413,
99
- }),
100
- )
101
- if (bytes > budget)
102
- return callback(
103
- Object.assign(new CadError('STORAGE_FULL', 'CAD 服务存储容量不足'), {
104
- statusCode: 507,
105
- }),
106
- )
107
- digest.update(chunk)
108
- callback(null, chunk)
109
- },
110
- })
111
- try {
112
- await pipeline(stream, counter, createWriteStream(file, { flags: 'wx' }))
113
- if (!bytes) throw new CadError('INPUT_FORMAT', '请选择有效的 CAD 文件')
114
- const stored: StoredDocument = {
115
- id,
116
- path: file,
117
- bytes,
118
- sha256: digest.digest('hex'),
119
- fileName,
120
- accessedAt: Date.now(),
121
- }
122
- atomicJson(path.join(folder, 'document.json'), stored)
123
- return stored
124
- } catch (error) {
125
- // folder is a UUID child created by this operation beneath the validated root.
126
- if (path.dirname(folder) === this.root && !lstatSync(folder).isSymbolicLink())
127
- rmSync(folder, { recursive: true, force: true })
128
- throw error
129
- }
130
- }
131
- private cleanup() {
132
- for (const id of readdirSync(this.root)) {
133
- if (!idPattern.test(id)) continue
134
- const folder = path.join(this.root, id),
135
- receipt = path.join(folder, 'document.json')
136
- try {
137
- if (lstatSync(folder).isSymbolicLink() || !existsSync(receipt)) continue
138
- const value = JSON.parse(readFileSync(receipt, 'utf8'))
139
- if (
140
- value.id === id &&
141
- Number.isFinite(value.accessedAt) &&
142
- Date.now() - value.accessedAt > this.retentionMs &&
143
- path.dirname(folder) === this.root
144
- ) {
145
- directoryBytes(folder) // validate descendants before recursive cleanup
146
- rmSync(folder, { recursive: true })
147
- }
148
- } catch {
149
- /* a corrupt registration is retained for diagnosis */
150
- }
151
- }
28
+ override async close() {
29
+ this.closed = true
30
+ super.close()
31
+ for (const stream of this.uploads.keys()) stream.destroy(new CadError('SERVICE_CLOSING', '文档存储正在关闭'))
32
+ await Promise.allSettled(this.uploads.values())
152
33
  }
153
34
  }