any2orca 0.0.1 → 0.1.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 (194) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +28 -0
  4. package/README.md +96 -3
  5. package/dist/archive/adaptModelSettings.d.ts +1 -0
  6. package/dist/archive/adaptModelSettings.js +50 -0
  7. package/dist/archive/filamentColorNames.d.ts +8 -0
  8. package/dist/archive/filamentColorNames.js +760 -0
  9. package/dist/archive/fmtNum.d.ts +14 -0
  10. package/dist/archive/fmtNum.js +21 -0
  11. package/dist/archive/internal/escapeRegExp.d.ts +2 -0
  12. package/dist/archive/internal/escapeRegExp.js +5 -0
  13. package/dist/archive/lookupFilamentColorName.d.ts +45 -0
  14. package/dist/archive/lookupFilamentColorName.js +57 -0
  15. package/dist/archive/objectWorldBboxXY.d.ts +2 -0
  16. package/dist/archive/objectWorldBboxXY.js +123 -0
  17. package/dist/archive/parseItemPositions.d.ts +6 -0
  18. package/dist/archive/parseItemPositions.js +17 -0
  19. package/dist/archive/parseObjectMetadata.d.ts +10 -0
  20. package/dist/archive/parseObjectMetadata.js +97 -0
  21. package/dist/archive/parsePlateAssignments.d.ts +6 -0
  22. package/dist/archive/parsePlateAssignments.js +18 -0
  23. package/dist/archive/parseVertices.d.ts +7 -0
  24. package/dist/archive/parseVertices.js +12 -0
  25. package/dist/archive/paths.d.ts +5 -0
  26. package/dist/archive/paths.js +6 -0
  27. package/dist/archive/recenterAssembleItems.d.ts +9 -0
  28. package/dist/archive/recenterAssembleItems.js +53 -0
  29. package/dist/archive/recenterBuildItems.d.ts +15 -0
  30. package/dist/archive/recenterBuildItems.js +51 -0
  31. package/dist/archive/safeUnzip.d.ts +26 -0
  32. package/dist/archive/safeUnzip.js +126 -0
  33. package/dist/archive/setApplicationMetadata.d.ts +13 -0
  34. package/dist/archive/setApplicationMetadata.js +18 -0
  35. package/dist/archive/shouldDropFromBambu.d.ts +29 -0
  36. package/dist/archive/shouldDropFromBambu.js +39 -0
  37. package/dist/archive/streamObjectVertices.d.ts +19 -0
  38. package/dist/archive/streamObjectVertices.js +57 -0
  39. package/dist/archive/tolerantJsonParse.d.ts +20 -0
  40. package/dist/archive/tolerantJsonParse.js +71 -0
  41. package/dist/archive/transform.d.ts +21 -0
  42. package/dist/archive/transform.js +39 -0
  43. package/dist/archive/unwrapBundle.d.ts +24 -0
  44. package/dist/archive/unwrapBundle.js +41 -0
  45. package/dist/archive/xmlBlocks.d.ts +10 -0
  46. package/dist/archive/xmlBlocks.js +31 -0
  47. package/dist/archive/zip.d.ts +29 -0
  48. package/dist/archive/zip.js +141 -0
  49. package/dist/cli/archiveMove.d.ts +15 -0
  50. package/dist/cli/archiveMove.js +41 -0
  51. package/dist/cli/commands/convert.d.ts +89 -0
  52. package/dist/cli/commands/convert.js +311 -0
  53. package/dist/cli/commands/diff.d.ts +21 -0
  54. package/dist/cli/commands/diff.js +112 -0
  55. package/dist/cli/commands/presets.d.ts +51 -0
  56. package/dist/cli/commands/presets.js +280 -0
  57. package/dist/cli/commands/profiles.d.ts +5 -0
  58. package/dist/cli/commands/profiles.js +26 -0
  59. package/dist/cli/commands/telemetry.d.ts +6 -0
  60. package/dist/cli/commands/telemetry.js +45 -0
  61. package/dist/cli/config.d.ts +18 -0
  62. package/dist/cli/config.js +50 -0
  63. package/dist/cli/expandWildcards.d.ts +17 -0
  64. package/dist/cli/expandWildcards.js +81 -0
  65. package/dist/cli/logger.d.ts +17 -0
  66. package/dist/cli/logger.js +36 -0
  67. package/dist/cli/main.d.ts +24 -0
  68. package/dist/cli/main.js +598 -0
  69. package/dist/cli/sameFile.d.ts +9 -0
  70. package/dist/cli/sameFile.js +40 -0
  71. package/dist/cli/stats.d.ts +34 -0
  72. package/dist/cli/stats.js +137 -0
  73. package/dist/cli/table.d.ts +8 -0
  74. package/dist/cli/table.js +18 -0
  75. package/dist/cli/terminalText.d.ts +7 -0
  76. package/dist/cli/terminalText.js +22 -0
  77. package/dist/cli/updateCheck.d.ts +14 -0
  78. package/dist/cli/updateCheck.js +78 -0
  79. package/dist/cli/watchState.d.ts +18 -0
  80. package/dist/cli/watchState.js +33 -0
  81. package/dist/cli.d.ts +1 -0
  82. package/dist/cli.js +10 -0
  83. package/dist/diff/diffSettings.d.ts +81 -0
  84. package/dist/diff/diffSettings.js +259 -0
  85. package/dist/diff/reference.d.ts +14 -0
  86. package/dist/diff/reference.js +22 -0
  87. package/dist/diff/settingsCatalog.d.ts +28 -0
  88. package/dist/diff/settingsCatalog.js +605 -0
  89. package/dist/diff/valueLayout.d.ts +20 -0
  90. package/dist/diff/valueLayout.js +65 -0
  91. package/dist/engine/aboveStock.d.ts +20 -0
  92. package/dist/engine/aboveStock.js +89 -0
  93. package/dist/engine/applyFilamentComplianceMode.d.ts +40 -0
  94. package/dist/engine/applyFilamentComplianceMode.js +68 -0
  95. package/dist/engine/applyFilamentFlowVariants.d.ts +42 -0
  96. package/dist/engine/applyFilamentFlowVariants.js +109 -0
  97. package/dist/engine/applyHighFlowHotends.d.ts +52 -0
  98. package/dist/engine/applyHighFlowHotends.js +115 -0
  99. package/dist/engine/applyPresetChanges.d.ts +12 -0
  100. package/dist/engine/applyPresetChanges.js +23 -0
  101. package/dist/engine/bedCenter.d.ts +19 -0
  102. package/dist/engine/bedCenter.js +34 -0
  103. package/dist/engine/buildFilamentConfigs.d.ts +18 -0
  104. package/dist/engine/buildFilamentConfigs.js +49 -0
  105. package/dist/engine/buildProjectSettings.d.ts +24 -0
  106. package/dist/engine/buildProjectSettings.js +164 -0
  107. package/dist/engine/carrySourceLayerHeight.d.ts +15 -0
  108. package/dist/engine/carrySourceLayerHeight.js +41 -0
  109. package/dist/engine/clampColorPenetration.d.ts +12 -0
  110. package/dist/engine/clampColorPenetration.js +28 -0
  111. package/dist/engine/clampToMachineLimits.d.ts +21 -0
  112. package/dist/engine/clampToMachineLimits.js +84 -0
  113. package/dist/engine/coerceValue.d.ts +15 -0
  114. package/dist/engine/coerceValue.js +56 -0
  115. package/dist/engine/collapseNozzleVariants.d.ts +31 -0
  116. package/dist/engine/collapseNozzleVariants.js +63 -0
  117. package/dist/engine/computeShifts.d.ts +12 -0
  118. package/dist/engine/computeShifts.js +339 -0
  119. package/dist/engine/constants.d.ts +11 -0
  120. package/dist/engine/constants.js +12 -0
  121. package/dist/engine/detectNozzleDiameter.d.ts +15 -0
  122. package/dist/engine/detectNozzleDiameter.js +29 -0
  123. package/dist/engine/detectVariantIndex.d.ts +39 -0
  124. package/dist/engine/detectVariantIndex.js +80 -0
  125. package/dist/engine/extractFilamentSlots.d.ts +18 -0
  126. package/dist/engine/extractFilamentSlots.js +88 -0
  127. package/dist/engine/filamentComplianceNames.d.ts +84 -0
  128. package/dist/engine/filamentComplianceNames.js +87 -0
  129. package/dist/engine/filamentVariantLayout.d.ts +29 -0
  130. package/dist/engine/filamentVariantLayout.js +38 -0
  131. package/dist/engine/fillFilamentSlots.d.ts +16 -0
  132. package/dist/engine/fillFilamentSlots.js +26 -0
  133. package/dist/engine/internal/jsonEqual.d.ts +2 -0
  134. package/dist/engine/internal/jsonEqual.js +5 -0
  135. package/dist/engine/parseTierName.d.ts +15 -0
  136. package/dist/engine/parseTierName.js +21 -0
  137. package/dist/engine/pickNearestProfile.d.ts +21 -0
  138. package/dist/engine/pickNearestProfile.js +24 -0
  139. package/dist/engine/pickProfile.d.ts +49 -0
  140. package/dist/engine/pickProfile.js +67 -0
  141. package/dist/engine/policy.d.ts +14 -0
  142. package/dist/engine/policy.js +266 -0
  143. package/dist/engine/remapBrimType.d.ts +30 -0
  144. package/dist/engine/remapBrimType.js +34 -0
  145. package/dist/engine/reshapeToCount.d.ts +15 -0
  146. package/dist/engine/reshapeToCount.js +27 -0
  147. package/dist/engine/resizeFlushVolumes.d.ts +27 -0
  148. package/dist/engine/resizeFlushVolumes.js +57 -0
  149. package/dist/engine/resolveMinIfLower.d.ts +21 -0
  150. package/dist/engine/resolveMinIfLower.js +59 -0
  151. package/dist/engine/runConvertPipeline.d.ts +79 -0
  152. package/dist/engine/runConvertPipeline.js +281 -0
  153. package/dist/engine/stripBambuOnlyNozzleVariantKeys.d.ts +2 -0
  154. package/dist/engine/stripBambuOnlyNozzleVariantKeys.js +35 -0
  155. package/dist/engine/types.d.ts +2 -0
  156. package/dist/engine/types.js +1 -0
  157. package/dist/errors.d.ts +18 -0
  158. package/dist/errors.js +9 -0
  159. package/dist/explain/whatChanged.d.ts +102 -0
  160. package/dist/explain/whatChanged.js +197 -0
  161. package/dist/index.d.ts +49 -0
  162. package/dist/index.js +33 -0
  163. package/dist/inspect.d.ts +63 -0
  164. package/dist/inspect.js +103 -0
  165. package/dist/node.d.ts +11 -0
  166. package/dist/node.js +50 -0
  167. package/dist/plainText.d.ts +10 -0
  168. package/dist/plainText.js +14 -0
  169. package/dist/presets/extractPreset.d.ts +13 -0
  170. package/dist/presets/extractPreset.js +87 -0
  171. package/dist/presets/preset.d.ts +124 -0
  172. package/dist/presets/preset.js +289 -0
  173. package/dist/presets/presetKeys.d.ts +5 -0
  174. package/dist/presets/presetKeys.js +42 -0
  175. package/dist/profiles.d.ts +184 -0
  176. package/dist/profiles.js +314 -0
  177. package/dist/project.d.ts +146 -0
  178. package/dist/project.js +342 -0
  179. package/dist/schema.d.ts +103 -0
  180. package/dist/schema.js +87 -0
  181. package/dist/stamp.d.ts +45 -0
  182. package/dist/stamp.js +111 -0
  183. package/dist/telemetry.d.ts +101 -0
  184. package/dist/telemetry.js +94 -0
  185. package/dist/version.d.ts +1 -0
  186. package/dist/version.js +3 -0
  187. package/dist/worker-entry.d.ts +1 -0
  188. package/dist/worker-entry.js +142 -0
  189. package/dist/worker.d.ts +86 -0
  190. package/dist/worker.js +97 -0
  191. package/dist/workerProtocol.d.ts +91 -0
  192. package/dist/workerProtocol.js +1 -0
  193. package/package.json +78 -12
  194. package/index.js +0 -3
