tsdraft 0.1.0 → 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/dist/lint.js ADDED
@@ -0,0 +1,109 @@
1
+ import { layerColorProblem, layerNameProblem, textProblem } from "./rules.js";
2
+ /**
3
+ * Checks a drawing against the rules AutoCAD enforces when it opens DXF.
4
+ *
5
+ * A drawing made with `createDrawing()` already passes the error rules for its
6
+ * own DXF version, because the builder throws at the offending call. `lint`
7
+ * matters when a `Drawing` was built by hand or by other code, when it is
8
+ * exported as a different version than it was built for, and for warnings.
9
+ */
10
+ export function lint(drawing, options = {}) {
11
+ const version = options.version ?? drawing.dxf;
12
+ const out = [];
13
+ if (!["in", "ft", "mm", "cm", "m"].includes(drawing.units)) {
14
+ out.push({
15
+ rule: "units",
16
+ severity: "error",
17
+ message: `Unknown units: ${JSON.stringify(drawing.units)}`,
18
+ });
19
+ }
20
+ const seen = new Set();
21
+ for (const layer of drawing.layers) {
22
+ const error = (rule, message) => out.push({ rule, severity: "error", message, layer: layer.name });
23
+ const nameProblem = layerNameProblem(layer.name, version);
24
+ if (nameProblem)
25
+ error("layer-name", `Layer ${JSON.stringify(layer.name)}: ${nameProblem}`);
26
+ const colorProblem = layerColorProblem(layer.color);
27
+ if (colorProblem)
28
+ error("layer-color", `Layer ${JSON.stringify(layer.name)}: ${colorProblem}`);
29
+ const key = layer.name.toLowerCase();
30
+ if (seen.has(key)) {
31
+ error("duplicate-layer", `Layer ${JSON.stringify(layer.name)} is defined twice. CAD ignores case in layer names`);
32
+ }
33
+ seen.add(key);
34
+ }
35
+ if (!seen.has("0")) {
36
+ out.push({ rule: "undefined-layer", severity: "error", message: 'Layer "0" is missing' });
37
+ }
38
+ drawing.entities.forEach((entity, index) => {
39
+ const add = (rule, severity, problem) => out.push({ rule, severity, message: `${entity.kind} #${index}: ${problem}`, entity: index });
40
+ if (!seen.has(entity.layer.toLowerCase())) {
41
+ add("undefined-layer", "error", `layer ${JSON.stringify(entity.layer)} is not defined`);
42
+ }
43
+ for (const problem of geometryProblems(entity))
44
+ add("geometry", "error", problem);
45
+ if (entity.kind === "text") {
46
+ const problem = textProblem(entity.value);
47
+ if (problem)
48
+ add("text", "error", problem);
49
+ }
50
+ if (entity.kind === "line" && same(entity.from, entity.to)) {
51
+ add("zero-length", "warning", "the line has no length");
52
+ }
53
+ });
54
+ return out;
55
+ }
56
+ /** Thrown by `toDXF` when a drawing has lint errors for the version being written. */
57
+ export class DrawingError extends Error {
58
+ diagnostics;
59
+ constructor(diagnostics) {
60
+ const shown = diagnostics.slice(0, 10).map((d) => `- ${d.message}`);
61
+ const more = diagnostics.length > 10 ? [`- and ${diagnostics.length - 10} more`] : [];
62
+ super(["The drawing cannot be written as DXF:", ...shown, ...more].join("\n"));
63
+ this.name = "DrawingError";
64
+ this.diagnostics = diagnostics;
65
+ }
66
+ }
67
+ function geometryProblems(e) {
68
+ const out = [];
69
+ const finite = (label, ...values) => {
70
+ if (!values.every(Number.isFinite))
71
+ out.push(`${label} must be finite numbers`);
72
+ };
73
+ const positive = (label, value) => {
74
+ if (!(Number.isFinite(value) && value > 0))
75
+ out.push(`${label} must be greater than 0`);
76
+ };
77
+ switch (e.kind) {
78
+ case "line":
79
+ finite("its points", ...e.from, ...e.to);
80
+ break;
81
+ case "polyline":
82
+ if (e.points.length < 2)
83
+ out.push("a polyline needs at least 2 points");
84
+ finite("its points", ...e.points.flat());
85
+ break;
86
+ case "circle":
87
+ finite("its center", ...e.center);
88
+ positive("its radius", e.radius);
89
+ break;
90
+ case "arc":
91
+ finite("its center", ...e.center);
92
+ positive("its radius", e.radius);
93
+ if (![e.startAngle, e.endAngle].every((a) => Number.isFinite(a) && a >= 0 && a < 360)) {
94
+ out.push("its angles must be from 0 up to 360");
95
+ }
96
+ else if (e.startAngle === e.endAngle) {
97
+ out.push("its start and end angles must differ");
98
+ }
99
+ break;
100
+ case "text":
101
+ finite("its position and rotation", ...e.at, e.rotation);
102
+ positive("its height", e.height);
103
+ break;
104
+ }
105
+ return out;
106
+ }
107
+ function same(a, b) {
108
+ return a[0] === b[0] && a[1] === b[1];
109
+ }
@@ -0,0 +1,33 @@
1
+ import type { DxfVersion } from "./drawing.ts";
2
+ declare const NAME_EMPTY = "Layer names cannot be empty";
3
+ declare const NAME_CHARS = "Layer names cannot contain < > / \\ \" : ; ? * | = ` ^ , or line breaks";
4
+ declare const NAME_EDGE = "Layer names cannot start or end with a space";
5
+ declare const NAME_R12_CHARS = "R12 layer names can only use letters, digits, $, - and _. Use DXF version \"R2018\" for other characters";
6
+ declare const NAME_R12_LENGTH = "R12 layer names cannot be longer than 31 characters. Use DXF version \"R2018\" for longer names";
7
+ declare const COLOR = "A layer color must be an AutoCAD Color Index integer from 1 to 255";
8
+ declare const POSITIVE = "This value must be greater than 0";
9
+ type ForbiddenChar = "<" | ">" | "/" | "\\" | '"' | ":" | ";" | "?" | "*" | "|" | "=" | "`" | "^" | "," | "\n" | "\r" | "\t";
10
+ type Chars<S extends string, Found = never> = S extends `${infer C}${infer Rest}` ? Chars<Rest, Found | C> : Found;
11
+ type R12Char = Chars<"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$_-">;
12
+ /** Walks the name one character at a time, counting, so it can check both the characters and the length. */
13
+ type R12Name<N extends string, Rest extends string = N, Count extends 0[] = []> = Count["length"] extends 32 ? typeof NAME_R12_LENGTH : Rest extends `${infer C}${infer Tail}` ? C extends R12Char ? R12Name<N, Tail, [...Count, 0]> : typeof NAME_R12_CHARS : N;
14
+ /**
15
+ * Resolves to `N` when it is a valid layer name for DXF version `V`, and to the
16
+ * error message otherwise, so the compiler reports the reason. Names that are
17
+ * not literals pass the compiler and are checked when the code runs.
18
+ */
19
+ export type LayerName<N extends string, V extends DxfVersion> = string extends N ? N : N extends "" ? typeof NAME_EMPTY : N extends `${string}${ForbiddenChar}${string}` ? typeof NAME_CHARS : N extends ` ${string}` | `${string} ` ? typeof NAME_EDGE : V extends "R12" ? R12Name<N> : N;
20
+ type Enumerate<N extends number, A extends number[] = []> = A["length"] extends N ? A[number] : Enumerate<N, [...A, A["length"]]>;
21
+ /** AutoCAD Color Index: an integer from 1 to 255. */
22
+ export type Aci = Exclude<Enumerate<256>, 0>;
23
+ /** Resolves to `C` when it is a valid layer color, and to the error message otherwise. */
24
+ export type LayerColor<C extends number> = number extends C ? C : C extends Aci ? C : typeof COLOR;
25
+ /** Resolves to `N` when it is greater than 0, and to the error message otherwise. */
26
+ export type Positive<N extends number> = number extends N ? N : `${N}` extends `-${string}` | "0" ? typeof POSITIVE : N;
27
+ /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */
28
+ export declare function layerNameProblem(name: string, version: DxfVersion): string | undefined;
29
+ /** Returns what is wrong with a layer color, or undefined when it is valid. */
30
+ export declare function layerColorProblem(color: number): string | undefined;
31
+ /** Returns what is wrong with a single-line text value, or undefined when it is valid. */
32
+ export declare function textProblem(value: string): string | undefined;
33
+ export {};
package/dist/rules.js ADDED
@@ -0,0 +1,56 @@
1
+ const NAME_EMPTY = "Layer names cannot be empty";
2
+ const NAME_CHARS = 'Layer names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks';
3
+ const NAME_EDGE = "Layer names cannot start or end with a space";
4
+ const NAME_LENGTH = "Layer names cannot be longer than 255 characters";
5
+ const NAME_R12_CHARS = 'R12 layer names can only use letters, digits, $, - and _. Use DXF version "R2018" for other characters';
6
+ const NAME_R12_LENGTH = 'R12 layer names cannot be longer than 31 characters. Use DXF version "R2018" for longer names';
7
+ const COLOR = "A layer color must be an AutoCAD Color Index integer from 1 to 255";
8
+ const POSITIVE = "This value must be greater than 0";
9
+ /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */
10
+ export function layerNameProblem(name, version) {
11
+ if (name.length === 0)
12
+ return NAME_EMPTY;
13
+ if (/[<>/\\":;?*|=`^,]/.test(name) || hasControl(name) || hasAstral(name))
14
+ return NAME_CHARS;
15
+ if (name !== name.trim())
16
+ return NAME_EDGE;
17
+ if (name.length > 255)
18
+ return NAME_LENGTH;
19
+ if (version === "R12") {
20
+ if (!/^[A-Za-z0-9$_-]+$/.test(name))
21
+ return NAME_R12_CHARS;
22
+ if (name.length > 31)
23
+ return NAME_R12_LENGTH;
24
+ }
25
+ return undefined;
26
+ }
27
+ /** Returns what is wrong with a layer color, or undefined when it is valid. */
28
+ export function layerColorProblem(color) {
29
+ return Number.isInteger(color) && color >= 1 && color <= 255 ? undefined : COLOR;
30
+ }
31
+ /** Returns what is wrong with a single-line text value, or undefined when it is valid. */
32
+ export function textProblem(value) {
33
+ if (hasControl(value))
34
+ return "Text must be a single line with no control characters";
35
+ if (hasAstral(value)) {
36
+ return "Text cannot contain emoji or other characters above U+FFFF, because AutoCAD cannot read them from DXF";
37
+ }
38
+ return undefined;
39
+ }
40
+ function hasControl(value) {
41
+ for (let i = 0; i < value.length; i++) {
42
+ const code = value.charCodeAt(i);
43
+ if (code < 0x20 || code === 0x7f)
44
+ return true;
45
+ }
46
+ return false;
47
+ }
48
+ /** True when the string has a character above U+FFFF, which JavaScript stores as a surrogate pair. */
49
+ function hasAstral(value) {
50
+ for (let i = 0; i < value.length; i++) {
51
+ const code = value.charCodeAt(i);
52
+ if (code >= 0xd800 && code <= 0xdfff)
53
+ return true;
54
+ }
55
+ return false;
56
+ }
package/dist/svg.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { sweep } from "./drawing.js";
2
+ import { extents } from "./extents.js";
2
3
  import { fmt } from "./format.js";
3
4
  /** Screen colors for the standard ACI colors 1 to 7. Other indexes draw in currentColor. */
4
5
  const ACI = {
@@ -61,45 +62,6 @@ function entityToSvg(e, color) {
61
62
  }
62
63
  }
63
64
  }
64
- /** Approximate extents. Arcs use their full circle; text assumes 0.6 × height per character. */
65
- function extents(entities) {
66
- let minX = Infinity;
67
- let minY = Infinity;
68
- let maxX = -Infinity;
69
- let maxY = -Infinity;
70
- const add = (x, y) => {
71
- minX = Math.min(minX, x);
72
- minY = Math.min(minY, y);
73
- maxX = Math.max(maxX, x);
74
- maxY = Math.max(maxY, y);
75
- };
76
- for (const e of entities) {
77
- switch (e.kind) {
78
- case "line":
79
- add(...e.from);
80
- add(...e.to);
81
- break;
82
- case "polyline":
83
- for (const p of e.points)
84
- add(...p);
85
- break;
86
- case "circle":
87
- case "arc":
88
- add(e.center[0] - e.radius, e.center[1] - e.radius);
89
- add(e.center[0] + e.radius, e.center[1] + e.radius);
90
- break;
91
- case "text": {
92
- const len = e.value.length * e.height * 0.6;
93
- const r = rad(e.rotation);
94
- add(...e.at);
95
- add(e.at[0] + len * Math.cos(r), e.at[1] + len * Math.sin(r));
96
- add(e.at[0] - e.height * Math.sin(r), e.at[1] + e.height * Math.cos(r));
97
- break;
98
- }
99
- }
100
- }
101
- return minX === Infinity ? [0, 0, 1, 1] : [minX, minY, maxX, maxY];
102
- }
103
65
  function rad(degrees) {
104
66
  return (degrees * Math.PI) / 180;
105
67
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdraft",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "2D CAD drawings as TypeScript: write the drawing in code, export DXF and SVG.",
5
5
  "keywords": [
6
6
  "2d",
@@ -22,7 +22,8 @@
22
22
  "url": "git+https://github.com/Surfside-Software/tsdraft.git"
23
23
  },
24
24
  "files": [
25
- "dist"
25
+ "dist",
26
+ "CHANGELOG.md"
26
27
  ],
27
28
  "type": "module",
28
29
  "sideEffects": false,
@@ -30,7 +31,8 @@
30
31
  ".": {
31
32
  "types": "./dist/index.d.ts",
32
33
  "default": "./dist/index.js"
33
- }
34
+ },
35
+ "./package.json": "./package.json"
34
36
  },
35
37
  "scripts": {
36
38
  "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
@@ -43,6 +45,7 @@
43
45
  "fmt:check": "oxfmt --check",
44
46
  "test": "node --test test/*.test.ts",
45
47
  "test:package": "node scripts/package-smoke.ts",
48
+ "test:cad": "node scripts/cad-check.ts",
46
49
  "example": "node examples/site-plan.ts",
47
50
  "verify": "pnpm fmt:check && pnpm lint && pnpm check && pnpm test && pnpm test:package"
48
51
  },