tsdraft 0.1.0 → 0.2.1

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.
@@ -0,0 +1,116 @@
1
+ import type { DxfVersion } from "./drawing.ts";
2
+ import { type REJECTED_COPTIC, type REJECTED_FORMAT, type REJECTED_GEORGIAN, type REJECTED_GLAGOLITIC, type REJECTED_LETTERLIKE, type REJECTED_PRIVATE } from "./layers.ts";
3
+ declare const NAME_EMPTY = "Layer names cannot be empty";
4
+ declare const NAME_CHARS = "Layer names cannot contain < > / \\ \" : ; ? * | = ` ^ , or line breaks";
5
+ declare const NAME_REJECTED = "Layer names cannot contain a character AutoCAD rejects or replaces in names, such as a zero-width space or the ohm sign U+2126. The README lists them";
6
+ declare const NAME_EDGE = "Layer names cannot start or end with a space";
7
+ declare const NAME_R12_CHARS = "R12 layer names can only use letters, digits, $, - and _. Use DXF version \"R2018\" for other characters";
8
+ declare const NAME_R12_LENGTH = "R12 layer names cannot be longer than 31 characters. Use DXF version \"R2018\" for longer names";
9
+ declare const COLOR = "A layer color must be an AutoCAD Color Index integer from 1 to 255";
10
+ declare const POSITIVE = "This value must be greater than 0";
11
+ declare const WRITTEN_AS_ZERO = "This value is written as 0, because tsdraft writes 6 decimals. Use 0.000001 or more";
12
+ declare const TOO_LARGE = "This value must be under 1e100, because AutoCAD reads only two exponent digits from DXF and would take 1e+100 for 1e+10";
13
+ type ForbiddenChar = "<" | ">" | "/" | "\\" | '"' | ":" | ";" | "?" | "*" | "|" | "=" | "`" | "^" | "," | "\n" | "\r" | "\t";
14
+ type Chars<S extends string, Found = never> = S extends `${infer C}${infer Rest}` ? Chars<Rest, Found | C> : Found;
15
+ type R12Char = Chars<"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$_-">;
16
+ type RejectedChar = Chars<typeof REJECTED_FORMAT> | Chars<typeof REJECTED_LETTERLIKE> | Chars<typeof REJECTED_GLAGOLITIC> | Chars<typeof REJECTED_COPTIC> | Chars<typeof REJECTED_GEORGIAN> | Chars<typeof REJECTED_PRIVATE>;
17
+ /** Walks the name one character at a time, counting, so it can check both the characters and the length. */
18
+ 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;
19
+ /**
20
+ * Resolves to `N` when it is a valid layer name for DXF version `V`, and to the
21
+ * error message otherwise, so the compiler reports the reason. Names that are
22
+ * not literals pass the compiler and are checked when the code runs.
23
+ */
24
+ 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}${RejectedChar}${string}` ? typeof NAME_REJECTED : N extends ` ${string}` | `${string} ` ? typeof NAME_EDGE : V extends "R12" ? R12Name<N> : N;
25
+ type Enumerate<N extends number, A extends number[] = []> = A["length"] extends N ? A[number] : Enumerate<N, [...A, A["length"]]>;
26
+ /** AutoCAD Color Index: an integer from 1 to 255. */
27
+ export type Aci = Exclude<Enumerate<256>, 0>;
28
+ /** Resolves to `C` when it is a valid layer color, and to the error message otherwise. */
29
+ export type LayerColor<C extends number> = number extends C ? C : C extends Aci ? C : typeof COLOR;
30
+ /**
31
+ * True for a number the writers round to 0, given as the compiler prints it.
32
+ * A number under 0.000001 prints in exponent form, such as `4e-7`, and those
33
+ * under 0.0000005 round to 0. `5e-7` itself is stored a little below a half,
34
+ * so it rounds down too.
35
+ */
36
+ type WrittenAsZero<S extends string> = S extends `${infer Mantissa}e-${infer Exponent}` ? Exponent extends "7" ? Mantissa extends "5" ? true : Mantissa extends `${5 | 6 | 7 | 8 | 9}${string}` ? false : true : true : false;
37
+ type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
38
+ /**
39
+ * Resolves to `N` when it is a size the writers can keep, and to the error
40
+ * message otherwise: `N` must be greater than 0, must not round to 0 at the
41
+ * 6 decimals tsdraft writes, and must be under 1e100, where the compiler
42
+ * prints a third exponent digit as the writers do.
43
+ */
44
+ export type Positive<N extends number> = number extends N ? N : `${N}` extends `-${string}` | "0" ? typeof POSITIVE : WrittenAsZero<`${N}`> extends true ? typeof WRITTEN_AS_ZERO : `${N}` extends `${string}e+${Digit}${Digit}${Digit}` ? typeof TOO_LARGE : N;
45
+ /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */
46
+ export declare function layerNameProblem(name: string, version: DxfVersion): string | undefined;
47
+ /**
48
+ * Returns what is wrong with a drawing that has both names as layers, or
49
+ * undefined when the two can stand together. AutoCAD looks layers up one way
50
+ * and its AUDIT compares their names another, so a few pairs of names, such
51
+ * as `ΟΔΟΣ` and `οδος`, are two layers to AutoCAD and one duplicate name to
52
+ * AUDIT. Names that are one layer to AutoCAD are not this function's concern.
53
+ * The rule compares two names, so it has no type.
54
+ *
55
+ * @param name - The name of the layer being checked.
56
+ * @param other - The name of another layer in the drawing.
57
+ * @returns The problem, or undefined.
58
+ */
59
+ export declare function layerTwinProblem(name: string, other: string): string | undefined;
60
+ /** Returns what is wrong with a layer color, or undefined when it is valid. */
61
+ export declare function layerColorProblem(color: number): string | undefined;
62
+ /**
63
+ * Returns what is wrong with a radius, a text height or a rectangle size, or
64
+ * undefined when it is valid. A size that is written as 0 is refused like 0
65
+ * itself: AutoCAD gives text of height 0 the drawing's default text height,
66
+ * and a circle of radius 0 is a point. A size of 1e100 or more is refused
67
+ * too, as `magnitudeProblem` explains.
68
+ *
69
+ * @param value - The size, which must be a finite number.
70
+ * @returns The problem, or undefined.
71
+ */
72
+ export declare function sizeProblem(value: number): string | undefined;
73
+ /**
74
+ * Returns what is wrong with the size of a number a drawing holds, or
75
+ * undefined when AutoCAD can read it. This goes for every number that is
76
+ * written: coordinates, sizes and text rotation. Only sizes can be checked as
77
+ * literals, through `Positive`, because points and rotations have no literal
78
+ * types.
79
+ *
80
+ * @param value - The number, which must be finite.
81
+ * @returns The problem, or undefined.
82
+ */
83
+ export declare function magnitudeProblem(value: number): string | undefined;
84
+ /**
85
+ * Returns what is wrong with an arc's angles once they are rounded for
86
+ * writing, or undefined when the arc can be written. AutoCAD holds an arc
87
+ * whose start and end angles are equal as an arc of no length, so an arc that
88
+ * is all but a full circle would vanish. The compiler cannot subtract two
89
+ * literals, so this rule has no type.
90
+ *
91
+ * @param startAngle - The start angle in degrees, from 0 up to 360.
92
+ * @param endAngle - The end angle in degrees, from 0 up to 360.
93
+ * @returns The problem, or undefined.
94
+ */
95
+ export declare function arcProblem(startAngle: number, endAngle: number): string | undefined;
96
+ /**
97
+ * True for an arc so short that its angles are the same once rounded, which
98
+ * is written as an arc of no length. That is within rounding of what was
99
+ * drawn, so it is worth a warning and not an error.
100
+ *
101
+ * @param startAngle - The start angle in degrees, from 0 up to 360.
102
+ * @param endAngle - The end angle in degrees, from 0 up to 360.
103
+ * @returns Whether the arc is written with no length.
104
+ */
105
+ export declare function arcIsWrittenAsPoint(startAngle: number, endAngle: number): boolean;
106
+ /** Returns what is wrong with a single-line text value, or undefined when it is valid. */
107
+ export declare function textProblem(value: string): string | undefined;
108
+ /**
109
+ * Returns a warning for text that AutoCAD stores as written but draws
110
+ * differently, or undefined when it draws what it stores.
111
+ *
112
+ * @param value - The text value.
113
+ * @returns The warning, or undefined.
114
+ */
115
+ export declare function textWarning(value: string): string | undefined;
116
+ export {};
package/dist/rules.js ADDED
@@ -0,0 +1,164 @@
1
+ import { isTooLarge, written, writtenAngle } from "./format.js";
2
+ import { layerAuditKey, layerKey, rejectedNameCharacter, } from "./layers.js";
3
+ const NAME_EMPTY = "Layer names cannot be empty";
4
+ const NAME_CHARS = 'Layer names cannot contain < > / \\ " : ; ? * | = ` ^ , or line breaks';
5
+ const NAME_REJECTED = "Layer names cannot contain a character AutoCAD rejects or replaces in names, such as a zero-width space or the ohm sign U+2126. The README lists them";
6
+ const NAME_EDGE = "Layer names cannot start or end with a space";
7
+ const NAME_LENGTH = "Layer names cannot be longer than 255 characters";
8
+ const NAME_R12_CHARS = 'R12 layer names can only use letters, digits, $, - and _. Use DXF version "R2018" for other characters';
9
+ const NAME_R12_LENGTH = 'R12 layer names cannot be longer than 31 characters. Use DXF version "R2018" for longer names';
10
+ const COLOR = "A layer color must be an AutoCAD Color Index integer from 1 to 255";
11
+ const POSITIVE = "This value must be greater than 0";
12
+ const WRITTEN_AS_ZERO = "This value is written as 0, because tsdraft writes 6 decimals. Use 0.000001 or more";
13
+ const TOO_LARGE = "This value must be under 1e100, because AutoCAD reads only two exponent digits from DXF and would take 1e+100 for 1e+10";
14
+ const ARC_LOST = "An arc of nearly a full turn cannot be written: its angles are the same once rounded to 6 decimals, so AutoCAD would hold an arc of no length. Draw a circle instead";
15
+ const TEXT_PRIVATE_USE = "Text cannot contain the private-use characters U+E800 to U+E8FF, because AutoCAD replaces them when it reads DXF";
16
+ const TEXT_PERCENT = 'AutoCAD reads "%%" in text as the start of a control code: it draws "%%d" as a degree sign and "%%%" as one percent sign. The text is stored as written';
17
+ /** Returns what is wrong with a layer name for a DXF version, or undefined when it is valid. */
18
+ export function layerNameProblem(name, version) {
19
+ if (name.length === 0)
20
+ return NAME_EMPTY;
21
+ if (/[<>/\\":;?*|=`^,]/.test(name) || hasControl(name) || hasAstral(name))
22
+ return NAME_CHARS;
23
+ const rejected = rejectedNameCharacter(name);
24
+ if (rejected !== undefined)
25
+ return `${NAME_REJECTED}. This name has ${codePoint(rejected)}`;
26
+ // Only the ASCII space: AutoCAD takes a no-break space or any other at either end.
27
+ if (name.startsWith(" ") || name.endsWith(" "))
28
+ return NAME_EDGE;
29
+ if (name.length > 255)
30
+ return NAME_LENGTH;
31
+ if (version === "R12") {
32
+ if (!/^[A-Za-z0-9$_-]+$/.test(name))
33
+ return NAME_R12_CHARS;
34
+ if (name.length > 31)
35
+ return NAME_R12_LENGTH;
36
+ }
37
+ return undefined;
38
+ }
39
+ /**
40
+ * Returns what is wrong with a drawing that has both names as layers, or
41
+ * undefined when the two can stand together. AutoCAD looks layers up one way
42
+ * and its AUDIT compares their names another, so a few pairs of names, such
43
+ * as `ΟΔΟΣ` and `οδος`, are two layers to AutoCAD and one duplicate name to
44
+ * AUDIT. Names that are one layer to AutoCAD are not this function's concern.
45
+ * The rule compares two names, so it has no type.
46
+ *
47
+ * @param name - The name of the layer being checked.
48
+ * @param other - The name of another layer in the drawing.
49
+ * @returns The problem, or undefined.
50
+ */
51
+ export function layerTwinProblem(name, other) {
52
+ if (layerKey(name) === layerKey(other) || layerAuditKey(name) !== layerAuditKey(other)) {
53
+ return undefined;
54
+ }
55
+ return `AutoCAD keeps this layer and ${JSON.stringify(other)} as two layers, but its AUDIT reports them as one duplicate name`;
56
+ }
57
+ /** Returns what is wrong with a layer color, or undefined when it is valid. */
58
+ export function layerColorProblem(color) {
59
+ return Number.isInteger(color) && color >= 1 && color <= 255 ? undefined : COLOR;
60
+ }
61
+ /**
62
+ * Returns what is wrong with a radius, a text height or a rectangle size, or
63
+ * undefined when it is valid. A size that is written as 0 is refused like 0
64
+ * itself: AutoCAD gives text of height 0 the drawing's default text height,
65
+ * and a circle of radius 0 is a point. A size of 1e100 or more is refused
66
+ * too, as `magnitudeProblem` explains.
67
+ *
68
+ * @param value - The size, which must be a finite number.
69
+ * @returns The problem, or undefined.
70
+ */
71
+ export function sizeProblem(value) {
72
+ if (!(value > 0))
73
+ return POSITIVE;
74
+ return written(value) === 0 ? WRITTEN_AS_ZERO : magnitudeProblem(value);
75
+ }
76
+ /**
77
+ * Returns what is wrong with the size of a number a drawing holds, or
78
+ * undefined when AutoCAD can read it. This goes for every number that is
79
+ * written: coordinates, sizes and text rotation. Only sizes can be checked as
80
+ * literals, through `Positive`, because points and rotations have no literal
81
+ * types.
82
+ *
83
+ * @param value - The number, which must be finite.
84
+ * @returns The problem, or undefined.
85
+ */
86
+ export function magnitudeProblem(value) {
87
+ return isTooLarge(value) ? TOO_LARGE : undefined;
88
+ }
89
+ /**
90
+ * Returns what is wrong with an arc's angles once they are rounded for
91
+ * writing, or undefined when the arc can be written. AutoCAD holds an arc
92
+ * whose start and end angles are equal as an arc of no length, so an arc that
93
+ * is all but a full circle would vanish. The compiler cannot subtract two
94
+ * literals, so this rule has no type.
95
+ *
96
+ * @param startAngle - The start angle in degrees, from 0 up to 360.
97
+ * @param endAngle - The end angle in degrees, from 0 up to 360.
98
+ * @returns The problem, or undefined.
99
+ */
100
+ export function arcProblem(startAngle, endAngle) {
101
+ return roundsToOneAngle(startAngle, endAngle) && !isShortArc(startAngle, endAngle)
102
+ ? ARC_LOST
103
+ : undefined;
104
+ }
105
+ /**
106
+ * True for an arc so short that its angles are the same once rounded, which
107
+ * is written as an arc of no length. That is within rounding of what was
108
+ * drawn, so it is worth a warning and not an error.
109
+ *
110
+ * @param startAngle - The start angle in degrees, from 0 up to 360.
111
+ * @param endAngle - The end angle in degrees, from 0 up to 360.
112
+ * @returns Whether the arc is written with no length.
113
+ */
114
+ export function arcIsWrittenAsPoint(startAngle, endAngle) {
115
+ return roundsToOneAngle(startAngle, endAngle) && isShortArc(startAngle, endAngle);
116
+ }
117
+ /** Returns what is wrong with a single-line text value, or undefined when it is valid. */
118
+ export function textProblem(value) {
119
+ if (hasControl(value))
120
+ return "Text must be a single line with no control characters";
121
+ if (hasAstral(value)) {
122
+ return "Text cannot contain emoji or other characters above U+FFFF, because AutoCAD cannot read them from DXF";
123
+ }
124
+ if (/[\ue800-\ue8ff]/.test(value))
125
+ return TEXT_PRIVATE_USE;
126
+ return undefined;
127
+ }
128
+ /**
129
+ * Returns a warning for text that AutoCAD stores as written but draws
130
+ * differently, or undefined when it draws what it stores.
131
+ *
132
+ * @param value - The text value.
133
+ * @returns The warning, or undefined.
134
+ */
135
+ export function textWarning(value) {
136
+ return value.includes("%%") ? TEXT_PERCENT : undefined;
137
+ }
138
+ function roundsToOneAngle(startAngle, endAngle) {
139
+ return writtenAngle(startAngle) === writtenAngle(endAngle);
140
+ }
141
+ /** True when the counterclockwise sweep from start to end is half a turn or less. */
142
+ function isShortArc(startAngle, endAngle) {
143
+ return (((endAngle - startAngle) % 360) + 360) % 360 <= 180;
144
+ }
145
+ function codePoint(character) {
146
+ return `U+${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`;
147
+ }
148
+ function hasControl(value) {
149
+ for (let i = 0; i < value.length; i++) {
150
+ const code = value.charCodeAt(i);
151
+ if (code < 0x20 || code === 0x7f)
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ /** True when the string has a character above U+FFFF, which JavaScript stores as a surrogate pair. */
157
+ function hasAstral(value) {
158
+ for (let i = 0; i < value.length; i++) {
159
+ const code = value.charCodeAt(i);
160
+ if (code >= 0xd800 && code <= 0xdfff)
161
+ return true;
162
+ }
163
+ return false;
164
+ }
package/dist/svg.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { sweep } from "./drawing.js";
2
+ import { extents } from "./extents.js";
2
3
  import { fmt } from "./format.js";
4
+ import { layerKey } from "./layers.js";
3
5
  /** Screen colors for the standard ACI colors 1 to 7. Other indexes draw in currentColor. */
4
6
  const ACI = {
5
7
  1: "#ff0000",
@@ -18,10 +20,11 @@ export function toSVG(drawing, options = {}) {
18
20
  const y = -(maxY + margin);
19
21
  const w = maxX - minX + margin * 2;
20
22
  const h = maxY - minY + margin * 2;
21
- const colors = new Map(drawing.layers.map((l) => [l.name, ACI[l.color] ?? "currentColor"]));
23
+ // Keyed as AutoCAD looks layers up, so an entity on `wall` takes the color of layer `WALL`.
24
+ const colors = new Map(drawing.layers.map((l) => [layerKey(l.name), ACI[l.color] ?? "currentColor"]));
22
25
  const stroke = options.strokeWidth ?? 1;
23
26
  const body = drawing.entities
24
- .map((e) => entityToSvg(e, colors.get(e.layer) ?? "currentColor"))
27
+ .map((e) => entityToSvg(e, colors.get(layerKey(e.layer)) ?? "currentColor"))
25
28
  .join("\n ");
26
29
  return [
27
30
  `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${fmt(x)} ${fmt(y)} ${fmt(w)} ${fmt(h)}">`,
@@ -51,6 +54,11 @@ function entityToSvg(e, color) {
51
54
  const large = sweep(e.startAngle, e.endAngle) > 180 ? 1 : 0;
52
55
  const start = `${fmt(cx + e.radius * Math.cos(a0))} ${fmt(cy + e.radius * Math.sin(a0))}`;
53
56
  const end = `${fmt(cx + e.radius * Math.cos(a1))} ${fmt(cy + e.radius * Math.sin(a1))}`;
57
+ // SVG draws nothing for an arc that ends where it starts, which is where rounding can
58
+ // put the ends of an arc that is all but a full turn.
59
+ if (start === end && large === 1) {
60
+ return `<circle cx="${fmt(cx)}" cy="${fmt(cy)}" r="${fmt(e.radius)}" ${s}/>`;
61
+ }
54
62
  // sweep-flag 1 is the positive-angle direction in local (Y-up) coordinates: counterclockwise.
55
63
  return `<path d="M ${start} A ${fmt(e.radius)} ${fmt(e.radius)} 0 ${large} 1 ${end}" ${s}/>`;
56
64
  }
@@ -61,45 +69,6 @@ function entityToSvg(e, color) {
61
69
  }
62
70
  }
63
71
  }
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
72
  function rad(degrees) {
104
73
  return (degrees * Math.PI) / 180;
105
74
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdraft",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
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
  },