ducjs 4.0.4 → 4.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 (122) hide show
  1. package/dist/duc_locator_wasm.d.ts +48 -0
  2. package/dist/duc_locator_wasm.js +296 -0
  3. package/dist/duc_locator_wasm_bg.wasm +0 -0
  4. package/dist/duc_locator_wasm_bg.wasm.d.ts +13 -0
  5. package/dist/ducjs_wasi.wasm +0 -0
  6. package/dist/ducjs_wasm.d.ts +14 -2
  7. package/dist/ducjs_wasm.js +96 -8
  8. package/dist/ducjs_wasm_bg.wasm +0 -0
  9. package/dist/ducjs_wasm_bg.wasm.d.ts +6 -2
  10. package/dist/index.d.ts +4 -1
  11. package/dist/index.js +4 -1
  12. package/dist/locator-runtime.d.ts +4 -0
  13. package/dist/locator-runtime.js +7 -0
  14. package/dist/restore/index.d.ts +1 -0
  15. package/dist/restore/index.js +1 -0
  16. package/dist/restore/restoreDataState.d.ts +13 -24
  17. package/dist/restore/restoreDataState.js +49 -83
  18. package/dist/restore/restoreElements.d.ts +10 -15
  19. package/dist/restore/restoreElements.js +128 -125
  20. package/dist/restore/updateModelCode.d.ts +11 -0
  21. package/dist/restore/updateModelCode.js +63 -0
  22. package/dist/thumbnails/bounds.d.ts +21 -0
  23. package/dist/thumbnails/bounds.js +84 -0
  24. package/dist/thumbnails/browserRunner.d.ts +60 -0
  25. package/dist/thumbnails/browserRunner.js +446 -0
  26. package/dist/thumbnails/cameraPresets.d.ts +47 -0
  27. package/dist/thumbnails/cameraPresets.js +222 -0
  28. package/dist/thumbnails/cli.d.ts +2 -0
  29. package/dist/thumbnails/cli.js +102 -0
  30. package/dist/thumbnails/index.d.ts +11 -0
  31. package/dist/thumbnails/index.js +11 -0
  32. package/dist/thumbnails/lib/clientBundle.min.js +10427 -0
  33. package/dist/thumbnails/lib/clientEntry.d.ts +3 -0
  34. package/dist/thumbnails/lib/clientEntry.js +8 -0
  35. package/dist/thumbnails/lib/clippingUtils.d.ts +10 -0
  36. package/dist/thumbnails/lib/clippingUtils.js +3 -0
  37. package/dist/thumbnails/lib/defaultModelColor.d.ts +3 -0
  38. package/dist/thumbnails/lib/defaultModelColor.js +22 -0
  39. package/dist/thumbnails/lib/index.d.ts +12 -0
  40. package/dist/thumbnails/lib/index.js +12 -0
  41. package/dist/thumbnails/lib/mapViewerStateToOptions.d.ts +34 -0
  42. package/dist/thumbnails/lib/mapViewerStateToOptions.js +69 -0
  43. package/dist/thumbnails/lib/offscreen-dxf-thumbnail.d.ts +16 -0
  44. package/dist/thumbnails/lib/offscreen-dxf-thumbnail.js +173 -0
  45. package/dist/thumbnails/lib/offscreen-model-thumbnail.d.ts +16 -0
  46. package/dist/thumbnails/lib/offscreen-model-thumbnail.js +209 -0
  47. package/dist/thumbnails/lib/parametricClip.d.ts +18 -0
  48. package/dist/thumbnails/lib/parametricClip.js +177 -0
  49. package/dist/thumbnails/lib/parametricShapes.d.ts +1 -0
  50. package/dist/thumbnails/lib/parametricShapes.js +75 -0
  51. package/dist/thumbnails/lib/parametricViewerState.d.ts +26 -0
  52. package/dist/thumbnails/lib/parametricViewerState.js +198 -0
  53. package/dist/thumbnails/lib/thumbnail-camera-fit.d.ts +6 -0
  54. package/dist/thumbnails/lib/thumbnail-camera-fit.js +292 -0
  55. package/dist/thumbnails/lib/thumbnail-capture.d.ts +23 -0
  56. package/dist/thumbnails/lib/thumbnail-capture.js +161 -0
  57. package/dist/thumbnails/lib/thumbnail-visibility.d.ts +12 -0
  58. package/dist/thumbnails/lib/thumbnail-visibility.js +97 -0
  59. package/dist/thumbnails/lib/viewerGrid.d.ts +13 -0
  60. package/dist/thumbnails/lib/viewerGrid.js +57 -0
  61. package/dist/thumbnails/modelCache.d.ts +56 -0
  62. package/dist/thumbnails/modelCache.js +165 -0
  63. package/dist/thumbnails/modelOutputArtifact.d.ts +19 -0
  64. package/dist/thumbnails/modelOutputArtifact.js +87 -0
  65. package/dist/thumbnails/render.d.ts +45 -0
  66. package/dist/thumbnails/render.js +162 -0
  67. package/dist/thumbnails/templates.d.ts +16 -0
  68. package/dist/thumbnails/templates.js +786 -0
  69. package/dist/thumbnails/tessellator.d.ts +33 -0
  70. package/dist/thumbnails/tessellator.js +349 -0
  71. package/dist/thumbnails/types.d.ts +233 -0
  72. package/dist/thumbnails/types.js +1 -0
  73. package/dist/thumbnails/worker.d.ts +10 -0
  74. package/dist/thumbnails/worker.js +119 -0
  75. package/dist/transform.d.ts +1 -1
  76. package/dist/transform.js +20 -22
  77. package/dist/types/elements/index.d.ts +22 -28
  78. package/dist/types/elements/index.js +0 -1
  79. package/dist/types/geometry.types.d.ts +5 -5
  80. package/dist/types/index.d.ts +13 -59
  81. package/dist/types/index.js +0 -1
  82. package/dist/types/issues.types.d.ts +1 -2
  83. package/dist/utils/bounds.d.ts +10 -11
  84. package/dist/utils/bounds.js +105 -84
  85. package/dist/utils/constants.d.ts +5 -7
  86. package/dist/utils/constants.js +10 -15
  87. package/dist/utils/elements/freedrawElement.js +6 -3
  88. package/dist/utils/elements/index.d.ts +2 -6
  89. package/dist/utils/elements/index.js +4 -9
  90. package/dist/utils/elements/linearElement.d.ts +12 -14
  91. package/dist/utils/elements/linearElement.js +81 -66
  92. package/dist/utils/elements/newElement.d.ts +37 -22
  93. package/dist/utils/elements/newElement.js +70 -64
  94. package/dist/utils/elements/textElement.d.ts +34 -35
  95. package/dist/utils/elements/textElement.js +79 -83
  96. package/dist/utils/index.d.ts +1 -1
  97. package/dist/utils/index.js +1 -1
  98. package/dist/utils/locator.d.ts +43 -0
  99. package/dist/utils/locator.js +112 -0
  100. package/dist/utils/math/bbox.d.ts +1 -2
  101. package/dist/utils/math/geometry.js +5 -4
  102. package/dist/utils/math/index.d.ts +13 -17
  103. package/dist/utils/math/index.js +53 -41
  104. package/dist/utils/math/random.js +7 -2
  105. package/dist/utils/normalize.d.ts +5 -5
  106. package/dist/utils/normalize.js +15 -10
  107. package/dist/utils/shape.d.ts +3 -4
  108. package/dist/utils/shape.js +64 -48
  109. package/dist/utils/state/index.d.ts +3 -4
  110. package/dist/utils/state/index.js +8 -23
  111. package/dist/wasi.js +38 -12
  112. package/package.json +23 -9
  113. package/dist/technical/index.d.ts +0 -2
  114. package/dist/technical/index.js +0 -2
  115. package/dist/technical/measurements.d.ts +0 -31
  116. package/dist/technical/measurements.js +0 -64
  117. package/dist/technical/scopes.d.ts +0 -261
  118. package/dist/technical/scopes.js +0 -676
  119. package/dist/types/typeChecks.d.ts +0 -5
  120. package/dist/types/typeChecks.js +0 -10
  121. package/dist/utils/traverse.d.ts +0 -30
  122. package/dist/utils/traverse.js +0 -124
