nerdgram1337 1.7.5 → 1.8.5

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,470 @@
1
+ import {
2
+ LOCK_STALE_MS,
3
+ META_DIR_NAME,
4
+ REVISION_RETENTION,
5
+ atomicWriteJson,
6
+ atomicWriteText,
7
+ createId,
8
+ dropThumbnail,
9
+ ensureDataRoot,
10
+ evaluateWrite,
11
+ getInstanceIdentity,
12
+ getLocksRoot,
13
+ getMetaPath,
14
+ getVersionsRoot,
15
+ hashContent,
16
+ httpFail,
17
+ isProcessAlive,
18
+ normalizeRelative,
19
+ readJsonFile,
20
+ resolveSafePath,
21
+ rethrowKnownReadError,
22
+ safeStorageKey,
23
+ textFiles,
24
+ toRelativePath
25
+ } from "./chunk-7XBDBMFZ.js";
26
+ import {
27
+ invalidateDiagramLint
28
+ } from "./chunk-TDN24VZZ.js";
29
+ import {
30
+ reportUnreadable
31
+ } from "./chunk-GK3V52XM.js";
32
+
33
+ // server/src/fsStore.ts
34
+ import fs2 from "node:fs/promises";
35
+ import path4 from "node:path";
36
+
37
+ // server/src/diagramSightings.ts
38
+ import path from "node:path";
39
+ var FILE_NAME = "diagram-sightings.json";
40
+ var chain = Promise.resolve();
41
+ var depth = 0;
42
+ var suppress = 0;
43
+ function sightingsPath() {
44
+ return path.join(getMetaPath(), FILE_NAME);
45
+ }
46
+ function emptyCatalog() {
47
+ return { version: 1, updatedAt: 0, files: [], pending: [] };
48
+ }
49
+ function isPending(value) {
50
+ if (!value || typeof value !== "object") return false;
51
+ const item = value;
52
+ return typeof item.from === "string" && (item.to === null || typeof item.to === "string") && (item.match === "content" || item.match === "basename" || item.match === "ambiguous") && Array.isArray(item.candidates) && item.candidates.every((candidate) => typeof candidate === "string") && typeof item.noticedAt === "number";
53
+ }
54
+ function isSighting(value) {
55
+ if (!value || typeof value !== "object") return false;
56
+ const item = value;
57
+ return typeof item.path === "string" && typeof item.hash === "string" && typeof item.seenAt === "number" && (item.missingAt == null || typeof item.missingAt === "number");
58
+ }
59
+ function normalizeCatalog(value) {
60
+ if (!value || typeof value !== "object") return null;
61
+ const record = value;
62
+ if (record.version !== 1 || !Array.isArray(record.files) || !Array.isArray(record.pending)) return null;
63
+ if (typeof record.updatedAt !== "number") return null;
64
+ return {
65
+ version: 1,
66
+ updatedAt: record.updatedAt,
67
+ files: record.files.filter(isSighting).map((file) => ({
68
+ path: normalizeRelative(file.path),
69
+ hash: file.hash,
70
+ seenAt: file.seenAt,
71
+ ...file.missingAt != null ? { missingAt: file.missingAt } : {}
72
+ })),
73
+ pending: record.pending.filter(isPending).map((item) => ({
74
+ from: normalizeRelative(item.from),
75
+ to: item.to ? normalizeRelative(item.to) : null,
76
+ match: item.match,
77
+ candidates: item.candidates.map((candidate) => normalizeRelative(candidate)).filter(Boolean),
78
+ noticedAt: item.noticedAt
79
+ }))
80
+ };
81
+ }
82
+ async function load() {
83
+ try {
84
+ return normalizeCatalog(await readJsonFile(sightingsPath())) ?? emptyCatalog();
85
+ } catch {
86
+ return emptyCatalog();
87
+ }
88
+ }
89
+ async function save(catalog) {
90
+ const files = [...catalog.files].sort((a, b) => a.path.localeCompare(b.path));
91
+ const pending = [...catalog.pending].sort((a, b) => a.from.localeCompare(b.from));
92
+ await atomicWriteJson(sightingsPath(), { ...catalog, files, pending });
93
+ }
94
+ function exclusive(fn) {
95
+ if (depth > 0) return fn();
96
+ const run = chain.then(async () => {
97
+ depth += 1;
98
+ try {
99
+ return await fn();
100
+ } finally {
101
+ depth -= 1;
102
+ }
103
+ });
104
+ chain = run.then(
105
+ () => void 0,
106
+ () => void 0
107
+ );
108
+ return run;
109
+ }
110
+ async function noteDiagramSighting(snapshot) {
111
+ if (suppress > 0) return;
112
+ const filePath = normalizeRelative(snapshot.path);
113
+ if (!filePath || !snapshot.hash) return;
114
+ await exclusive(async () => {
115
+ if (suppress > 0) return;
116
+ const now = Date.now();
117
+ const catalog = await load();
118
+ const files = catalog.files.filter((file) => file.path !== filePath && file.missingAt == null);
119
+ files.push({ path: filePath, hash: snapshot.hash, seenAt: now });
120
+ for (const old of catalog.files) {
121
+ if (old.missingAt == null || old.path === filePath) continue;
122
+ if (!catalog.pending.some((item) => item.from === old.path)) continue;
123
+ files.push(old);
124
+ }
125
+ const pending = catalog.pending.filter((item) => item.from !== filePath);
126
+ const updatedAt = catalog.updatedAt === 0 ? now : catalog.updatedAt;
127
+ await save({ version: 1, updatedAt, files, pending });
128
+ });
129
+ }
130
+
131
+ // server/src/history.ts
132
+ import fs from "node:fs/promises";
133
+ import path2 from "node:path";
134
+ function versionDirFor(relativePath) {
135
+ return path2.join(getVersionsRoot(), safeStorageKey(relativePath));
136
+ }
137
+ function indexPath(dir) {
138
+ return path2.join(dir, "index.json");
139
+ }
140
+ async function loadIndex(dir, fallbackPath) {
141
+ const parsed = await readJsonFile(indexPath(dir));
142
+ if (!parsed || !Array.isArray(parsed.revisions)) {
143
+ return { path: fallbackPath, revisions: [] };
144
+ }
145
+ return {
146
+ path: typeof parsed.path === "string" ? parsed.path : fallbackPath,
147
+ revisions: parsed.revisions.flatMap((revision) => {
148
+ const meta = readRevisionMeta(revision);
149
+ return meta ? [meta] : [];
150
+ })
151
+ };
152
+ }
153
+ function readRevisionMeta(value) {
154
+ if (!value || typeof value !== "object") return null;
155
+ const revision = value;
156
+ if (typeof revision.id !== "string" || typeof revision.createdAt !== "string" || typeof revision.mtimeMs !== "number" || typeof revision.size !== "number" || typeof revision.hash !== "string") {
157
+ return null;
158
+ }
159
+ const meta = {
160
+ id: revision.id,
161
+ createdAt: revision.createdAt,
162
+ mtimeMs: revision.mtimeMs,
163
+ size: revision.size,
164
+ hash: revision.hash
165
+ };
166
+ if (typeof revision.name === "string" && revision.name.trim()) meta.name = revision.name;
167
+ if (typeof revision.note === "string" && revision.note.trim()) meta.note = revision.note;
168
+ if (typeof revision.namedAt === "string" && revision.namedAt.trim()) meta.namedAt = revision.namedAt;
169
+ return meta;
170
+ }
171
+ function isNamedRevision(revision) {
172
+ return typeof revision.name === "string" && revision.name.trim().length > 0;
173
+ }
174
+ async function saveIndex(dir, index) {
175
+ await atomicWriteJson(indexPath(dir), index);
176
+ }
177
+ async function prune(dir, index) {
178
+ const named = index.revisions.filter((revision) => isNamedRevision(revision));
179
+ const unnamed = index.revisions.filter((revision) => !isNamedRevision(revision));
180
+ unnamed.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
181
+ while (unnamed.length > REVISION_RETENTION) {
182
+ const dropped = unnamed.shift();
183
+ if (!dropped) break;
184
+ await fs.rm(path2.join(dir, `${dropped.id}.mmd`), { force: true });
185
+ }
186
+ index.revisions = [...named, ...unnamed];
187
+ }
188
+ async function snapshotPrevious(relativePath, previous) {
189
+ const normalized = normalizeRelative(relativePath);
190
+ const dir = versionDirFor(normalized);
191
+ await fs.mkdir(dir, { recursive: true });
192
+ const index = await loadIndex(dir, normalized);
193
+ const id = createId();
194
+ await atomicWriteText(path2.join(dir, `${id}.mmd`), previous.content);
195
+ index.path = normalized;
196
+ index.revisions.push({
197
+ id,
198
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
199
+ mtimeMs: previous.mtimeMs,
200
+ size: previous.size,
201
+ hash: previous.hash
202
+ });
203
+ await prune(dir, index);
204
+ await saveIndex(dir, index);
205
+ return id;
206
+ }
207
+
208
+ // server/src/locks.ts
209
+ import path3 from "node:path";
210
+ var SAME_INSTANCE_MESSAGE = "This diagram is open in another window.";
211
+ function lockStorageKey(relativePath) {
212
+ return safeStorageKey(relativePath, ".json");
213
+ }
214
+ function lockFile(relativePath) {
215
+ return path3.join(getLocksRoot(), `${lockStorageKey(relativePath)}.json`);
216
+ }
217
+ function optionalText(value) {
218
+ if (typeof value !== "string") return void 0;
219
+ const trimmed = value.trim();
220
+ return trimmed || void 0;
221
+ }
222
+ function isLockRecord(value) {
223
+ if (!value || typeof value !== "object") return false;
224
+ const record = value;
225
+ return typeof record.path === "string" && typeof record.token === "string" && typeof record.sessionId === "string" && typeof record.pid === "number" && typeof record.acquiredAt === "string" && typeof record.heartbeatAt === "string";
226
+ }
227
+ function normalizeLock(record) {
228
+ const instanceId = optionalText(record.instanceId);
229
+ const instanceName = optionalText(record.instanceName);
230
+ const hostname = optionalText(record.hostname);
231
+ return {
232
+ path: record.path,
233
+ token: record.token,
234
+ sessionId: record.sessionId,
235
+ pid: record.pid,
236
+ acquiredAt: record.acquiredAt,
237
+ heartbeatAt: record.heartbeatAt,
238
+ ...instanceId ? { instanceId } : {},
239
+ ...instanceName ? { instanceName } : {},
240
+ ...hostname ? { hostname } : {}
241
+ };
242
+ }
243
+ function lockIsStale(record, now = Date.now(), instanceId) {
244
+ const heartbeat = Date.parse(record.heartbeatAt);
245
+ if (!Number.isFinite(heartbeat) || now - heartbeat > LOCK_STALE_MS) return true;
246
+ const legacy = !optionalText(record.instanceId);
247
+ const sameInstance2 = Boolean(instanceId) && record.instanceId === instanceId;
248
+ if ((sameInstance2 || legacy) && record.pid !== process.pid && !isProcessAlive(record.pid)) return true;
249
+ return false;
250
+ }
251
+ function sameInstance(record, identity) {
252
+ return !optionalText(record.instanceId) || record.instanceId === identity.instanceId;
253
+ }
254
+ function diagramLabel(relativePath) {
255
+ const base = relativePath.split("/").pop() || relativePath;
256
+ return base.replace(/\.mmd$/i, "") || base;
257
+ }
258
+ function formatLockSince(iso) {
259
+ const date = new Date(iso);
260
+ if (Number.isNaN(date.getTime())) return iso;
261
+ return new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit" }).format(date);
262
+ }
263
+ function lockedMessage(record, identity) {
264
+ if (sameInstance(record, identity)) return SAME_INSTANCE_MESSAGE;
265
+ const name = record.instanceName || record.hostname || "another instance";
266
+ const host = record.hostname && record.instanceName && record.hostname !== record.instanceName ? ` (${record.hostname})` : "";
267
+ return `${diagramLabel(record.path)} is open on ${name}${host} since ${formatLockSince(record.acquiredAt)}. Try again when it's closed.`;
268
+ }
269
+ async function readLock(relativePath) {
270
+ const parsed = await readJsonFile(lockFile(relativePath));
271
+ if (!isLockRecord(parsed)) return null;
272
+ const record = normalizeLock(parsed);
273
+ const identity = await getInstanceIdentity();
274
+ return { ...record, stale: lockIsStale(record, Date.now(), identity.instanceId) };
275
+ }
276
+ function holderDetails(record, identity) {
277
+ return {
278
+ acquiredAt: record.acquiredAt,
279
+ heartbeatAt: record.heartbeatAt,
280
+ staleAfterMs: LOCK_STALE_MS,
281
+ instanceId: record.instanceId ?? null,
282
+ instanceName: record.instanceName ?? null,
283
+ hostname: record.hostname ?? null,
284
+ sameInstance: sameInstance(record, identity)
285
+ };
286
+ }
287
+ async function lockedError(record) {
288
+ const identity = await getInstanceIdentity();
289
+ return httpFail(423, lockedMessage(record, identity), "locked", {
290
+ lock: holderDetails(record, identity)
291
+ });
292
+ }
293
+ async function assertWriteAllowed(relativePath, token) {
294
+ const existing = await readLock(relativePath);
295
+ if (!existing || existing.stale) return;
296
+ if (token && existing.token === token) return;
297
+ throw await lockedError(existing);
298
+ }
299
+
300
+ // server/src/fsStore.ts
301
+ var DIAGRAM_EXT = ".mmd";
302
+ function isDiagramFile(name) {
303
+ return name.toLowerCase().endsWith(DIAGRAM_EXT);
304
+ }
305
+ async function readDirSafe(dir) {
306
+ try {
307
+ return await fs2.readdir(dir);
308
+ } catch (err) {
309
+ const code = err.code;
310
+ if (code === "ENOENT") return [];
311
+ throw err;
312
+ }
313
+ }
314
+ async function buildTree(relativePath = "") {
315
+ ensureDataRoot();
316
+ const abs = resolveSafePath(relativePath || ".");
317
+ const entries = await readDirSafe(abs);
318
+ const nodes = [];
319
+ for (const name of entries) {
320
+ if (name === META_DIR_NAME || name.startsWith(".")) continue;
321
+ const childAbs = path4.join(abs, name);
322
+ const stat = await fs2.stat(childAbs);
323
+ const rel = toRelativePath(childAbs);
324
+ if (stat.isDirectory()) {
325
+ nodes.push({
326
+ name,
327
+ path: rel,
328
+ type: "folder",
329
+ mtimeMs: stat.mtimeMs,
330
+ children: await buildTree(rel)
331
+ });
332
+ } else if (stat.isFile() && isDiagramFile(name)) {
333
+ nodes.push({
334
+ name,
335
+ path: rel,
336
+ type: "file",
337
+ mtimeMs: stat.mtimeMs,
338
+ size: stat.size
339
+ });
340
+ }
341
+ }
342
+ nodes.sort((a, b) => {
343
+ if (a.type !== b.type) return a.type === "folder" ? -1 : 1;
344
+ return a.name.localeCompare(b.name, void 0, { sensitivity: "base" });
345
+ });
346
+ return nodes;
347
+ }
348
+ function skippedUnreadable(filePath, err) {
349
+ if (!err || typeof err !== "object") return null;
350
+ const status = "status" in err ? err.status : void 0;
351
+ const code = "code" in err ? String(err.code ?? "") : "";
352
+ const errno = err.code;
353
+ const skip = status === 500 && code === "unreadable" || status === 404 || code === "not_found" || errno === "EACCES" || errno === "EPERM" || errno === "EIO" || errno === "EBUSY" || errno === "ETIMEDOUT" || errno === "ENOENT";
354
+ if (!skip) return null;
355
+ return reportUnreadable(filePath, err);
356
+ }
357
+ async function readDisk(abs) {
358
+ try {
359
+ const stat = await fs2.stat(abs);
360
+ if (!stat.isFile()) throw httpFail(400, "Not a diagram file", "invalid");
361
+ const content = await textFiles.read(abs);
362
+ return {
363
+ exists: true,
364
+ content,
365
+ mtimeMs: stat.mtimeMs,
366
+ size: stat.size,
367
+ hash: hashContent(content)
368
+ };
369
+ } catch (err) {
370
+ if (err && typeof err === "object" && "status" in err) throw err;
371
+ const code = err.code;
372
+ if (code === "ENOENT") return { exists: false };
373
+ rethrowKnownReadError(path4.basename(abs), err);
374
+ throw err;
375
+ }
376
+ }
377
+ function requireDiagram(relativePath) {
378
+ const normalized = normalizeRelative(relativePath);
379
+ if (!isDiagramFile(normalized)) {
380
+ throw httpFail(400, "Only .mmd diagram files are supported", "invalid");
381
+ }
382
+ return normalized;
383
+ }
384
+ async function readFile(relativePath) {
385
+ const normalized = requireDiagram(relativePath);
386
+ const abs = resolveSafePath(normalized);
387
+ const disk = await readDisk(abs);
388
+ if (!disk.exists) throw httpFail(404, "Not found", "not_found");
389
+ return {
390
+ path: toRelativePath(abs),
391
+ name: path4.basename(abs),
392
+ content: disk.content,
393
+ mtimeMs: disk.mtimeMs,
394
+ size: disk.size,
395
+ hash: disk.hash
396
+ };
397
+ }
398
+ async function writeFile(relativePath, content, options = {}) {
399
+ const normalized = requireDiagram(relativePath);
400
+ const abs = resolveSafePath(normalized);
401
+ const relative = toRelativePath(abs);
402
+ await assertWriteAllowed(relative, options.lockToken);
403
+ const disk = await readDisk(abs);
404
+ const decision = evaluateWrite(disk, { ...options, content });
405
+ if (decision.action === "reject") {
406
+ if (decision.code === "missing") {
407
+ throw httpFail(409, "This diagram is no longer on disk.", "missing");
408
+ }
409
+ if (decision.code === "exists") {
410
+ throw httpFail(
411
+ 409,
412
+ "A diagram already exists at that path. Choose a different name.",
413
+ "exists",
414
+ { path: relative }
415
+ );
416
+ }
417
+ if (!disk.exists) throw httpFail(409, "This diagram changed on disk.", "conflict");
418
+ throw httpFail(409, "This diagram changed on disk since it was last loaded.", "conflict", {
419
+ current: {
420
+ path: relative,
421
+ content: disk.content,
422
+ mtimeMs: disk.mtimeMs,
423
+ size: disk.size,
424
+ hash: disk.hash
425
+ }
426
+ });
427
+ }
428
+ if (decision.action === "unchanged" && disk.exists) {
429
+ await noteDiagramSighting({ path: relative, hash: disk.hash });
430
+ return {
431
+ path: relative,
432
+ mtimeMs: disk.mtimeMs,
433
+ size: disk.size,
434
+ hash: disk.hash,
435
+ unchanged: true
436
+ };
437
+ }
438
+ let revisionId;
439
+ if (decision.action === "overwrite" && disk.exists) {
440
+ revisionId = await snapshotPrevious(relative, disk);
441
+ }
442
+ await fs2.mkdir(path4.dirname(abs), { recursive: true });
443
+ await atomicWriteText(abs, content);
444
+ await dropThumbnail(relative);
445
+ const stat = await fs2.stat(abs);
446
+ const search = await import("./chunk-46CLFN4M.js");
447
+ await search.rememberSearchEntry(relative, content, stat.mtimeMs, stat.size);
448
+ await noteDiagramSighting({ path: relative, hash: hashContent(content) });
449
+ noteSync({ kind: "content", summary: `Update ${relative}` });
450
+ invalidateDiagramLint([relative]);
451
+ return {
452
+ path: relative,
453
+ mtimeMs: stat.mtimeMs,
454
+ size: stat.size,
455
+ hash: hashContent(content),
456
+ revisionId
457
+ };
458
+ }
459
+ function noteSync(change) {
460
+ void import("./chunk-GD2NZSZO.js").then((mod) => mod.noteLocalChange(change)).catch(() => {
461
+ console.error("GitHub sync could not record a local change");
462
+ });
463
+ }
464
+
465
+ export {
466
+ buildTree,
467
+ skippedUnreadable,
468
+ readFile,
469
+ writeFile
470
+ };
@@ -0,0 +1,12 @@
1
+ import {
2
+ lintDiagramSource,
3
+ mermaidSyntaxDiagnostic
4
+ } from "./chunk-M4HT24R6.js";
5
+ import "./chunk-WCRNLGMN.js";
6
+ import "./chunk-BW6ANOTX.js";
7
+ import "./chunk-6LCHDAAN.js";
8
+ import "./chunk-MLKGABMK.js";
9
+ export {
10
+ lintDiagramSource,
11
+ mermaidSyntaxDiagnostic
12
+ };
@@ -1,11 +1,21 @@
1
- import "./chunk-5IHMGYXV.js";
2
- import "./chunk-6ELR2KYA.js";
1
+ import "./chunk-TVIG7AQK.js";
2
+ import "./chunk-DHVVDJDI.js";
3
3
  import {
4
4
  ensureDataRoot,
5
5
  getMetaPath,
6
- httpFail,
6
+ httpFail
7
+ } from "./chunk-7XBDBMFZ.js";
8
+ import "./chunk-TDN24VZZ.js";
9
+ import {
10
+ warnUnreadable
11
+ } from "./chunk-GK3V52XM.js";
12
+ import "./chunk-M4HT24R6.js";
13
+ import "./chunk-WCRNLGMN.js";
14
+ import "./chunk-WYQ4QDCF.js";
15
+ import "./chunk-ARL7TA3D.js";
16
+ import {
7
17
  isDataFileName
8
- } from "./chunk-KA5X3YY6.js";
18
+ } from "./chunk-M63FV47T.js";
9
19
  import "./chunk-BW6ANOTX.js";
