-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
668 lines (623 loc) · 26.9 KB
/
Copy pathserver.mjs
File metadata and controls
668 lines (623 loc) · 26.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// JotSON - zero-dependency local server (drop the jotson/ folder into any project).
// Serves the editor UI and a small read/write API over the configured JSON data dir.
// Run with: node jotson/server.mjs (never deployed; binds to localhost only)
// Requires Node 18+. No npm packages - Vue is vendored in jotson/vendor/.
import http from 'node:http'
import { randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
// Project root defaults to the jotson/ folder's parent; override with JOTSON_ROOT if placed elsewhere
const ROOT = process.env.JOTSON_ROOT ? path.resolve(process.env.JOTSON_ROOT) : path.resolve(__dirname, '..')
const PUBLIC_DIR = path.join(__dirname, 'public')
// Vendored copy keeps the editor dependency-free; falls back to a host-project install if removed
const VUE_CANDIDATES = [
path.join(__dirname, 'vendor', 'vue.js'),
path.join(ROOT, 'node_modules', 'vue', 'dist', 'vue.global.prod.js')
]
// Config resolves per-project so npx runs (shared npm cache) don't bleed settings between
// projects: $JOTSON_CONFIG → <root>/jotson.config.json → in-folder jotson.config.json (drop-in)
const LEGACY_CONFIG_PATH = path.join(__dirname, 'jotson.config.json')
const PROJECT_CONFIG_PATH = path.join(ROOT, 'jotson.config.json')
const fileExists = (p) => fs.access(p).then(() => true, () => false)
const CONFIG_PATH = process.env.JOTSON_CONFIG
? path.resolve(process.env.JOTSON_CONFIG)
: (await fileExists(PROJECT_CONFIG_PATH)) || !(await fileExists(LEGACY_CONFIG_PATH))
? PROJECT_CONFIG_PATH
: LEGACY_CONFIG_PATH
// Path shown in the UI: project-relative when inside the root, absolute otherwise
const configDisplayPath = () => {
const rel = path.relative(ROOT, CONFIG_PATH)
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel.replaceAll('\\', '/') : CONFIG_PATH
}
// Own version - package.json ships in the npm tarball and lives in the repo for drop-in
let VERSION = null
try {
VERSION = JSON.parse(await fs.readFile(path.join(__dirname, 'package.json'), 'utf8')).version || null
} catch {
/* drop-in copy without package.json */
}
// How jotson is running decides the right update command (npx cache paths contain _npx,
// so that check must come before the general node_modules one)
const UPDATE_COMMAND = /[\\/]_npx[\\/]/.test(__dirname) || process.env.npm_command === 'exec'
? 'npx @blindmikey/jotson@latest'
: /[\\/]node_modules[\\/]/.test(__dirname)
? 'npm i -g @blindmikey/jotson'
: null // drop-in folder - updated by copying/pulling, not npm
// One registry lookup per server run, on first /api/version request; fail-silent offline
let latestVersionPromise = null
function fetchLatestVersion() {
latestVersionPromise ||= (async () => {
try {
const res = await fetch('https://registry.npmjs.org/@blindmikey/jotson/latest', {
signal: AbortSignal.timeout(4000)
})
if (!res.ok) return null
return (await res.json()).version || null
} catch {
return null
}
})()
return latestVersionPromise
}
// Numeric major.minor.patch comparison; prerelease suffixes are ignored
function isNewer(a, b) {
if (!a || !b) return false
const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0)
const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0)
for (let i = 0; i < 3; i++) {
if (pa[i] !== pb[i]) return pa[i] > pb[i]
}
return false
}
// Preferred port. If the default is busy the OS picks a free one; an explicit
// JOTSON_PORT is honored strictly and errors out instead of silently moving.
const PORT = Number(process.env.JOTSON_PORT) || 4400
const FILE_NAME_RE = /^[A-Za-z0-9_-]+\.json$/
const CONFIG_DEFAULTS = {
jsonDir: '',
publicDir: '',
uploadDir: '',
logo: null,
logoLight: null,
title: '',
labelFields: ['title', 'label', 'name', 'id'],
idFields: ['id'],
// Opt-in: reference detection is data-driven, so datasets with non-unique ids would
// show spurious references out of the box
references: false,
// Conditional-schema fill: when a discriminator field (e.g. a block's `type`) gains a
// value whose schema branch requires keys not yet present, offer to add them.
// 'ask' (default) prompts, 'auto' adds silently, 'off' disables.
schemaFill: 'ask',
}
// Internal branding - not part of the per-project config
const JOTSON_BRAND = '{J𝘰𝓉SON}'
let config = { ...CONFIG_DEFAULTS }
let rawConfig = {}
try {
rawConfig = JSON.parse(await fs.readFile(CONFIG_PATH, 'utf8'))
config = { ...CONFIG_DEFAULTS, ...rawConfig }
} catch {
/* no config file - defaults apply */
}
delete config.jotsonBrand // legacy key from configs written by <= 1.0.0 - now internal-only
// Rename (v1.2): dataDir -> jsonDir. Legacy configs keep working untouched; the ⚙ panel
// writes the new key on its next save. An explicit jsonDir wins ("" = project root is a
// real value, so presence in the file decides, not truthiness).
if (!('jsonDir' in rawConfig) && typeof config.dataDir === 'string') config.jsonDir = config.dataDir
delete config.dataDir
// Pre-release rename: mediaDir -> uploadDir (migrate silently, drop the old key on next save)
if (typeof config.mediaDir === 'string' && !config.uploadDir) config.uploadDir = config.mediaDir
delete config.mediaDir
// Pre-release semantics change: uploadDir was project-root-relative, now publicDir-relative.
// Strip a leading "<publicDir>/" so session-era configs keep pointing at the same folder.
if (config.uploadDir && config.publicDir) {
if (config.uploadDir === config.publicDir) config.uploadDir = ''
else if (config.uploadDir.startsWith(config.publicDir + '/')) config.uploadDir = config.uploadDir.slice(config.publicDir.length + 1)
}
const jsonDir = () => path.resolve(ROOT, config.jsonDir)
const sitePublicDir = () => path.resolve(ROOT, config.publicDir)
// Uploads land here - always inside the public dir so stored paths are site-relative
// and previews/serving work by construction; empty = the public dir root itself
const uploadDir = () => path.resolve(sitePublicDir(), config.uploadDir || '')
// Extensions accepted by POST /api/upload (media only - this is a data editor, not a file manager)
const UPLOAD_EXTS = new Set([
'png', 'jpg', 'jpeg', 'webp', 'gif', 'svg', 'avif', 'ico',
'mp4', 'webm', 'mov', 'ogg', 'mp3', 'wav', 'pdf'
])
const UPLOAD_MAX_BYTES = 100 * 1024 * 1024
// The cleanup endpoints only ever touch files jotson itself created: uuid4-named,
// directly inside the upload dir (no separators possible - traversal-proof)
const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]{1,10}$/i
const MIME = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.avif': 'image/avif',
'.ico': 'image/x-icon',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.mov': 'video/quicktime',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.pdf': 'application/pdf',
'.ogg': 'video/ogg'
}
function send(res, status, body, type = 'application/json; charset=utf-8') {
res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' })
res.end(body)
}
function sendJson(res, status, obj) {
send(res, status, JSON.stringify(obj))
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = []
req.on('data', (c) => chunks.push(c))
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
req.on('error', reject)
})
}
function validName(name) {
return typeof name === 'string' && FILE_NAME_RE.test(name)
}
// Binary-safe body reader for uploads, with a size cap
function readBodyRaw(req, maxBytes) {
return new Promise((resolve, reject) => {
const chunks = []
let size = 0
req.on('data', (c) => {
size += c.length
if (size > maxBytes) {
req.destroy()
reject(new Error(`Upload exceeds ${Math.round(maxBytes / 1024 / 1024)} MB`))
return
}
chunks.push(c)
})
req.on('end', () => resolve(Buffer.concat(chunks)))
req.on('error', reject)
})
}
async function listDataFiles() {
const entries = await fs.readdir(jsonDir())
// The sidecars are already in this listing (FILE_NAME_RE filters them out of the editable
// tabs below). A Set lets us flag hasSchema per file for free - no extra stat, so the
// client only fetches schemas that exist instead of probing every file with a 404.
const present = new Set(entries)
const files = []
// Only list names the read/write endpoints accept (FILE_NAME_RE), and never the
// tool's own config, which shows up when jsonDir is the project root
for (const name of entries.filter((n) => FILE_NAME_RE.test(n)).sort()) {
const full = path.join(jsonDir(), name)
if (full === CONFIG_PATH) continue
const stat = await fs.stat(full)
files.push({ name, size: stat.size, mtime: stat.mtimeMs, hasSchema: present.has(name.replace(/\.json$/, '.schema.json')) })
}
return files
}
async function isDirectory(p) {
try {
return (await fs.stat(p)).isDirectory()
} catch {
return false
}
}
/* ---------- link unfurling (OpenGraph/Twitter meta) ---------- */
const unfurlCache = new Map()
const UNFURL_TTL = 3600e3
const UNFURL_MAX = 200
function decodeEntities(s) {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/�?39;|'/g, "'")
.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
}
function metaContent(html, names) {
for (const name of names) {
const patterns = [
new RegExp(`<meta[^>]+(?:property|name)=["']${name}["'][^>]*content=["']([^"']*)["']`, 'i'),
new RegExp(`<meta[^>]+content=["']([^"']*)["'][^>]*(?:property|name)=["']${name}["']`, 'i')
]
for (const re of patterns) {
const m = html.match(re)
if (m && m[1]) return decodeEntities(m[1].trim())
}
}
return null
}
async function unfurl(target) {
const cached = unfurlCache.get(target)
if (cached && Date.now() - cached.at < UNFURL_TTL) return cached.data
const ctrl = new AbortController()
const timer = setTimeout(() => ctrl.abort(), 6000)
let data
try {
const resp = await fetch(target, {
signal: ctrl.signal,
redirect: 'follow',
headers: {
// Some sites only serve OpenGraph tags to browser-like agents
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36',
Accept: 'text/html,application/xhtml+xml'
}
})
const html = (await resp.text()).slice(0, 500000)
data = {
url: target,
title:
metaContent(html, ['og:title', 'twitter:title']) ||
decodeEntities((html.match(/<title[^>]*>([^<]*)<\/title>/i) || [])[1] || '').trim() ||
null,
description: metaContent(html, ['og:description', 'twitter:description', 'description']),
image: metaContent(html, ['og:image', 'og:image:url', 'twitter:image']),
siteName: metaContent(html, ['og:site_name'])
}
} catch {
data = { url: target, title: null, description: null, image: null, siteName: null }
} finally {
clearTimeout(timer)
}
unfurlCache.set(target, { at: Date.now(), data })
if (unfurlCache.size > UNFURL_MAX) unfurlCache.delete(unfurlCache.keys().next().value)
return data
}
async function handleApi(req, res, url) {
const parts = url.pathname.split('/').filter(Boolean) // ['api', ...]
if (parts[1] === 'config' && parts.length === 2) {
if (req.method === 'GET') return sendJson(res, 200, { config, configPath: configDisplayPath() })
if (req.method === 'PUT') {
let body
try {
body = JSON.parse(await readBody(req))
} catch {
return sendJson(res, 400, { error: 'Request body must be JSON' })
}
const next = { ...config }
// Empty string is a valid value for all dirs - project root for json/public,
// "same as public dir" for media
if (typeof body.jsonDir === 'string') next.jsonDir = body.jsonDir.trim()
else if (typeof body.dataDir === 'string') next.jsonDir = body.dataDir.trim() // legacy key
if (typeof body.publicDir === 'string') next.publicDir = body.publicDir.trim()
if (typeof body.uploadDir === 'string') next.uploadDir = body.uploadDir.trim()
next.logo = typeof body.logo === 'string' && body.logo.trim() ? body.logo.trim() : null
next.logoLight = typeof body.logoLight === 'string' && body.logoLight.trim() ? body.logoLight.trim() : null
if (typeof body.title === 'string') next.title = body.title.trim() || CONFIG_DEFAULTS.title
if (Array.isArray(body.labelFields)) {
const fields = body.labelFields.map((f) => String(f).trim()).filter(Boolean)
next.labelFields = fields.length ? fields : CONFIG_DEFAULTS.labelFields
}
if (Array.isArray(body.idFields)) {
const fields = body.idFields.map((f) => String(f).trim()).filter(Boolean)
next.idFields = fields.length ? fields : CONFIG_DEFAULTS.idFields
}
if (typeof body.references === 'boolean') next.references = body.references
if (['ask', 'auto', 'off'].includes(body.schemaFill)) next.schemaFill = body.schemaFill
if (!(await isDirectory(path.resolve(ROOT, next.jsonDir)))) {
return sendJson(res, 400, { error: `JSON directory not found: ${next.jsonDir}` })
}
if (!(await isDirectory(path.resolve(ROOT, next.publicDir)))) {
return sendJson(res, 400, { error: `Public directory not found: ${next.publicDir}` })
}
// Upload dir resolves inside the public dir and must not escape it; it may not
// exist yet (created on first upload), but if it exists it must be a directory
const pubAbs = path.resolve(ROOT, next.publicDir)
const uploadAbs = path.resolve(pubAbs, next.uploadDir || '')
const uploadRel = path.relative(pubAbs, uploadAbs)
if (uploadRel.startsWith('..') || path.isAbsolute(uploadRel)) {
return sendJson(res, 400, { error: `Upload directory must be inside the public directory: ${next.uploadDir}` })
}
const uploadStat = await fs.stat(uploadAbs).catch(() => null)
if (uploadStat && !uploadStat.isDirectory()) {
return sendJson(res, 400, { error: `Upload directory is not a directory: ${next.uploadDir}` })
}
config = next
await fs.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + '\n', 'utf8')
return sendJson(res, 200, { ok: true, config, configPath: configDisplayPath() })
}
}
// List uuid-named media files that nothing references. "Referenced" is the union of
// every data file on disk, jotson's own config (logo/logoLight may point at an uploaded
// file), and the client's in-memory strings (body.referenced), so unsaved edits that
// point at a fresh upload keep it safe.
if (req.method === 'POST' && parts[1] === 'media' && parts[2] === 'orphans' && parts.length === 3) {
let body = {}
try {
body = JSON.parse((await readBody(req)) || '{}')
} catch {
return sendJson(res, 400, { error: 'Request body must be JSON' })
}
const dir = uploadDir()
let names = []
try {
names = (await fs.readdir(dir)).filter((n) => UUID_FILE_RE.test(n))
} catch {
/* upload dir does not exist yet - nothing to clean */
}
if (!names.length) return sendJson(res, 200, { orphans: [] })
let haystack = (Array.isArray(body.referenced) ? body.referenced : []).map(String).join('\n')
haystack += '\n' + JSON.stringify(config) // logo/logoLight etc. protect their uploads
for (const f of await listDataFiles()) {
haystack += '\n' + (await fs.readFile(path.join(jsonDir(), f.name), 'utf8'))
}
const orphans = []
for (const name of names) {
if (haystack.includes(name)) continue // uuids are unique - substring match is exact enough
const stat = await fs.stat(path.join(dir, name))
orphans.push({ name, size: stat.size, mtime: stat.mtimeMs })
}
return sendJson(res, 200, { orphans })
}
// Move uuid-named uploads from a previous upload dir into the current one (both
// inside the public dir). Only files jotson created move; hand-placed assets stay.
if (req.method === 'POST' && parts[1] === 'media' && parts[2] === 'migrate' && parts.length === 3) {
let body
try {
body = JSON.parse(await readBody(req))
} catch {
return sendJson(res, 400, { error: 'Request body must be JSON' })
}
const pub = sitePublicDir()
const sitePrefix = (abs) => {
const rel = path.relative(pub, abs).replaceAll('\\', '/')
return rel ? '/' + rel : ''
}
const fromAbs = path.resolve(pub, typeof body.from === 'string' ? body.from : '')
const fromRel = path.relative(pub, fromAbs)
if (fromRel.startsWith('..') || path.isAbsolute(fromRel)) {
return sendJson(res, 400, { error: 'Source directory must be inside the public directory' })
}
const toAbs = uploadDir()
if (fromAbs === toAbs) return sendJson(res, 200, { ok: true, moved: [], from: sitePrefix(fromAbs), to: sitePrefix(toAbs) })
let names = []
try {
names = (await fs.readdir(fromAbs)).filter((n) => UUID_FILE_RE.test(n))
} catch {
/* old dir gone - nothing to move */
}
const moved = []
if (names.length) {
await fs.mkdir(toAbs, { recursive: true })
for (const name of names) {
try {
await fs.rename(path.join(fromAbs, name), path.join(toAbs, name))
moved.push(name)
} catch {
/* locked or already moved - skip */
}
}
}
return sendJson(res, 200, { ok: true, moved, from: sitePrefix(fromAbs), to: sitePrefix(toAbs) })
}
// Remove named uuid media files (the client confirms with the user first). Either
// permanently deletes them, or - with body.trash - moves them to <root>/trash
// (created on demand) so they can be recovered.
if (req.method === 'POST' && parts[1] === 'media' && parts[2] === 'clean' && parts.length === 3) {
let body
try {
body = JSON.parse(await readBody(req))
} catch {
return sendJson(res, 400, { error: 'Request body must be JSON' })
}
const toTrash = body.trash === true
const trashDir = path.resolve(ROOT, 'trash')
if (toTrash) await fs.mkdir(trashDir, { recursive: true })
const deleted = []
for (const name of Array.isArray(body.files) ? body.files : []) {
if (typeof name !== 'string' || !UUID_FILE_RE.test(name)) continue
const src = path.join(uploadDir(), name)
try {
if (toTrash) {
const dest = path.join(trashDir, name)
try {
await fs.rename(src, dest)
} catch {
// cross-device or existing dest: fall back to copy + remove
await fs.copyFile(src, dest)
await fs.unlink(src)
}
} else {
await fs.unlink(src)
}
deleted.push(name)
} catch {
/* already gone or locked - skip */
}
}
return sendJson(res, 200, { ok: true, deleted, trashed: toTrash })
}
// Copy an uploaded file into the upload dir as <uuid4>.<ext>; body is the raw file bytes.
// Responds with the path to store: site-relative when the upload dir is inside the public
// dir (so previews work), project-root-relative otherwise.
if (req.method === 'POST' && parts[1] === 'upload' && parts.length === 2) {
const original = url.searchParams.get('name') || ''
const ext = (original.match(/\.([A-Za-z0-9]{1,10})$/) || [])[1]?.toLowerCase()
if (!ext || !UPLOAD_EXTS.has(ext)) {
return sendJson(res, 400, { error: `Unsupported file type - allowed: ${[...UPLOAD_EXTS].join(', ')}` })
}
let body
try {
body = await readBodyRaw(req, UPLOAD_MAX_BYTES)
} catch (e) {
return sendJson(res, 400, { error: e.message })
}
if (!body.length) return sendJson(res, 400, { error: 'Empty upload' })
const dir = uploadDir()
// Containment is enforced at config save; re-check here in case the config file
// was hand-edited to point outside the public dir
const containRel = path.relative(sitePublicDir(), dir)
if (containRel.startsWith('..') || path.isAbsolute(containRel)) {
return sendJson(res, 400, { error: 'Upload directory must be inside the public directory' })
}
await fs.mkdir(dir, { recursive: true })
const filename = `${randomUUID()}.${ext}`
const dest = path.join(dir, filename)
await fs.writeFile(dest, body)
const relPub = path.relative(sitePublicDir(), dest).replaceAll('\\', '/')
return sendJson(res, 200, { ok: true, path: '/' + relPub, file: filename })
}
if (req.method === 'GET' && parts[1] === 'version' && parts.length === 2) {
const latest = await fetchLatestVersion()
return sendJson(res, 200, {
version: VERSION,
latest,
updateAvailable: isNewer(latest, VERSION),
updateCommand: UPDATE_COMMAND
})
}
if (req.method === 'GET' && parts[1] === 'files' && parts.length === 2) {
return sendJson(res, 200, { files: await listDataFiles() })
}
if (req.method === 'GET' && parts[1] === 'unfurl' && parts.length === 2) {
const target = url.searchParams.get('url') || ''
if (!/^https?:\/\//i.test(target)) return sendJson(res, 400, { error: 'Only http(s) URLs' })
return sendJson(res, 200, await unfurl(target))
}
// Schema sidecar for a data file: <name>.schema.json next to <name>.json. The dotted
// stem keeps schema files outside FILE_NAME_RE, so they never appear as editable tabs.
if (parts[1] === 'schema' && parts.length === 3) {
const name = decodeURIComponent(parts[2]) // the DATA file's name, e.g. records.json
if (!validName(name)) return sendJson(res, 400, { error: 'Invalid file name' })
const schemaPath = path.join(jsonDir(), name.replace(/\.json$/, '.schema.json'))
if (req.method === 'GET') {
try {
const text = await fs.readFile(schemaPath, 'utf8')
return send(res, 200, text, 'application/json; charset=utf-8')
} catch {
return sendJson(res, 404, { error: 'No schema for this file' })
}
}
if (req.method === 'PUT') {
// Unlike data files, schemas may be created here - that's the derive button's job
const text = await readBody(req)
try {
JSON.parse(text)
} catch (e) {
return sendJson(res, 400, { error: `Refusing to save invalid JSON: ${e.message}` })
}
await fs.writeFile(schemaPath, text, 'utf8')
return sendJson(res, 200, { ok: true, path: path.basename(schemaPath) })
}
// No DELETE: removing a schema is a file-manager job. Once the file is gone, the
// gear offers to derive a fresh one again (after the next reload).
}
if (parts[1] === 'files' && parts.length === 3) {
const name = decodeURIComponent(parts[2])
if (!validName(name)) return sendJson(res, 400, { error: 'Invalid file name' })
const filePath = path.join(jsonDir(), name)
if (req.method === 'GET') {
// Raw text, not a JSON envelope: wrapping a 100 MB file in {"text": ...} would
// force the client to JSON-parse the whole payload twice
try {
const text = await fs.readFile(filePath, 'utf8')
return send(res, 200, text, 'application/json; charset=utf-8')
} catch {
return sendJson(res, 404, { error: 'File not found' })
}
}
if (req.method === 'PUT') {
// Only overwrite files that already exist - the CMS edits, it doesn't create.
try {
await fs.access(filePath)
} catch {
return sendJson(res, 404, { error: 'File not found' })
}
// Body is the raw file text (same no-envelope reasoning as GET)
const text = await readBody(req)
try {
JSON.parse(text)
} catch (e) {
return sendJson(res, 400, { error: `Refusing to save invalid JSON: ${e.message}` })
}
await fs.writeFile(filePath, text, 'utf8')
return sendJson(res, 200, { ok: true })
}
}
return sendJson(res, 404, { error: 'Unknown API route' })
}
async function handleStatic(res, pathname) {
if (pathname === '/vendor/vue.js') {
for (const candidate of VUE_CANDIDATES) {
try {
const buf = await fs.readFile(candidate)
return send(res, 200, buf, MIME['.js'])
} catch {
/* try next candidate */
}
}
return send(res, 500, 'Vue build not found - restore jotson/vendor/vue.js', 'text/plain')
}
// /site/* serves the project's public dir so media previews work without the project's dev server
if (pathname.startsWith('/site/')) {
const base = sitePublicDir()
const sitePath = path.join(base, decodeURIComponent(pathname.slice(6)))
if (!sitePath.startsWith(base)) return send(res, 403, 'Forbidden', 'text/plain')
try {
const buf = await fs.readFile(sitePath)
const ext = path.extname(sitePath).toLowerCase()
const type = MIME[ext] || 'application/octet-stream'
const headers = { 'Content-Type': type, 'Cache-Control': 'no-store' }
if (ext === '.svg') {
// <img> previews never execute SVG scripts, but if the URL is opened directly as a
// document this blocks scripts/external loads too (inline styles stay allowed)
headers['Content-Security-Policy'] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:"
}
res.writeHead(200, headers)
return res.end(buf)
} catch {
return send(res, 404, 'Not found in public/', 'text/plain')
}
}
const rel = pathname === '/' ? 'index.html' : pathname.slice(1)
const filePath = path.join(PUBLIC_DIR, rel)
if (!filePath.startsWith(PUBLIC_DIR)) return send(res, 403, 'Forbidden', 'text/plain')
try {
const buf = await fs.readFile(filePath)
const type = MIME[path.extname(filePath)] || 'application/octet-stream'
return send(res, 200, buf, type)
} catch {
return send(res, 404, 'Not found', 'text/plain')
}
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://localhost:${PORT}`)
try {
if (url.pathname.startsWith('/api/')) {
await handleApi(req, res, url)
} else {
await handleStatic(res, url.pathname)
}
} catch (e) {
sendJson(res, 500, { error: e.message })
}
})
server.on('error', (err) => {
if (err.code !== 'EADDRINUSE') throw err
if (process.env.JOTSON_PORT) {
console.error(`\n Port ${PORT} (JOTSON_PORT) is already in use.\n`)
process.exit(1)
}
server.listen(0, '127.0.0.1') // default port taken - let the OS assign a free one
})
server.listen(PORT, '127.0.0.1', () => {
const { port } = server.address()
console.log(`\n ${config.title === '' ? JOTSON_BRAND : JOTSON_BRAND + ' - ' + config.title}`)
if (port !== PORT) console.log(` Port ${PORT} is in use - using ${port} instead`)
console.log(` Editing: ${jsonDir()}`)
console.log(` Media: ${sitePublicDir()}`)
console.log(` Config: ${CONFIG_PATH}`)
console.log(`\n ➜ http://localhost:${port}\n`)
})