@senad-d/drawme 0.1.2 → 0.1.4

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/src/drawio.ts CHANGED
@@ -1,14 +1,13 @@
1
1
  /**
2
2
  * draw.io desktop CLI wrapper: binary resolution + export. Encodes the tricky
3
- * flag knowledge from the skill (preview vs final export, the vision width cap,
4
- * the `-e` PNG IEND repair, page indexing, Linux-headless quirks) so callers
5
- * never hand-build a draw.io command line. Local-only — the only process it
6
- * spawns is the draw.io CLI (and, on headless Linux, `xvfb-run`). No network.
3
+ * flag knowledge for focused previews vs final export, the vision width cap,
4
+ * `-e` PNG IEND repair, page indexing, and headless-Linux handling so callers never
5
+ * hand-build a draw.io command line.
7
6
  */
8
7
  import { execFile } from "node:child_process";
9
- import { existsSync } from "node:fs";
8
+ import { existsSync, realpathSync } from "node:fs";
10
9
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
11
- import { basename, dirname, extname, join } from "node:path";
10
+ import { basename, dirname, extname, join, resolve } from "node:path";
12
11
  import { platform, tmpdir } from "node:os";
13
12
  import { repairPng } from "./png";
14
13
 
@@ -52,7 +51,7 @@ export interface ExportPlan {
52
51
  linuxExtra: string[];
53
52
  }
54
53
 
