@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,1322 @@
|
|
|
1
|
+
import { type Context, Hono } from 'hono';
|
|
2
|
+
import { type AssetConfig, AssetOperations } from './asset-operations.js';
|
|
3
|
+
import { findAssetUsage } from './asset-usage.js';
|
|
4
|
+
import type { ContentAPI } from './content-api.interface.js';
|
|
5
|
+
import { normalizeAndValidatePathname } from './content-utils.js';
|
|
6
|
+
import { createGitOperations, type GitAuthor, type GitConfig } from './git-operations.js';
|
|
7
|
+
import type {
|
|
8
|
+
APIError,
|
|
9
|
+
CreateResult,
|
|
10
|
+
DeleteResult,
|
|
11
|
+
ErrorCode,
|
|
12
|
+
FindOptions,
|
|
13
|
+
GlobalFilters,
|
|
14
|
+
UpdateResult,
|
|
15
|
+
} from './types.js';
|
|
16
|
+
import { ErrorCodes } from './types.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Helper to create standardized error responses
|
|
20
|
+
*/
|
|
21
|
+
function errorResponse(code: ErrorCode, message: string, details?: any): APIError {
|
|
22
|
+
return {
|
|
23
|
+
error: {
|
|
24
|
+
code,
|
|
25
|
+
message,
|
|
26
|
+
...(details && { details }),
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Helper to log and create error responses for unexpected errors
|
|
33
|
+
*/
|
|
34
|
+
function logAndCreateErrorResponse(error: unknown, code: ErrorCode, message: string, details?: any): APIError {
|
|
35
|
+
console.error(`[Content API] ${message}:`, error);
|
|
36
|
+
return errorResponse(code, message, details);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function errorMessage(error: unknown, fallback: string): string {
|
|
40
|
+
return error instanceof Error ? error.message : fallback;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A reason a create or an update refuses, other than those each route answers itself. */
|
|
44
|
+
type Refusal = Exclude<
|
|
45
|
+
NonNullable<CreateResult['reason'] | UpdateResult['reason']>,
|
|
46
|
+
'write_error' | 'stale_write' | 'not_found'
|
|
47
|
+
>;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* How a refused create or update answers, by reason: the error code, the HTTP status and the
|
|
51
|
+
* message when the backend gave none. 409 when another entry has the path or name, or a page
|
|
52
|
+
* redirects from the path; 400 when the caller can fix the input. A caller that can fix it by
|
|
53
|
+
* changing one field is told which one (`details.field`), so none of these falls through to a 500
|
|
54
|
+
* whose only clue is a raw error string.
|
|
55
|
+
*/
|
|
56
|
+
const refusals: Record<Refusal, { code: ErrorCode; status: 400 | 409; message: string }> = {
|
|
57
|
+
already_exists: { code: ErrorCodes.ALREADY_EXISTS, status: 409, message: 'Content already exists' },
|
|
58
|
+
name_taken: { code: ErrorCodes.NAME_TAKEN, status: 409, message: 'A fragment with that name already exists' },
|
|
59
|
+
pathname_taken: { code: ErrorCodes.PATHNAME_TAKEN, status: 409, message: 'Pathname already taken' },
|
|
60
|
+
pathname_in_redirects: {
|
|
61
|
+
code: ErrorCodes.PATHNAME_TAKEN,
|
|
62
|
+
status: 409,
|
|
63
|
+
message: 'Pathname is already in use as a redirect',
|
|
64
|
+
},
|
|
65
|
+
invalid_name: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Invalid name' },
|
|
66
|
+
invalid_collection: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Invalid collection' },
|
|
67
|
+
invalid_locale: { code: ErrorCodes.INVALID_LOCALE, status: 400, message: 'Invalid locale' },
|
|
68
|
+
invalid_pathname: { code: ErrorCodes.INVALID_PATHNAME, status: 400, message: 'Invalid pathname' },
|
|
69
|
+
metadata_too_large: { code: ErrorCodes.METADATA_TOO_LARGE, status: 400, message: 'Metadata too large' },
|
|
70
|
+
missing_field: { code: ErrorCodes.MISSING_REQUIRED_FIELD, status: 400, message: 'Missing required field' },
|
|
71
|
+
// Site resolution failing, not a bad field: with no sites configured at all, no value the caller
|
|
72
|
+
// could send would satisfy it.
|
|
73
|
+
no_sites_configured: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Site not found' },
|
|
74
|
+
unknown_site: { code: ErrorCodes.INVALID_REQUEST, status: 400, message: 'Site not found' },
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function refusalOf(reason: string | undefined) {
|
|
78
|
+
return reason !== undefined && Object.hasOwn(refusals, reason) ? refusals[reason as Refusal] : undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Whether a request is a write another website made the browser send. The routes write into the
|
|
83
|
+
* project, and any page open in the browser can make it send a form post without asking the
|
|
84
|
+
* server first. The browser says where a request comes from: `Sec-Fetch-Site`, or in older
|
|
85
|
+
* browsers the `Origin` of the page, which for the editor is the address it sent the request to
|
|
86
|
+
* (the `Host`). A request with neither did not come from a web page.
|
|
87
|
+
*/
|
|
88
|
+
function isCrossSiteWrite(c: Context): boolean {
|
|
89
|
+
if (c.req.method === 'GET' || c.req.method === 'HEAD' || c.req.method === 'OPTIONS') return false;
|
|
90
|
+
const fetchSite = c.req.header('Sec-Fetch-Site');
|
|
91
|
+
if (fetchSite !== undefined) return fetchSite !== 'same-origin';
|
|
92
|
+
const origin = c.req.header('Origin');
|
|
93
|
+
if (origin === undefined) return false;
|
|
94
|
+
return !URL.canParse(origin) || new URL(origin).host !== c.req.header('Host');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Create REST API router using Hono. Routes address content by id rather than
|
|
99
|
+
* by file path, so storage layout stays an implementation detail.
|
|
100
|
+
*/
|
|
101
|
+
export interface ContentAPIRouterOptions {
|
|
102
|
+
assetsPath?: string;
|
|
103
|
+
/** Where the site serves `assetsPath`, which begins every image link the editor stores; `/assets` when unset */
|
|
104
|
+
assetRefBase?: string;
|
|
105
|
+
assetConfig?: Omit<AssetConfig, 'assetsPath' | 'contentRoot'>;
|
|
106
|
+
/** Content root directory: holds asset metadata records, is scanned for asset usage, and is where git runs */
|
|
107
|
+
contentRoot?: string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function createContentAPIRouter(api: ContentAPI, options?: ContentAPIRouterOptions) {
|
|
111
|
+
const app = new Hono();
|
|
112
|
+
|
|
113
|
+
// The editor calls these routes from the page they are served with, so no other origin is
|
|
114
|
+
// granted access (no CORS headers), and a write another website sends is refused.
|
|
115
|
+
app.use('/*', async (c, next) => {
|
|
116
|
+
if (!isCrossSiteWrite(c)) return next();
|
|
117
|
+
return c.json(errorResponse(ErrorCodes.FORBIDDEN, 'Refused a write another website sent through the browser'), 403);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// GET /auth/user - Get current authenticated user
|
|
121
|
+
app.get('/auth/user', async (c) => {
|
|
122
|
+
const email = c.req.header('X-CF-User-Email');
|
|
123
|
+
const sub = c.req.header('X-CF-User-Sub');
|
|
124
|
+
|
|
125
|
+
if (!email) {
|
|
126
|
+
return c.json({ authenticated: false });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return c.json({
|
|
130
|
+
authenticated: true,
|
|
131
|
+
user: { email, sub },
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// GET /content/collections - List all collections across all sites
|
|
136
|
+
app.get('/content/collections', async (c) => {
|
|
137
|
+
try {
|
|
138
|
+
const allCollections = new Set<string>();
|
|
139
|
+
|
|
140
|
+
// Get collections from fragments
|
|
141
|
+
const fragmentCollections = api.fragments.collections;
|
|
142
|
+
for (const collection of fragmentCollections) {
|
|
143
|
+
allCollections.add(collection);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Get collections from all sites
|
|
147
|
+
for (const siteName of Object.keys(api.sitesConfig.sites)) {
|
|
148
|
+
const site = api.getSite(siteName);
|
|
149
|
+
if (site) {
|
|
150
|
+
const siteCollections = site.collections;
|
|
151
|
+
for (const collection of siteCollections) {
|
|
152
|
+
allCollections.add(collection);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return c.json({
|
|
158
|
+
collections: Array.from(allCollections).sort(),
|
|
159
|
+
});
|
|
160
|
+
} catch (error) {
|
|
161
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list collections'), 500);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// GET /content - List all content with optional filters
|
|
166
|
+
app.get('/content', async (c) => {
|
|
167
|
+
const kind = c.req.query('kind'); // 'fragment' or 'page'
|
|
168
|
+
const site = c.req.query('site');
|
|
169
|
+
const collection = c.req.query('collection');
|
|
170
|
+
const locales = c.req.query('locales'); // comma-separated
|
|
171
|
+
const type = c.req.query('type'); // 'puck' or 'mdx'
|
|
172
|
+
const published = c.req.query('published');
|
|
173
|
+
const localization = c.req.query('localization'); // 'complete', 'partial', 'one'
|
|
174
|
+
const missingLocales = c.req.query('missingLocales'); // comma-separated
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
const filters: GlobalFilters = {};
|
|
178
|
+
|
|
179
|
+
// Pass all filters to the API - let it handle the logic
|
|
180
|
+
if (kind) filters.kind = kind as GlobalFilters['kind'];
|
|
181
|
+
if (site) filters.site = site;
|
|
182
|
+
if (collection) filters.collection = collection;
|
|
183
|
+
if (locales) filters.locales = locales.split(',').map((l) => l.trim());
|
|
184
|
+
if (type) filters.type = type as GlobalFilters['type'];
|
|
185
|
+
if (published !== undefined) filters.published = published === 'true';
|
|
186
|
+
if (localization) filters.localization = localization as GlobalFilters['localization'];
|
|
187
|
+
if (missingLocales) filters.missingLocales = missingLocales.split(',').map((l) => l.trim());
|
|
188
|
+
|
|
189
|
+
const items = Array.from(api.listAllContent(filters));
|
|
190
|
+
return c.json({ items, total: items.length });
|
|
191
|
+
} catch (error) {
|
|
192
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list content'), 500);
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// GET /content/:id - Get all locales for content ID
|
|
197
|
+
app.get('/content/:id', async (c) => {
|
|
198
|
+
const id = c.req.param('id');
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const content = await api.getContent(id);
|
|
202
|
+
|
|
203
|
+
if (!content) {
|
|
204
|
+
return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return c.json(content);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch content'), 500);
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// GET /content/:id/:locale - Get specific locale only
|
|
214
|
+
app.get('/content/:id/:locale', async (c) => {
|
|
215
|
+
const id = c.req.param('id');
|
|
216
|
+
const locale = c.req.param('locale');
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
const content = await api.getLocalized(id, locale);
|
|
220
|
+
|
|
221
|
+
if (!content) {
|
|
222
|
+
return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Set ETag header
|
|
226
|
+
c.header('ETag', content.localized.etag);
|
|
227
|
+
|
|
228
|
+
return c.json(content);
|
|
229
|
+
} catch (error) {
|
|
230
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch localized content'), 500);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
// POST /content - Create new content
|
|
235
|
+
app.post('/content', async (c) => {
|
|
236
|
+
try {
|
|
237
|
+
const data = await c.req.json();
|
|
238
|
+
const result = await api.createContent(data);
|
|
239
|
+
|
|
240
|
+
if (!result.success) {
|
|
241
|
+
// Map structured CreateResult failures onto the standard error
|
|
242
|
+
// envelope so the client can decode `error.code` / `error.message`
|
|
243
|
+
// and surface them in the UI. Without the envelope the client falls
|
|
244
|
+
// back to a generic "API error: 500" string and inline error copy
|
|
245
|
+
// like "already exists" never reaches the user.
|
|
246
|
+
const errMessage = (result.error instanceof Error ? result.error.message : undefined) ?? '';
|
|
247
|
+
const fieldDetails = result.field ? { field: result.field } : undefined;
|
|
248
|
+
const refusal = refusalOf(result.reason);
|
|
249
|
+
if (refusal) {
|
|
250
|
+
return c.json(
|
|
251
|
+
{ ...result, ...errorResponse(refusal.code, errMessage || refusal.message, fieldDetails) },
|
|
252
|
+
refusal.status,
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
return c.json(
|
|
256
|
+
{ ...result, ...errorResponse(ErrorCodes.WRITE_ERROR, errMessage || 'Failed to create content') },
|
|
257
|
+
500,
|
|
258
|
+
);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return c.json(result, 201);
|
|
262
|
+
} catch (error) {
|
|
263
|
+
console.error('[Content API] Failed to create content:', error);
|
|
264
|
+
return c.json(
|
|
265
|
+
{
|
|
266
|
+
success: false,
|
|
267
|
+
reason: 'write_error',
|
|
268
|
+
...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(error, 'Failed to create content')),
|
|
269
|
+
},
|
|
270
|
+
500,
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
// PUT /content/:id - Update content (full update); PATCH /content/:id - Partial update
|
|
276
|
+
const updateContent = async (c: Context) => {
|
|
277
|
+
const id = c.req.param('id') ?? '';
|
|
278
|
+
const locale = c.req.query('locale');
|
|
279
|
+
const etag = c.req.query('etag') || '';
|
|
280
|
+
|
|
281
|
+
if (!locale) {
|
|
282
|
+
return c.json(
|
|
283
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'locale query parameter is required', { field: 'locale' }),
|
|
284
|
+
400,
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
try {
|
|
289
|
+
const data = await c.req.json();
|
|
290
|
+
const result = await api.updateLocalized({ id, locale, data, etag });
|
|
291
|
+
|
|
292
|
+
if (!result.success) {
|
|
293
|
+
if (result.reason === 'stale_write') {
|
|
294
|
+
return c.json(
|
|
295
|
+
errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
|
|
296
|
+
currentEtag: result.currentEtag,
|
|
297
|
+
}),
|
|
298
|
+
412,
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
if (result.reason === 'not_found') {
|
|
302
|
+
return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }), 404);
|
|
303
|
+
}
|
|
304
|
+
const refusal = refusalOf(result.reason);
|
|
305
|
+
if (refusal) {
|
|
306
|
+
return c.json(
|
|
307
|
+
{ ...result, ...errorResponse(refusal.code, errorMessage(result.error, refusal.message)) },
|
|
308
|
+
refusal.status,
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
// The backend's own refusals, such as an emptied title or metadata over 4 KB, carry their
|
|
312
|
+
// message in an Error, which serializes to `{}`: send it as a refused create does.
|
|
313
|
+
return c.json(
|
|
314
|
+
{
|
|
315
|
+
...result,
|
|
316
|
+
...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(result.error, 'Failed to update content')),
|
|
317
|
+
},
|
|
318
|
+
500,
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Set ETag header
|
|
323
|
+
c.header('ETag', result.etag);
|
|
324
|
+
|
|
325
|
+
return c.json(result);
|
|
326
|
+
} catch (error) {
|
|
327
|
+
console.error('[Content API] Failed to update content:', error);
|
|
328
|
+
return c.json(
|
|
329
|
+
{
|
|
330
|
+
success: false,
|
|
331
|
+
reason: 'write_error',
|
|
332
|
+
...errorResponse(ErrorCodes.WRITE_ERROR, errorMessage(error, 'Failed to update content')),
|
|
333
|
+
},
|
|
334
|
+
500,
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
app.put('/content/:id', updateContent);
|
|
339
|
+
app.patch('/content/:id', updateContent);
|
|
340
|
+
|
|
341
|
+
// DELETE /content/:id - Delete content (entire entry or specific locale)
|
|
342
|
+
app.delete('/content/:id', async (c) => {
|
|
343
|
+
const id = c.req.param('id');
|
|
344
|
+
const locale = c.req.query('locale');
|
|
345
|
+
const ifMatch = c.req.header('If-Match') || '';
|
|
346
|
+
|
|
347
|
+
try {
|
|
348
|
+
let result: DeleteResult;
|
|
349
|
+
|
|
350
|
+
if (locale) {
|
|
351
|
+
// Delete specific locale
|
|
352
|
+
result = await api.deleteLocalized({ id, locale, etag: ifMatch });
|
|
353
|
+
} else {
|
|
354
|
+
// Delete entire content entry
|
|
355
|
+
result = await api.deleteContent(id, ifMatch);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (!result.success) {
|
|
359
|
+
if (result.reason === 'not_found') {
|
|
360
|
+
return c.json(
|
|
361
|
+
{
|
|
362
|
+
success: false,
|
|
363
|
+
error: 'Content not found',
|
|
364
|
+
},
|
|
365
|
+
404,
|
|
366
|
+
);
|
|
367
|
+
}
|
|
368
|
+
if (result.reason === 'stale_write') {
|
|
369
|
+
// The error envelope is what a client reads to tell an outdated etag from any other failure.
|
|
370
|
+
return c.json(
|
|
371
|
+
{
|
|
372
|
+
success: false,
|
|
373
|
+
reason: result.reason,
|
|
374
|
+
currentEtag: result.currentEtag,
|
|
375
|
+
message: 'Content has been modified',
|
|
376
|
+
...errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
|
|
377
|
+
currentEtag: result.currentEtag,
|
|
378
|
+
}),
|
|
379
|
+
},
|
|
380
|
+
412,
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
return c.json(result, 500);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
return c.json({ success: true });
|
|
387
|
+
} catch (error) {
|
|
388
|
+
console.error('[Content API] Failed to delete content:', error);
|
|
389
|
+
return c.json(
|
|
390
|
+
{
|
|
391
|
+
success: false,
|
|
392
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
393
|
+
},
|
|
394
|
+
500,
|
|
395
|
+
);
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
// ===== Data Routes =====
|
|
400
|
+
// NOTE: These routes MUST come before /:site/* routes to avoid being captured by them
|
|
401
|
+
|
|
402
|
+
// GET /data/collections - List all data collections (must be before /data/:name)
|
|
403
|
+
app.get('/data/collections', async (c) => {
|
|
404
|
+
try {
|
|
405
|
+
const collections = api.data.collections;
|
|
406
|
+
return c.json({
|
|
407
|
+
collections: Array.from(collections).sort(),
|
|
408
|
+
});
|
|
409
|
+
} catch (error) {
|
|
410
|
+
return c.json(
|
|
411
|
+
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data collections'),
|
|
412
|
+
500,
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// GET /data/name-available - Check if data name is available
|
|
418
|
+
app.get('/data/name-available', async (c) => {
|
|
419
|
+
const name = c.req.query('name');
|
|
420
|
+
const collection = c.req.query('collection');
|
|
421
|
+
const excludeId = c.req.query('excludeId');
|
|
422
|
+
|
|
423
|
+
if (!name) {
|
|
424
|
+
return c.json(
|
|
425
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }),
|
|
426
|
+
400,
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (!collection) {
|
|
431
|
+
return c.json(
|
|
432
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {
|
|
433
|
+
field: 'collection',
|
|
434
|
+
}),
|
|
435
|
+
400,
|
|
436
|
+
);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
try {
|
|
440
|
+
const available = api.data.isNameAvailable(collection, name, excludeId);
|
|
441
|
+
if (available) {
|
|
442
|
+
return c.json({ available: true });
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
return c.json({
|
|
446
|
+
available: false,
|
|
447
|
+
existingId: api.data.getNameConflict(collection, name, excludeId),
|
|
448
|
+
});
|
|
449
|
+
} catch (error) {
|
|
450
|
+
return c.json(
|
|
451
|
+
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check data name availability'),
|
|
452
|
+
500,
|
|
453
|
+
);
|
|
454
|
+
}
|
|
455
|
+
});
|
|
456
|
+
|
|
457
|
+
// GET /data - List data entries
|
|
458
|
+
app.get('/data', async (c) => {
|
|
459
|
+
const collection = c.req.query('collection');
|
|
460
|
+
const locale = c.req.query('locale');
|
|
461
|
+
|
|
462
|
+
try {
|
|
463
|
+
const filters: GlobalFilters = { kind: 'data' };
|
|
464
|
+
if (collection) filters.collection = collection;
|
|
465
|
+
if (locale) filters.locales = [locale];
|
|
466
|
+
|
|
467
|
+
const items = Array.from(api.listAllContent(filters));
|
|
468
|
+
return c.json({ items, total: items.length });
|
|
469
|
+
} catch (error) {
|
|
470
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list data entries'), 500);
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
// GET /data/:name - Get data entry by name
|
|
475
|
+
app.get('/data/:name', async (c) => {
|
|
476
|
+
const name = c.req.param('name');
|
|
477
|
+
const collection = c.req.query('collection');
|
|
478
|
+
const locale = c.req.query('locale');
|
|
479
|
+
|
|
480
|
+
if (!collection) {
|
|
481
|
+
return c.json(
|
|
482
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'collection query parameter is required', {
|
|
483
|
+
field: 'collection',
|
|
484
|
+
}),
|
|
485
|
+
400,
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
try {
|
|
490
|
+
const dataEntry = api.data.getByName(collection, name, locale);
|
|
491
|
+
|
|
492
|
+
if (!dataEntry) {
|
|
493
|
+
return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Data entry not found', { name, collection }), 404);
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// If locale specified and provided, filter the response
|
|
497
|
+
if (locale && dataEntry.locales[locale]) {
|
|
498
|
+
return c.json({
|
|
499
|
+
...dataEntry,
|
|
500
|
+
locales: { [locale]: dataEntry.locales[locale] },
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
return c.json(dataEntry);
|
|
505
|
+
} catch (error) {
|
|
506
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch data entry'), 500);
|
|
507
|
+
}
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
// ===== Asset Routes =====
|
|
511
|
+
// Must be registered BEFORE /:site routes to avoid route conflicts (/:site would match "assets")
|
|
512
|
+
|
|
513
|
+
if (options?.assetsPath) {
|
|
514
|
+
// Asset metadata records live under the content root. There is no falling
|
|
515
|
+
// back to the media folder: a site serves it, so a record there is published.
|
|
516
|
+
if (!options.contentRoot) {
|
|
517
|
+
throw new Error('The assetsPath option needs contentRoot as well: asset metadata is kept under the content root');
|
|
518
|
+
}
|
|
519
|
+
const assetOps = new AssetOperations({
|
|
520
|
+
assetsPath: options.assetsPath,
|
|
521
|
+
contentRoot: options.contentRoot,
|
|
522
|
+
...options.assetConfig,
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
// Split a relative asset path into folder and filename
|
|
526
|
+
// e.g. 'uploads/photo.png' → { folder: '/uploads', filename: 'photo.png' }
|
|
527
|
+
// e.g. 'photo.png' → { folder: '/', filename: 'photo.png' }
|
|
528
|
+
function splitAssetPath(relativePath: string): { folder: string; filename: string } {
|
|
529
|
+
const lastSlash = relativePath.lastIndexOf('/');
|
|
530
|
+
if (lastSlash > 0) {
|
|
531
|
+
return { folder: `/${relativePath.slice(0, lastSlash)}`, filename: relativePath.slice(lastSlash + 1) };
|
|
532
|
+
}
|
|
533
|
+
return { folder: '/', filename: relativePath };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// The router decodes `%2F`, so a path in the address can climb out of the assets folder. The
|
|
537
|
+
// containment check refuses it, and that is the caller's mistake, not a server fault.
|
|
538
|
+
function isPathTraversal(error: unknown): boolean {
|
|
539
|
+
return error instanceof Error && error.message === 'Path traversal detected';
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// POST /assets/move — move assets between folders
|
|
543
|
+
app.post('/assets/move', async (c) => {
|
|
544
|
+
try {
|
|
545
|
+
const { filenames, sourceFolder, targetFolder } = await c.req.json<{
|
|
546
|
+
filenames: string[];
|
|
547
|
+
sourceFolder: string;
|
|
548
|
+
targetFolder: string;
|
|
549
|
+
}>();
|
|
550
|
+
|
|
551
|
+
if (!Array.isArray(filenames)) {
|
|
552
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'filenames must be an array'), 400);
|
|
553
|
+
}
|
|
554
|
+
if (typeof sourceFolder !== 'string') {
|
|
555
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'sourceFolder is required'), 400);
|
|
556
|
+
}
|
|
557
|
+
if (typeof targetFolder !== 'string') {
|
|
558
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'targetFolder is required'), 400);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);
|
|
562
|
+
|
|
563
|
+
if (!result.success) {
|
|
564
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
return c.json(result);
|
|
568
|
+
} catch (error) {
|
|
569
|
+
if (isPathTraversal(error)) {
|
|
570
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);
|
|
571
|
+
}
|
|
572
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move assets'), 500);
|
|
573
|
+
}
|
|
574
|
+
});
|
|
575
|
+
|
|
576
|
+
// POST /assets/upload — multipart form data upload
|
|
577
|
+
app.post('/assets/upload', async (c) => {
|
|
578
|
+
try {
|
|
579
|
+
const body = await c.req.parseBody();
|
|
580
|
+
const file = body.file;
|
|
581
|
+
if (!(file instanceof File)) {
|
|
582
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'No file provided in "file" field'), 400);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const alt = typeof body.alt === 'string' ? body.alt : undefined;
|
|
586
|
+
const folder = typeof body.folder === 'string' ? body.folder : undefined;
|
|
587
|
+
|
|
588
|
+
// The uploader is deliberately not read from the request: anyone who can
|
|
589
|
+
// reach this route could otherwise put any name on any picture, and an
|
|
590
|
+
// audit trail that anyone can write is worse than no audit trail.
|
|
591
|
+
const result = await assetOps.upload(file, { alt, folder });
|
|
592
|
+
|
|
593
|
+
if (!result.success) {
|
|
594
|
+
return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
return c.json(result.asset, 201);
|
|
598
|
+
} catch (error) {
|
|
599
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'Upload failed'), 500);
|
|
600
|
+
}
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
// POST /assets/import-url — import image from URL
|
|
604
|
+
app.post('/assets/import-url', async (c) => {
|
|
605
|
+
try {
|
|
606
|
+
const { url, alt, folder } = await c.req.json<{
|
|
607
|
+
url: string;
|
|
608
|
+
alt?: string;
|
|
609
|
+
folder?: string;
|
|
610
|
+
}>();
|
|
611
|
+
|
|
612
|
+
if (!url) {
|
|
613
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'url is required'), 400);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// As with /assets/upload: the uploader never comes off the wire
|
|
617
|
+
const result = await assetOps.importFromUrl(url, { alt, folder });
|
|
618
|
+
|
|
619
|
+
if (!result.success) {
|
|
620
|
+
return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
return c.json(result.asset, 201);
|
|
624
|
+
} catch (error) {
|
|
625
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, 'URL import failed'), 500);
|
|
626
|
+
}
|
|
627
|
+
});
|
|
628
|
+
|
|
629
|
+
// GET /assets — list all assets
|
|
630
|
+
app.get('/assets', async (c) => {
|
|
631
|
+
try {
|
|
632
|
+
const assets = await assetOps.list();
|
|
633
|
+
return c.json({ assets });
|
|
634
|
+
} catch (error) {
|
|
635
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list assets'), 500);
|
|
636
|
+
}
|
|
637
|
+
});
|
|
638
|
+
|
|
639
|
+
// GET /assets/folders — list assets and subfolders within a folder
|
|
640
|
+
app.get('/assets/folders', async (c) => {
|
|
641
|
+
try {
|
|
642
|
+
const path = c.req.query('path') || '/';
|
|
643
|
+
const result = await assetOps.listFolder(path);
|
|
644
|
+
return c.json(result);
|
|
645
|
+
} catch (error) {
|
|
646
|
+
if (isPathTraversal(error)) {
|
|
647
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid folder path'), 400);
|
|
648
|
+
}
|
|
649
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list folder'), 500);
|
|
650
|
+
}
|
|
651
|
+
});
|
|
652
|
+
|
|
653
|
+
// POST /assets/folders — create a folder
|
|
654
|
+
app.post('/assets/folders', async (c) => {
|
|
655
|
+
try {
|
|
656
|
+
const { path } = await c.req.json<{ path: string }>();
|
|
657
|
+
|
|
658
|
+
if (!path) {
|
|
659
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'path is required'), 400);
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
const result = await assetOps.createFolder(path);
|
|
663
|
+
|
|
664
|
+
if (!result.success) {
|
|
665
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
return c.json({ success: true }, 201);
|
|
669
|
+
} catch (error) {
|
|
670
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to create folder'), 500);
|
|
671
|
+
}
|
|
672
|
+
});
|
|
673
|
+
|
|
674
|
+
// GET /assets/folder-tree — get complete folder hierarchy with asset counts
|
|
675
|
+
app.get('/assets/folder-tree', async (c) => {
|
|
676
|
+
try {
|
|
677
|
+
const tree = await assetOps.getFolderTree();
|
|
678
|
+
return c.json({ tree });
|
|
679
|
+
} catch (error) {
|
|
680
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get folder tree'), 500);
|
|
681
|
+
}
|
|
682
|
+
});
|
|
683
|
+
|
|
684
|
+
// GET /assets/usage/:path{.+} — content that links to the asset at this path from the assets root
|
|
685
|
+
app.get('/assets/usage/:path{.+}', async (c) => {
|
|
686
|
+
try {
|
|
687
|
+
const usage = await findAssetUsage(api, c.req.param('path'), options.assetRefBase);
|
|
688
|
+
return c.json({ usage });
|
|
689
|
+
} catch (error) {
|
|
690
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset usage'), 500);
|
|
691
|
+
}
|
|
692
|
+
});
|
|
693
|
+
|
|
694
|
+
// GET /assets/serve/:path{.+} — serve actual asset file (supports subfolders)
|
|
695
|
+
app.get('/assets/serve/:path{.+}', async (c) => {
|
|
696
|
+
try {
|
|
697
|
+
const { folder, filename } = splitAssetPath(c.req.param('path'));
|
|
698
|
+
assetOps.getAssetPath(filename, folder);
|
|
699
|
+
const result = await assetOps.readAssetFile(filename, folder);
|
|
700
|
+
|
|
701
|
+
if (!result.success) {
|
|
702
|
+
return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
return new Response(new Uint8Array(result.buffer), {
|
|
706
|
+
headers: {
|
|
707
|
+
'Content-Type': result.mimeType,
|
|
708
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
709
|
+
},
|
|
710
|
+
});
|
|
711
|
+
} catch (error) {
|
|
712
|
+
if (isPathTraversal(error)) {
|
|
713
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
|
|
714
|
+
}
|
|
715
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to serve asset'), 500);
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
// GET /assets/meta/:path{.+} — get single asset metadata (supports subfolders)
|
|
720
|
+
app.get('/assets/meta/:path{.+}', async (c) => {
|
|
721
|
+
try {
|
|
722
|
+
const { folder, filename } = splitAssetPath(c.req.param('path'));
|
|
723
|
+
assetOps.getAssetPath(filename, folder);
|
|
724
|
+
const asset = await assetOps.getAsset(filename, folder);
|
|
725
|
+
|
|
726
|
+
if (!asset) {
|
|
727
|
+
return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, 'Asset not found'), 404);
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
return c.json(asset);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
if (isPathTraversal(error)) {
|
|
733
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
|
|
734
|
+
}
|
|
735
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to get asset'), 500);
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
|
|
739
|
+
// PATCH /assets/meta/:path{.+} — update asset metadata (supports subfolders)
|
|
740
|
+
app.patch('/assets/meta/:path{.+}', async (c) => {
|
|
741
|
+
try {
|
|
742
|
+
const { folder, filename } = splitAssetPath(c.req.param('path'));
|
|
743
|
+
assetOps.getAssetPath(filename, folder);
|
|
744
|
+
const { alt, tags } = await c.req.json<{ alt?: string; tags?: string[] }>();
|
|
745
|
+
|
|
746
|
+
const result = await assetOps.updateMetadata(filename, { alt, tags }, folder);
|
|
747
|
+
|
|
748
|
+
if (!result.success) {
|
|
749
|
+
// A disk problem is not a missing picture: saying 404 sent the editor
|
|
750
|
+
// back to refetch a value it had just failed to store.
|
|
751
|
+
return result.reason === 'not-found'
|
|
752
|
+
? c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404)
|
|
753
|
+
: c.json(errorResponse(ErrorCodes.INTERNAL_ERROR, result.error), 500);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
return c.json(result.asset);
|
|
757
|
+
} catch (error) {
|
|
758
|
+
if (isPathTraversal(error)) {
|
|
759
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
|
|
760
|
+
}
|
|
761
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to update asset'), 500);
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
|
|
765
|
+
// DELETE /assets/meta/:path{.+} — delete asset (supports subfolders)
|
|
766
|
+
app.delete('/assets/meta/:path{.+}', async (c) => {
|
|
767
|
+
try {
|
|
768
|
+
const { folder, filename } = splitAssetPath(c.req.param('path'));
|
|
769
|
+
assetOps.getAssetPath(filename, folder);
|
|
770
|
+
const result = await assetOps.delete(filename, folder);
|
|
771
|
+
|
|
772
|
+
if (!result.success) {
|
|
773
|
+
return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
return c.json({ success: true });
|
|
777
|
+
} catch (error) {
|
|
778
|
+
if (isPathTraversal(error)) {
|
|
779
|
+
return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, 'Invalid asset path'), 400);
|
|
780
|
+
}
|
|
781
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to delete asset'), 500);
|
|
782
|
+
}
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// ===== Site Routes =====
|
|
787
|
+
// These use /:site parameter which matches any path segment
|
|
788
|
+
|
|
789
|
+
// GET /:site/collections - Get collections for a site
|
|
790
|
+
app.get('/:site/collections', async (c) => {
|
|
791
|
+
const site = c.req.param('site');
|
|
792
|
+
|
|
793
|
+
try {
|
|
794
|
+
if (site === 'fragments') {
|
|
795
|
+
// Use the efficient collections getter for fragments
|
|
796
|
+
const collections = Array.from(api.fragments.collections).sort();
|
|
797
|
+
return c.json({ collections });
|
|
798
|
+
}
|
|
799
|
+
// Use the efficient collections getter for sites
|
|
800
|
+
const siteObj = api.getSite(site);
|
|
801
|
+
if (!siteObj) {
|
|
802
|
+
return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
803
|
+
}
|
|
804
|
+
const collections = Array.from(siteObj.collections).sort();
|
|
805
|
+
return c.json({ collections });
|
|
806
|
+
} catch {
|
|
807
|
+
return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
|
|
811
|
+
// GET /:site/pages - Get pages for a site (not valid for fragments)
|
|
812
|
+
app.get('/:site/pages', async (c) => {
|
|
813
|
+
const site = c.req.param('site');
|
|
814
|
+
const locale = c.req.query('locale');
|
|
815
|
+
|
|
816
|
+
try {
|
|
817
|
+
if (site === 'fragments') {
|
|
818
|
+
return c.json(
|
|
819
|
+
errorResponse(
|
|
820
|
+
ErrorCodes.INVALID_REQUEST,
|
|
821
|
+
'Fragments do not have pages. Use /content?kind=fragment to list fragments.',
|
|
822
|
+
),
|
|
823
|
+
400,
|
|
824
|
+
);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const siteObj = api.getSite(site);
|
|
828
|
+
if (!siteObj) {
|
|
829
|
+
return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// Use listContent with locales filter
|
|
833
|
+
const items = Array.from(siteObj.listContent(locale ? { locales: [locale] } : {}));
|
|
834
|
+
const result = { items, total: items.length };
|
|
835
|
+
return c.json(result);
|
|
836
|
+
} catch (error) {
|
|
837
|
+
return c.json(
|
|
838
|
+
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, `Failed to list pages for site '${site}'`, {
|
|
839
|
+
site,
|
|
840
|
+
}),
|
|
841
|
+
500,
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
});
|
|
845
|
+
|
|
846
|
+
// GET /:site/pathname-available - Check if pathname is available
|
|
847
|
+
app.get('/:site/pathname-available', async (c) => {
|
|
848
|
+
const site = c.req.param('site');
|
|
849
|
+
const pathname = c.req.query('pathname');
|
|
850
|
+
const locale = c.req.query('locale') || 'en';
|
|
851
|
+
const excludeId = c.req.query('excludeId');
|
|
852
|
+
|
|
853
|
+
if (!pathname) {
|
|
854
|
+
return c.json(
|
|
855
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'pathname query parameter is required', { field: 'pathname' }),
|
|
856
|
+
400,
|
|
857
|
+
);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
try {
|
|
861
|
+
if (site === 'fragments') {
|
|
862
|
+
return c.json(
|
|
863
|
+
errorResponse(
|
|
864
|
+
ErrorCodes.INVALID_REQUEST,
|
|
865
|
+
'Fragments do not have pathnames. This endpoint is only for page content.',
|
|
866
|
+
),
|
|
867
|
+
400,
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// Defensive: if the pathname shape is malformed, short-circuit with
|
|
872
|
+
// a structured reason instead of a meaningless index lookup. The
|
|
873
|
+
// dialog short-circuits client-side already, so this guards direct
|
|
874
|
+
// API callers (and future clients) from getting a misleading
|
|
875
|
+
// `{ available: true }` for an invalid path.
|
|
876
|
+
const validation = normalizeAndValidatePathname(pathname);
|
|
877
|
+
if (!validation.valid) {
|
|
878
|
+
return c.json({
|
|
879
|
+
available: false,
|
|
880
|
+
reason: 'invalid_pathname',
|
|
881
|
+
message: validation.message,
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
const normalized = validation.value;
|
|
885
|
+
|
|
886
|
+
// Use the optimized pathname index via site.isPathnameAvailable
|
|
887
|
+
const siteObj = api.getSite(site);
|
|
888
|
+
if (!siteObj) {
|
|
889
|
+
return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
890
|
+
}
|
|
891
|
+
const available = siteObj.isPathnameAvailable(normalized, locale, excludeId);
|
|
892
|
+
|
|
893
|
+
if (available) {
|
|
894
|
+
return c.json({ available: true });
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// Get the conflicting content ID if pathname is taken
|
|
898
|
+
const existingId = siteObj.getPathnameConflict(normalized, locale, excludeId);
|
|
899
|
+
|
|
900
|
+
return c.json({
|
|
901
|
+
available: false,
|
|
902
|
+
existingId,
|
|
903
|
+
});
|
|
904
|
+
} catch (error) {
|
|
905
|
+
return c.json(
|
|
906
|
+
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check pathname availability'),
|
|
907
|
+
500,
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
|
|
912
|
+
// GET /fragments - Shorthand for all fragments
|
|
913
|
+
app.get('/fragments', async (c) => {
|
|
914
|
+
const collection = c.req.query('collection');
|
|
915
|
+
const locale = c.req.query('locale');
|
|
916
|
+
|
|
917
|
+
try {
|
|
918
|
+
const filters: GlobalFilters = { kind: 'fragment' };
|
|
919
|
+
if (collection) filters.collection = collection;
|
|
920
|
+
if (locale) filters.locales = [locale];
|
|
921
|
+
|
|
922
|
+
const items = Array.from(api.listAllContent(filters));
|
|
923
|
+
return c.json({ items, total: items.length });
|
|
924
|
+
} catch (error) {
|
|
925
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to list fragments'), 500);
|
|
926
|
+
}
|
|
927
|
+
});
|
|
928
|
+
|
|
929
|
+
// GET /fragments/name-available - Check if fragment name is available, the way a create checks it: in
|
|
930
|
+
// any letter case and in any language. `locale` is still accepted but narrows nothing, since a fragment
|
|
931
|
+
// has one name for all its languages.
|
|
932
|
+
app.get('/fragments/name-available', async (c) => {
|
|
933
|
+
const name = c.req.query('name');
|
|
934
|
+
const collection = c.req.query('collection') || 'components';
|
|
935
|
+
const excludeId = c.req.query('excludeId');
|
|
936
|
+
|
|
937
|
+
if (!name) {
|
|
938
|
+
return c.json(
|
|
939
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'name query parameter is required', { field: 'name' }),
|
|
940
|
+
400,
|
|
941
|
+
);
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
try {
|
|
945
|
+
const existingId = api.fragments.getNameConflict(collection, name, excludeId);
|
|
946
|
+
if (existingId === null) {
|
|
947
|
+
return c.json({ available: true });
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
return c.json({ available: false, existingId });
|
|
951
|
+
} catch (error) {
|
|
952
|
+
return c.json(
|
|
953
|
+
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to check fragment name availability'),
|
|
954
|
+
500,
|
|
955
|
+
);
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
|
|
959
|
+
// GET /fragments/:name - Get fragment by name
|
|
960
|
+
app.get('/fragments/:name', async (c) => {
|
|
961
|
+
const name = c.req.param('name');
|
|
962
|
+
const collection = c.req.query('collection') || 'components';
|
|
963
|
+
const locale = c.req.query('locale');
|
|
964
|
+
|
|
965
|
+
try {
|
|
966
|
+
const fragment = api.fragments.getByName(collection, name, locale);
|
|
967
|
+
|
|
968
|
+
if (!fragment) {
|
|
969
|
+
return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Fragment not found', { name, collection }), 404);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// If locale specified and provided, filter the response
|
|
973
|
+
if (locale && fragment.locales[locale]) {
|
|
974
|
+
return c.json({
|
|
975
|
+
...fragment,
|
|
976
|
+
locales: { [locale]: fragment.locales[locale] },
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
return c.json(fragment);
|
|
981
|
+
} catch (error) {
|
|
982
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch fragment'), 500);
|
|
983
|
+
}
|
|
984
|
+
});
|
|
985
|
+
|
|
986
|
+
// POST /:site/move - Move page to new pathname
|
|
987
|
+
app.post('/:site/move', async (c) => {
|
|
988
|
+
const site = c.req.param('site');
|
|
989
|
+
|
|
990
|
+
try {
|
|
991
|
+
const { id, pathname, locale, etag } = await c.req.json();
|
|
992
|
+
|
|
993
|
+
if (!id || !pathname || !locale || !etag) {
|
|
994
|
+
return c.json(
|
|
995
|
+
errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, 'id, pathname, locale, and etag are required'),
|
|
996
|
+
400,
|
|
997
|
+
);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
const siteObj = api.getSite(site);
|
|
1001
|
+
if (!siteObj) {
|
|
1002
|
+
return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
// First check if the pathname is available
|
|
1006
|
+
const existing = siteObj.getByPathname(pathname, locale);
|
|
1007
|
+
if (existing && existing.id !== id) {
|
|
1008
|
+
return c.json(
|
|
1009
|
+
{
|
|
1010
|
+
moved: false,
|
|
1011
|
+
reason: 'already_exists',
|
|
1012
|
+
...errorResponse(ErrorCodes.PATHNAME_TAKEN, 'Pathname already taken', { existingId: existing.id }),
|
|
1013
|
+
},
|
|
1014
|
+
409,
|
|
1015
|
+
);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// Get current content to track previous pathname
|
|
1019
|
+
const current = await api.getLocalized(id, locale);
|
|
1020
|
+
if (!current) {
|
|
1021
|
+
return c.json(
|
|
1022
|
+
{ moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) },
|
|
1023
|
+
404,
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
const previousPathname = current.localized.pathname;
|
|
1028
|
+
|
|
1029
|
+
// Update with new pathname using updateLocalized for etag validation
|
|
1030
|
+
const updateResult = await api.updateLocalized({
|
|
1031
|
+
id,
|
|
1032
|
+
locale,
|
|
1033
|
+
data: {
|
|
1034
|
+
pathname: pathname,
|
|
1035
|
+
meta: current.localized.meta,
|
|
1036
|
+
},
|
|
1037
|
+
etag: etag,
|
|
1038
|
+
});
|
|
1039
|
+
|
|
1040
|
+
if (!updateResult.success) {
|
|
1041
|
+
if (updateResult.reason === 'stale_write') {
|
|
1042
|
+
// The error envelope is what a client reads to tell an outdated etag from any other failure.
|
|
1043
|
+
return c.json(
|
|
1044
|
+
{
|
|
1045
|
+
moved: false,
|
|
1046
|
+
reason: 'stale_write',
|
|
1047
|
+
currentEtag: updateResult.currentEtag,
|
|
1048
|
+
message: 'Content has been modified',
|
|
1049
|
+
...errorResponse(ErrorCodes.STALE_WRITE, 'Content has been modified since you last loaded it', {
|
|
1050
|
+
currentEtag: updateResult.currentEtag,
|
|
1051
|
+
}),
|
|
1052
|
+
},
|
|
1053
|
+
412,
|
|
1054
|
+
);
|
|
1055
|
+
}
|
|
1056
|
+
if (updateResult.reason === 'not_found') {
|
|
1057
|
+
return c.json(
|
|
1058
|
+
{ moved: false, ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, 'Content not found', { id }) },
|
|
1059
|
+
404,
|
|
1060
|
+
);
|
|
1061
|
+
}
|
|
1062
|
+
// The update checks the new path as a create does: a malformed one is invalid_pathname, and
|
|
1063
|
+
// another page's path written loosely ('/team/') passes the check above but not the update.
|
|
1064
|
+
// A move calls a taken path already_exists, as the check above does.
|
|
1065
|
+
const refusal = refusalOf(updateResult.reason);
|
|
1066
|
+
if (refusal) {
|
|
1067
|
+
const reason = updateResult.reason === 'invalid_pathname' ? 'invalid_pathname' : 'already_exists';
|
|
1068
|
+
return c.json(
|
|
1069
|
+
{ moved: false, reason, ...errorResponse(refusal.code, errorMessage(updateResult.error, 'Move refused')) },
|
|
1070
|
+
refusal.status,
|
|
1071
|
+
);
|
|
1072
|
+
}
|
|
1073
|
+
return c.json({ moved: false, ...errorResponse(ErrorCodes.WRITE_ERROR, 'Update failed') }, 500);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
return c.json({
|
|
1077
|
+
moved: true,
|
|
1078
|
+
previousPathname: previousPathname,
|
|
1079
|
+
etag: updateResult.etag,
|
|
1080
|
+
});
|
|
1081
|
+
} catch (error) {
|
|
1082
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to move page'), 500);
|
|
1083
|
+
}
|
|
1084
|
+
});
|
|
1085
|
+
|
|
1086
|
+
// GET /untranslated/:locale - Find untranslated content
|
|
1087
|
+
app.get('/untranslated/:targetLocale', async (c) => {
|
|
1088
|
+
const targetLocale = c.req.param('targetLocale');
|
|
1089
|
+
const excludeSites = c.req
|
|
1090
|
+
.query('excludeSites')
|
|
1091
|
+
?.split(',')
|
|
1092
|
+
.map((s) => s.trim())
|
|
1093
|
+
.filter((s) => s);
|
|
1094
|
+
const includeUnpublished = c.req.query('includeUnpublished') === 'true';
|
|
1095
|
+
|
|
1096
|
+
try {
|
|
1097
|
+
const options: FindOptions = {
|
|
1098
|
+
...(excludeSites?.length && { excludeSites }),
|
|
1099
|
+
...(includeUnpublished && { includeUnpublished }),
|
|
1100
|
+
};
|
|
1101
|
+
|
|
1102
|
+
const items = Array.from(api.findUntranslatedContent(targetLocale, options));
|
|
1103
|
+
return c.json({ items, total: items.length });
|
|
1104
|
+
} catch (error) {
|
|
1105
|
+
return c.json(
|
|
1106
|
+
logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, 'Failed to find untranslated content'),
|
|
1107
|
+
500,
|
|
1108
|
+
);
|
|
1109
|
+
}
|
|
1110
|
+
});
|
|
1111
|
+
|
|
1112
|
+
// GET /sites - Get sites configuration
|
|
1113
|
+
app.get('/sites', async (c) => {
|
|
1114
|
+
try {
|
|
1115
|
+
const config = api.sitesConfig;
|
|
1116
|
+
return c.json(config);
|
|
1117
|
+
} catch (error) {
|
|
1118
|
+
return c.json(
|
|
1119
|
+
logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, 'Failed to fetch sites configuration'),
|
|
1120
|
+
500,
|
|
1121
|
+
);
|
|
1122
|
+
}
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
// POST /content/batch - Batch update operations
|
|
1126
|
+
app.post('/content/batch', async (c) => {
|
|
1127
|
+
try {
|
|
1128
|
+
const { operations } = await c.req.json();
|
|
1129
|
+
const result = await api.batchUpdate(operations);
|
|
1130
|
+
|
|
1131
|
+
if (!result.success) {
|
|
1132
|
+
return c.json(result, 207); // Multi-status
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
return c.json(result);
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
console.error('[Content API] Failed to batch update:', error);
|
|
1138
|
+
return c.json(
|
|
1139
|
+
{
|
|
1140
|
+
success: false,
|
|
1141
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
1142
|
+
},
|
|
1143
|
+
500,
|
|
1144
|
+
);
|
|
1145
|
+
}
|
|
1146
|
+
});
|
|
1147
|
+
|
|
1148
|
+
// ===== Git Routes =====
|
|
1149
|
+
|
|
1150
|
+
/**
|
|
1151
|
+
* Get git config from router options or environment variables.
|
|
1152
|
+
* contentRoot from router options takes priority over CONTENT_PATH env var.
|
|
1153
|
+
* Optional: GIT_BRANCH (defaults to current checked-out branch)
|
|
1154
|
+
*/
|
|
1155
|
+
function getGitConfig(): GitConfig {
|
|
1156
|
+
const contentPath = options?.contentRoot || process.env.CONTENT_PATH;
|
|
1157
|
+
if (!contentPath) {
|
|
1158
|
+
throw new Error('contentRoot option or CONTENT_PATH environment variable is required for git operations');
|
|
1159
|
+
}
|
|
1160
|
+
return {
|
|
1161
|
+
contentPath,
|
|
1162
|
+
branch: process.env.GIT_BRANCH,
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// GET /git/status - Get git repository status
|
|
1167
|
+
app.get('/git/status', async (c) => {
|
|
1168
|
+
try {
|
|
1169
|
+
const config = getGitConfig();
|
|
1170
|
+
const gitOps = createGitOperations(config);
|
|
1171
|
+
const status = await gitOps.getStatus();
|
|
1172
|
+
|
|
1173
|
+
if (!status.isRepo) {
|
|
1174
|
+
return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, 'Repository not accessible'), 400);
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
return c.json(status);
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
|
|
1180
|
+
return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
1181
|
+
}
|
|
1182
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_STATUS_FAILED, 'Failed to get git status'), 500);
|
|
1183
|
+
}
|
|
1184
|
+
});
|
|
1185
|
+
|
|
1186
|
+
// POST /git/commit - Commit all changes
|
|
1187
|
+
app.post('/git/commit', async (c) => {
|
|
1188
|
+
try {
|
|
1189
|
+
const body = await c.req.json<{ message?: string }>().catch(() => undefined);
|
|
1190
|
+
|
|
1191
|
+
// Auto-generate message if not provided
|
|
1192
|
+
const date = new Date();
|
|
1193
|
+
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
1194
|
+
const defaultMessage = `CMS changes - ${monthNames[date.getMonth()]} ${date.getDate()}`;
|
|
1195
|
+
const message = body?.message || defaultMessage;
|
|
1196
|
+
|
|
1197
|
+
// Extract user email from CF Access header for commit attribution
|
|
1198
|
+
const userEmail = c.req.header('X-CF-User-Email');
|
|
1199
|
+
const author: GitAuthor | undefined = userEmail ? { name: userEmail.split('@')[0], email: userEmail } : undefined;
|
|
1200
|
+
|
|
1201
|
+
const config = getGitConfig();
|
|
1202
|
+
const gitOps = createGitOperations(config);
|
|
1203
|
+
const result = await gitOps.commitAll(message, author);
|
|
1204
|
+
|
|
1205
|
+
if (!result.success) {
|
|
1206
|
+
return c.json(errorResponse(ErrorCodes.GIT_COMMIT_FAILED, result.error || 'Commit failed'), 500);
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
return c.json(result);
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
|
|
1212
|
+
return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
1213
|
+
}
|
|
1214
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_COMMIT_FAILED, 'Failed to commit changes'), 500);
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
|
|
1218
|
+
// POST /git/push - Push to origin
|
|
1219
|
+
app.post('/git/push', async (c) => {
|
|
1220
|
+
try {
|
|
1221
|
+
const config = getGitConfig();
|
|
1222
|
+
const gitOps = createGitOperations(config);
|
|
1223
|
+
const result = await gitOps.pushOrigin();
|
|
1224
|
+
|
|
1225
|
+
if (!result.success) {
|
|
1226
|
+
return c.json(errorResponse(ErrorCodes.GIT_PUSH_FAILED, result.error || 'Push failed'), 500);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
return c.json(result);
|
|
1230
|
+
} catch (error) {
|
|
1231
|
+
if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
|
|
1232
|
+
return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
1233
|
+
}
|
|
1234
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PUSH_FAILED, 'Failed to push to origin'), 500);
|
|
1235
|
+
}
|
|
1236
|
+
});
|
|
1237
|
+
|
|
1238
|
+
// POST /git/pull - Pull from origin with autostash + rebase
|
|
1239
|
+
app.post('/git/pull', async (c) => {
|
|
1240
|
+
try {
|
|
1241
|
+
const config = getGitConfig();
|
|
1242
|
+
const gitOps = createGitOperations(config);
|
|
1243
|
+
const result = await gitOps.pull();
|
|
1244
|
+
|
|
1245
|
+
if (!result.success) {
|
|
1246
|
+
return c.json(errorResponse(ErrorCodes.GIT_PULL_FAILED, result.error || 'Pull failed'), 500);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
return c.json(result);
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
if (error instanceof Error && (error.message.includes('contentRoot') || error.message.includes('CONTENT_PATH'))) {
|
|
1252
|
+
return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
|
|
1253
|
+
}
|
|
1254
|
+
return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, 'Failed to pull from origin'), 500);
|
|
1255
|
+
}
|
|
1256
|
+
});
|
|
1257
|
+
|
|
1258
|
+
return app;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* Create middleware for backwards compatibility with existing code
|
|
1263
|
+
* This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse
|
|
1264
|
+
*/
|
|
1265
|
+
export function createContentMiddleware(contentApi: ContentAPI, options?: ContentAPIRouterOptions) {
|
|
1266
|
+
const app = createContentAPIRouter(contentApi, options);
|
|
1267
|
+
|
|
1268
|
+
// Convert Hono app to Node.js middleware
|
|
1269
|
+
return async (req: any, res: any, next: () => void) => {
|
|
1270
|
+
const url = new URL(req.url, `http://${req.headers.host}`);
|
|
1271
|
+
|
|
1272
|
+
// Only handle API routes (base path depends on context)
|
|
1273
|
+
const basePath = url.pathname.startsWith('/__cms/api') ? '/__cms/api' : '/__conloca/api';
|
|
1274
|
+
if (!url.pathname.startsWith(basePath)) {
|
|
1275
|
+
return next();
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
// Strip the base path to match Hono routes
|
|
1279
|
+
const path = url.pathname.replace(basePath, '');
|
|
1280
|
+
|
|
1281
|
+
// Create a Request object for Hono
|
|
1282
|
+
const request = new Request(`http://localhost${path}${url.search}`, {
|
|
1283
|
+
method: req.method,
|
|
1284
|
+
headers: req.headers,
|
|
1285
|
+
body: ['GET', 'HEAD'].includes(req.method) ? undefined : await readBody(req),
|
|
1286
|
+
});
|
|
1287
|
+
|
|
1288
|
+
// Handle with Hono
|
|
1289
|
+
const response = await app.fetch(request);
|
|
1290
|
+
|
|
1291
|
+
// Copy response headers
|
|
1292
|
+
response.headers.forEach((value, key) => {
|
|
1293
|
+
res.setHeader(key, value);
|
|
1294
|
+
});
|
|
1295
|
+
|
|
1296
|
+
// Set status code
|
|
1297
|
+
res.statusCode = response.status;
|
|
1298
|
+
|
|
1299
|
+
// Send response body
|
|
1300
|
+
const body = await response.text();
|
|
1301
|
+
res.end(body);
|
|
1302
|
+
};
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// Helper to read request body
|
|
1306
|
+
function readBody(req: any): Promise<string> {
|
|
1307
|
+
return new Promise((resolve, reject) => {
|
|
1308
|
+
const chunks: Uint8Array[] = [];
|
|
1309
|
+
req.on('data', (chunk: Buffer) => chunks.push(new Uint8Array(chunk)));
|
|
1310
|
+
req.on('end', () => {
|
|
1311
|
+
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
|
|
1312
|
+
const combined = new Uint8Array(totalLength);
|
|
1313
|
+
let offset = 0;
|
|
1314
|
+
for (const chunk of chunks) {
|
|
1315
|
+
combined.set(chunk, offset);
|
|
1316
|
+
offset += chunk.length;
|
|
1317
|
+
}
|
|
1318
|
+
resolve(Buffer.from(combined).toString());
|
|
1319
|
+
});
|
|
1320
|
+
req.on('error', reject);
|
|
1321
|
+
});
|
|
1322
|
+
}
|