any2orca 0.0.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -0
- package/LICENSE +21 -0
- package/NOTICE +28 -0
- package/README.md +96 -3
- package/dist/archive/adaptModelSettings.d.ts +1 -0
- package/dist/archive/adaptModelSettings.js +50 -0
- package/dist/archive/filamentColorNames.d.ts +8 -0
- package/dist/archive/filamentColorNames.js +760 -0
- package/dist/archive/fmtNum.d.ts +14 -0
- package/dist/archive/fmtNum.js +21 -0
- package/dist/archive/internal/escapeRegExp.d.ts +2 -0
- package/dist/archive/internal/escapeRegExp.js +5 -0
- package/dist/archive/lookupFilamentColorName.d.ts +45 -0
- package/dist/archive/lookupFilamentColorName.js +57 -0
- package/dist/archive/objectWorldBboxXY.d.ts +2 -0
- package/dist/archive/objectWorldBboxXY.js +123 -0
- package/dist/archive/parseItemPositions.d.ts +6 -0
- package/dist/archive/parseItemPositions.js +17 -0
- package/dist/archive/parseObjectMetadata.d.ts +10 -0
- package/dist/archive/parseObjectMetadata.js +97 -0
- package/dist/archive/parsePlateAssignments.d.ts +6 -0
- package/dist/archive/parsePlateAssignments.js +18 -0
- package/dist/archive/parseVertices.d.ts +7 -0
- package/dist/archive/parseVertices.js +12 -0
- package/dist/archive/paths.d.ts +5 -0
- package/dist/archive/paths.js +6 -0
- package/dist/archive/recenterAssembleItems.d.ts +9 -0
- package/dist/archive/recenterAssembleItems.js +53 -0
- package/dist/archive/recenterBuildItems.d.ts +15 -0
- package/dist/archive/recenterBuildItems.js +51 -0
- package/dist/archive/safeUnzip.d.ts +26 -0
- package/dist/archive/safeUnzip.js +126 -0
- package/dist/archive/setApplicationMetadata.d.ts +13 -0
- package/dist/archive/setApplicationMetadata.js +18 -0
- package/dist/archive/shouldDropFromBambu.d.ts +29 -0
- package/dist/archive/shouldDropFromBambu.js +39 -0
- package/dist/archive/streamObjectVertices.d.ts +19 -0
- package/dist/archive/streamObjectVertices.js +57 -0
- package/dist/archive/tolerantJsonParse.d.ts +20 -0
- package/dist/archive/tolerantJsonParse.js +71 -0
- package/dist/archive/transform.d.ts +21 -0
- package/dist/archive/transform.js +39 -0
- package/dist/archive/unwrapBundle.d.ts +24 -0
- package/dist/archive/unwrapBundle.js +41 -0
- package/dist/archive/xmlBlocks.d.ts +10 -0
- package/dist/archive/xmlBlocks.js +31 -0
- package/dist/archive/zip.d.ts +29 -0
- package/dist/archive/zip.js +141 -0
- package/dist/cli/archiveMove.d.ts +15 -0
- package/dist/cli/archiveMove.js +41 -0
- package/dist/cli/commands/convert.d.ts +89 -0
- package/dist/cli/commands/convert.js +311 -0
- package/dist/cli/commands/diff.d.ts +21 -0
- package/dist/cli/commands/diff.js +112 -0
- package/dist/cli/commands/presets.d.ts +51 -0
- package/dist/cli/commands/presets.js +280 -0
- package/dist/cli/commands/profiles.d.ts +5 -0
- package/dist/cli/commands/profiles.js +26 -0
- package/dist/cli/commands/telemetry.d.ts +6 -0
- package/dist/cli/commands/telemetry.js +45 -0
- package/dist/cli/config.d.ts +18 -0
- package/dist/cli/config.js +50 -0
- package/dist/cli/expandWildcards.d.ts +17 -0
- package/dist/cli/expandWildcards.js +81 -0
- package/dist/cli/logger.d.ts +17 -0
- package/dist/cli/logger.js +36 -0
- package/dist/cli/main.d.ts +24 -0
- package/dist/cli/main.js +598 -0
- package/dist/cli/sameFile.d.ts +9 -0
- package/dist/cli/sameFile.js +40 -0
- package/dist/cli/stats.d.ts +34 -0
- package/dist/cli/stats.js +137 -0
- package/dist/cli/table.d.ts +8 -0
- package/dist/cli/table.js +18 -0
- package/dist/cli/terminalText.d.ts +7 -0
- package/dist/cli/terminalText.js +22 -0
- package/dist/cli/updateCheck.d.ts +14 -0
- package/dist/cli/updateCheck.js +78 -0
- package/dist/cli/watchState.d.ts +18 -0
- package/dist/cli/watchState.js +33 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +10 -0
- package/dist/diff/diffSettings.d.ts +81 -0
- package/dist/diff/diffSettings.js +259 -0
- package/dist/diff/reference.d.ts +14 -0
- package/dist/diff/reference.js +22 -0
- package/dist/diff/settingsCatalog.d.ts +28 -0
- package/dist/diff/settingsCatalog.js +605 -0
- package/dist/diff/valueLayout.d.ts +20 -0
- package/dist/diff/valueLayout.js +65 -0
- package/dist/engine/aboveStock.d.ts +20 -0
- package/dist/engine/aboveStock.js +89 -0
- package/dist/engine/applyFilamentComplianceMode.d.ts +40 -0
- package/dist/engine/applyFilamentComplianceMode.js +68 -0
- package/dist/engine/applyFilamentFlowVariants.d.ts +42 -0
- package/dist/engine/applyFilamentFlowVariants.js +109 -0
- package/dist/engine/applyHighFlowHotends.d.ts +52 -0
- package/dist/engine/applyHighFlowHotends.js +115 -0
- package/dist/engine/applyPresetChanges.d.ts +12 -0
- package/dist/engine/applyPresetChanges.js +23 -0
- package/dist/engine/bedCenter.d.ts +19 -0
- package/dist/engine/bedCenter.js +34 -0
- package/dist/engine/buildFilamentConfigs.d.ts +18 -0
- package/dist/engine/buildFilamentConfigs.js +49 -0
- package/dist/engine/buildProjectSettings.d.ts +24 -0
- package/dist/engine/buildProjectSettings.js +164 -0
- package/dist/engine/carrySourceLayerHeight.d.ts +15 -0
- package/dist/engine/carrySourceLayerHeight.js +41 -0
- package/dist/engine/clampColorPenetration.d.ts +12 -0
- package/dist/engine/clampColorPenetration.js +28 -0
- package/dist/engine/clampToMachineLimits.d.ts +21 -0
- package/dist/engine/clampToMachineLimits.js +84 -0
- package/dist/engine/coerceValue.d.ts +15 -0
- package/dist/engine/coerceValue.js +56 -0
- package/dist/engine/collapseNozzleVariants.d.ts +31 -0
- package/dist/engine/collapseNozzleVariants.js +63 -0
- package/dist/engine/computeShifts.d.ts +12 -0
- package/dist/engine/computeShifts.js +339 -0
- package/dist/engine/constants.d.ts +11 -0
- package/dist/engine/constants.js +12 -0
- package/dist/engine/detectNozzleDiameter.d.ts +15 -0
- package/dist/engine/detectNozzleDiameter.js +29 -0
- package/dist/engine/detectVariantIndex.d.ts +39 -0
- package/dist/engine/detectVariantIndex.js +80 -0
- package/dist/engine/extractFilamentSlots.d.ts +18 -0
- package/dist/engine/extractFilamentSlots.js +88 -0
- package/dist/engine/filamentComplianceNames.d.ts +84 -0
- package/dist/engine/filamentComplianceNames.js +87 -0
- package/dist/engine/filamentVariantLayout.d.ts +29 -0
- package/dist/engine/filamentVariantLayout.js +38 -0
- package/dist/engine/fillFilamentSlots.d.ts +16 -0
- package/dist/engine/fillFilamentSlots.js +26 -0
- package/dist/engine/internal/jsonEqual.d.ts +2 -0
- package/dist/engine/internal/jsonEqual.js +5 -0
- package/dist/engine/parseTierName.d.ts +15 -0
- package/dist/engine/parseTierName.js +21 -0
- package/dist/engine/pickNearestProfile.d.ts +21 -0
- package/dist/engine/pickNearestProfile.js +24 -0
- package/dist/engine/pickProfile.d.ts +49 -0
- package/dist/engine/pickProfile.js +67 -0
- package/dist/engine/policy.d.ts +22 -0
- package/dist/engine/policy.js +274 -0
- package/dist/engine/remapBrimType.d.ts +30 -0
- package/dist/engine/remapBrimType.js +34 -0
- package/dist/engine/reshapeToCount.d.ts +15 -0
- package/dist/engine/reshapeToCount.js +27 -0
- package/dist/engine/resizeFlushVolumes.d.ts +27 -0
- package/dist/engine/resizeFlushVolumes.js +57 -0
- package/dist/engine/resolveMinIfLower.d.ts +21 -0
- package/dist/engine/resolveMinIfLower.js +59 -0
- package/dist/engine/runConvertPipeline.d.ts +79 -0
- package/dist/engine/runConvertPipeline.js +281 -0
- package/dist/engine/stripBambuOnlyNozzleVariantKeys.d.ts +2 -0
- package/dist/engine/stripBambuOnlyNozzleVariantKeys.js +35 -0
- package/dist/engine/types.d.ts +2 -0
- package/dist/engine/types.js +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +9 -0
- package/dist/explain/whatChanged.d.ts +102 -0
- package/dist/explain/whatChanged.js +199 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +34 -0
- package/dist/inspect.d.ts +63 -0
- package/dist/inspect.js +103 -0
- package/dist/node.d.ts +11 -0
- package/dist/node.js +50 -0
- package/dist/plainText.d.ts +10 -0
- package/dist/plainText.js +14 -0
- package/dist/presets/extractPreset.d.ts +13 -0
- package/dist/presets/extractPreset.js +87 -0
- package/dist/presets/preset.d.ts +124 -0
- package/dist/presets/preset.js +289 -0
- package/dist/presets/presetKeys.d.ts +5 -0
- package/dist/presets/presetKeys.js +42 -0
- package/dist/profiles.d.ts +184 -0
- package/dist/profiles.js +318 -0
- package/dist/project.d.ts +146 -0
- package/dist/project.js +342 -0
- package/dist/schema.d.ts +103 -0
- package/dist/schema.js +87 -0
- package/dist/stamp.d.ts +45 -0
- package/dist/stamp.js +111 -0
- package/dist/telemetry.d.ts +101 -0
- package/dist/telemetry.js +94 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/worker-entry.d.ts +1 -0
- package/dist/worker-entry.js +142 -0
- package/dist/worker.d.ts +86 -0
- package/dist/worker.js +97 -0
- package/dist/workerProtocol.d.ts +91 -0
- package/dist/workerProtocol.js +1 -0
- package/package.json +80 -12
- package/index.js +0 -3
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { basename } from "node:path";
|
|
4
|
+
import { diffSettings } from "../../diff/diffSettings.js";
|
|
5
|
+
import { diffReference, presetDiffSide } from "../../diff/reference.js";
|
|
6
|
+
import { valueLayoutNotes } from "../../diff/valueLayout.js";
|
|
7
|
+
import { Project } from "../../project.js";
|
|
8
|
+
import { formatTable } from "../table.js";
|
|
9
|
+
/** The largest source file these commands read (the web app's hand-off limit). */
|
|
10
|
+
const MAX_INPUT_BYTES = 512 * 1024 * 1024;
|
|
11
|
+
const MAX_CELL = 48;
|
|
12
|
+
function openFile(path) {
|
|
13
|
+
const lower = path.toLowerCase();
|
|
14
|
+
if (!lower.endsWith(".3mf"))
|
|
15
|
+
throw new Error(`${path} isn't a .3mf project; diff compares one project file with another (a .zip of several isn't supported).`);
|
|
16
|
+
const size = statSync(path).size;
|
|
17
|
+
if (size > MAX_INPUT_BYTES)
|
|
18
|
+
throw new Error(`${path} is larger than ${MAX_INPUT_BYTES / 1024 / 1024} MB, the most diff reads.`);
|
|
19
|
+
return Project.open(new Uint8Array(readFileSync(path)));
|
|
20
|
+
}
|
|
21
|
+
/** One table cell: G-code and other long text is summarized, so the table stays readable. */
|
|
22
|
+
function cell(value) {
|
|
23
|
+
if (value === null)
|
|
24
|
+
return "(not set)";
|
|
25
|
+
if (value.includes("\n"))
|
|
26
|
+
return `(${value.split("\n").length} lines)`;
|
|
27
|
+
const flat = value.replace(/\s+/g, " ");
|
|
28
|
+
return flat.length > MAX_CELL ? `${flat.slice(0, MAX_CELL - 3)}...` : flat;
|
|
29
|
+
}
|
|
30
|
+
const STATUS_TEXT = {
|
|
31
|
+
same: "same",
|
|
32
|
+
changed: "changed",
|
|
33
|
+
"only-a": "only in source (A)",
|
|
34
|
+
"only-b": "only in target (B)",
|
|
35
|
+
unmatched: "not a Snapmaker Orca setting",
|
|
36
|
+
};
|
|
37
|
+
function groupTitle(group, slot) {
|
|
38
|
+
if (group === "filament")
|
|
39
|
+
return slot === undefined ? "Filament settings" : `Filament ${slot}`;
|
|
40
|
+
if (group === "other")
|
|
41
|
+
return "Other (not in Snapmaker Orca's settings)";
|
|
42
|
+
return `${group === "print" ? "Print" : "Machine"} settings`;
|
|
43
|
+
}
|
|
44
|
+
const ATTENTION_TEXT = {
|
|
45
|
+
"above-limit": "above the U1's limit (capped)",
|
|
46
|
+
"above-stock": "above stock",
|
|
47
|
+
};
|
|
48
|
+
const ATTENTION_RANK = { "above-limit": 0, "above-stock": 1 };
|
|
49
|
+
const STATUS_RANK = { changed: 0, "only-a": 1, "only-b": 2, unmatched: 3, same: 4 };
|
|
50
|
+
/** Rows in the chosen order. The diff's own order (Snapmaker Orca's page order) breaks ties. */
|
|
51
|
+
function ordered(rows, sort) {
|
|
52
|
+
const position = new Map(rows.map((r, i) => [r, i]));
|
|
53
|
+
const rank = (r) => (sort === "attention" ? (r.attention ? ATTENTION_RANK[r.attention] : 2) : sort === "status" ? STATUS_RANK[r.status] : 0);
|
|
54
|
+
return [...rows].sort((x, y) => rank(x) - rank(y) || (position.get(x) ?? 0) - (position.get(y) ?? 0));
|
|
55
|
+
}
|
|
56
|
+
/** 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. */
|
|
57
|
+
export function formatDiff(diff, sort = "attention") {
|
|
58
|
+
const lines = [`Source (A): ${diff.aLabel}`, `Target (B): ${diff.bLabel}`, ""];
|
|
59
|
+
if (diff.groups.length === 0) {
|
|
60
|
+
lines.push(diff.identical ? "No differences." : "No differences in the settings compared.");
|
|
61
|
+
return lines.join("\n");
|
|
62
|
+
}
|
|
63
|
+
for (const g of diff.groups) {
|
|
64
|
+
lines.push(`${groupTitle(g.group, g.slot)} (${g.rows.length})`);
|
|
65
|
+
for (const note of valueLayoutNotes(g.rows))
|
|
66
|
+
lines.push(` ${note}`);
|
|
67
|
+
lines.push(formatTable(ordered(g.rows, sort).map((r) => [` ${r.label === r.key ? r.key : `${r.label} [${r.key}]`}`, cell(r.a), cell(r.b), STATUS_TEXT[r.status], r.attention ? ATTENTION_TEXT[r.attention] : ""])));
|
|
68
|
+
lines.push("");
|
|
69
|
+
}
|
|
70
|
+
const changed = diff.groups.reduce((n, g) => n + g.rows.filter((r) => r.status !== "same").length, 0);
|
|
71
|
+
lines.push(`${changed} difference${changed === 1 ? "" : "s"}. Use --json for full values (including G-code).`);
|
|
72
|
+
return lines.join("\n");
|
|
73
|
+
}
|
|
74
|
+
/** `any2orca diff`: returns the exit code (0 no differences, 1 differences). Errors throw and exit 2. */
|
|
75
|
+
export async function runDiff(options, out) {
|
|
76
|
+
let diff;
|
|
77
|
+
if (options.againstStock !== undefined && options.againstPreset) {
|
|
78
|
+
throw new Error("Use --against-stock or --against-preset, not both.");
|
|
79
|
+
}
|
|
80
|
+
if (options.againstPreset) {
|
|
81
|
+
if (options.files.length !== 1)
|
|
82
|
+
throw new Error("--against-preset compares one .3mf with a preset; give exactly one file.");
|
|
83
|
+
const [file] = options.files;
|
|
84
|
+
const project = openFile(file);
|
|
85
|
+
const side = await presetDiffSide(options.againstPreset, options.catalog);
|
|
86
|
+
diff = diffSettings({ label: basename(file), settings: project.settings() }, { label: side.label, settings: side.settings },
|
|
87
|
+
// A preset holds print settings only, so that's what's compared unless asked otherwise.
|
|
88
|
+
{ groups: options.groups ?? ["print"], includeUnchanged: options.all, reference: await diffReference(options.catalog, side.profileId) });
|
|
89
|
+
}
|
|
90
|
+
else if (options.againstStock !== undefined) {
|
|
91
|
+
if (options.files.length !== 1)
|
|
92
|
+
throw new Error("--against-stock compares one .3mf with Snapmaker's stock profile; give exactly one file.");
|
|
93
|
+
const [file] = options.files;
|
|
94
|
+
const project = openFile(file);
|
|
95
|
+
const profileId = options.againstStock === true ? (await project.matchProfile(options.catalog)).profileId : options.againstStock;
|
|
96
|
+
const loaded = await options.catalog.load(profileId);
|
|
97
|
+
diff = diffSettings({ label: basename(file), settings: project.settings() }, { label: `Snapmaker's stock ${loaded.summary.displayName} profile`, settings: loaded.convertProfile.profile.baselineProjectSettings },
|
|
98
|
+
// Filament settings come from the creator, not the stock profile, so they're only compared when asked for.
|
|
99
|
+
{ groups: options.groups ?? ["print", "machine"], includeUnchanged: options.all, reference: await diffReference(options.catalog, profileId) });
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
if (options.files.length !== 2)
|
|
103
|
+
throw new Error("diff compares two .3mf files (or one with --against-stock or --against-preset).");
|
|
104
|
+
const [first, second] = options.files;
|
|
105
|
+
const a = openFile(first);
|
|
106
|
+
// Values are measured against the profile the first file would convert with.
|
|
107
|
+
const reference = await diffReference(options.catalog, (await a.matchProfile(options.catalog)).profileId);
|
|
108
|
+
diff = diffSettings({ label: basename(first), settings: a.settings() }, { label: basename(second), settings: openFile(second).settings() }, { ...(options.groups ? { groups: options.groups } : {}), includeUnchanged: options.all, reference });
|
|
109
|
+
}
|
|
110
|
+
out(options.json ? JSON.stringify(diff, null, 2) : formatDiff(diff, options.sort));
|
|
111
|
+
return diff.identical ? 0 : 1;
|
|
112
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { ProfileCatalog } from "../../profiles.js";
|
|
2
|
+
import { type Preset, type PresetChange } from "../../presets/preset.js";
|
|
3
|
+
import { type Env } from "../config.js";
|
|
4
|
+
export declare function presetsDir(env: Env): string;
|
|
5
|
+
/** A file name for a preset name: lowercase letters, digits and dashes. */
|
|
6
|
+
export declare function presetSlug(name: string): string;
|
|
7
|
+
interface SavedPreset {
|
|
8
|
+
preset: Preset;
|
|
9
|
+
path: string;
|
|
10
|
+
}
|
|
11
|
+
/** Every saved preset. A file that isn't a valid preset is reported and skipped, never used. */
|
|
12
|
+
export declare function loadSavedPresets(env: Env, warn?: (line: string) => void): SavedPreset[];
|
|
13
|
+
export declare function formatChanges(changes: readonly PresetChange[]): string;
|
|
14
|
+
/** What to do with a preset's values above stock: keep them all, use stock for all, or keep only the listed settings. */
|
|
15
|
+
export interface AboveStockPresetChoice {
|
|
16
|
+
mode?: "keep" | "stock";
|
|
17
|
+
keep?: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
export interface PresetsCommandOptions {
|
|
20
|
+
env: Env;
|
|
21
|
+
catalog: ProfileCatalog;
|
|
22
|
+
aboveStock: AboveStockPresetChoice;
|
|
23
|
+
force: boolean;
|
|
24
|
+
json: boolean;
|
|
25
|
+
out?: string;
|
|
26
|
+
}
|
|
27
|
+
/** `presets add <name> <master.3mf>` */
|
|
28
|
+
export declare function runPresetsAdd(name: string, masterPath: string, options: PresetsCommandOptions, out: (line: string) => void): Promise<number>;
|
|
29
|
+
/** `presets list` */
|
|
30
|
+
export declare function runPresetsList(options: PresetsCommandOptions, out: (line: string) => void, err: (line: string) => void): number;
|
|
31
|
+
/** `presets show <name>` */
|
|
32
|
+
export declare function runPresetsShow(name: string, options: PresetsCommandOptions, out: (line: string) => void): Promise<number>;
|
|
33
|
+
/** `presets remove <name>` */
|
|
34
|
+
export declare function runPresetsRemove(name: string, options: PresetsCommandOptions, out: (line: string) => void): number;
|
|
35
|
+
/** `presets export [names...] [--out <file>]` */
|
|
36
|
+
export declare function runPresetsExport(names: string[], options: PresetsCommandOptions, out: (line: string) => void): number;
|
|
37
|
+
/** `presets import <file>`: saves each preset in the file. One that can't be saved is skipped with the reason. */
|
|
38
|
+
export declare function runPresetsImport(file: string, options: PresetsCommandOptions, out: (line: string) => void): Promise<number>;
|
|
39
|
+
/**
|
|
40
|
+
* The preset `convert --preset` names: a saved preset's name, or a presets
|
|
41
|
+
* file holding exactly one preset. A preset from a file hasn't been agreed
|
|
42
|
+
* to, so speeds above stock need a choice (--above-stock or --keep).
|
|
43
|
+
*/
|
|
44
|
+
export declare function presetForConvert(nameOrPath: string, env: Env, catalog: ProfileCatalog, choice: AboveStockPresetChoice): Promise<Preset>;
|
|
45
|
+
/**
|
|
46
|
+
* The preset `diff --against-preset` names, found the same way as for
|
|
47
|
+
* convert. A comparison only shows the preset's values, so a presets file
|
|
48
|
+
* needs no choice about speeds above stock.
|
|
49
|
+
*/
|
|
50
|
+
export declare function presetForDiff(nameOrPath: string, env: Env): Preset;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
/**
|
|
3
|
+
* `any2orca presets`: save, list, show, remove, export and import presets,
|
|
4
|
+
* and find the one `convert --preset` names.
|
|
5
|
+
*
|
|
6
|
+
* Saved presets live in the CLI's config folder, under presets/, one file
|
|
7
|
+
* per preset in the same any2orca-presets format the web app exports. The
|
|
8
|
+
* file name is a slug of the preset's name; the name itself stays inside the
|
|
9
|
+
* file. A preset only enters this folder through `add` or `import`, which
|
|
10
|
+
* list any speeds above stock and need a choice for them (keep them all, put
|
|
11
|
+
* them all back to stock, or keep only some), so a saved preset is one the
|
|
12
|
+
* user has already agreed to.
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
import { Any2orcaError } from "../../errors.js";
|
|
17
|
+
import { Project } from "../../project.js";
|
|
18
|
+
import { extractPreset } from "../../presets/extractPreset.js";
|
|
19
|
+
import { MAX_PRESETS_FILE_BYTES, MAX_PRESETS_PER_FILE, parsePresetFile, PresetSchema, resolvePreset, serializePresets, withoutChanges, } from "../../presets/preset.js";
|
|
20
|
+
import { configDir } from "../config.js";
|
|
21
|
+
import { formatTable } from "../table.js";
|
|
22
|
+
/** The largest source file these commands read (the web app's hand-off limit). */
|
|
23
|
+
const MAX_INPUT_BYTES = 512 * 1024 * 1024;
|
|
24
|
+
const MAX_CELL = 40;
|
|
25
|
+
export function presetsDir(env) {
|
|
26
|
+
return join(configDir(env), "presets");
|
|
27
|
+
}
|
|
28
|
+
/** A file name for a preset name: lowercase letters, digits and dashes. */
|
|
29
|
+
export function presetSlug(name) {
|
|
30
|
+
const slug = name
|
|
31
|
+
.normalize("NFKD")
|
|
32
|
+
.toLowerCase()
|
|
33
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
34
|
+
.replace(/^-+|-+$/g, "")
|
|
35
|
+
.slice(0, 40);
|
|
36
|
+
if (!slug)
|
|
37
|
+
throw new Error(`A preset name needs at least one letter or digit, got "${name.slice(0, 40)}".`);
|
|
38
|
+
return slug;
|
|
39
|
+
}
|
|
40
|
+
/** Every saved preset. A file that isn't a valid preset is reported and skipped, never used. */
|
|
41
|
+
export function loadSavedPresets(env, warn = () => { }) {
|
|
42
|
+
const dir = presetsDir(env);
|
|
43
|
+
if (!existsSync(dir))
|
|
44
|
+
return [];
|
|
45
|
+
const saved = [];
|
|
46
|
+
for (const file of readdirSync(dir).filter((f) => f.endsWith(".json")).sort().slice(0, MAX_PRESETS_PER_FILE * 2)) {
|
|
47
|
+
const path = join(dir, file);
|
|
48
|
+
try {
|
|
49
|
+
if (statSync(path).size > MAX_PRESETS_FILE_BYTES)
|
|
50
|
+
throw new Error("too large");
|
|
51
|
+
const parsed = parsePresetFile(new Uint8Array(readFileSync(path)));
|
|
52
|
+
if (parsed.presets.length !== 1)
|
|
53
|
+
throw new Error("holds more than one preset");
|
|
54
|
+
saved.push({ preset: parsed.presets[0], path });
|
|
55
|
+
}
|
|
56
|
+
catch (err) {
|
|
57
|
+
warn(`Skipping ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return saved;
|
|
61
|
+
}
|
|
62
|
+
function findSaved(env, name) {
|
|
63
|
+
const wanted = name.trim().toLowerCase();
|
|
64
|
+
return loadSavedPresets(env).find((s) => s.preset.name.toLowerCase() === wanted);
|
|
65
|
+
}
|
|
66
|
+
/** Writes atomically (temp file + rename), so a crash never leaves a half-written preset. */
|
|
67
|
+
function savePreset(env, preset, replace) {
|
|
68
|
+
const dir = presetsDir(env);
|
|
69
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
70
|
+
const existing = findSaved(env, preset.name);
|
|
71
|
+
const path = join(dir, `${presetSlug(preset.name)}.json`);
|
|
72
|
+
if (existing && !replace)
|
|
73
|
+
throw new Error(`A preset named "${existing.preset.name}" already exists. Add --force to replace it.`);
|
|
74
|
+
if (!existing && existsSync(path))
|
|
75
|
+
throw new Error(`A preset with a name too similar to "${preset.name}" already exists (${path}). Choose another name.`);
|
|
76
|
+
if (loadSavedPresets(env).length >= MAX_PRESETS_PER_FILE && !existing)
|
|
77
|
+
throw new Error(`You can save at most ${MAX_PRESETS_PER_FILE} presets. Remove one first.`);
|
|
78
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
79
|
+
writeFileSync(temp, serializePresets([preset]), { mode: 0o600 });
|
|
80
|
+
renameSync(temp, existing?.path ?? path);
|
|
81
|
+
return existing?.path ?? path;
|
|
82
|
+
}
|
|
83
|
+
function cell(value) {
|
|
84
|
+
if (value.includes("\n"))
|
|
85
|
+
return `(${value.split("\n").length} lines)`;
|
|
86
|
+
return value.length > MAX_CELL ? `${value.slice(0, MAX_CELL - 3)}...` : value;
|
|
87
|
+
}
|
|
88
|
+
export function formatChanges(changes) {
|
|
89
|
+
if (changes.length === 0)
|
|
90
|
+
return " No changes: converts exactly like choosing the base profile.";
|
|
91
|
+
return formatTable([
|
|
92
|
+
[" SETTING", "STOCK", "YOURS", ""],
|
|
93
|
+
...changes.map((c) => [` ${c.label === c.key ? c.key : `${c.label} [${c.key}]`}`, cell(c.stock), cell(c.yours), c.cappedAt !== undefined ? `above stock, capped at ${c.cappedAt}` : c.aboveStock ? "above stock" : ""]),
|
|
94
|
+
]);
|
|
95
|
+
}
|
|
96
|
+
function aboveStockText(above, verb) {
|
|
97
|
+
return [
|
|
98
|
+
`${above.length === 1 ? "This setting is" : "These settings are"} faster than Snapmaker's stock profile:`,
|
|
99
|
+
...above.map((c) => ` ${c.label} [${c.key}]: ${c.yours} (stock ${c.stock}${c.cappedAt !== undefined ? `; the U1's limit caps it at ${c.cappedAt}` : ""})`),
|
|
100
|
+
"The U1's machine limits still apply, but faster isn't safe for every filament or model. Check them with a test print.",
|
|
101
|
+
`To ${verb} the preset, choose: --above-stock keep (keep them all), --above-stock stock (use Snapmaker's stock value for all), or --keep <setting,...> (keep only these, stock for the rest).`,
|
|
102
|
+
].join("\n");
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Applies the choice to a preset: "use stock" leaves a setting out, since a
|
|
106
|
+
* preset only holds what differs from stock. Throws, listing the values and
|
|
107
|
+
* the flags, when the preset has values above stock and nothing was chosen.
|
|
108
|
+
*/
|
|
109
|
+
function decideAboveStock(preset, described, choice, verb) {
|
|
110
|
+
const above = described.filter((c) => c.aboveStock);
|
|
111
|
+
if (above.length === 0)
|
|
112
|
+
return { preset, reverted: [] };
|
|
113
|
+
if (choice.keep) {
|
|
114
|
+
const unknown = choice.keep.filter((key) => !above.some((c) => c.key === key));
|
|
115
|
+
if (unknown.length > 0) {
|
|
116
|
+
throw new Error(`--keep: ${unknown.map((k) => k.slice(0, 60)).join(", ")} ${unknown.length === 1 ? "isn't" : "aren't"} above stock in this preset. Above stock: ${above.map((c) => c.key).join(", ")}.`);
|
|
117
|
+
}
|
|
118
|
+
const reverted = above.filter((c) => !choice.keep?.includes(c.key));
|
|
119
|
+
return { preset: withoutChanges(preset, reverted.map((c) => c.key)), reverted };
|
|
120
|
+
}
|
|
121
|
+
if (choice.mode === "keep")
|
|
122
|
+
return { preset, reverted: [] };
|
|
123
|
+
if (choice.mode === "stock")
|
|
124
|
+
return { preset: withoutChanges(preset, above.map((c) => c.key)), reverted: above };
|
|
125
|
+
throw new Error(aboveStockText(above, verb));
|
|
126
|
+
}
|
|
127
|
+
function revertedText(reverted) {
|
|
128
|
+
return ` Snapmaker's stock value for: ${reverted.map((c) => `${c.label} (${c.stock})`).join(", ")}`;
|
|
129
|
+
}
|
|
130
|
+
function openMaster(path) {
|
|
131
|
+
if (!path.toLowerCase().endsWith(".3mf"))
|
|
132
|
+
throw new Error(`${path} isn't a .3mf project; a preset is made from one project you tuned in Snapmaker Orca.`);
|
|
133
|
+
if (statSync(path).size > MAX_INPUT_BYTES)
|
|
134
|
+
throw new Error(`${path} is larger than ${MAX_INPUT_BYTES / 1024 / 1024} MB, the most a preset can be made from.`);
|
|
135
|
+
return Project.open(new Uint8Array(readFileSync(path)));
|
|
136
|
+
}
|
|
137
|
+
/** `presets add <name> <master.3mf>` */
|
|
138
|
+
export async function runPresetsAdd(name, masterPath, options, out) {
|
|
139
|
+
const extracted = await extractPreset(openMaster(masterPath), { profiles: options.catalog });
|
|
140
|
+
const checked = PresetSchema.safeParse({ ...extracted.preset, name });
|
|
141
|
+
if (!checked.success)
|
|
142
|
+
throw new Error(`A preset name must be 1 to 40 characters of plain text on one line.`);
|
|
143
|
+
const preset = checked.data;
|
|
144
|
+
const base = options.catalog.get(preset.base);
|
|
145
|
+
out(`${preset.name}: ${extracted.changes.length} change${extracted.changes.length === 1 ? "" : "s"} on ${base?.displayName ?? preset.base}${preset.baseInferred ? " (matched from nozzle and layer height)" : ""}`);
|
|
146
|
+
out(formatChanges(extracted.changes));
|
|
147
|
+
for (const note of extracted.notes)
|
|
148
|
+
out(` note: ${note}`);
|
|
149
|
+
let decided;
|
|
150
|
+
try {
|
|
151
|
+
decided = decideAboveStock(preset, extracted.changes, options.aboveStock, "save");
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
throw new Error(`Not saved.\n${err instanceof Error ? err.message : String(err)}`);
|
|
155
|
+
}
|
|
156
|
+
if (decided.reverted.length > 0)
|
|
157
|
+
out(revertedText(decided.reverted));
|
|
158
|
+
out(`Saved to ${savePreset(options.env, decided.preset, options.force)}`);
|
|
159
|
+
return 0;
|
|
160
|
+
}
|
|
161
|
+
/** `presets list` */
|
|
162
|
+
export function runPresetsList(options, out, err) {
|
|
163
|
+
const saved = loadSavedPresets(options.env, err);
|
|
164
|
+
if (options.json) {
|
|
165
|
+
out(serializePresets(saved.map((s) => s.preset)).trimEnd());
|
|
166
|
+
return 0;
|
|
167
|
+
}
|
|
168
|
+
if (saved.length === 0) {
|
|
169
|
+
out('No saved presets. Make one with "any2orca presets add <name> <tuned.3mf>".');
|
|
170
|
+
return 0;
|
|
171
|
+
}
|
|
172
|
+
out(formatTable([["NAME", "BASE PROFILE", "CHANGES", "CREATED"], ...saved.map((s) => [s.preset.name, s.preset.base, String(Object.keys(s.preset.changes).length), s.preset.created])]));
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
/** `presets show <name>` */
|
|
176
|
+
export async function runPresetsShow(name, options, out) {
|
|
177
|
+
const saved = findSaved(options.env, name);
|
|
178
|
+
if (!saved)
|
|
179
|
+
throw new Error(`No saved preset named "${name.slice(0, 40)}". Run "any2orca presets list".`);
|
|
180
|
+
const resolved = await resolvePreset(saved.preset, options.catalog);
|
|
181
|
+
if (options.json) {
|
|
182
|
+
out(JSON.stringify({ preset: saved.preset, changes: resolved.described, notes: resolved.notes }, null, 2));
|
|
183
|
+
return 0;
|
|
184
|
+
}
|
|
185
|
+
out(`${saved.preset.name}: on ${options.catalog.get(resolved.profileId)?.displayName ?? resolved.profileId}, made ${saved.preset.created} with profiles ${saved.preset.catalog.version}`);
|
|
186
|
+
out(formatChanges(resolved.described));
|
|
187
|
+
for (const note of resolved.notes)
|
|
188
|
+
out(` note: ${note}`);
|
|
189
|
+
return 0;
|
|
190
|
+
}
|
|
191
|
+
/** `presets remove <name>` */
|
|
192
|
+
export function runPresetsRemove(name, options, out) {
|
|
193
|
+
const saved = findSaved(options.env, name);
|
|
194
|
+
if (!saved)
|
|
195
|
+
throw new Error(`No saved preset named "${name.slice(0, 40)}". Run "any2orca presets list".`);
|
|
196
|
+
rmSync(saved.path);
|
|
197
|
+
out(`Removed ${saved.preset.name}.`);
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
/** `presets export [names...] [--out <file>]` */
|
|
201
|
+
export function runPresetsExport(names, options, out) {
|
|
202
|
+
const saved = loadSavedPresets(options.env);
|
|
203
|
+
const chosen = names.length === 0 ? saved : names.map((n) => saved.find((s) => s.preset.name.toLowerCase() === n.trim().toLowerCase()) ?? n);
|
|
204
|
+
const missing = chosen.filter((c) => typeof c === "string");
|
|
205
|
+
if (missing.length > 0)
|
|
206
|
+
throw new Error(`No saved preset named ${missing.map((m) => `"${m.slice(0, 40)}"`).join(", ")}. Run "any2orca presets list".`);
|
|
207
|
+
const text = serializePresets(chosen.map((s) => s.preset));
|
|
208
|
+
if (options.out) {
|
|
209
|
+
if (existsSync(options.out) && !options.force)
|
|
210
|
+
throw new Error(`${options.out} already exists. Add --force to replace it.`);
|
|
211
|
+
writeFileSync(options.out, text);
|
|
212
|
+
out(`Exported ${chosen.length} preset${chosen.length === 1 ? "" : "s"} to ${options.out}`);
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
out(text.trimEnd());
|
|
216
|
+
}
|
|
217
|
+
return 0;
|
|
218
|
+
}
|
|
219
|
+
/** `presets import <file>`: saves each preset in the file. One that can't be saved is skipped with the reason. */
|
|
220
|
+
export async function runPresetsImport(file, options, out) {
|
|
221
|
+
if (statSync(file).size > MAX_PRESETS_FILE_BYTES)
|
|
222
|
+
throw new Any2orcaError("invalid_preset", `${file} is larger than the ${MAX_PRESETS_FILE_BYTES / 1024 / 1024} MB a presets file can be.`);
|
|
223
|
+
const parsed = parsePresetFile(new Uint8Array(readFileSync(file)));
|
|
224
|
+
let added = 0;
|
|
225
|
+
let skipped = 0;
|
|
226
|
+
for (const preset of parsed.presets) {
|
|
227
|
+
try {
|
|
228
|
+
const resolved = await resolvePreset(preset, options.catalog);
|
|
229
|
+
const decided = decideAboveStock(preset, resolved.described, options.aboveStock, "save");
|
|
230
|
+
savePreset(options.env, decided.preset, options.force);
|
|
231
|
+
if (decided.reverted.length > 0)
|
|
232
|
+
out(` ${preset.name}: ${revertedText(decided.reverted).trim()}`);
|
|
233
|
+
for (const note of resolved.notes)
|
|
234
|
+
out(` ${preset.name}: note: ${note}`);
|
|
235
|
+
out(`Imported ${preset.name}`);
|
|
236
|
+
added++;
|
|
237
|
+
}
|
|
238
|
+
catch (err) {
|
|
239
|
+
out(`Skipped ${preset.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
240
|
+
skipped++;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
out(`${added} imported, ${skipped} skipped.`);
|
|
244
|
+
return skipped > 0 ? 1 : 0;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* The preset `convert --preset` names: a saved preset's name, or a presets
|
|
248
|
+
* file holding exactly one preset. A preset from a file hasn't been agreed
|
|
249
|
+
* to, so speeds above stock need a choice (--above-stock or --keep).
|
|
250
|
+
*/
|
|
251
|
+
export async function presetForConvert(nameOrPath, env, catalog, choice) {
|
|
252
|
+
const { preset, saved } = namedPreset(nameOrPath, env, "--preset");
|
|
253
|
+
if (saved)
|
|
254
|
+
return preset;
|
|
255
|
+
const resolved = await resolvePreset(preset, catalog);
|
|
256
|
+
return decideAboveStock(preset, resolved.described, choice, "use").preset;
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* The preset `diff --against-preset` names, found the same way as for
|
|
260
|
+
* convert. A comparison only shows the preset's values, so a presets file
|
|
261
|
+
* needs no choice about speeds above stock.
|
|
262
|
+
*/
|
|
263
|
+
export function presetForDiff(nameOrPath, env) {
|
|
264
|
+
return namedPreset(nameOrPath, env, "--against-preset").preset;
|
|
265
|
+
}
|
|
266
|
+
/** A saved preset by name, or the one preset in a presets file at that path. */
|
|
267
|
+
function namedPreset(nameOrPath, env, flag) {
|
|
268
|
+
const saved = findSaved(env, nameOrPath);
|
|
269
|
+
if (saved)
|
|
270
|
+
return { preset: saved.preset, saved: true };
|
|
271
|
+
if (!nameOrPath.toLowerCase().endsWith(".json") || !existsSync(nameOrPath)) {
|
|
272
|
+
throw new Error(`No saved preset named "${nameOrPath.slice(0, 40)}", and no presets file at that path. Run "any2orca presets list".`);
|
|
273
|
+
}
|
|
274
|
+
if (statSync(nameOrPath).size > MAX_PRESETS_FILE_BYTES)
|
|
275
|
+
throw new Any2orcaError("invalid_preset", `${nameOrPath} is larger than a presets file can be.`);
|
|
276
|
+
const parsed = parsePresetFile(new Uint8Array(readFileSync(nameOrPath)));
|
|
277
|
+
if (parsed.presets.length !== 1)
|
|
278
|
+
throw new Error(`${nameOrPath} holds ${parsed.presets.length} presets; ${flag} takes a file with exactly one. Import it with "any2orca presets import" and name one instead.`);
|
|
279
|
+
return { preset: parsed.presets[0], saved: false };
|
|
280
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ProfileCatalog, ProfileSummary } from "../../profiles.js";
|
|
2
|
+
/** Renders `any2orca profiles`: one row per profile, sorted by id the way `sort` would. */
|
|
3
|
+
export declare function formatProfiles(profiles: ProfileSummary[]): string;
|
|
4
|
+
/** `any2orca profiles [--nozzle <mm>]`: what `convert --profile <id>` accepts. */
|
|
5
|
+
export declare function runProfiles(catalog: ProfileCatalog, nozzleDiameter: string | undefined, out: (line: string) => void): void;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { formatTable } from "../table.js";
|
|
2
|
+
/** Renders `any2orca profiles`: one row per profile, sorted by id the way `sort` would. */
|
|
3
|
+
export function formatProfiles(profiles) {
|
|
4
|
+
// Byte-wise, not localeCompare, so it matches piping through `sort`.
|
|
5
|
+
const sorted = [...profiles].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
|
6
|
+
return formatTable(sorted.map((p) => [
|
|
7
|
+
p.id,
|
|
8
|
+
p.displayName,
|
|
9
|
+
`${p.nozzleDiameter}mm`,
|
|
10
|
+
p.tierName + (p.autoSelectable ? "" : " (manual-select only)") + (p.highFlowSpeeds ? " (high-flow speeds)" : ""),
|
|
11
|
+
]));
|
|
12
|
+
}
|
|
13
|
+
/** `any2orca profiles [--nozzle <mm>]`: what `convert --profile <id>` accepts. */
|
|
14
|
+
export function runProfiles(catalog, nozzleDiameter, out) {
|
|
15
|
+
const profiles = catalog.list(nozzleDiameter ? { nozzleDiameter } : {});
|
|
16
|
+
if (profiles.length === 0) {
|
|
17
|
+
out(nozzleDiameter ? `No profiles found for nozzle diameter ${nozzleDiameter}.` : "No profiles found.");
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
out(formatProfiles(profiles));
|
|
21
|
+
const { slicer, dataVersion } = catalog.index;
|
|
22
|
+
out(`\nProfiles track ${slicer.name} ${slicer.version} (catalog ${dataVersion}).`);
|
|
23
|
+
if (profiles.some((p) => p.highFlowSpeeds)) {
|
|
24
|
+
out('"high-flow speeds": has Snapmaker\'s high-flow tuning, used with convert --high-flow (Liber High Flow Hotend on all four toolheads).');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Env } from "../config.js";
|
|
2
|
+
/** `any2orca telemetry show`: everything this tool can contact, and why, in one place. */
|
|
3
|
+
export declare function runTelemetryShow(env: Env, isTTY: boolean, out: (line: string) => void): void;
|
|
4
|
+
export declare function runTelemetrySet(choice: "on" | "off", env: Env, out: (line: string) => void): void;
|
|
5
|
+
export declare function runUpdateCheckSet(enabled: boolean, env: Env, out: (line: string) => void): void;
|
|
6
|
+
export declare function runTelemetryClear(env: Env, out: (line: string) => void): void;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
import { NEVER_SENT, StatsEventSchema } from "../../telemetry.js";
|
|
3
|
+
import { readCliConfig, updateCliConfig } from "../config.js";
|
|
4
|
+
import { clearSentLog, readSentLog, resolveStatsStatus } from "../stats.js";
|
|
5
|
+
import { REGISTRY_LATEST_URL, updateCheckDisabledReason } from "../updateCheck.js";
|
|
6
|
+
/** `any2orca telemetry show`: everything this tool can contact, and why, in one place. */
|
|
7
|
+
export function runTelemetryShow(env, isTTY, out) {
|
|
8
|
+
const stats = resolveStatsStatus(env);
|
|
9
|
+
out(`Usage stats: ${stats.enabled ? "ON" : "off"} (${stats.reason}).`);
|
|
10
|
+
if (stats.endpoint)
|
|
11
|
+
out(` Collector: ${stats.endpoint}`);
|
|
12
|
+
out(" When on, one small event is sent after each successful conversion. Its fields:");
|
|
13
|
+
for (const [key, schema] of Object.entries(StatsEventSchema.shape)) {
|
|
14
|
+
out(` ${key}${schema.isOptional() ? " (optional)" : ""}: ${schema.description ?? ""}`.trimEnd());
|
|
15
|
+
}
|
|
16
|
+
out(" Never sent:");
|
|
17
|
+
for (const item of NEVER_SENT)
|
|
18
|
+
out(` - ${item}`);
|
|
19
|
+
out(" Like any web request, sending an event shows the collector your IP address.");
|
|
20
|
+
out(' To see the exact event for a file without sending anything: any2orca convert <file> --dry-run-telemetry');
|
|
21
|
+
const disabled = updateCheckDisabledReason({ env, isTTY, flagDisabled: false });
|
|
22
|
+
out(`\nUpdate check: ${disabled ? `off (${disabled})` : "on"}.`);
|
|
23
|
+
out(` Saved setting: ${readCliConfig(env).updateCheck?.enabled === false ? "off" : "on"}.`);
|
|
24
|
+
out(` At most once a day, asks ${REGISTRY_LATEST_URL} for the latest version. Sends the package name only.`);
|
|
25
|
+
out(" Turn off: NO_UPDATE_NOTIFIER=1, --no-update-notifier, or: any2orca telemetry update-check off");
|
|
26
|
+
const sent = readSentLog(env);
|
|
27
|
+
out(`\nStats events sent from this machine (last ${sent.length}, stored only here):`);
|
|
28
|
+
if (sent.length === 0)
|
|
29
|
+
out(" none");
|
|
30
|
+
for (const entry of sent)
|
|
31
|
+
out(` ${entry.sentAt} -> ${entry.endpoint}\n ${JSON.stringify(entry.event)}`);
|
|
32
|
+
}
|
|
33
|
+
export function runTelemetrySet(choice, env, out) {
|
|
34
|
+
updateCliConfig((c) => ({ ...c, stats: { choice, decidedOn: new Date().toISOString().slice(0, 10) } }), env);
|
|
35
|
+
const status = resolveStatsStatus(env);
|
|
36
|
+
out(`Usage stats turned ${choice}.${choice === "on" && !status.enabled ? ` Nothing is sent yet: ${status.reason}.` : ""}`);
|
|
37
|
+
}
|
|
38
|
+
export function runUpdateCheckSet(enabled, env, out) {
|
|
39
|
+
updateCliConfig((c) => ({ ...c, updateCheck: { ...c.updateCheck, enabled } }), env);
|
|
40
|
+
out(`Update check turned ${enabled ? "on" : "off"}.`);
|
|
41
|
+
}
|
|
42
|
+
export function runTelemetryClear(env, out) {
|
|
43
|
+
clearSentLog(env);
|
|
44
|
+
out("Cleared the local log of sent stats.");
|
|
45
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface CliConfig {
|
|
2
|
+
stats?: {
|
|
3
|
+
choice: "on" | "off";
|
|
4
|
+
decidedOn: string;
|
|
5
|
+
};
|
|
6
|
+
updateCheck?: {
|
|
7
|
+
enabled?: boolean;
|
|
8
|
+
lastCheckedAt?: number;
|
|
9
|
+
latest?: string;
|
|
10
|
+
outputAffecting?: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export type Env = Record<string, string | undefined>;
|
|
14
|
+
export declare function configDir(env?: Env): string;
|
|
15
|
+
export declare function readCliConfig(env?: Env): CliConfig;
|
|
16
|
+
/** Writes atomically (temp file + rename), so a crash never leaves a half-written config. */
|
|
17
|
+
export declare function writeCliConfig(config: CliConfig, env?: Env): void;
|
|
18
|
+
export declare function updateCliConfig(update: (config: CliConfig) => CliConfig, env?: Env): void;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT
|
|
2
|
+
/**
|
|
3
|
+
* The CLI's own small config folder: the usage-stats choice, the
|
|
4
|
+
* update-check cache, and the local log of stats actually sent. Nothing in
|
|
5
|
+
* it ever leaves the machine.
|
|
6
|
+
*
|
|
7
|
+
* Location: $ANY2ORCA_CONFIG_DIR, else %APPDATA%\any2orca on Windows, else
|
|
8
|
+
* $XDG_CONFIG_HOME/any2orca or ~/.config/any2orca.
|
|
9
|
+
*/
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
export function configDir(env = process.env) {
|
|
14
|
+
if (env.ANY2ORCA_CONFIG_DIR)
|
|
15
|
+
return env.ANY2ORCA_CONFIG_DIR;
|
|
16
|
+
if (process.platform === "win32" && env.APPDATA)
|
|
17
|
+
return join(env.APPDATA, "any2orca");
|
|
18
|
+
return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "any2orca");
|
|
19
|
+
}
|
|
20
|
+
function configPath(env) {
|
|
21
|
+
return join(configDir(env), "config.json");
|
|
22
|
+
}
|
|
23
|
+
const MAX_CONFIG_BYTES = 64 * 1024;
|
|
24
|
+
export function readCliConfig(env = process.env) {
|
|
25
|
+
const path = configPath(env);
|
|
26
|
+
if (!existsSync(path))
|
|
27
|
+
return {};
|
|
28
|
+
try {
|
|
29
|
+
const text = readFileSync(path, "utf-8");
|
|
30
|
+
if (text.length > MAX_CONFIG_BYTES)
|
|
31
|
+
return {};
|
|
32
|
+
const value = JSON.parse(text);
|
|
33
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Writes atomically (temp file + rename), so a crash never leaves a half-written config. */
|
|
40
|
+
export function writeCliConfig(config, env = process.env) {
|
|
41
|
+
const dir = configDir(env);
|
|
42
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
43
|
+
const path = configPath(env);
|
|
44
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
45
|
+
writeFileSync(temp, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
46
|
+
renameSync(temp, path);
|
|
47
|
+
}
|
|
48
|
+
export function updateCliConfig(update, env = process.env) {
|
|
49
|
+
writeCliConfig(update(readCliConfig(env)), env);
|
|
50
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** The most files one pattern may name. A folder holding more than this is a mistake to stop, not a job to start. */
|
|
2
|
+
export declare const MAX_WILDCARD_MATCHES = 5000;
|
|
3
|
+
/**
|
|
4
|
+
* Expands `*` and `?` in the file-name part of each argument, for shells that
|
|
5
|
+
* leave them for the program (Command Prompt and PowerShell). An argument that
|
|
6
|
+
* names a file that exists is left alone, as is one with no wildcard, so a
|
|
7
|
+
* shell that already expanded the pattern changes nothing.
|
|
8
|
+
*
|
|
9
|
+
* Wildcards work in the file name only, never in folder names, and never
|
|
10
|
+
* reach into subfolders. A name starting with a dot matches only a pattern
|
|
11
|
+
* that starts with one, as in a Unix shell. Matches are files (not folders),
|
|
12
|
+
* sorted by name, and a file already in the list is not added twice.
|
|
13
|
+
* A pattern that matches nothing, or too much, is an error.
|
|
14
|
+
*/
|
|
15
|
+
export declare function expandInputPatterns(args: string[], options?: {
|
|
16
|
+
caseInsensitive?: boolean;
|
|
17
|
+
}): string[];
|