bambu-printer-mcp 1.1.49 → 1.1.51

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.
@@ -113,6 +113,45 @@ const PROFILE_METADATA_KEYS = new Set([
113
113
  'name', 'type', 'from', 'inherits', 'instantiation', 'setting_id', 'version', 'is_custom_defined',
114
114
  'compatible_printers', 'compatible_printers_condition', 'compatible_prints', 'compatible_prints_condition',
115
115
  ]);
116
+ /**
117
+ * A slicer failure that keeps the slicer's own result.json. The message starts
118
+ * with the slicer's own words (`slicerText`), when it gave any, then `detail`.
119
+ */
120
+ export class SlicerRunError extends Error {
121
+ constructor(detail, slicerResult) {
122
+ const slicerText = slicerResult ? slicerResultText(slicerResult) : "";
123
+ super(slicerText ? `${slicerText}\n${detail}` : detail);
124
+ this.slicerResult = slicerResult;
125
+ this.name = "SlicerRunError";
126
+ this.slicerText = slicerText;
127
+ }
128
+ }
129
+ /**
130
+ * The result.json this run wrote. Bambu Studio 02.08.02.61 writes it on macOS
131
+ * for successes and failures alike; an older file must not describe this run.
132
+ */
133
+ function readCliResult(cli) {
134
+ try {
135
+ if (fs.statSync(cli.resultPath).mtimeMs < cli.startedAt)
136
+ return undefined;
137
+ const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
138
+ return result && typeof result === "object" && !Array.isArray(result) ? result : undefined;
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ }
144
+ /**
145
+ * The slicer's own words: its error_string when it reports a failing
146
+ * return_code (not "Success."), then each plate's warning_message.
147
+ */
148
+ function slicerResultText(result) {
149
+ const plates = Array.isArray(result.sliced_plates) ? result.sliced_plates : [];
150
+ return [
151
+ result.return_code === 0 ? undefined : result.error_string,
152
+ ...plates.map(plate => plate && typeof plate === "object" ? plate.warning_message : undefined),
153
+ ].filter((text) => typeof text === "string" && text.trim() !== "").map(text => text.trim()).join("\n");
154
+ }
116
155
  function describeSlicerFailure(error, stdout, stderr, cli) {
117
156
  const status = typeof error.signal === "string" && error.signal
118
157
  ? `crashed with ${error.signal}`
@@ -122,7 +161,7 @@ function describeSlicerFailure(error, stdout, stderr, cli) {
122
161
  return `Slicer failed: the slicer ${status}${reason ? ` (${reason})` : ""}. ${error.message.trim()}${output ? `\nSlicer output: ${output}` : ""}`;
123
162
  }
124
163
  // Bambu Studio and OrcaSlicer CLI errors (libslic3r/Utils.hpp). The process
125
- // exits with the low byte of the code; on Linux result.json names the error.
164
+ // exits with the low byte of the code; result.json names the error.
126
165
  const BAMBU_CLI_ERRORS = {
127
166
  [-2]: "invalid parameters to the slicer",
128
167
  [-3]: "input files not found",
@@ -145,16 +184,9 @@ const BAMBU_CLI_ERRORS = {
145
184
  [-102]: "G-code in an unprintable area",
146
185
  };
147
186
  function bambuCliFailureReason(exitCode, cli) {
148
- try {
149
- if (fs.statSync(cli.resultPath).mtimeMs >= cli.startedAt) {
150
- const result = JSON.parse(fs.readFileSync(cli.resultPath, "utf8"));
151
- if (typeof result.error_string === "string" && result.error_string.trim()) {
152
- return `${result.error_string.trim()} [${result.return_code}]`;
153
- }
154
- }
155
- }
156
- catch {
157
- // result.json is written only on Linux and only for handled errors.
187
+ const result = readCliResult(cli);
188
+ if (typeof result?.error_string === "string" && result.error_string.trim()) {
189
+ return `${result.error_string.trim()} [${result.return_code}]`;
158
190
  }
159
191
  if (typeof exitCode !== "number")
160
192
  return undefined;
@@ -1305,6 +1337,14 @@ export class STLManipulator extends EventEmitter {
1305
1337
  * @returns Path to the generated G-code or sliced 3MF file
1306
1338
  */
1307
1339
  async sliceSTL(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1340
+ return (await this.sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions)).path;
1341
+ }
1342
+ /**
1343
+ * sliceSTL with the Bambu-compatible CLI's own result.json, parsed verbatim.
1344
+ * A failure throws SlicerRunError, whose message starts with the slicer's
1345
+ * error_string and plate warnings.
1346
+ */
1347
+ async sliceSTLWithResult(stlFilePath, slicerType, slicerPath, slicerProfile, progressCallback, printerPreset, bambuOptions) {
1308
1348
  const operationId = this.generateOperationId();
1309
1349
  this.activeOperations.set(operationId, true);
1310
1350
  if (slicerType !== 'orca-slicer-api' && isPathLikeExecutable(slicerPath) && !fs.existsSync(slicerPath)) {
@@ -1538,7 +1578,8 @@ export class STLManipulator extends EventEmitter {
1538
1578
  if (error) {
1539
1579
  console.error(`Slicer Error: ${error.message}`);
1540
1580
  console.error(`Slicer Stderr: ${stderr}`);
1541
- reject(new Error(describeSlicerFailure(error, stdout, stderr, cliResult)));
1581
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1582
+ reject(new SlicerRunError(describeSlicerFailure(error, stdout, stderr, cliResult), slicerResult));
1542
1583
  }
1543
1584
  else {
1544
1585
  console.error(`Slicer Stdout: ${stdout}`);
@@ -1573,8 +1614,16 @@ export class STLManipulator extends EventEmitter {
1573
1614
  // This check might be redundant if the promise rejected on kill, but good safety
1574
1615
  throw new Error("Slicing operation cancelled after process finished");
1575
1616
  }
1617
+ const slicerResult = cliResult ? readCliResult(cliResult) : undefined;
1618
+ if (cliResult && !slicerResult) {
1619
+ // Older or Linux CLIs may write result.json only for handled errors.
1620
+ console.error(`${slicerType} wrote no result.json for this slice, so its own checks are not available.`);
1621
+ }
1622
+ if (typeof slicerResult?.return_code === "number" && slicerResult.return_code !== 0) {
1623
+ throw new SlicerRunError(`Slicer failed: the slicer exited with code 0, but its result.json reports return_code ${slicerResult.return_code}.`, slicerResult);
1624
+ }
1576
1625
  if (!fs.existsSync(outputFilePath)) {
1577
- throw new Error(`Slicer finished but output file not found: ${outputFilePath}`);
1626
+ throw new SlicerRunError(`Slicer finished but output file not found: ${outputFilePath}`, slicerResult);
1578
1627
  }
1579
1628
  if (progressCallback)
1580
1629
  progressCallback(100, "Slicing completed successfully");
@@ -1584,7 +1633,7 @@ export class STLManipulator extends EventEmitter {
1584
1633
  success: true,
1585
1634
  output: outputFilePath
1586
1635
  });
1587
- return outputFilePath;
1636
+ return slicerResult ? { path: outputFilePath, slicer_result: slicerResult } : { path: outputFilePath };
1588
1637
  }
1589
1638
  catch (error) {
1590
1639
  console.error(`Slicing failed for ${stlFilePath}:`, error);
@@ -1774,9 +1823,19 @@ export class STLManipulator extends EventEmitter {
1774
1823
  }
1775
1824
  }
1776
1825
  /**
1777
- * Rotate the model so its largest flat face lies on the XY plane (Z=0).
1826
+ * Rotate the model so a face rests on the bed, in the pose with the least
1827
+ * part and support material per mm² of bed contact, then move it down to
1828
+ * Z=0. Returns the new file's path, or the input path when no pose qualifies.
1778
1829
  */
1779
1830
  async layFlat(stlFilePath, progressCallback) {
1831
+ return (await this.layFlatWithResult(stlFilePath, progressCallback)).path;
1832
+ }
1833
+ /**
1834
+ * layFlat with its outcome. A pose qualifies only when some face, turned to
1835
+ * face down, lies on the rotated mesh's lowest plane; `laid_flat` is false
1836
+ * and the model is unchanged when none does.
1837
+ */
1838
+ async layFlatWithResult(stlFilePath, progressCallback) {
1780
1839
  const operationId = this.generateOperationId();
1781
1840
  this.activeOperations.set(operationId, true);
1782
1841
  try {
@@ -1790,91 +1849,96 @@ export class STLManipulator extends EventEmitter {
1790
1849
  const positionAttribute = geometry.getAttribute('position');
1791
1850
  if (!positionAttribute)
1792
1851
  throw new Error("Geometry has no position attribute.");
1793
- const faces = [];
1852
+ const faceCount = Math.floor(positionAttribute.count / 3);
1853
+ if (faceCount === 0)
1854
+ throw new Error("No faces found in geometry.");
1855
+ const mesh = {
1856
+ positions: new Float64Array(faceCount * 9),
1857
+ normals: new Float64Array(faceCount * 3),
1858
+ areas: new Float64Array(faceCount),
1859
+ volume: 0,
1860
+ };
1861
+ const center = new THREE.Vector3();
1862
+ boundingBox.getCenter(center);
1794
1863
  const vA = new THREE.Vector3();
1795
1864
  const vB = new THREE.Vector3();
1796
1865
  const vC = new THREE.Vector3();
1797
- const faceNormal = new THREE.Vector3();
1798
1866
  const cb = new THREE.Vector3(), ab = new THREE.Vector3();
1799
- // Iterate through faces (triangles)
1800
- for (let i = 0; i < positionAttribute.count; i += 3) {
1801
- vA.fromBufferAttribute(positionAttribute, i);
1802
- vB.fromBufferAttribute(positionAttribute, i + 1);
1803
- vC.fromBufferAttribute(positionAttribute, i + 2);
1804
- // Calculate face normal
1867
+ const fromA = new THREE.Vector3(), fromB = new THREE.Vector3(), fromC = new THREE.Vector3();
1868
+ for (let face = 0; face < faceCount; face++) {
1869
+ vA.fromBufferAttribute(positionAttribute, face * 3);
1870
+ vB.fromBufferAttribute(positionAttribute, face * 3 + 1);
1871
+ vC.fromBufferAttribute(positionAttribute, face * 3 + 2);
1872
+ vA.toArray(mesh.positions, face * 9);
1873
+ vB.toArray(mesh.positions, face * 9 + 3);
1874
+ vC.toArray(mesh.positions, face * 9 + 6);
1875
+ // Signed tetrahedron volumes about the center sum to the enclosed volume.
1876
+ fromA.subVectors(vA, center);
1877
+ fromB.subVectors(vB, center);
1878
+ fromC.subVectors(vC, center);
1879
+ mesh.volume += fromA.dot(fromB.cross(fromC)) / 6;
1880
+ // The cross product's direction is the outward normal; half its length is the area.
1805
1881
  cb.subVectors(vC, vB);
1806
1882
  ab.subVectors(vA, vB);
1807
1883
  cb.cross(ab);
1808
- faceNormal.copy(cb).normalize();
1809
- // Calculate face area (using cross product magnitude / 2)
1810
- const area = cb.length() / 2;
1811
- faces.push({
1812
- normal: faceNormal.clone(),
1813
- area: area,
1814
- vertices: [vA.clone(), vB.clone(), vC.clone()] // Store vertices if needed for center calculation
1815
- });
1884
+ mesh.areas[face] = cb.length() / 2;
1885
+ cb.normalize().toArray(mesh.normals, face * 3);
1816
1886
  }
1817
- if (faces.length === 0)
1818
- throw new Error("No faces found in geometry.");
1887
+ mesh.volume = Math.abs(mesh.volume);
1819
1888
  if (!this.activeOperations.get(operationId))
1820
1889
  throw new Error("Operation cancelled");
1821
1890
  if (progressCallback)
1822
1891
  progressCallback(65, "Grouping faces by normal...");
1823
1892
  // Group faces by similar normal vectors (tolerance for floating point errors)
1824
- const normalGroups = new Map();
1893
+ const normalGroups = [];
1825
1894
  const tolerance = 1e-5;
1826
- for (const face of faces) {
1827
- let foundGroup = false;
1828
- for (const [key, group] of normalGroups.entries()) {
1829
- if (face.normal.distanceToSquared(group.representativeNormal) < tolerance) {
1830
- group.totalArea += face.area;
1831
- // Optional: Average the normal? For now, just use the first one.
1832
- foundGroup = true;
1833
- break;
1834
- }
1835
- }
1836
- if (!foundGroup) {
1837
- const key = `${face.normal.x.toFixed(5)},${face.normal.y.toFixed(5)},${face.normal.z.toFixed(5)}`;
1838
- if (!normalGroups.has(key)) { // Ensure unique key even if floats slightly differ after toFixed
1839
- normalGroups.set(key, { totalArea: face.area, representativeNormal: face.normal });
1840
- }
1841
- }
1895
+ const faceNormal = new THREE.Vector3();
1896
+ for (let face = 0; face < faceCount; face++) {
1897
+ if (!(mesh.areas[face] > 0))
1898
+ continue;
1899
+ faceNormal.fromArray(mesh.normals, face * 3);
1900
+ const group = normalGroups.find(candidate => faceNormal.distanceToSquared(candidate.representativeNormal) < tolerance);
1901
+ if (group)
1902
+ group.totalArea += mesh.areas[face];
1903
+ else
1904
+ normalGroups.push({ totalArea: mesh.areas[face], representativeNormal: faceNormal.clone() });
1842
1905
  }
1843
- if (normalGroups.size === 0)
1844
- throw new Error("Could not group faces by normal.");
1845
1906
  if (!this.activeOperations.get(operationId))
1846
1907
  throw new Error("Operation cancelled");
1847
1908
  if (progressCallback)
1848
- progressCallback(75, "Finding largest flat surface...");
1849
- // Include already-horizontal faces: excluding Z-aligned normals can
1850
- // stand a flat model on its edge, including on a repeated layFlat call.
1851
- let largestArea = 0;
1852
- let targetNormal = null;
1853
- const downVector = new THREE.Vector3(0, 0, -1); // Target normal (pointing down)
1854
- // Faces are grouped by direction, so a part whose flat faces are all
1855
- // horizontal has equal up- and down-facing areas. On a tie, keep the
1856
- // face that already points down so a seated part is not flipped.
1857
- for (const group of normalGroups.values()) {
1858
- const tied = targetNormal !== null && Math.abs(group.totalArea - largestArea) <= largestArea * 1e-6;
1859
- if (tied ? group.representativeNormal.z < targetNormal.z : group.totalArea > largestArea) {
1860
- largestArea = group.totalArea;
1861
- targetNormal = group.representativeNormal;
1862
- }
1909
+ progressCallback(75, "Finding the pose that rests on the bed...");
1910
+ // Candidate directions to turn down: the largest face groups, plus the
1911
+ // model's own axes so a part with a domed side can be flipped exactly.
1912
+ const candidates = normalGroups
1913
+ .sort((a, b) => b.totalArea - a.totalArea)
1914
+ .slice(0, LAY_FLAT_MAX_GROUP_CANDIDATES)
1915
+ .map(group => group.representativeNormal);
1916
+ for (const axis of [[0, 0, -1], [0, 0, 1], [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0]]) {
1917
+ const normal = new THREE.Vector3(axis[0], axis[1], axis[2]);
1918
+ if (!candidates.some(candidate => candidate.distanceToSquared(normal) < tolerance))
1919
+ candidates.push(normal);
1863
1920
  }
1864
- if (!targetNormal) {
1865
- // Only a mesh without any face area reaches this.
1866
- console.warn("Could not find a suitable large flat face to lay down. No changes made.");
1867
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message: "No suitable flat face found." });
1868
- return stlFilePath;
1921
+ let best = null;
1922
+ for (const normal of candidates) {
1923
+ const pose = evaluateLayFlatPose(mesh, normal);
1924
+ if (pose && (!best || isBetterLayFlatPose(pose, best)))
1925
+ best = pose;
1926
+ }
1927
+ if (!best) {
1928
+ const message = "No face lies on the model's lowest plane in any candidate orientation, so the model is unchanged.";
1929
+ console.error(`lay_flat: ${message}`);
1930
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: stlFilePath, message });
1931
+ return { path: stlFilePath, laid_flat: false, message };
1869
1932
  }
1870
1933
  if (progressCallback)
1871
1934
  progressCallback(80, "Calculating rotation...");
1872
- // Calculate the rotation needed to align targetNormal with downVector
1873
- const quaternion = new THREE.Quaternion().setFromUnitVectors(targetNormal, downVector);
1874
- const rotationMatrix = new THREE.Matrix4().makeRotationFromQuaternion(quaternion);
1935
+ // Turn the chosen normal to face straight down. Turning +Z down rotates
1936
+ // half a turn about X, which keeps the model's X layout.
1937
+ const downVector = new THREE.Vector3(0, 0, -1);
1938
+ const rotationMatrix = best.normal.dot(downVector) < -1 + 1e-9
1939
+ ? new THREE.Matrix4().makeRotationX(Math.PI)
1940
+ : new THREE.Matrix4().makeRotationFromQuaternion(new THREE.Quaternion().setFromUnitVectors(best.normal, downVector));
1875
1941
  // Rotate around the model's center
1876
- const center = new THREE.Vector3();
1877
- boundingBox.getCenter(center);
1878
1942
  const toOriginMatrix = new THREE.Matrix4().makeTranslation(-center.x, -center.y, -center.z);
1879
1943
  const fromOriginMatrix = new THREE.Matrix4().makeTranslation(center.x, center.y, center.z);
1880
1944
  // Apply rotation
@@ -1892,8 +1956,9 @@ export class STLManipulator extends EventEmitter {
1892
1956
  const outputFileName = path.basename(stlFilePath, '.stl') + '_flat.stl';
1893
1957
  const outputFilePath = path.join(this.tempDir, outputFileName);
1894
1958
  await this.saveSTL(geometry, outputFilePath, progressCallback); // 90-100% progress
1895
- this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath });
1896
- return outputFilePath;
1959
+ const message = `Rests on ${best.contactArea.toFixed(1)} mm² of bed contact; overhangs more than 45° from vertical need about ${best.supportVolume.toFixed(0)} mm³ of support.`;
1960
+ this.emit('operationComplete', { operationId, type: 'layFlat', success: true, output: outputFilePath, message });
1961
+ return { path: outputFilePath, laid_flat: true, message };
1897
1962
  }
1898
1963
  catch (error) {
1899
1964
  this.emit('operationError', { operationId, type: 'layFlat', error: error instanceof Error ? error.message : String(error) });
@@ -1904,3 +1969,62 @@ export class STLManipulator extends EventEmitter {
1904
1969
  }
1905
1970
  }
1906
1971
  }
1972
+ const LAY_FLAT_MAX_GROUP_CANDIDATES = 64;
1973
+ /** Faces tilted more than 45° from vertical overhang and need support. */
1974
+ const LAY_FLAT_OVERHANG_COS = Math.SQRT1_2 + 1e-6;
1975
+ /**
1976
+ * Score turning `normal` to face the bed. The bed is the mesh's lowest plane in
1977
+ * that pose, its support plane. Faces lying on it, within 0.5% of the model's
1978
+ * height there (at most 0.2 mm), are bed contact. Overhanging faces above it
1979
+ * need support up from the bed: their projected area times their height.
1980
+ * Returns null when no face lies on the bed: turning that normal down would
1981
+ * rest the model on an edge or a point, not a face.
1982
+ */
1983
+ function evaluateLayFlatPose(mesh, normal) {
1984
+ const { positions, normals, areas } = mesh;
1985
+ const nx = normal.x, ny = normal.y, nz = normal.z;
1986
+ // Distance along the normal grows toward the bed: the bed is at its maximum.
1987
+ let bed = -Infinity, top = Infinity;
1988
+ for (let index = 0; index < positions.length; index += 3) {
1989
+ const along = positions[index] * nx + positions[index + 1] * ny + positions[index + 2] * nz;
1990
+ if (along > bed)
1991
+ bed = along;
1992
+ if (along < top)
1993
+ top = along;
1994
+ }
1995
+ const tolerance = Math.min(0.2, Math.max(0.005 * (bed - top), 1e-4));
1996
+ let contactArea = 0;
1997
+ let supportVolume = 0;
1998
+ for (let face = 0; face < areas.length; face++) {
1999
+ const facing = normals[face * 3] * nx + normals[face * 3 + 1] * ny + normals[face * 3 + 2] * nz;
2000
+ if (!(facing > 0))
2001
+ continue;
2002
+ const base = face * 9;
2003
+ let heightSum = 0, heightMax = 0;
2004
+ for (let corner = base; corner < base + 9; corner += 3) {
2005
+ const height = bed - (positions[corner] * nx + positions[corner + 1] * ny + positions[corner + 2] * nz);
2006
+ heightSum += height;
2007
+ if (height > heightMax)
2008
+ heightMax = height;
2009
+ }
2010
+ if (heightMax <= tolerance)
2011
+ contactArea += areas[face];
2012
+ else if (facing > LAY_FLAT_OVERHANG_COS)
2013
+ supportVolume += areas[face] * facing * (heightSum / 3);
2014
+ }
2015
+ if (!(contactArea > 0))
2016
+ return null;
2017
+ return { normal, contactArea, supportVolume, stackHeight: (mesh.volume + supportVolume) / contactArea };
2018
+ }
2019
+ /**
2020
+ * Prefer the pose with the lowest stack height, then the larger contact. On a
2021
+ * tie, keep the face that already points down so a seated part is not flipped.
2022
+ */
2023
+ function isBetterLayFlatPose(pose, best) {
2024
+ const same = (a, b) => Math.abs(a - b) <= 1e-9 + 1e-6 * Math.max(Math.abs(a), Math.abs(b));
2025
+ if (!same(pose.stackHeight, best.stackHeight))
2026
+ return pose.stackHeight < best.stackHeight;
2027
+ if (!same(pose.contactArea, best.contactArea))
2028
+ return pose.contactArea > best.contactArea;
2029
+ return pose.normal.z < best.normal.z;
2030
+ }
@@ -0,0 +1,2 @@
1
+ /** Bambu Studio's downloaded text for a 16-hex HMS code or an 8-hex print_error code, by serial prefix, else from hms_en.json. */
2
+ export declare function studioDownloadedText(kind: "hms" | "error", code: string, serial: string): string | undefined;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * HMS and print-error text from the user's own Bambu Studio download, for
3
+ * codes the tables bundled at the pinned Studio tag lack (it bundles no P1,
4
+ * X1 or A1 table). Bambu Studio downloads hms_en_<serial prefix>.json and
5
+ * hms_en.json into an hms folder next to BambuStudio.conf; this reads them
6
+ * read-only and returns Bambu's text unchanged, with no advice added. The
7
+ * files are Bambu's and are never copied or redistributed.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { studioConfigPath } from "./studio-print-options.js";
12
+ const cache = new Map();
13
+ function entries(value) {
14
+ const map = new Map();
15
+ if (!Array.isArray(value))
16
+ return map;
17
+ for (const entry of value) {
18
+ const code = typeof entry?.ecode === "string" ? entry.ecode.trim().toUpperCase() : "";
19
+ const text = typeof entry?.intro === "string" ? entry.intro.trim() : "";
20
+ if (/^[0-9A-F]{8}([0-9A-F]{8})?$/.test(code) && text)
21
+ map.set(code, text);
22
+ }
23
+ return map;
24
+ }
25
+ function load(file) {
26
+ let stat;
27
+ try {
28
+ stat = fs.statSync(file);
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ if (!stat.isFile() || stat.size > 32 * 1024 * 1024)
34
+ return undefined;
35
+ const cached = cache.get(file);
36
+ if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size)
37
+ return cached.table;
38
+ let table;
39
+ try {
40
+ const data = JSON.parse(fs.readFileSync(file, "utf8"))?.data;
41
+ table = { hms: entries(data?.device_hms?.en), error: entries(data?.device_error?.en) };
42
+ }
43
+ catch {
44
+ table = undefined;
45
+ }
46
+ cache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, table });
47
+ return table;
48
+ }
49
+ /** Bambu Studio's downloaded text for a 16-hex HMS code or an 8-hex print_error code, by serial prefix, else from hms_en.json. */
50
+ export function studioDownloadedText(kind, code, serial) {
51
+ const config = studioConfigPath();
52
+ if (!config)
53
+ return undefined;
54
+ const directory = path.join(path.dirname(config), "hms");
55
+ const prefix = serial.trim().toUpperCase().slice(0, 3);
56
+ const files = [...(/^[0-9A-Z]{3}$/.test(prefix) ? [`hms_en_${prefix}.json`] : []), "hms_en.json"];
57
+ for (const name of files) {
58
+ const text = load(path.join(directory, name))?.[kind].get(code.toUpperCase());
59
+ if (text)
60
+ return text;
61
+ }
62
+ return undefined;
63
+ }
@@ -0,0 +1,57 @@
1
+ export type StudioOptionValue = "off" | "on" | "auto";
2
+ export type StudioOptionSource = "caller" | "studio-config" | "studio-default";
3
+ /** Explicit caller choices; each one wins over Studio's resolution. */
4
+ export type CallerPrintOptions = {
5
+ bedLeveling?: boolean;
6
+ flowCalibration?: boolean;
7
+ vibrationCalibration?: boolean;
8
+ layerInspect?: boolean;
9
+ /** 0 off, 1 on, 2 auto, as Studio's getValueInt. */
10
+ autoBedLeveling?: number;
11
+ autoFlowCali?: number;
12
+ autoOffsetCali?: number;
13
+ extruderCaliManualMode?: number;
14
+ };
15
+ export type StudioPrintOptions = {
16
+ printerType?: string;
17
+ values: {
18
+ bed_leveling: StudioOptionValue;
19
+ flow_cali: StudioOptionValue;
20
+ nozzle_offset_cali: StudioOptionValue;
21
+ };
22
+ sources: {
23
+ bed_leveling: StudioOptionSource;
24
+ flow_cali: StudioOptionSource;
25
+ nozzle_offset_cali: StudioOptionSource;
26
+ };
27
+ task_bed_leveling: boolean;
28
+ task_flow_cali: boolean;
29
+ task_vibration_cali: boolean;
30
+ task_layer_inspect: boolean;
31
+ auto_bed_leveling: number;
32
+ auto_flow_cali: number;
33
+ auto_offset_cali: number;
34
+ extruder_cali_manual_mode: number;
35
+ };
36
+ /** Where Studio keeps BambuStudio.conf; BAMBU_STUDIO_CONFIG overrides it (empty: none). */
37
+ export declare function studioConfigPath(): string | undefined;
38
+ /**
39
+ * The Send dialog options Studio saved for a printer type, and nothing else:
40
+ * BambuStudio.conf also holds access codes, so only that one section is kept,
41
+ * and a parse failure is reported without any of the file's text.
42
+ */
43
+ export declare function readStudioSavedOptions(printerTypes: string[], configPath: string | undefined): Record<string, string> | undefined;
44
+ /**
45
+ * What Studio's Send dialog would send for this model, with the caller's
46
+ * explicit choices taking precedence. usedNozzles is the number of nozzles the
47
+ * job uses, for dual-nozzle printers.
48
+ */
49
+ export declare function resolveStudioPrintOptions(model: string, caller?: CallerPrintOptions, options?: {
50
+ usedNozzles?: number;
51
+ configPath?: string;
52
+ }): StudioPrintOptions;
53
+ /** The number of nozzles a job's used filaments print from, when the inspection knows. */
54
+ export declare function usedNozzleCount(inspection: {
55
+ usedFilamentPositions: number[];
56
+ filamentNozzleIndices?: Array<number | undefined>;
57
+ }): number | undefined;