55
- /** Candidate binary names/paths, in resolution order (matches the skill's Step 1). */
54
+ /** Candidate binary names and paths in resolution order. */
56
55
  const CANDIDATES = [
57
56
  "drawio", // Homebrew cask, jgraph .deb/.rpm, Arch AUR
58
57
  "draw.io", // older builds / custom symlinks
@@ -120,7 +119,7 @@ export function deriveOutput(input: string, format: ExportFormat, embed: boolean
120
119
  /**
121
120
  * Build the full export plan (no side effects) so the argument logic is unit-testable.
122
121
  *
123
- * Rules baked in from the skill:
122
+ * Export planning rules:
124
123
  * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
125
124
  * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
126
125
  * - `--width` and `-s` are never combined; an explicit width/height wins
@@ -164,9 +163,108 @@ export interface ExportResult {
164
163
  version?: string;
165
164
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
166
165
  repaired: boolean;
166
+ /** Superseded preview artifacts removed after this successful preview or final export. */
167
+ removedPreviews: string[];
168
+ /** Best-effort preview cleanup failures; the export itself still succeeded. */
169
+ previewCleanupWarnings: string[];
167
170
  command: string;
168
171
  }
169
172
 
173
+ /** Successful preview outputs still present, grouped by their canonical source path. */
174
+ const previewOutputs = new Map<string, Map<string, string>>();
175
+ /** Serialize exports per source so concurrent preview calls cannot leave multiple latest artifacts. */
176
+ const exportQueues = new Map<string, Promise<void>>();
177
+
178
+ function sourceKey(input: string): string {
179
+ try {
180
+ return realpathSync(input);
181
+ } catch {
182
+ return resolve(input);
183
+ }
184
+ }
185
+
186
+ interface PreviewCleanup {
187
+ removed: string[];
188
+ warnings: string[];
189
+ }
190
+
191
+ /**
192
+ * Keep the newly exported preview and retire every older tracked preview for the
193
+ * same source. Cleanup happens only after the replacement exists, so a failed
194
+ * export never destroys the last usable review image.
195
+ */
196
+ async function replaceTrackedPreview(input: string, latestOutput: string): Promise<PreviewCleanup> {
197
+ const key = sourceKey(input);
198
+ const previous = previewOutputs.get(key) ?? new Map<string, string>();
199
+ const latestPath = resolve(latestOutput);
200
+ const retained = new Map<string, string>([[latestPath, latestOutput]]);
201
+ const removed: string[] = [];
202
+ const warnings: string[] = [];
203
+
204
+ for (const [path, displayPath] of previous) {
205
+ if (path === latestPath) continue;
206
+ const existed = existsSync(path);
207
+ try {
208
+ await rm(path, { force: true });
209
+ if (existed) removed.push(displayPath);
210
+ } catch (error) {
211
+ retained.set(path, displayPath);
212
+ const message = error instanceof Error ? error.message : String(error);
213
+ warnings.push(`${displayPath}: ${message}`);
214
+ }
215
+ }
216
+
217
+ previewOutputs.set(key, retained);
218
+ return { removed, warnings };
219
+ }
220
+
221
+ async function removeTrackedPreviews(input: string, finalOutput: string): Promise<PreviewCleanup> {
222
+ const key = sourceKey(input);
223
+ const previews = previewOutputs.get(key);
224
+ if (!previews) return { removed: [], warnings: [] };
225
+
226
+ previewOutputs.delete(key);
227
+ const finalPath = resolve(finalOutput);
228
+ const removed: string[] = [];
229
+ const warnings: string[] = [];
230
+ const retry = new Map<string, string>();
231
+
232
+ for (const [path, displayPath] of previews) {
233
+ if (path === finalPath) continue;
234
+ const existed = existsSync(path);
235
+ try {
236
+ await rm(path, { force: true });
237
+ if (existed) removed.push(displayPath);
238
+ } catch (error) {
239
+ retry.set(path, displayPath);
240
+ const message = error instanceof Error ? error.message : String(error);
241
+ warnings.push(`${displayPath}: ${message}`);
242
+ }
243
+ }
244
+
245
+ if (retry.size > 0) previewOutputs.set(key, retry);
246
+ return { removed, warnings };
247
+ }
248
+
249
+ async function withSourceExportQueue<T>(input: string, action: () => Promise<T>): Promise<T> {
250
+ const key = sourceKey(input);
251
+ const previous = exportQueues.get(key) ?? Promise.resolve();
252
+ let release = (): void => {};
253
+ const current = new Promise<void>((resolveCurrent) => {
254
+ release = resolveCurrent;
255
+ });
256
+ const tail = previous.then(() => current);
257
+ exportQueues.set(key, tail);
258
+
259
+ await previous;
260
+ try {
261
+ return await action();
262
+ } finally {
263
+ release();
264
+ if (exportQueues.get(key) === tail) exportQueues.delete(key);
265
+ }
266
+ }
267
+
170
268
  function isRootUser(): boolean {
171
269
  const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
172
270
  return typeof getuid === "function" && getuid() === 0;
@@ -194,6 +292,10 @@ async function invoke(binary: string, fullArgs: string[]): Promise<string> {
194
292
  */
195
293
  export async function exportDiagram(opts: ExportOptions): Promise<ExportResult> {
196
294
  if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
295
+ return withSourceExportQueue(opts.input, () => exportDiagramQueued(opts));
296
+ }
297
+
298
+ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
197
299
  const info = await resolveBinary(opts.binary);
198
300
  if (!info.available || !info.binary) {
199
301
  throw new Error(
@@ -217,6 +319,10 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
217
319
  }
218
320
 
219
321
  const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
322
+ const cleanup =
323
+ plan.mode === "preview"
324
+ ? await replaceTrackedPreview(plan.input, plan.output)
325
+ : await removeTrackedPreviews(plan.input, plan.output);
220
326
  return {
221
327
  output: plan.output,
222
328
  format: plan.format,
@@ -225,6 +331,8 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
225
331
  binary: info.binary,
226
332
  version: info.version,
227
333
  repaired,
334
+ removedPreviews: cleanup.removed,
335
+ previewCleanupWarnings: cleanup.warnings,
228
336
  command,
229
337
  };
230
338
  }
package/src/explain.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  /**
2
- * Describe a `.drawio` as structured Markdown — a pure-TypeScript port of the
3
- * skill's `scripts/explain.py`. The inverse of authoring: it lists components
4
- * (grouped by container/swimlane/tier), the relations between them (edge labels
5
- * become the relation verb), and a per-page breakdown for multi-page files.
6
- * Handy for a README/PR summary or a text-only read-back. Local-only, no network.
2
+ * Describe a `.drawio` as structured Markdown. The inverse of authoring: it
3
+ * lists components (grouped by container/swimlane/tier), the relations between
4
+ * them (edge labels become the relation verb), and a per-page breakdown for
5
+ * multi-page files. Handy for a README/PR summary or a text-only read-back.
7
6
  */
8
7
  import { readFile } from "node:fs/promises";
9
8
  import { basename } from "node:path";
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * DrawMe — a native Pi extension that turns natural-language descriptions into
3
3
  * `.drawio` diagrams and exports them to PNG/SVG/PDF/JPG via the draw.io desktop
4
- * CLI. It exposes the skill's workflow as plain commands + tools instead of a
5
- * skill, and does zero network I/O (see the audit note in the README).
4
+ * CLI. It exposes the authoring workflow as plain commands and model-callable
5
+ * tools.
6
6
  *
7
7
  * Tools: drawio_check · drawio_export · drawio_validate · drawio_from_mermaid
8
8
  * drawio_layout · drawio_shapesearch · drawio_explain · drawio_open
@@ -12,6 +12,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
12
12
  import { Type, type Static } from "typebox";
13
13
  import { fileURLToPath } from "node:url";
14
14
  import { dirname, resolve } from "node:path";
15
+ import { readFile } from "node:fs/promises";
15
16
  import {
16
17
  applyLayout,
17
18
  convertMermaid,
@@ -53,6 +54,18 @@ export type DrawioExportInput = Static<typeof exportParams>;
53
54
 
54
55
  const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
55
56
 
57
+ async function exportResult(text: string, result: Awaited<ReturnType<typeof exportDiagram>>) {
58
+ const content: (
59
+ | { type: "text"; text: string }
60
+ | { type: "image"; data: string; mimeType: "image/png" }
61
+ )[] = [{ type: "text", text }];
62
+ if (result.mode === "preview" && result.format === "png") {
63
+ const png = await readFile(result.output);
64
+ content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
65
+ }
66
+ return { content, details: result };
67
+ }
68
+
56
69
  export default function drawme(pi: ExtensionAPI): void {
57
70
  pi.registerTool({
58
71
  name: "drawio_check",
@@ -82,17 +95,22 @@ export default function drawme(pi: ExtensionAPI): void {
82
95
  name: "drawio_export",
83
96
  label: "draw.io: export",
84
97
  description:
85
- "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. Use mode:'preview' for a clean, width-capped PNG to self-check with vision (never embedded), and mode:'final' for the deliverable (embedded editable output; the truncated -e PNG IEND chunk is auto-repaired). Runs entirely locally.",
86
- promptSnippet: "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' for self-check, mode:'final' for the deliverable).",
98
+ "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. A successful mode:'preview' PNG is clean, width-capped, never embedded, and attached to the text/metadata tool result for focused visual review. Each successful preview removes the prior preview artifact for the same source, leaving only the latest file. mode:'final' creates the deliverable (embedded editable output; truncated PNG IEND is repaired) and removes the remaining preview.",
99
+ promptSnippet:
100
+ "Export a .drawio to PNG/SVG/PDF/JPG (each mode:'preview' call attaches the latest review image and removes the previous preview file; mode:'final' creates the deliverable and cleans the remaining preview).",
87
101
  parameters: exportParams,
88
102
  async execute(_id, params) {
89
103
  try {
90
104
  const r = await exportDiagram(params as ExportOptions);
91
105
  const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed}`];
92
106
  if (r.repaired) lines.push("(repaired truncated -e PNG IEND chunk)");
107
+ if (r.removedPreviews.length > 0) lines.push(`Removed preview artifact(s): ${r.removedPreviews.join(", ")}`);
108
+ if (r.previewCleanupWarnings.length > 0) {
109
+ lines.push(`Preview cleanup warning(s): ${r.previewCleanupWarnings.join("; ")}`);
110
+ }
93
111
  const versionSuffix = r.version ? ` (${r.version})` : "";
94
112
  lines.push(`binary=${r.binary}${versionSuffix}`);
95
- return textResult(lines.join("\n"), r);
113
+ return exportResult(lines.join("\n"), r);
96
114
  } catch (e) {
97
115
  return textResult(`Export failed: ${(e as Error).message}`, { error: (e as Error).message });
98
116
  }
@@ -103,15 +121,20 @@ export default function drawme(pi: ExtensionAPI): void {
103
121
  name: "drawio_validate",
104
122
  label: "draw.io: validate",
105
123
  description:
106
- "Structurally lint a .drawio file: errors for dangling edge endpoints, duplicate/reserved ids, broken parents, and missing geometry; warnings for overlapping nodes, off-canvas shapes, and edges that route through shapes or cross each other. Deterministic and does not launch draw.io. Run before exporting.",
107
- promptSnippet: "Lint a .drawio for structural errors before exporting.",
124
+ "Structurally lint a .drawio file: errors for dangling endpoints, duplicate/reserved ids, broken parents, and missing/malformed vertex or edge geometry; actionable warnings for overlap, page/containment bounds, conservative readability defects, and explicit routes through shapes or across edges. Reports observations and a readability score. Deterministic and does not launch draw.io. Run after every source edit and before exporting.",
125
+ promptSnippet: "Lint a .drawio after every source edit and before exporting.",
108
126
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
109
127
  async execute(_id, params) {
110
128
  const r = await validateFile(params.input);
111
129
  const lines = [
112
- ...r.warnings.map((w) => `warning: ${w}`),
113
- ...r.errors.map((e) => `error: ${e}`),
114
- `${r.errors.length} error(s), ${r.warnings.length} warning(s)`,
130
+ `Errors (${r.errors.length}):`,
131
+ ...(r.errors.length > 0 ? r.errors.map((error) => `- ${error}`) : ["- none"]),
132
+ `Actionable warnings (${r.warnings.length}):`,
133
+ ...(r.warnings.length > 0 ? r.warnings.map((warning) => `- ${warning}`) : ["- none"]),
134
+ `Informational observations (${r.observations.length}):`,
135
+ ...(r.observations.length > 0 ? r.observations.map((observation) => `- ${observation}`) : ["- none"]),
136
+ `Readability score: ${r.score.total} (route-through=${r.score.through}, crossings=${r.score.crossings}, overlaps=${r.score.overlaps}; lower is better for variants of this graph)`,
137
+ `${r.errors.length} error(s), ${r.warnings.length} unresolved warning(s)`,
115
138
  ];
116
139
  return textResult(lines.join("\n"), r);
117
140
  },
@@ -178,7 +201,7 @@ export default function drawme(pi: ExtensionAPI): void {
178
201
  name: "drawio_shapesearch",
179
202
  label: "draw.io: shape search",
180
203
  description:
181
- "Find the exact official draw.io style= string for a shape by keyword (e.g. 'aws lambda', 'uml actor', 'k8s pod'). Covers 10k+ AWS/Azure/GCP/Cisco/Kubernetes/UML/BPMN/network shapes. Use this instead of guessing a style= when a diagram needs a specific vendor or notation shape. Local index, no network.",
204
+ "Find the exact official draw.io style= string for a shape by keyword (e.g. 'aws lambda', 'uml actor', 'k8s pod'). Covers 10k+ AWS/Azure/GCP/Cisco/Kubernetes/UML/BPMN/network shapes from a bundled index. Use this instead of guessing a style= when a diagram needs a specific vendor or notation shape.",
182
205
  promptSnippet: "Look up the exact official style= string for a draw.io shape by keyword.",
183
206
  parameters: Type.Object({
184
207
  query: Type.String({ description: "Keywords, e.g. 'aws lambda' or 'uml actor'" }),
@@ -196,7 +219,7 @@ export default function drawme(pi: ExtensionAPI): void {
196
219
  name: "drawio_explain",
197
220
  label: "draw.io: explain",
198
221
  description:
199
- "Describe an existing .drawio as structured Markdown (components grouped by container, relations with edge-label verbs, per page). Useful for a README/PR summary or to read a diagram back before editing. Pure-local, no draw.io CLI needed.",
222
+ "Describe an existing .drawio as structured Markdown (components grouped by container, relations with edge-label verbs, per page). Useful for a README/PR summary or to read a diagram back before editing. No draw.io CLI needed.",
200
223
  promptSnippet: "Describe an existing .drawio as Markdown (components + relations).",
201
224
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
202
225
  async execute(_id, params) {
@@ -213,7 +236,7 @@ export default function drawme(pi: ExtensionAPI): void {
213
236
  name: "drawio_open",
214
237
  label: "draw.io: open",
215
238
  description:
216
- "Open a .drawio source or an exported file in the OS default application (draw.io desktop for .drawio) so the user can fine-tune it. Local action, no network.",
239
+ "Open a .drawio source or an exported file in the OS default application (draw.io desktop for .drawio) so the user can fine-tune it.",
217
240
  promptSnippet: "Open a .drawio or exported file in the desktop app.",
218
241
  parameters: Type.Object({ path: Type.String({ description: "File to open" }) }),
219
242
  async execute(_id, params) {
package/src/png.ts CHANGED
@@ -4,11 +4,10 @@
4
4
  * draw.io's CLI emits `-e` (embedded-XML) PNGs with the 4-byte IEND length
5
5
  * field present but the trailing 8 bytes of "IEND" type + CRC missing, so strict
6
6
  * PNG decoders and vision APIs reject the file (draw.io-desktop issue #8).
7
- * SVG/PDF are unaffected. Ported 1:1 from the skill's `scripts/repair_png.py`.
7
+ * SVG/PDF are unaffected.
8
8
  *
9
9
  * Idempotent: a no-op once the file already ends with a valid IEND chunk, so it
10
- * is safe to run unconditionally after every `-e` PNG export. Local-only, no
11
- * network.
10
+ * is safe to run unconditionally after every `-e` PNG export.
12
11
  */
13
12
  import { readFile, writeFile } from "node:fs/promises";
14
13
 
@@ -1,13 +1,11 @@
1
1
  /**
2
- * Search 10k+ official draw.io shapes for their exact `style=` strings — a
3
- * pure-TypeScript port of the skill's `scripts/shapesearch.py`, over the bundled
4
- * `assets/data/shape-index.json.gz` (upstream draw.io shape data; see the notice
5
- * beside it). Resolves a keyword query (e.g. "aws lambda", "uml actor") to the
6
- * real palette style so a diagram uses the official shape instead of a guess.
7
- * Local-only, no network.
2
+ * Search 10k+ official draw.io shapes for their exact `style=` strings using the
3
+ * bundled `assets/data/shape-index.json.gz` file (upstream draw.io shape data;
4
+ * see the notice beside it). Resolves a keyword query such as "aws lambda" or
5
+ * "uml actor" to the real palette style instead of a guess.
8
6
  *
9
- * Algorithm mirrors upstream (tag map with exact + Soundex matching, strict AND
10
- * first, scored OR fallback) plus the skill's verbatim-title tiebreaker.
7
+ * Uses a tag map with exact + Soundex matching, strict AND first, a scored OR
8
+ * fallback, and a verbatim-title tiebreaker.
11
9
  */
12
10
  import { readFileSync } from "node:fs";
13
11
  import { gunzipSync } from "node:zlib";