@@ -0,0 +1,56 @@
1
+ import type { DucModelElement, DucExternalFiles } from "../types";
2
+ export type ModelCacheKind = "dwg-dxf" | "parametric-json" | "ifc-json" | "python-ifc" | "python-dxf" | "model-artifact";
3
+ export interface ModelCacheKeyInput {
4
+ kind: ModelCacheKind;
5
+ sourceFileId: string;
6
+ sourceRevisionId: string;
7
+ variant?: string;
8
+ }
9
+ export interface ModelCacheEntry {
10
+ key: string;
11
+ kind: ModelCacheKind;
12
+ sourceFileId: string;
13
+ sourceRevisionId: string;
14
+ mimeType: string;
15
+ sizeBytes: number;
16
+ data: Uint8Array;
17
+ created: number;
18
+ outputKind?: ModelCacheKind;
19
+ modelType?: string;
20
+ }
21
+ /**
22
+ * Manages in-memory and local disk caching of tessellated model geometry.
23
+ * Matches Scopture's ModelElementCacheManager key scheme:
24
+ * SHA-256(kind:sourceFileId:sourceRevisionId:variant)
25
+ */
26
+ export declare class ModelElementCacheManager {
27
+ private memoryCache;
28
+ private diskCacheDir;
29
+ private useDiskCache;
30
+ constructor(options?: {
31
+ diskCacheDir?: string;
32
+ useDiskCache?: boolean;
33
+ });
34
+ /**
35
+ * Generates canonical deterministic cache key for a model source and revision.
36
+ */
37
+ createKey(input: ModelCacheKeyInput): string;
38
+ /**
39
+ * Retrieves cached model payload by key input.
40
+ */
41
+ get(input: ModelCacheKeyInput): Promise<ModelCacheEntry | null>;
42
+ /**
43
+ * Stores a model entry in memory and on disk.
44
+ */
45
+ save(input: ModelCacheKeyInput & {
46
+ mimeType?: string;
47
+ outputKind?: ModelCacheKind;
48
+ modelType?: string;
49
+ }, data: Uint8Array): Promise<ModelCacheEntry>;
50
+ /**
51
+ * Clears in-memory cache.
52
+ */
53
+ clearMemory(): void;
54
+ }
55
+ export declare const createModelElementCacheInput: (element: DucModelElement, files?: DucExternalFiles) => ModelCacheKeyInput;
56
+ export declare function getSharedModelCacheManager(): ModelElementCacheManager;
@@ -0,0 +1,165 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ import crypto from "crypto";
22
+ import fs from "fs";
23
+ import os from "os";
24
+ import path from "path";
25
+ const DEFAULT_MODEL_CACHE_MIME_TYPES = {
26
+ "dwg-dxf": "application/dxf",
27
+ "parametric-json": "application/json",
28
+ "ifc-json": "application/json",
29
+ "python-ifc": "application/x-ifc",
30
+ "python-dxf": "application/dxf",
31
+ "model-artifact": "application/json",
32
+ };
33
+ function sha256Hex(value) {
34
+ return crypto.createHash("sha256").update(value, "utf8").digest("hex");
35
+ }
36
+ /**
37
+ * Manages in-memory and local disk caching of tessellated model geometry.
38
+ * Matches Scopture's ModelElementCacheManager key scheme:
39
+ * SHA-256(kind:sourceFileId:sourceRevisionId:variant)
40
+ */
41
+ export class ModelElementCacheManager {
42
+ constructor(options = {}) {
43
+ var _a, _b;
44
+ this.memoryCache = new Map();
45
+ this.useDiskCache = (_a = options.useDiskCache) !== null && _a !== void 0 ? _a : true;
46
+ this.diskCacheDir =
47
+ (_b = options.diskCacheDir) !== null && _b !== void 0 ? _b : path.join(os.tmpdir(), "duc-model-cache");
48
+ if (this.useDiskCache) {
49
+ try {
50
+ fs.mkdirSync(this.diskCacheDir, { recursive: true });
51
+ }
52
+ catch (_c) {
53
+ // Best-effort cache directory creation
54
+ }
55
+ }
56
+ }
57
+ /**
58
+ * Generates canonical deterministic cache key for a model source and revision.
59
+ */
60
+ createKey(input) {
61
+ var _a;
62
+ const variant = (_a = input.variant) !== null && _a !== void 0 ? _a : "v1";
63
+ return sha256Hex(`${input.kind}:${input.sourceFileId}:${input.sourceRevisionId}:${variant}`);
64
+ }
65
+ /**
66
+ * Retrieves cached model payload by key input.
67
+ */
68
+ get(input) {
69
+ return __awaiter(this, void 0, void 0, function* () {
70
+ const key = this.createKey(input);
71
+ // 1. Check in-memory cache
72
+ const memEntry = this.memoryCache.get(key);
73
+ if (memEntry) {
74
+ return memEntry;
75
+ }
76
+ // 2. Check disk cache
77
+ if (this.useDiskCache) {
78
+ try {
79
+ const filePath = path.join(this.diskCacheDir, `${key}.bin`);
80
+ if (fs.existsSync(filePath)) {
81
+ const data = fs.readFileSync(filePath);
82
+ const entry = {
83
+ key,
84
+ kind: input.kind,
85
+ sourceFileId: input.sourceFileId,
86
+ sourceRevisionId: input.sourceRevisionId,
87
+ mimeType: DEFAULT_MODEL_CACHE_MIME_TYPES[input.kind],
88
+ sizeBytes: data.byteLength,
89
+ data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
90
+ created: Date.now(),
91
+ };
92
+ const metadataPath = path.join(this.diskCacheDir, `${key}.json`);
93
+ if (fs.existsSync(metadataPath)) {
94
+ const metadata = JSON.parse(fs.readFileSync(metadataPath, "utf8"));
95
+ if (metadata.key === key && metadata.sizeBytes === data.byteLength) {
96
+ entry.outputKind = metadata.outputKind;
97
+ entry.modelType = metadata.modelType;
98
+ }
99
+ }
100
+ this.memoryCache.set(key, entry);
101
+ return entry;
102
+ }
103
+ }
104
+ catch (_a) {
105
+ // Disk read error fallback
106
+ }
107
+ }
108
+ return null;
109
+ });
110
+ }
111
+ /**
112
+ * Stores a model entry in memory and on disk.
113
+ */
114
+ save(input, data) {
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ var _a;
117
+ const key = this.createKey(input);
118
+ const entry = {
119
+ key,
120
+ kind: input.kind,
121
+ sourceFileId: input.sourceFileId,
122
+ sourceRevisionId: input.sourceRevisionId,
123
+ mimeType: (_a = input.mimeType) !== null && _a !== void 0 ? _a : DEFAULT_MODEL_CACHE_MIME_TYPES[input.kind],
124
+ sizeBytes: data.byteLength,
125
+ data,
126
+ created: Date.now(),
127
+ outputKind: input.outputKind,
128
+ modelType: input.modelType,
129
+ };
130
+ this.memoryCache.set(key, entry);
131
+ if (this.useDiskCache) {
132
+ try {
133
+ const filePath = path.join(this.diskCacheDir, `${key}.bin`);
134
+ fs.writeFileSync(filePath, data);
135
+ const { data: _data } = entry, metadata = __rest(entry, ["data"]);
136
+ fs.writeFileSync(path.join(this.diskCacheDir, `${key}.json`), JSON.stringify(metadata));
137
+ }
138
+ catch (_b) {
139
+ // Best-effort disk write
140
+ }
141
+ }
142
+ return entry;
143
+ });
144
+ }
145
+ /**
146
+ * Clears in-memory cache.
147
+ */
148
+ clearMemory() {
149
+ this.memoryCache.clear();
150
+ }
151
+ }
152
+ export const createModelElementCacheInput = (element, files) => {
153
+ const modelType = (element.modelType || "python").toLowerCase();
154
+ const kind = modelType === "ifc" ? "ifc-json" : modelType === "dxf" || modelType === "dwg" ? "python-dxf" : "parametric-json";
155
+ const inputs = (element.fileIds || []).filter(id => !id.startsWith("model_output_") && !id.startsWith("model_preview_") && !id.startsWith("dwg_dxf_cache_") && !(modelType === "python" && id.startsWith("model_python_")))
156
+ .sort().map(id => { var _a; return [id, ((_a = files === null || files === void 0 ? void 0 : files[id]) === null || _a === void 0 ? void 0 : _a.activeRevisionId) || ""]; });
157
+ return { kind, sourceFileId: `model:${element.id}`, sourceRevisionId: sha256Hex(JSON.stringify(inputs)), variant: `v2:${modelType}:${kind}:${sha256Hex(element.code || "")}` };
158
+ };
159
+ let sharedCacheManager = null;
160
+ export function getSharedModelCacheManager() {
161
+ if (!sharedCacheManager) {
162
+ sharedCacheManager = new ModelElementCacheManager();
163
+ }
164
+ return sharedCacheManager;
165
+ }
@@ -0,0 +1,19 @@
1
+ import type { DucExternalFiles, ExternalFilesData, DucModelElement } from '../types';
2
+ import type { RenderThumbnailOptions } from './render';
3
+ import type { ModelThumbnailResult } from './types';
4
+ export interface ModelOutputArtifact {
5
+ envelope: {
6
+ version: 1;
7
+ kind: string;
8
+ renderer: string;
9
+ mimeType: string;
10
+ contentHash: string;
11
+ sourceFingerprint: string;
12
+ inputFingerprints: Record<string, string>;
13
+ };
14
+ data: Uint8Array;
15
+ preview?: Uint8Array;
16
+ }
17
+ export declare const readPersistedModelArtifact: (element: DucModelElement, files?: DucExternalFiles, data?: ExternalFilesData) => ModelOutputArtifact | null;
18
+ export declare const parseModelArtifactPayload: (payload: string) => ModelOutputArtifact;
19
+ export declare const renderModelArtifact: (artifact: ModelOutputArtifact, element: DucModelElement, options: RenderThumbnailOptions) => Promise<ModelThumbnailResult>;
@@ -0,0 +1,87 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import crypto from 'node:crypto';
11
+ import { getSharedBrowserRunner } from './browserRunner';
12
+ import { getModelThumbnailBoundsUpdate } from './bounds';
13
+ const hash = (data) => crypto.createHash('sha256').update(data).digest('hex');
14
+ const revisionBytes = (fileId, files, data) => {
15
+ var _a;
16
+ const revisionId = (_a = files === null || files === void 0 ? void 0 : files[fileId]) === null || _a === void 0 ? void 0 : _a.activeRevisionId;
17
+ return revisionId ? data === null || data === void 0 ? void 0 : data[revisionId] : undefined;
18
+ };
19
+ export const readPersistedModelArtifact = (element, files, data) => {
20
+ var _a, _b;
21
+ const output = (_a = element.customData) === null || _a === void 0 ? void 0 : _a.modelOutput;
22
+ if ((output === null || output === void 0 ? void 0 : output.version) !== 1 || output.status !== 'fresh' || typeof output.fileId !== 'string')
23
+ return null;
24
+ if (output.sourceFingerprint !== hash(JSON.stringify({ code: element.code || '', modules: [] })))
25
+ return null;
26
+ const inputs = (element.fileIds || []).filter(id => { var _a; return !id.startsWith('model_output_') && !id.startsWith('model_preview_') && !id.startsWith('dwg_dxf_cache_') && !(((_a = element.modelType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === 'python' && id.startsWith('model_python_')); });
27
+ const fingerprints = Object.keys(output.inputFingerprints || {});
28
+ if (inputs.length !== fingerprints.length || inputs.some(id => !fingerprints.includes(id)))
29
+ return null;
30
+ for (const [id, expected] of Object.entries(output.inputFingerprints || {})) {
31
+ const bytes = revisionBytes(id, files, data);
32
+ const file = files === null || files === void 0 ? void 0 : files[id];
33
+ const checksum = (_b = file === null || file === void 0 ? void 0 : file.revisions[file.activeRevisionId]) === null || _b === void 0 ? void 0 : _b.checksum;
34
+ if (bytes ? hash(bytes) !== expected : checksum !== expected)
35
+ return null;
36
+ }
37
+ const bytes = revisionBytes(output.fileId, files, data);
38
+ if (!(bytes === null || bytes === void 0 ? void 0 : bytes.byteLength) || hash(bytes) !== output.contentHash)
39
+ return null;
40
+ return { envelope: output, data: bytes, preview: output.previewFileId ? revisionBytes(output.previewFileId, files, data) : undefined };
41
+ };
42
+ export const parseModelArtifactPayload = (payload) => {
43
+ var _a;
44
+ const value = JSON.parse(payload);
45
+ const data = value.dataBase64 ? new Uint8Array(Buffer.from(value.dataBase64, 'base64')) : new TextEncoder().encode(value.content || '');
46
+ if (value.type !== 'artifact' || ((_a = value.envelope) === null || _a === void 0 ? void 0 : _a.version) !== 1 || hash(data) !== value.envelope.contentHash)
47
+ throw new Error('Invalid model output artifact');
48
+ return { envelope: value.envelope, data };
49
+ };
50
+ export const renderModelArtifact = (artifact, element, options) => __awaiter(void 0, void 0, void 0, function* () {
51
+ var _a, _b, _c, _d, _e, _f;
52
+ let bytes = artifact.data;
53
+ let mime = artifact.envelope.mimeType;
54
+ const renderer = artifact.envelope.renderer;
55
+ if (renderer === 'pdf') {
56
+ if (options.rasterizePdf)
57
+ bytes = yield options.rasterizePdf(bytes, 1200);
58
+ else if (((_a = element.thumbnail) === null || _a === void 0 ? void 0 : _a.byteLength) && ((_b = element.customData) === null || _b === void 0 ? void 0 : _b.scoptureModelContentGeneration) === ((_d = (_c = element.customData) === null || _c === void 0 ? void 0 : _c.modelOutput) === null || _d === void 0 ? void 0 : _d.generation))
59
+ bytes = element.thumbnail;
60
+ else
61
+ throw new Error('PDF model output requires a host PDF rasterizer');
62
+ mime = 'image/png';
63
+ }
64
+ if (!['image', 'svg', 'pdf', 'table'].includes(renderer))
65
+ throw new Error(`Unsupported artifact thumbnail renderer: ${renderer}`);
66
+ if (renderer !== 'table' && !/^image\/(png|jpeg|webp|svg\+xml)$/.test(mime))
67
+ throw new Error('Unsupported image output MIME type');
68
+ const width = Math.min(8192, Math.max(1, Math.round(((_e = options.viewConfig) === null || _e === void 0 ? void 0 : _e.width) || 1200)));
69
+ const height = Math.min(8192, Math.max(1, Math.round(((_f = options.viewConfig) === null || _f === void 0 ? void 0 : _f.height) || 900)));
70
+ const payload = Buffer.from(bytes).toString('base64');
71
+ const script = renderer === 'table' ? `
72
+ const value = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob('${payload}'), c => c.charCodeAt(0))));
73
+ const columns = Array.isArray(value) ? [...new Set(value.flatMap(row => Object.keys(row)))] : value.columns;
74
+ const rows = Array.isArray(value) ? value.map(row => columns.map(column => row[column])) : value.rows;
75
+ const table = document.createElement('table');
76
+ for (const row of [columns, ...rows.slice(0, 25)]) { const tr = table.insertRow(); for (const cell of row) tr.insertCell().textContent = String(cell ?? ''); }
77
+ document.body.appendChild(table);
78
+ window.__thumbnailReady = true;` : `
79
+ const image = new Image(); image.src = 'data:${mime};base64,${payload}';
80
+ document.body.appendChild(image); image.decode().then(() => { window.__thumbnailReady = true; }).catch(error => { window.__thumbnailError = String(error); });`;
81
+ const html = `<!doctype html><meta charset="utf-8"><style>body{margin:0;background:white;width:${width}px;height:${height}px;display:flex;align-items:center;justify-content:center;font:20px sans-serif}img{max-width:100%;max-height:100%;object-fit:contain}table{border-collapse:collapse}td{border:1px solid #ccc;padding:8px}</style><body><script>${script}</script></body>`;
82
+ const runner = options.runner || getSharedBrowserRunner({ executablePath: options.browserExecutablePath, mode: options.mode, useSoftwareRenderer: options.useSoftwareRenderer });
83
+ const format = options.format || 'png';
84
+ const start = Date.now();
85
+ const result = yield runner.captureHtml(html, width, height, format, options.timeoutMs || 45000);
86
+ return { data: result.data, base64: result.base64, width: result.width, height: result.height, format, renderTimeMs: Date.now() - start, boundsUpdate: getModelThumbnailBoundsUpdate(element, result.width, result.height), glRenderer: result.renderer, backend: result.isGpu ? 'gpu' : 'cpu' };
87
+ });
@@ -0,0 +1,45 @@
1
+ import type { DucExternalFiles, ExternalFilesData } from "../types";
2
+ import type { DucModelElement } from "../types/elements";
3
+ import { HeadlessBrowserRunner } from "./browserRunner";
4
+ import type { ModelThumbnailInput, ModelThumbnailResult, ModelViewConfig } from "./types";
5
+ export interface RenderThumbnailOptions {
6
+ runner?: HeadlessBrowserRunner;
7
+ browserExecutablePath?: string;
8
+ useSoftwareRenderer?: boolean;
9
+ mode?: "auto" | "gpu" | "cpu";
10
+ timeoutMs?: number;
11
+ files?: DucExternalFiles;
12
+ filesData?: ExternalFilesData;
13
+ ducPath?: string;
14
+ ducpyDir?: string;
15
+ shapes?: unknown;
16
+ dxf?: Uint8Array | string;
17
+ format?: "png" | "webp" | "jpeg";
18
+ viewConfig?: ModelViewConfig;
19
+ rasterizePdf?: (data: Uint8Array, maxDimension: number) => Promise<Uint8Array>;
20
+ }
21
+ /**
22
+ * Renders a thumbnail or frame from a specified model and view configuration.
23
+ * Uses three-cad-viewer for 3D CAD/Python models and dxf-renderer for DXF drawings,
24
+ * trimming transparent borders and scaling to 1200px long edge.
25
+ */
26
+ export declare function renderModelViewThumbnail(input: ModelThumbnailInput, options?: RenderThumbnailOptions): Promise<ModelThumbnailResult>;
27
+ /**
28
+ * Generates and returns thumbnail image bytes for a DucModelElement.
29
+ */
30
+ export declare function renderModelElementThumbnail(element: DucModelElement, options?: RenderThumbnailOptions & {
31
+ viewConfig?: ModelViewConfig;
32
+ }): Promise<Uint8Array>;
33
+ /**
34
+ * Generates and returns a detailed thumbnail result including proportional bounds update.
35
+ * Thumbnails are ALWAYS rendered fresh from the model data via the headless renderer.
36
+ */
37
+ export declare function renderModelElementThumbnailWithResult(element: DucModelElement, options?: RenderThumbnailOptions & {
38
+ viewConfig?: ModelViewConfig;
39
+ }): Promise<ModelThumbnailResult>;
40
+ /**
41
+ * Updates a DucModelElement with a newly generated thumbnail buffer and optional bounds update.
42
+ */
43
+ export declare function updateModelElementThumbnail(element: DucModelElement, options?: RenderThumbnailOptions & {
44
+ viewConfig?: ModelViewConfig;
45
+ }): Promise<DucModelElement>;
@@ -0,0 +1,162 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { resolveModelViewConfig, } from "./cameraPresets";
11
+ import { getSharedBrowserRunner, } from "./browserRunner";
12
+ import { getModelThumbnailBoundsUpdate } from "./bounds";
13
+ import { buildCadViewerHtml, buildDxfViewerHtml } from "./templates";
14
+ import { tessellateModelElement } from "./tessellator";
15
+ import { readPersistedModelArtifact, parseModelArtifactPayload, renderModelArtifact } from "./modelOutputArtifact";
16
+ /**
17
+ * Converts a string or Uint8Array to base64.
18
+ */
19
+ function toBase64String(data) {
20
+ if (typeof data === "string") {
21
+ return Buffer.from(data, "utf8").toString("base64");
22
+ }
23
+ return Buffer.from(data).toString("base64");
24
+ }
25
+ /**
26
+ * Resolves file bytes for a model element from files & filesData maps.
27
+ */
28
+ function resolveElementFileData(element, files, filesData) {
29
+ var _a;
30
+ if (!files || !filesData || !((_a = element.fileIds) === null || _a === void 0 ? void 0 : _a.length)) {
31
+ return null;
32
+ }
33
+ for (const fileId of element.fileIds) {
34
+ const file = files[fileId];
35
+ const revId = file === null || file === void 0 ? void 0 : file.activeRevisionId;
36
+ if (revId && filesData[revId]) {
37
+ return filesData[revId];
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+ /**
43
+ * Renders a thumbnail or frame from a specified model and view configuration.
44
+ * Uses three-cad-viewer for 3D CAD/Python models and dxf-renderer for DXF drawings,
45
+ * trimming transparent borders and scaling to 1200px long edge.
46
+ */
47
+ export function renderModelViewThumbnail(input_1) {
48
+ return __awaiter(this, arguments, void 0, function* (input, options = {}) {
49
+ var _a, _b, _c, _d;
50
+ const startTime = Date.now();
51
+ const config = Object.assign(Object.assign({}, resolveModelViewConfig(input.viewConfig, input.viewerState)), { format: (_a = input.format) !== null && _a !== void 0 ? _a : "png" });
52
+ const isDxf = (input.modelType && input.modelType.toUpperCase() === "DXF") ||
53
+ input.dxf !== undefined;
54
+ let html;
55
+ if (isDxf && input.dxf) {
56
+ const base64Dxf = toBase64String(input.dxf);
57
+ html = buildDxfViewerHtml(base64Dxf, config);
58
+ }
59
+ else {
60
+ html = buildCadViewerHtml(input.shapes, config);
61
+ }
62
+ const runner = (_b = options.runner) !== null && _b !== void 0 ? _b : getSharedBrowserRunner({
63
+ executablePath: options.browserExecutablePath,
64
+ useSoftwareRenderer: options.useSoftwareRenderer,
65
+ mode: options.mode,
66
+ });
67
+ const requestedLongEdge = Math.max(config.targetLongEdge || 0, config.width || 0, config.height || 0, 1200);
68
+ const aspect = config.width && config.height ? config.width / config.height : 4 / 3;
69
+ let captureWidth = requestedLongEdge;
70
+ let captureHeight = Math.round(requestedLongEdge / aspect);
71
+ if (aspect < 1) {
72
+ captureHeight = requestedLongEdge;
73
+ captureWidth = Math.round(requestedLongEdge * aspect);
74
+ }
75
+ const format = (_c = input.format) !== null && _c !== void 0 ? _c : "png";
76
+ const { data, base64, width: renderedWidth, height: renderedHeight, renderer, isGpu } = yield runner.captureHtml(html, captureWidth, captureHeight, format, (_d = options.timeoutMs) !== null && _d !== void 0 ? _d : 45000);
77
+ const renderTimeMs = Date.now() - startTime;
78
+ return {
79
+ data,
80
+ base64,
81
+ format,
82
+ width: renderedWidth,
83
+ height: renderedHeight,
84
+ renderTimeMs,
85
+ glRenderer: renderer,
86
+ backend: isGpu ? "gpu" : "cpu",
87
+ };
88
+ });
89
+ }
90
+ /**
91
+ * Generates and returns thumbnail image bytes for a DucModelElement.
92
+ */
93
+ export function renderModelElementThumbnail(element_1) {
94
+ return __awaiter(this, arguments, void 0, function* (element, options = {}) {
95
+ const result = yield renderModelElementThumbnailWithResult(element, options);
96
+ return result.data;
97
+ });
98
+ }
99
+ /**
100
+ * Generates and returns a detailed thumbnail result including proportional bounds update.
101
+ * Thumbnails are ALWAYS rendered fresh from the model data via the headless renderer.
102
+ */
103
+ export function renderModelElementThumbnailWithResult(element_1) {
104
+ return __awaiter(this, arguments, void 0, function* (element, options = {}) {
105
+ var _a, _b, _c, _d, _e, _f, _g, _h;
106
+ const startTime = Date.now();
107
+ const fileData = resolveElementFileData(element, options.files, options.filesData);
108
+ const artifact = readPersistedModelArtifact(element, options.files, options.filesData);
109
+ if (artifact && ['image', 'svg', 'pdf', 'table'].includes(artifact.envelope.renderer))
110
+ return renderModelArtifact(artifact, element, options);
111
+ let isDxf = (artifact === null || artifact === void 0 ? void 0 : artifact.envelope.renderer) === 'dxf' || ((_a = element.modelType) === null || _a === void 0 ? void 0 : _a.toUpperCase()) === "DXF";
112
+ let shapes = (_c = (_b = options.shapes) !== null && _b !== void 0 ? _b : element.shapes) !== null && _c !== void 0 ? _c : (artifact && (artifact.envelope.renderer === "parametric" || artifact.preview) ? JSON.parse(new TextDecoder().decode(artifact.preview || artifact.data)) : undefined);
113
+ let dxf = (_e = (_d = options.dxf) !== null && _d !== void 0 ? _d : ((artifact === null || artifact === void 0 ? void 0 : artifact.envelope.renderer) === "dxf" ? artifact.data : undefined)) !== null && _e !== void 0 ? _e : (isDxf ? fileData !== null && fileData !== void 0 ? fileData : element.dxf : undefined);
114
+ if (!isDxf && !shapes) {
115
+ try {
116
+ const tessRes = yield tessellateModelElement(element, {
117
+ ducPath: options.ducPath,
118
+ files: options.files,
119
+ filesData: options.filesData,
120
+ ducpyDir: options.ducpyDir,
121
+ timeoutMs: Math.max((_f = options.timeoutMs) !== null && _f !== void 0 ? _f : 120000, 120000),
122
+ });
123
+ if (tessRes.kind === "model-artifact")
124
+ return renderModelArtifact(parseModelArtifactPayload(tessRes.rawPayload), element, options);
125
+ if (tessRes.dxf) {
126
+ dxf = tessRes.dxf;
127
+ isDxf = true;
128
+ }
129
+ if (tessRes === null || tessRes === void 0 ? void 0 : tessRes.shapes) {
130
+ shapes = tessRes.shapes;
131
+ }
132
+ }
133
+ catch (_j) {
134
+ // Fallback to geometric models if Python tessellator is not run
135
+ }
136
+ }
137
+ if (!isDxf && !shapes) {
138
+ throw new Error(`Unable to render thumbnail for model element '${element.id}': no 3D geometry shapes or DXF drawing available.`);
139
+ }
140
+ const result = yield renderModelViewThumbnail({
141
+ modelType: isDxf ? "dxf" : element.modelType,
142
+ viewerState: element.viewerState,
143
+ viewConfig: options.viewConfig,
144
+ shapes,
145
+ dxf,
146
+ pythonCode: element.code,
147
+ format: (_g = options.format) !== null && _g !== void 0 ? _g : (_h = options.viewConfig) === null || _h === void 0 ? void 0 : _h.format,
148
+ }, options);
149
+ const boundsUpdate = getModelThumbnailBoundsUpdate(element, result.width, result.height);
150
+ return Object.assign(Object.assign({}, result), { boundsUpdate });
151
+ });
152
+ }
153
+ /**
154
+ * Updates a DucModelElement with a newly generated thumbnail buffer and optional bounds update.
155
+ */
156
+ export function updateModelElementThumbnail(element_1) {
157
+ return __awaiter(this, arguments, void 0, function* (element, options = {}) {
158
+ var _a;
159
+ const result = yield renderModelElementThumbnailWithResult(element, options);
160
+ return Object.assign(Object.assign(Object.assign({}, element), { thumbnail: result.data }), ((_a = result.boundsUpdate) !== null && _a !== void 0 ? _a : {}));
161
+ });
162
+ }
@@ -0,0 +1,16 @@
1
+ import type { ResolvedModelViewConfig } from "./cameraPresets";
2
+ /**
3
+ * Generates an HTML document that renders 3D CAD shapes using three-cad-viewer,
4
+ * strictly matching the app's offscreen-model-thumbnail.ts and thumbnail-capture.ts.
5
+ */
6
+ export declare function buildCadViewerHtml(shapes: unknown, config: ResolvedModelViewConfig): string;
7
+ /**
8
+ * Returns a base64 data URL for the default CAD font (Roboto-Regular.ttf),
9
+ * ensuring vector text and dimension annotations render in offline and headless environments.
10
+ */
11
+ export declare function getDxfDefaultFontDataUrl(): string | null;
12
+ /**
13
+ * Generates an HTML document that renders 2D/3D DXF content using dxf-renderer,
14
+ * strictly matching the app's offscreen-dxf-thumbnail.ts and thumbnail-capture.ts.
15
+ */
16
+ export declare function buildDxfViewerHtml(dxfContentBase64: string, config: ResolvedModelViewConfig): string;