@conloca/content-api 0.1.15 → 0.2.0

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.
Files changed (281) hide show
  1. package/dist/asset-constraints.d.ts +16 -0
  2. package/dist/asset-constraints.d.ts.map +1 -0
  3. package/dist/asset-constraints.js +29 -0
  4. package/dist/asset-constraints.js.map +1 -0
  5. package/dist/asset-metadata-store.d.ts +60 -0
  6. package/dist/asset-metadata-store.d.ts.map +1 -0
  7. package/dist/asset-metadata-store.js +335 -0
  8. package/dist/asset-metadata-store.js.map +1 -0
  9. package/dist/asset-operations.d.ts +164 -0
  10. package/dist/asset-operations.d.ts.map +1 -0
  11. package/dist/asset-operations.js +784 -0
  12. package/dist/asset-operations.js.map +1 -0
  13. package/dist/asset-types.d.ts +72 -0
  14. package/dist/asset-types.d.ts.map +1 -0
  15. package/dist/asset-types.js +13 -0
  16. package/dist/asset-types.js.map +1 -0
  17. package/dist/asset-usage.d.ts +10 -0
  18. package/dist/asset-usage.d.ts.map +1 -0
  19. package/dist/asset-usage.js +49 -0
  20. package/dist/asset-usage.js.map +1 -0
  21. package/dist/base-content-index.d.ts +63 -0
  22. package/dist/base-content-index.d.ts.map +1 -0
  23. package/dist/base-content-index.js +200 -0
  24. package/dist/base-content-index.js.map +1 -0
  25. package/dist/cf-access.d.ts +31 -0
  26. package/dist/cf-access.d.ts.map +1 -0
  27. package/dist/cf-access.js +67 -0
  28. package/dist/cf-access.js.map +1 -0
  29. package/dist/component-registry.d.ts +50 -0
  30. package/dist/component-registry.d.ts.map +1 -0
  31. package/dist/component-registry.js +121 -0
  32. package/dist/component-registry.js.map +1 -0
  33. package/dist/component-registry.types.d.ts +11 -0
  34. package/dist/component-registry.types.d.ts.map +1 -0
  35. package/dist/component-registry.types.js +2 -0
  36. package/dist/component-registry.types.js.map +1 -0
  37. package/dist/component-vocabulary.d.ts +33 -0
  38. package/dist/component-vocabulary.d.ts.map +1 -0
  39. package/dist/component-vocabulary.js +105 -0
  40. package/dist/component-vocabulary.js.map +1 -0
  41. package/dist/content-api.interface.d.ts +64 -0
  42. package/dist/content-api.interface.d.ts.map +1 -0
  43. package/dist/content-api.interface.js +2 -0
  44. package/dist/content-api.interface.js.map +1 -0
  45. package/dist/content-filters.d.ts +31 -0
  46. package/dist/content-filters.d.ts.map +1 -0
  47. package/dist/content-filters.js +247 -0
  48. package/dist/content-filters.js.map +1 -0
  49. package/dist/content-index.d.ts +184 -0
  50. package/dist/content-index.d.ts.map +1 -0
  51. package/dist/content-index.js +546 -0
  52. package/dist/content-index.js.map +1 -0
  53. package/dist/content-operations.d.ts +157 -0
  54. package/dist/content-operations.d.ts.map +1 -0
  55. package/dist/content-operations.js +359 -0
  56. package/dist/content-operations.js.map +1 -0
  57. package/dist/content-path.d.ts +59 -0
  58. package/dist/content-path.d.ts.map +1 -0
  59. package/dist/content-path.js +88 -0
  60. package/dist/content-path.js.map +1 -0
  61. package/dist/content-reader.d.ts +10 -0
  62. package/dist/content-reader.d.ts.map +1 -0
  63. package/dist/content-reader.js +14 -0
  64. package/dist/content-reader.js.map +1 -0
  65. package/dist/content-utils.d.ts +175 -0
  66. package/dist/content-utils.d.ts.map +1 -0
  67. package/dist/content-utils.js +421 -0
  68. package/dist/content-utils.js.map +1 -0
  69. package/dist/content-watcher.d.ts +43 -0
  70. package/dist/content-watcher.d.ts.map +1 -0
  71. package/dist/content-watcher.js +86 -0
  72. package/dist/content-watcher.js.map +1 -0
  73. package/dist/data-index.d.ts +8 -0
  74. package/dist/data-index.d.ts.map +1 -0
  75. package/dist/data-index.js +8 -0
  76. package/dist/data-index.js.map +1 -0
  77. package/dist/data.d.ts +35 -0
  78. package/dist/data.d.ts.map +1 -0
  79. package/dist/data.js +104 -0
  80. package/dist/data.js.map +1 -0
  81. package/dist/editor-data-bindings.d.ts +10 -0
  82. package/dist/editor-data-bindings.d.ts.map +1 -0
  83. package/dist/editor-data-bindings.js +67 -0
  84. package/dist/editor-data-bindings.js.map +1 -0
  85. package/dist/etag-utils.d.ts +77 -0
  86. package/dist/etag-utils.d.ts.map +1 -0
  87. package/dist/etag-utils.js +161 -0
  88. package/dist/etag-utils.js.map +1 -0
  89. package/dist/filesystem-content-api.d.ts +162 -0
  90. package/dist/filesystem-content-api.d.ts.map +1 -0
  91. package/dist/filesystem-content-api.js +2307 -0
  92. package/dist/filesystem-content-api.js.map +1 -0
  93. package/dist/filesystem-reader-backend.d.ts +46 -0
  94. package/dist/filesystem-reader-backend.d.ts.map +1 -0
  95. package/dist/filesystem-reader-backend.js +119 -0
  96. package/dist/filesystem-reader-backend.js.map +1 -0
  97. package/dist/fragment-index.d.ts +8 -0
  98. package/dist/fragment-index.d.ts.map +1 -0
  99. package/dist/fragment-index.js +8 -0
  100. package/dist/fragment-index.js.map +1 -0
  101. package/dist/fragments.d.ts +16 -0
  102. package/dist/fragments.d.ts.map +1 -0
  103. package/dist/fragments.js +104 -0
  104. package/dist/fragments.js.map +1 -0
  105. package/dist/git-operations.d.ts +49 -0
  106. package/dist/git-operations.d.ts.map +1 -0
  107. package/dist/git-operations.js +256 -0
  108. package/dist/git-operations.js.map +1 -0
  109. package/dist/header-parser.d.ts +37 -0
  110. package/dist/header-parser.d.ts.map +1 -0
  111. package/dist/header-parser.js +233 -0
  112. package/dist/header-parser.js.map +1 -0
  113. package/dist/in-memory-content-api.d.ts +35 -0
  114. package/dist/in-memory-content-api.d.ts.map +1 -0
  115. package/dist/in-memory-content-api.js +609 -0
  116. package/dist/in-memory-content-api.js.map +1 -0
  117. package/dist/index.d.ts +26 -0
  118. package/dist/index.d.ts.map +1 -0
  119. package/dist/index.js +28 -0
  120. package/dist/index.js.map +1 -0
  121. package/dist/indexing.d.ts +5 -0
  122. package/dist/indexing.d.ts.map +1 -0
  123. package/dist/indexing.js +8 -0
  124. package/dist/indexing.js.map +1 -0
  125. package/dist/json-whitespace-view.d.ts +32 -0
  126. package/dist/json-whitespace-view.d.ts.map +1 -0
  127. package/dist/json-whitespace-view.js +153 -0
  128. package/dist/json-whitespace-view.js.map +1 -0
  129. package/dist/middleware.d.ts +20 -0
  130. package/dist/middleware.d.ts.map +1 -0
  131. package/dist/middleware.js +1082 -0
  132. package/dist/middleware.js.map +1 -0
  133. package/dist/node.d.ts +32 -0
  134. package/dist/node.d.ts.map +1 -0
  135. package/dist/node.js +27 -0
  136. package/dist/node.js.map +1 -0
  137. package/dist/page-references.d.ts +21 -0
  138. package/dist/page-references.d.ts.map +1 -0
  139. package/dist/page-references.js +50 -0
  140. package/dist/page-references.js.map +1 -0
  141. package/dist/read-date.d.ts +3 -0
  142. package/dist/read-date.d.ts.map +1 -0
  143. package/dist/read-date.js +9 -0
  144. package/dist/read-date.js.map +1 -0
  145. package/dist/reader-backend.d.ts +54 -0
  146. package/dist/reader-backend.d.ts.map +1 -0
  147. package/dist/reader-backend.js +2 -0
  148. package/dist/reader-backend.js.map +1 -0
  149. package/dist/reader.d.ts +15 -0
  150. package/dist/reader.d.ts.map +1 -0
  151. package/dist/reader.js +14 -0
  152. package/dist/reader.js.map +1 -0
  153. package/dist/schemas/index.d.ts +102 -0
  154. package/dist/schemas/index.d.ts.map +1 -0
  155. package/dist/schemas/index.js +88 -0
  156. package/dist/schemas/index.js.map +1 -0
  157. package/dist/site-index.d.ts +60 -0
  158. package/dist/site-index.d.ts.map +1 -0
  159. package/dist/site-index.js +291 -0
  160. package/dist/site-index.js.map +1 -0
  161. package/dist/site.d.ts +23 -0
  162. package/dist/site.d.ts.map +1 -0
  163. package/dist/site.js +180 -0
  164. package/dist/site.js.map +1 -0
  165. package/dist/types.d.ts +641 -0
  166. package/dist/types.d.ts.map +1 -0
  167. package/dist/types.js +45 -0
  168. package/dist/types.js.map +1 -0
  169. package/dist/url-safe-base64.d.ts +12 -0
  170. package/dist/url-safe-base64.d.ts.map +1 -0
  171. package/dist/url-safe-base64.js +41 -0
  172. package/dist/url-safe-base64.js.map +1 -0
  173. package/dist/url-validation.d.ts +28 -0
  174. package/dist/url-validation.d.ts.map +1 -0
  175. package/dist/url-validation.js +123 -0
  176. package/dist/url-validation.js.map +1 -0
  177. package/dist/utils/atomic-write.d.ts +6 -0
  178. package/dist/utils/atomic-write.d.ts.map +1 -0
  179. package/dist/utils/atomic-write.js +21 -0
  180. package/dist/utils/atomic-write.js.map +1 -0
  181. package/dist/utils.d.ts +46 -0
  182. package/dist/utils.d.ts.map +1 -0
  183. package/dist/utils.js +71 -0
  184. package/dist/utils.js.map +1 -0
  185. package/dist/vite-plugin.d.ts +12 -0
  186. package/dist/vite-plugin.d.ts.map +1 -0
  187. package/dist/vite-plugin.js +30 -0
  188. package/dist/vite-plugin.js.map +1 -0
  189. package/dist/vxjson-serialize.d.ts +13 -0
  190. package/dist/vxjson-serialize.d.ts.map +1 -0
  191. package/dist/vxjson-serialize.js +53 -0
  192. package/dist/vxjson-serialize.js.map +1 -0
  193. package/dist/vxjson.d.ts +113 -0
  194. package/dist/vxjson.d.ts.map +1 -0
  195. package/dist/vxjson.js +381 -0
  196. package/dist/vxjson.js.map +1 -0
  197. package/dist/xxhash.d.ts +10 -0
  198. package/dist/xxhash.d.ts.map +1 -0
  199. package/dist/xxhash.js +35 -0
  200. package/dist/xxhash.js.map +1 -0
  201. package/package.json +132 -34
  202. package/src/asset-constraints.ts +33 -0
  203. package/src/asset-metadata-store.ts +401 -0
  204. package/src/asset-operations.ts +914 -0
  205. package/src/asset-types.ts +74 -0
  206. package/src/asset-usage.ts +47 -0
  207. package/src/base-content-index.ts +227 -0
  208. package/src/cf-access.ts +85 -0
  209. package/src/component-registry.ts +145 -0
  210. package/src/component-registry.types.ts +12 -0
  211. package/src/component-vocabulary.ts +87 -0
  212. package/src/content-api.interface.ts +94 -0
  213. package/src/content-filters.ts +278 -0
  214. package/src/content-index.ts +642 -0
  215. package/src/content-operations.ts +497 -0
  216. package/src/content-path.ts +113 -0
  217. package/src/content-reader.ts +18 -0
  218. package/src/content-utils.ts +474 -0
  219. package/src/content-watcher.ts +122 -0
  220. package/src/data-index.ts +7 -0
  221. package/src/data.ts +134 -0
  222. package/src/editor-data-bindings.ts +66 -0
  223. package/src/etag-utils.ts +204 -0
  224. package/src/filesystem-content-api.ts +2685 -0
  225. package/src/filesystem-reader-backend.ts +135 -0
  226. package/src/fragment-index.ts +7 -0
  227. package/src/fragments.ts +113 -0
  228. package/src/git-operations.ts +340 -0
  229. package/src/header-parser.ts +272 -0
  230. package/src/in-memory-content-api.ts +760 -0
  231. package/src/index.ts +45 -0
  232. package/src/indexing.ts +8 -0
  233. package/src/json-whitespace-view.ts +155 -0
  234. package/src/middleware.ts +1341 -0
  235. package/src/node.ts +40 -0
  236. package/src/page-references.ts +76 -0
  237. package/src/read-date.ts +7 -0
  238. package/src/reader-backend.ts +54 -0
  239. package/src/reader.ts +15 -0
  240. package/src/schemas/index.ts +113 -0
  241. package/src/site-index.ts +330 -0
  242. package/src/site.ts +198 -0
  243. package/src/types.ts +759 -0
  244. package/src/url-safe-base64.ts +38 -0
  245. package/src/url-validation.ts +121 -0
  246. package/src/utils/atomic-write.ts +20 -0
  247. package/src/utils.ts +84 -0
  248. package/src/vite-plugin.ts +45 -0
  249. package/src/vxjson-serialize.ts +66 -0
  250. package/src/vxjson.ts +442 -0
  251. package/src/xxhash.ts +43 -0
  252. package/dist/component-registry.types-CBGONnYn.d.mts +0 -71
  253. package/dist/component-registry.types-CBGONnYn.d.mts.map +0 -1
  254. package/dist/content-operations-Dv67amz3.d.mts +0 -852
  255. package/dist/content-operations-Dv67amz3.d.mts.map +0 -1
  256. package/dist/data-Db1Iv9T0.mjs +0 -60
  257. package/dist/data-Db1Iv9T0.mjs.map +0 -1
  258. package/dist/filesystem-content-api-C1TM0GLo.d.mts +0 -119
  259. package/dist/filesystem-content-api-C1TM0GLo.d.mts.map +0 -1
  260. package/dist/filesystem-content-api-kxKY5IUw.mjs +0 -2678
  261. package/dist/filesystem-content-api-kxKY5IUw.mjs.map +0 -1
  262. package/dist/index.d.mts +0 -79
  263. package/dist/index.d.mts.map +0 -1
  264. package/dist/index.mjs +0 -47
  265. package/dist/index.mjs.map +0 -1
  266. package/dist/node.d.mts +0 -378
  267. package/dist/node.d.mts.map +0 -1
  268. package/dist/node.mjs +0 -2618
  269. package/dist/node.mjs.map +0 -1
  270. package/dist/reader.d.mts +0 -18
  271. package/dist/reader.d.mts.map +0 -1
  272. package/dist/reader.mjs +0 -22
  273. package/dist/reader.mjs.map +0 -1
  274. package/dist/schemas/index.d.mts +0 -90
  275. package/dist/schemas/index.d.mts.map +0 -1
  276. package/dist/schemas/index.mjs +0 -70
  277. package/dist/schemas/index.mjs.map +0 -1
  278. package/dist/site-vNtJ5jCh.mjs +0 -538
  279. package/dist/site-vNtJ5jCh.mjs.map +0 -1
  280. package/dist/types-DWt912tu.mjs +0 -33
  281. package/dist/types-DWt912tu.mjs.map +0 -1
