@open-slide/core 2.0.0-beta.6 → 2.0.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,895 @@
1
+ import path from "node:path";
2
+ import { spawn } from "node:child_process";
3
+ import fs from "node:fs/promises";
4
+ import { parse } from "@babel/parser";
5
+ import { randomUUID } from "node:crypto";
6
+ //#region src/http/request-guard.ts
7
+ function headerValue(req, name) {
8
+ const raw = req.headers[name.toLowerCase()];
9
+ return (Array.isArray(raw) ? raw[0] : raw)?.trim() ?? null;
10
+ }
11
+ function firstCommaToken(value) {
12
+ if (!value) return null;
13
+ const [first] = value.split(",", 1);
14
+ return first?.trim() || null;
15
+ }
16
+ function requestProto(req) {
17
+ const forwarded = firstCommaToken(headerValue(req, "x-forwarded-proto"))?.toLowerCase();
18
+ if (forwarded === "http" || forwarded === "https") return forwarded;
19
+ return "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
20
+ }
21
+ function normalizedOrigin(origin) {
22
+ try {
23
+ const url = new URL(origin);
24
+ return `${url.protocol}//${url.host}`.toLowerCase();
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ function validateMutationRequest(req, opts = {}) {
30
+ if (opts.requireJsonBody) {
31
+ if (!(headerValue(req, "content-type")?.toLowerCase())?.startsWith("application/json")) return {
32
+ ok: false,
33
+ status: 415,
34
+ error: "content-type must be application/json"
35
+ };
36
+ }
37
+ if (firstCommaToken(headerValue(req, "sec-fetch-site"))?.toLowerCase() === "cross-site") return {
38
+ ok: false,
39
+ status: 403,
40
+ error: "cross-site request blocked"
41
+ };
42
+ const originRaw = headerValue(req, "origin");
43
+ if (!originRaw) return { ok: true };
44
+ if (originRaw.toLowerCase() === "null") return {
45
+ ok: false,
46
+ status: 403,
47
+ error: "opaque origin is not allowed"
48
+ };
49
+ const actualOrigin = normalizedOrigin(originRaw);
50
+ if (!actualOrigin) return {
51
+ ok: false,
52
+ status: 403,
53
+ error: "invalid origin header"
54
+ };
55
+ const host = firstCommaToken(headerValue(req, "x-forwarded-host")) ?? headerValue(req, "host");
56
+ if (!host) return {
57
+ ok: false,
58
+ status: 400,
59
+ error: "missing host header"
60
+ };
61
+ if (actualOrigin !== `${requestProto(req)}://${host}`.toLowerCase()) return {
62
+ ok: false,
63
+ status: 403,
64
+ error: "origin mismatch"
65
+ };
66
+ return { ok: true };
67
+ }
68
+ //#endregion
69
+ //#region src/editing/slide-ops.ts
70
+ const SLIDE_ID_RE = /^[a-z0-9_-]+$/i;
71
+ function validateSlideName(v) {
72
+ if (typeof v !== "string") return null;
73
+ const trimmed = v.trim();
74
+ if (trimmed.length < 1 || trimmed.length > 80) return null;
75
+ return trimmed;
76
+ }
77
+ function unwrapExpression(node) {
78
+ let current = node;
79
+ while (current && (current.type === "TSAsExpression" || current.type === "TSSatisfiesExpression")) current = current.expression;
80
+ return current;
81
+ }
82
+ function readMetaTitleInSource(source) {
83
+ let ast;
84
+ try {
85
+ ast = parse(source, {
86
+ sourceType: "module",
87
+ plugins: ["typescript", "jsx"],
88
+ errorRecovery: true
89
+ });
90
+ } catch {
91
+ return { kind: "unsupported" };
92
+ }
93
+ const body = ast.program?.body ?? [];
94
+ for (const stmt of body) {
95
+ if (stmt.type !== "ExportNamedDeclaration") continue;
96
+ const decl = stmt.declaration;
97
+ if (decl?.type !== "VariableDeclaration") continue;
98
+ const declarations = decl.declarations ?? [];
99
+ for (const d of declarations) {
100
+ const id = d.id;
101
+ if (id?.type !== "Identifier" || id.name !== "meta") continue;
102
+ const init = unwrapExpression(d.init);
103
+ if (init?.type !== "ObjectExpression") return { kind: "unsupported" };
104
+ const properties = init.properties ?? [];
105
+ for (const property of properties) {
106
+ if (property.type !== "ObjectProperty" || property.computed) continue;
107
+ const key = property.key;
108
+ if ((key?.type === "Identifier" ? key.name : key?.type === "StringLiteral" ? key.value : void 0) !== "title") continue;
109
+ const value = property.value;
110
+ if (value?.type === "StringLiteral" && typeof value.value === "string") return {
111
+ kind: "found",
112
+ title: value.value
113
+ };
114
+ if (value?.type === "TemplateLiteral") {
115
+ const expressions = value.expressions ?? [];
116
+ const firstValue = (value.quasis ?? [])[0]?.value;
117
+ const cooked = firstValue?.cooked;
118
+ const raw = firstValue?.raw;
119
+ if (expressions.length === 0 && typeof (cooked ?? raw) === "string") return {
120
+ kind: "found",
121
+ title: cooked ?? raw
122
+ };
123
+ }
124
+ return { kind: "unsupported" };
125
+ }
126
+ return { kind: "missing" };
127
+ }
128
+ }
129
+ return { kind: "missing" };
130
+ }
131
+ async function rmSlideDir(slidesRoot, slideId) {
132
+ if (!SLIDE_ID_RE.test(slideId)) return false;
133
+ const dir = path.resolve(slidesRoot, slideId);
134
+ if (!dir.startsWith(slidesRoot + path.sep)) return false;
135
+ try {
136
+ await fs.rm(dir, {
137
+ recursive: true,
138
+ force: true
139
+ });
140
+ return true;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+ async function duplicateSlideDir(slidesRoot, slideId, desiredId) {
146
+ if (!SLIDE_ID_RE.test(slideId)) return {
147
+ ok: false,
148
+ status: 400,
149
+ error: "invalid slideId"
150
+ };
151
+ const root = path.resolve(slidesRoot);
152
+ const srcDir = path.resolve(root, slideId);
153
+ if (!srcDir.startsWith(root + path.sep)) return {
154
+ ok: false,
155
+ status: 400,
156
+ error: "invalid slideId"
157
+ };
158
+ try {
159
+ await fs.access(path.join(srcDir, "index.tsx"));
160
+ } catch {
161
+ return {
162
+ ok: false,
163
+ status: 404,
164
+ error: "slide not found"
165
+ };
166
+ }
167
+ let newId;
168
+ if (desiredId !== void 0) {
169
+ if (!SLIDE_ID_RE.test(desiredId)) return {
170
+ ok: false,
171
+ status: 400,
172
+ error: "invalid newId"
173
+ };
174
+ newId = desiredId;
175
+ const dstDir = path.resolve(root, newId);
176
+ if (!dstDir.startsWith(root + path.sep)) return {
177
+ ok: false,
178
+ status: 400,
179
+ error: "invalid newId"
180
+ };
181
+ try {
182
+ await fs.access(dstDir);
183
+ return {
184
+ ok: false,
185
+ status: 409,
186
+ error: "slide already exists"
187
+ };
188
+ } catch {}
189
+ } else {
190
+ let suffix = 1;
191
+ while (true) {
192
+ newId = suffix === 1 ? `${slideId}-copy` : `${slideId}-copy-${suffix}`;
193
+ try {
194
+ await fs.access(path.resolve(root, newId));
195
+ suffix++;
196
+ } catch {
197
+ break;
198
+ }
199
+ }
200
+ }
201
+ const dstDir = path.resolve(root, newId);
202
+ if (!dstDir.startsWith(root + path.sep)) return {
203
+ ok: false,
204
+ status: 400,
205
+ error: "invalid newId"
206
+ };
207
+ const srcEntry = path.join(srcDir, "index.tsx");
208
+ let copiedEntrySource;
209
+ try {
210
+ const source = await fs.readFile(srcEntry, "utf8");
211
+ const metaTitle = readMetaTitleInSource(source);
212
+ if (metaTitle.kind === "unsupported") return {
213
+ ok: false,
214
+ status: 422,
215
+ error: "could not update copied slide title"
216
+ };
217
+ const updated = updateMetaTitleInSource(source, `${metaTitle.kind === "found" ? metaTitle.title : slideId} (copy)`);
218
+ if (updated === null) return {
219
+ ok: false,
220
+ status: 422,
221
+ error: "could not update copied slide title"
222
+ };
223
+ copiedEntrySource = updated;
224
+ } catch {
225
+ return {
226
+ ok: false,
227
+ status: 404,
228
+ error: "slide not found"
229
+ };
230
+ }
231
+ try {
232
+ await fs.cp(srcDir, dstDir, {
233
+ recursive: true,
234
+ errorOnExist: true,
235
+ force: false
236
+ });
237
+ await fs.writeFile(path.join(dstDir, "index.tsx"), copiedEntrySource, "utf8");
238
+ return {
239
+ ok: true,
240
+ slideId: newId
241
+ };
242
+ } catch (err) {
243
+ if (err.code === "EEXIST") return {
244
+ ok: false,
245
+ status: 409,
246
+ error: "slide already exists"
247
+ };
248
+ return {
249
+ ok: false,
250
+ status: 500,
251
+ error: String(err.message ?? err)
252
+ };
253
+ }
254
+ }
255
+ function resolveSlideEntry(slidesRoot, slideId) {
256
+ if (!SLIDE_ID_RE.test(slideId)) return null;
257
+ const dir = path.resolve(slidesRoot, slideId);
258
+ if (!dir.startsWith(slidesRoot + path.sep)) return null;
259
+ return path.join(dir, "index.tsx");
260
+ }
261
+ function escapeSingleQuoted(s) {
262
+ return s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
263
+ }
264
+ /**
265
+ * Rewrite (or insert) the `title` field in the slide module's `export const meta`.
266
+ *
267
+ * Strategy:
268
+ * 1. Find `export const meta` and brace-match its object literal.
269
+ * 2. If the object already has a `title: '...'` entry, replace the literal.
270
+ * 3. If the object exists but has no title, inject a new `title: '...'` line
271
+ * as the first property (preserving the author's surrounding indentation).
272
+ * 4. If there is no `meta` export at all, insert a fresh one right before
273
+ * `export default`.
274
+ *
275
+ * Returns the rewritten source, or `null` if the file shape was too surprising
276
+ * to touch safely (e.g. `export default` missing when we'd need to inject meta).
277
+ */
278
+ function updateMetaTitleInSource(source, title) {
279
+ const newLiteral = `'${escapeSingleQuoted(title)}'`;
280
+ const metaStart = source.search(/export\s+const\s+meta\b/);
281
+ if (metaStart !== -1) {
282
+ const eqIdx = source.indexOf("=", metaStart);
283
+ if (eqIdx === -1) return null;
284
+ const openBrace = source.indexOf("{", eqIdx);
285
+ if (openBrace === -1) return null;
286
+ let depth = 0;
287
+ let closeBrace = -1;
288
+ for (let i = openBrace; i < source.length; i++) {
289
+ const ch = source[i];
290
+ if (ch === "{") depth++;
291
+ else if (ch === "}") {
292
+ depth--;
293
+ if (depth === 0) {
294
+ closeBrace = i;
295
+ break;
296
+ }
297
+ }
298
+ }
299
+ if (closeBrace === -1) return null;
300
+ const body = source.slice(openBrace + 1, closeBrace);
301
+ const titleRe = /(^|[\s,{])(title\s*:\s*)(['"`])((?:\\.|(?!\3).)*)\3/;
302
+ const match = body.match(titleRe);
303
+ if (match) {
304
+ const newBody = body.replace(titleRe, `${match[1]}${match[2]}${newLiteral}`);
305
+ return source.slice(0, openBrace + 1) + newBody + source.slice(closeBrace);
306
+ }
307
+ const firstIndentMatch = body.match(/\n([ \t]+)\S/);
308
+ const insertion = `\n${firstIndentMatch ? firstIndentMatch[1] : " "}title: ${newLiteral}${body.replace(/^\s*\n?/, "").trim().length > 0 ? "," : ""}`;
309
+ return source.slice(0, openBrace + 1) + insertion + body + source.slice(closeBrace);
310
+ }
311
+ const exportDefaultIdx = source.search(/export\s+default\b/);
312
+ if (exportDefaultIdx === -1) return null;
313
+ const insertion = `export const meta: SlideMeta = { title: ${newLiteral} };\n\n`;
314
+ return source.slice(0, exportDefaultIdx) + insertion + source.slice(exportDefaultIdx);
315
+ }
316
+ function findDefaultExportArray(source) {
317
+ let ast;
318
+ try {
319
+ ast = parse(source, {
320
+ sourceType: "module",
321
+ plugins: ["typescript", "jsx"],
322
+ errorRecovery: true
323
+ });
324
+ } catch {
325
+ return null;
326
+ }
327
+ const body = ast.program?.body ?? [];
328
+ for (const node of body) {
329
+ if (node.type !== "ExportDefaultDeclaration") continue;
330
+ let inner = node.declaration;
331
+ while (inner && (inner.type === "TSAsExpression" || inner.type === "TSSatisfiesExpression")) inner = inner.expression;
332
+ if (inner?.type !== "ArrayExpression") return null;
333
+ const arrayStart = inner.start;
334
+ const arrayEnd = inner.end;
335
+ const rawElements = inner.elements ?? [];
336
+ const elements = [];
337
+ for (const el of rawElements) {
338
+ if (!el || typeof el.start !== "number" || typeof el.end !== "number") return null;
339
+ elements.push({
340
+ start: el.start,
341
+ end: el.end
342
+ });
343
+ }
344
+ return {
345
+ elements,
346
+ arrayStart,
347
+ arrayEnd
348
+ };
349
+ }
350
+ return null;
351
+ }
352
+ /**
353
+ * Rewrite `export default [...]` so its elements appear in the requested order.
354
+ *
355
+ * `order[i]` is the original index that should land at new position `i`. The
356
+ * function preserves each element's exact source slice (including any inline
357
+ * comments that hug an identifier) and keeps the inter-element separator slots
358
+ * in their original positions, so a 3-page array `[A, B, C]` reordered to
359
+ * `[2, 0, 1]` becomes `[C, A, B]` with the same indentation and trailing
360
+ * commas the author wrote.
361
+ *
362
+ * Returns `null` when the file's default export isn't an array literal, or the
363
+ * order is not a valid permutation of `[0, n-1]`.
364
+ */
365
+ function reorderDefaultExportPagesInSource(source, order) {
366
+ const found = findDefaultExportArray(source);
367
+ if (!found) return null;
368
+ const { elements, arrayStart, arrayEnd } = found;
369
+ const n = elements.length;
370
+ if (order.length !== n) return null;
371
+ const seen = /* @__PURE__ */ new Set();
372
+ for (const idx of order) {
373
+ if (!Number.isInteger(idx) || idx < 0 || idx >= n) return null;
374
+ if (seen.has(idx)) return null;
375
+ seen.add(idx);
376
+ }
377
+ if (n === 0) return source;
378
+ let identity = true;
379
+ for (let i = 0; i < n; i++) if (order[i] !== i) {
380
+ identity = false;
381
+ break;
382
+ }
383
+ if (identity) return source;
384
+ const prefix = source.slice(arrayStart, elements[0].start);
385
+ const suffix = source.slice(elements[n - 1].end, arrayEnd);
386
+ const separators = [];
387
+ for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
388
+ const elementText = elements.map((el) => source.slice(el.start, el.end));
389
+ let rebuilt = prefix + elementText[order[0]];
390
+ for (let i = 1; i < n; i++) rebuilt += separators[i - 1] + elementText[order[i]];
391
+ rebuilt += suffix;
392
+ return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
393
+ }
394
+ function findNotesArray(source) {
395
+ let ast;
396
+ try {
397
+ ast = parse(source, {
398
+ sourceType: "module",
399
+ plugins: ["typescript", "jsx"],
400
+ errorRecovery: true
401
+ });
402
+ } catch {
403
+ return "invalid";
404
+ }
405
+ const body = ast.program?.body ?? [];
406
+ for (const stmt of body) {
407
+ if (stmt.type !== "ExportNamedDeclaration") continue;
408
+ const decl = stmt.declaration;
409
+ if (decl?.type !== "VariableDeclaration") continue;
410
+ const declarations = decl.declarations ?? [];
411
+ for (const d of declarations) {
412
+ const id = d.id;
413
+ if (id?.type !== "Identifier" || id.name !== "notes") continue;
414
+ const init = d.init;
415
+ if (init?.type !== "ArrayExpression") return "invalid";
416
+ const arrayStart = init.start;
417
+ const arrayEnd = init.end;
418
+ if (typeof arrayStart !== "number" || typeof arrayEnd !== "number") return "invalid";
419
+ const rawElements = init.elements ?? [];
420
+ const elementTexts = [];
421
+ for (const el of rawElements) {
422
+ if (el === null) {
423
+ elementTexts.push("undefined");
424
+ continue;
425
+ }
426
+ if (el.type === "SpreadElement") return "invalid";
427
+ const start = el.start;
428
+ const end = el.end;
429
+ if (typeof start !== "number" || typeof end !== "number") return "invalid";
430
+ elementTexts.push(source.slice(start, end));
431
+ }
432
+ return {
433
+ arrayStart,
434
+ arrayEnd,
435
+ elementTexts
436
+ };
437
+ }
438
+ }
439
+ return null;
440
+ }
441
+ /**
442
+ * Reorder `export const notes = [...]` to follow the page-array reorder.
443
+ *
444
+ * `order[i]` is the original page index that should land at new position `i`.
445
+ * The notes array is index-aligned with the pages array but may be shorter
446
+ * (trailing `undefined` slots are routinely trimmed). Missing elements are
447
+ * treated as `undefined`, and trailing `undefined` is trimmed again after
448
+ * reordering to keep the file tidy.
449
+ *
450
+ * Returns the rewritten source, the original source if no `notes` export
451
+ * exists or the reorder is a no-op, or `null` if the `notes` export's shape
452
+ * is too surprising to touch safely.
453
+ */
454
+ function reorderNotesArrayInSource(source, order) {
455
+ for (const idx of order) if (!Number.isInteger(idx) || idx < 0) return null;
456
+ const found = findNotesArray(source);
457
+ if (found === "invalid") return null;
458
+ if (found === null) return source;
459
+ const { arrayStart, arrayEnd, elementTexts } = found;
460
+ const pick = (i) => i >= 0 && i < elementTexts.length ? elementTexts[i] : "undefined";
461
+ return rebuildNotesArray(source, arrayStart, arrayEnd, order.map(pick));
462
+ }
463
+ /**
464
+ * Remove the note aligned with the page at `index` so the `notes` export stays
465
+ * index-aligned with `export default [...]` after a page deletion. Mirrors
466
+ * {@link removePageFromDefaultExportInSource}.
467
+ *
468
+ * Returns the rewritten source, the original source if no `notes` export exists
469
+ * or the index falls past the recorded notes, or `null` if the `notes` export's
470
+ * shape is too surprising to touch safely.
471
+ */
472
+ function removeNotesElementInSource(source, index) {
473
+ if (!Number.isInteger(index) || index < 0) return null;
474
+ const found = findNotesArray(source);
475
+ if (found === "invalid") return null;
476
+ if (found === null) return source;
477
+ const { arrayStart, arrayEnd, elementTexts } = found;
478
+ if (index >= elementTexts.length) return source;
479
+ const next = elementTexts.slice();
480
+ next.splice(index, 1);
481
+ return rebuildNotesArray(source, arrayStart, arrayEnd, next);
482
+ }
483
+ /**
484
+ * Duplicate the note aligned with the page at `index`, inserting the copy right
485
+ * after it so the `notes` export stays index-aligned with `export default [...]`
486
+ * after a page duplication. Mirrors {@link duplicatePageInDefaultExportInSource}.
487
+ *
488
+ * Returns the rewritten source, the original source if no `notes` export exists
489
+ * or the index falls past the recorded notes (the new slot and everything after
490
+ * it are absent, so nothing shifts), or `null` if the shape is too surprising.
491
+ */
492
+ function duplicateNotesElementInSource(source, index) {
493
+ if (!Number.isInteger(index) || index < 0) return null;
494
+ const found = findNotesArray(source);
495
+ if (found === "invalid") return null;
496
+ if (found === null) return source;
497
+ const { arrayStart, arrayEnd, elementTexts } = found;
498
+ if (index >= elementTexts.length) return source;
499
+ const next = elementTexts.slice();
500
+ next.splice(index + 1, 0, next[index]);
501
+ return rebuildNotesArray(source, arrayStart, arrayEnd, next);
502
+ }
503
+ function rebuildNotesArray(source, arrayStart, arrayEnd, elements) {
504
+ const trimmed = elements.slice();
505
+ while (trimmed.length > 0 && trimmed[trimmed.length - 1] === "undefined") trimmed.pop();
506
+ const replacement = trimmed.length === 0 ? "[]" : `[\n${trimmed.map((s) => ` ${s},`).join("\n")}\n]`;
507
+ if (replacement === source.slice(arrayStart, arrayEnd)) return source;
508
+ return source.slice(0, arrayStart) + replacement + source.slice(arrayEnd);
509
+ }
510
+ /**
511
+ * Remove the element at `index` from `export default [...]`.
512
+ *
513
+ * Preserves the source slice of every other element, dropping the separator
514
+ * immediately following the removed element (or the preceding one when the
515
+ * removed element is the last). Returns `null` when the default export isn't
516
+ * an array literal or `index` is out of range.
517
+ */
518
+ function removePageFromDefaultExportInSource(source, index) {
519
+ const found = findDefaultExportArray(source);
520
+ if (!found) return null;
521
+ const { elements, arrayStart, arrayEnd } = found;
522
+ const n = elements.length;
523
+ if (!Number.isInteger(index) || index < 0 || index >= n) return null;
524
+ if (n === 1) return `${source.slice(0, arrayStart)}[]${source.slice(arrayEnd)}`;
525
+ const prefix = source.slice(arrayStart, elements[0].start);
526
+ const suffix = source.slice(elements[n - 1].end, arrayEnd);
527
+ const separators = [];
528
+ for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
529
+ const elementText = elements.map((el) => source.slice(el.start, el.end));
530
+ const keptElements = [];
531
+ const keptSeparators = [];
532
+ for (let i = 0; i < n; i++) {
533
+ if (i === index) continue;
534
+ keptElements.push(elementText[i]);
535
+ }
536
+ for (let i = 0; i < n - 1; i++) {
537
+ if (index === n - 1 ? i === n - 2 : i === index) continue;
538
+ keptSeparators.push(separators[i]);
539
+ }
540
+ let rebuilt = prefix + keptElements[0];
541
+ for (let i = 1; i < keptElements.length; i++) rebuilt += keptSeparators[i - 1] + keptElements[i];
542
+ rebuilt += suffix;
543
+ return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
544
+ }
545
+ function chooseInsertSeparator(prefix, existingSeparators) {
546
+ const sample = existingSeparators.find((s) => s.includes(","));
547
+ if (sample) return sample;
548
+ if (prefix.includes("\n")) {
549
+ const m = prefix.match(/\n([ \t]*)$/);
550
+ return `,\n${m ? m[1] : " "}`;
551
+ }
552
+ return ", ";
553
+ }
554
+ /**
555
+ * Duplicate the element at `index` in `export default [...]`, inserting the
556
+ * copy immediately after the original. Reuses an existing inter-element
557
+ * separator when one is available so the cloned entry matches the surrounding
558
+ * indentation. Returns `null` when the default export isn't an array literal
559
+ * or `index` is out of range.
560
+ */
561
+ function duplicatePageInDefaultExportInSource(source, index) {
562
+ const found = findDefaultExportArray(source);
563
+ if (!found) return null;
564
+ const { elements, arrayStart, arrayEnd } = found;
565
+ const n = elements.length;
566
+ if (!Number.isInteger(index) || index < 0 || index >= n) return null;
567
+ const prefix = source.slice(arrayStart, elements[0].start);
568
+ const suffix = source.slice(elements[n - 1].end, arrayEnd);
569
+ const separators = [];
570
+ for (let i = 0; i < n - 1; i++) separators.push(source.slice(elements[i].end, elements[i + 1].start));
571
+ const elementText = elements.map((el) => source.slice(el.start, el.end));
572
+ const insertSep = chooseInsertSeparator(prefix, separators);
573
+ const newElements = [];
574
+ const newSeparators = [];
575
+ for (let i = 0; i < n; i++) {
576
+ newElements.push(elementText[i]);
577
+ if (i === index) {
578
+ newElements.push(elementText[i]);
579
+ newSeparators.push(insertSep);
580
+ }
581
+ if (i < n - 1) newSeparators.push(separators[i]);
582
+ }
583
+ let rebuilt = prefix + newElements[0];
584
+ for (let i = 1; i < newElements.length; i++) rebuilt += newSeparators[i - 1] + newElements[i];
585
+ rebuilt += suffix;
586
+ return source.slice(0, arrayStart) + rebuilt + source.slice(arrayEnd);
587
+ }
588
+ //#endregion
589
+ //#region src/files/short-id.ts
590
+ function shortId(prefix) {
591
+ return `${prefix}-${randomUUID().replace(/-/g, "").slice(0, 8)}`;
592
+ }
593
+ //#endregion
594
+ //#region src/files/folders.ts
595
+ const FOLDER_ID_RE = /^f-[a-f0-9]{8}$/;
596
+ const COLOR_RE = /^#[0-9a-fA-F]{6}$/;
597
+ function foldersManifestPath(slidesRoot) {
598
+ return path.join(slidesRoot, ".folders.json");
599
+ }
600
+ function emptyManifest() {
601
+ return {
602
+ folders: [],
603
+ assignments: {}
604
+ };
605
+ }
606
+ async function readManifest(file) {
607
+ try {
608
+ const raw = await fs.readFile(file, "utf8");
609
+ const parsed = JSON.parse(raw);
610
+ return {
611
+ folders: Array.isArray(parsed.folders) ? parsed.folders : [],
612
+ assignments: parsed.assignments && typeof parsed.assignments === "object" ? parsed.assignments : {}
613
+ };
614
+ } catch (err) {
615
+ if (err.code === "ENOENT") return emptyManifest();
616
+ throw err;
617
+ }
618
+ }
619
+ async function writeManifest(file, manifest) {
620
+ await fs.mkdir(path.dirname(file), { recursive: true });
621
+ await fs.writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
622
+ }
623
+ function newFolderId() {
624
+ return shortId("f");
625
+ }
626
+ function validateName(v) {
627
+ if (typeof v !== "string") return null;
628
+ const trimmed = v.trim();
629
+ if (trimmed.length < 1 || trimmed.length > 40) return null;
630
+ return trimmed;
631
+ }
632
+ function validateReorder(v, current) {
633
+ if (!Array.isArray(v) || v.length !== current.length) return null;
634
+ const known = new Set(current.map((f) => f.id));
635
+ const seen = /* @__PURE__ */ new Set();
636
+ const out = [];
637
+ for (const id of v) {
638
+ if (typeof id !== "string" || !FOLDER_ID_RE.test(id)) return null;
639
+ if (!known.has(id) || seen.has(id)) return null;
640
+ seen.add(id);
641
+ out.push(id);
642
+ }
643
+ return out;
644
+ }
645
+ function validateIcon(v) {
646
+ if (!v || typeof v !== "object") return null;
647
+ const icon = v;
648
+ if (icon.type === "emoji") {
649
+ if (typeof icon.value !== "string") return null;
650
+ if (icon.value.length < 1 || icon.value.length > 8) return null;
651
+ return {
652
+ type: "emoji",
653
+ value: icon.value
654
+ };
655
+ }
656
+ if (icon.type === "color") {
657
+ if (typeof icon.value !== "string" || !COLOR_RE.test(icon.value)) return null;
658
+ return {
659
+ type: "color",
660
+ value: icon.value
661
+ };
662
+ }
663
+ return null;
664
+ }
665
+ //#endregion
666
+ //#region src/vite/routes/context.ts
667
+ function makeContext(opts) {
668
+ const userCwd = opts.userCwd;
669
+ const slidesDir = opts.slidesDir ?? "slides";
670
+ const assetsDir = opts.assetsDir ?? "assets";
671
+ const slidesRoot = path.resolve(userCwd, slidesDir);
672
+ return {
673
+ userCwd,
674
+ slidesDir,
675
+ slidesRoot,
676
+ globalAssetsRoot: path.resolve(userCwd, assetsDir),
677
+ manifestPath: foldersManifestPath(slidesRoot),
678
+ coreVersion: opts.coreVersion
679
+ };
680
+ }
681
+ async function readBody(req) {
682
+ return await new Promise((resolve, reject) => {
683
+ const chunks = [];
684
+ req.on("data", (c) => chunks.push(c));
685
+ req.on("end", () => {
686
+ const raw = Buffer.concat(chunks).toString("utf8");
687
+ if (!raw) return resolve({});
688
+ try {
689
+ resolve(JSON.parse(raw));
690
+ } catch (e) {
691
+ reject(e);
692
+ }
693
+ });
694
+ req.on("error", reject);
695
+ });
696
+ }
697
+ function json(res, status, body) {
698
+ res.statusCode = status;
699
+ res.setHeader("content-type", "application/json");
700
+ res.end(JSON.stringify(body));
701
+ }
702
+ function resolveSlideEntryPath(ctx, slideId) {
703
+ return resolveSlideEntry(ctx.slidesRoot, slideId);
704
+ }
705
+ async function readSlideSource(file) {
706
+ try {
707
+ return await fs.readFile(file, "utf8");
708
+ } catch (err) {
709
+ if (err.code === "ENOENT") return null;
710
+ throw err;
711
+ }
712
+ }
713
+ //#endregion
714
+ //#region src/vite/routes/update.ts
715
+ const PKG = "@open-slide/core";
716
+ const CACHE_TTL_MS = 6e5;
717
+ const COMMAND_TIMEOUT_MS = 3e5;
718
+ let cache = null;
719
+ let updateInFlight = null;
720
+ function parseSemver(v) {
721
+ const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(v.trim());
722
+ if (!m) return null;
723
+ return [
724
+ Number(m[1]),
725
+ Number(m[2]),
726
+ Number(m[3])
727
+ ];
728
+ }
729
+ function isOutdated(current, latest) {
730
+ const a = parseSemver(current);
731
+ const b = parseSemver(latest);
732
+ if (!a || !b) return false;
733
+ for (let i = 0; i < 3; i++) {
734
+ if (b[i] > a[i]) return true;
735
+ if (b[i] < a[i]) return false;
736
+ }
737
+ return false;
738
+ }
739
+ async function fetchLatest(now) {
740
+ if (cache && now - cache.at < CACHE_TTL_MS) return cache.latest;
741
+ try {
742
+ const res = await fetch(`https://registry.npmjs.org/${PKG}/latest`, {
743
+ signal: AbortSignal.timeout(3e3),
744
+ headers: { accept: "application/json" }
745
+ });
746
+ if (!res.ok) throw new Error(`registry ${res.status}`);
747
+ const body = await res.json();
748
+ const latest = typeof body.version === "string" ? body.version : null;
749
+ cache = {
750
+ at: now,
751
+ latest
752
+ };
753
+ return latest;
754
+ } catch {
755
+ return cache?.latest ?? null;
756
+ }
757
+ }
758
+ async function fileExists(file) {
759
+ try {
760
+ await fs.access(file);
761
+ return true;
762
+ } catch {
763
+ return false;
764
+ }
765
+ }
766
+ const LOCKFILES = [
767
+ ["pnpm-lock.yaml", "pnpm"],
768
+ ["yarn.lock", "yarn"],
769
+ ["bun.lockb", "bun"],
770
+ ["bun.lock", "bun"],
771
+ ["package-lock.json", "npm"]
772
+ ];
773
+ async function detectPackageManager(cwd) {
774
+ const ua = process.env.npm_config_user_agent ?? "";
775
+ if (ua.startsWith("pnpm")) return "pnpm";
776
+ if (ua.startsWith("yarn")) return "yarn";
777
+ if (ua.startsWith("bun")) return "bun";
778
+ if (ua.startsWith("npm")) return "npm";
779
+ let dir = cwd;
780
+ while (true) {
781
+ for (const [lockfile, pm] of LOCKFILES) if (await fileExists(path.join(dir, lockfile))) return pm;
782
+ const parent = path.dirname(dir);
783
+ if (parent === dir) return "npm";
784
+ dir = parent;
785
+ }
786
+ }
787
+ function updateCommandFor(packageManager) {
788
+ switch (packageManager) {
789
+ case "pnpm": return {
790
+ cmd: "pnpm",
791
+ args: ["add", `${PKG}@latest`]
792
+ };
793
+ case "yarn": return {
794
+ cmd: "yarn",
795
+ args: ["add", `${PKG}@latest`]
796
+ };
797
+ case "bun": return {
798
+ cmd: "bun",
799
+ args: ["add", `${PKG}@latest`]
800
+ };
801
+ case "npm": return {
802
+ cmd: "npm",
803
+ args: ["install", `${PKG}@latest`]
804
+ };
805
+ }
806
+ }
807
+ function localOpenSlideCommand(cwd) {
808
+ const bin = process.platform === "win32" ? "open-slide.cmd" : "open-slide";
809
+ return {
810
+ cmd: path.join(cwd, "node_modules", ".bin", bin),
811
+ args: ["sync:skills"]
812
+ };
813
+ }
814
+ function formatCommand(spec) {
815
+ return [spec.cmd, ...spec.args].join(" ");
816
+ }
817
+ async function runCommand(spec, cwd) {
818
+ await new Promise((resolve, reject) => {
819
+ const child = spawn(spec.cmd, spec.args, {
820
+ cwd,
821
+ env: process.env,
822
+ shell: process.platform === "win32",
823
+ stdio: [
824
+ "ignore",
825
+ "ignore",
826
+ "pipe"
827
+ ]
828
+ });
829
+ let stderr = "";
830
+ const timer = setTimeout(() => {
831
+ child.kill();
832
+ reject(/* @__PURE__ */ new Error(`${formatCommand(spec)} timed out`));
833
+ }, COMMAND_TIMEOUT_MS);
834
+ child.stderr.on("data", (chunk) => {
835
+ stderr += chunk.toString("utf8");
836
+ if (stderr.length > 2e3) stderr = stderr.slice(-2e3);
837
+ });
838
+ child.on("error", (err) => {
839
+ clearTimeout(timer);
840
+ reject(err);
841
+ });
842
+ child.on("close", (code) => {
843
+ clearTimeout(timer);
844
+ if (code === 0) {
845
+ resolve();
846
+ return;
847
+ }
848
+ const detail = stderr.trim();
849
+ reject(new Error(detail || `${formatCommand(spec)} exited with code ${code ?? "unknown"}`));
850
+ });
851
+ });
852
+ }
853
+ async function updatePackage(ctx) {
854
+ const packageManager = await detectPackageManager(ctx.userCwd);
855
+ const updateCommand = updateCommandFor(packageManager);
856
+ const syncCommand = localOpenSlideCommand(ctx.userCwd);
857
+ await runCommand(updateCommand, ctx.userCwd);
858
+ await runCommand(syncCommand, ctx.userCwd);
859
+ cache = null;
860
+ const latest = await fetchLatest(Date.now());
861
+ return {
862
+ packageManager,
863
+ command: `${formatCommand(updateCommand)} && open-slide sync:skills`,
864
+ latest,
865
+ message: "Updated @open-slide/core and synced skills."
866
+ };
867
+ }
868
+ function registerUpdateRoutes(server, ctx) {
869
+ server.middlewares.use("/__update-check", async (req, res, next) => {
870
+ if ((req.method ?? "GET") !== "GET") return next();
871
+ const latest = await fetchLatest(Date.now());
872
+ const result = {
873
+ current: ctx.coreVersion,
874
+ latest,
875
+ outdated: latest ? isOutdated(ctx.coreVersion, latest) : false
876
+ };
877
+ res.setHeader("cache-control", "no-store");
878
+ json(res, 200, result);
879
+ });
880
+ server.middlewares.use("/__update-package", async (req, res, next) => {
881
+ if ((req.method ?? "GET") !== "POST") return next();
882
+ const guard = validateMutationRequest(req);
883
+ if (!guard.ok) return json(res, guard.status, { error: guard.error });
884
+ try {
885
+ updateInFlight ??= updatePackage(ctx).finally(() => {
886
+ updateInFlight = null;
887
+ });
888
+ json(res, 200, await updateInFlight);
889
+ } catch (err) {
890
+ json(res, 500, { error: err instanceof Error ? err.message : "update failed" });
891
+ }
892
+ });
893
+ }
894
+ //#endregion
895
+ export { reorderDefaultExportPagesInSource as C, updateMetaTitleInSource as D, rmSlideDir as E, validateSlideName as O, removePageFromDefaultExportInSource as S, resolveSlideEntry as T, SLIDE_ID_RE as _, readBody as a, duplicateSlideDir as b, FOLDER_ID_RE as c, readManifest as d, validateIcon as f, shortId as g, writeManifest as h, makeContext as i, validateMutationRequest as k, foldersManifestPath as l, validateReorder as m, registerUpdateRoutes as n, readSlideSource as o, validateName as p, json as r, resolveSlideEntryPath as s, detectPackageManager as t, newFolderId as u, duplicateNotesElementInSource as v, reorderNotesArrayInSource as w, removeNotesElementInSource as x, duplicatePageInDefaultExportInSource as y };