@conloca/content-api 0.1.16 → 0.2.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.
- package/dist/asset-constraints.d.ts +16 -0
- package/dist/asset-constraints.d.ts.map +1 -0
- package/dist/asset-constraints.js +29 -0
- package/dist/asset-constraints.js.map +1 -0
- package/dist/asset-metadata-store.d.ts +60 -0
- package/dist/asset-metadata-store.d.ts.map +1 -0
- package/dist/asset-metadata-store.js +335 -0
- package/dist/asset-metadata-store.js.map +1 -0
- package/dist/asset-operations.d.ts +21 -28
- package/dist/asset-operations.d.ts.map +1 -1
- package/dist/asset-operations.js +268 -305
- package/dist/asset-operations.js.map +1 -0
- package/dist/asset-types.d.ts +23 -7
- package/dist/asset-types.d.ts.map +1 -1
- package/dist/asset-types.js +8 -2
- package/dist/asset-types.js.map +1 -0
- package/dist/asset-usage.d.ts +11 -0
- package/dist/asset-usage.d.ts.map +1 -0
- package/dist/asset-usage.js +50 -0
- package/dist/asset-usage.js.map +1 -0
- package/dist/base-content-index.d.ts +8 -2
- package/dist/base-content-index.d.ts.map +1 -1
- package/dist/base-content-index.js +24 -3
- package/dist/base-content-index.js.map +1 -0
- package/dist/cf-access.js +1 -0
- package/dist/cf-access.js.map +1 -0
- package/dist/component-registry.d.ts +1 -1
- package/dist/component-registry.d.ts.map +1 -1
- package/dist/component-registry.js +2 -1
- package/dist/component-registry.js.map +1 -0
- package/dist/component-registry.types.js +1 -0
- package/dist/component-registry.types.js.map +1 -0
- package/dist/component-vocabulary.d.ts +33 -0
- package/dist/component-vocabulary.d.ts.map +1 -0
- package/dist/component-vocabulary.js +105 -0
- package/dist/component-vocabulary.js.map +1 -0
- package/dist/content-api.interface.d.ts +5 -5
- package/dist/content-api.interface.d.ts.map +1 -1
- package/dist/content-api.interface.js +1 -0
- package/dist/content-api.interface.js.map +1 -0
- package/dist/content-filters.d.ts +2 -2
- package/dist/content-filters.d.ts.map +1 -1
- package/dist/content-filters.js +9 -8
- package/dist/content-filters.js.map +1 -0
- package/dist/content-index.d.ts +74 -16
- package/dist/content-index.d.ts.map +1 -1
- package/dist/content-index.js +183 -55
- package/dist/content-index.js.map +1 -0
- package/dist/content-operations.d.ts +71 -7
- package/dist/content-operations.d.ts.map +1 -1
- package/dist/content-operations.js +166 -82
- package/dist/content-operations.js.map +1 -0
- package/dist/content-path.d.ts +64 -0
- package/dist/content-path.d.ts.map +1 -0
- package/dist/content-path.js +95 -0
- package/dist/content-path.js.map +1 -0
- package/dist/content-reader.d.ts +2 -2
- package/dist/content-reader.d.ts.map +1 -1
- package/dist/content-reader.js +2 -1
- package/dist/content-reader.js.map +1 -0
- package/dist/content-utils.d.ts +53 -10
- package/dist/content-utils.d.ts.map +1 -1
- package/dist/content-utils.js +103 -34
- package/dist/content-utils.js.map +1 -0
- package/dist/content-watcher.d.ts +3 -3
- package/dist/content-watcher.d.ts.map +1 -1
- package/dist/content-watcher.js +13 -10
- package/dist/content-watcher.js.map +1 -0
- package/dist/data-index.d.ts +1 -1
- package/dist/data-index.d.ts.map +1 -1
- package/dist/data-index.js +2 -1
- package/dist/data-index.js.map +1 -0
- package/dist/data.d.ts +5 -13
- package/dist/data.d.ts.map +1 -1
- package/dist/data.js +7 -6
- package/dist/data.js.map +1 -0
- package/dist/editor-data-bindings.d.ts +10 -0
- package/dist/editor-data-bindings.d.ts.map +1 -0
- package/dist/editor-data-bindings.js +67 -0
- package/dist/editor-data-bindings.js.map +1 -0
- package/dist/etag-utils.d.ts.map +1 -1
- package/dist/etag-utils.js +5 -4
- package/dist/etag-utils.js.map +1 -0
- package/dist/filesystem-content-api.d.ts +45 -18
- package/dist/filesystem-content-api.d.ts.map +1 -1
- package/dist/filesystem-content-api.js +455 -286
- package/dist/filesystem-content-api.js.map +1 -0
- package/dist/filesystem-reader-backend.d.ts +46 -0
- package/dist/filesystem-reader-backend.d.ts.map +1 -0
- package/dist/filesystem-reader-backend.js +119 -0
- package/dist/filesystem-reader-backend.js.map +1 -0
- package/dist/fragment-index.d.ts +8 -0
- package/dist/fragment-index.d.ts.map +1 -0
- package/dist/fragment-index.js +8 -0
- package/dist/fragment-index.js.map +1 -0
- package/dist/fragments.d.ts +16 -0
- package/dist/fragments.d.ts.map +1 -0
- package/dist/fragments.js +104 -0
- package/dist/fragments.js.map +1 -0
- package/dist/git-operations.d.ts.map +1 -1
- package/dist/git-operations.js +5 -1
- package/dist/git-operations.js.map +1 -0
- package/dist/header-parser.d.ts +4 -4
- package/dist/header-parser.d.ts.map +1 -1
- package/dist/header-parser.js +8 -61
- package/dist/header-parser.js.map +1 -0
- package/dist/in-memory-content-api.d.ts +7 -7
- package/dist/in-memory-content-api.d.ts.map +1 -1
- package/dist/in-memory-content-api.js +74 -56
- package/dist/in-memory-content-api.js.map +1 -0
- package/dist/index.d.ts +19 -12
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +21 -9
- package/dist/index.js.map +1 -0
- package/dist/indexing.d.ts +4 -4
- package/dist/indexing.d.ts.map +1 -1
- package/dist/indexing.js +6 -5
- package/dist/indexing.js.map +1 -0
- package/dist/json-whitespace-view.js +1 -0
- package/dist/json-whitespace-view.js.map +1 -0
- package/dist/middleware.d.ts +8 -6
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +178 -142
- package/dist/middleware.js.map +1 -0
- package/dist/node.d.ts +24 -17
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +17 -14
- package/dist/node.js.map +1 -0
- package/dist/page-references.d.ts +21 -0
- package/dist/page-references.d.ts.map +1 -0
- package/dist/page-references.js +50 -0
- package/dist/page-references.js.map +1 -0
- package/dist/read-date.d.ts +3 -0
- package/dist/read-date.d.ts.map +1 -0
- package/dist/read-date.js +9 -0
- package/dist/read-date.js.map +1 -0
- package/dist/reader-backend.d.ts +54 -0
- package/dist/reader-backend.d.ts.map +1 -0
- package/dist/reader-backend.js +2 -0
- package/dist/reader-backend.js.map +1 -0
- package/dist/reader.d.ts +8 -8
- package/dist/reader.d.ts.map +1 -1
- package/dist/reader.js +8 -7
- package/dist/reader.js.map +1 -0
- package/dist/schemas/index.d.ts +6 -6
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +9 -8
- package/dist/schemas/index.js.map +1 -0
- package/dist/site-index.d.ts +3 -3
- package/dist/site-index.d.ts.map +1 -1
- package/dist/site-index.js +9 -5
- package/dist/site-index.js.map +1 -0
- package/dist/site.d.ts +5 -3
- package/dist/site.d.ts.map +1 -1
- package/dist/site.js +14 -2
- package/dist/site.js.map +1 -0
- package/dist/types.d.ts +203 -15
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +9 -0
- package/dist/types.js.map +1 -0
- package/dist/url-safe-base64.js +1 -0
- package/dist/url-safe-base64.js.map +1 -0
- package/dist/url-validation.d.ts +14 -0
- package/dist/url-validation.d.ts.map +1 -1
- package/dist/url-validation.js +56 -14
- package/dist/url-validation.js.map +1 -0
- package/dist/utils/atomic-write.js +1 -0
- package/dist/utils/atomic-write.js.map +1 -0
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +2 -1
- package/dist/utils.js.map +1 -0
- package/dist/vite-plugin.d.ts +2 -2
- package/dist/vite-plugin.js +5 -4
- package/dist/vite-plugin.js.map +1 -0
- package/dist/vxjson-serialize.d.ts +5 -6
- package/dist/vxjson-serialize.d.ts.map +1 -1
- package/dist/vxjson-serialize.js +13 -10
- package/dist/vxjson-serialize.js.map +1 -0
- package/dist/vxjson.d.ts +4 -3
- package/dist/vxjson.d.ts.map +1 -1
- package/dist/vxjson.js +10 -20
- package/dist/vxjson.js.map +1 -0
- package/dist/xxhash.d.ts.map +1 -1
- package/dist/xxhash.js +6 -2
- package/dist/xxhash.js.map +1 -0
- package/package.json +92 -56
- package/src/asset-constraints.ts +33 -0
- package/src/asset-metadata-store.ts +401 -0
- package/src/asset-operations.ts +814 -0
- package/src/asset-types.ts +74 -0
- package/src/asset-usage.ts +48 -0
- package/src/base-content-index.ts +227 -0
- package/src/cf-access.ts +85 -0
- package/src/component-registry.ts +145 -0
- package/src/component-registry.types.ts +12 -0
- package/src/component-vocabulary.ts +87 -0
- package/src/content-api.interface.ts +94 -0
- package/src/content-filters.ts +278 -0
- package/src/content-index.ts +642 -0
- package/src/content-operations.ts +497 -0
- package/src/content-path.ts +121 -0
- package/src/content-reader.ts +18 -0
- package/src/content-utils.ts +474 -0
- package/src/content-watcher.ts +122 -0
- package/src/data-index.ts +7 -0
- package/src/data.ts +134 -0
- package/src/editor-data-bindings.ts +66 -0
- package/src/etag-utils.ts +204 -0
- package/src/filesystem-content-api.ts +2740 -0
- package/src/filesystem-reader-backend.ts +135 -0
- package/src/fragment-index.ts +7 -0
- package/src/fragments.ts +113 -0
- package/src/git-operations.ts +340 -0
- package/src/header-parser.ts +272 -0
- package/src/in-memory-content-api.ts +760 -0
- package/src/index.ts +45 -0
- package/src/indexing.ts +8 -0
- package/src/json-whitespace-view.ts +155 -0
- package/src/middleware.ts +1322 -0
- package/src/node.ts +40 -0
- package/src/page-references.ts +76 -0
- package/src/read-date.ts +7 -0
- package/src/reader-backend.ts +54 -0
- package/src/reader.ts +15 -0
- package/src/schemas/index.ts +113 -0
- package/src/site-index.ts +330 -0
- package/src/site.ts +198 -0
- package/src/types.ts +759 -0
- package/src/url-safe-base64.ts +38 -0
- package/src/url-validation.ts +121 -0
- package/src/utils/atomic-write.ts +20 -0
- package/src/utils.ts +84 -0
- package/src/vite-plugin.ts +45 -0
- package/src/vxjson-serialize.ts +66 -0
- package/src/vxjson.ts +442 -0
- package/src/xxhash.ts +43 -0
- package/dist/asset-manifest.d.ts +0 -23
- package/dist/asset-manifest.d.ts.map +0 -1
- package/dist/asset-manifest.js +0 -73
- package/dist/block-index.d.ts +0 -9
- package/dist/block-index.d.ts.map +0 -1
- package/dist/block-index.js +0 -11
- package/dist/blocks.d.ts +0 -16
- package/dist/blocks.d.ts.map +0 -1
- package/dist/blocks.js +0 -103
- package/dist/component-registry.types-C0ctF9nh.d.mts +0 -71
- package/dist/component-registry.types-C0ctF9nh.d.mts.map +0 -1
- package/dist/content-index-D092_vk1.mjs +0 -629
- package/dist/content-index-D092_vk1.mjs.map +0 -1
- package/dist/content-index-D6IVMmAB.d.mts +0 -127
- package/dist/content-index-D6IVMmAB.d.mts.map +0 -1
- package/dist/content-operations-DIbsxG5A.d.mts +0 -354
- package/dist/content-operations-DIbsxG5A.d.mts.map +0 -1
- package/dist/content-utils-fWNHTrPy.mjs +0 -280
- package/dist/content-utils-fWNHTrPy.mjs.map +0 -1
- package/dist/data-DquNIEnQ.mjs +0 -62
- package/dist/data-DquNIEnQ.mjs.map +0 -1
- package/dist/filesystem-content-api-B1KIQJfk.mjs +0 -2
- package/dist/filesystem-content-api-C0HIhqZi.mjs +0 -1620
- package/dist/filesystem-content-api-C0HIhqZi.mjs.map +0 -1
- package/dist/filesystem-content-api-DCdNi-co.d.mts +0 -134
- package/dist/filesystem-content-api-DCdNi-co.d.mts.map +0 -1
- package/dist/index-DxVTFK66.d.mts +0 -105
- package/dist/index-DxVTFK66.d.mts.map +0 -1
- package/dist/index.d.mts +0 -80
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -78
- package/dist/index.mjs.map +0 -1
- package/dist/indexing.d.mts +0 -152
- package/dist/indexing.d.mts.map +0 -1
- package/dist/indexing.mjs +0 -255
- package/dist/indexing.mjs.map +0 -1
- package/dist/node.d.mts +0 -373
- package/dist/node.d.mts.map +0 -1
- package/dist/node.mjs +0 -2572
- package/dist/node.mjs.map +0 -1
- package/dist/reader.d.mts +0 -15
- package/dist/reader.d.mts.map +0 -1
- package/dist/reader.mjs +0 -22
- package/dist/reader.mjs.map +0 -1
- package/dist/schemas/index.d.mts +0 -2
- package/dist/schemas/index.mjs +0 -2
- package/dist/schemas-CFRD0FIQ.mjs +0 -84
- package/dist/schemas-CFRD0FIQ.mjs.map +0 -1
- package/dist/site-8oaj1Q60.mjs +0 -366
- package/dist/site-8oaj1Q60.mjs.map +0 -1
- package/dist/site-index-B_254bCc.d.mts +0 -136
- package/dist/site-index-B_254bCc.d.mts.map +0 -1
- package/dist/types-DOdldbfD.mjs +0 -34
- package/dist/types-DOdldbfD.mjs.map +0 -1
- package/dist/types-DjfhS272.d.mts +0 -456
- package/dist/types-DjfhS272.d.mts.map +0 -1
- package/dist/vxjson-qHrgLGip.mjs +0 -555
- package/dist/vxjson-qHrgLGip.mjs.map +0 -1
- package/dist/vxjson-serialize-geF6qvpn.mjs +0 -34
- package/dist/vxjson-serialize-geF6qvpn.mjs.map +0 -1
- package/dist/vxjson-serialize.d.mts +0 -17
- package/dist/vxjson-serialize.d.mts.map +0 -1
- package/dist/vxjson-serialize.mjs +0 -2
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, rename, unlink } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
ASSET_METADATA_DIR,
|
|
6
|
+
type AssetManifestData,
|
|
7
|
+
type AssetMetadata,
|
|
8
|
+
type AssetMetadataPatch,
|
|
9
|
+
} from './asset-types.js';
|
|
10
|
+
import { applyNullClearPatch } from './content-utils.js';
|
|
11
|
+
import type { JsonValue } from './types.js';
|
|
12
|
+
import { atomicWriteFile } from './utils/atomic-write.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The two folders the store works across. One metadata record per asset, so
|
|
16
|
+
* two people annotating two pictures cannot touch each other's work: two
|
|
17
|
+
* pictures are two files. The records live in ASSET_METADATA_DIR under the
|
|
18
|
+
* content root, committed with the content they describe, and never inside the
|
|
19
|
+
* media folder: a site serves that folder as it is, dotfiles included, so a
|
|
20
|
+
* record written there is published. The media folder is read only to find a
|
|
21
|
+
* pre-0.2 manifest.
|
|
22
|
+
*/
|
|
23
|
+
export interface MetadataRoots {
|
|
24
|
+
assetsPath: string;
|
|
25
|
+
contentRoot: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The pre-0.2 shared manifest, read once by the migration and then moved to the records directory */
|
|
29
|
+
const LEGACY_MANIFEST = '.asset-manifest.json';
|
|
30
|
+
|
|
31
|
+
/** The legacy manifest's copy once migrated. Never deleted: it is the only way back */
|
|
32
|
+
const MIGRATED_MANIFEST = `${LEGACY_MANIFEST}.migrated`;
|
|
33
|
+
|
|
34
|
+
/** The fields a person owns. Anything else on an older entry (cached sizes) is dropped */
|
|
35
|
+
const STORED_FIELDS = ['alt', 'tags', 'uploadedAt', 'uploadedBy', 'originalName'] as const;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* One promise chain per record path, so a read-modify-write on one record is
|
|
39
|
+
* never interleaved with another in this process. Anchored on a global symbol
|
|
40
|
+
* rather than on module identity: a dev server can end up holding two copies of
|
|
41
|
+
* this module, and a module-level Map would then split into two locks — the
|
|
42
|
+
* exact fault this file repairs.
|
|
43
|
+
*
|
|
44
|
+
* Scope claim, stated honestly: this serialises writers INSIDE one process.
|
|
45
|
+
* Across processes, safety comes from the shape of the data — two assets are
|
|
46
|
+
* two files — not from this.
|
|
47
|
+
*/
|
|
48
|
+
declare global {
|
|
49
|
+
// Shared across duplicate module instances in one dev-server process.
|
|
50
|
+
var conlocaAssetMetadataChains: Map<string, Promise<unknown>> | undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function sharedChains(): Map<string, Promise<unknown>> {
|
|
54
|
+
globalThis.conlocaAssetMetadataChains ??= new Map<string, Promise<unknown>>();
|
|
55
|
+
return globalThis.conlocaAssetMetadataChains;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const chains = sharedChains();
|
|
59
|
+
|
|
60
|
+
function isNotFoundError(error: Error): boolean {
|
|
61
|
+
return 'code' in error && error.code === 'ENOENT';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function serialize<T>(key: string, fn: () => Promise<T>): Promise<T> {
|
|
65
|
+
const previous = chains.get(key) ?? Promise.resolve();
|
|
66
|
+
// Run whether or not the previous holder failed, and keep a guarded copy in
|
|
67
|
+
// the map so the chain itself can never reject and strand later arrivals.
|
|
68
|
+
const mine = previous.then(fn, fn);
|
|
69
|
+
const guarded = mine.catch(() => {});
|
|
70
|
+
chains.set(key, guarded);
|
|
71
|
+
try {
|
|
72
|
+
return await mine;
|
|
73
|
+
} finally {
|
|
74
|
+
// Delete only OUR entry. A bare delete lets a finishing writer drop a LATER
|
|
75
|
+
// writer's chain, and the next arrival then runs alongside it.
|
|
76
|
+
if (chains.get(key) === guarded) chains.delete(key);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function relativeMetadataFolder(folder: string): string {
|
|
81
|
+
return folder.replace(/^\/+|\/+$/g, '');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The metadata directory, under the content root */
|
|
85
|
+
function recordsRoot(roots: MetadataRoots): string {
|
|
86
|
+
return resolve(roots.contentRoot, ASSET_METADATA_DIR);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Keep a path inside the metadata directory, or refuse it.
|
|
91
|
+
*
|
|
92
|
+
* Asset paths arrive from an HTTP route, and this store now deletes and
|
|
93
|
+
* overwrites real files rather than keys in one shared document: without this,
|
|
94
|
+
* `../sites` names a file that has nothing to do with the media library.
|
|
95
|
+
*/
|
|
96
|
+
function containedPath(roots: MetadataRoots, unsafePath: string): string {
|
|
97
|
+
const root = recordsRoot(roots);
|
|
98
|
+
const full = resolve(root, unsafePath);
|
|
99
|
+
if (full !== root && !full.startsWith(root + sep)) {
|
|
100
|
+
throw new Error(`Path traversal detected: ${unsafePath} is outside the asset metadata directory`);
|
|
101
|
+
}
|
|
102
|
+
return full;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Where one asset's record lives: the asset's own path, mirrored under the metadata directory */
|
|
106
|
+
export function recordPath(roots: MetadataRoots, relativePath: string): string {
|
|
107
|
+
return containedPath(roots, `${relativePath}.json`);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The serialiser key is the record's own path, already resolved, so two callers configured with different spellings of one directory share a lock */
|
|
111
|
+
function lockKey(roots: MetadataRoots, relativePath: string): string {
|
|
112
|
+
return recordPath(roots, relativePath);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* What one record's bytes turned out to be. `damaged` is deliberately distinct
|
|
117
|
+
* from `absent`: reading may treat the two alike, but writing may not — an
|
|
118
|
+
* overwrite of bytes we failed to parse destroys whatever alt text, original
|
|
119
|
+
* name and upload date are still in them, which is the exact defect this store
|
|
120
|
+
* exists to remove.
|
|
121
|
+
*/
|
|
122
|
+
type StoredRecord = { state: 'ok'; metadata: AssetMetadata } | { state: 'absent' } | { state: 'damaged' };
|
|
123
|
+
|
|
124
|
+
type ParsedJson = JsonValue | AssetMetadata | AssetManifestData;
|
|
125
|
+
|
|
126
|
+
/** Validate known fields without dropping forward-compatible extension fields. */
|
|
127
|
+
function isAssetMetadata(value: ParsedJson): value is AssetMetadata {
|
|
128
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
129
|
+
if ('alt' in value && typeof value.alt !== 'string') return false;
|
|
130
|
+
if ('uploadedAt' in value && typeof value.uploadedAt !== 'string') return false;
|
|
131
|
+
if ('uploadedBy' in value && typeof value.uploadedBy !== 'string') return false;
|
|
132
|
+
if ('originalName' in value && typeof value.originalName !== 'string') return false;
|
|
133
|
+
return !('tags' in value) || (Array.isArray(value.tags) && value.tags.every((tag) => typeof tag === 'string'));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function isLegacyManifest(value: ParsedJson): value is AssetManifestData {
|
|
137
|
+
return (
|
|
138
|
+
value !== null && typeof value === 'object' && !Array.isArray(value) && Object.values(value).every(isAssetMetadata)
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function parseRecord(raw: string, path: string): StoredRecord {
|
|
143
|
+
if (raw.trim() === '') {
|
|
144
|
+
console.warn(`[asset-metadata] empty record ${path} — reading the asset as having no metadata`);
|
|
145
|
+
return { state: 'damaged' };
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
const metadata: ParsedJson = JSON.parse(raw);
|
|
149
|
+
if (!isAssetMetadata(metadata)) throw new Error('Invalid asset metadata shape');
|
|
150
|
+
return { state: 'ok', metadata };
|
|
151
|
+
} catch {
|
|
152
|
+
console.warn(`[asset-metadata] unreadable record ${path} — reading the asset as having no metadata`);
|
|
153
|
+
return { state: 'damaged' };
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function readLegacyManifest(roots: MetadataRoots): Promise<AssetManifestData | undefined> {
|
|
158
|
+
try {
|
|
159
|
+
const manifest: ParsedJson = JSON.parse(await readFile(join(roots.assetsPath, LEGACY_MANIFEST), 'utf-8'));
|
|
160
|
+
return isLegacyManifest(manifest) ? manifest : undefined;
|
|
161
|
+
} catch {
|
|
162
|
+
return undefined;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Read one record straight off disk, without waiting on the serialiser: a rename is atomic, so no read sees half a file */
|
|
167
|
+
async function readRecord(roots: MetadataRoots, relativePath: string): Promise<StoredRecord> {
|
|
168
|
+
const path = recordPath(roots, relativePath);
|
|
169
|
+
let raw: string;
|
|
170
|
+
try {
|
|
171
|
+
raw = await readFile(path, 'utf-8');
|
|
172
|
+
} catch (error) {
|
|
173
|
+
// A record that exists but cannot be opened holds bytes nobody has seen;
|
|
174
|
+
// reading it as absent would let the next save replace them
|
|
175
|
+
if (error instanceof Error && isNotFoundError(error)) return { state: 'absent' };
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
return parseRecord(raw, path);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* One asset's metadata. Until the first write migrates it, an asset with no
|
|
183
|
+
* record of its own still answers out of the legacy manifest, so upgrading and
|
|
184
|
+
* browsing shows everything it showed before.
|
|
185
|
+
*/
|
|
186
|
+
export async function read(roots: MetadataRoots, relativePath: string): Promise<AssetMetadata | undefined> {
|
|
187
|
+
const record = await readRecord(roots, relativePath);
|
|
188
|
+
if (record.state === 'ok') return record.metadata;
|
|
189
|
+
// Damaged reads as nothing rather than falling through to the legacy file:
|
|
190
|
+
// showing stale metadata for a record we cannot parse would misrepresent what
|
|
191
|
+
// is on disk, and the warning has already named the file. Writing refuses.
|
|
192
|
+
if (record.state === 'damaged') return undefined;
|
|
193
|
+
return (await readLegacyManifest(roots))?.[relativePath];
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Every record in one folder, keyed by path relative to the assets root */
|
|
197
|
+
export async function readFolder(roots: MetadataRoots, folder: string): Promise<Map<string, AssetMetadata>> {
|
|
198
|
+
const prefix = relativeMetadataFolder(folder);
|
|
199
|
+
const records = new Map<string, AssetMetadata>();
|
|
200
|
+
const presentRecords = new Set<string>();
|
|
201
|
+
|
|
202
|
+
let dir: string;
|
|
203
|
+
try {
|
|
204
|
+
dir = containedPath(roots, prefix);
|
|
205
|
+
} catch {
|
|
206
|
+
// Nothing outside the metadata directory is ours to read out of
|
|
207
|
+
return records;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
let filenames: string[];
|
|
211
|
+
try {
|
|
212
|
+
filenames = await readdir(dir);
|
|
213
|
+
} catch (error) {
|
|
214
|
+
// Only a missing directory permits legacy fallback; unreadable is not absent.
|
|
215
|
+
if (!(error instanceof Error && isNotFoundError(error))) return records;
|
|
216
|
+
filenames = [];
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const loaded = await Promise.all(
|
|
220
|
+
filenames
|
|
221
|
+
.filter((filename) => filename.endsWith('.json'))
|
|
222
|
+
.map(async (filename) => {
|
|
223
|
+
const assetName = filename.slice(0, -'.json'.length);
|
|
224
|
+
const relativePath = prefix ? `${prefix}/${assetName}` : assetName;
|
|
225
|
+
const path = join(dir, filename);
|
|
226
|
+
try {
|
|
227
|
+
return [relativePath, parseRecord(await readFile(path, 'utf-8'), path)] as const;
|
|
228
|
+
} catch {
|
|
229
|
+
return [relativePath, { state: 'absent' } satisfies StoredRecord] as const;
|
|
230
|
+
}
|
|
231
|
+
}),
|
|
232
|
+
);
|
|
233
|
+
for (const [relativePath, record] of loaded) {
|
|
234
|
+
presentRecords.add(relativePath);
|
|
235
|
+
if (record.state === 'ok') records.set(relativePath, record.metadata);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const legacy = await readLegacyManifest(roots);
|
|
239
|
+
if (legacy) {
|
|
240
|
+
for (const [relativePath, entry] of Object.entries(legacy)) {
|
|
241
|
+
const slash = relativePath.lastIndexOf('/');
|
|
242
|
+
const entryFolder = slash > 0 ? relativePath.slice(0, slash) : '';
|
|
243
|
+
// An unreadable record is not absent: never revive the older manifest value.
|
|
244
|
+
if (entryFolder === prefix && !presentRecords.has(relativePath)) records.set(relativePath, entry);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return records;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function writeRecord(roots: MetadataRoots, relativePath: string, metadata: AssetMetadata): Promise<void> {
|
|
252
|
+
const path = recordPath(roots, relativePath);
|
|
253
|
+
await mkdir(dirname(path), { recursive: true });
|
|
254
|
+
await atomicWriteFile(path, JSON.stringify(metadata, null, 2));
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Replace an asset's record wholesale. Upload uses this: a new file must not inherit the previous occupant's alt text */
|
|
258
|
+
export async function write(roots: MetadataRoots, relativePath: string, metadata: AssetMetadata): Promise<void> {
|
|
259
|
+
await serialize(lockKey(roots, relativePath), () => writeRecord(roots, relativePath, metadata));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Merge a patch into an asset's record and return the merged value, so a caller
|
|
264
|
+
* never has to read back what it just wrote. Read and write happen as one unit.
|
|
265
|
+
*/
|
|
266
|
+
export async function update(
|
|
267
|
+
roots: MetadataRoots,
|
|
268
|
+
relativePath: string,
|
|
269
|
+
patch: AssetMetadataPatch,
|
|
270
|
+
): Promise<AssetMetadata> {
|
|
271
|
+
return serialize(lockKey(roots, relativePath), async () => {
|
|
272
|
+
const record = await readRecord(roots, relativePath);
|
|
273
|
+
if (record.state === 'damaged') {
|
|
274
|
+
// Refusing loudly is the whole point: merging onto `{}` here would write
|
|
275
|
+
// away the alt text and upload date still sitting in the bytes we could
|
|
276
|
+
// not parse, and report success. The file is left untouched so it can be
|
|
277
|
+
// repaired by hand.
|
|
278
|
+
throw new Error(
|
|
279
|
+
`Asset metadata for ${relativePath} is unreadable; refusing to overwrite it. Repair or delete ${recordPath(roots, relativePath)} and try again.`,
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
const existing =
|
|
283
|
+
record.state === 'ok' ? record.metadata : ((await readLegacyManifest(roots))?.[relativePath] ?? {});
|
|
284
|
+
const merged: AssetMetadata = applyNullClearPatch(existing, patch);
|
|
285
|
+
await writeRecord(roots, relativePath, merged);
|
|
286
|
+
return merged;
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** Drop an asset's record. Already gone counts as done */
|
|
291
|
+
export async function remove(roots: MetadataRoots, relativePath: string): Promise<void> {
|
|
292
|
+
await serialize(lockKey(roots, relativePath), async () => {
|
|
293
|
+
try {
|
|
294
|
+
await unlink(recordPath(roots, relativePath));
|
|
295
|
+
} catch (error) {
|
|
296
|
+
if (!(error instanceof Error && isNotFoundError(error))) throw error;
|
|
297
|
+
}
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Carry an asset's record to its new path. Locks are taken in sorted order so two moves cannot deadlock */
|
|
302
|
+
export async function move(roots: MetadataRoots, from: string, to: string): Promise<void> {
|
|
303
|
+
const fromKey = lockKey(roots, from);
|
|
304
|
+
const toKey = lockKey(roots, to);
|
|
305
|
+
// Both ends are the same record: there is nothing to carry, and taking that
|
|
306
|
+
// one lock twice would wait on a lock this call is already holding — a wait
|
|
307
|
+
// that never ends, and that strands every later save on the same picture.
|
|
308
|
+
if (fromKey === toKey) return;
|
|
309
|
+
|
|
310
|
+
const [first, second] = fromKey < toKey ? [fromKey, toKey] : [toKey, fromKey];
|
|
311
|
+
await serialize(first, () =>
|
|
312
|
+
serialize(second, async () => {
|
|
313
|
+
const target = recordPath(roots, to);
|
|
314
|
+
await mkdir(dirname(target), { recursive: true });
|
|
315
|
+
try {
|
|
316
|
+
await rename(recordPath(roots, from), target);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (!(error instanceof Error && isNotFoundError(error))) throw error;
|
|
319
|
+
// ENOENT can also mean the destination disappeared, not that the source is absent.
|
|
320
|
+
if ((await readRecord(roots, from)).state !== 'absent') throw error;
|
|
321
|
+
}
|
|
322
|
+
}),
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Fold a pre-0.2 shared manifest into per-asset records, once, on the first
|
|
328
|
+
* write a person makes. Never on install or start-up: an upgrade that has not
|
|
329
|
+
* been asked to change anything changes nothing.
|
|
330
|
+
*
|
|
331
|
+
* A record that already parses wins — it is newer than the manifest. The
|
|
332
|
+
* manifest leaves the media folder only after every record is on disk, so a
|
|
333
|
+
* crash anywhere above leaves it in place and the next write tries again.
|
|
334
|
+
*/
|
|
335
|
+
export async function migrateLegacyManifest(roots: MetadataRoots): Promise<void> {
|
|
336
|
+
const legacyPath = join(roots.assetsPath, LEGACY_MANIFEST);
|
|
337
|
+
|
|
338
|
+
await serialize(resolve(legacyPath), async () => {
|
|
339
|
+
let raw: string;
|
|
340
|
+
try {
|
|
341
|
+
raw = await readFile(legacyPath, 'utf-8');
|
|
342
|
+
} catch (error) {
|
|
343
|
+
if (error instanceof Error && isNotFoundError(error)) return;
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
let legacy: AssetManifestData;
|
|
348
|
+
try {
|
|
349
|
+
const parsed: ParsedJson = JSON.parse(raw);
|
|
350
|
+
if (!isLegacyManifest(parsed)) throw new Error('Invalid asset metadata manifest shape');
|
|
351
|
+
legacy = parsed;
|
|
352
|
+
} catch (error) {
|
|
353
|
+
// Refuse rather than treat it as empty: an unreadable manifest that reads
|
|
354
|
+
// as {} is how every asset's metadata gets written over by the next save.
|
|
355
|
+
throw new Error(
|
|
356
|
+
`Cannot migrate ${LEGACY_MANIFEST}: it is not a valid metadata manifest (${legacyPath}). ` +
|
|
357
|
+
`Fix or remove the file and try again. Cause: ${error instanceof Error ? error.message : 'parse error'}`,
|
|
358
|
+
{ cause: error },
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
await Promise.all(
|
|
363
|
+
Object.entries(legacy).map(async ([relativePath, entry]) => {
|
|
364
|
+
let key: string;
|
|
365
|
+
try {
|
|
366
|
+
key = lockKey(roots, relativePath);
|
|
367
|
+
} catch {
|
|
368
|
+
// One bad key is not a reason to strand every other picture's metadata.
|
|
369
|
+
console.warn(`[asset-metadata] skipping legacy entry ${relativePath} — it points outside the media library`);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
await serialize(key, async () => {
|
|
374
|
+
// Each asset has its own lock and record; independent migrations can run together.
|
|
375
|
+
// This migration is the one safe repair window for a damaged record: afterwards the
|
|
376
|
+
// legacy source is removed, and ordinary updates deliberately refuse to overwrite
|
|
377
|
+
// bytes they cannot parse. A record that already parses is newer and always wins.
|
|
378
|
+
if ((await readRecord(roots, relativePath)).state === 'ok') return;
|
|
379
|
+
const metadata: AssetMetadata = {};
|
|
380
|
+
for (const field of STORED_FIELDS) {
|
|
381
|
+
const value = entry[field];
|
|
382
|
+
if (value !== undefined) Object.assign(metadata, { [field]: value });
|
|
383
|
+
}
|
|
384
|
+
await writeRecord(roots, relativePath, metadata);
|
|
385
|
+
});
|
|
386
|
+
}),
|
|
387
|
+
);
|
|
388
|
+
|
|
389
|
+
// Copied, then removed, rather than renamed: the content root can sit on
|
|
390
|
+
// another disk than the media folder, and a rename cannot cross disks
|
|
391
|
+
const backup = join(recordsRoot(roots), MIGRATED_MANIFEST);
|
|
392
|
+
await mkdir(dirname(backup), { recursive: true });
|
|
393
|
+
await atomicWriteFile(backup, raw);
|
|
394
|
+
try {
|
|
395
|
+
await unlink(legacyPath);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
// A concurrent first-write may have removed it already; anything else is real
|
|
398
|
+
if (!(error instanceof Error && isNotFoundError(error))) throw error;
|
|
399
|
+
}
|
|
400
|
+
});
|
|
401
|
+
}
|