@@ -0,0 +1,141 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import { zipSync } from "fflate";
3
+ import { Any2orcaError } from "../errors.js";
4
+ import { MAX_OBJECTS } from "../schema.js";
5
+ import { adaptModelSettings } from "./adaptModelSettings.js";
6
+ import { setApplicationMetadata } from "./setApplicationMetadata.js";
7
+ import { objectWorldBboxXY } from "./objectWorldBboxXY.js";
8
+ import { parseItemPositions } from "./parseItemPositions.js";
9
+ import { MODEL_SETTINGS_PATH, PROJECT_SETTINGS_PATH, SPECIAL_HANDLING, TOP_MODEL_PATH } from "./paths.js";
10
+ import { parseObjectMetadata } from "./parseObjectMetadata.js";
11
+ import { parsePlateAssignments } from "./parsePlateAssignments.js";
12
+ import { recenterAssembleItems } from "./recenterAssembleItems.js";
13
+ import { recenterBuildItems } from "./recenterBuildItems.js";
14
+ import { formatSize, LARGE_PROJECT_BYTES, safeUnzipSync } from "./safeUnzip.js";
15
+ import { shouldDropFromBambu } from "./shouldDropFromBambu.js";
16
+ import { tolerantJsonParse } from "./tolerantJsonParse.js";
17
+ const utf8Decoder = new TextDecoder("utf-8");
18
+ const utf8Encoder = new TextEncoder();
19
+ /** The largest main model file read as text: the engine's longest string is about 512 MB, and UTF-8 never takes fewer bytes than characters. */
20
+ const MAX_TOP_MODEL_BYTES = 500 * 1024 * 1024;
21
+ /**
22
+ * Unzip a source .3mf (already in memory as bytes) and build the conversion request payload: the
23
+ * full project_settings.config JSON, plus each top-level object's
24
+ * world-space bounding box (or its raw transform translation as a
25
+ * fallback when mesh geometry is missing), its plate assignment, and its name.
26
+ */
27
+ export function prepareConvertRequest(fileBytes, maxUnpackedBytes) {
28
+ const zipEntries = safeUnzipSync(fileBytes, maxUnpackedBytes);
29
+ const warnings = [];
30
+ const unpackedBytes = Object.values(zipEntries).reduce((n, bytes) => n + bytes.length, 0);
31
+ if (unpackedBytes > LARGE_PROJECT_BYTES) {
32
+ warnings.push(` WARN: This is a large project (${formatSize(unpackedBytes)} unpacked). Converting it takes a minute or two and a few GB of memory; close other apps or tabs if your computer has little memory.`);
33
+ }
34
+ // A sliced plate file (.gcode.3mf) holds G-code for the printer it was sliced for and usually no model; a
35
+ // converted copy would carry that G-code into a file labeled for the U1.
36
+ if (Object.keys(zipEntries).some((name) => /^Metadata\/plate_\d+\.gcode$/i.test(name))) {
37
+ throw new Any2orcaError("invalid_project", "This is a sliced plate file (.gcode.3mf): it holds G-code for the printer it was sliced for, not a project to convert. Convert the project file it was sliced from instead.");
38
+ }
39
+ const projectSettingsBytes = zipEntries[PROJECT_SETTINGS_PATH];
40
+ if (!projectSettingsBytes) {
41
+ throw new Any2orcaError("invalid_file", "This 3MF holds only the model, with no print settings, so there's nothing to convert: open it in Snapmaker Orca and choose a U1 profile.");
42
+ }
43
+ let parsed;
44
+ try {
45
+ parsed = tolerantJsonParse(utf8Decoder.decode(projectSettingsBytes));
46
+ }
47
+ catch (err) {
48
+ const reason = err instanceof Error ? err.message : String(err);
49
+ throw new Any2orcaError("invalid_file", "This project's print settings are damaged, so it can't be converted. Re-saving the project in its slicer usually fixes this.", { cause: new Error(`${PROJECT_SETTINGS_PATH} isn't valid JSON (${reason})`) });
50
+ }
51
+ const { value: projectSettings, trailingText } = parsed;
52
+ if (trailingText.trim()) {
53
+ warnings.push(` (note: ignored ${trailingText.length} bytes of trailing non-JSON content after project_settings.config, e.g. ${JSON.stringify(trailingText.slice(0, 60))})`);
54
+ }
55
+ const topModelBytes = zipEntries[TOP_MODEL_PATH];
56
+ if (!topModelBytes) {
57
+ throw new Any2orcaError("invalid_file", "This 3MF has no model in it, so there's nothing to convert.");
58
+ }
59
+ // The main model is read as text, and a JavaScript string can't be longer than about 512 MB. Slicers keep big
60
+ // meshes in their own part files (3D/Objects/), which are scanned in chunks; this only stops an odd file.
61
+ if (topModelBytes.length > MAX_TOP_MODEL_BYTES) {
62
+ throw new Any2orcaError("invalid_project", `This project's main model file is ${Math.round(topModelBytes.length / 1024 / 1024)} MB, more than the ${MAX_TOP_MODEL_BYTES / 1024 / 1024} MB any2orca can read in one piece. Re-saving the project in its slicer usually stores the meshes as separate files, which have no such limit.`);
63
+ }
64
+ const topModelText = utf8Decoder.decode(topModelBytes);
65
+ const modelSettingsBytes = zipEntries[MODEL_SETTINGS_PATH];
66
+ const modelSettingsText = modelSettingsBytes ? utf8Decoder.decode(modelSettingsBytes) : "";
67
+ const itemPositions = parseItemPositions(topModelText);
68
+ // Refused before any per-object work, which scans the model once per object.
69
+ const itemCount = Object.keys(itemPositions).length;
70
+ if (itemCount > MAX_OBJECTS) {
71
+ throw new Any2orcaError("invalid_project", `This project has ${itemCount} objects, more than the ${MAX_OBJECTS} a conversion supports.`);
72
+ }
73
+ const plateAssignments = modelSettingsText ? parsePlateAssignments(modelSettingsText) : {};
74
+ const objectMetadata = parseObjectMetadata(topModelText, modelSettingsText);
75
+ const partFileCache = new Map();
76
+ const objects = Object.entries(itemPositions).map(([id, fallbackXy]) => {
77
+ const bbox = objectWorldBboxXY(id, topModelText, partFileCache, zipEntries);
78
+ const plate = plateAssignments[id];
79
+ const meta = objectMetadata[id];
80
+ return {
81
+ id,
82
+ ...(meta?.name ? { name: meta.name } : {}),
83
+ ...(meta?.sequence !== undefined ? { sequence: meta.sequence } : {}),
84
+ ...(meta?.isAssembly !== undefined ? { isAssembly: meta.isAssembly } : {}),
85
+ ...(plate !== undefined ? { plate } : {}),
86
+ ...(bbox ? { bbox } : { bbox: null, fallbackXy }),
87
+ };
88
+ });
89
+ return {
90
+ zipEntries,
91
+ request: { projectSettings: projectSettings, objects },
92
+ warnings,
93
+ unpackedBytes,
94
+ };
95
+ }
96
+ /**
97
+ * Apply a conversion response to the originally parsed project and
98
+ * produce the final Snapmaker Orca .3mf bytes, ready to offer as a
99
+ * download. Copies every untouched zip entry verbatim (dropping
100
+ * Bambu-only files per shouldDropFromBambu), sets the Application line (or, when
101
+ * the catalog names none, adds the OrcaSlicer origin tag), recenters the build/assemble transforms using the
102
+ * response's shift map, adapts model_settings.config, and writes the
103
+ * response's merged project_settings.config plus every generated/
104
+ * passthrough config file. `extraEntries` are added last (the output stamp).
105
+ */
106
+ export function applyConvertResponse(parsed, response, extraEntries = {}) {
107
+ const { zipEntries, warnings } = parsed;
108
+ const outputEntries = {};
109
+ for (const [name, data] of Object.entries(zipEntries)) {
110
+ if (shouldDropFromBambu(name) || SPECIAL_HANDLING.has(name))
111
+ continue;
112
+ outputEntries[name] = data;
113
+ }
114
+ const modelSettingsBytes = zipEntries[MODEL_SETTINGS_PATH];
115
+ if (modelSettingsBytes) {
116
+ const adapted = adaptModelSettings(utf8Decoder.decode(modelSettingsBytes));
117
+ const recentered = recenterAssembleItems(adapted, response.shifts, warnings);
118
+ outputEntries[MODEL_SETTINGS_PATH] = utf8Encoder.encode(recentered);
119
+ }
120
+ const topModelBytes = zipEntries[TOP_MODEL_PATH];
121
+ if (topModelBytes) {
122
+ // The target slicer's own Application value, so the file says what a save in that release says.
123
+ const text = utf8Decoder.decode(topModelBytes);
124
+ const tagged = setApplicationMetadata(text, response.application);
125
+ const recentered = recenterBuildItems(tagged, response.shifts, warnings);
126
+ outputEntries[TOP_MODEL_PATH] = utf8Encoder.encode(recentered);
127
+ }
128
+ for (const [arcname, config] of Object.entries(response.configFiles)) {
129
+ outputEntries[arcname] = utf8Encoder.encode(JSON.stringify(config, null, 4));
130
+ }
131
+ outputEntries[PROJECT_SETTINGS_PATH] = utf8Encoder.encode(JSON.stringify(response.projectSettings, null, 4));
132
+ for (const [arcname, data] of Object.entries(extraEntries)) {
133
+ outputEntries[arcname] = data;
134
+ }
135
+ // A fixed entry time, so the same input and options always give the same
136
+ // bytes (stable checksums in a publish step), and a converted file doesn't
137
+ // record when, or in which time zone, it was converted. Zip times are local
138
+ // clock fields, so a Date built from local fields encodes identically everywhere.
139
+ return zipSync(outputEntries, { level: 9, mtime: FIXED_ENTRY_TIME });
140
+ }
141
+ const FIXED_ENTRY_TIME = new Date(2000, 0, 1, 0, 0, 0);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Moves `filePath` into `archiveDir` after a fully successful conversion --
3
+ * the recommended workflow when it fits:
4
+ * the archive dir becomes the record of what's already been handled, so
5
+ * there's nothing left in the watched folder to ever re-scan, re-unzip, or
6
+ * consult a state file for.
7
+ *
8
+ * Collision-safe: never silently overwrites an earlier archived original
9
+ * that happens to share a name (e.g. the same filename dropped in twice on
10
+ * different days). Atomic where possible -- a same-filesystem rename, so
11
+ * there's no window where the file could appear duplicated or lost; only
12
+ * falls back to copy-then-delete across filesystems (EXDEV), and only
13
+ * removes the original once the copy has fully completed.
14
+ */
15
+ export declare function archiveOriginal(filePath: string, archiveDir: string): string;
@@ -0,0 +1,41 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import { copyFileSync, existsSync, mkdirSync, renameSync, unlinkSync } from "node:fs";
3
+ import { basename, extname, join, resolve } from "node:path";
4
+ /**
5
+ * Moves `filePath` into `archiveDir` after a fully successful conversion --
6
+ * the recommended workflow when it fits:
7
+ * the archive dir becomes the record of what's already been handled, so
8
+ * there's nothing left in the watched folder to ever re-scan, re-unzip, or
9
+ * consult a state file for.
10
+ *
11
+ * Collision-safe: never silently overwrites an earlier archived original
12
+ * that happens to share a name (e.g. the same filename dropped in twice on
13
+ * different days). Atomic where possible -- a same-filesystem rename, so
14
+ * there's no window where the file could appear duplicated or lost; only
15
+ * falls back to copy-then-delete across filesystems (EXDEV), and only
16
+ * removes the original once the copy has fully completed.
17
+ */
18
+ export function archiveOriginal(filePath, archiveDir) {
19
+ mkdirSync(archiveDir, { recursive: true });
20
+ const dest = uniqueDestination(filePath, archiveDir);
21
+ try {
22
+ renameSync(filePath, dest);
23
+ }
24
+ catch (err) {
25
+ if (err.code !== "EXDEV")
26
+ throw err;
27
+ copyFileSync(filePath, dest);
28
+ unlinkSync(filePath);
29
+ }
30
+ return dest;
31
+ }
32
+ function uniqueDestination(filePath, archiveDir) {
33
+ const resolvedDir = resolve(archiveDir);
34
+ const ext = extname(filePath);
35
+ const base = basename(filePath, ext);
36
+ let candidate = join(resolvedDir, `${base}${ext}`);
37
+ for (let n = 1; existsSync(candidate); n++) {
38
+ candidate = join(resolvedDir, `${base}-${n}${ext}`);
39
+ }
40
+ return candidate;
41
+ }
@@ -0,0 +1,89 @@
1
+ import type { MatchSource } from "../../schema.js";
2
+ import type { ProfileCatalog } from "../../profiles.js";
3
+ import type { Preset } from "../../presets/preset.js";
4
+ import type { AboveStockChoice } from "../../engine/aboveStock.js";
5
+ import type { Logger } from "../logger.js";
6
+ import type { StatsReporter } from "../stats.js";
7
+ export interface ConvertOptions {
8
+ catalog: ProfileCatalog;
9
+ profile?: string;
10
+ /** Convert onto this preset's base profile with its settings (--preset). */
11
+ preset?: Preset;
12
+ /** --use-stock / --keep-higher: the choice for values above stock. */
13
+ aboveStock?: AboveStockChoice;
14
+ filamentCompliance?: "generic" | "snapmaker";
15
+ /** --high-flow: all four toolheads have the Liber High Flow Hotend. */
16
+ /** All toolheads have the Liber hotend (true), or exactly these ones, T1 first. */
17
+ highFlow?: boolean | boolean[];
18
+ hardenedNozzle?: boolean;
19
+ /** Leave the version note (Metadata/any2orca.json) out of the converted file. */
20
+ noStamp?: boolean;
21
+ /** --max-unpacked: the most a project may unpack to, in bytes (default 2 GB). */
22
+ maxUnpackedBytes?: number;
23
+ /** --explain: print what the conversion changed, grouped by why. */
24
+ explain?: boolean;
25
+ /** --explain-json: also write it, with every settings difference, as <output>.what-changed.json. */
26
+ explainJson?: boolean;
27
+ outDir?: string;
28
+ archiveDir?: string;
29
+ suffix: string;
30
+ dryRun: boolean;
31
+ verbose: boolean;
32
+ skipExisting: boolean;
33
+ /** True under `convert --watch`; only affects whether state tracking is on (see {@link runConvert}). */
34
+ watch: boolean;
35
+ logger: Logger;
36
+ stats?: StatsReporter;
37
+ }
38
+ export interface ConvertRunSummary {
39
+ converted: number;
40
+ failed: number;
41
+ }
42
+ /**
43
+ * The output path for one converted entry: the entry's own name (a
44
+ * bundle's nested name, or the input file name) with `suffix` added, next
45
+ * to the input unless `--out-dir` is set.
46
+ */
47
+ export declare function computeOutputPath(entryName: string, defaultDir: string, suffix: string, outDir: string | undefined): string;
48
+ /**
49
+ * --skip-existing's check. Opt-in on purpose: an output is a re-derivable
50
+ * build artifact, so overwriting is the right default; this is for
51
+ * resuming an interrupted batch.
52
+ */
53
+ export declare function shouldSkipExisting(outPath: string, skipExisting: boolean): boolean;
54
+ /**
55
+ * A line for the two match outcomes worth printing: no match at all
56
+ * (fell back to the default) and closest-but-not-exact. A confident match
57
+ * gets nothing here.
58
+ */
59
+ export declare function matchWarningLine(matchSource: MatchSource, profileIdLabel: string): string | null;
60
+ /**
61
+ * Whether retrying this exact file could give a different result. A
62
+ * conversion is deterministic, so a problem with the file itself is
63
+ * permanent; a filesystem hiccup (disk full, file locked) or an unreadable
64
+ * profile catalog is not.
65
+ */
66
+ export declare function isPermanentFailure(err: unknown): boolean;
67
+ /**
68
+ * Converts each input in turn. One bad file (or one bad entry in a bundle)
69
+ * doesn't stop the rest. With state tracking on, records each input's
70
+ * outcome so an unchanged file isn't redone, and with --archive-dir moves
71
+ * a fully converted input out of the way.
72
+ */
73
+ export declare function runConvert(inputPaths: string[], options: ConvertOptions): Promise<ConvertRunSummary>;
74
+ /** Per-file state a watch session keeps between polls. Exported for tests. */
75
+ export interface WatchState {
76
+ /** The fingerprint last seen per file name, to tell when a file has stopped changing. */
77
+ lastFingerprint: Map<string, string>;
78
+ /** "name:fingerprint" already handed to runConvert this session; an edited file gets a new key. */
79
+ reported: Set<string>;
80
+ }
81
+ export declare function createWatchState(): WatchState;
82
+ /**
83
+ * One poll over `folder`: converts each file whose fingerprint is unchanged
84
+ * since the previous poll (so a file still being copied in isn't read
85
+ * half-written) and that hasn't been handled this session.
86
+ */
87
+ export declare function watchPollOnce(folder: string, options: ConvertOptions, state: WatchState): Promise<void>;
88
+ /** Watches `folder` and converts each new .3mf/.zip as it settles, until interrupted. */
89
+ export declare function runWatch(folder: string, options: ConvertOptions): Promise<never>;
@@ -0,0 +1,311 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, extname, join, resolve } from "node:path";
4
+ import { Any2orcaError } from "../../errors.js";
5
+ import { formatWhatChanged } from "../../explain/whatChanged.js";
6
+ import { openProject, unwrapBundle } from "../../project.js";
7
+ import { archiveOriginal } from "../archiveMove.js";
8
+ import { describeFsError, isSamePath } from "../sameFile.js";
9
+ import { computeFingerprint, loadStateFile, saveStateFile } from "../watchState.js";
10
+ /** An error as the CLI prints it. A project over the size limit gets the CLI's own way to raise it, not the library's. */
11
+ function errorText(err) {
12
+ if (err instanceof Any2orcaError && err.code === "too_large") {
13
+ return `${err.message.split(". ")[0].replace(/\.$/, "")}. Raise the limit with --max-unpacked, for example --max-unpacked 4GB; it needs about twice that much memory.`;
14
+ }
15
+ return err instanceof Error ? err.message : String(err);
16
+ }
17
+ /**
18
+ * The output path for one converted entry: the entry's own name (a
19
+ * bundle's nested name, or the input file name) with `suffix` added, next
20
+ * to the input unless `--out-dir` is set.
21
+ */
22
+ export function computeOutputPath(entryName, defaultDir, suffix, outDir) {
23
+ const dir = resolveWorkDir(defaultDir, outDir);
24
+ const base = basename(entryName, extname(entryName));
25
+ return join(dir, `${base}${suffix}.3mf`);
26
+ }
27
+ /** Where outputs and the state file go: `--out-dir` if set, otherwise alongside the input. */
28
+ function resolveWorkDir(defaultDir, outDir) {
29
+ return outDir ? resolve(outDir) : resolve(defaultDir);
30
+ }
31
+ /**
32
+ * --skip-existing's check. Opt-in on purpose: an output is a re-derivable
33
+ * build artifact, so overwriting is the right default; this is for
34
+ * resuming an interrupted batch.
35
+ */
36
+ export function shouldSkipExisting(outPath, skipExisting) {
37
+ return skipExisting && existsSync(outPath);
38
+ }
39
+ /**
40
+ * A line for the two match outcomes worth printing: no match at all
41
+ * (fell back to the default) and closest-but-not-exact. A confident match
42
+ * gets nothing here.
43
+ */
44
+ export function matchWarningLine(matchSource, profileIdLabel) {
45
+ if (matchSource === "default-fallback") {
46
+ return (` WARNING: no confident profile match found for this file (neither its layer height nor its quality name, such as Standard or Fine, matched a U1 profile), ` +
47
+ `so it falls back to ${profileIdLabel}. Consider passing --profile <id> explicitly (see "any2orca profiles").`);
48
+ }
49
+ if (matchSource === "auto-nearest") {
50
+ return ` note: ${profileIdLabel} is the closest available layer height, not an exact match.`;
51
+ }
52
+ return null;
53
+ }
54
+ function logReport(report, verbose, logger) {
55
+ if (report.profileMatch) {
56
+ const line = matchWarningLine(report.profileMatch.matchSource, report.profile.id);
57
+ if (line)
58
+ logger.log(line);
59
+ else if (verbose)
60
+ logger.log(` matched profile: ${report.profile.id} (${report.profileMatch.matchSource})`);
61
+ }
62
+ else if (verbose) {
63
+ logger.log(` profile: ${report.profile.id}`);
64
+ }
65
+ if (report.preset) {
66
+ const above = report.preset.changes.filter((c) => c.aboveStock).length;
67
+ logger.log(` preset: ${report.preset.changes.length} setting${report.preset.changes.length === 1 ? "" : "s"} set${above > 0 ? `, ${above} above stock` : ""}`);
68
+ if (verbose)
69
+ for (const c of report.preset.changes)
70
+ logger.log(` preset: ${c.key} ${c.stock} -> ${c.yours}${c.aboveStock ? " (above stock)" : ""}`);
71
+ }
72
+ const fallback = report.filamentComplianceFallback ?? [];
73
+ if (fallback.length > 0) {
74
+ logger.log(` note: Snapmaker makes no preset for ${fallback.join(", ")} at this nozzle size, so ${fallback.length === 1 ? "it uses" : "those use"} Generic.`);
75
+ }
76
+ const unchanged = report.filamentComplianceUnchanged ?? [];
77
+ if (unchanged.length > 0) {
78
+ logger.log(` note: no Snapmaker or Generic preset fits ${unchanged.join(", ")} at this nozzle size, so ${unchanged.length === 1 ? "its name stays" : "those names stay"} as the creator had ${unchanged.length === 1 ? "it" : "them"}.`);
79
+ }
80
+ for (const w of report.warnings)
81
+ logger.log(` warning: ${w}`);
82
+ if (verbose)
83
+ for (const line of report.log)
84
+ logger.log(` log: ${line}`);
85
+ }
86
+ /**
87
+ * Whether retrying this exact file could give a different result. A
88
+ * conversion is deterministic, so a problem with the file itself is
89
+ * permanent; a filesystem hiccup (disk full, file locked) or an unreadable
90
+ * profile catalog is not.
91
+ */
92
+ export function isPermanentFailure(err) {
93
+ if (err instanceof Any2orcaError)
94
+ return err.code === "invalid_file" || err.code === "too_large" || err.code === "invalid_project" || err.code === "profile_not_found" || err.code === "invalid_preset";
95
+ const code = err?.code;
96
+ if (typeof code === "string" && /^E[A-Z]+$/.test(code))
97
+ return false;
98
+ return true;
99
+ }
100
+ async function convertOne(entryName, bytes, defaultDir, originalInputPath, options, written) {
101
+ const { logger } = options;
102
+ const outPath = computeOutputPath(entryName, defaultDir, options.suffix, options.outDir);
103
+ // Compared by file identity too, so a case-only difference or a symlink to the input is caught.
104
+ if (resolve(outPath) === resolve(originalInputPath) || isSamePath(outPath, originalInputPath)) {
105
+ throw new Error(`Refusing to run: the output path for "${entryName}" (${outPath}) is the input file itself. Use --out-dir to write somewhere else, or a non-empty --suffix.`);
106
+ }
107
+ for (const [earlier, from] of written) {
108
+ if (resolve(earlier) === resolve(outPath) || isSamePath(earlier, outPath)) {
109
+ throw new Error(`Not converted: its output, ${outPath}, was already written in this run from ${from}. Give the inputs different names or convert them separately.`);
110
+ }
111
+ }
112
+ if (shouldSkipExisting(outPath, options.skipExisting)) {
113
+ logger.log(`${options.dryRun ? "[dry-run] " : ""}${entryName}: skipped (already exists at ${outPath})`);
114
+ return;
115
+ }
116
+ const project = openProject(bytes, { maxUnpackedBytes: options.maxUnpackedBytes });
117
+ if (options.dryRun) {
118
+ logger.log(`[dry-run] ${entryName}`);
119
+ if (options.preset) {
120
+ logger.log(` profile: ${options.preset.base} (from preset ${options.preset.name}, ${Object.keys(options.preset.changes).length} changes)`);
121
+ }
122
+ else if (options.profile) {
123
+ logger.log(` profile: ${options.profile}`);
124
+ }
125
+ else {
126
+ const choice = await project.matchProfile(options.catalog);
127
+ const shown = options.catalog.get(choice.profileId)?.displayName ?? choice.profileId;
128
+ logger.log(` predicted profile: ${shown} (${choice.profileId})`);
129
+ const line = matchWarningLine(choice.profileMatch.matchSource, choice.profileId);
130
+ if (line)
131
+ logger.log(line);
132
+ }
133
+ logger.log(` would write: ${outPath}`);
134
+ written.set(outPath, originalInputPath);
135
+ return;
136
+ }
137
+ const { output, report } = await project.convert({
138
+ profiles: options.catalog,
139
+ ...(options.profile ? { profileId: options.profile } : {}),
140
+ ...(options.preset ? { preset: options.preset } : {}),
141
+ ...(options.aboveStock ? { aboveStock: options.aboveStock } : {}),
142
+ ...(options.filamentCompliance ? { filamentComplianceMode: options.filamentCompliance } : {}),
143
+ ...(options.highFlow ? { highFlowHotends: options.highFlow } : {}),
144
+ ...(options.hardenedNozzle ? { hardenedNozzles: true } : {}),
145
+ ...(options.noStamp ? { stamp: false } : {}),
146
+ ...(options.explainJson ? { explain: true } : {}),
147
+ });
148
+ // The result line comes first, so in a batch each file's notes sit under its own name.
149
+ const replaced = existsSync(outPath);
150
+ writeFileSync(outPath, output);
151
+ written.set(outPath, originalInputPath);
152
+ logger.log(`${entryName} -> ${outPath}${replaced ? " (replaced)" : ""}`);
153
+ logReport(report, options.verbose, logger);
154
+ if (options.explain)
155
+ for (const line of formatWhatChanged(report.whatChanged, { cliHints: true }).split("\n"))
156
+ logger.log(` ${line}`.trimEnd());
157
+ if (options.explainJson) {
158
+ const jsonPath = outPath.replace(/\.3mf$/i, ".what-changed.json");
159
+ writeFileSync(jsonPath, `${JSON.stringify(report.whatChanged, null, 2)}\n`);
160
+ logger.log(` what changed: ${jsonPath}`);
161
+ }
162
+ await options.stats?.afterConversion(report, project.inspect());
163
+ }
164
+ /** State tracking is on for repeated or resumable runs (--watch, --archive-dir, --skip-existing), never for --dry-run. */
165
+ function isStateTrackingActive(options) {
166
+ return !options.dryRun && (options.watch || Boolean(options.archiveDir) || options.skipExisting);
167
+ }
168
+ /**
169
+ * Converts each input in turn. One bad file (or one bad entry in a bundle)
170
+ * doesn't stop the rest. With state tracking on, records each input's
171
+ * outcome so an unchanged file isn't redone, and with --archive-dir moves
172
+ * a fully converted input out of the way.
173
+ */
174
+ export async function runConvert(inputPaths, options) {
175
+ const { logger } = options;
176
+ const tracking = isStateTrackingActive(options);
177
+ const summary = { converted: 0, failed: 0 };
178
+ const written = new Map();
179
+ for (const inputPath of inputPaths) {
180
+ const name = basename(inputPath);
181
+ const defaultDir = dirname(resolve(inputPath));
182
+ const workDir = resolveWorkDir(defaultDir, options.outDir);
183
+ if (tracking) {
184
+ let fingerprint;
185
+ try {
186
+ fingerprint = computeFingerprint(inputPath);
187
+ }
188
+ catch (err) {
189
+ logger.error(`Could not read ${name}: ${describeFsError(err)}`);
190
+ summary.failed++;
191
+ continue;
192
+ }
193
+ const record = loadStateFile(workDir)[name];
194
+ if (record && record.fingerprint === fingerprint && record.outcome !== "failed-once") {
195
+ if (record.outcome === "succeeded")
196
+ logger.log(`${name}: already converted (unchanged since last run), skipping`);
197
+ else
198
+ logger.log(`${name}: skipping, it failed last time with an error retrying won't fix (unchanged since). Fix or replace the file to retry.`);
199
+ continue;
200
+ }
201
+ }
202
+ let bytes;
203
+ try {
204
+ bytes = new Uint8Array(readFileSync(inputPath));
205
+ }
206
+ catch (err) {
207
+ logger.error(`Error reading ${name}: ${describeFsError(err)}`);
208
+ summary.failed++;
209
+ continue;
210
+ }
211
+ const entries = unwrapBundle(bytes, { maxUnpackedBytes: options.maxUnpackedBytes }) ?? [{ name, bytes }];
212
+ let anyFailed = false;
213
+ let allFailuresPermanent = true;
214
+ for (const entry of entries) {
215
+ try {
216
+ await convertOne(entry.name, entry.bytes, defaultDir, inputPath, options, written);
217
+ summary.converted++;
218
+ }
219
+ catch (err) {
220
+ anyFailed = true;
221
+ summary.failed++;
222
+ if (!isPermanentFailure(err))
223
+ allFailuresPermanent = false;
224
+ logger.error(`Error converting ${entry.name}: ${errorText(err)}`);
225
+ }
226
+ }
227
+ if (tracking)
228
+ recordOutcome(workDir, name, inputPath, anyFailed, allFailuresPermanent);
229
+ if (!anyFailed && options.archiveDir && !options.dryRun) {
230
+ try {
231
+ logger.log(`${name}: archived to ${archiveOriginal(inputPath, options.archiveDir)}`);
232
+ }
233
+ catch (err) {
234
+ logger.error(`Could not archive ${name}: ${err instanceof Error ? err.message : String(err)}`);
235
+ }
236
+ }
237
+ }
238
+ return summary;
239
+ }
240
+ /**
241
+ * Records "succeeded", or for a failure retrying won't fix, "failed-once"
242
+ * the first time and "permanently-failed" when the same unchanged file
243
+ * fails again. The one retry is for a file still being copied in: some
244
+ * copies set the final size and time before every byte has arrived, so a
245
+ * half-written file can look settled. A transient failure records nothing.
246
+ */
247
+ function recordOutcome(workDir, name, inputPath, anyFailed, allFailuresPermanent) {
248
+ if (anyFailed && !allFailuresPermanent)
249
+ return;
250
+ const state = loadStateFile(workDir);
251
+ const fingerprint = computeFingerprint(inputPath);
252
+ const failedBefore = state[name]?.outcome === "failed-once" && state[name]?.fingerprint === fingerprint;
253
+ state[name] = { fingerprint, outcome: !anyFailed ? "succeeded" : failedBefore ? "permanently-failed" : "failed-once" };
254
+ saveStateFile(workDir, state);
255
+ }
256
+ const WATCH_POLL_INTERVAL_MS = 2000;
257
+ function sleep(ms) {
258
+ return new Promise((res) => setTimeout(res, ms));
259
+ }
260
+ function isConvertibleFile(name) {
261
+ const ext = extname(name).toLowerCase();
262
+ return ext === ".3mf" || ext === ".zip";
263
+ }
264
+ export function createWatchState() {
265
+ return { lastFingerprint: new Map(), reported: new Set() };
266
+ }
267
+ /**
268
+ * One poll over `folder`: converts each file whose fingerprint is unchanged
269
+ * since the previous poll (so a file still being copied in isn't read
270
+ * half-written) and that hasn't been handled this session.
271
+ */
272
+ export async function watchPollOnce(folder, options, state) {
273
+ for (const name of readdirSync(folder).filter(isConvertibleFile)) {
274
+ const fullPath = join(folder, name);
275
+ let fingerprint;
276
+ try {
277
+ fingerprint = computeFingerprint(fullPath);
278
+ }
279
+ catch {
280
+ continue; // vanished between readdir and stat; reconsider next poll
281
+ }
282
+ const key = `${name}:${fingerprint}`;
283
+ if (state.reported.has(key))
284
+ continue;
285
+ const previous = state.lastFingerprint.get(name);
286
+ state.lastFingerprint.set(name, fingerprint);
287
+ if (previous !== fingerprint)
288
+ continue; // still being written, or just appeared
289
+ state.reported.add(key);
290
+ try {
291
+ await runConvert([fullPath], options);
292
+ }
293
+ catch (err) {
294
+ options.logger.error(`Error converting ${name}: ${errorText(err)}`);
295
+ }
296
+ // Failed once: let it settle again and retry, in case it was still being written.
297
+ if (loadStateFile(resolveWorkDir(folder, options.outDir))[name]?.outcome === "failed-once") {
298
+ state.reported.delete(key);
299
+ state.lastFingerprint.delete(name);
300
+ }
301
+ }
302
+ }
303
+ /** Watches `folder` and converts each new .3mf/.zip as it settles, until interrupted. */
304
+ export async function runWatch(folder, options) {
305
+ const state = createWatchState();
306
+ options.logger.log(`Watching ${folder} for new .3mf/.zip files (Ctrl+C to stop)...`);
307
+ for (;;) {
308
+ await watchPollOnce(folder, options, state);
309
+ await sleep(WATCH_POLL_INTERVAL_MS);
310
+ }
311
+ }
@@ -0,0 +1,21 @@
1
+ import { type DiffGroupName, type SettingsDiff } from "../../diff/diffSettings.js";
2
+ import type { Preset } from "../../presets/preset.js";
3
+ import type { ProfileCatalog } from "../../profiles.js";
4
+ export interface DiffCommandOptions {
5
+ files: string[];
6
+ /** Compare the one file with Snapmaker's stock profile: true for the profile auto-matching picks, or a profile id. */
7
+ againstStock?: true | string;
8
+ /** Compare the one file with a preset as it converts: its base profile's stock settings with its changes. */
9
+ againstPreset?: Preset;
10
+ groups?: DiffGroupName[];
11
+ json: boolean;
12
+ all: boolean;
13
+ /** Row order within each group: values needing attention first (default), Snapmaker Orca's page order, or by status. */
14
+ sort?: DiffSort;
15
+ catalog: ProfileCatalog;
16
+ }
17
+ export type DiffSort = "attention" | "setting" | "status";
18
+ /** The text report: a heading per group, then setting, first value, second value, status, and a note on values above stock or the U1's limits. */
19
+ export declare function formatDiff(diff: SettingsDiff, sort?: DiffSort): string;
20
+ /** `any2orca diff`: returns the exit code (0 no differences, 1 differences). Errors throw and exit 2. */
21
+ export declare function runDiff(options: DiffCommandOptions, out: (line: string) => void): Promise<number>;