Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
{
"name": "shapeitup",
"description": "CAD scripting toolkit: create/modify .shape.ts files, validate geometry, check collisions, export STEP/STL/3MF via Replicad + OpenCascade. Runs headless; live 3D preview available if the ShapeItUp VS Code extension is installed.",
"version": "1.30.1",
"version": "1.31.1",
"author": {
"name": "Asbjorn Rorvik",
"email": "rorvik.asbjorn@gmail.com"
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Thumbs.db
*.stl
*.step
*.tsbuildinfo
# ...except STEP inputs the importStep tests read.
!packages/core/src/testing/fixtures/*.step

# Claude Code local state
.claude/plans/
Expand Down
39 changes: 39 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,45 @@ Releases 1.17.0–1.24.0 are described only in their
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); the
project follows semantic versioning at the extension level.

## [1.31.1] - 2026-10-24

Extension `1.31.1` / mcp-server `1.31.1` — STEP export no longer crashes the
next run.

### Fixed
- **The render after a STEP export could crash OpenCascade** with "memory
access out of bounds", most often when that render rebundled because a local
import had changed (about 4 runs in 5). One MCP process doing export → next
file, as a benchmark run does, hit it every few files. Replicad's
`exportSTEP` frees its STEP work session twice once the garbage collector
gets to it: directly, and again through the refcounted handle the writer
shares. ShapeItUp now writes STEP itself with one owner per OpenCascade
object and frees them all before returning. The file is the same as before.
This covers `export_shape`, the viewer's STEP button, and scripts that call
`exportSTEP` themselves.

## [1.31.0] - 2026-10-22

Extension `1.31.0` / mcp-server `1.31.0` — STEP import.

### Added
- **Scripts can load an existing STEP file and edit it.** A `.shape.ts` can
`import part from "./input.step"` (`.step` / `.stp`, either case); every
bundler — the MCP engine, the VS Code extension and the serve host — inlines
the file as a `Uint8Array`. `importStep(bytes)` from `"shapeitup"` turns
those bytes into a shape synchronously, so it works inside `main()`, and the
result cuts, fuses and exports like any other shape. Editing the STEP file
re-renders the script. Editor typings declare `*.step` / `*.stp` modules, so
the import type-checks. Documented in `get_api_reference` (`stdlib`,
`export`) and the skill.

### Fixed
- **An `async main()` failed with "main() must return one of …"**, which said
nothing about the cause. `main()` runs synchronously, so an async main, or
Replicad's async `importSTEP()` returned directly, now fails with "main()
returned a Promise" and points at `importStep`. The abandoned Promise's
rejection is silenced instead of surfacing later as an unhandled one.

## [1.30.1] - 2026-10-12

Extension `1.30.1` / mcp-server `1.30.1` — Codex setup docs and three fixes.
Expand Down
8 changes: 7 additions & 1 deletion esbuild.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,14 @@ function copyExtensionTypings() {
// Wrapper index.d.ts — re-exports everything from the emitted stdlib.
// Matches packages/extension/typings/shapeitup/index.d.ts but self-
// contained (no relative path out to the core source).
const wrapper = `// Auto-generated by ShapeItUp build. Do not edit.\n// Re-exports the stdlib declarations bundled alongside this file.\nexport * from "./stdlib/index";\n`;
// The reference pulls in the ambient `*.step` module types, so
// `import part from "./input.step"` type-checks in user projects.
const wrapper = `// Auto-generated by ShapeItUp build. Do not edit.\n// Re-exports the stdlib declarations bundled alongside this file.\n/// <reference path="./step-imports.d.ts" />\nexport * from "./stdlib/index";\n`;
writeFileSync(resolve(shapeitupDest, "index.d.ts"), wrapper);
cpSync(
resolve(typingsSrc, "shapeitup/step-imports.d.ts"),
resolve(shapeitupDest, "step-imports.d.ts"),
);

const pkg = {
name: "shapeitup",
Expand Down
43 changes: 43 additions & 0 deletions packages/core/src/executor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,49 @@ describe("executeScript — minimal scripts", () => {
});
});

describe("executeScript — main() returning a Promise", () => {
// `async function main()` and replicad's async `importSTEP` both hand back a
// Promise; the executor never awaits it. The error must say so and point at
// the synchronous `importStep`, not fall through to "must return one of".
const ASYNC_MESSAGE = /main\(\) returned a Promise[\s\S]*importStep/;

it("rejects an async main with a message that names importStep", () => {
const js = `
async function main() { return 1; }
export { main as default };
`;
expect(() => executeScript(js, {}, {})).toThrow(ASYNC_MESSAGE);
});

it("rejects a part whose shape is still a Promise", () => {
const importSTEP = async () => ({});
const js = `
import { importSTEP } from "replicad";
function main() { return [{ shape: importSTEP(new Blob([])), name: "input" }]; }
export { main as default };
`;
expect(() => executeScript(js, { importSTEP }, {})).toThrow(ASYNC_MESSAGE);
});

it("silences the abandoned Promise's rejection", async () => {
const unhandled: unknown[] = [];
const onUnhandled = (reason: unknown) => unhandled.push(reason);
process.on("unhandledRejection", onUnhandled);
try {
const js = `
async function main() { throw new Error("STEP read failed"); }
export { main as default };
`;
expect(() => executeScript(js, {}, {})).toThrow(ASYNC_MESSAGE);
// Unhandled rejections are reported after the microtask queue drains.
await new Promise((r) => setTimeout(r, 10));
expect(unhandled).toEqual([]);
} finally {
process.off("unhandledRejection", onUnhandled);
}
});
});

describe("executeScript — params flow", () => {
it("uses declared param defaults when no overrides are passed", () => {
const js = `
Expand Down
42 changes: 42 additions & 0 deletions packages/core/src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,46 @@ export function rewriteImports(js: string): string {
return code;
}

const isThenable = (v: any): boolean =>
v !== null && (typeof v === "object" || typeof v === "function") && typeof v.then === "function";

/**
* Throw a clear error when `main()` handed back a Promise — an `async main`, or
* replicad's `importSTEP` / `importSTL` (both async) returned directly. The
* executor calls `main()` synchronously, so without this the Promise reaches
* `normalizeParts` and fails as "main() must return one of …", which says
* nothing about why.
*
* Each Promise gets a no-op rejection handler first: nothing will ever await
* it, and a rejection would otherwise surface later as an unhandled one.
*/
export function rejectAsyncResult(result: any): void {
const pending: any[] = [];
if (isThenable(result)) pending.push(result);
else if (Array.isArray(result)) {
for (const item of result) {
if (isThenable(item)) pending.push(item);
else if (item && isThenable(item.shape)) pending.push(item.shape);
}
}
if (pending.length === 0) return;
for (const p of pending) {
try {
p.then(undefined, () => {});
} catch {
// A thenable with a throwing `then` — nothing to silence.
}
}
throw new Error(
`main() returned a Promise. ShapeItUp calls main() synchronously, so an async main(), ` +
`await, and replicad's async importSTEP()/importSTL() cannot be used.\n` +
`To load a STEP file, import it and use the synchronous importStep from "shapeitup":\n` +
` import part from "./input.step";\n` +
` import { importStep } from "shapeitup";\n` +
` export default function main() { return importStep(part); }`,
);
}

/**
* Execute a user .shape.ts script (already transpiled/bundled to JS).
*
Expand Down Expand Up @@ -501,6 +541,8 @@ export function executeScript(
paramOverrides || null
);

rejectAsyncResult(result);

// Resolve the script-level `export const material = ...` via the shared
// resolver (also used per-part inside `normalizeParts`). Unknown strings
// emit a runtime warning so a typo is visible instead of silently losing
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/exporter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { PartInput } from "./tessellate";
import { generate3MF } from "./3mf";
import { writeStep } from "./step-writer";

export async function exportShapes(
parts: PartInput[],
Expand All @@ -15,9 +16,11 @@ async function exportPartsCombined(
replicadModule: any
): Promise<ArrayBuffer> {
if (format === "step") {
// Not replicadModule.exportSTEP: that one frees its work session twice
// once GC collects it, and the next OCCT call crashes. See step-writer.ts.
const stepParts = parts.map((p) => ({ shape: p.shape, name: p.name }));
const blob: Blob = replicadModule.exportSTEP(stepParts);
return blob.arrayBuffer();
const bytes = writeStep(replicadModule.getOC(), stepParts);
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
} else if (format === "3mf") {
return generate3MF(parts);
} else {
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { executeScript } from "./executor";
export { extractParamsStatic, extractConfigStatic, extractExpectedContactsStatic } from "./executor";
import { describeFaces, normalizeParts, tessellatePart, type MeshQuality, type PartInput, type PartStatsLevel, type TessellatedPart } from "./tessellate";
import { exportShapes, exportShapesSplit } from "./exporter";
import { makeExportSTEP } from "./step-writer";
import {
validateParts,
hasGeometryErrors,
Expand Down Expand Up @@ -871,6 +872,10 @@ export async function initCore(
patchShapeFuseNoOpGuard(replicad);

const replicadExports: Record<string, any> = { ...replicad };
// Scripts that call exportSTEP themselves get the version without the
// double-freed work session too. The module namespace is read-only, so the
// swap happens on this copy, which is what scripts destructure from.
replicadExports.exportSTEP = makeExportSTEP(replicad.getOC);
instrumentReplicadExports(replicadExports);

let lastParts: PartInput[] = [];
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/stdlib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { Part, joint, jointAt, part, faceAt, shaftAt, boreAt } from "./parts";
import { mate, assemble, subassembly, stack, stackOnZ, entries, symmetricPair, debugJoints, highlightJoints, composeAssembly } from "./assembly";
import { cylinder, rod } from "./cylinder";
import { box, prism, plate, wall } from "./shapes";
import { importStep } from "./step";
// `plates` is a small namespace containing the plate-shaped helper(s). Kept
// separate from the top-level `plate` export so user scripts can reach either
// (`plates.plate({...})` mirrors `holes.through(...)` / `motors.nema17()`).
Expand Down Expand Up @@ -64,6 +65,9 @@ export type { Placement } from "./patterns";
// warning can type its callback without reaching into the module.
export type { CombineOp, CombineOptions, CombineStats } from "./booleans";

// The argument type of `importStep`, for scripts that wrap it.
export type { StepSource } from "./step";

// User-facing view of the standards namespace. Unknown-key reads throw with
// a did-you-mean suggestion so `standards.NEMA17.pilotDiameter` (typo for
// `pilotDia`) fails fast instead of returning undefined and propagating as
Expand Down Expand Up @@ -138,6 +142,7 @@ export {
gears,
pins,
cradles,
importStep,
};

/**
Expand Down Expand Up @@ -200,6 +205,7 @@ export const shapeitupStdlib = {
gears,
pins,
cradles,
importStep,
standards,
};

Expand Down
127 changes: 127 additions & 0 deletions packages/core/src/stdlib/step.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/**
* importStep against real OCCT.
*
* The fixture is a 40 x 30 x 10 mm block that ShapeItUp exported itself — the
* MCP engine ran
*
* export default function main() {
* return { shape: drawRectangle(40, 30).sketchOnPlane("XY").extrude(10), name: "block" };
* }
*
* and `export_shape` wrote the STEP. Volumes are checked against that, not
* snapshotted: the failures worth catching are an import that silently comes
* back empty, or a shape that loads but won't take a boolean.
*/
import { describe, it, expect, beforeAll } from "vitest";
import { readFileSync } from "node:fs";
import { loadOCCTForTest } from "../testing/occt.js";

const FIXTURE = new URL("../testing/fixtures/block-40x30x10.step", import.meta.url);
const BLOCK_VOLUME = 40 * 30 * 10;

let oc: any;
let rc: typeof import("replicad");
let importStep: typeof import("./step.js").importStep;
let writeStep: typeof import("../step-writer.js").writeStep;
let shapeitupStdlib: typeof import("./index.js").shapeitupStdlib;
let fixture: Uint8Array;

beforeAll(async () => {
oc = await loadOCCTForTest();
rc = await import("replicad");
rc.setOC(oc);
({ importStep } = await import("./step.js"));
({ writeStep } = await import("../step-writer.js"));
({ shapeitupStdlib } = await import("./index.js"));
fixture = new Uint8Array(readFileSync(FIXTURE));
}, 120_000);

const vol = (s: any) => rc.measureVolume(s);

describe("importStep", () => {
it("is on the runtime stdlib object scripts destructure from", () => {
expect(shapeitupStdlib.importStep).toBe(importStep);
});

it("returns the file's solid, synchronously", () => {
const shape = importStep(fixture) as any;
expect(shape instanceof Promise).toBe(false);
expect(shape.constructor.name).toBe("Solid");
expect(vol(shape)).toBeCloseTo(BLOCK_VOLUME, 1);
const bb = shape.boundingBox;
expect(bb.width).toBeCloseTo(40, 3);
expect(bb.height).toBeCloseTo(30, 3);
expect(bb.depth).toBeCloseTo(10, 3);
});

it("gives a shape that takes a boolean cut", () => {
const hole = rc.makeCylinder(5, 20, [0, 0, -5]);
const cut = (importStep(fixture) as any).cut(hole);
expect(vol(cut)).toBeCloseTo(BLOCK_VOLUME - Math.PI * 25 * 10, 1);
});

it("accepts an ArrayBuffer and the STEP text itself", () => {
const buffer = new ArrayBuffer(fixture.byteLength);
new Uint8Array(buffer).set(fixture);
expect(vol(importStep(buffer))).toBeCloseTo(BLOCK_VOLUME, 1);
expect(vol(importStep(new TextDecoder().decode(fixture)))).toBeCloseTo(BLOCK_VOLUME, 1);
});

it("round-trips a multi-body export as a compound", () => {
const a = rc.drawRectangle(10, 10).sketchOnPlane("XY").extrude(10);
const b = rc.drawRectangle(10, 10).sketchOnPlane("XY").extrude(10).translate(30, 0, 0);
const shape = importStep(
writeStep(oc, [
{ shape: a, name: "a" },
{ shape: b, name: "b" },
]),
);
expect(shape.constructor.name).toBe("Compound");
expect(vol(shape)).toBeCloseTo(2000, 1);
});

// Class checks compare names: on failure vitest would otherwise try to print
// a replicad shape, whose graph reaches the whole OCCT module, and run out of
// memory instead of reporting.
it("returns a 3D shape for files with no solid in them", async () => {
const face = (rc.drawRectangle(10, 20).sketchOnPlane("XY") as any).face();
const surface = importStep(new Uint8Array(await face.blobSTEP().arrayBuffer())) as any;
expect(surface.constructor.name).toBe("Shell");
expect(rc.measureArea(surface)).toBeCloseTo(200, 3);

const edge = rc.makeLine([0, 0, 0], [25, 0, 0]) as any;
const curve = importStep(new Uint8Array(await edge.blobSTEP().arrayBuffer())) as any;
expect(curve.constructor.name).toBe("Compound");
expect(curve.edges).toHaveLength(1);
expect(rc.measureLength(curve)).toBeCloseTo(25, 3);
});

it("leaves nothing behind in the Emscripten FS", () => {
const before = oc.FS.readdir("/").filter((f: string) => f.startsWith("shapeitup-import-"));
importStep(fixture);
expect(() => importStep(new TextEncoder().encode("not a step file"))).toThrow();
const after = oc.FS.readdir("/").filter((f: string) => f.startsWith("shapeitup-import-"));
expect(after).toEqual(before);
});

it("says to pass bytes when given a path", () => {
expect(() => importStep("./input.step")).toThrow(/bytes, not its path[\s\S]*import part from "\.\/input\.step"/);
});

it("says why a Blob can't work", () => {
const blob = new Blob([fixture as BlobPart]);
expect(() => importStep(blob as any)).toThrow(/Blob[\s\S]*synchronously/);
});

it("names the problem for data that isn't STEP", () => {
expect(() => importStep(new TextEncoder().encode("solid cube\nendsolid cube\n"))).toThrow(
/not a STEP file/,
);
expect(() => importStep(new Uint8Array())).toThrow(/empty/);
});

it("reports a STEP header with a body OCCT can't read as a parse failure", () => {
const truncated = new TextEncoder().encode("ISO-10303-21;\nHEADER;\n");
expect(() => importStep(truncated)).toThrow(/could not parse|contains no shape/);
});
});
Loading