nerdgram1337 1.6.1 → 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.
@@ -1,12 +1,49 @@
1
1
  // server/src/diagramLinks.ts
2
2
  var DIAGRAM_SCHEME = /^(nerdgram|diagram):/i;
3
3
  var ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
4
+ var SAFE_HTTP = /^https?:$/i;
4
5
  function isDiagramLink(url) {
5
6
  if (!url || url.startsWith("//")) return false;
6
7
  if (ANY_SCHEME.test(url) && !DIAGRAM_SCHEME.test(url)) return false;
7
8
  const pathPart = url.split(/[?#]/)[0] ?? "";
8
9
  return DIAGRAM_SCHEME.test(url) || /\.mmd$/i.test(pathPart) || pathPart.startsWith("./") || pathPart.includes("/");
9
10
  }
11
+ function hasControlCharacter(value) {
12
+ for (let index = 0; index < value.length; index += 1) {
13
+ const code = value.charCodeAt(index);
14
+ if (code < 32 || code === 127) return true;
15
+ }
16
+ return false;
17
+ }
18
+ function clickTargetKind(raw) {
19
+ const url = raw.trim();
20
+ if (!url) return "none";
21
+ if (url.startsWith("//") || hasControlCharacter(url)) return "unsafe";
22
+ const squashed = url.replace(/[\u0000-\u0020]+/g, "").toLowerCase();
23
+ if (squashed.startsWith("javascript:") || squashed.startsWith("vbscript:") || squashed.startsWith("data:")) {
24
+ return "unsafe";
25
+ }
26
+ if (DIAGRAM_SCHEME.test(url)) return "diagram";
27
+ const scheme = ANY_SCHEME.exec(url);
28
+ if (scheme) {
29
+ const safe = safeHttpUrl(url);
30
+ return safe ? "external" : "unsafe";
31
+ }
32
+ return isDiagramLink(url) ? "diagram" : "none";
33
+ }
34
+ function safeHttpUrl(raw) {
35
+ const trimmed = raw.trim();
36
+ if (!trimmed || hasControlCharacter(trimmed) || trimmed.startsWith("//")) return null;
37
+ let parsed;
38
+ try {
39
+ parsed = new URL(trimmed);
40
+ } catch {
41
+ return null;
42
+ }
43
+ if (!SAFE_HTTP.test(parsed.protocol)) return null;
44
+ if (parsed.username || parsed.password) return null;
45
+ return parsed.toString();
46
+ }
10
47
  function parentPath(filePath) {
11
48
  const parts = filePath.replace(/\\/g, "/").split("/").filter(Boolean);
12
49
  parts.pop();
@@ -84,6 +121,7 @@ function parseClickLine(line, lineStart, lineNo) {
84
121
 
85
122
  export {
86
123
  isDiagramLink,
124
+ clickTargetKind,
87
125
  resolveDiagramTarget,
88
126
  diagramTargetExists,
89
127
  parseClickLine
@@ -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,12 +1,24 @@
1
- import "./chunk-JL7RYIQE.js";
1
+ import "./chunk-TVIG7AQK.js";
2
+ import "./chunk-DHVVDJDI.js";
2
3
  import {
3
4
  ensureDataRoot,
4
5
  getMetaPath,
5
- 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 {
6
17
  isDataFileName
7
- } from "./chunk-KA5X3YY6.js";
8
- import "./chunk-5C6VO4LC.js";
18
+ } from "./chunk-M63FV47T.js";
19
+ import "./chunk-BW6ANOTX.js";
9
20
  import "./chunk-6LCHDAAN.js";
21
+ import "./chunk-MLKGABMK.js";
10
22
 
11
23
  // server/src/sync/engine.ts
12
24
  import fsp2 from "node:fs/promises";
@@ -95,12 +107,15 @@ function isSyncedFile(relativePath) {
95
107
  function isBoilerplate(relativePath) {
96
108
  return BOILERPLATE.has(relativePath);
97
109
  }
98
- async function listUserFiles(root) {
99
- const out = /* @__PURE__ */ new Map();
100
- await walkUserFiles(root, root, out);
101
- 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 };
102
116
  }
103
- 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) {
104
119
  let entries;
105
120
  try {
106
121
  entries = await fs.readdir(dir, { withFileTypes: true });
@@ -113,13 +128,19 @@ async function walkUserFiles(root, dir, out) {
113
128
  if (entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
114
129
  const abs = path.join(dir, entry.name);
115
130
  if (entry.isDirectory()) {
116
- await walkUserFiles(root, abs, out);
131
+ await walkUserFiles(root, abs, out, unreadable);
117
132
  continue;
118
133
  }
119
134
  if (!entry.isFile()) continue;
120
135
  const rel = path.relative(root, abs).split(path.sep).join("/");
121
136
  if (!isSyncedFile(rel)) continue;
122
- 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
+ }
123
144
  }
124
145
  }
125
146
  async function writePrivateFile(file, content) {
@@ -782,7 +803,9 @@ async function ensureBoilerplate(dir) {
782
803
  await writeIfChanged(path2.join(dir, ".gitattributes"), GITATTRIBUTES);
783
804
  }
784
805
  async function copyDataToMirror(dataRoot, dir) {
785
- 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));
786
809
  await ensureBoilerplate(dir);
787
810
  const changed = [];
788
811
  for (const [rel, content] of desired) {
@@ -793,7 +816,7 @@ async function copyDataToMirror(dataRoot, dir) {
793
816
  await fsp.writeFile(abs, content, "utf8");
794
817
  changed.push(rel);
795
818
  }
796
- await deleteExtra(dir, dir, desired);
819
+ await deleteExtra(dir, dir, desired, preserve);
797
820
  return changed;
798
821
  }
799
822
  async function commitMirror(dir, message, parents) {
@@ -966,7 +989,7 @@ async function writeIfChanged(file, content) {
966
989
  await fsp.mkdir(path2.dirname(file), { recursive: true });
967
990
  await fsp.writeFile(file, content, "utf8");
968
991
  }
969
- async function deleteExtra(mirror, dir, desired) {
992
+ async function deleteExtra(mirror, dir, desired, preserve) {
970
993
  let entries;
971
994
  try {
972
995
  entries = await fsp.readdir(dir, { withFileTypes: true });
@@ -984,12 +1007,12 @@ async function deleteExtra(mirror, dir, desired) {
984
1007
  await fsp.rm(abs, { recursive: true, force: true });
985
1008
  continue;
986
1009
  }
987
- await deleteExtra(mirror, abs, desired);
1010
+ await deleteExtra(mirror, abs, desired, preserve);
988
1011
  const left = await fsp.readdir(abs).catch(() => ["keep"]);
989
1012
  if (left.length === 0) await fsp.rmdir(abs).catch(() => void 0);
990
1013
  continue;
991
1014
  }
992
- if (isBoilerplate(rel)) continue;
1015
+ if (isBoilerplate(rel) || preserve.has(rel)) continue;
993
1016
  if (entry.name.startsWith(".") || !isSyncedFile(rel) || !desired.has(rel)) {
994
1017
  await fsp.rm(abs, { force: true });
995
1018
  }
@@ -1227,9 +1250,10 @@ async function copyWouldChange() {
1227
1250
  } catch {
1228
1251
  return false;
1229
1252
  }
1230
- const desired = await listUserFiles(ensureDataRoot());
1253
+ const listed = await listUserFilesDetailed(ensureDataRoot());
1231
1254
  const committed = await readUserFilesAt(mirror, "HEAD");
1232
- return !mapsEqual(desired, committed);
1255
+ for (const item of listed.unreadable) committed.delete(item.path);
1256
+ return !mapsEqual(listed.files, committed);
1233
1257
  }
1234
1258
  function mapsEqual(left, right) {
1235
1259
  if (left.size !== right.size) return false;