any2orca 0.0.0-stage → 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 (193) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +28 -0
  4. package/README.md +99 -2
  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 +85 -4
@@ -0,0 +1,598 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import { existsSync, mkdirSync, statSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { createInterface } from "node:readline/promises";
5
+ import { parseArgs } from "node:util";
6
+ import { bundledProfileSource, dirProfileSource } from "../node.js";
7
+ import { loadCatalog } from "../profiles.js";
8
+ import { VERSION } from "../version.js";
9
+ import { MAX_UNPACKED_BYTES_LIMIT } from "../archive/safeUnzip.js";
10
+ import { runConvert, runWatch } from "./commands/convert.js";
11
+ import { runDiff } from "./commands/diff.js";
12
+ import { presetForConvert, presetForDiff, runPresetsAdd, runPresetsExport, runPresetsImport, runPresetsList, runPresetsRemove, runPresetsShow, } from "./commands/presets.js";
13
+ import { resolveAboveStockChoice } from "../engine/aboveStock.js";
14
+ import { runProfiles } from "./commands/profiles.js";
15
+ import { runTelemetryClear, runTelemetrySet, runTelemetryShow, runUpdateCheckSet } from "./commands/telemetry.js";
16
+ import { readCliConfig } from "./config.js";
17
+ import { expandInputPatterns } from "./expandWildcards.js";
18
+ import { describeFsError, isSamePath } from "./sameFile.js";
19
+ import { createLogger } from "./logger.js";
20
+ import { createStatsReporter, resolveStatsStatus } from "./stats.js";
21
+ import { formatTable } from "./table.js";
22
+ import { escapeUnsafeForJson, safeTerminalText } from "./terminalText.js";
23
+ import { refreshUpdateCache, updateCheckDisabledReason, updateNotice } from "./updateCheck.js";
24
+ const HELP_WIDTH = 100;
25
+ /** Option tables with descriptions wrapped to fit HELP_WIDTH columns, continuation lines under the description. */
26
+ function formatOptions(entries) {
27
+ const flagWidth = Math.max(...entries.map(([flag]) => flag.length + 2));
28
+ const indent = flagWidth + 3;
29
+ const wrapWidth = Math.max(40, HELP_WIDTH - indent);
30
+ return formatTable(entries.map(([flag, description]) => [` ${flag}`, wrapText(description, wrapWidth).join(`\n${" ".repeat(indent)}`)]), 3);
31
+ }
32
+ function wrapText(text, width) {
33
+ const lines = [];
34
+ let line = "";
35
+ for (const word of text.split(" ")) {
36
+ if (line && line.length + 1 + word.length > width) {
37
+ lines.push(line);
38
+ line = word;
39
+ }
40
+ else {
41
+ line = line ? `${line} ${word}` : word;
42
+ }
43
+ }
44
+ if (line)
45
+ lines.push(line);
46
+ return lines;
47
+ }
48
+ const TOP_LEVEL_HELP = `any2orca ${VERSION}: convert Bambu Studio, Creality Print and Anycubic Slicer Next .3mf projects to Snapmaker U1 / Orca format, entirely on this machine.
49
+
50
+ Usage: any2orca <command> [options]
51
+
52
+ Commands:
53
+ ${formatOptions([
54
+ ["convert <files...>", "Convert one or more .3mf files (or bundle .zip files of several)"],
55
+ ["diff <a.3mf> <b.3mf>", "Compare the settings of two projects, or one with Snapmaker's stock profile"],
56
+ ["presets add | list | show | ...", "Save your own tuned print settings from a 3MF and convert with them"],
57
+ ["profiles", "List the profiles convert can use"],
58
+ ["telemetry show | on | off | clear", "Show or change usage stats and the update check"],
59
+ ["--version", "Print the version"],
60
+ ])}
61
+
62
+ Run "any2orca <command> --help" for a command's options.
63
+ Nothing you convert ever leaves this machine. See "any2orca telemetry show" for the
64
+ only requests this tool can make.
65
+ `;
66
+ const DIFF_HELP = `Usage: any2orca diff <a.3mf> <b.3mf> [options]
67
+ any2orca diff <file.3mf> --against-stock [<profile id>] [options]
68
+ any2orca diff <file.3mf> --against-preset <name|file> [options]
69
+
70
+ Compares project settings the way Snapmaker Orca groups and names them: print
71
+ settings, each filament slot, machine settings, and anything that isn't a
72
+ Snapmaker Orca setting at all. Only differences are listed unless --all.
73
+
74
+ --against-stock compares one project with Snapmaker's stock profile: the one
75
+ convert would pick for it, or the profile id given (see "any2orca profiles").
76
+ It compares print and machine settings; filaments come from the creator, so
77
+ add --group filament to compare them too.
78
+
79
+ --against-preset compares one project with a preset as it converts: its base
80
+ profile's stock settings with the preset's changes. Give a saved preset's name
81
+ (see "any2orca presets list") or a presets file holding one preset. A preset
82
+ holds print settings only, so only those are compared unless you add --group.
83
+
84
+ Options:
85
+ ${formatOptions([
86
+ ["--against-stock [<id>]", "Compare one project with Snapmaker's stock profile"],
87
+ ["--against-preset <name|file>", "Compare one project with a saved preset, or a presets file holding one"],
88
+ ["--group <name>", "Only this group: print, filament, machine or other (repeatable)"],
89
+ ["--all", "Also list settings that are the same"],
90
+ ["--sort <order>", "attention (default: values above the U1's limits, then above stock, first), setting (Snapmaker Orca's page order) or status"],
91
+ ["--json", "Print the full result as JSON (format any2orca-diff, version 1)"],
92
+ ["--profiles-dir <dir>", "Use a profile catalog folder instead of the bundled one"],
93
+ ["-h, --help", "Show this help"],
94
+ ])}
95
+
96
+ Values are measured against the stock profile compared with (the preset's
97
+ base profile for --against-preset, or, for two files, the profile the first
98
+ would convert with): a speed or acceleration above the U1's machine limits is
99
+ marked "above the U1's limit (capped)", and one above Snapmaker's stock value
100
+ "above stock". Those rows come first.
101
+
102
+ Exit codes: 0 no differences, 1 differences, 2 an error.
103
+ `;
104
+ const PROFILES_HELP = `Usage: any2orca profiles [options]
105
+
106
+ Lists the profiles "convert --profile <id>" accepts.
107
+
108
+ Options:
109
+ ${formatOptions([
110
+ ["--nozzle <mm>", "Only list profiles for this nozzle diameter, e.g. 0.4"],
111
+ ["--profiles-dir <dir>", "Use a profile catalog folder instead of the bundled one"],
112
+ ["-h, --help", "Show this help"],
113
+ ])}
114
+ `;
115
+ const PRESETS_HELP = `Usage: any2orca presets add <name> <tuned.3mf> [--above-stock keep|stock | --keep <settings>] [--force]
116
+ any2orca presets list [--json]
117
+ any2orca presets show <name> [--json]
118
+ any2orca presets remove <name>
119
+ any2orca presets export [<name>...] [--out <file>] [--force]
120
+ any2orca presets import <file> [--above-stock keep|stock | --keep <settings>] [--force]
121
+
122
+ A preset is your own print settings, applied to other people's models:
123
+ make one from a .3mf you tuned in Snapmaker Orca, then convert with
124
+ "any2orca convert <files...> --preset <name>". It keeps only the print
125
+ settings you changed from the U1 profile the file was tuned on: walls,
126
+ infill, supports, speeds, seams and so on. Machine settings, G-code,
127
+ filaments and the model's layout are never part of a preset.
128
+
129
+ Speeds and accelerations above Snapmaker's stock values are listed before
130
+ saving, and need a choice: keep them all, use Snapmaker's stock value for
131
+ all, or keep only some. The U1's machine limits still cap them.
132
+
133
+ Presets are saved in ${"$"}ANY2ORCA_CONFIG_DIR/presets (default
134
+ ~/.config/any2orca/presets), one any2orca-presets file per preset, the same
135
+ format the web app exports and imports.
136
+
137
+ Options:
138
+ ${formatOptions([
139
+ ["--above-stock keep|stock", "For speeds or accelerations above stock: keep them all, or use Snapmaker's stock value for all"],
140
+ ["--keep <setting,...>", "Keep only these settings above stock (keys, e.g. sparse_infill_speed); the rest use stock"],
141
+ ["--force", "Replace a preset (or export file) with the same name"],
142
+ ["--out <file>", "export: write to this file instead of printing"],
143
+ ["--json", "list, show: print JSON"],
144
+ ["--profiles-dir <dir>", "Use a profile catalog folder instead of the bundled one"],
145
+ ["-h, --help", "Show this help"],
146
+ ])}
147
+ `;
148
+ const TELEMETRY_HELP = `Usage: any2orca telemetry show
149
+ any2orca telemetry on | off
150
+ any2orca telemetry clear
151
+ any2orca telemetry update-check on | off
152
+
153
+ ${formatOptions([
154
+ ["show", "What this tool can contact, its current settings, and the stats events it has sent"],
155
+ ["on | off", "Share anonymous usage stats (off unless you turn it on)"],
156
+ ["clear", "Delete the local log of sent stats events"],
157
+ ["update-check on | off", "The once-a-day check for a newer version (on by default)"],
158
+ ])}
159
+
160
+ Environment: ANY2ORCA_TELEMETRY=1|0, DO_NOT_TRACK=1 (always off),
161
+ ANY2ORCA_STATS_ENDPOINT=<https url> (your own collector), NO_UPDATE_NOTIFIER=1.
162
+ `;
163
+ const CONVERT_HELP = `Usage: any2orca convert <files...> [options]
164
+
165
+ Converts .3mf files to Snapmaker U1 / Orca format on this machine. A .zip
166
+ bundling several .3mf files (e.g. a "download all variants" archive) is
167
+ expanded into a batch automatically. Files are converted one at a time.
168
+
169
+ * and ? in a file name are expanded by this command, so "models/*.3mf" works in
170
+ Command Prompt and PowerShell too (file names only, not folder names).
171
+
172
+ Arguments:
173
+ ${formatOptions([["<files...>", "One or more .3mf or bundle .zip files. Omit when using --watch"]])}
174
+
175
+ Options:
176
+ ${formatOptions([
177
+ ["--profile <id>", 'Use this profile instead of matching one (see "any2orca profiles")'],
178
+ ["--preset <name|file>", 'Convert with your saved preset (see "any2orca presets"), or a presets file holding one preset: its profile, and its print settings over the creator\'s'],
179
+ ["--above-stock keep|stock", "A --preset file's speeds or accelerations above stock: keep them all, or use stock for all (saved presets were decided when saved)"],
180
+ ["--keep <setting,...>", "A --preset file: keep only these settings above stock; the rest use stock"],
181
+ ["--use-stock <setting,...>", "Use Snapmaker's stock value for these settings instead of the creator's faster one (print speeds, e.g. outer_wall_speed)"],
182
+ ["--keep-higher <setting,...>", "Keep the creator's value for these settings even when higher than stock (accelerations, travel speed, filament_max_volumetric_speed). The U1's machine limits still apply"],
183
+ ["--filament-compliance <mode>", '"generic" or "snapmaker": relabel filament identity for marketplace uploads (e.g. Snapmaker Space). Identity only: never changes temperatures, retraction, flow or other tuning. Omit to keep the source file\'s filament names'],
184
+ ["--high-flow", "All four toolheads have the Snapmaker Liber High Flow Hotend. The converted file records it, so Snapmaker Orca matches your printer; colors you put on a high-flow nozzle when slicing use Snapmaker's high-flow speeds on profiles that have them (today only 0.20mm Standard, 0.4mm nozzle). Gains are largest on big prints with long, continuous paths. Ignored, with a note, on nozzle sizes with no high-flow option"],
185
+ ["--high-flow-toolheads <list>", "Only these toolheads have the Liber hotend, numbered 1 to 4, e.g. 1 or 1,3. Otherwise the same as --high-flow; use one or the other"],
186
+ ["--hardened-nozzle", "Your U1 has hardened steel nozzles instead of the stock stainless steel 0.4. The file records it, so Snapmaker Orca warns about abrasive filaments correctly. Only changes 0.4 nozzle conversions; Snapmaker's other sizes are hardened steel already"],
187
+ ["--explain", "After each file, list what the conversion changed, grouped by why: from the creator's file, kept at Snapmaker's stock value, capped for the U1, set for the firmware, layout, and your choices"],
188
+ ["--explain-json", "Also write that, with every settings difference, to <output>.what-changed.json next to each output (format any2orca-what-changed)"],
189
+ ["--max-unpacked <size>", "The most a project may unpack to, e.g. 4GB or 3000MB (default 2GB, at most 16GB). For a very large project; it needs about twice that much memory"],
190
+ ["--no-stamp", "Leave the small version note (Metadata/any2orca.json) out of the converted file. The note says which any2orca version, profile catalog and options made the file, so it can be traced if a bug turns up; it holds no file names, paths, times or identifiers. The file works the same without it"],
191
+ ["--out-dir <dir>", "Write outputs here instead of next to each input (created if missing)"],
192
+ ["--suffix <text>", 'Output filename suffix (default "_U1"; "" removes it, refused if the output would overwrite the input)'],
193
+ ["--skip-existing", "Skip a file whose output already exists, to resume an interrupted batch"],
194
+ ["--watch <dir>", "Watch this folder and convert each new .3mf/.zip as it appears, until Ctrl+C. Takes no <files...>. Requires --out-dir pointing elsewhere"],
195
+ ["--archive-dir <dir>", "After a file converts, move the original here (created if missing)"],
196
+ ["--log-file <path>", "Append every log line, timestamped, to this file as well"],
197
+ ["--quiet", "No output to the terminal. Requires --log-file"],
198
+ ["--dry-run", "Show which profile each file would use, without writing anything"],
199
+ ["--verbose", "Show the matched profile and the full conversion log"],
200
+ ["--profiles-dir <dir>", "Use a profile catalog folder instead of the bundled one"],
201
+ ["--dry-run-telemetry", "Print the usage stats event for each file instead of sending it"],
202
+ ["--stats-endpoint <url>", "Send opted-in usage stats to your own collector (same as ANY2ORCA_STATS_ENDPOINT)"],
203
+ ["-h, --help", "Show this help"],
204
+ ])}
205
+
206
+ Folders that get new files over time: --watch converts each new file as it
207
+ settles (Ctrl+C to stop):
208
+ any2orca convert --watch ./exports --out-dir ./converted
209
+
210
+ Or run a plain convert on a schedule, e.g. from cron:
211
+ */5 * * * * any2orca convert ./exports/*.3mf --archive-dir ./exports/done \\
212
+ --out-dir ./converted --log-file ./any2orca.log --quiet
213
+
214
+ With --watch, --archive-dir or --skip-existing, a small state file
215
+ (.any2orca-state.json in the output folder) records each input's outcome by
216
+ name, size and modification time, so an unchanged file isn't redone and a
217
+ file that failed for a reason retrying can't fix isn't retried forever.
218
+ `;
219
+ function hasHelpFlag(args) {
220
+ return args.includes("--help") || args.includes("-h");
221
+ }
222
+ async function openCatalog(profilesDir) {
223
+ return loadCatalog(profilesDir ? dirProfileSource(profilesDir) : bundledProfileSource());
224
+ }
225
+ /** First interactive run with somewhere to send stats: ask once, default No. */
226
+ async function maybeAskAboutStats(io) {
227
+ if (!io.isTTY || !process.stdin.isTTY)
228
+ return;
229
+ if (io.env.ANY2ORCA_TELEMETRY !== undefined || io.env.DO_NOT_TRACK !== undefined || io.env.CI)
230
+ return;
231
+ if (readCliConfig(io.env).stats)
232
+ return;
233
+ const status = resolveStatsStatus({ ...io.env, ANY2ORCA_TELEMETRY: "1" });
234
+ if (!status.endpoint)
235
+ return; // nowhere to send yet, so nothing to ask
236
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
237
+ try {
238
+ io.out("any2orca can send a small anonymous usage event after each conversion (profile used, counts, date; never your file).");
239
+ io.out('It also checks npm once a day for a newer version. Details: "any2orca telemetry show".');
240
+ const answer = await rl.question("Help improve any2orca by sharing anonymous usage stats? [y/N] ");
241
+ runTelemetrySet(/^y(es)?$/i.test(answer.trim()) ? "on" : "off", io.env, io.out);
242
+ }
243
+ finally {
244
+ rl.close();
245
+ }
246
+ }
247
+ async function runCommand(command, rest, io) {
248
+ if (!command || command === "help" || hasHelpFlag([command])) {
249
+ io.out(TOP_LEVEL_HELP);
250
+ return 0;
251
+ }
252
+ if (command === "--version" || command === "-v" || command === "version") {
253
+ io.out(VERSION);
254
+ return 0;
255
+ }
256
+ switch (command) {
257
+ case "diff": {
258
+ if (hasHelpFlag(rest)) {
259
+ io.out(DIFF_HELP);
260
+ return 0;
261
+ }
262
+ try {
263
+ // --against-stock takes an optional value: the next argument, unless it's a flag or a project file.
264
+ const args = [...rest];
265
+ let againstStock;
266
+ const at = args.indexOf("--against-stock");
267
+ if (at !== -1) {
268
+ const next = args[at + 1];
269
+ const takesValue = next !== undefined && !next.startsWith("-") && !/\.(3mf|zip)$/i.test(next);
270
+ againstStock = takesValue ? next : true;
271
+ args.splice(at, takesValue ? 2 : 1);
272
+ }
273
+ const { values, positionals } = parseArgs({
274
+ args,
275
+ allowPositionals: true,
276
+ options: {
277
+ group: { type: "string", multiple: true },
278
+ all: { type: "boolean", default: false },
279
+ sort: { type: "string" },
280
+ json: { type: "boolean", default: false },
281
+ "profiles-dir": { type: "string" },
282
+ "against-preset": { type: "string" },
283
+ },
284
+ });
285
+ const againstPreset = values["against-preset"] !== undefined ? presetForDiff(values["against-preset"], io.env) : undefined;
286
+ const allowed = ["print", "filament", "machine", "other"];
287
+ const groups = values.group?.map((g) => {
288
+ if (!allowed.includes(g))
289
+ throw new Error(`--group takes print, filament, machine or other, not "${g.slice(0, 40)}"`);
290
+ return g;
291
+ });
292
+ const sort = values.sort ?? "attention";
293
+ if (sort !== "attention" && sort !== "setting" && sort !== "status")
294
+ throw new Error(`--sort takes attention, setting or status, not "${sort.slice(0, 20)}"`);
295
+ return await runDiff({ files: positionals, againstStock, againstPreset, groups, json: Boolean(values.json), all: Boolean(values.all), sort, catalog: await openCatalog(values["profiles-dir"]) }, io.out);
296
+ }
297
+ catch (err) {
298
+ io.err(`Error: ${describeFsError(err)}`);
299
+ return 2;
300
+ }
301
+ }
302
+ case "presets": {
303
+ const [sub, ...args] = rest;
304
+ if (!sub || hasHelpFlag(rest)) {
305
+ io.out(PRESETS_HELP);
306
+ return 0;
307
+ }
308
+ const { values, positionals } = parseArgs({
309
+ args,
310
+ allowPositionals: true,
311
+ options: {
312
+ "above-stock": { type: "string" },
313
+ keep: { type: "string", multiple: true },
314
+ force: { type: "boolean", default: false },
315
+ json: { type: "boolean", default: false },
316
+ out: { type: "string" },
317
+ "profiles-dir": { type: "string" },
318
+ },
319
+ });
320
+ const options = {
321
+ env: io.env,
322
+ catalog: await openCatalog(values["profiles-dir"]),
323
+ aboveStock: presetAboveStockChoice(values),
324
+ force: Boolean(values.force),
325
+ json: Boolean(values.json),
326
+ ...(values.out ? { out: values.out } : {}),
327
+ };
328
+ const usage = (form) => new Error(`Usage: any2orca presets ${form} (see: any2orca presets --help)`);
329
+ switch (sub) {
330
+ case "add":
331
+ if (positionals.length !== 2)
332
+ throw usage("add <name> <tuned.3mf>");
333
+ return runPresetsAdd(positionals[0], positionals[1], options, io.out);
334
+ case "list":
335
+ return runPresetsList(options, io.out, io.err);
336
+ case "show":
337
+ if (positionals.length !== 1)
338
+ throw usage("show <name>");
339
+ return runPresetsShow(positionals[0], options, io.out);
340
+ case "remove":
341
+ if (positionals.length !== 1)
342
+ throw usage("remove <name>");
343
+ return runPresetsRemove(positionals[0], options, io.out);
344
+ case "export":
345
+ return runPresetsExport(positionals, options, io.out);
346
+ case "import":
347
+ if (positionals.length !== 1)
348
+ throw usage("import <file>");
349
+ return runPresetsImport(positionals[0], options, io.out);
350
+ default:
351
+ throw usage("add | list | show | remove | export | import");
352
+ }
353
+ }
354
+ case "profiles": {
355
+ if (hasHelpFlag(rest)) {
356
+ io.out(PROFILES_HELP);
357
+ return 0;
358
+ }
359
+ const { values } = parseArgs({ args: rest, options: { nozzle: { type: "string" }, "profiles-dir": { type: "string" } } });
360
+ runProfiles(await openCatalog(values["profiles-dir"]), values.nozzle, io.out);
361
+ return 0;
362
+ }
363
+ case "telemetry": {
364
+ const [sub, arg] = rest;
365
+ if (!sub || hasHelpFlag(rest)) {
366
+ io.out(TELEMETRY_HELP);
367
+ return 0;
368
+ }
369
+ if (sub === "show")
370
+ runTelemetryShow(io.env, io.isTTY, io.out);
371
+ else if (sub === "on" || sub === "off")
372
+ runTelemetrySet(sub, io.env, io.out);
373
+ else if (sub === "clear")
374
+ runTelemetryClear(io.env, io.out);
375
+ else if (sub === "update-check" && (arg === "on" || arg === "off"))
376
+ runUpdateCheckSet(arg === "on", io.env, io.out);
377
+ else
378
+ throw new Error('Usage: any2orca telemetry show | on | off | clear | update-check on|off (see: any2orca telemetry --help)');
379
+ return 0;
380
+ }
381
+ case "convert": {
382
+ if (hasHelpFlag(rest)) {
383
+ io.out(CONVERT_HELP);
384
+ return 0;
385
+ }
386
+ const { values, positionals } = parseArgs({
387
+ args: rest,
388
+ allowPositionals: true,
389
+ options: {
390
+ profile: { type: "string" },
391
+ preset: { type: "string" },
392
+ "above-stock": { type: "string" },
393
+ keep: { type: "string", multiple: true },
394
+ "use-stock": { type: "string", multiple: true },
395
+ "keep-higher": { type: "string", multiple: true },
396
+ "filament-compliance": { type: "string" },
397
+ "high-flow": { type: "boolean", default: false },
398
+ "high-flow-toolheads": { type: "string" },
399
+ "hardened-nozzle": { type: "boolean", default: false },
400
+ "no-stamp": { type: "boolean", default: false },
401
+ "max-unpacked": { type: "string" },
402
+ explain: { type: "boolean", default: false },
403
+ "explain-json": { type: "boolean", default: false },
404
+ "out-dir": { type: "string" },
405
+ suffix: { type: "string", default: "_U1" },
406
+ "dry-run": { type: "boolean", default: false },
407
+ verbose: { type: "boolean", default: false },
408
+ "skip-existing": { type: "boolean", default: false },
409
+ watch: { type: "string" },
410
+ "archive-dir": { type: "string" },
411
+ "log-file": { type: "string" },
412
+ quiet: { type: "boolean", default: false },
413
+ "profiles-dir": { type: "string" },
414
+ "dry-run-telemetry": { type: "boolean", default: false },
415
+ "stats-endpoint": { type: "string" },
416
+ },
417
+ });
418
+ if (values.watch !== undefined && positionals.length > 0) {
419
+ throw new Error("--watch takes no file arguments; pass the folder to watch as --watch <dir> (see: any2orca convert --help)");
420
+ }
421
+ if (values.watch === undefined && positionals.length === 0) {
422
+ throw new Error("Usage: any2orca convert <files...> [options] (see: any2orca convert --help)");
423
+ }
424
+ // Command Prompt and PowerShell leave `*.3mf` for the program to expand; a Unix shell already has.
425
+ const inputs = expandInputPatterns(positionals);
426
+ const filamentCompliance = values["filament-compliance"];
427
+ if (filamentCompliance !== undefined && filamentCompliance !== "generic" && filamentCompliance !== "snapmaker") {
428
+ throw new Error(`--filament-compliance must be "generic" or "snapmaker", got "${filamentCompliance}" (see: any2orca convert --help)`);
429
+ }
430
+ if (values["high-flow"] && values["high-flow-toolheads"] !== undefined) {
431
+ throw new Error("Use --high-flow (all four toolheads) or --high-flow-toolheads <list>, not both (see: any2orca convert --help)");
432
+ }
433
+ const highFlow = values["high-flow-toolheads"] !== undefined ? parseHighFlowToolheads(values["high-flow-toolheads"]) : Boolean(values["high-flow"]);
434
+ if (values.quiet && !values["log-file"])
435
+ throw new Error("--quiet requires --log-file, otherwise errors would have nowhere to go (see: any2orca convert --help)");
436
+ if (values["out-dir"]) {
437
+ if (existsSync(values["out-dir"]) && !statSync(values["out-dir"]).isDirectory())
438
+ throw new Error(`--out-dir must be a folder, got "${values["out-dir"]}"`);
439
+ if (!values["dry-run"])
440
+ mkdirSync(values["out-dir"], { recursive: true });
441
+ }
442
+ const archiveDir = values["archive-dir"];
443
+ if (archiveDir) {
444
+ for (const input of inputs) {
445
+ if (isSamePath(dirname(resolve(input)), archiveDir))
446
+ throw new Error(`--archive-dir must be a different folder than the one "${input}" is in`);
447
+ }
448
+ }
449
+ // Checks --stats-endpoint/ANY2ORCA_STATS_ENDPOINT up front when stats would send, so a typo fails loudly instead of silently not sending.
450
+ resolveStatsStatus(io.env, values["stats-endpoint"]);
451
+ const catalog = await openCatalog(values["profiles-dir"]);
452
+ if (values.profile && !catalog.get(values.profile) && !catalog.retiredSuccessor(values.profile)) {
453
+ throw new Error(`No profile "${values.profile}". Run "any2orca profiles" for the list.`);
454
+ }
455
+ if (values.profile && values.preset)
456
+ throw new Error("A preset sets its own profile; use --preset or --profile, not both (see: any2orca convert --help)");
457
+ const preset = values.preset ? await presetForConvert(values.preset, io.env, catalog, presetAboveStockChoice(values)) : undefined;
458
+ const useStock = settingList(values["use-stock"]);
459
+ const keepHigher = settingList(values["keep-higher"]);
460
+ const aboveStock = useStock.length + keepHigher.length > 0 ? { stock: useStock, keep: keepHigher } : undefined;
461
+ // Checked here, so a typo fails before anything converts.
462
+ resolveAboveStockChoice(aboveStock);
463
+ if (!values["dry-run"] && !values["dry-run-telemetry"])
464
+ await maybeAskAboutStats(io);
465
+ const logger = createLogger({ logFile: values["log-file"], quiet: Boolean(values.quiet) });
466
+ const options = {
467
+ catalog,
468
+ profile: values.profile,
469
+ ...(preset ? { preset } : {}),
470
+ ...(aboveStock ? { aboveStock } : {}),
471
+ filamentCompliance,
472
+ highFlow,
473
+ hardenedNozzle: Boolean(values["hardened-nozzle"]),
474
+ noStamp: Boolean(values["no-stamp"]),
475
+ ...(values["max-unpacked"] !== undefined ? { maxUnpackedBytes: parseMaxUnpacked(values["max-unpacked"]) } : {}),
476
+ explain: Boolean(values.explain),
477
+ explainJson: Boolean(values["explain-json"]),
478
+ outDir: values["out-dir"],
479
+ archiveDir: values["archive-dir"],
480
+ suffix: values.suffix ?? "_U1",
481
+ dryRun: Boolean(values["dry-run"]),
482
+ verbose: Boolean(values.verbose),
483
+ skipExisting: Boolean(values["skip-existing"]),
484
+ watch: values.watch !== undefined,
485
+ logger,
486
+ stats: createStatsReporter({
487
+ env: io.env,
488
+ logger,
489
+ dryRun: Boolean(values["dry-run-telemetry"]),
490
+ ...(values["stats-endpoint"] ? { endpoint: values["stats-endpoint"] } : {}),
491
+ ...(io.fetch ? { fetch: io.fetch } : {}),
492
+ }),
493
+ };
494
+ if (values.watch !== undefined) {
495
+ const folder = values.watch;
496
+ if (!existsSync(folder) || !statSync(folder).isDirectory())
497
+ throw new Error(`--watch requires an existing folder, got "${folder}"`);
498
+ if (!options.outDir)
499
+ throw new Error("--watch requires --out-dir pointing somewhere other than the watched folder");
500
+ if (resolve(options.outDir) === resolve(folder) || isSamePath(options.outDir, folder))
501
+ throw new Error("--out-dir must be a different folder than the one being watched");
502
+ if (archiveDir && (resolve(archiveDir) === resolve(folder) || isSamePath(archiveDir, folder))) {
503
+ throw new Error("--archive-dir must be a different folder than the one being watched");
504
+ }
505
+ await runWatch(folder, options);
506
+ }
507
+ const summary = await runConvert(inputs, options);
508
+ return summary.failed > 0 ? 1 : 0;
509
+ }
510
+ default:
511
+ io.err(`Unknown command "${command}".\n`);
512
+ io.out(TOP_LEVEL_HELP);
513
+ return 1;
514
+ }
515
+ }
516
+ const UPDATE_CHECK_COMMANDS = new Set(["convert", "diff", "presets", "profiles"]);
517
+ /** Runs the CLI and returns its exit code. Never calls process.exit, so tests can drive it. */
518
+ export async function runCli(argv, rawIo) {
519
+ // Everything printed passes through here, so text from files can't carry terminal control codes.
520
+ // --json output is for programs: unsafe characters stay, as JSON escapes, so the data isn't changed.
521
+ const json = argv.includes("--json");
522
+ const io = { ...rawIo, out: (line) => rawIo.out(json ? escapeUnsafeForJson(line) : safeTerminalText(line)), err: (line) => rawIo.err(safeTerminalText(line)) };
523
+ const flagDisabled = argv.includes("--no-update-notifier");
524
+ const args = argv.filter((a) => a !== "--no-update-notifier");
525
+ // Only for real work: not for the version, help, telemetry settings (including turning the check off) or a mistyped command.
526
+ const worthChecking = UPDATE_CHECK_COMMANDS.has(args[0] ?? "") && !hasHelpFlag(args.slice(1));
527
+ const updatesOff = !worthChecking || updateCheckDisabledReason({ env: io.env, isTTY: io.isTTY, flagDisabled }) !== null;
528
+ const notice = updatesOff ? null : updateNotice(io.env);
529
+ if (!updatesOff && readCliConfig(io.env).updateCheck?.lastCheckedAt === undefined) {
530
+ io.err('Note: any2orca checks npm once a day for a newer version (package name only). Turn off: any2orca telemetry update-check off');
531
+ }
532
+ const refresh = updatesOff ? Promise.resolve() : refreshUpdateCache(io.env, io.fetch);
533
+ let code;
534
+ try {
535
+ code = await runCommand(args[0], args.slice(1), io);
536
+ }
537
+ catch (err) {
538
+ io.err(`Error: ${describeFsError(err)}`);
539
+ code = 1;
540
+ }
541
+ await refresh;
542
+ if (notice)
543
+ io.err(`\n${notice}`);
544
+ return code;
545
+ }
546
+ /** `--keep a,b --keep c` -> ["a", "b", "c"]. */
547
+ function settingList(raw) {
548
+ return (raw ?? []).flatMap((value) => value.split(",")).map((key) => key.trim()).filter(Boolean);
549
+ }
550
+ /** --above-stock keep|stock and --keep <settings>. */
551
+ function presetAboveStockChoice(values) {
552
+ const mode = values["above-stock"];
553
+ if (mode !== undefined && mode !== "keep" && mode !== "stock")
554
+ throw new Error(`--above-stock takes keep or stock, not "${mode.slice(0, 20)}"`);
555
+ const keep = settingList(values.keep);
556
+ if (mode && keep.length > 0)
557
+ throw new Error("Use --above-stock or --keep, not both.");
558
+ return keep.length > 0 ? { keep } : mode ? { mode } : {};
559
+ }
560
+ const TOOLHEADS = 4;
561
+ /**
562
+ * `--max-unpacked 4GB` -> bytes. Takes a number with GB or MB (or plain
563
+ * bytes), from 1 MB to the library's 16 GB ceiling; anything else is refused
564
+ * with the reason, never rounded into range.
565
+ */
566
+ export function parseMaxUnpacked(raw) {
567
+ const usage = `--max-unpacked takes a size from 1MB to ${MAX_UNPACKED_BYTES_LIMIT / 1024 ** 3}GB, e.g. 4GB or 3000MB`;
568
+ const match = raw.length <= 32 ? /^\s*(\d+(?:\.\d+)?)\s*(GB|MB|B)?\s*$/i.exec(raw) : null;
569
+ if (!match)
570
+ throw new Error(`${usage}; got "${raw.slice(0, 32)}"`);
571
+ const unit = (match[2] ?? "B").toUpperCase();
572
+ const bytes = Math.floor(Number(match[1]) * (unit === "GB" ? 1024 ** 3 : unit === "MB" ? 1024 ** 2 : 1));
573
+ if (bytes < 1024 ** 2 || bytes > MAX_UNPACKED_BYTES_LIMIT)
574
+ throw new Error(`${usage}; got "${raw}"`);
575
+ return bytes;
576
+ }
577
+ /**
578
+ * `--high-flow-toolheads 1,3` -> `[true, false, true, false]`. Toolheads are
579
+ * numbered 1 to 4 as on the printer. Rejects anything else (empty entries,
580
+ * duplicates, numbers out of range) instead of guessing, since a wrong
581
+ * hotend choice changes the speeds a toolhead prints at.
582
+ */
583
+ export function parseHighFlowToolheads(raw) {
584
+ const usage = `--high-flow-toolheads takes toolhead numbers 1 to ${TOOLHEADS}, comma-separated, e.g. 1 or 1,3`;
585
+ if (raw.length > 32)
586
+ throw new Error(`${usage}; got a value that is too long`);
587
+ const parts = raw.split(",").map((part) => part.trim());
588
+ const selection = new Array(TOOLHEADS).fill(false);
589
+ for (const part of parts) {
590
+ if (!/^[1-9]$/.test(part) || Number(part) > TOOLHEADS)
591
+ throw new Error(`${usage}; got "${raw}"`);
592
+ const index = Number(part) - 1;
593
+ if (selection[index])
594
+ throw new Error(`${usage}; toolhead ${part} is listed twice`);
595
+ selection[index] = true;
596
+ }
597
+ return selection;
598
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Whether two existing paths name the same file or folder. Compares the
3
+ * file system's own identity (device and inode), so a different spelling
4
+ * (case on macOS and Windows, a symlink, `..`) still counts as the same.
5
+ * A path that doesn't exist is never the same as anything.
6
+ */
7
+ export declare function isSamePath(a: string, b: string): boolean;
8
+ /** A file system error as a sentence, for the errors people commonly hit; anything else keeps its own message. */
9
+ export declare function describeFsError(err: unknown): string;
@@ -0,0 +1,40 @@
1
+ // SPDX-License-Identifier: MIT
2
+ import { statSync } from "node:fs";
3
+ /**
4
+ * Whether two existing paths name the same file or folder. Compares the
5
+ * file system's own identity (device and inode), so a different spelling
6
+ * (case on macOS and Windows, a symlink, `..`) still counts as the same.
7
+ * A path that doesn't exist is never the same as anything.
8
+ */
9
+ export function isSamePath(a, b) {
10
+ try {
11
+ const x = statSync(a, { bigint: true });
12
+ const y = statSync(b, { bigint: true });
13
+ return x.dev === y.dev && x.ino === y.ino;
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ /** A file system error as a sentence, for the errors people commonly hit; anything else keeps its own message. */
20
+ export function describeFsError(err) {
21
+ const e = err;
22
+ const path = typeof e?.path === "string" ? `"${e.path}"` : "that path";
23
+ switch (e?.code) {
24
+ case "ENOENT":
25
+ return `${path} doesn't exist.`;
26
+ case "EISDIR":
27
+ return `${path} is a folder, not a file.`;
28
+ case "ENOTDIR":
29
+ return `part of ${path} is a file, not a folder.`;
30
+ case "EEXIST":
31
+ return `${path} already exists.`;
32
+ case "EACCES":
33
+ case "EPERM":
34
+ return `no permission to use ${path}.`;
35
+ case "ENOSPC":
36
+ return "the disk is full.";
37
+ default:
38
+ return err instanceof Error ? err.message : String(err);
39
+ }
40
+ }