package/dist/node.mjs DELETED
@@ -1,2618 +0,0 @@
1
- import { a as findMdxContentStartPosition, c as atomicWriteFile, i as calculateEtagsFromMdxBuffer, o as ContentIndex, r as VXJSON, s as filterContentWithIndexes, t as FileSystemContentAPI } from "./filesystem-content-api-kxKY5IUw.mjs";
2
- import { C as parseDate, E as Blocks, S as normalizePathname, T as serializeMdxWithFrontmatter, _ as isValidBlockName, a as buildPathnameHistory, b as mapLocales, c as validateAndPrepareMetadata, d as formatFileSize, f as generateContentId, g as isMetadataTooLarge, h as isContentPublished, i as buildLocaleVersion, l as validateCreateContent, m as getMetadataSize, n as UPDATE_SCOPE, o as shouldUpdateModifiedTimestamp, p as getCurrentISODate, r as analyzeUpdateScope, s as updatePublishDates, t as Site, u as extractBlockName, v as isValidPathname, w as resolvePublishDate, x as mapSiteNames, y as localesOf } from "./site-vNtJ5jCh.mjs";
3
- import { t as ErrorCodes } from "./types-DWt912tu.mjs";
4
- import { t as Data } from "./data-Db1Iv9T0.mjs";
5
- import sortKeys from "sort-keys";
6
- import { access, mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
7
- import { dirname, extname, join, normalize, parse, resolve } from "node:path";
8
- import { imageSize } from "image-size";
9
- import { spawn } from "node:child_process";
10
- import { createRemoteJWKSet, jwtVerify } from "jose";
11
- import matter from "gray-matter";
12
- import { compile } from "@mdx-js/mdx";
13
- import remarkFrontmatter from "remark-frontmatter";
14
- import remarkGfm from "remark-gfm";
15
- import remarkMdxFrontmatter from "remark-mdx-frontmatter";
16
- import { Hono } from "hono";
17
- import { cors } from "hono/cors";
18
- import { getRequestListener } from "@hono/node-server";
19
-
20
- //#region src/asset-manifest.ts
21
- const MANIFEST_FILENAME = ".asset-manifest.json";
22
- var AssetManifest = class {
23
- manifestPath;
24
- _lock = Promise.resolve();
25
- constructor(assetsPath) {
26
- this.manifestPath = join(assetsPath, MANIFEST_FILENAME);
27
- }
28
- async read() {
29
- try {
30
- const raw = await readFile(this.manifestPath, "utf-8");
31
- return JSON.parse(raw);
32
- } catch {
33
- return {};
34
- }
35
- }
36
- async write(data) {
37
- await atomicWriteFile(this.manifestPath, JSON.stringify(data, null, 2));
38
- }
39
- /** Atomic read-modify-write with promise-based mutex to prevent concurrent corruption */
40
- async withManifest(fn) {
41
- const prev = this._lock;
42
- let release;
43
- this._lock = new Promise((r) => {
44
- release = r;
45
- });
46
- await prev;
47
- try {
48
- const updated = fn(await this.read());
49
- await this.write(updated);
50
- } finally {
51
- release();
52
- }
53
- }
54
- async add(relativePath, data) {
55
- await this.withManifest((manifest) => {
56
- manifest[relativePath] = data;
57
- return manifest;
58
- });
59
- }
60
- async remove(relativePath) {
61
- let existed = false;
62
- await this.withManifest((manifest) => {
63
- existed = relativePath in manifest;
64
- if (existed) delete manifest[relativePath];
65
- return manifest;
66
- });
67
- return existed;
68
- }
69
- async get(relativePath) {
70
- return (await this.read())[relativePath];
71
- }
72
- /**
73
- * Backward compat helper: search manifest keys for entry ending with /filename or equal to filename
74
- * Useful during transition when only filename is known (not full relative path)
75
- */
76
- async getByFilename(filename) {
77
- const manifest = await this.read();
78
- for (const [key, value] of Object.entries(manifest)) if (key === filename || key.endsWith(`/${filename}`)) return {
79
- relativePath: key,
80
- data: value
81
- };
82
- }
83
- };
84
-
85
- //#endregion
86
- //#region src/git-operations.ts
87
- function runGitCommand(cwd, args) {
88
- return new Promise((resolveCommand, reject) => {
89
- const process = spawn("git", args, {
90
- cwd,
91
- stdio: [
92
- "ignore",
93
- "pipe",
94
- "pipe"
95
- ]
96
- });
97
- let stdout = "";
98
- let stderr = "";
99
- process.stdout.on("data", (data) => {
100
- stdout += data.toString();
101
- });
102
- process.stderr.on("data", (data) => {
103
- stderr += data.toString();
104
- });
105
- process.on("error", reject);
106
- process.on("close", (exitCode) => {
107
- resolveCommand({
108
- exitCode: exitCode ?? 1,
109
- stdout: stdout.trim(),
110
- stderr: stderr.trim()
111
- });
112
- });
113
- });
114
- }
115
- /**
116
- * Resolve the git repository root from a content path.
117
- * Uses `git rev-parse --show-toplevel` starting from the parent of the content directory.
118
- */
119
- async function resolveRepoRoot(contentPath) {
120
- const result = await runGitCommand(dirname(resolve(contentPath)), ["rev-parse", "--show-toplevel"]);
121
- if (result.exitCode !== 0) return null;
122
- return result.stdout;
123
- }
124
- /**
125
- * Create git operations using local git CLI commands.
126
- * Requires git binary available on PATH and CONTENT_PATH inside a git repository.
127
- */
128
- function createGitOperations(config) {
129
- const { contentPath, branch } = config;
130
- let cachedRepoRoot;
131
- async function getCachedRepoRoot() {
132
- if (cachedRepoRoot === void 0) cachedRepoRoot = await resolveRepoRoot(contentPath);
133
- return cachedRepoRoot;
134
- }
135
- return {
136
- async getStatus() {
137
- try {
138
- const repoRoot = await getCachedRepoRoot();
139
- if (!repoRoot) return {
140
- isRepo: false,
141
- hasChanges: false,
142
- changedFiles: 0,
143
- ahead: 0,
144
- behind: 0,
145
- branch: "unknown"
146
- };
147
- const branchResult = await runGitCommand(repoRoot, [
148
- "rev-parse",
149
- "--abbrev-ref",
150
- "HEAD"
151
- ]);
152
- const currentBranch = branchResult.exitCode === 0 ? branchResult.stdout : "unknown";
153
- const statusResult = await runGitCommand(repoRoot, [
154
- "status",
155
- "--porcelain",
156
- "--",
157
- contentPath
158
- ]);
159
- const changedFiles = (statusResult.stdout ? statusResult.stdout.split("\n").filter((l) => l.trim()) : []).length;
160
- const hasChanges = changedFiles > 0;
161
- const remoteConfigured = (await runGitCommand(repoRoot, [
162
- "remote",
163
- "get-url",
164
- "origin"
165
- ])).exitCode === 0;
166
- let ahead = 0;
167
- let behind = 0;
168
- if (remoteConfigured) {
169
- const revListResult = await runGitCommand(repoRoot, [
170
- "rev-list",
171
- "--left-right",
172
- "--count",
173
- `HEAD...origin/${branch || currentBranch}`
174
- ]);
175
- if (revListResult.exitCode === 0 && revListResult.stdout) {
176
- const [a, b] = revListResult.stdout.split(" ").map(Number);
177
- ahead = a || 0;
178
- behind = b || 0;
179
- }
180
- }
181
- return {
182
- isRepo: true,
183
- hasChanges,
184
- changedFiles,
185
- ahead,
186
- behind,
187
- branch: currentBranch,
188
- remoteConfigured
189
- };
190
- } catch {
191
- return {
192
- isRepo: false,
193
- hasChanges: false,
194
- changedFiles: 0,
195
- ahead: 0,
196
- behind: 0,
197
- branch: "unknown"
198
- };
199
- }
200
- },
201
- async commitAll(message, author) {
202
- try {
203
- const repoRoot = await getCachedRepoRoot();
204
- if (!repoRoot) return {
205
- success: false,
206
- error: "Not a git repository"
207
- };
208
- const addResult = await runGitCommand(repoRoot, [
209
- "add",
210
- "-A",
211
- "--",
212
- contentPath
213
- ]);
214
- if (addResult.exitCode !== 0) return {
215
- success: false,
216
- error: addResult.stderr || "Failed to stage changes"
217
- };
218
- if ((await runGitCommand(repoRoot, [
219
- "diff",
220
- "--cached",
221
- "--quiet",
222
- "--",
223
- contentPath
224
- ])).exitCode === 0) return {
225
- success: false,
226
- error: "No changes to commit"
227
- };
228
- const diffStatResult = await runGitCommand(repoRoot, [
229
- "diff",
230
- "--cached",
231
- "--numstat",
232
- "--",
233
- contentPath
234
- ]);
235
- const fileCount = diffStatResult.stdout ? diffStatResult.stdout.split("\n").filter((l) => l.trim()).length : 0;
236
- const commitArgs = [
237
- "commit",
238
- "-m",
239
- message
240
- ];
241
- if (author) commitArgs.push("--author", `${author.name} <${author.email}>`);
242
- const commitResult = await runGitCommand(repoRoot, commitArgs);
243
- if (commitResult.exitCode !== 0) return {
244
- success: false,
245
- error: commitResult.stderr || "Commit failed"
246
- };
247
- return {
248
- success: true,
249
- commit: (await runGitCommand(repoRoot, ["rev-parse", "HEAD"])).stdout || void 0,
250
- summary: `${fileCount} files committed`
251
- };
252
- } catch (error) {
253
- return {
254
- success: false,
255
- error: error instanceof Error ? error.message : "Commit failed"
256
- };
257
- }
258
- },
259
- async pushOrigin() {
260
- try {
261
- const repoRoot = await getCachedRepoRoot();
262
- if (!repoRoot) return {
263
- success: false,
264
- error: "Not a git repository"
265
- };
266
- if ((await runGitCommand(repoRoot, [
267
- "remote",
268
- "get-url",
269
- "origin"
270
- ])).exitCode !== 0) return {
271
- success: false,
272
- error: "No git remote \"origin\" configured. Please configure a remote to enable push."
273
- };
274
- let targetBranch = branch;
275
- if (!targetBranch) targetBranch = (await runGitCommand(repoRoot, [
276
- "rev-parse",
277
- "--abbrev-ref",
278
- "HEAD"
279
- ])).stdout;
280
- const pushResult = await runGitCommand(repoRoot, [
281
- "push",
282
- "origin",
283
- targetBranch
284
- ]);
285
- if (pushResult.exitCode !== 0) {
286
- const stderr = pushResult.stderr || "";
287
- if (stderr.includes("non-fast-forward") || stderr.includes("rejected")) return {
288
- success: false,
289
- error: "Push rejected: remote has changes. Pull first, then try pushing again."
290
- };
291
- if (stderr.includes("Could not resolve host")) return {
292
- success: false,
293
- error: "Cannot reach git remote. Check your network connection."
294
- };
295
- if (stderr.includes("Permission denied") || stderr.includes("Authentication failed")) return {
296
- success: false,
297
- error: "Git remote authentication failed. Check server SSH key or credential configuration."
298
- };
299
- return {
300
- success: false,
301
- error: stderr || "Push failed"
302
- };
303
- }
304
- return { success: true };
305
- } catch (error) {
306
- return {
307
- success: false,
308
- error: error instanceof Error ? error.message : "Push failed"
309
- };
310
- }
311
- },
312
- async pull() {
313
- try {
314
- const repoRoot = await getCachedRepoRoot();
315
- if (!repoRoot) return {
316
- success: false,
317
- error: "Not a git repository"
318
- };
319
- let targetBranch = branch;
320
- if (!targetBranch) targetBranch = (await runGitCommand(repoRoot, [
321
- "rev-parse",
322
- "--abbrev-ref",
323
- "HEAD"
324
- ])).stdout;
325
- const pullResult = await runGitCommand(repoRoot, [
326
- "pull",
327
- "--autostash",
328
- "--rebase",
329
- "origin",
330
- targetBranch
331
- ]);
332
- if (pullResult.exitCode !== 0) return {
333
- success: false,
334
- error: pullResult.stderr || pullResult.stdout || "Pull failed"
335
- };
336
- return {
337
- success: true,
338
- summary: pullResult.stdout || `Pulled latest changes from origin/${targetBranch}`
339
- };
340
- } catch (error) {
341
- return {
342
- success: false,
343
- error: error instanceof Error ? error.message : "Pull failed"
344
- };
345
- }
346
- }
347
- };
348
- }
349
- const LFS_PATTERNS = [
350
- "*.jpg filter=lfs diff=lfs merge=lfs -text",
351
- "*.jpeg filter=lfs diff=lfs merge=lfs -text",
352
- "*.png filter=lfs diff=lfs merge=lfs -text",
353
- "*.gif filter=lfs diff=lfs merge=lfs -text",
354
- "*.svg filter=lfs diff=lfs merge=lfs -text",
355
- "*.webp filter=lfs diff=lfs merge=lfs -text",
356
- "*.avif filter=lfs diff=lfs merge=lfs -text",
357
- "*.ico filter=lfs diff=lfs merge=lfs -text"
358
- ];
359
- /**
360
- * Ensure .gitattributes exists at contentRoot with LFS tracking patterns for web image extensions.
361
- * Creates the file if missing, or appends missing patterns if file exists.
362
- */
363
- async function setupGitLfsAttributes(contentRoot) {
364
- const gitattributesPath = join(contentRoot, ".gitattributes");
365
- let existing = "";
366
- try {
367
- await access(gitattributesPath);
368
- existing = await readFile(gitattributesPath, "utf-8");
369
- } catch {}
370
- const missingPatterns = LFS_PATTERNS.filter((pattern) => !existing.includes(pattern));
371
- if (missingPatterns.length === 0) return;
372
- await writeFile(gitattributesPath, existing ? `${existing.trimEnd()}\n${missingPatterns.join("\n")}\n` : `${missingPatterns.join("\n")}\n`, "utf-8");
373
- }
374
-
375
- //#endregion
376
- //#region src/url-validation.ts
377
- /**
378
- * URL validation for SSRF prevention in server-side fetch operations.
379
- * Blocks private/reserved IP addresses and non-http(s) schemes.
380
- */
381
- const BLOCKED_HOSTNAMES = new Set(["localhost"]);
382
- /** Check if an IPv4 address string points to a private/reserved range */
383
- function isPrivateIPv4(hostname) {
384
- const parts = hostname.split(".");
385
- if (parts.length !== 4) return false;
386
- const octets = parts.map((p) => Number.parseInt(p, 10));
387
- if (octets.some((o) => Number.isNaN(o) || o < 0 || o > 255)) return false;
388
- const [first, second] = octets;
389
- if (first === 0) return true;
390
- if (first === 10) return true;
391
- if (first === 127) return true;
392
- if (first === 169 && second === 254) return true;
393
- if (first === 172 && second >= 16 && second <= 31) return true;
394
- if (first === 192 && second === 168) return true;
395
- return false;
396
- }
397
- /** Check if an IPv6 address string points to a private/reserved range */
398
- function isPrivateIPv6(hostname) {
399
- const lower = hostname.toLowerCase();
400
- if (lower === "::1") return true;
401
- if (lower === "::") return true;
402
- if (lower.startsWith("fe80:") || lower.startsWith("fe80%")) return true;
403
- if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
404
- return false;
405
- }
406
- /**
407
- * Validate that a URL is safe to fetch server-side.
408
- * Blocks private/reserved IP addresses and non-http(s) schemes.
409
- *
410
- * @param url The URL string to validate
411
- * @returns The parsed URL object if valid
412
- * @throws Error if the URL is invalid, uses a blocked scheme, or points to a private IP
413
- */
414
- function validateFetchUrl(url) {
415
- const parsed = new URL(url);
416
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("URL scheme must be http or https");
417
- const hostname = parsed.hostname.replace(/^\[|\]$/g, "");
418
- if (BLOCKED_HOSTNAMES.has(hostname.toLowerCase())) throw new Error("URL points to a private/reserved IP address");
419
- if (isPrivateIPv4(hostname)) throw new Error("URL points to a private/reserved IP address");
420
- if (isPrivateIPv6(hostname)) throw new Error("URL points to a private/reserved IP address");
421
- return parsed;
422
- }
423
-
424
- //#endregion
425
- //#region src/asset-operations.ts
426
- const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
427
- const DEFAULT_ACCEPTED_FORMATS = [
428
- "jpg",
429
- "jpeg",
430
- "png",
431
- "gif",
432
- "webp",
433
- "avif",
434
- "svg",
435
- "ico"
436
- ];
437
- const MIME_MAP = {
438
- jpg: "image/jpeg",
439
- jpeg: "image/jpeg",
440
- png: "image/png",
441
- gif: "image/gif",
442
- webp: "image/webp",
443
- avif: "image/avif",
444
- svg: "image/svg+xml",
445
- ico: "image/x-icon"
446
- };
447
- /** Recognized web image extensions for filesystem scanning */
448
- const RECOGNIZED_IMAGE_EXTENSIONS = new Set([
449
- "jpg",
450
- "jpeg",
451
- "png",
452
- "gif",
453
- "webp",
454
- "svg",
455
- "avif",
456
- "ico"
457
- ]);
458
- /** System files to skip during filesystem scanning */
459
- const SYSTEM_FILES = new Set([
460
- ".ds_store",
461
- "thumbs.db",
462
- ".gitkeep",
463
- "desktop.ini",
464
- ".asset-manifest.json"
465
- ]);
466
- /** Check if filename has a recognized web image extension */
467
- function isRecognizedImageExtension(filename) {
468
- const ext = extname(filename).slice(1).toLowerCase();
469
- return RECOGNIZED_IMAGE_EXTENSIONS.has(ext);
470
- }
471
- /** Check if file is a system/hidden file that should be skipped */
472
- function isSystemFile(filename) {
473
- return filename.startsWith(".") || SYSTEM_FILES.has(filename.toLowerCase());
474
- }
475
- var AssetOperations = class {
476
- config;
477
- manifest;
478
- dirEnsured = false;
479
- lfsSetup = false;
480
- constructor(config) {
481
- this.config = {
482
- assetsPath: config.assetsPath,
483
- maxFileSize: config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE,
484
- acceptedFormats: config.acceptedFormats ?? DEFAULT_ACCEPTED_FORMATS,
485
- contentRoot: config.contentRoot
486
- };
487
- this.manifest = new AssetManifest(config.assetsPath);
488
- }
489
- /** Resolve folder from manifest when only filename is known */
490
- async resolveFolder(filename) {
491
- const entry = await this.manifest.getByFilename(filename);
492
- if (!entry) return "/";
493
- const lastSlash = entry.relativePath.lastIndexOf("/");
494
- return lastSlash > 0 ? `/${entry.relativePath.slice(0, lastSlash)}` : "/";
495
- }
496
- async ensureDir(subpath) {
497
- const targetPath = subpath ? join(this.config.assetsPath, subpath) : this.config.assetsPath;
498
- if (!subpath && this.dirEnsured) return;
499
- await mkdir(targetPath, { recursive: true });
500
- if (!subpath) this.dirEnsured = true;
501
- }
502
- /**
503
- * Validate that a subpath is safe (no path traversal attacks)
504
- * Returns the resolved full path if valid, throws if invalid
505
- */
506
- validateSubpath(subpath) {
507
- const normalizedSubpath = subpath.replace(/^\/+|\/+$/g, "") || ".";
508
- const assetsAbsolute = resolve(this.config.assetsPath);
509
- const fullPath = resolve(assetsAbsolute, normalizedSubpath);
510
- if (!fullPath.startsWith(assetsAbsolute)) throw new Error("Path traversal detected");
511
- return fullPath;
512
- }
513
- /**
514
- * Resolve a unique filename by appending -1, -2, etc. if collision exists
515
- * @param originalName Original filename
516
- * @param folder Optional folder path (relative to assets root)
517
- */
518
- async resolveFilename(originalName, folder) {
519
- const { name, ext } = parse(originalName);
520
- const sanitized = name.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
521
- const safeExt = ext.toLowerCase();
522
- const baseDir = folder && folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\/+|\/+$/g, "")) : this.config.assetsPath;
523
- let candidate = `${sanitized}${safeExt}`;
524
- let counter = 0;
525
- while (true) try {
526
- await access(join(baseDir, candidate));
527
- counter++;
528
- candidate = `${sanitized}-${counter}${safeExt}`;
529
- } catch {
530
- break;
531
- }
532
- return candidate;
533
- }
534
- validateFormat(filename) {
535
- const ext = extname(filename).slice(1).toLowerCase();
536
- return this.config.acceptedFormats.includes(ext);
537
- }
538
- validateSize(size) {
539
- return size <= this.config.maxFileSize;
540
- }
541
- /**
542
- * Get image dimensions from manifest cache or by reading file headers
543
- */
544
- async getDimensions(filePath, manifestEntry) {
545
- if (manifestEntry?.width && manifestEntry?.height) return {
546
- width: manifestEntry.width,
547
- height: manifestEntry.height,
548
- fromCache: true
549
- };
550
- try {
551
- const buffer = await readFile(filePath);
552
- const result = imageSize(new Uint8Array(buffer));
553
- return {
554
- width: result.width,
555
- height: result.height,
556
- fromCache: false
557
- };
558
- } catch {
559
- return {
560
- width: void 0,
561
- height: void 0,
562
- fromCache: false
563
- };
564
- }
565
- }
566
- /**
567
- * Build an AssetEntry from a directory entry, enriching with manifest metadata
568
- */
569
- async buildAssetEntry(dirent, folder, manifestData) {
570
- const relativePath = folder === "/" ? dirent.name : `${folder.slice(1)}/${dirent.name}`;
571
- const manifestEntry = manifestData[relativePath];
572
- const fullPath = this.getAssetPath(dirent.name, folder);
573
- const stats = await stat(fullPath);
574
- const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
575
- if (!fromCache && width && height) this.manifest.add(relativePath, {
576
- ...manifestEntry,
577
- width,
578
- height
579
- }).catch(() => {});
580
- const ext = extname(dirent.name).slice(1).toLowerCase();
581
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
582
- return {
583
- filename: dirent.name,
584
- originalName: manifestEntry?.originalName || dirent.name,
585
- mimeType,
586
- size: stats.size,
587
- width,
588
- height,
589
- alt: manifestEntry?.alt,
590
- uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
591
- uploadedBy: manifestEntry?.uploadedBy,
592
- folder,
593
- tags: manifestEntry?.tags
594
- };
595
- }
596
- async upload(file, metadata) {
597
- if (!this.validateFormat(file.name)) return {
598
- success: false,
599
- error: `Invalid format. Accepted: ${this.config.acceptedFormats.join(", ")}`
600
- };
601
- if (!this.validateSize(file.size)) return {
602
- success: false,
603
- error: `File too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
604
- };
605
- const folder = metadata?.folder && metadata.folder !== "/" ? "/" + metadata.folder.replace(/^\/+|\/+$/g, "") : "/";
606
- if (folder !== "/") try {
607
- this.validateSubpath(folder);
608
- } catch {
609
- return {
610
- success: false,
611
- error: "Invalid folder path"
612
- };
613
- }
614
- await this.ensureDir();
615
- if (folder !== "/") await this.ensureDir(folder.replace(/^\//, ""));
616
- if (!this.lfsSetup) {
617
- await setupGitLfsAttributes(this.config.assetsPath);
618
- this.lfsSetup = true;
619
- }
620
- const filename = await this.resolveFilename(file.name, folder);
621
- const filePath = folder !== "/" ? join(this.config.assetsPath, folder.replace(/^\//, ""), filename) : join(this.config.assetsPath, filename);
622
- const arrayBuffer = await file.arrayBuffer();
623
- await writeFile(filePath, new Uint8Array(arrayBuffer));
624
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
625
- const manifestEntry = {
626
- alt: metadata?.alt,
627
- width: metadata?.width,
628
- height: metadata?.height,
629
- uploadedAt: (/* @__PURE__ */ new Date()).toISOString(),
630
- uploadedBy: metadata?.uploadedBy,
631
- originalName: file.name
632
- };
633
- await this.manifest.add(relativePath, manifestEntry);
634
- const ext = extname(filename).slice(1).toLowerCase();
635
- return {
636
- success: true,
637
- asset: {
638
- filename,
639
- originalName: file.name,
640
- mimeType: MIME_MAP[ext] || `image/${ext}`,
641
- size: file.size,
642
- width: metadata?.width,
643
- height: metadata?.height,
644
- alt: metadata?.alt,
645
- uploadedAt: manifestEntry.uploadedAt,
646
- uploadedBy: metadata?.uploadedBy,
647
- folder
648
- }
649
- };
650
- }
651
- /**
652
- * List all assets recursively from filesystem
653
- */
654
- async list() {
655
- const manifestData = await this.manifest.read();
656
- const assets = [];
657
- const scanFolder = async (folderPath, folder) => {
658
- let entries;
659
- try {
660
- entries = await readdir(folderPath, { withFileTypes: true });
661
- } catch {
662
- return;
663
- }
664
- for (const entry of entries) {
665
- if (isSystemFile(entry.name) || entry.isSymbolicLink()) continue;
666
- const entryPath = join(folderPath, entry.name);
667
- if (entry.isDirectory()) await scanFolder(entryPath, folder === "/" ? `/${entry.name}` : `${folder}/${entry.name}`);
668
- else if (entry.isFile() && isRecognizedImageExtension(entry.name)) {
669
- const assetEntry = await this.buildAssetEntry(entry, folder, manifestData);
670
- assets.push(assetEntry);
671
- }
672
- }
673
- };
674
- await scanFolder(this.config.assetsPath, "/");
675
- return assets;
676
- }
677
- /**
678
- * Get asset by filename and optional folder
679
- */
680
- async getAsset(filename, folder = "/") {
681
- if (folder === "/") folder = await this.resolveFolder(filename);
682
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
683
- const fullPath = this.getAssetPath(filename, folder);
684
- let stats;
685
- try {
686
- stats = await stat(fullPath);
687
- } catch {
688
- return;
689
- }
690
- if (!stats.isFile()) return;
691
- const manifestEntry = (await this.manifest.read())[relativePath];
692
- const { width, height, fromCache } = await this.getDimensions(fullPath, manifestEntry);
693
- if (!fromCache && width && height) this.manifest.add(relativePath, {
694
- ...manifestEntry,
695
- width,
696
- height
697
- }).catch(() => {});
698
- const ext = extname(filename).slice(1).toLowerCase();
699
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
700
- return {
701
- filename,
702
- originalName: manifestEntry?.originalName || filename,
703
- mimeType,
704
- size: stats.size,
705
- width,
706
- height,
707
- alt: manifestEntry?.alt,
708
- uploadedAt: manifestEntry?.uploadedAt || stats.birthtime.toISOString(),
709
- uploadedBy: manifestEntry?.uploadedBy,
710
- folder,
711
- tags: manifestEntry?.tags
712
- };
713
- }
714
- /**
715
- * Delete asset file and manifest entry
716
- */
717
- async delete(filename, folder = "/") {
718
- if (folder === "/") folder = await this.resolveFolder(filename);
719
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
720
- const filePath = this.getAssetPath(filename, folder);
721
- try {
722
- await unlink(filePath);
723
- } catch {}
724
- await this.manifest.remove(relativePath);
725
- return { success: true };
726
- }
727
- /**
728
- * Import an image from a URL (server-side fetch, no CORS issues)
729
- * Validates URL against SSRF, enforces 30s timeout, and checks response size.
730
- */
731
- async importFromUrl(url, metadata) {
732
- try {
733
- validateFetchUrl(url);
734
- } catch (err) {
735
- return {
736
- success: false,
737
- error: err instanceof Error ? err.message : "Invalid URL"
738
- };
739
- }
740
- const controller = new AbortController();
741
- const timeout = setTimeout(() => controller.abort(), 3e4);
742
- let response;
743
- try {
744
- response = await fetch(url, { signal: controller.signal });
745
- } catch {
746
- return {
747
- success: false,
748
- error: "Failed to fetch URL"
749
- };
750
- } finally {
751
- clearTimeout(timeout);
752
- }
753
- if (!response.ok) return {
754
- success: false,
755
- error: `Fetch failed with status ${response.status}`
756
- };
757
- const contentLength = response.headers.get("content-length");
758
- if (contentLength && Number.parseInt(contentLength, 10) > this.config.maxFileSize) return {
759
- success: false,
760
- error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
761
- };
762
- const contentType = response.headers.get("content-type") || "";
763
- const urlFilename = new URL(url).pathname.split("/").pop() || "imported-image.jpg";
764
- const arrayBuffer = await response.arrayBuffer();
765
- if (arrayBuffer.byteLength > this.config.maxFileSize) return {
766
- success: false,
767
- error: `Remote file too large. Maximum: ${Math.round(this.config.maxFileSize / (1024 * 1024))}MB`
768
- };
769
- const file = new File([new Uint8Array(arrayBuffer)], urlFilename, { type: contentType });
770
- return this.upload(file, metadata);
771
- }
772
- /**
773
- * List assets and subfolders within a folder (filesystem-first)
774
- * @param subpath Folder path relative to assets root (default '/')
775
- */
776
- async listFolder(subpath = "/") {
777
- const normalizedSubpath = subpath === "/" ? "/" : "/" + subpath.replace(/^\/+|\/+$/g, "");
778
- let fullPath;
779
- if (normalizedSubpath === "/") fullPath = this.config.assetsPath;
780
- else fullPath = this.validateSubpath(normalizedSubpath);
781
- let entries;
782
- try {
783
- entries = await readdir(fullPath, { withFileTypes: true });
784
- } catch {
785
- return {
786
- assets: [],
787
- folders: []
788
- };
789
- }
790
- const folders = entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && !e.isSymbolicLink()).map((e) => ({
791
- name: e.name,
792
- path: normalizedSubpath === "/" ? `/${e.name}` : `${normalizedSubpath}/${e.name}`
793
- }));
794
- const imageFiles = entries.filter((e) => e.isFile() && !isSystemFile(e.name) && !e.isSymbolicLink() && isRecognizedImageExtension(e.name));
795
- const manifestData = await this.manifest.read();
796
- return {
797
- assets: await Promise.all(imageFiles.map((dirent) => this.buildAssetEntry(dirent, normalizedSubpath, manifestData))),
798
- folders
799
- };
800
- }
801
- /**
802
- * Create a folder on disk
803
- * @param subpath Folder path relative to assets root
804
- */
805
- async createFolder(subpath) {
806
- if (!subpath || subpath === "/") return {
807
- success: false,
808
- error: "Cannot create root folder"
809
- };
810
- let fullPath;
811
- try {
812
- fullPath = this.validateSubpath(subpath);
813
- } catch {
814
- return {
815
- success: false,
816
- error: "Invalid folder path"
817
- };
818
- }
819
- try {
820
- await mkdir(fullPath, { recursive: true });
821
- return { success: true };
822
- } catch (err) {
823
- return {
824
- success: false,
825
- error: `Failed to create folder: ${err instanceof Error ? err.message : "Unknown error"}`
826
- };
827
- }
828
- }
829
- /**
830
- * Update asset metadata (alt text, tags)
831
- * @param filename Asset filename
832
- * @param updates Metadata updates (alt, tags)
833
- * @param folder Optional folder path (default '/')
834
- */
835
- async updateMetadata(filename, updates, folder = "/") {
836
- if (folder === "/") folder = await this.resolveFolder(filename);
837
- const relativePath = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
838
- const fullPath = this.getAssetPath(filename, folder);
839
- try {
840
- await stat(fullPath);
841
- } catch {
842
- return {
843
- success: false,
844
- error: "Asset not found"
845
- };
846
- }
847
- const merged = {
848
- ...(await this.manifest.read())[relativePath] || {},
849
- ...updates
850
- };
851
- await this.manifest.add(relativePath, merged);
852
- const asset = await this.getAsset(filename, folder);
853
- if (!asset) return {
854
- success: false,
855
- error: "Failed to retrieve updated asset"
856
- };
857
- return {
858
- success: true,
859
- asset
860
- };
861
- }
862
- /**
863
- * Get usage information for an asset (which pages reference it)
864
- * @param filename Asset filename
865
- */
866
- async getUsage(filename) {
867
- if (!this.config.contentRoot) return [];
868
- const usages = [];
869
- const searchPatterns = [
870
- filename,
871
- `/assets/uploads/${filename}`,
872
- `assets/uploads/${filename}`
873
- ];
874
- const walkDir = async (dir) => {
875
- const files = [];
876
- let entries;
877
- try {
878
- entries = await readdir(dir, { withFileTypes: true });
879
- } catch {
880
- return files;
881
- }
882
- for (const entry of entries) {
883
- const fullPath = join(dir, entry.name);
884
- if (entry.isDirectory() && !entry.name.startsWith(".")) files.push(...await walkDir(fullPath));
885
- else if (entry.isFile() && entry.name.endsWith(".vxjson")) files.push(fullPath);
886
- }
887
- return files;
888
- };
889
- const vxjsonFiles = await walkDir(this.config.contentRoot);
890
- for (const filePath of vxjsonFiles) try {
891
- const content = await readFile(filePath, "utf-8");
892
- if (searchPatterns.some((pattern) => content.includes(pattern))) {
893
- const pageName = filePath.replace(this.config.contentRoot, "").replace(/^[/\\]/, "").replace(/\.vxjson$/, "");
894
- let field = "unknown";
895
- try {
896
- const json = JSON.parse(content);
897
- field = this.findFieldWithAsset(json, searchPatterns) || "content";
898
- } catch {
899
- field = "content";
900
- }
901
- usages.push({
902
- page: pageName,
903
- field
904
- });
905
- }
906
- } catch {}
907
- return usages;
908
- }
909
- /**
910
- * Get the file path for an asset
911
- * @param filename Asset filename
912
- * @param folder Optional folder path (defaults to asset's stored folder)
913
- */
914
- getAssetPath(filename, folder) {
915
- const subpath = folder && folder !== "/" ? folder.replace(/^\/+|\/+$/g, "") : "";
916
- const combined = subpath ? `${subpath}/${filename}` : filename;
917
- return this.validateSubpath(combined);
918
- }
919
- /**
920
- * Read asset file contents for serving (filesystem-first)
921
- * @param filename Asset filename
922
- * @param folder Optional folder path (default '/')
923
- */
924
- async readAssetFile(filename, folder = "/") {
925
- const filePath = this.getAssetPath(filename, folder);
926
- const ext = extname(filename).slice(1).toLowerCase();
927
- const mimeType = MIME_MAP[ext] || `image/${ext}`;
928
- try {
929
- return {
930
- success: true,
931
- buffer: await readFile(filePath),
932
- mimeType
933
- };
934
- } catch {
935
- return {
936
- success: false,
937
- error: "Asset not found"
938
- };
939
- }
940
- }
941
- /**
942
- * Helper to find which field contains an asset reference
943
- */
944
- findFieldWithAsset(obj, patterns, path = "") {
945
- if (typeof obj === "string") {
946
- if (patterns.some((p) => obj.includes(p))) return path || "root";
947
- return null;
948
- }
949
- if (Array.isArray(obj)) {
950
- for (let i = 0; i < obj.length; i++) {
951
- const result = this.findFieldWithAsset(obj[i], patterns, path ? `${path}[${i}]` : `[${i}]`);
952
- if (result) return result;
953
- }
954
- return null;
955
- }
956
- if (obj && typeof obj === "object") for (const [key, value] of Object.entries(obj)) {
957
- const result = this.findFieldWithAsset(value, patterns, path ? `${path}.${key}` : key);
958
- if (result) return result;
959
- }
960
- return null;
961
- }
962
- /**
963
- * Move assets from one folder to another
964
- * @param filenames List of filenames to move
965
- * @param sourceFolder Source folder path (relative to assets root)
966
- * @param targetFolder Target folder path (relative to assets root)
967
- */
968
- async moveAssets(filenames, sourceFolder, targetFolder) {
969
- const normalizedSource = sourceFolder === "/" ? "/" : "/" + sourceFolder.replace(/^\/+|\/+$/g, "");
970
- const normalizedTarget = targetFolder === "/" ? "/" : "/" + targetFolder.replace(/^\/+|\/+$/g, "");
971
- let sourcePath;
972
- let targetPath;
973
- try {
974
- sourcePath = normalizedSource === "/" ? this.config.assetsPath : this.validateSubpath(normalizedSource);
975
- targetPath = normalizedTarget === "/" ? this.config.assetsPath : this.validateSubpath(normalizedTarget);
976
- } catch {
977
- return {
978
- success: false,
979
- error: "Invalid folder path"
980
- };
981
- }
982
- try {
983
- if (!(await stat(sourcePath)).isDirectory()) return {
984
- success: false,
985
- error: "Source folder does not exist"
986
- };
987
- } catch {
988
- return {
989
- success: false,
990
- error: "Source folder does not exist"
991
- };
992
- }
993
- try {
994
- if (!(await stat(targetPath)).isDirectory()) return {
995
- success: false,
996
- error: "Target folder does not exist"
997
- };
998
- } catch {
999
- return {
1000
- success: false,
1001
- error: "Target folder does not exist"
1002
- };
1003
- }
1004
- const moves = [];
1005
- for (const filename of filenames) {
1006
- const sourceFile = join(sourcePath, filename);
1007
- const targetFile = join(targetPath, filename);
1008
- const oldRelativePath = normalizedSource === "/" ? filename : `${normalizedSource.slice(1)}/${filename}`;
1009
- const newRelativePath = normalizedTarget === "/" ? filename : `${normalizedTarget.slice(1)}/${filename}`;
1010
- try {
1011
- await rename(sourceFile, targetFile);
1012
- moves.push({
1013
- oldPath: oldRelativePath,
1014
- newPath: newRelativePath
1015
- });
1016
- } catch (err) {
1017
- console.error(`[AssetOperations] Failed to move ${filename}:`, err);
1018
- }
1019
- }
1020
- if (moves.length > 0) await this.manifest.withManifest((data) => {
1021
- for (const { oldPath, newPath } of moves) {
1022
- const entry = data[oldPath];
1023
- if (entry) {
1024
- delete data[oldPath];
1025
- data[newPath] = entry;
1026
- }
1027
- }
1028
- return data;
1029
- });
1030
- return {
1031
- success: true,
1032
- moved: moves.length
1033
- };
1034
- }
1035
- /**
1036
- * Get the complete folder tree with asset counts
1037
- * @returns Array of folder tree nodes representing the folder hierarchy
1038
- */
1039
- async getFolderTree() {
1040
- const buildTree = async (folderPath, folder) => {
1041
- let entries;
1042
- try {
1043
- entries = await readdir(folderPath, { withFileTypes: true });
1044
- } catch {
1045
- return [];
1046
- }
1047
- const result = [];
1048
- for (const entry of entries) {
1049
- if (isSystemFile(entry.name) || entry.isSymbolicLink()) continue;
1050
- if (entry.isDirectory()) {
1051
- const entryPath = join(folderPath, entry.name);
1052
- const subFolder = folder === "/" ? `/${entry.name}` : `${folder}/${entry.name}`;
1053
- let assetCount = 0;
1054
- try {
1055
- assetCount = (await readdir(entryPath, { withFileTypes: true })).filter((e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name)).length;
1056
- } catch {}
1057
- const children = await buildTree(entryPath, subFolder);
1058
- result.push({
1059
- name: entry.name,
1060
- path: subFolder,
1061
- assetCount,
1062
- children
1063
- });
1064
- }
1065
- }
1066
- return result;
1067
- };
1068
- let rootAssetCount = 0;
1069
- try {
1070
- rootAssetCount = (await readdir(this.config.assetsPath, { withFileTypes: true })).filter((e) => e.isFile() && !isSystemFile(e.name) && isRecognizedImageExtension(e.name)).length;
1071
- } catch {}
1072
- const children = await buildTree(this.config.assetsPath, "/");
1073
- return [{
1074
- name: "Root",
1075
- path: "/",
1076
- assetCount: rootAssetCount,
1077
- children
1078
- }];
1079
- }
1080
- };
1081
-
1082
- //#endregion
1083
- //#region src/cf-access.ts
1084
- /**
1085
- * Cloudflare Access JWT validation utility
1086
- *
1087
- * Validates JWT tokens from CF Access for API authorization and git commit attribution.
1088
- * When CF_ACCESS_TEAM_NAME and CF_ACCESS_AUD env vars are set, requests must have valid tokens.
1089
- * When env vars are not set (local dev), validation is skipped.
1090
- */
1091
- const CF_ACCESS_TEAM_NAME = process.env.CF_ACCESS_TEAM_NAME;
1092
- const CF_ACCESS_AUD = process.env.CF_ACCESS_AUD;
1093
- const JWKS = CF_ACCESS_TEAM_NAME ? createRemoteJWKSet(new URL(`https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com/cdn-cgi/access/certs`)) : null;
1094
- /**
1095
- * Extract CF Access JWT token from request.
1096
- * Checks Cf-Access-Jwt-Assertion header first, falls back to CF_Authorization cookie.
1097
- */
1098
- function extractCFAccessToken(request) {
1099
- const headerToken = request.headers.get("Cf-Access-Jwt-Assertion");
1100
- if (headerToken) return headerToken;
1101
- const match = (request.headers.get("Cookie") || "").match(/CF_Authorization=([^;]+)/);
1102
- return match ? match[1] : null;
1103
- }
1104
- /**
1105
- * Validate CF Access JWT from request.
1106
- *
1107
- * Returns { valid: true, required: false } when env vars not set (local dev mode).
1108
- * Returns { valid: true, required: true, user } when token is valid.
1109
- * Returns { valid: false, required: true, error } when token is invalid or missing.
1110
- */
1111
- async function validateCFAccessRequest(request) {
1112
- if (!CF_ACCESS_TEAM_NAME || !CF_ACCESS_AUD || !JWKS) return {
1113
- valid: true,
1114
- required: false
1115
- };
1116
- const token = extractCFAccessToken(request);
1117
- if (!token) return {
1118
- valid: false,
1119
- required: true,
1120
- error: "No token provided"
1121
- };
1122
- try {
1123
- const { payload } = await jwtVerify(token, JWKS, {
1124
- issuer: `https://${CF_ACCESS_TEAM_NAME}.cloudflareaccess.com`,
1125
- audience: CF_ACCESS_AUD
1126
- });
1127
- return {
1128
- valid: true,
1129
- required: true,
1130
- user: {
1131
- email: typeof payload.email === "string" && payload.email ? payload.email : void 0,
1132
- sub: typeof payload.sub === "string" && payload.sub ? payload.sub : void 0
1133
- }
1134
- };
1135
- } catch (error) {
1136
- return {
1137
- valid: false,
1138
- required: true,
1139
- error: error instanceof Error ? error.message : "Validation failed"
1140
- };
1141
- }
1142
- }
1143
-
1144
- //#endregion
1145
- //#region src/component-registry.ts
1146
- /**
1147
- * Component Registry for managing linked and unlinked components
1148
- *
1149
- * Registry is stored at {canvasDir}/components/registry.json
1150
- * Component IDs must follow the format: vx-{uuid}
1151
- */
1152
- var ComponentRegistry = class {
1153
- registryPath;
1154
- registry = {};
1155
- initialized = false;
1156
- constructor(canvasDir) {
1157
- this.registryPath = join(canvasDir, "components", "registry.json");
1158
- }
1159
- /**
1160
- * Initialize the registry by loading from disk or creating new
1161
- */
1162
- async initialize() {
1163
- if (this.initialized) return;
1164
- try {
1165
- const content = await readFile(this.registryPath, "utf-8");
1166
- this.registry = JSON.parse(content);
1167
- } catch (error) {
1168
- if (error.code === "ENOENT") await this.save();
1169
- else throw error;
1170
- }
1171
- this.initialized = true;
1172
- }
1173
- /**
1174
- * Validate component ID format (vx-{uuid})
1175
- */
1176
- validateComponentId(id) {
1177
- if (!/^vx-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id)) throw new Error("Invalid component ID format. Expected: vx-{uuid}");
1178
- }
1179
- /**
1180
- * Save registry to disk atomically
1181
- */
1182
- async save() {
1183
- await mkdir(dirname(this.registryPath), { recursive: true });
1184
- const sorted = sortKeys(this.registry, { deep: true });
1185
- const content = JSON.stringify(sorted, null, 2);
1186
- await atomicWriteFile(this.registryPath, content);
1187
- }
1188
- /**
1189
- * Register a new component or update existing
1190
- */
1191
- async register(id, entry) {
1192
- await this.initialize();
1193
- this.validateComponentId(id);
1194
- this.registry[id] = {
1195
- displayName: entry.displayName,
1196
- path: entry.path
1197
- };
1198
- await this.save();
1199
- }
1200
- /**
1201
- * Get a component entry by ID
1202
- */
1203
- async get(id) {
1204
- await this.initialize();
1205
- return this.registry[id] || null;
1206
- }
1207
- /**
1208
- * Link a component to a path
1209
- */
1210
- async link(id, path) {
1211
- await this.initialize();
1212
- const entry = this.registry[id];
1213
- if (!entry) throw new Error(`Component ${id} not found in registry`);
1214
- entry.path = path;
1215
- await this.save();
1216
- }
1217
- /**
1218
- * Unlink a component (set path to null)
1219
- */
1220
- async unlink(id) {
1221
- await this.initialize();
1222
- const entry = this.registry[id];
1223
- if (!entry) throw new Error(`Component ${id} not found in registry`);
1224
- entry.path = null;
1225
- await this.save();
1226
- }
1227
- /**
1228
- * List all components
1229
- */
1230
- async list() {
1231
- await this.initialize();
1232
- return Object.entries(this.registry).map(([id, entry]) => ({
1233
- id,
1234
- ...entry
1235
- }));
1236
- }
1237
- /**
1238
- * Delete a component from registry
1239
- */
1240
- async delete(id) {
1241
- await this.initialize();
1242
- delete this.registry[id];
1243
- await this.save();
1244
- }
1245
- };
1246
-
1247
- //#endregion
1248
- //#region src/content-watcher.ts
1249
- /**
1250
- * Creates a content API instance for the given options
1251
- */
1252
- async function createContentAPI(options) {
1253
- return await FileSystemContentAPI.create({
1254
- contentRoot: options.contentRoot,
1255
- canvasDir: options.canvasDir || "./canvas"
1256
- });
1257
- }
1258
- /**
1259
- * Creates file change handlers for content watching
1260
- */
1261
- function createContentWatchHandlers(contentApi, options, ws, onReindexed) {
1262
- const handleFileChange = async (file, action) => {
1263
- const isContentFile = file.endsWith(".mdx") || file.endsWith(".vxjson");
1264
- const isDataFile = file.endsWith(".json") && file.includes("/data/");
1265
- if (!isContentFile && !isDataFile) return;
1266
- const normalizedFile = normalize(resolve(file));
1267
- const normalizedRoot = normalize(resolve(options.contentRoot));
1268
- if (normalizedFile.startsWith(normalizedRoot)) {
1269
- const relativePath = normalizedFile.replace(normalizedRoot + "/", "");
1270
- console.log(`[Content] ${action}: ${relativePath}`);
1271
- try {
1272
- const reindexOptions = action === "delete" ? { handleDeletions: true } : void 0;
1273
- const result = await contentApi.reindex([normalizedFile], reindexOptions);
1274
- for (const manifest of result.updated) {
1275
- const message = {
1276
- type: "custom",
1277
- event: "conloca:content-update",
1278
- data: {
1279
- action,
1280
- manifest
1281
- }
1282
- };
1283
- ws.send(message);
1284
- }
1285
- if (action === "delete" && result.deleted) for (const deletion of result.deleted) ws.send({
1286
- type: "custom",
1287
- event: "conloca:content-update",
1288
- data: {
1289
- action: "delete",
1290
- ...deletion
1291
- }
1292
- });
1293
- } catch (error) {
1294
- console.error("[Content Watcher] Reindex failed:", error);
1295
- return;
1296
- }
1297
- try {
1298
- await onReindexed?.({
1299
- file: normalizedFile,
1300
- action
1301
- });
1302
- } catch (error) {
1303
- console.error("[Content Watcher] onReindexed callback failed:", error);
1304
- }
1305
- }
1306
- };
1307
- return {
1308
- onChange: (file) => handleFileChange(file, "update"),
1309
- onAdd: (file) => handleFileChange(file, "create"),
1310
- onUnlink: (file) => handleFileChange(file, "delete")
1311
- };
1312
- }
1313
-
1314
- //#endregion
1315
- //#region src/in-memory-content-api.ts
1316
- /**
1317
- * In-memory implementation of ContentAPI for testing
1318
- * Provides a clean, mock-free way to test the API without filesystem dependencies
1319
- */
1320
- var InMemoryContentAPI = class {
1321
- contentIndex;
1322
- sitesConfig;
1323
- blocks;
1324
- data;
1325
- sites;
1326
- constructor(sitesConfig) {
1327
- this.sitesConfig = sitesConfig || {
1328
- sites: {},
1329
- globalLocales: ["en"]
1330
- };
1331
- this.contentIndex = ContentIndex.createUncached(this.sitesConfig);
1332
- this.blocks = new Blocks(this, this.contentIndex.getBlockIndex());
1333
- this.data = new Data(this, this.contentIndex.getDataIndex());
1334
- this.sites = mapSiteNames(this.sitesConfig, (siteName) => {
1335
- const siteIndex = this.contentIndex.getSiteIndex(siteName);
1336
- if (!siteIndex) throw new Error(`Site index not found for ${siteName}`);
1337
- return new Site(siteName, this, siteIndex);
1338
- });
1339
- }
1340
- async getContent(id) {
1341
- const manifest = this.contentIndex.getManifest(id);
1342
- if (!manifest) return null;
1343
- const contentEntry = {
1344
- id: manifest.id,
1345
- kind: manifest.kind,
1346
- site: manifest.site,
1347
- collection: manifest.collection,
1348
- type: manifest.type,
1349
- locales: {}
1350
- };
1351
- for (const localeVersion of localesOf(manifest)) {
1352
- const { locale } = localeVersion;
1353
- const cachedContent = this.contentIndex.getCachedContent(id, locale);
1354
- if (cachedContent) {
1355
- let contentToReturn = cachedContent;
1356
- if (manifest.type === "mdx" && cachedContent.mdx) {
1357
- const frontmatterData = {
1358
- id: manifest.id,
1359
- created: localeVersion.created,
1360
- modified: localeVersion.modified,
1361
- ...localeVersion.publishAt && { publishAt: localeVersion.publishAt },
1362
- ...localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt },
1363
- ...localeVersion.meta
1364
- };
1365
- contentToReturn = {
1366
- ...cachedContent,
1367
- mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx)
1368
- };
1369
- }
1370
- contentEntry.locales[locale] = {
1371
- ...localeVersion,
1372
- content: contentToReturn
1373
- };
1374
- }
1375
- }
1376
- return contentEntry;
1377
- }
1378
- async getLocalized(id, locale) {
1379
- const manifest = this.contentIndex.getManifest(id);
1380
- if (!manifest || !manifest.locales[locale]) return null;
1381
- const localeVersion = manifest.locales[locale];
1382
- const cachedContent = this.contentIndex.getCachedContent(id, locale);
1383
- if (!cachedContent) return null;
1384
- let contentToReturn = { ...cachedContent };
1385
- if (manifest.type === "mdx" && cachedContent.mdx) {
1386
- const frontmatterData = {
1387
- id: manifest.id,
1388
- created: localeVersion.created,
1389
- modified: localeVersion.modified,
1390
- ...localeVersion.publishAt && { publishAt: localeVersion.publishAt },
1391
- ...localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt },
1392
- ...localeVersion.meta
1393
- };
1394
- contentToReturn = {
1395
- ...cachedContent,
1396
- mdx: serializeMdxWithFrontmatter(frontmatterData, cachedContent.mdx)
1397
- };
1398
- }
1399
- return {
1400
- id,
1401
- site: manifest.site,
1402
- collection: manifest.collection,
1403
- type: manifest.type,
1404
- kind: manifest.kind,
1405
- localized: {
1406
- ...localeVersion,
1407
- meta: { ...localeVersion.meta },
1408
- content: contentToReturn,
1409
- previousPathnames: localeVersion.previousPathnames ? { ...localeVersion.previousPathnames } : void 0
1410
- }
1411
- };
1412
- }
1413
- async createContent(data) {
1414
- const validation = validateCreateContent(data, this.sites, this.blocks);
1415
- if (!validation.valid) return {
1416
- success: false,
1417
- reason: validation.reason,
1418
- error: validation.error ? new Error(validation.error) : void 0,
1419
- existingId: validation.existingId
1420
- };
1421
- const id = generateContentId();
1422
- const now = getCurrentISODate();
1423
- const contentCache = {};
1424
- const locales = mapLocales(data.site ? this.sitesConfig.sites[data.site].locales : this.sitesConfig.globalLocales, (locale) => {
1425
- const localeData = data.locales[locale];
1426
- if (!localeData) return void 0;
1427
- const meta = {
1428
- ...data.meta,
1429
- ...localeData.meta
1430
- };
1431
- const fileData = {
1432
- id,
1433
- type: data.type,
1434
- created: now,
1435
- modified: now,
1436
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
1437
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0,
1438
- meta,
1439
- content: localeData.content
1440
- };
1441
- let buffer;
1442
- let etag;
1443
- if (data.type === "mdx") {
1444
- const mdxContent = serializeMdxWithFrontmatter({
1445
- id,
1446
- created: now,
1447
- modified: now,
1448
- ...localeData.publishAt && { publishAt: localeData.publishAt },
1449
- ...localeData.unpublishAt && { unpublishAt: localeData.unpublishAt },
1450
- ...meta
1451
- }, localeData.content.mdx || "");
1452
- buffer = new TextEncoder().encode(mdxContent);
1453
- const contentPos = findMdxContentStartPosition(buffer);
1454
- const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);
1455
- etag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;
1456
- } else {
1457
- const jsonStr = VXJSON.serialize(fileData);
1458
- buffer = Buffer.from(jsonStr, "utf-8");
1459
- const etagResult = VXJSON.calculateETags(buffer);
1460
- if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}`);
1461
- etag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1462
- }
1463
- const localeVersion = buildLocaleVersion({
1464
- locale,
1465
- etag,
1466
- created: now,
1467
- modified: now,
1468
- meta,
1469
- kind: data.kind,
1470
- pathname: data.kind === "page" ? localeData.pathname : void 0,
1471
- name: data.kind === "block" || data.kind === "data" ? data.name : void 0,
1472
- publishAt: localeData.publishAt && typeof localeData.publishAt === "string" ? localeData.publishAt : void 0,
1473
- unpublishAt: localeData.unpublishAt && typeof localeData.unpublishAt === "string" ? localeData.unpublishAt : void 0
1474
- });
1475
- contentCache[locale] = localeData.content;
1476
- return localeVersion;
1477
- });
1478
- const manifest = {
1479
- id,
1480
- type: data.type,
1481
- kind: data.kind,
1482
- site: data.site,
1483
- collection: data.collection,
1484
- locales
1485
- };
1486
- for (const localeVersion of localesOf(manifest)) this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);
1487
- return {
1488
- success: true,
1489
- id,
1490
- etag: Object.values(manifest.locales)[0]?.etag || "",
1491
- created: new Date(now)
1492
- };
1493
- }
1494
- async updateLocalized(input) {
1495
- const { id, locale, data, etag } = input;
1496
- const manifest = this.contentIndex.getManifest(id);
1497
- if (!manifest) return {
1498
- success: false,
1499
- reason: "not_found"
1500
- };
1501
- const localeVersion = manifest.locales[locale];
1502
- if (!localeVersion) return {
1503
- success: false,
1504
- reason: "not_found"
1505
- };
1506
- if (localeVersion.etag !== etag) return {
1507
- success: false,
1508
- reason: "stale_write",
1509
- currentEtag: localeVersion.etag
1510
- };
1511
- const currentContent = this.contentIndex.getCachedContent(id, locale);
1512
- if (!currentContent) return {
1513
- success: false,
1514
- reason: "not_found"
1515
- };
1516
- if (data.meta) {
1517
- const validation = validateAndPrepareMetadata({
1518
- ...localeVersion.meta,
1519
- ...data.meta
1520
- });
1521
- if (!validation.valid) return {
1522
- success: false,
1523
- reason: "write_error",
1524
- error: new Error(validation.error)
1525
- };
1526
- }
1527
- if (data.pathname && manifest.kind === "page" && manifest.site) {
1528
- const site = this.sites[manifest.site];
1529
- if (site) {
1530
- const existingId = site.getPathnameConflict(data.pathname, locale, id);
1531
- if (existingId) return {
1532
- success: false,
1533
- reason: "write_error",
1534
- error: /* @__PURE__ */ new Error(`Pathname ${data.pathname} is already taken by content ${existingId}`)
1535
- };
1536
- }
1537
- }
1538
- const now = /* @__PURE__ */ new Date();
1539
- const nowStr = now.toISOString();
1540
- const oldPathname = localeVersion.pathname;
1541
- const updatedLocaleVersion = { ...localeVersion };
1542
- if (shouldUpdateModifiedTimestamp(data)) updatedLocaleVersion.modified = data.modified || nowStr;
1543
- else if (data.modified) updatedLocaleVersion.modified = data.modified;
1544
- if (data.meta) updatedLocaleVersion.meta = {
1545
- ...localeVersion.meta,
1546
- ...data.meta
1547
- };
1548
- if (data.pathname !== void 0 && manifest.kind === "page") {
1549
- const pathnameHistory = buildPathnameHistory(oldPathname, data.pathname, isContentPublished(localeVersion), nowStr);
1550
- if (Object.keys(pathnameHistory).length > 0) updatedLocaleVersion.previousPathnames = {
1551
- ...localeVersion.previousPathnames,
1552
- ...pathnameHistory
1553
- };
1554
- updatedLocaleVersion.pathname = data.pathname;
1555
- }
1556
- updatePublishDates(updatedLocaleVersion, data);
1557
- const updatedContent = data.content ? {
1558
- ...currentContent,
1559
- ...data.content
1560
- } : currentContent;
1561
- const fileData = {
1562
- id: manifest.id,
1563
- type: manifest.type,
1564
- created: updatedLocaleVersion.created,
1565
- modified: updatedLocaleVersion.modified,
1566
- publishAt: updatedLocaleVersion.publishAt,
1567
- unpublishAt: updatedLocaleVersion.unpublishAt,
1568
- meta: updatedLocaleVersion.meta,
1569
- previousPathnames: updatedLocaleVersion.previousPathnames,
1570
- content: updatedContent
1571
- };
1572
- let buffer;
1573
- let newEtag;
1574
- if (manifest.type === "mdx") {
1575
- const mdxContent = serializeMdxWithFrontmatter({
1576
- id: manifest.id,
1577
- created: updatedLocaleVersion.created,
1578
- modified: updatedLocaleVersion.modified,
1579
- ...updatedLocaleVersion.publishAt && { publishAt: updatedLocaleVersion.publishAt },
1580
- ...updatedLocaleVersion.unpublishAt && { unpublishAt: updatedLocaleVersion.unpublishAt },
1581
- ...updatedLocaleVersion.meta
1582
- }, updatedContent.mdx || "");
1583
- buffer = new TextEncoder().encode(mdxContent);
1584
- const contentPos = findMdxContentStartPosition(buffer);
1585
- const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);
1586
- newEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;
1587
- } else {
1588
- const jsonStr = VXJSON.serialize(fileData);
1589
- buffer = Buffer.from(jsonStr, "utf-8");
1590
- const etagResult = VXJSON.calculateETags(buffer);
1591
- if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}`);
1592
- newEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1593
- }
1594
- updatedLocaleVersion.etag = newEtag;
1595
- const updatedManifest = {
1596
- ...manifest,
1597
- locales: {
1598
- ...manifest.locales,
1599
- [locale]: updatedLocaleVersion
1600
- }
1601
- };
1602
- this.contentIndex.addContent(updatedManifest, updatedLocaleVersion, updatedContent);
1603
- return {
1604
- success: true,
1605
- etag: updatedLocaleVersion.etag,
1606
- modified: now
1607
- };
1608
- }
1609
- async deleteContent(id, etag) {
1610
- const manifest = this.contentIndex.getManifest(id);
1611
- if (!manifest) return {
1612
- success: false,
1613
- reason: "not_found",
1614
- error: /* @__PURE__ */ new Error("Content not found")
1615
- };
1616
- let hasMatchingEtag = false;
1617
- for (const localeVersion of localesOf(manifest)) if (localeVersion.etag === etag) {
1618
- hasMatchingEtag = true;
1619
- break;
1620
- }
1621
- if (!hasMatchingEtag && etag) return {
1622
- success: false,
1623
- reason: "stale_write",
1624
- currentEtag: Array.from(localesOf(manifest))[0]?.etag || "",
1625
- error: /* @__PURE__ */ new Error("ETag mismatch")
1626
- };
1627
- this.contentIndex.removeEntry(id);
1628
- return { success: true };
1629
- }
1630
- getSite(siteName) {
1631
- if (siteName === "blocks") throw new Error("Use `blocks` property instead of getSite(\"blocks\")");
1632
- return this.sites[siteName] || null;
1633
- }
1634
- *listAllContent(filters) {
1635
- yield* filterContentWithIndexes(this.contentIndex, filters, this.sitesConfig);
1636
- }
1637
- *findUntranslatedContent(targetLocale, options) {
1638
- yield* this.contentIndex.findUntranslatedContent(targetLocale, options);
1639
- }
1640
- async deleteLocalized(input) {
1641
- const { id, locale, etag } = input;
1642
- const manifest = this.contentIndex.getManifest(id);
1643
- if (!manifest) return {
1644
- success: false,
1645
- reason: "not_found",
1646
- error: /* @__PURE__ */ new Error("Content not found")
1647
- };
1648
- const localeVersion = manifest.locales[locale];
1649
- if (!localeVersion) return {
1650
- success: false,
1651
- reason: "not_found",
1652
- error: /* @__PURE__ */ new Error("Locale not found")
1653
- };
1654
- if (localeVersion.etag !== etag) return {
1655
- success: false,
1656
- reason: "stale_write",
1657
- currentEtag: localeVersion.etag,
1658
- error: /* @__PURE__ */ new Error("Stale write - etag mismatch")
1659
- };
1660
- if (Object.keys(manifest.locales).length === 1) this.contentIndex.removeEntry(id);
1661
- else {
1662
- const updatedManifest = {
1663
- ...manifest,
1664
- locales: { ...manifest.locales }
1665
- };
1666
- updatedManifest.locales[locale] = void 0;
1667
- this.contentIndex.removeLocale(manifest.id, locale);
1668
- }
1669
- return { success: true };
1670
- }
1671
- async batchUpdate(operations) {
1672
- const results = {
1673
- operations: [],
1674
- success: true,
1675
- failed: 0,
1676
- updated: 0
1677
- };
1678
- for (const op of operations) {
1679
- const result = await this.updateLocalized(op);
1680
- if (result.success) {
1681
- results.updated++;
1682
- results.operations.push({
1683
- id: op.id,
1684
- locale: op.locale,
1685
- updated: true,
1686
- etag: result.etag
1687
- });
1688
- } else {
1689
- results.failed++;
1690
- results.success = false;
1691
- results.operations.push({
1692
- id: op.id,
1693
- locale: op.locale,
1694
- updated: false,
1695
- error: result.error || new Error(result.reason || "Update failed")
1696
- });
1697
- }
1698
- }
1699
- return results;
1700
- }
1701
- setContent(id, content) {
1702
- const manifest = {
1703
- id: content.id,
1704
- type: content.type,
1705
- kind: content.kind,
1706
- site: content.site,
1707
- collection: content.collection,
1708
- locales: {}
1709
- };
1710
- const contentCache = {};
1711
- for (const [locale, localeData] of Object.entries(content.locales)) {
1712
- const manifestLocale = {
1713
- locale,
1714
- etag: localeData.etag,
1715
- created: localeData.created,
1716
- modified: localeData.modified,
1717
- meta: localeData.meta
1718
- };
1719
- if (localeData.publishAt !== void 0) manifestLocale.publishAt = localeData.publishAt;
1720
- if (localeData.unpublishAt !== void 0) manifestLocale.unpublishAt = localeData.unpublishAt;
1721
- if (localeData.name) manifestLocale.name = localeData.name;
1722
- if (localeData.pathname) manifestLocale.pathname = localeData.pathname;
1723
- if (localeData.previousPathnames) manifestLocale.previousPathnames = localeData.previousPathnames;
1724
- manifest.locales[locale] = manifestLocale;
1725
- contentCache[locale] = localeData.content;
1726
- }
1727
- for (const localeVersion of localesOf(manifest)) this.contentIndex.addContent(manifest, localeVersion, contentCache[localeVersion.locale]);
1728
- }
1729
- clear() {
1730
- this.contentIndex.clear();
1731
- }
1732
- async getContentAsBuffer(id, locale) {
1733
- const manifest = this.contentIndex.getManifest(id);
1734
- if (!manifest || !manifest.locales[locale]) return null;
1735
- const localeVersion = manifest.locales[locale];
1736
- const cachedContent = this.contentIndex.getCachedContent(id, locale);
1737
- if (!cachedContent) return null;
1738
- let buffer;
1739
- let calculatedEtag;
1740
- let contentType;
1741
- if (manifest.type === "mdx") {
1742
- const mdxContent = serializeMdxWithFrontmatter({
1743
- id: manifest.id,
1744
- created: localeVersion.created,
1745
- modified: localeVersion.modified,
1746
- ...localeVersion.publishAt && { publishAt: localeVersion.publishAt },
1747
- ...localeVersion.unpublishAt && { unpublishAt: localeVersion.unpublishAt },
1748
- ...localeVersion.meta
1749
- }, cachedContent.mdx || "");
1750
- buffer = new TextEncoder().encode(mdxContent);
1751
- const contentPos = findMdxContentStartPosition(buffer);
1752
- const etagResult = calculateEtagsFromMdxBuffer(buffer, contentPos);
1753
- calculatedEtag = `${etagResult.metaEtag}.${etagResult.contentEtag}`;
1754
- contentType = "text/mdx";
1755
- } else {
1756
- const fileData = {
1757
- id: manifest.id,
1758
- type: manifest.type,
1759
- created: localeVersion.created,
1760
- modified: localeVersion.modified,
1761
- publishAt: localeVersion.publishAt,
1762
- unpublishAt: localeVersion.unpublishAt,
1763
- meta: localeVersion.meta,
1764
- previousPathnames: localeVersion.previousPathnames,
1765
- content: cachedContent
1766
- };
1767
- const jsonStr = VXJSON.serialize(fileData);
1768
- buffer = Buffer.from(jsonStr, "utf-8");
1769
- const etagResult = VXJSON.calculateETags(buffer);
1770
- if (!etagResult.success) throw new Error(`Invalid VXJSON format: ${etagResult.error}`);
1771
- calculatedEtag = etagResult.contentEtag ? `${etagResult.metaEtag}.${etagResult.contentEtag}` : etagResult.metaEtag;
1772
- contentType = "application/json";
1773
- }
1774
- return {
1775
- buffer,
1776
- etag: calculatedEtag,
1777
- contentType
1778
- };
1779
- }
1780
- };
1781
-
1782
- //#endregion
1783
- //#region src/mdx/compile.ts
1784
- async function compileMDX(content) {
1785
- try {
1786
- const { data: metadata } = matter(content);
1787
- const compiled = await compile(content, {
1788
- outputFormat: "function-body",
1789
- development: process.env.NODE_ENV === "development",
1790
- remarkPlugins: [
1791
- remarkFrontmatter,
1792
- remarkMdxFrontmatter,
1793
- remarkGfm
1794
- ]
1795
- });
1796
- return {
1797
- code: String(compiled.value),
1798
- metadata
1799
- };
1800
- } catch (error) {
1801
- if (error instanceof Error) {
1802
- const enhancedError = /* @__PURE__ */ new Error(`MDX compilation failed: ${error.message}`);
1803
- enhancedError.stack = error.stack;
1804
- throw enhancedError;
1805
- }
1806
- throw error;
1807
- }
1808
- }
1809
-
1810
- //#endregion
1811
- //#region src/middleware.ts
1812
- /**
1813
- * Helper to create standardized error responses
1814
- */
1815
- function errorResponse(code, message, details) {
1816
- return { error: {
1817
- code,
1818
- message,
1819
- ...details && { details }
1820
- } };
1821
- }
1822
- /**
1823
- * Helper to log and create error responses for unexpected errors
1824
- */
1825
- function logAndCreateErrorResponse(error, code, message, details) {
1826
- console.error(`[Content API] ${message}:`, error);
1827
- return errorResponse(code, message, details);
1828
- }
1829
- function errorMessage(error, fallback) {
1830
- return error instanceof Error ? error.message : fallback;
1831
- }
1832
- function createContentAPIRouter(api, options) {
1833
- const app = new Hono();
1834
- app.use("/*", cors());
1835
- app.get("/auth/user", async (c) => {
1836
- const email = c.req.header("X-CF-User-Email");
1837
- const sub = c.req.header("X-CF-User-Sub");
1838
- if (!email) return c.json({ authenticated: false });
1839
- return c.json({
1840
- authenticated: true,
1841
- user: {
1842
- email,
1843
- sub
1844
- }
1845
- });
1846
- });
1847
- app.get("/content/collections", async (c) => {
1848
- try {
1849
- const allCollections = /* @__PURE__ */ new Set();
1850
- api.blocks.collections.forEach((c) => allCollections.add(c));
1851
- for (const siteName of Object.keys(api.sitesConfig.sites)) {
1852
- const site = api.getSite(siteName);
1853
- if (site) site.collections.forEach((c) => allCollections.add(c));
1854
- }
1855
- return c.json({ collections: Array.from(allCollections).sort() });
1856
- } catch (error) {
1857
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list collections"), 500);
1858
- }
1859
- });
1860
- app.get("/content", async (c) => {
1861
- const kind = c.req.query("kind");
1862
- const site = c.req.query("site");
1863
- const collection = c.req.query("collection");
1864
- const locales = c.req.query("locales");
1865
- const type = c.req.query("type");
1866
- const published = c.req.query("published");
1867
- const localization = c.req.query("localization");
1868
- const missingLocales = c.req.query("missingLocales");
1869
- try {
1870
- const filters = {};
1871
- if (kind) filters.kind = kind;
1872
- if (site) filters.site = site;
1873
- if (collection) filters.collection = collection;
1874
- if (locales) filters.locales = locales.split(",").map((l) => l.trim());
1875
- if (type) filters.type = type;
1876
- if (published !== void 0) filters.published = published === "true";
1877
- if (localization) filters.localization = localization;
1878
- if (missingLocales) filters.missingLocales = missingLocales.split(",").map((l) => l.trim());
1879
- const items = Array.from(api.listAllContent(filters));
1880
- return c.json({
1881
- items,
1882
- total: items.length
1883
- });
1884
- } catch (error) {
1885
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list content"), 500);
1886
- }
1887
- });
1888
- app.get("/content/:id", async (c) => {
1889
- const id = c.req.param("id");
1890
- try {
1891
- const content = await api.getContent(id);
1892
- if (!content) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
1893
- return c.json(content);
1894
- } catch (error) {
1895
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch content"), 500);
1896
- }
1897
- });
1898
- app.get("/content/:id/:locale", async (c) => {
1899
- const id = c.req.param("id");
1900
- const locale = c.req.param("locale");
1901
- try {
1902
- const content = await api.getLocalized(id, locale);
1903
- if (!content) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
1904
- c.header("ETag", content.localized.etag);
1905
- return c.json(content);
1906
- } catch (error) {
1907
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch localized content"), 500);
1908
- }
1909
- });
1910
- app.post("/content", async (c) => {
1911
- try {
1912
- const data = await c.req.json();
1913
- const result = await api.createContent(data);
1914
- if (!result.success) {
1915
- if (result.reason === "already_exists") return c.json(result, 409);
1916
- if (result.reason === "pathname_taken") return c.json(result, 409);
1917
- if (result.reason === "metadata_too_large") return c.json(result, 400);
1918
- return c.json(result, 500);
1919
- }
1920
- return c.json(result, 201);
1921
- } catch (error) {
1922
- console.error("[Content API] Failed to create content:", error);
1923
- return c.json({
1924
- success: false,
1925
- reason: "write_error",
1926
- error: error instanceof Error ? error.message : "Unknown error"
1927
- }, 500);
1928
- }
1929
- });
1930
- app.put("/content/:id", async (c) => {
1931
- const id = c.req.param("id");
1932
- const locale = c.req.query("locale");
1933
- const etag = c.req.query("etag") || "";
1934
- if (!locale) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "locale query parameter is required", { field: "locale" }), 400);
1935
- try {
1936
- const data = await c.req.json();
1937
- const result = await api.updateLocalized({
1938
- id,
1939
- locale,
1940
- data,
1941
- etag
1942
- });
1943
- if (!result.success) {
1944
- if (result.reason === "stale_write") return c.json(errorResponse(ErrorCodes.STALE_WRITE, "Content has been modified since you last loaded it", { currentEtag: result.currentEtag }), 412);
1945
- if (result.reason === "not_found") return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
1946
- return c.json(result, 500);
1947
- }
1948
- c.header("ETag", result.etag);
1949
- return c.json(result);
1950
- } catch (error) {
1951
- console.error("[Content API] Failed to update content:", error);
1952
- return c.json({
1953
- success: false,
1954
- reason: "write_error",
1955
- error: error instanceof Error ? error.message : "Unknown error"
1956
- }, 500);
1957
- }
1958
- });
1959
- app.patch("/content/:id", async (c) => {
1960
- const id = c.req.param("id");
1961
- const locale = c.req.query("locale");
1962
- const etag = c.req.query("etag") || "";
1963
- if (!locale) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "locale query parameter is required", { field: "locale" }), 400);
1964
- try {
1965
- const data = await c.req.json();
1966
- const result = await api.updateLocalized({
1967
- id,
1968
- locale,
1969
- data,
1970
- etag
1971
- });
1972
- if (!result.success) {
1973
- if (result.reason === "stale_write") return c.json(errorResponse(ErrorCodes.STALE_WRITE, "Content has been modified since you last loaded it", { currentEtag: result.currentEtag }), 412);
1974
- if (result.reason === "not_found") return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id }), 404);
1975
- return c.json(result, 500);
1976
- }
1977
- c.header("ETag", result.etag);
1978
- return c.json(result);
1979
- } catch (error) {
1980
- console.error("[Content API] Failed to patch content:", error);
1981
- return c.json({
1982
- success: false,
1983
- reason: "write_error",
1984
- error: error instanceof Error ? error.message : "Unknown error"
1985
- }, 500);
1986
- }
1987
- });
1988
- app.delete("/content/:id", async (c) => {
1989
- const id = c.req.param("id");
1990
- const locale = c.req.query("locale");
1991
- const ifMatch = c.req.header("If-Match") || "";
1992
- try {
1993
- let result;
1994
- if (locale) result = await api.deleteLocalized({
1995
- id,
1996
- locale,
1997
- etag: ifMatch
1998
- });
1999
- else result = await api.deleteContent(id, ifMatch);
2000
- if (!result.success) {
2001
- if (result.reason === "not_found") return c.json({
2002
- success: false,
2003
- error: "Content not found"
2004
- }, 404);
2005
- if (result.reason === "stale_write") return c.json({
2006
- success: false,
2007
- reason: result.reason,
2008
- currentEtag: result.currentEtag,
2009
- message: "Content has been modified"
2010
- }, 412);
2011
- return c.json(result, 500);
2012
- }
2013
- return c.json({ success: true });
2014
- } catch (error) {
2015
- console.error("[Content API] Failed to delete content:", error);
2016
- return c.json({
2017
- success: false,
2018
- error: error instanceof Error ? error.message : "Unknown error"
2019
- }, 500);
2020
- }
2021
- });
2022
- app.get("/data/collections", async (c) => {
2023
- try {
2024
- const collections = api.data.collections;
2025
- return c.json({ collections: Array.from(collections).sort() });
2026
- } catch (error) {
2027
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list data collections"), 500);
2028
- }
2029
- });
2030
- app.get("/data/name-available", async (c) => {
2031
- const name = c.req.query("name");
2032
- const collection = c.req.query("collection");
2033
- const excludeId = c.req.query("excludeId");
2034
- if (!name) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "name query parameter is required", { field: "name" }), 400);
2035
- if (!collection) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "collection query parameter is required", { field: "collection" }), 400);
2036
- try {
2037
- if (api.data.isNameAvailable(collection, name, excludeId)) return c.json({ available: true });
2038
- const existing = api.data.getByName(collection, name);
2039
- return c.json({
2040
- available: false,
2041
- existingId: existing?.id
2042
- });
2043
- } catch (error) {
2044
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to check data name availability"), 500);
2045
- }
2046
- });
2047
- app.get("/data", async (c) => {
2048
- const collection = c.req.query("collection");
2049
- const locale = c.req.query("locale");
2050
- try {
2051
- const filters = { kind: "data" };
2052
- if (collection) filters.collection = collection;
2053
- if (locale) filters.locales = [locale];
2054
- const items = Array.from(api.listAllContent(filters));
2055
- return c.json({
2056
- items,
2057
- total: items.length
2058
- });
2059
- } catch (error) {
2060
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list data entries"), 500);
2061
- }
2062
- });
2063
- app.get("/data/:name", async (c) => {
2064
- const name = c.req.param("name");
2065
- const collection = c.req.query("collection");
2066
- const locale = c.req.query("locale");
2067
- if (!collection) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "collection query parameter is required", { field: "collection" }), 400);
2068
- try {
2069
- const dataEntry = api.data.getByName(collection, name, locale);
2070
- if (!dataEntry) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Data entry not found", {
2071
- name,
2072
- collection
2073
- }), 404);
2074
- if (locale && dataEntry.locales[locale]) return c.json({
2075
- ...dataEntry,
2076
- locales: { [locale]: dataEntry.locales[locale] }
2077
- });
2078
- return c.json(dataEntry);
2079
- } catch (error) {
2080
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch data entry"), 500);
2081
- }
2082
- });
2083
- if (options?.assetsPath) {
2084
- const assetOps = new AssetOperations({
2085
- assetsPath: options.assetsPath,
2086
- contentRoot: options.contentRoot,
2087
- ...options.assetConfig
2088
- });
2089
- function splitAssetPath(relativePath) {
2090
- const lastSlash = relativePath.lastIndexOf("/");
2091
- if (lastSlash > 0) return {
2092
- folder: `/${relativePath.slice(0, lastSlash)}`,
2093
- filename: relativePath.slice(lastSlash + 1)
2094
- };
2095
- return {
2096
- folder: "/",
2097
- filename: relativePath
2098
- };
2099
- }
2100
- app.post("/assets/move", async (c) => {
2101
- try {
2102
- const { filenames, sourceFolder, targetFolder } = await c.req.json();
2103
- if (!Array.isArray(filenames)) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "filenames must be an array"), 400);
2104
- if (typeof sourceFolder !== "string") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "sourceFolder is required"), 400);
2105
- if (typeof targetFolder !== "string") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "targetFolder is required"), 400);
2106
- const result = await assetOps.moveAssets(filenames, sourceFolder, targetFolder);
2107
- if (!result.success) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
2108
- return c.json(result);
2109
- } catch (error) {
2110
- if (error instanceof Error && error.message === "Path traversal detected") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Invalid folder path"), 400);
2111
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to move assets"), 500);
2112
- }
2113
- });
2114
- app.post("/assets/upload", async (c) => {
2115
- try {
2116
- const body = await c.req.parseBody();
2117
- const file = body.file;
2118
- if (!(file instanceof File)) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "No file provided in \"file\" field"), 400);
2119
- const alt = typeof body.alt === "string" ? body.alt : void 0;
2120
- const uploadedBy = typeof body.uploadedBy === "string" ? body.uploadedBy : void 0;
2121
- const width = typeof body.width === "string" ? Number.parseInt(body.width, 10) : void 0;
2122
- const height = typeof body.height === "string" ? Number.parseInt(body.height, 10) : void 0;
2123
- const folder = typeof body.folder === "string" ? body.folder : void 0;
2124
- const result = await assetOps.upload(file, {
2125
- alt,
2126
- uploadedBy,
2127
- width,
2128
- height,
2129
- folder
2130
- });
2131
- if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
2132
- return c.json(result.asset, 201);
2133
- } catch (error) {
2134
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, "Upload failed"), 500);
2135
- }
2136
- });
2137
- app.post("/assets/import-url", async (c) => {
2138
- try {
2139
- const { url, alt, uploadedBy, folder } = await c.req.json();
2140
- if (!url) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "url is required"), 400);
2141
- const result = await assetOps.importFromUrl(url, {
2142
- alt,
2143
- uploadedBy,
2144
- folder
2145
- });
2146
- if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_UPLOAD_FAILED, result.error), 400);
2147
- return c.json(result.asset, 201);
2148
- } catch (error) {
2149
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.ASSET_UPLOAD_FAILED, "URL import failed"), 500);
2150
- }
2151
- });
2152
- app.get("/assets", async (c) => {
2153
- try {
2154
- const assets = await assetOps.list();
2155
- return c.json({ assets });
2156
- } catch (error) {
2157
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list assets"), 500);
2158
- }
2159
- });
2160
- app.get("/assets/folders", async (c) => {
2161
- try {
2162
- const path = c.req.query("path") || "/";
2163
- const result = await assetOps.listFolder(path);
2164
- return c.json(result);
2165
- } catch (error) {
2166
- if (error instanceof Error && error.message === "Path traversal detected") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Invalid folder path"), 400);
2167
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list folder"), 500);
2168
- }
2169
- });
2170
- app.post("/assets/folders", async (c) => {
2171
- try {
2172
- const { path } = await c.req.json();
2173
- if (!path) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "path is required"), 400);
2174
- const result = await assetOps.createFolder(path);
2175
- if (!result.success) return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, result.error), 400);
2176
- return c.json({ success: true }, 201);
2177
- } catch (error) {
2178
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to create folder"), 500);
2179
- }
2180
- });
2181
- app.get("/assets/folder-tree", async (c) => {
2182
- try {
2183
- const tree = await assetOps.getFolderTree();
2184
- return c.json({ tree });
2185
- } catch (error) {
2186
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get folder tree"), 500);
2187
- }
2188
- });
2189
- app.get("/assets/usage/:path{.+}", async (c) => {
2190
- try {
2191
- const { filename } = splitAssetPath(c.req.param("path"));
2192
- const usage = await assetOps.getUsage(filename);
2193
- return c.json({ usage });
2194
- } catch (error) {
2195
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get asset usage"), 500);
2196
- }
2197
- });
2198
- app.get("/assets/serve/:path{.+}", async (c) => {
2199
- try {
2200
- const { folder, filename } = splitAssetPath(c.req.param("path"));
2201
- const result = await assetOps.readAssetFile(filename, folder);
2202
- if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
2203
- return new Response(new Uint8Array(result.buffer), { headers: {
2204
- "Content-Type": result.mimeType,
2205
- "Cache-Control": "public, max-age=31536000, immutable"
2206
- } });
2207
- } catch (error) {
2208
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to serve asset"), 500);
2209
- }
2210
- });
2211
- app.get("/assets/meta/:path{.+}", async (c) => {
2212
- try {
2213
- const { folder, filename } = splitAssetPath(c.req.param("path"));
2214
- const asset = await assetOps.getAsset(filename, folder);
2215
- if (!asset) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, "Asset not found"), 404);
2216
- return c.json(asset);
2217
- } catch (error) {
2218
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to get asset"), 500);
2219
- }
2220
- });
2221
- app.patch("/assets/meta/:path{.+}", async (c) => {
2222
- try {
2223
- const { folder, filename } = splitAssetPath(c.req.param("path"));
2224
- const { alt, tags } = await c.req.json();
2225
- const result = await assetOps.updateMetadata(filename, {
2226
- alt,
2227
- tags
2228
- }, folder);
2229
- if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
2230
- return c.json(result.asset);
2231
- } catch (error) {
2232
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to update asset"), 500);
2233
- }
2234
- });
2235
- app.delete("/assets/meta/:path{.+}", async (c) => {
2236
- try {
2237
- const { folder, filename } = splitAssetPath(c.req.param("path"));
2238
- const result = await assetOps.delete(filename, folder);
2239
- if (!result.success) return c.json(errorResponse(ErrorCodes.ASSET_NOT_FOUND, result.error), 404);
2240
- return c.json({ success: true });
2241
- } catch (error) {
2242
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to delete asset"), 500);
2243
- }
2244
- });
2245
- }
2246
- app.get("/:site/collections", async (c) => {
2247
- const site = c.req.param("site");
2248
- try {
2249
- if (site === "blocks") {
2250
- const collections = Array.from(api.blocks.collections).sort();
2251
- return c.json({ collections });
2252
- }
2253
- const siteObj = api.getSite(site);
2254
- if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
2255
- const collections = Array.from(siteObj.collections).sort();
2256
- return c.json({ collections });
2257
- } catch (error) {
2258
- return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
2259
- }
2260
- });
2261
- app.get("/:site/pages", async (c) => {
2262
- const site = c.req.param("site");
2263
- const locale = c.req.query("locale");
2264
- try {
2265
- if (site === "blocks") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Blocks do not have pages. Use /content?kind=block to list blocks."), 400);
2266
- const siteObj = api.getSite(site);
2267
- if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
2268
- const items = Array.from(siteObj.listContent(locale ? { locales: [locale] } : {}));
2269
- const result = {
2270
- items,
2271
- total: items.length
2272
- };
2273
- return c.json(result);
2274
- } catch (error) {
2275
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, `Failed to list pages for site '${site}'`, { site }), 500);
2276
- }
2277
- });
2278
- app.get("/:site/pathname-available", async (c) => {
2279
- const site = c.req.param("site");
2280
- const pathname = c.req.query("pathname");
2281
- const locale = c.req.query("locale") || "en";
2282
- const excludeId = c.req.query("excludeId");
2283
- if (!pathname) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "pathname query parameter is required", { field: "pathname" }), 400);
2284
- try {
2285
- if (site === "blocks") return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Blocks do not have pathnames. This endpoint is only for page content."), 400);
2286
- const siteObj = api.getSite(site);
2287
- if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
2288
- if (siteObj.isPathnameAvailable(pathname, locale, excludeId)) return c.json({ available: true });
2289
- const existingId = siteObj.getPathnameConflict(pathname, locale, excludeId);
2290
- return c.json({
2291
- available: false,
2292
- existingId
2293
- });
2294
- } catch (error) {
2295
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to check pathname availability"), 500);
2296
- }
2297
- });
2298
- app.get("/blocks", async (c) => {
2299
- const collection = c.req.query("collection");
2300
- const locale = c.req.query("locale");
2301
- try {
2302
- const filters = { kind: "block" };
2303
- if (collection) filters.collection = collection;
2304
- if (locale) filters.locales = [locale];
2305
- const items = Array.from(api.listAllContent(filters));
2306
- return c.json({
2307
- items,
2308
- total: items.length
2309
- });
2310
- } catch (error) {
2311
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to list blocks"), 500);
2312
- }
2313
- });
2314
- app.get("/blocks/name-available", async (c) => {
2315
- const name = c.req.query("name");
2316
- const collection = c.req.query("collection") || "components";
2317
- const locale = c.req.query("locale") || "en";
2318
- const excludeId = c.req.query("excludeId");
2319
- if (!name) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "name query parameter is required", { field: "name" }), 400);
2320
- try {
2321
- const existing = Array.from(api.listAllContent({
2322
- kind: "block",
2323
- collection,
2324
- locales: [locale]
2325
- }));
2326
- let taken;
2327
- for (const item of existing) for (const localeVersion of localesOf(item)) if (localeVersion.name === name) {
2328
- taken = item;
2329
- break;
2330
- }
2331
- if (!taken) return c.json({ available: true });
2332
- if (excludeId && taken.id === excludeId) return c.json({ available: true });
2333
- return c.json({
2334
- available: false,
2335
- existingId: taken.id
2336
- });
2337
- } catch (error) {
2338
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to check block name availability"), 500);
2339
- }
2340
- });
2341
- app.get("/blocks/:name", async (c) => {
2342
- const name = c.req.param("name");
2343
- const collection = c.req.query("collection") || "components";
2344
- const locale = c.req.query("locale");
2345
- try {
2346
- const block = api.blocks.getByName(collection, name, locale);
2347
- if (!block) return c.json(errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Block not found", {
2348
- name,
2349
- collection
2350
- }), 404);
2351
- if (locale && block.locales[locale]) return c.json({
2352
- ...block,
2353
- locales: { [locale]: block.locales[locale] }
2354
- });
2355
- return c.json(block);
2356
- } catch (error) {
2357
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch block"), 500);
2358
- }
2359
- });
2360
- app.post("/:site/move", async (c) => {
2361
- const site = c.req.param("site");
2362
- try {
2363
- const { id, pathname, locale, etag } = await c.req.json();
2364
- if (!id || !pathname || !locale || !etag) return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "id, pathname, locale, and etag are required"), 400);
2365
- const siteObj = api.getSite(site);
2366
- if (!siteObj) return c.json(errorResponse(ErrorCodes.SITE_NOT_FOUND, `Site '${site}' not found`, { site }), 404);
2367
- const existing = siteObj.getByPathname(pathname, locale);
2368
- if (existing && existing.id !== id) return c.json({
2369
- moved: false,
2370
- reason: "already_exists",
2371
- ...errorResponse(ErrorCodes.PATHNAME_TAKEN, "Pathname already taken", { existingId: existing.id })
2372
- }, 409);
2373
- const current = await api.getLocalized(id, locale);
2374
- if (!current) return c.json({
2375
- moved: false,
2376
- ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id })
2377
- }, 404);
2378
- const previousPathname = current.localized.pathname;
2379
- const updateResult = await api.updateLocalized({
2380
- id,
2381
- locale,
2382
- data: {
2383
- pathname,
2384
- meta: current.localized.meta
2385
- },
2386
- etag
2387
- });
2388
- if (!updateResult.success) {
2389
- if (updateResult.reason === "stale_write") return c.json({
2390
- moved: false,
2391
- reason: "stale_write",
2392
- currentEtag: updateResult.currentEtag,
2393
- message: "Content has been modified"
2394
- }, 412);
2395
- if (updateResult.reason === "not_found") return c.json({
2396
- moved: false,
2397
- ...errorResponse(ErrorCodes.CONTENT_NOT_FOUND, "Content not found", { id })
2398
- }, 404);
2399
- return c.json({
2400
- moved: false,
2401
- ...errorResponse(ErrorCodes.WRITE_ERROR, "Update failed")
2402
- }, 500);
2403
- }
2404
- return c.json({
2405
- moved: true,
2406
- previousPathname,
2407
- etag: updateResult.etag
2408
- });
2409
- } catch (error) {
2410
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to move page"), 500);
2411
- }
2412
- });
2413
- app.get("/untranslated/:targetLocale", async (c) => {
2414
- const targetLocale = c.req.param("targetLocale");
2415
- const excludeSites = c.req.query("excludeSites")?.split(",").map((s) => s.trim()).filter((s) => s);
2416
- const includeUnpublished = c.req.query("includeUnpublished") === "true";
2417
- try {
2418
- const options = {
2419
- ...excludeSites?.length && { excludeSites },
2420
- ...includeUnpublished && { includeUnpublished }
2421
- };
2422
- const items = Array.from(api.findUntranslatedContent(targetLocale, options));
2423
- return c.json({
2424
- items,
2425
- total: items.length
2426
- });
2427
- } catch (error) {
2428
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.INTERNAL_ERROR, "Failed to find untranslated content"), 500);
2429
- }
2430
- });
2431
- app.get("/sites", async (c) => {
2432
- try {
2433
- const config = api.sitesConfig;
2434
- return c.json(config);
2435
- } catch (error) {
2436
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.FETCH_ERROR, "Failed to fetch sites configuration"), 500);
2437
- }
2438
- });
2439
- app.post("/content/batch", async (c) => {
2440
- try {
2441
- const { operations } = await c.req.json();
2442
- const result = await api.batchUpdate(operations);
2443
- if (!result.success) return c.json(result, 207);
2444
- return c.json(result);
2445
- } catch (error) {
2446
- console.error("[Content API] Failed to batch update:", error);
2447
- return c.json({
2448
- success: false,
2449
- error: error instanceof Error ? error.message : "Unknown error"
2450
- }, 500);
2451
- }
2452
- });
2453
- /**
2454
- * Get git config from router options or environment variables.
2455
- * contentRoot from router options takes priority over CONTENT_PATH env var.
2456
- * Optional: GIT_BRANCH (defaults to current checked-out branch)
2457
- */
2458
- function getGitConfig() {
2459
- const contentPath = options?.contentRoot || process.env.CONTENT_PATH;
2460
- if (!contentPath) throw new Error("contentRoot option or CONTENT_PATH environment variable is required for git operations");
2461
- return {
2462
- contentPath,
2463
- branch: process.env.GIT_BRANCH
2464
- };
2465
- }
2466
- app.get("/git/status", async (c) => {
2467
- try {
2468
- const status = await createGitOperations(getGitConfig()).getStatus();
2469
- if (!status.isRepo) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, "Repository not accessible"), 400);
2470
- return c.json(status);
2471
- } catch (error) {
2472
- if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
2473
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_STATUS_FAILED, "Failed to get git status"), 500);
2474
- }
2475
- });
2476
- app.post("/git/commit", async (c) => {
2477
- try {
2478
- const body = await c.req.json().catch(() => ({}));
2479
- const date = /* @__PURE__ */ new Date();
2480
- const defaultMessage = `CMS changes - ${[
2481
- "Jan",
2482
- "Feb",
2483
- "Mar",
2484
- "Apr",
2485
- "May",
2486
- "Jun",
2487
- "Jul",
2488
- "Aug",
2489
- "Sep",
2490
- "Oct",
2491
- "Nov",
2492
- "Dec"
2493
- ][date.getMonth()]} ${date.getDate()}`;
2494
- const message = body.message || defaultMessage;
2495
- const userEmail = c.req.header("X-CF-User-Email");
2496
- const author = userEmail ? {
2497
- name: userEmail.split("@")[0],
2498
- email: userEmail
2499
- } : void 0;
2500
- const result = await createGitOperations(getGitConfig()).commitAll(message, author);
2501
- if (!result.success) return c.json(errorResponse(ErrorCodes.GIT_COMMIT_FAILED, result.error || "Commit failed"), 500);
2502
- return c.json(result);
2503
- } catch (error) {
2504
- if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
2505
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_COMMIT_FAILED, "Failed to commit changes"), 500);
2506
- }
2507
- });
2508
- app.post("/git/push", async (c) => {
2509
- try {
2510
- const result = await createGitOperations(getGitConfig()).pushOrigin();
2511
- if (!result.success) return c.json(errorResponse(ErrorCodes.GIT_PUSH_FAILED, result.error || "Push failed"), 500);
2512
- return c.json(result);
2513
- } catch (error) {
2514
- if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
2515
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PUSH_FAILED, "Failed to push to origin"), 500);
2516
- }
2517
- });
2518
- app.post("/git/pull", async (c) => {
2519
- try {
2520
- const result = await createGitOperations(getGitConfig()).pull();
2521
- if (!result.success) return c.json(errorResponse(ErrorCodes.GIT_PULL_FAILED, result.error || "Pull failed"), 500);
2522
- return c.json(result);
2523
- } catch (error) {
2524
- if (error instanceof Error && (error.message.includes("contentRoot") || error.message.includes("CONTENT_PATH"))) return c.json(errorResponse(ErrorCodes.GIT_NOT_REPO, error.message), 400);
2525
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.GIT_PULL_FAILED, "Failed to pull from origin"), 500);
2526
- }
2527
- });
2528
- app.post("/mdx/compile", async (c) => {
2529
- try {
2530
- let body;
2531
- try {
2532
- body = await c.req.json();
2533
- } catch {
2534
- return c.json(errorResponse(ErrorCodes.INVALID_REQUEST, "Invalid JSON body"), 400);
2535
- }
2536
- const mdxContent = typeof body === "object" && body !== null ? body.mdxContent : null;
2537
- if (!mdxContent || typeof mdxContent !== "string") return c.json(errorResponse(ErrorCodes.MISSING_REQUIRED_FIELD, "mdxContent string required", { field: "mdxContent" }), 400);
2538
- const { code, metadata } = await compileMDX(mdxContent);
2539
- return c.json({
2540
- code,
2541
- metadata
2542
- });
2543
- } catch (error) {
2544
- return c.json(logAndCreateErrorResponse(error, ErrorCodes.MDX_COMPILE_FAILED, errorMessage(error, "Failed to compile MDX")), 422);
2545
- }
2546
- });
2547
- return app;
2548
- }
2549
- /**
2550
- * Create middleware for backwards compatibility with existing code
2551
- * This wraps the Hono app to work with Node.js IncomingMessage/ServerResponse
2552
- */
2553
- function createContentMiddleware(contentApi) {
2554
- const app = createContentAPIRouter(contentApi);
2555
- return async (req, res, next) => {
2556
- const url = new URL(req.url, `http://${req.headers.host}`);
2557
- const basePath = url.pathname.startsWith("/__cms/api") ? "/__cms/api" : "/__conloca/api";
2558
- if (!url.pathname.startsWith(basePath)) return next();
2559
- const path = url.pathname.replace(basePath, "");
2560
- const request = new Request(`http://localhost${path}${url.search}`, {
2561
- method: req.method,
2562
- headers: req.headers,
2563
- body: ["GET", "HEAD"].includes(req.method) ? void 0 : await readBody(req)
2564
- });
2565
- const response = await app.fetch(request);
2566
- response.headers.forEach((value, key) => {
2567
- res.setHeader(key, value);
2568
- });
2569
- res.statusCode = response.status;
2570
- const body = await response.text();
2571
- res.end(body);
2572
- };
2573
- }
2574
- function readBody(req) {
2575
- return new Promise((resolve, reject) => {
2576
- const chunks = [];
2577
- req.on("data", (chunk) => chunks.push(new Uint8Array(chunk)));
2578
- req.on("end", () => {
2579
- const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
2580
- const combined = new Uint8Array(totalLength);
2581
- let offset = 0;
2582
- for (const chunk of chunks) {
2583
- combined.set(chunk, offset);
2584
- offset += chunk.length;
2585
- }
2586
- resolve(Buffer.from(combined).toString());
2587
- });
2588
- req.on("error", reject);
2589
- });
2590
- }
2591
-
2592
- //#endregion
2593
- //#region src/vite-plugin.ts
2594
- /**
2595
- * Vite plugin wrapper for content middleware
2596
- * This follows the spec in 04-cms-api.md and 09-conloca-content-editing.md
2597
- */
2598
- function conlocaContent(options) {
2599
- let contentApi;
2600
- const basePath = options.basePath || "/__conloca/api/content";
2601
- return {
2602
- name: "vite-plugin-conloca-content",
2603
- async configureServer(server) {
2604
- contentApi = await createContentAPI(options);
2605
- server.watcher.add(options.contentRoot);
2606
- const app = createContentAPIRouter(contentApi);
2607
- server.middlewares.use(basePath, getRequestListener(app.fetch));
2608
- const handlers = createContentWatchHandlers(contentApi, options, server.ws);
2609
- server.watcher.on("change", handlers.onChange);
2610
- server.watcher.on("add", handlers.onAdd);
2611
- server.watcher.on("unlink", handlers.onUnlink);
2612
- }
2613
- };
2614
- }
2615
-
2616
- //#endregion
2617
- export { AssetManifest, AssetOperations, Blocks, ComponentRegistry, ErrorCodes, FileSystemContentAPI, InMemoryContentAPI, Site, UPDATE_SCOPE, analyzeUpdateScope, buildLocaleVersion, buildPathnameHistory, compileMDX, conlocaContent, createContentAPI, createContentAPIRouter, createContentMiddleware, createContentWatchHandlers, extractBlockName, extractCFAccessToken, formatFileSize, generateContentId, getCurrentISODate, getMetadataSize, isContentPublished, isMetadataTooLarge, isValidBlockName, isValidPathname, localesOf, mapLocales, mapSiteNames, normalizePathname, parseDate, resolvePublishDate, serializeMdxWithFrontmatter, shouldUpdateModifiedTimestamp, updatePublishDates, validateAndPrepareMetadata, validateCFAccessRequest, validateCreateContent };
2618
- //# sourceMappingURL=node.mjs.map