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
@@ -1,127 +1,28 @@
1
- import { createWriteStream, mkdirSync, readFileSync, existsSync, lstatSync, readdirSync, rmSync, } from 'node:fs';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { Transform } from 'node:stream';
4
- import { pipeline } from 'node:stream/promises';
5
- import path from 'node:path';
6
- import { CadError, CAD_INPUT_LIMITS as limits } from 'zelos-recad/protocol';
7
- import { atomicJson, checkedId, directoryBytes, jobIdPattern as idPattern } from "./storage.js";
8
- export class DocumentStore {
9
- data;
10
- retentionMs;
11
- maxStorageBytes;
12
- root;
1
+ import { DocumentStore as SharedDocumentStore } from "../../shared/service-storage/src/documents.js";
2
+ import { CadError, CAD_INPUT_LIMITS } from "../contracts.js";
3
+ /** Shared document persistence; the public runtime owns upload cancellation and close. */
4
+ export class DocumentStore extends SharedDocumentStore {
13
5
  closed = false;
14
6
  uploads = new Map();
15
- timer;
16
- constructor(data, retentionMs = 2 * 86400000, maxStorageBytes = 0) {
17
- this.data = data;
18
- this.retentionMs = retentionMs;
19
- this.maxStorageBytes = maxStorageBytes;
20
- this.root = path.join(data, '.documents');
21
- mkdirSync(this.root, { recursive: true });
22
- if (lstatSync(this.root).isSymbolicLink())
23
- throw new CadError('STORAGE_LINK', 'CAD 文档目录包含链接');
24
- this.timer = setInterval(() => this.cleanup(), 60000);
25
- this.timer.unref();
26
- }
27
- async close() {
28
- this.closed = true;
29
- clearInterval(this.timer);
30
- for (const stream of this.uploads.keys())
31
- stream.destroy(new CadError('SERVICE_CLOSING', '文档存储正在关闭'));
32
- await Promise.allSettled(this.uploads.values());
33
- }
34
- get(id) {
35
- const folder = path.join(this.root, checkedId(id)), file = path.join(folder, 'source.bin'), receipt = path.join(folder, 'document.json');
36
- if (!existsSync(receipt))
37
- throw new CadError('DOCUMENT_EXPIRED', 'CAD 文档已过期,请重新上传');
38
- if ([folder, file, receipt].some((p) => lstatSync(p).isSymbolicLink()) ||
39
- !lstatSync(file).isFile())
40
- throw new CadError('STORAGE_LINK', 'CAD 文档路径包含链接');
41
- const stored = JSON.parse(readFileSync(receipt, 'utf8'));
42
- if (stored.id !== id ||
43
- stored.bytes !== lstatSync(file).size ||
44
- !/^[a-f0-9]{64}$/.test(stored.sha256))
45
- throw new CadError('DOCUMENT_CHANGED', 'CAD 文档登记不一致');
46
- stored.path = file;
47
- stored.accessedAt = Date.now();
48
- atomicJson(receipt, stored);
49
- return stored;
7
+ constructor(data, retentionMs, maxStorageBytes, quota) {
8
+ super(data, {
9
+ sourceName: 'source.bin', defaultName: 'source.dxf',
10
+ fileName: /^[^\\/:\x00-\x1f]{1,180}\.(dwg|dxf)$/i,
11
+ inputBytes: CAD_INPUT_LIMITS.inputBytes,
12
+ }, retentionMs, maxStorageBytes, quota);
50
13
  }
51
14
  upload(stream, fileName) {
52
15
  if (this.closed)
53
16
  throw new CadError('SERVICE_CLOSING', '文档存储正在关闭');
54
- const operation = this.performUpload(stream, fileName).finally(() => this.uploads.delete(stream));
17
+ const operation = super.upload(stream, fileName).finally(() => this.uploads.delete(stream));
55
18
  this.uploads.set(stream, operation);
56
19
  return operation;
57
20
  }
58
- async performUpload(stream, fileName = 'source.dxf') {
59
- if (!/^[^\\/:\x00-\x1f]{1,180}\.(dwg|dxf)$/i.test(fileName))
60
- throw new CadError('INPUT_NAME', '请提供 CAD 文件名');
61
- const id = randomUUID(), folder = path.join(this.root, id), file = path.join(folder, 'source.bin');
62
- mkdirSync(folder);
63
- let bytes = 0;
64
- const digest = createHash('sha256');
65
- const budget = this.maxStorageBytes
66
- ? this.maxStorageBytes - directoryBytes(this.data)
67
- : Infinity;
68
- const counter = new Transform({
69
- transform(chunk, _encoding, callback) {
70
- bytes += chunk.length;
71
- if (bytes > limits.inputBytes)
72
- return callback(Object.assign(new CadError('INPUT_SIZE', '每个 CAD 源文件最大 200 MiB'), {
73
- statusCode: 413,
74
- }));
75
- if (bytes > budget)
76
- return callback(Object.assign(new CadError('STORAGE_FULL', 'CAD 服务存储容量不足'), {
77
- statusCode: 507,
78
- }));
79
- digest.update(chunk);
80
- callback(null, chunk);
81
- },
82
- });
83
- try {
84
- await pipeline(stream, counter, createWriteStream(file, { flags: 'wx' }));
85
- if (!bytes)
86
- throw new CadError('INPUT_FORMAT', '请选择有效的 CAD 文件');
87
- const stored = {
88
- id,
89
- path: file,
90
- bytes,
91
- sha256: digest.digest('hex'),
92
- fileName,
93
- accessedAt: Date.now(),
94
- };
95
- atomicJson(path.join(folder, 'document.json'), stored);
96
- return stored;
97
- }
98
- catch (error) {
99
- // folder is a UUID child created by this operation beneath the validated root.
100
- if (path.dirname(folder) === this.root && !lstatSync(folder).isSymbolicLink())
101
- rmSync(folder, { recursive: true, force: true });
102
- throw error;
103
- }
104
- }
105
- cleanup() {
106
- for (const id of readdirSync(this.root)) {
107
- if (!idPattern.test(id))
108
- continue;
109
- const folder = path.join(this.root, id), receipt = path.join(folder, 'document.json');
110
- try {
111
- if (lstatSync(folder).isSymbolicLink() || !existsSync(receipt))
112
- continue;
113
- const value = JSON.parse(readFileSync(receipt, 'utf8'));
114
- if (value.id === id &&
115
- Number.isFinite(value.accessedAt) &&
116
- Date.now() - value.accessedAt > this.retentionMs &&
117
- path.dirname(folder) === this.root) {
118
- directoryBytes(folder); // validate descendants before recursive cleanup
119
- rmSync(folder, { recursive: true });
120
- }
121
- }
122
- catch {
123
- /* a corrupt registration is retained for diagnosis */
124
- }
125
- }
21
+ async close() {
22
+ this.closed = true;
23
+ super.close();
24
+ for (const stream of this.uploads.keys())
25
+ stream.destroy(new CadError('SERVICE_CLOSING', '文档存储正在关闭'));
26
+ await Promise.allSettled(this.uploads.values());
126
27
  }
127
28
  }
@@ -2,6 +2,8 @@ import type { Readable } from 'node:stream';
2
2
  import { type ArtifactReceipt } from '../dwg-fallback.js';
3
3
  import { type RuntimeOptions } from './jobs.js';
4
4
  export * from '../runner.js';
5
+ export { runManagedWorker, withRecadStorage, type ManagedStorageOptions } from './managed-worker.js';
6
+ export { recadStorageOptions, type StorageSettings } from './storage-policy.js';
5
7
  export type { RuntimeOptions, Job, JobStatus } from './jobs.js';
6
8
  export type { StoredDocument } from './documents.js';
7
9
  export interface Submission {
@@ -18,6 +20,8 @@ export declare class RecadRuntime {
18
20
  private closing?;
19
21
  private readonly releaseLock;
20
22
  private lockFailure?;
23
+ private readonly artifactRequests;
24
+ private readonly downloads;
21
25
  constructor(options: RuntimeOptions);
22
26
  private assertOpen;
23
27
  health(): {
@@ -32,10 +36,24 @@ export declare class RecadRuntime {
32
36
  };
33
37
  readiness(): Promise<any>;
34
38
  capabilities(): Promise<{
39
+ build: Readonly<import("../../shared/build-identity.d.mts").BuildIdentity>;
35
40
  pngRuntimeConfigured: any;
36
41
  printRuntimeConfigured: any;
42
+ consumptionReceipts: number;
43
+ storage: {
44
+ version: number;
45
+ retentionMs: number | undefined;
46
+ maxStorageBytes: number;
47
+ workerStorageBytes: number | undefined;
48
+ policy: {
49
+ version: string;
50
+ safetyBytes: number;
51
+ resumeExtraBytes: number;
52
+ estimateFactor: number;
53
+ } | undefined;
54
+ };
37
55
  format: "XDTrace.RecadCapabilities";
38
- version: 30;
56
+ version: 34;
39
57
  layouts: {
40
58
  readonly version: 1;
41
59
  readonly selection: true;
@@ -45,6 +63,9 @@ export declare class RecadRuntime {
45
63
  readonly version: 1;
46
64
  readonly coordinates: "cad-world-y-up-v1";
47
65
  readonly sheetPolicy: 1;
66
+ readonly sheetModes: readonly ["auto", "single"];
67
+ readonly textGeometry: 1;
68
+ readonly fontResources: 1;
48
69
  };
49
70
  nativeEvidence: {
50
71
  readonly version: 1;
@@ -67,18 +88,18 @@ export declare class RecadRuntime {
67
88
  readonly sourceHashBinding: true;
68
89
  };
69
90
  maturity: "experimental";
70
- operations: readonly ["inspect", "render", "readback", "scene", "layouts"];
91
+ operations: readonly ["inspect", "render", "readback", "scene", "layouts", "source-records"];
71
92
  input: readonly ["dwg", "ascii-dxf", "binary-dxf-8bit-groups", "binary-dxf-16bit-groups"];
72
93
  output: readonly ["pdf", "png", "readback-json", "source-scene-json"];
73
94
  layout: "Model (default); named paper layouts via layout selection";
74
- rendering: readonly ["fit-window", "fixed-scale"];
95
+ rendering: readonly ["fit-window", "fixed-scale", "auto-overview"];
75
96
  printPlanVersion: 1;
76
97
  colorModes: readonly ["monochrome", "source"];
77
98
  minimumDpi: 300;
78
99
  maxPixels: 150000000;
79
100
  independentCadVerification: true;
80
101
  productionReplacementReady: false;
81
- limitations: readonly ["Ordinary source CAD jobs isolate bounded unsupported application objects, failed HATCH/REGION and BLOCKLOOKUPACTION records with per-object receipts; structural/CRC/section/critical failures remain blocking. Core strict mode, explicit bundles and final readback never certify recovery as complete parsing", "R2007 VLO-VL ASCII payloads retain typed data; other VLO/application payloads are omitted with handles and source hashes in source recovery mode, never executed", "Straight planar LEADER retains dimension styles, annotations and verified DSTYLE overrides, prints closed filled and DOT arrows; dimension-only overrides retain values without modifying saved leader geometry", "Saved anonymous dynamic-block representations can be plotted in source recovery mode with explicit unevaluated-program metadata; no editing/constraint solver is claimed", "Measured print suggestions retain all content and offer spatial regions and aspect-matched 300 DPI paper; they do not claim authored sheet frames and never silently discard distant geometry", "3DFACE plots saved visible edges in 2D wireframe, respecting hidden-edge flags and double-precision coordinates; no shaded 3D rendering or hidden-surface solver is claimed", "R2004/R2007 version-2 ASSOC2DCONSTRAINTGROUP retains five verified node types, graph connections and raw payload; source recovery may plot saved geometry with pending-evaluation receipts; strict/readback rejects pending evaluation, unknown nodes and broken graphs", "Verified electrical-application INSERT dictionary/XRECORD records retain typed payloads and ownership receipts; unknown extensions still fail; final readback rejects business metadata until independent replay is supported", "Ordinary service CAD plotting defaults to best-effort text: bundled Noto Sans SC substitutes missing faces, uncovered glyphs leave spaces, unsupported text emits omission receipts; explicit resource bundles and readback remain strict; SHAPE libraries are not text substitutes", "Bundled DWG/DXF XREF loads explicit hashed dependencies, nested attachments and overlay non-propagation, model basepoints, affine/mirrored instances, scoped fonts/images and host VISRETAIN 0/1 layer properties; unknown INSERT extension programs and non-default XREFOVERRIDE/VISRETAINMODE fail explicitly", "2D block/XREF positive rectangular and simple polygon clipping supports nested affine instances, disabled filters and validated inverse matrices; inverse clips, depth planes, non-identity clip-space matrices, printed clip frames and clipped arrays remain explicit failures; final readback rejects block clipping until its semantics can be replayed", "XREF cache geometry never substitutes for missing dependencies; final readback rejects every external drawing reference, including unused and cached definitions", "Collected stroke/fill vector bounds use the final composed instance coordinates instead of repeatedly transformed AABBs; text/image/specialized operations retain conservative loaded-resource bounds", "Horizontal SHX TEXT/ATTRIB/ATTDEF percent underline/overline/strike toggles preserve pen advances, alignment bounds, spaces, mirrors, obliquing, negative-Z and block affine transforms; decorated custom TTF and vertical TEXT remain explicit failures", "MINSERT DXF/R2000/R2007/R2018 retains array dispatch, rotated unscaled spacing, repeated attributes, nested transforms and readback subclass grammar; per-array and total-instance limits apply", "Planar negative-Z single-line SHX placement is verified across 36 alignment/mirror cases; nonplanar TEXT remains unsupported", "SHX shapes/unifont, ordinary and extended BigFont, fractional arcs, dual-mode vertical writing are covered by explicit font fixtures; this is not universal font compatibility", "Extended BigFont signed basepoint drawing and unsigned cursor restoration are verified; nested extended calls, vertical MTEXT and vertical non-baseline alignment remain explicit failures", "SHX/TTF TEXT Aligned/Fit and combined entity/STYLE mirrors, explicit TTC faceIndex, and R2018 multiline attributes with masks/columns are supported", "MTEXT static/equal-height/manual-height columns preserve widths, gutters, flow, rotation and per-column masks; complete legacy XDATA/EED linked columns normalize to the same layout, ambiguous or broken links fail", "GROUP references to legacy linked child columns preserve original handles and source programs in readback without duplicate rendering", "Multiline attributes retain embedded styles, indexed/true-color masks, frames and three column modes; malformed embedded programs fail explicitly", "DWG ATTRIB STYLE/layer/flags verified on R2000–R2018 fixtures; original and remaining native statuses are retained; unresolved structural decode failures remain explicit", "Explicit print policy; no arbitrary CTB/STB equivalence", "Binary DXF R12/R2000/R2007/R2018 fixtures are verified, including R12 markerless geometry, attribute sequences and one-byte group envelopes; unresolved XREF and unsupported entities fail explicitly", "Complex A-aligned linetypes retain source text/shape STYLE, offsets, rotation and physical lineweights; missing definitions fail", "Monochrome uses black vectors and grayscale images; PNG retains antialiasing", "DXF/DWG MTEXT masks preserve rotation and authored column widths; monochrome makes all masks white, source mode preserves color", "PNG/JPEG IMAGE supports block instances, affine placement and polygon/inverse clipping; non-default brightness/contrast/fade still fail", "Model reachability filters unused definitions; unresolved DWG decoder omissions remain conservative failures", "Independent readback supplies evidence; the application must compare geometry/resources/GROUP and recompute topology, then separately review appearance", "Inspect measureBounds=true loads actual resources and collects layout before paper clipping; plain parserBounds remains a diagnostic estimate"];
102
+ limitations: readonly ["Ordinary source CAD jobs isolate bounded unsupported application objects, failed HATCH/REGION and BLOCKLOOKUPACTION records with per-object receipts; structural/CRC/section/critical failures remain blocking. Core strict mode, explicit bundles and final readback never certify recovery as complete parsing", "R2007 VLO-VL ASCII payloads retain typed data; other VLO/application payloads are omitted with handles and source hashes in source recovery mode, never executed", "Straight planar LEADER retains dimension styles, annotations and verified DSTYLE overrides, prints closed filled and DOT arrows; dimension-only overrides retain values without modifying saved leader geometry", "Saved anonymous dynamic-block representations can be plotted in source recovery mode with explicit unevaluated-program metadata; no editing/constraint solver is claimed", "Measured print suggestions retain all content and offer spatial regions and aspect-matched 300 DPI paper; they do not claim authored sheet frames and never silently discard distant geometry", "3DFACE plots saved visible edges in 2D wireframe, respecting hidden-edge flags and double-precision coordinates; no shaded 3D rendering or hidden-surface solver is claimed", "R2004/R2007 version-2 ASSOC2DCONSTRAINTGROUP retains five verified node types, graph connections and raw payload; source recovery may plot saved geometry with pending-evaluation receipts; strict/readback rejects pending evaluation, unknown nodes and broken graphs", "Verified electrical-application INSERT dictionary/XRECORD records retain typed payloads and ownership receipts; unknown extensions still fail; final readback rejects business metadata until independent replay is supported", "Owned empty INSERT extension dictionaries retain dictionary identity and source hash; source reading and final readback accept the empty declaration, while malformed references and unknown entries remain rejected", "Ordinary service CAD plotting defaults to best-effort text: bundled Noto Sans SC substitutes missing faces, uncovered glyphs leave spaces, unsupported text emits omission receipts; explicit resource bundles and readback remain strict; SHAPE libraries are not text substitutes", "Bundled DWG/DXF XREF loads explicit hashed dependencies, nested attachments and overlay non-propagation, model basepoints, affine/mirrored instances, scoped fonts/images and host VISRETAIN 0/1 layer properties; unknown INSERT extension programs and non-default XREFOVERRIDE/VISRETAINMODE fail explicitly", "2D block/XREF positive rectangular and simple polygon clipping supports nested affine instances, disabled filters and validated inverse matrices; inverse clips, depth planes, non-identity clip-space matrices, printed clip frames and clipped arrays remain explicit failures; final readback rejects block clipping until its semantics can be replayed", "XREF cache geometry never substitutes for missing dependencies; final readback rejects every external drawing reference, including unused and cached definitions", "Collected stroke/fill vector bounds use the final composed instance coordinates instead of repeatedly transformed AABBs; text/image/specialized operations retain conservative loaded-resource bounds", "Horizontal SHX TEXT/ATTRIB/ATTDEF percent underline/overline/strike toggles preserve pen advances, alignment bounds, spaces, mirrors, obliquing, negative-Z and block affine transforms; decorated custom TTF and vertical TEXT remain explicit failures", "MINSERT DXF/R2000/R2007/R2018 retains array dispatch, rotated unscaled spacing, repeated attributes, nested transforms and readback subclass grammar; per-array and total-instance limits apply", "Planar negative-Z single-line SHX placement is verified across 36 alignment/mirror cases; nonplanar TEXT remains unsupported", "SHX shapes/unifont, ordinary and extended BigFont, fractional arcs, dual-mode vertical writing are covered by explicit font fixtures; this is not universal font compatibility", "Extended BigFont signed basepoint drawing and unsigned cursor restoration are verified; nested extended calls, vertical MTEXT and vertical non-baseline alignment remain explicit failures", "SHX/TTF TEXT Aligned/Fit and combined entity/STYLE mirrors, explicit TTC faceIndex, and R2018 multiline attributes with masks/columns are supported", "MTEXT static/equal-height/manual-height columns preserve widths, gutters, flow, rotation and per-column masks; complete legacy XDATA/EED linked columns normalize to the same layout, ambiguous or broken links fail", "GROUP references to legacy linked child columns preserve original handles and source programs in readback without duplicate rendering", "Multiline attributes retain embedded styles, indexed/true-color masks, frames and three column modes; malformed embedded programs fail explicitly", "DWG ATTRIB STYLE/layer/flags verified on R2000–R2018 fixtures; original and remaining native statuses are retained; unresolved structural decode failures remain explicit", "Explicit print policy; no arbitrary CTB/STB equivalence", "Binary DXF R12/R2000/R2007/R2018 fixtures are verified, including R12 markerless geometry, attribute sequences and one-byte group envelopes; unresolved XREF and unsupported entities fail explicitly", "Complex A-aligned linetypes retain source text/shape STYLE, offsets, rotation and physical lineweights; missing definitions fail", "Monochrome uses black vectors and grayscale images; PNG retains antialiasing", "DXF/DWG MTEXT masks preserve rotation and authored column widths; monochrome makes all masks white, source mode preserves color", "PNG/JPEG IMAGE supports block instances, affine placement and polygon/inverse clipping; non-default brightness/contrast/fade still fail", "Model reachability filters unused definitions; unresolved DWG decoder omissions remain conservative failures", "Independent readback supplies evidence; the application must compare geometry/resources/GROUP and recompute topology, then separately review appearance", "Inspect measureBounds=true loads actual resources and collects layout before paper clipping; plain parserBounds remains a diagnostic estimate"];
82
103
  dependencies: {
83
104
  readonly dataModel: "1.15.2";
84
105
  readonly dwgConverter: "3.15.2";
@@ -109,6 +130,22 @@ export declare class RecadRuntime {
109
130
  cancelled: boolean;
110
131
  jobs: string[];
111
132
  };
133
+ consume(id: string, receipt: unknown): {
134
+ id: string;
135
+ consumedAt: any;
136
+ } | {
137
+ consumed: boolean;
138
+ id: string;
139
+ consumedAt: any;
140
+ };
141
+ private artifactEntry;
142
+ streamArtifact(id: string, name: string): Promise<{
143
+ contentType: string;
144
+ stream: import("fs").ReadStream;
145
+ name: string;
146
+ sha256: string;
147
+ bytes: number;
148
+ }>;
112
149
  artifact(id: string, name: string): ArtifactReceipt & {
113
150
  buffer: Buffer;
114
151
  contentType: string;
@@ -3,13 +3,19 @@ import { mkdirSync, realpathSync } from 'node:fs';
3
3
  import { readFileSync, lstatSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { CadError, capabilities } from "../contracts.js";
6
- import { hashFile } from "../io.js";
6
+ import { sha256 } from "../io.js";
7
7
  import { decodeBundle } from "../bundle.js";
8
- import { fallbackArtifacts, drawingArtifacts } from "../dwg-fallback.js";
8
+ import { fallbackArtifacts, isDrawingArtifact } from "../dwg-fallback.js";
9
9
  import { JobQueue } from "./jobs.js";
10
10
  import { DocumentStore } from "./documents.js";
11
11
  import { checkReadiness } from "./readiness.js";
12
+ import { StorageQuota } from "../../shared/service-storage/src/quota.js";
13
+ import { artifactStream } from "../../shared/service-storage/src/downloads.js";
14
+ import { recadStorageOptions } from "./storage-policy.js";
15
+ import { getRecadBuildInfo } from "../build-info.js";
12
16
  export * from "../runner.js";
17
+ export { runManagedWorker, withRecadStorage } from "./managed-worker.js";
18
+ export { recadStorageOptions } from "./storage-policy.js";
13
19
  /** CAD lifecycle and verified artifacts shared by local callers and transports. */
14
20
  export class RecadRuntime {
15
21
  options;
@@ -20,10 +26,12 @@ export class RecadRuntime {
20
26
  closing;
21
27
  releaseLock;
22
28
  lockFailure;
29
+ artifactRequests = new Set();
30
+ downloads = new Set();
23
31
  constructor(options) {
24
32
  this.options = options;
25
33
  mkdirSync(options.data, { recursive: true });
26
- options = { ...options, data: realpathSync(options.data) };
34
+ options = { ...options, ...recadStorageOptions(options), data: realpathSync(options.data) };
27
35
  this.options = options;
28
36
  try {
29
37
  this.releaseLock = lockSync(options.data, {
@@ -45,8 +53,9 @@ export class RecadRuntime {
45
53
  }
46
54
  let documents;
47
55
  try {
48
- this.documents = documents = new DocumentStore(options.data, options.retentionMs, options.maxStorageBytes);
49
- this.queue = new JobQueue(options);
56
+ const quota = new StorageQuota(options.data, options.maxStorageBytes, options.storageCapacity);
57
+ this.documents = documents = new DocumentStore(options.data, options.retentionMs, options.maxStorageBytes, quota);
58
+ this.queue = new JobQueue(options, quota);
50
59
  }
51
60
  catch (error) {
52
61
  void documents?.close();
@@ -79,8 +88,17 @@ export class RecadRuntime {
79
88
  const result = await this.readiness();
80
89
  return {
81
90
  ...capabilities,
91
+ build: getRecadBuildInfo(),
82
92
  pngRuntimeConfigured: result.printRuntimeReady,
83
93
  printRuntimeConfigured: result.printRuntimeReady,
94
+ consumptionReceipts: 1,
95
+ storage: {
96
+ version: 1,
97
+ retentionMs: this.options.retentionMs,
98
+ maxStorageBytes: this.options.maxStorageBytes ?? 0,
99
+ workerStorageBytes: this.options.workerStorageBytes,
100
+ policy: this.options.storageCapacity?.policy,
101
+ },
84
102
  };
85
103
  }
86
104
  uploadDocument(stream, fileName) {
@@ -124,43 +142,79 @@ export class RecadRuntime {
124
142
  this.assertOpen();
125
143
  return this.queue.cancelOwner(id);
126
144
  }
127
- artifact(id, name) {
145
+ consume(id, receipt) {
146
+ this.assertOpen();
147
+ return this.queue.consume(id, receipt);
148
+ }
149
+ artifactEntry(id, name) {
128
150
  this.assertOpen();
129
151
  const job = this.queue.get(id);
130
152
  if (!job || !['succeeded', 'failed', 'cancelled', 'interrupted'].includes(job.status))
131
153
  throw new CadError('NOT_FOUND', '任务成果尚未就绪');
132
154
  const diagnostic = fallbackArtifacts.includes(name);
133
- if (!diagnostic && (job.status !== 'succeeded' || !drawingArtifacts.includes(name)))
155
+ if (!diagnostic && (job.status !== 'succeeded' || !isDrawingArtifact(name)))
134
156
  throw new CadError('NOT_FOUND', '成果不存在');
135
157
  const artifact = (diagnostic ? job.diagnostics : job.result?.artifacts)?.find((a) => a.name === name);
136
158
  if (!artifact)
137
159
  throw new CadError('NOT_FOUND', '成果不存在');
138
- const file = path.join(this.queue.directory(id), name);
160
+ const directory = this.queue.directory(id);
161
+ const contentType = name.endsWith('.pdf') ? 'application/pdf'
162
+ : name.endsWith('.png') ? 'image/png'
163
+ : name.endsWith('.dxf') ? 'application/dxf'
164
+ : name.endsWith('.ttf') ? 'font/ttf'
165
+ : name.endsWith('.otf') ? 'font/otf'
166
+ : name.endsWith('.shx') ? 'application/octet-stream' : 'application/json';
167
+ return { artifact: artifact, directory, contentType };
168
+ }
169
+ streamArtifact(id, name) {
170
+ const { artifact, directory, contentType } = this.artifactEntry(id, name);
171
+ const operation = (async () => {
172
+ const stream = await artifactStream(directory, name, artifact, this.queue.holdDownload(id));
173
+ if (this.closing) {
174
+ await new Promise(resolve => { stream.once('close', resolve); stream.destroy(); });
175
+ throw new CadError('SERVICE_CLOSING', 'CAD 运行实例正在停止');
176
+ }
177
+ this.downloads.add(stream);
178
+ stream.once('close', () => this.downloads.delete(stream));
179
+ return { ...artifact, contentType, stream };
180
+ })().finally(() => this.artifactRequests.delete(operation));
181
+ this.artifactRequests.add(operation);
182
+ return operation;
183
+ }
184
+ artifact(id, name) {
185
+ const { artifact, directory, contentType } = this.artifactEntry(id, name);
186
+ const file = path.join(directory, name);
139
187
  const stat = lstatSync(file);
140
188
  if (!stat.isFile() ||
141
189
  stat.isSymbolicLink() ||
142
- stat.size !== artifact.bytes ||
143
- hashFile(file) !== artifact.sha256)
190
+ stat.size !== artifact.bytes)
191
+ throw new CadError('ARTIFACT_CHANGED', '成果与本次核验哈希不一致');
192
+ const buffer = readFileSync(file);
193
+ if (sha256(buffer) !== artifact.sha256)
144
194
  throw new CadError('ARTIFACT_CHANGED', '成果与本次核验哈希不一致');
145
195
  return {
146
196
  ...artifact,
147
- buffer: readFileSync(file),
148
- contentType: name.endsWith('.pdf')
149
- ? 'application/pdf'
150
- : name.endsWith('.png')
151
- ? 'image/png'
152
- : name.endsWith('.dxf')
153
- ? 'application/dxf'
154
- : 'application/json',
197
+ buffer,
198
+ contentType,
155
199
  };
156
200
  }
157
201
  close() {
158
202
  if (!this.closing) {
159
203
  this.closing = (async () => {
204
+ const closingDownloads = [...this.downloads].map(stream => new Promise(resolve => {
205
+ if (stream.closed)
206
+ resolve();
207
+ else {
208
+ stream.once('close', resolve);
209
+ stream.destroy();
210
+ }
211
+ }));
160
212
  const results = await Promise.allSettled([
161
213
  this.documents.close(),
162
214
  this.queue.close(),
163
215
  this.pending,
216
+ Promise.allSettled(this.artifactRequests),
217
+ ...closingDownloads,
164
218
  ]);
165
219
  try {
166
220
  this.releaseLock();
@@ -1,3 +1,5 @@
1
+ import { StorageQuota, type ServiceCapacityOptions } from '../../shared/service-storage/src/quota.js';
2
+ import { type Consumption } from '../../shared/service-storage/src/consumption.js';
1
3
  import type { StoredDocument } from './documents.js';
2
4
  import { type CadRequest } from '../contracts.js';
3
5
  import { runWorker } from '../runner.js';
@@ -23,6 +25,9 @@ export interface Job {
23
25
  fingerprint?: string;
24
26
  owner?: string;
25
27
  serverResourceFingerprint?: string;
28
+ sourceSha256?: string;
29
+ consumed?: Consumption;
30
+ consumedAt?: string;
26
31
  }
27
32
  export interface RuntimeOptions {
28
33
  /** Internal process boundary; omitted by the standalone service. */
@@ -33,25 +38,31 @@ export interface RuntimeOptions {
33
38
  baseFonts?: boolean;
34
39
  missingText?: 'strict' | ServerFonts['missingText'];
35
40
  python?: string;
41
+ token?: string;
36
42
  concurrency?: number;
37
43
  timeoutMs?: number;
38
44
  retentionMs?: number;
39
45
  maxStorageBytes?: number;
46
+ workerStorageBytes?: number;
47
+ storageCapacity?: ServiceCapacityOptions;
40
48
  cleanupIntervalMs?: number;
41
49
  downloadGraceMs?: number;
42
50
  }
43
51
  export declare function sourceTextPolicy(options: Pick<RuntimeOptions, 'baseFonts' | 'missingText'>): "noto-sans-sc" | "best-effort" | undefined;
44
52
  export declare class JobQueue {
45
53
  private options;
54
+ readonly quota: StorageQuota;
55
+ private staging;
46
56
  private jobs;
47
57
  private running;
58
+ private retention;
48
59
  private closing;
49
60
  private cleanupTimer?;
50
61
  readonly storageWarnings: {
51
62
  directory: string;
52
63
  message: string;
53
64
  }[];
54
- constructor(options: RuntimeOptions);
65
+ constructor(options: RuntimeOptions, quota?: StorageQuota);
55
66
  private marker;
56
67
  directory(id: string): string;
57
68
  get(id: string): Job | undefined;
@@ -76,7 +87,15 @@ export declare class JobQueue {
76
87
  cancelled: boolean;
77
88
  jobs: Job[];
78
89
  };
79
- private storageBytes;
90
+ holdDownload(id: string): () => void;
91
+ consume(id: string, receipt: unknown): {
92
+ id: string;
93
+ consumedAt: any;
94
+ } | {
95
+ consumed: boolean;
96
+ id: string;
97
+ consumedAt: any;
98
+ };
80
99
  cleanup(now?: number): {
81
100
  removed: string[];
82
101
  };