10
20
  import "./chunk-6LCHDAAN.js";
11
21
  import "./chunk-MLKGABMK.js";
@@ -97,12 +107,15 @@ function isSyncedFile(relativePath) {
97
107
  function isBoilerplate(relativePath) {
98
108
  return BOILERPLATE.has(relativePath);
99
109
  }
100
- async function listUserFiles(root) {
101
- const out = /* @__PURE__ */ new Map();
102
- await walkUserFiles(root, root, out);
103
- return out;
110
+ async function listUserFilesDetailed(root) {
111
+ const files = /* @__PURE__ */ new Map();
112
+ const unreadable = [];
113
+ await walkUserFiles(root, root, files, unreadable);
114
+ warnUnreadable(unreadable);
115
+ return { files, unreadable };
104
116
  }
105
- async function walkUserFiles(root, dir, out) {
117
+ var READ_SKIP = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EIO", "EBUSY", "ETIMEDOUT", "ENOENT"]);
118
+ async function walkUserFiles(root, dir, out, unreadable) {
106
119
  let entries;
107
120
  try {
108
121
  entries = await fs.readdir(dir, { withFileTypes: true });
@@ -115,13 +128,19 @@ async function walkUserFiles(root, dir, out) {
115
128
  if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
116
129
  const abs = path.join(dir, entry.name);
117
130
  if (entry.isDirectory()) {
118
- await walkUserFiles(root, abs, out);
131
+ await walkUserFiles(root, abs, out, unreadable);
119
132
  continue;
120
133
  }
121
134
  if (!entry.isFile()) continue;
122
135
  const rel = path.relative(root, abs).split(path.sep).join("/");
123
136
  if (!isSyncedFile(rel)) continue;
124
- out.set(rel, await fs.readFile(abs, "utf8"));
137
+ try {
138
+ out.set(rel, await fs.readFile(abs, "utf8"));
139
+ } catch (err) {
140
+ const code = err.code ?? "";
141
+ if (!READ_SKIP.has(code)) throw err;
142
+ unreadable.push({ path: rel, code });
143
+ }
125
144
  }
126
145
  }
127
146
  async function writePrivateFile(file, content) {
@@ -784,7 +803,9 @@ async function ensureBoilerplate(dir) {
784
803
  await writeIfChanged(path2.join(dir, ".gitattributes"), GITATTRIBUTES);
785
804
  }
786
805
  async function copyDataToMirror(dataRoot, dir) {
787
- const desired = await listUserFiles(dataRoot);
806
+ const listed = await listUserFilesDetailed(dataRoot);
807
+ const desired = listed.files;
808
+ const preserve = new Set(listed.unreadable.map((item) => item.path));
788
809
  await ensureBoilerplate(dir);
789
810
  const changed = [];
790
811
  for (const [rel, content] of desired) {
@@ -795,7 +816,7 @@ async function copyDataToMirror(dataRoot, dir) {
795
816
  await fsp.writeFile(abs, content, "utf8");
796
817
  changed.push(rel);
797
818
  }
798
- await deleteExtra(dir, dir, desired);
819
+ await deleteExtra(dir, dir, desired, preserve);
799
820
  return changed;
800
821
  }
801
822
  async function commitMirror(dir, message, parents) {
@@ -968,7 +989,7 @@ async function writeIfChanged(file, content) {
968
989
  await fsp.mkdir(path2.dirname(file), { recursive: true });
969
990
  await fsp.writeFile(file, content, "utf8");
970
991
  }
971
- async function deleteExtra(mirror, dir, desired) {
992
+ async function deleteExtra(mirror, dir, desired, preserve) {
972
993
  let entries;
973
994
  try {
974
995
  entries = await fsp.readdir(dir, { withFileTypes: true });
@@ -986,12 +1007,12 @@ async function deleteExtra(mirror, dir, desired) {
986
1007
  await fsp.rm(abs, { recursive: true, force: true });
987
1008
  continue;
988
1009
  }
989
- await deleteExtra(mirror, abs, desired);
1010
+ await deleteExtra(mirror, abs, desired, preserve);
990
1011
  const left = await fsp.readdir(abs).catch(() => ["keep"]);
991
1012
  if (left.length === 0) await fsp.rmdir(abs).catch(() => void 0);
992
1013
  continue;
993
1014
  }
994
- if (isBoilerplate(rel)) continue;
1015
+ if (isBoilerplate(rel) || preserve.has(rel)) continue;
995
1016
  if (entry.name.startsWith(".") || !isSyncedFile(rel) || !desired.has(rel)) {
996
1017
  await fsp.rm(abs, { force: true });
997
1018
  }
@@ -1229,9 +1250,10 @@ async function copyWouldChange() {
1229
1250
  } catch {
1230
1251
  return false;
1231
1252
  }
1232
- const desired = await listUserFiles(ensureDataRoot());
1253
+ const listed = await listUserFilesDetailed(ensureDataRoot());
1233
1254
  const committed = await readUserFilesAt(mirror, "HEAD");
1234
- return !mapsEqual(desired, committed);
1255
+ for (const item of listed.unreadable) committed.delete(item.path);
1256
+ return !mapsEqual(listed.files, committed);
1235
1257
  }
1236
1258
  function mapsEqual(left, right) {
1237
1259
  if (left.size !== right.size) return false;
@@ -0,0 +1,87 @@
1
+ import {
2
+ EXPORTER_INFRA,
3
+ assertExporterModule,
4
+ exporterBasenames,
5
+ exporterById,
6
+ exporterDirectory,
7
+ installedExporters,
8
+ listExporterInfo,
9
+ loadExporters,
10
+ loadedExporterIds,
11
+ runExport
12
+ } from "./chunk-KIK3WXJL.js";
13
+ import {
14
+ labelFromPath,
15
+ parseNetworkDocument,
16
+ readDiagramNetwork
17
+ } from "./chunk-WYQ4QDCF.js";
18
+ import {
19
+ EXPORT_MAX_DEVICES,
20
+ EXPORT_MAX_INPUT_BYTES,
21
+ EXPORT_MAX_LINKS,
22
+ assertExportInputSize,
23
+ exporterFail,
24
+ isRecord,
25
+ mappingRowsFromUnknown
26
+ } from "./chunk-ARL7TA3D.js";
27
+ import "./chunk-M63FV47T.js";
28
+ import "./chunk-BW6ANOTX.js";
29
+ import "./chunk-6LCHDAAN.js";
30
+ import "./chunk-MLKGABMK.js";
31
+
32
+ // server/src/exporters/request.ts
33
+ function own(record, key) {
34
+ return Object.prototype.hasOwnProperty.call(record, key);
35
+ }
36
+ async function prepareExport(options) {
37
+ assertExportInputSize(options.bytes);
38
+ const record = isRecord(options.body) ? options.body : null;
39
+ let label = "nerdgram";
40
+ let mapping = null;
41
+ let mappingDocument = null;
42
+ if (record && own(record, "mapping")) {
43
+ if (Array.isArray(record.mapping)) mapping = mappingRowsFromUnknown(record.mapping);
44
+ else mappingDocument = record.mapping;
45
+ }
46
+ if (record && typeof record.label === "string" && record.label.trim()) label = record.label.trim();
47
+ let document;
48
+ if (record && typeof record.path === "string" && record.path.trim()) {
49
+ const filePath = record.path.trim();
50
+ if (!options.readText) throw exporterFail(400, "path is only valid for a workspace file.");
51
+ if (filePath.toLowerCase().endsWith(".mmd")) {
52
+ const loaded = await readDiagramNetwork(filePath, options.readText);
53
+ document = loaded.document;
54
+ label = loaded.label;
55
+ } else if (filePath.toLowerCase().endsWith(".network.json")) {
56
+ const text = await options.readText(filePath).catch(() => {
57
+ throw exporterFail(400, `Could not read ${filePath}.`);
58
+ });
59
+ document = parseNetworkDocument(text);
60
+ label = labelFromPath(filePath);
61
+ } else {
62
+ throw exporterFail(400, "path must be a diagram or a .network.json file.");
63
+ }
64
+ } else if (record && own(record, "input")) {
65
+ document = parseNetworkDocument(JSON.stringify(record.input));
66
+ } else {
67
+ document = parseNetworkDocument(JSON.stringify(options.body));
68
+ }
69
+ return runExport(options.target, document, { label, mapping }, mappingDocument);
70
+ }
71
+ export {
72
+ EXPORTER_INFRA,
73
+ EXPORT_MAX_DEVICES,
74
+ EXPORT_MAX_INPUT_BYTES,
75
+ EXPORT_MAX_LINKS,
76
+ assertExportInputSize,
77
+ assertExporterModule,
78
+ exporterBasenames,
79
+ exporterById,
80
+ exporterDirectory,
81
+ installedExporters,
82
+ listExporterInfo,
83
+ loadExporters,
84
+ loadedExporterIds,
85
+ prepareExport,
86
+ runExport
87
+ };