@conloca/astro-cms 0.1.15 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -5
- package/dist/collections-Bd7EME4b.mjs +129 -0
- package/dist/collections-Bd7EME4b.mjs.map +1 -0
- package/dist/collections.d.mts +0 -1
- package/dist/collections.d.mts.map +1 -1
- package/dist/collections.mjs +1 -64
- package/dist/components.d.mts +2 -7
- package/dist/components.d.mts.map +1 -1
- package/dist/components.mjs +3 -6
- package/dist/components.mjs.map +1 -1
- package/dist/hydration.d.mts +2 -2
- package/dist/hydration.mjs +2 -3
- package/dist/index.d.mts +6 -37
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +7 -6
- package/dist/index.mjs.map +1 -1
- package/dist/internal/cms-handler.d.mts +0 -1
- package/dist/internal/cms-handler.d.mts.map +1 -1
- package/dist/internal/cms-handler.mjs +55 -8
- package/dist/internal/cms-handler.mjs.map +1 -1
- package/dist/lib/hydration-script.d.mts +1 -2
- package/dist/lib/hydration-script.d.mts.map +1 -1
- package/dist/lib/hydration-script.mjs +1 -2
- package/dist/lib/hydration-script.mjs.map +1 -1
- package/dist/locales-helpers-BvYYqnJ5.d.mts +64 -0
- package/dist/locales-helpers-BvYYqnJ5.d.mts.map +1 -0
- package/dist/locales-helpers-qiwh7nxS.mjs +54 -0
- package/dist/locales-helpers-qiwh7nxS.mjs.map +1 -0
- package/dist/node/content.d.mts +0 -1
- package/dist/node/content.d.mts.map +1 -1
- package/dist/node/content.d.ts +3 -0
- package/dist/node/content.d.ts.map +1 -0
- package/dist/node/content.js +2 -0
- package/dist/node/content.mjs +2 -4
- package/dist/node/index.d.mts +151 -3
- package/dist/node/index.d.mts.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node/index.js +3 -0
- package/dist/node/index.mjs +1857 -97
- package/dist/node/index.mjs.map +1 -1
- package/dist/{serialize-props-Dhv_MnkY.mjs → serialize-props-BHoNpzH6.mjs} +2 -3
- package/dist/{serialize-props-Dhv_MnkY.mjs.map → serialize-props-BHoNpzH6.mjs.map} +1 -1
- package/dist/src/cms-handler.d.ts +19 -0
- package/dist/src/cms-handler.d.ts.map +1 -0
- package/dist/src/cms-handler.js +366 -0
- package/dist/src/collections.d.ts +32 -0
- package/dist/src/collections.d.ts.map +1 -0
- package/dist/src/collections.js +50 -0
- package/dist/src/components/HydrationWrapper.d.ts +18 -0
- package/dist/src/components/HydrationWrapper.d.ts.map +1 -0
- package/dist/src/components/HydrationWrapper.js +21 -0
- package/dist/src/components/RenderWithBlocks.d.ts +23 -0
- package/dist/src/components/RenderWithBlocks.d.ts.map +1 -0
- package/dist/src/components/RenderWithBlocks.js +129 -0
- package/dist/src/components/RenderWithHydration.d.ts +17 -0
- package/dist/src/components/RenderWithHydration.d.ts.map +1 -0
- package/dist/src/components/RenderWithHydration.js +36 -0
- package/dist/src/components.d.ts +4 -0
- package/dist/src/components.d.ts.map +1 -0
- package/dist/src/components.js +3 -0
- package/dist/src/discovery/astro-frontmatter.d.ts +18 -0
- package/dist/src/discovery/astro-frontmatter.d.ts.map +1 -0
- package/dist/src/discovery/astro-frontmatter.js +24 -0
- package/dist/src/discovery/extract-props-ts.d.ts +41 -0
- package/dist/src/discovery/extract-props-ts.d.ts.map +1 -0
- package/dist/src/discovery/extract-props-ts.js +231 -0
- package/dist/src/discovery/merge-registry.d.ts +58 -0
- package/dist/src/discovery/merge-registry.d.ts.map +1 -0
- package/dist/src/discovery/merge-registry.js +332 -0
- package/dist/src/discovery/registry-endpoint.d.ts +42 -0
- package/dist/src/discovery/registry-endpoint.d.ts.map +1 -0
- package/dist/src/discovery/registry-endpoint.js +81 -0
- package/dist/src/discovery/scan-components.d.ts +98 -0
- package/dist/src/discovery/scan-components.d.ts.map +1 -0
- package/dist/src/discovery/scan-components.js +399 -0
- package/dist/src/discovery/scan-mdx.d.ts +63 -0
- package/dist/src/discovery/scan-mdx.d.ts.map +1 -0
- package/dist/src/discovery/scan-mdx.js +112 -0
- package/dist/src/discovery/scan-overrides.d.ts +71 -0
- package/dist/src/discovery/scan-overrides.d.ts.map +1 -0
- package/dist/src/discovery/scan-overrides.js +33 -0
- package/dist/src/hydration.d.ts +4 -0
- package/dist/src/hydration.d.ts.map +1 -0
- package/dist/src/hydration.js +4 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +25 -0
- package/dist/src/lib/hydration-scanner.d.ts +47 -0
- package/dist/src/lib/hydration-scanner.d.ts.map +1 -0
- package/dist/src/lib/hydration-scanner.js +135 -0
- package/dist/src/lib/hydration-script.d.ts +28 -0
- package/dist/src/lib/hydration-script.d.ts.map +1 -0
- package/dist/src/lib/hydration-script.js +88 -0
- package/dist/src/lib/hydration-utils.d.ts +51 -0
- package/dist/src/lib/hydration-utils.d.ts.map +1 -0
- package/dist/src/lib/hydration-utils.js +83 -0
- package/dist/src/lib/page-api.d.ts +77 -0
- package/dist/src/lib/page-api.d.ts.map +1 -0
- package/dist/src/lib/page-api.js +121 -0
- package/dist/src/lib/route-utils.d.ts +41 -0
- package/dist/src/lib/route-utils.d.ts.map +1 -0
- package/dist/src/lib/route-utils.js +78 -0
- package/dist/src/lib/routing-config.d.ts +32 -0
- package/dist/src/lib/routing-config.d.ts.map +1 -0
- package/dist/src/lib/routing-config.js +93 -0
- package/dist/src/lib/serialize-props.d.ts +6 -0
- package/dist/src/lib/serialize-props.d.ts.map +1 -0
- package/dist/src/lib/serialize-props.js +7 -0
- package/dist/src/lib/virtual-module-generators.d.ts +57 -0
- package/dist/src/lib/virtual-module-generators.d.ts.map +1 -0
- package/dist/src/lib/virtual-module-generators.js +263 -0
- package/dist/src/lib/withHydration.d.ts +51 -0
- package/dist/src/lib/withHydration.d.ts.map +1 -0
- package/dist/src/lib/withHydration.js +49 -0
- package/dist/src/loader.d.ts +14 -0
- package/dist/src/loader.d.ts.map +1 -0
- package/dist/src/loader.js +89 -0
- package/dist/src/locales-helpers.d.ts +61 -0
- package/dist/src/locales-helpers.d.ts.map +1 -0
- package/dist/src/locales-helpers.js +49 -0
- package/dist/src/mime-types.d.ts +3 -0
- package/dist/src/mime-types.d.ts.map +1 -0
- package/dist/src/mime-types.js +19 -0
- package/dist/src/path-validation.d.ts +8 -0
- package/dist/src/path-validation.d.ts.map +1 -0
- package/dist/src/path-validation.js +12 -0
- package/dist/src/plugin-spa.d.ts +164 -0
- package/dist/src/plugin-spa.d.ts.map +1 -0
- package/dist/src/plugin-spa.js +972 -0
- package/dist/src/safe-json-stringify.d.ts +13 -0
- package/dist/src/safe-json-stringify.d.ts.map +1 -0
- package/dist/src/safe-json-stringify.js +6 -0
- package/dist/src/site-styles/content-wrapper-endpoint.d.ts +76 -0
- package/dist/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -0
- package/dist/src/site-styles/content-wrapper-endpoint.js +227 -0
- package/dist/src/site-styles/render-endpoint.d.ts +55 -0
- package/dist/src/site-styles/render-endpoint.d.ts.map +1 -0
- package/dist/src/site-styles/render-endpoint.js +263 -0
- package/dist/src/site-styles/styles-endpoint.d.ts +61 -0
- package/dist/src/site-styles/styles-endpoint.d.ts.map +1 -0
- package/dist/src/site-styles/styles-endpoint.js +158 -0
- package/dist/src/types.d.ts +627 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +1 -0
- package/dist/{types-CVQNmPxF.d.mts → types-CS9neadI.d.mts} +193 -3
- package/dist/types-CS9neadI.d.mts.map +1 -0
- package/dist/virtual-modules.d.ts +155 -0
- package/dist/{withHydration-EzyzBQ-Y.mjs → withHydration-C256ox_6.mjs} +2 -2
- package/dist/{withHydration-EzyzBQ-Y.mjs.map → withHydration-C256ox_6.mjs.map} +1 -1
- package/dist/{withHydration-HIvO9ysY.d.mts → withHydration-DkKpkmzJ.d.mts} +1 -2
- package/dist/withHydration-DkKpkmzJ.d.mts.map +1 -0
- package/package.json +82 -26
- package/dist/collections.mjs.map +0 -1
- package/dist/hydration-scanner-B0NjYkZ_.mjs +0 -109
- package/dist/hydration-scanner-B0NjYkZ_.mjs.map +0 -1
- package/dist/loader-By-AQWHc.mjs +0 -68
- package/dist/loader-By-AQWHc.mjs.map +0 -1
- package/dist/types-CVQNmPxF.d.mts.map +0 -1
- package/dist/withHydration-HIvO9ysY.d.mts.map +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join, resolve, sep } from "node:path";
|
|
4
|
+
import { ErrorCodes, FileSystemContentAPI, createContentAPI, createContentAPIRouter, validateCFAccessRequest } from "@conloca/content-api/node";
|
|
5
|
+
import { compileMDX } from "@conloca/mdx/node";
|
|
4
6
|
import spaConfig from "virtual:conloca-config";
|
|
5
7
|
import { contentOptions, getDataCollection, getPagesByPrefix } from "virtual:conloca-page-api";
|
|
6
8
|
import routingConfig from "virtual:conloca-routing-config";
|
|
7
|
-
import { FileSystemContentAPI, createContentAPI, createContentAPIRouter, validateCFAccessRequest } from "@conloca/content-api/node";
|
|
8
|
-
|
|
9
9
|
//#region src/mime-types.ts
|
|
10
10
|
/** MIME types for SPA static asset serving. Covers all file types produced by the cms-spa build. */
|
|
11
11
|
const SPA_MIME_TYPES = {
|
|
@@ -26,7 +26,6 @@ const SPA_MIME_TYPES = {
|
|
|
26
26
|
".map": "application/json",
|
|
27
27
|
".ico": "image/x-icon"
|
|
28
28
|
};
|
|
29
|
-
|
|
30
29
|
//#endregion
|
|
31
30
|
//#region src/path-validation.ts
|
|
32
31
|
/**
|
|
@@ -40,7 +39,6 @@ function isPathWithinBase(basePath, targetPath) {
|
|
|
40
39
|
const resolvedTarget = resolve(targetPath);
|
|
41
40
|
return resolvedTarget === resolvedBase || resolvedTarget.startsWith(resolvedBase + sep);
|
|
42
41
|
}
|
|
43
|
-
|
|
44
42
|
//#endregion
|
|
45
43
|
//#region src/safe-json-stringify.ts
|
|
46
44
|
function safeJsonStringify(data) {
|
|
@@ -48,9 +46,23 @@ function safeJsonStringify(data) {
|
|
|
48
46
|
if (json === void 0) return void 0;
|
|
49
47
|
return json.replace(/[<>&']/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
50
48
|
}
|
|
51
|
-
|
|
52
49
|
//#endregion
|
|
53
50
|
//#region src/cms-handler.ts
|
|
51
|
+
/**
|
|
52
|
+
* Read the top-level locales options from build-time env vars.
|
|
53
|
+
* `CONLOCA_LOCALES` is inlined as a JS array (or `null`) by Vite's
|
|
54
|
+
* `define`; `CONLOCA_DEFAULT_LOCALE` is a string (or `''`). When neither
|
|
55
|
+
* is set, returns an empty object so the spread is a no-op and the
|
|
56
|
+
* content-api falls back to sites.json (the existing behavior).
|
|
57
|
+
*/
|
|
58
|
+
function localesFromEnv() {
|
|
59
|
+
const list = import.meta.env.CONLOCA_LOCALES;
|
|
60
|
+
const defaultLocale = import.meta.env.CONLOCA_DEFAULT_LOCALE;
|
|
61
|
+
return {
|
|
62
|
+
...Array.isArray(list) && list.length > 0 ? { availableLocales: list } : {},
|
|
63
|
+
...typeof defaultLocale === "string" && defaultLocale ? { defaultLocale } : {}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
54
66
|
const cmsSpaPath = dirname(createRequire(import.meta.url).resolve("@conloca/cms-spa/package.json"));
|
|
55
67
|
/**
|
|
56
68
|
* Unified CMS handler - single entry point for all CMS routes.
|
|
@@ -92,6 +104,7 @@ function generateDevHtml(config) {
|
|
|
92
104
|
<title>Conloca CMS</title>
|
|
93
105
|
<link rel="stylesheet" href="${config.basename}/main.css" />
|
|
94
106
|
<script type="module" src="${config.basename}/site-styles.js"><\/script>
|
|
107
|
+
<script type="module" src="${config.basename}/editor-styles.js"><\/script>
|
|
95
108
|
<script>
|
|
96
109
|
// Configure UI with plugin options
|
|
97
110
|
window.__UI_CONFIG__ = ${safeJsonStringify(config)};
|
|
@@ -133,6 +146,7 @@ async function handleSpa(params, request) {
|
|
|
133
146
|
window.__UI_CONFIG__ = ${safeJsonStringify(spaConfig)};
|
|
134
147
|
<\/script>
|
|
135
148
|
<script type="module" src="${spaConfig.basename}/site-styles.js"><\/script>
|
|
149
|
+
<script type="module" src="${spaConfig.basename}/editor-styles.js"><\/script>
|
|
136
150
|
<script type="module" src="${spaConfig.basename}/schemas-entry.js"><\/script>
|
|
137
151
|
<script type="module" src="${spaConfig.basename}/puck-entry.js"><\/script>
|
|
138
152
|
<script type="module" src="${spaConfig.basename}/content-listener.js"><\/script>
|
|
@@ -179,7 +193,8 @@ async function handleDataContext(request) {
|
|
|
179
193
|
if (!config.enabled) return jsonResponse({});
|
|
180
194
|
const contentApi = await createContentAPI({
|
|
181
195
|
contentRoot: contentOptions.contentRoot,
|
|
182
|
-
canvasDir: contentOptions.canvasDir
|
|
196
|
+
canvasDir: contentOptions.canvasDir,
|
|
197
|
+
...localesFromEnv()
|
|
183
198
|
});
|
|
184
199
|
const locale = contentOptions.locale;
|
|
185
200
|
const content = await contentApi.getContent(pageId);
|
|
@@ -231,13 +246,45 @@ async function handleContentApi(request, cfResult) {
|
|
|
231
246
|
const canvasDir = import.meta.env.CONLOCA_CANVAS_DIR || "./canvas";
|
|
232
247
|
const contentApi = await FileSystemContentAPI.create({
|
|
233
248
|
contentRoot,
|
|
234
|
-
canvasDir
|
|
249
|
+
canvasDir,
|
|
250
|
+
...localesFromEnv()
|
|
235
251
|
});
|
|
236
252
|
const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || "";
|
|
237
253
|
const app = createContentAPIRouter(contentApi, {
|
|
238
254
|
...assetsPath && { assetsPath },
|
|
239
255
|
contentRoot
|
|
240
256
|
});
|
|
257
|
+
app.post("/mdx/compile", async (c) => {
|
|
258
|
+
let body;
|
|
259
|
+
try {
|
|
260
|
+
body = await c.req.json();
|
|
261
|
+
} catch {
|
|
262
|
+
return c.json({ error: {
|
|
263
|
+
code: ErrorCodes.INVALID_REQUEST,
|
|
264
|
+
message: "Invalid JSON body"
|
|
265
|
+
} }, 400);
|
|
266
|
+
}
|
|
267
|
+
const mdxContent = typeof body === "object" && body !== null ? body.mdxContent : null;
|
|
268
|
+
if (!mdxContent || typeof mdxContent !== "string") return c.json({ error: {
|
|
269
|
+
code: ErrorCodes.MISSING_REQUIRED_FIELD,
|
|
270
|
+
message: "mdxContent string required",
|
|
271
|
+
details: { field: "mdxContent" }
|
|
272
|
+
} }, 400);
|
|
273
|
+
try {
|
|
274
|
+
const { code, metadata } = await compileMDX(mdxContent);
|
|
275
|
+
return c.json({
|
|
276
|
+
code,
|
|
277
|
+
metadata
|
|
278
|
+
});
|
|
279
|
+
} catch (error) {
|
|
280
|
+
const message = error instanceof Error ? error.message : "Failed to compile MDX";
|
|
281
|
+
console.error("[CMS] /mdx/compile failed:", error);
|
|
282
|
+
return c.json({ error: {
|
|
283
|
+
code: ErrorCodes.MDX_COMPILE_FAILED,
|
|
284
|
+
message
|
|
285
|
+
} }, 422);
|
|
286
|
+
}
|
|
287
|
+
});
|
|
241
288
|
const url = new URL(request.url);
|
|
242
289
|
const apiIndex = url.pathname.indexOf("/api/");
|
|
243
290
|
if (apiIndex === -1) return new Response("Invalid API path", { status: 400 });
|
|
@@ -261,7 +308,7 @@ async function handleContentApi(request, cfResult) {
|
|
|
261
308
|
headers: response.headers
|
|
262
309
|
});
|
|
263
310
|
}
|
|
264
|
-
|
|
265
311
|
//#endregion
|
|
266
312
|
export { ALL, SPA_MIME_TYPES };
|
|
313
|
+
|
|
267
314
|
//# sourceMappingURL=cms-handler.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cms-handler.mjs","names":[],"sources":["../../src/mime-types.ts","../../src/path-validation.ts","../../src/safe-json-stringify.ts","../../src/cms-handler.ts"],"sourcesContent":["/** MIME types for SPA static asset serving. Covers all file types produced by the cms-spa build. */\nexport const SPA_MIME_TYPES: Record<string, string> = {\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.html': 'text/html',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.map': 'application/json',\n '.ico': 'image/x-icon',\n};\n","import { resolve, sep } from 'node:path';\n\n/**\n * Validates that a target path resolves within a base directory.\n * Prevents path traversal attacks by canonicalizing both paths\n * and checking that the target starts with the base path + separator\n * (or is exactly the base path).\n */\nexport function isPathWithinBase(basePath: string, targetPath: string): boolean {\n const resolvedBase = resolve(basePath);\n const resolvedTarget = resolve(targetPath);\n return resolvedTarget === resolvedBase || resolvedTarget.startsWith(resolvedBase + sep);\n}\n","/**\n * JSON.stringify replacement that escapes characters dangerous in HTML script contexts.\n *\n * When embedding JSON in `<script>` tags, characters like `<`, `>`, `&`, and `'` can break\n * out of the script context (e.g., `</script>` closes the tag prematurely). This function\n * replaces those characters with their Unicode escape equivalents, which are valid in both\n * JSON and JavaScript string contexts.\n *\n * @see https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n */\nexport function safeJsonStringify(data: Record<string, unknown> | unknown[] | string | number | boolean | null): string;\nexport function safeJsonStringify(data: unknown): string | undefined;\nexport function safeJsonStringify(data: unknown): string | undefined {\n const json = JSON.stringify(data);\n if (json === undefined) return undefined;\n return json.replace(/[<>&']/g, (ch) => `\\\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport spaConfig from 'virtual:conloca-config';\nimport { contentOptions, getDataCollection, getPagesByPrefix } from 'virtual:conloca-page-api';\nimport routingConfig from 'virtual:conloca-routing-config';\nimport {\n type CFAccessResult,\n createContentAPI,\n createContentAPIRouter,\n FileSystemContentAPI,\n validateCFAccessRequest,\n} from '@conloca/content-api/node';\nimport type { APIRoute } from 'astro';\nimport { SPA_MIME_TYPES } from './mime-types.js';\nimport { isPathWithinBase } from './path-validation.js';\nimport { safeJsonStringify } from './safe-json-stringify.js';\nimport type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from './types.js';\n\nexport { SPA_MIME_TYPES } from './mime-types.js';\n\n// Get the path to the cms-spa package by resolving its package.json\nconst require = createRequire(import.meta.url);\nconst cmsSpaPath = dirname(require.resolve('@conloca/cms-spa/package.json'));\n\n/**\n * Unified CMS handler - single entry point for all CMS routes.\n *\n * This handler:\n * 1. Validates CF Access authentication ONCE at the top\n * 2. Routes to appropriate sub-handler based on path:\n * - /api/data-context -> handleDataContext()\n * - /api/* -> handleContentApi()\n * - /* -> handleSpa()\n *\n * Benefits:\n * - Single authentication check prevents security gaps\n * - New routes automatically inherit auth protection\n * - Easier to audit security\n */\nexport const ALL: APIRoute = async ({ params, request }) => {\n // Step 1: Validate CF Access ONCE\n const cfResult = await validateCFAccessRequest(request);\n if (!cfResult.valid && cfResult.required) {\n return new Response(JSON.stringify({ error: 'Unauthorized' }), {\n status: 401,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Step 2: Route based on path\n const pathArray = params.path;\n const path = Array.isArray(pathArray) ? pathArray.join('/') : pathArray || '';\n\n // Route to appropriate handler\n if (path.startsWith('api/data-context')) {\n return handleDataContext(request);\n }\n\n if (path.startsWith('api/')) {\n return handleContentApi(request, cfResult);\n }\n\n return handleSpa(params, request);\n};\n\n// ============================================================================\n// SPA Handler (from spa-handler.ts)\n// ============================================================================\n\n/**\n * Generate HTML for dev mode that loads cms-spa source through Vite.\n * This ensures React is resolved from Vite's pre-bundled deps, not from the cms-spa bundle.\n */\nfunction generateDevHtml(config: typeof spaConfig): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Conloca CMS</title>\n <link rel=\"stylesheet\" href=\"${config.basename}/main.css\" />\n <script type=\"module\" src=\"${config.basename}/site-styles.js\"></script>\n <script>\n // Configure UI with plugin options\n window.__UI_CONFIG__ = ${safeJsonStringify(config)};\n </script>\n <script type=\"module\" src=\"${config.basename}/schemas-entry.js\"></script>\n <script type=\"module\" src=\"${config.basename}/puck-entry.js\"></script>\n <script type=\"module\" src=\"${config.basename}/content-listener.js\"></script>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"${config.basename}/cms-spa-entry.js\"></script>\n</body>\n</html>`;\n}\n\n/**\n * Load the HTML at runtime (production only)\n */\nasync function loadIndexHtml(): Promise<string> {\n const spaDir = join(cmsSpaPath, 'dist/spa');\n const { readdir } = await import('node:fs/promises');\n const files = await readdir(spaDir);\n const htmlFile = files.find((f) => f.startsWith('index.') && f.endsWith('.html'));\n\n if (!htmlFile) {\n throw new Error('No index.html found in @conloca/cms-spa dist/spa');\n }\n\n const htmlPath = join(spaDir, htmlFile);\n const html = await readFile(htmlPath, 'utf-8');\n\n return html;\n}\n\n/**\n * Handle SPA requests - serve CMS admin interface\n */\nasync function handleSpa(params: { path?: string | string[] }, request: Request): Promise<Response> {\n // The path parameter is an array for [...path] routes\n const pathArray = params.path;\n const path = Array.isArray(pathArray) ? pathArray.join('/') : pathArray || '';\n\n // For the root path or any path without an extension, serve the HTML\n if (!path || !path.includes('.')) {\n try {\n let html: string;\n\n // In dev mode, generate HTML that loads source through Vite\n // In production, load the pre-built HTML from cms-spa dist\n if (import.meta.env.DEV) {\n html = generateDevHtml(spaConfig);\n } else {\n html = await loadIndexHtml();\n // Inject CMS configuration and load virtual modules\n const configScript = `\n <script>\n // Configure UI with plugin options\n window.__UI_CONFIG__ = ${safeJsonStringify(spaConfig)};\n </script>\n <script type=\"module\" src=\"${spaConfig.basename}/site-styles.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/schemas-entry.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/puck-entry.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/content-listener.js\"></script>\n `;\n // Inject the script at the top to ensure config is available first\n html = html.replace('<head>', `<head>${configScript}`);\n }\n\n return new Response(html, {\n headers: {\n 'Content-Type': 'text/html',\n 'Cache-Control': 'no-store, must-revalidate',\n 'X-HMR': 'spa-page',\n },\n });\n } catch (error) {\n console.error('Error loading CMS HTML:', error);\n return new Response('CMS build not found. Run nx build @conloca/astro-cms', {\n status: 500,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n }\n\n // For asset requests, serve them from the cms-spa dist/spa directory\n try {\n const spaBase = join(cmsSpaPath, 'dist/spa');\n const assetPath = join(spaBase, path);\n\n if (!isPathWithinBase(spaBase, assetPath)) {\n console.warn('[security] Path traversal attempt blocked:', path);\n return new Response('Forbidden', { status: 403 });\n }\n\n const content = await readFile(assetPath);\n\n // Determine content type from extension map with octet-stream fallback\n const ext = path.substring(path.lastIndexOf('.'));\n const contentType = SPA_MIME_TYPES[ext] ?? 'application/octet-stream';\n\n return new Response(content as BodyInit, {\n headers: {\n 'Content-Type': contentType,\n 'Cache-Control': import.meta.env.DEV ? 'no-store, must-revalidate' : 'public, max-age=31536000',\n },\n });\n } catch {\n return new Response('Not found', { status: 404 });\n }\n}\n\n// ============================================================================\n// Data Context Handler (from data-context-handler.ts)\n// ============================================================================\n\n/**\n * Handle DataContext API requests - returns data bindings for CMS editor\n */\nasync function handleDataContext(request: Request): Promise<Response> {\n try {\n const url = new URL(request.url);\n const pageId = url.searchParams.get('pageId');\n\n if (!pageId) {\n return jsonResponse({});\n }\n\n const config = routingConfig as ResolvedRoutingConfig;\n if (!config.enabled) {\n return jsonResponse({});\n }\n\n // Find which route this page belongs to by loading the page manifest\n // and matching its collection against route configs\n const contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n });\n\n const locale = contentOptions.locale;\n\n // Get the page manifest to determine its collection\n const content = await contentApi.getContent(pageId);\n if (!content) {\n return jsonResponse({});\n }\n const pageCollection = content.collection || 'pages';\n\n // Find the route whose collection matches this page\n const routeEntry = Object.entries(config.routes).find(\n ([, routeConfig]) => routeConfig.collection === pageCollection,\n );\n\n if (!routeEntry) {\n return jsonResponse({});\n }\n\n const [, routeConfig] = routeEntry;\n const hasCollections = routeConfig.dataBindings?.collections?.length;\n const hasPages = routeConfig.dataBindings?.pages?.prefix;\n\n if (!hasCollections && !hasPages) {\n return jsonResponse({});\n }\n\n // Build DataContext using the same logic as page-handler.astro\n const collections: Record<string, DataCollectionEntry[]> = {};\n let pages: PageReference[] | undefined;\n\n if (hasCollections && routeConfig.dataBindings?.collections) {\n for (const collectionName of routeConfig.dataBindings.collections) {\n try {\n const bindingLocale = routeConfig.dataBindings.locale ?? locale;\n collections[collectionName] = await getDataCollection(collectionName, bindingLocale);\n } catch {\n collections[collectionName] = [];\n }\n }\n }\n\n if (hasPages && routeConfig.dataBindings?.pages) {\n try {\n const pagesConfig = routeConfig.dataBindings.pages;\n pages = await getPagesByPrefix(pagesConfig.prefix, {\n sort: pagesConfig.sort,\n limit: pagesConfig.limit,\n });\n } catch {\n pages = [];\n }\n }\n\n const dataContext: DataContext = {\n collections,\n pages,\n locale: routeConfig.dataBindings.locale ?? locale,\n siteName: contentOptions.siteName,\n };\n\n return jsonResponse({ dataContext });\n } catch {\n return jsonResponse({});\n }\n}\n\nfunction jsonResponse(data: object): Response {\n return new Response(JSON.stringify(data), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\n// ============================================================================\n// Content API Handler (from content-api-handler.ts)\n// ============================================================================\n\n/**\n * Handle Content API requests - delegates to Hono router\n */\nasync function handleContentApi(request: Request, cfResult: CFAccessResult): Promise<Response> {\n const contentRoot = import.meta.env.CONLOCA_CONTENT_ROOT || './content';\n const canvasDir = import.meta.env.CONLOCA_CANVAS_DIR || './canvas';\n\n // FileSystemContentAPI.create() handles caching internally\n const contentApi = await FileSystemContentAPI.create({ contentRoot, canvasDir });\n\n // Create the Hono router with assets and content root for git operations\n const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || '';\n const app = createContentAPIRouter(contentApi, { ...(assetsPath && { assetsPath }), contentRoot });\n\n // Extract the path after the API base\n const url = new URL(request.url);\n // Find where /api/ appears in the pathname\n const apiIndex = url.pathname.indexOf('/api/');\n if (apiIndex === -1) {\n return new Response('Invalid API path', { status: 400 });\n }\n const basePath = url.pathname.substring(0, apiIndex + 4); // Include '/api'\n const path = url.pathname.substring(basePath.length) || '/';\n\n // Pass user to Hono via headers for downstream use (needed for git commit attribution)\n const headers = new Headers(request.headers);\n if (cfResult.user) {\n if (cfResult.user.email) {\n headers.set('X-CF-User-Email', cfResult.user.email);\n }\n if (cfResult.user.sub) {\n headers.set('X-CF-User-Sub', cfResult.user.sub);\n }\n }\n\n // Create a new request with the correct path for Hono\n // Note: duplex option is required for Node.js fetch when sending a body\n // but not in the TypeScript RequestInit type\n const honoRequest = new Request(new URL(path + url.search, 'http://localhost').href, {\n method: request.method,\n headers,\n body: request.body,\n ...(request.body && { duplex: 'half' }),\n } as RequestInit);\n\n // Let Hono handle the request\n const response = await app.fetch(honoRequest);\n\n // Return the Hono response\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n"],"mappings":";;;;;;;;;;AACA,MAAa,iBAAyC;CACpD,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,QAAQ;CACT;;;;;;;;;;ACVD,SAAgB,iBAAiB,UAAkB,YAA6B;CAC9E,MAAM,eAAe,QAAQ,SAAS;CACtC,MAAM,iBAAiB,QAAQ,WAAW;AAC1C,QAAO,mBAAmB,gBAAgB,eAAe,WAAW,eAAe,IAAI;;;;;ACCzF,SAAgB,kBAAkB,MAAmC;CACnE,MAAM,OAAO,KAAK,U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,QAAQ,QAAQ;EACvC,CAAgB;CAGjB,MAAM,WAAW,MAAM,IAAI,MAAM,YAAY;AAG7C,QAAO,IAAI,SAAS,SAAS,MAAM;EACjC,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB,SAAS,SAAS;EACnB,CAAC"}
|
|
1
|
+
{"version":3,"file":"cms-handler.mjs","names":[],"sources":["../../src/mime-types.ts","../../src/path-validation.ts","../../src/safe-json-stringify.ts","../../src/cms-handler.ts"],"sourcesContent":["/** MIME types for SPA static asset serving. Covers all file types produced by the cms-spa build. */\nexport const SPA_MIME_TYPES: Record<string, string> = {\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.html': 'text/html',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.map': 'application/json',\n '.ico': 'image/x-icon',\n};\n","import { resolve, sep } from 'node:path';\n\n/**\n * Validates that a target path resolves within a base directory.\n * Prevents path traversal attacks by canonicalizing both paths\n * and checking that the target starts with the base path + separator\n * (or is exactly the base path).\n */\nexport function isPathWithinBase(basePath: string, targetPath: string): boolean {\n const resolvedBase = resolve(basePath);\n const resolvedTarget = resolve(targetPath);\n return resolvedTarget === resolvedBase || resolvedTarget.startsWith(resolvedBase + sep);\n}\n","/**\n * JSON.stringify replacement that escapes characters dangerous in HTML script contexts.\n *\n * When embedding JSON in `<script>` tags, characters like `<`, `>`, `&`, and `'` can break\n * out of the script context (e.g., `</script>` closes the tag prematurely). This function\n * replaces those characters with their Unicode escape equivalents, which are valid in both\n * JSON and JavaScript string contexts.\n *\n * @see https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\n */\nexport function safeJsonStringify(data: Record<string, unknown> | unknown[] | string | number | boolean | null): string;\nexport function safeJsonStringify(data: unknown): string | undefined;\nexport function safeJsonStringify(data: unknown): string | undefined {\n const json = JSON.stringify(data);\n if (json === undefined) return undefined;\n return json.replace(/[<>&']/g, (ch) => `\\\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);\n}\n","import { readFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\nimport spaConfig from 'virtual:conloca-config';\nimport { contentOptions, getDataCollection, getPagesByPrefix } from 'virtual:conloca-page-api';\nimport routingConfig from 'virtual:conloca-routing-config';\nimport {\n type CFAccessResult,\n createContentAPI,\n createContentAPIRouter,\n ErrorCodes,\n FileSystemContentAPI,\n validateCFAccessRequest,\n} from '@conloca/content-api/node';\nimport { compileMDX } from '@conloca/mdx/node';\nimport type { APIRoute } from 'astro';\nimport { SPA_MIME_TYPES } from './mime-types.js';\nimport { isPathWithinBase } from './path-validation.js';\nimport { safeJsonStringify } from './safe-json-stringify.js';\nimport type { DataCollectionEntry, DataContext, PageReference, ResolvedRoutingConfig } from './types.js';\n\nexport { SPA_MIME_TYPES } from './mime-types.js';\n\n/**\n * Read the top-level locales options from build-time env vars.\n * `CONLOCA_LOCALES` is inlined as a JS array (or `null`) by Vite's\n * `define`; `CONLOCA_DEFAULT_LOCALE` is a string (or `''`). When neither\n * is set, returns an empty object so the spread is a no-op and the\n * content-api falls back to sites.json (the existing behavior).\n */\nfunction localesFromEnv(): { availableLocales?: string[]; defaultLocale?: string } {\n const list = import.meta.env.CONLOCA_LOCALES as readonly string[] | null | undefined;\n const defaultLocale = import.meta.env.CONLOCA_DEFAULT_LOCALE as string | undefined;\n return {\n ...(Array.isArray(list) && list.length > 0 ? { availableLocales: list as string[] } : {}),\n ...(typeof defaultLocale === 'string' && defaultLocale ? { defaultLocale } : {}),\n };\n}\n\n// mdxPages config (root / site / defaultLocale) is no longer passed as\n// env vars — the content-api reads sites.json directly from disk under\n// `contentRoot`, so handlers below don't need to spread mdx-options at\n// all. See `readSitesConfig()` in @conloca/content-api/node.\n\n// Get the path to the cms-spa package by resolving its package.json\nconst require = createRequire(import.meta.url);\nconst cmsSpaPath = dirname(require.resolve('@conloca/cms-spa/package.json'));\n\n/**\n * Unified CMS handler - single entry point for all CMS routes.\n *\n * This handler:\n * 1. Validates CF Access authentication ONCE at the top\n * 2. Routes to appropriate sub-handler based on path:\n * - /api/data-context -> handleDataContext()\n * - /api/* -> handleContentApi()\n * - /* -> handleSpa()\n *\n * Benefits:\n * - Single authentication check prevents security gaps\n * - New routes automatically inherit auth protection\n * - Easier to audit security\n */\nexport const ALL: APIRoute = async ({ params, request }) => {\n // Step 1: Validate CF Access ONCE\n const cfResult = await validateCFAccessRequest(request);\n if (!cfResult.valid && cfResult.required) {\n return new Response(JSON.stringify({ error: 'Unauthorized' }), {\n status: 401,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n // Step 2: Route based on path\n const pathArray = params.path;\n const path = Array.isArray(pathArray) ? pathArray.join('/') : pathArray || '';\n\n // Route to appropriate handler\n if (path.startsWith('api/data-context')) {\n return handleDataContext(request);\n }\n\n if (path.startsWith('api/')) {\n return handleContentApi(request, cfResult);\n }\n\n return handleSpa(params, request);\n};\n\n// ============================================================================\n// SPA Handler (from spa-handler.ts)\n// ============================================================================\n\n/**\n * Generate HTML for dev mode that loads cms-spa source through Vite.\n * This ensures React is resolved from Vite's pre-bundled deps, not from the cms-spa bundle.\n */\nfunction generateDevHtml(config: typeof spaConfig): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Conloca CMS</title>\n <link rel=\"stylesheet\" href=\"${config.basename}/main.css\" />\n <script type=\"module\" src=\"${config.basename}/site-styles.js\"></script>\n <script type=\"module\" src=\"${config.basename}/editor-styles.js\"></script>\n <script>\n // Configure UI with plugin options\n window.__UI_CONFIG__ = ${safeJsonStringify(config)};\n </script>\n <script type=\"module\" src=\"${config.basename}/schemas-entry.js\"></script>\n <script type=\"module\" src=\"${config.basename}/puck-entry.js\"></script>\n <script type=\"module\" src=\"${config.basename}/content-listener.js\"></script>\n</head>\n<body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"${config.basename}/cms-spa-entry.js\"></script>\n</body>\n</html>`;\n}\n\n/**\n * Load the HTML at runtime (production only)\n */\nasync function loadIndexHtml(): Promise<string> {\n const spaDir = join(cmsSpaPath, 'dist/spa');\n const { readdir } = await import('node:fs/promises');\n const files = await readdir(spaDir);\n const htmlFile = files.find((f) => f.startsWith('index.') && f.endsWith('.html'));\n\n if (!htmlFile) {\n throw new Error('No index.html found in @conloca/cms-spa dist/spa');\n }\n\n const htmlPath = join(spaDir, htmlFile);\n const html = await readFile(htmlPath, 'utf-8');\n\n return html;\n}\n\n/**\n * Handle SPA requests - serve CMS admin interface\n */\nasync function handleSpa(params: { path?: string | string[] }, request: Request): Promise<Response> {\n // The path parameter is an array for [...path] routes\n const pathArray = params.path;\n const path = Array.isArray(pathArray) ? pathArray.join('/') : pathArray || '';\n\n // For the root path or any path without an extension, serve the HTML\n if (!path || !path.includes('.')) {\n try {\n let html: string;\n\n // In dev mode, generate HTML that loads source through Vite\n // In production, load the pre-built HTML from cms-spa dist\n if (import.meta.env.DEV) {\n html = generateDevHtml(spaConfig);\n } else {\n html = await loadIndexHtml();\n // Inject CMS configuration and load virtual modules\n const configScript = `\n <script>\n // Configure UI with plugin options\n window.__UI_CONFIG__ = ${safeJsonStringify(spaConfig)};\n </script>\n <script type=\"module\" src=\"${spaConfig.basename}/site-styles.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/editor-styles.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/schemas-entry.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/puck-entry.js\"></script>\n <script type=\"module\" src=\"${spaConfig.basename}/content-listener.js\"></script>\n `;\n // Inject the script at the top to ensure config is available first\n html = html.replace('<head>', `<head>${configScript}`);\n }\n\n return new Response(html, {\n headers: {\n 'Content-Type': 'text/html',\n 'Cache-Control': 'no-store, must-revalidate',\n 'X-HMR': 'spa-page',\n },\n });\n } catch (error) {\n console.error('Error loading CMS HTML:', error);\n return new Response('CMS build not found. Run nx build @conloca/astro-cms', {\n status: 500,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n }\n\n // For asset requests, serve them from the cms-spa dist/spa directory\n try {\n const spaBase = join(cmsSpaPath, 'dist/spa');\n const assetPath = join(spaBase, path);\n\n if (!isPathWithinBase(spaBase, assetPath)) {\n console.warn('[security] Path traversal attempt blocked:', path);\n return new Response('Forbidden', { status: 403 });\n }\n\n const content = await readFile(assetPath);\n\n // Determine content type from extension map with octet-stream fallback\n const ext = path.substring(path.lastIndexOf('.'));\n const contentType = SPA_MIME_TYPES[ext] ?? 'application/octet-stream';\n\n return new Response(content as BodyInit, {\n headers: {\n 'Content-Type': contentType,\n 'Cache-Control': import.meta.env.DEV ? 'no-store, must-revalidate' : 'public, max-age=31536000',\n },\n });\n } catch {\n return new Response('Not found', { status: 404 });\n }\n}\n\n// ============================================================================\n// Data Context Handler (from data-context-handler.ts)\n// ============================================================================\n\n/**\n * Handle DataContext API requests - returns data bindings for CMS editor\n */\nasync function handleDataContext(request: Request): Promise<Response> {\n try {\n const url = new URL(request.url);\n const pageId = url.searchParams.get('pageId');\n\n if (!pageId) {\n return jsonResponse({});\n }\n\n const config = routingConfig as ResolvedRoutingConfig;\n if (!config.enabled) {\n return jsonResponse({});\n }\n\n // Find which route this page belongs to by loading the page manifest\n // and matching its collection against route configs\n const contentApi = await createContentAPI({\n contentRoot: contentOptions.contentRoot,\n canvasDir: contentOptions.canvasDir,\n ...localesFromEnv(),\n });\n\n const locale = contentOptions.locale;\n\n // Get the page manifest to determine its collection\n const content = await contentApi.getContent(pageId);\n if (!content) {\n return jsonResponse({});\n }\n const pageCollection = content.collection || 'pages';\n\n // Find the route whose collection matches this page\n const routeEntry = Object.entries(config.routes).find(\n ([, routeConfig]) => routeConfig.collection === pageCollection,\n );\n\n if (!routeEntry) {\n return jsonResponse({});\n }\n\n const [, routeConfig] = routeEntry;\n const hasCollections = routeConfig.dataBindings?.collections?.length;\n const hasPages = routeConfig.dataBindings?.pages?.prefix;\n\n if (!hasCollections && !hasPages) {\n return jsonResponse({});\n }\n\n // Build DataContext using the same logic as page-handler.astro\n const collections: Record<string, DataCollectionEntry[]> = {};\n let pages: PageReference[] | undefined;\n\n if (hasCollections && routeConfig.dataBindings?.collections) {\n for (const collectionName of routeConfig.dataBindings.collections) {\n try {\n const bindingLocale = routeConfig.dataBindings.locale ?? locale;\n collections[collectionName] = await getDataCollection(collectionName, bindingLocale);\n } catch {\n collections[collectionName] = [];\n }\n }\n }\n\n if (hasPages && routeConfig.dataBindings?.pages) {\n try {\n const pagesConfig = routeConfig.dataBindings.pages;\n pages = await getPagesByPrefix(pagesConfig.prefix, {\n sort: pagesConfig.sort,\n limit: pagesConfig.limit,\n });\n } catch {\n pages = [];\n }\n }\n\n const dataContext: DataContext = {\n collections,\n pages,\n locale: routeConfig.dataBindings.locale ?? locale,\n siteName: contentOptions.siteName,\n };\n\n return jsonResponse({ dataContext });\n } catch {\n return jsonResponse({});\n }\n}\n\nfunction jsonResponse(data: object): Response {\n return new Response(JSON.stringify(data), {\n status: 200,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n\n// ============================================================================\n// Content API Handler (from content-api-handler.ts)\n// ============================================================================\n\n/**\n * Handle Content API requests - delegates to Hono router\n */\nasync function handleContentApi(request: Request, cfResult: CFAccessResult): Promise<Response> {\n const contentRoot = import.meta.env.CONLOCA_CONTENT_ROOT || './content';\n const canvasDir = import.meta.env.CONLOCA_CANVAS_DIR || './canvas';\n\n // FileSystemContentAPI.create() handles caching internally.\n // mdxPages is read from sites.json by the content-api itself.\n const contentApi = await FileSystemContentAPI.create({\n contentRoot,\n canvasDir,\n ...localesFromEnv(),\n });\n\n // Create the Hono router with assets and content root for git operations\n const assetsPath = import.meta.env.CONLOCA_ASSETS_PATH || '';\n const app = createContentAPIRouter(contentApi, {\n ...(assetsPath && { assetsPath }),\n contentRoot,\n });\n\n // POST /mdx/compile — server-side MDX compilation for the browser preview.\n // The route lives here (not in @conloca/content-api) because compileMDX is\n // a renderer concern; content-api is purely storage. The browser sends raw\n // MDX, we return a JavaScript function body that @mdx-js/mdx's run() can\n // execute.\n app.post('/mdx/compile', async (c) => {\n let body: unknown;\n try {\n body = await c.req.json();\n } catch {\n return c.json({ error: { code: ErrorCodes.INVALID_REQUEST, message: 'Invalid JSON body' } }, 400);\n }\n\n const mdxContent = typeof body === 'object' && body !== null ? (body as { mdxContent?: unknown }).mdxContent : null;\n\n if (!mdxContent || typeof mdxContent !== 'string') {\n return c.json(\n {\n error: {\n code: ErrorCodes.MISSING_REQUIRED_FIELD,\n message: 'mdxContent string required',\n details: { field: 'mdxContent' },\n },\n },\n 400,\n );\n }\n\n try {\n const { code, metadata } = await compileMDX(mdxContent);\n return c.json({ code, metadata });\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Failed to compile MDX';\n console.error('[CMS] /mdx/compile failed:', error);\n return c.json({ error: { code: ErrorCodes.MDX_COMPILE_FAILED, message } }, 422);\n }\n });\n\n // Extract the path after the API base\n const url = new URL(request.url);\n // Find where /api/ appears in the pathname\n const apiIndex = url.pathname.indexOf('/api/');\n if (apiIndex === -1) {\n return new Response('Invalid API path', { status: 400 });\n }\n const basePath = url.pathname.substring(0, apiIndex + 4); // Include '/api'\n const path = url.pathname.substring(basePath.length) || '/';\n\n // Pass user to Hono via headers for downstream use (needed for git commit attribution)\n const headers = new Headers(request.headers);\n if (cfResult.user) {\n if (cfResult.user.email) {\n headers.set('X-CF-User-Email', cfResult.user.email);\n }\n if (cfResult.user.sub) {\n headers.set('X-CF-User-Sub', cfResult.user.sub);\n }\n }\n\n // Create a new request with the correct path for Hono\n // Note: duplex option is required for Node.js fetch when sending a body\n // but not in the TypeScript RequestInit type\n const honoRequest = new Request(new URL(path + url.search, 'http://localhost').href, {\n method: request.method,\n headers,\n body: request.body,\n ...(request.body && { duplex: 'half' }),\n } as RequestInit);\n\n // Let Hono handle the request\n const response = await app.fetch(honoRequest);\n\n // Return the Hono response\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n}\n"],"mappings":";;;;;;;;;;AACA,MAAa,iBAAyC;CACpD,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,QAAQ;CACR,SAAS;CACT,SAAS;CACT,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,QAAQ;AACV;;;;;;;;;ACVA,SAAgB,iBAAiB,UAAkB,YAA6B;CAC9E,MAAM,eAAe,QAAQ,QAAQ;CACrC,MAAM,iBAAiB,QAAQ,UAAU;CACzC,OAAO,mBAAmB,gBAAgB,eAAe,WAAW,eAAe,GAAG;AACxF;;;ACAA,SAAgB,kBAAkB,MAAmC;CACnE,MAAM,OAAO,KAAK,UAAU,IAAI;CAChC,IAAI,SAAS,KAAA,GAAW,OAAO,KAAA;CAC/B,OAAO,KAAK,QAAQ,YAAY,OAAO,MAAM,GAAG,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG;AAC/F;;;;;;;;;;ACcA,SAAS,iBAA0E;CACjF,MAAM,OAAO,OAAO,KAAK,IAAI;CAC7B,MAAM,gBAAgB,OAAO,KAAK,IAAI;CACtC,OAAO;EACL,GAAI,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,IAAI,EAAE,kBAAkB,KAAiB,IAAI,CAAC;EACvF,GAAI,OAAO,kBAAkB,YAAY,gBAAgB,EAAE,cAAc,IAAI,CAAC;CAChF;AACF;AASA,MAAM,aAAa,QADH,cAAc,OAAO,KAAK,GACT,CAAC,CAAC,QAAQ,+BAA+B,CAAC;;;;;;;;;;;;;;;;AAiB3E,MAAa,MAAgB,OAAO,EAAE,QAAQ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,MAAM,WAAW,IAAI,SAAS,QAAQ,OAAO;CAC7C,IAAI,aAAa,IACf,OAAO,IAAI,SAAS,oBAAoB,EAAE,QAAQ,IAAI,CAAC;CAEzD,MAAM,WAAW,IAAI,SAAS,UAAU,GAAG,WAAW,CAAC;CACvD,MAAM,OAAO,IAAI,SAAS,UAAU,SAAS,MAAM,KAAK;CAGxD,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;CAC3C,IAAI,SAAS,MAAM;EACjB,IAAI,SAAS,KAAK,OAChB,QAAQ,IAAI,mBAAmB,SAAS,KAAK,KAAK;EAEpD,IAAI,SAAS,KAAK,KAChB,QAAQ,IAAI,iBAAiB,SAAS,KAAK,GAAG;CAElD;CAKA,MAAM,cAAc,IAAI,QAAQ,IAAI,IAAI,OAAO,IAAI,QAAQ,kBAAkB,CAAC,CAAC,MAAM;EACnF,QAAQ,QAAQ;EAChB;EACA,MAAM,QAAQ;EACd,GAAI,QAAQ,QAAQ,EAAE,QAAQ,OAAO;CACvC,CAAgB;CAGhB,MAAM,WAAW,MAAM,IAAI,MAAM,WAAW;CAG5C,OAAO,IAAI,SAAS,SAAS,MAAM;EACjC,QAAQ,SAAS;EACjB,YAAY,SAAS;EACrB,SAAS,SAAS;CACpB,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-script.d.mts","names":[],"sources":["../../src/lib/hydration-script.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"hydration-script.d.mts","names":[],"sources":["../../src/lib/hydration-script.ts"],"mappings":";;;;;;KASK,wBAAwB,QAAQ,MAAM;;;;;UAMjC;EACR,QAAQ;EACR,UAAU;;;;;;KAOA,oBAAoB,eAAe;;;;;;;iBAuE/B,cAAc,UAAU"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { createElement } from "react";
|
|
2
2
|
import { hydrateRoot } from "react-dom/client";
|
|
3
|
-
|
|
4
3
|
//#region src/lib/hydration-script.ts
|
|
5
4
|
/**
|
|
6
5
|
* Hydrate a single element with its corresponding React component.
|
|
@@ -79,7 +78,7 @@ function initHydration(registry) {
|
|
|
79
78
|
}
|
|
80
79
|
}
|
|
81
80
|
}
|
|
82
|
-
|
|
83
81
|
//#endregion
|
|
84
82
|
export { initHydration };
|
|
83
|
+
|
|
85
84
|
//# sourceMappingURL=hydration-script.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hydration-script.mjs","names":[],"sources":["../../src/lib/hydration-script.ts"],"sourcesContent":["import { createElement } from 'react'
|
|
1
|
+
{"version":3,"file":"hydration-script.mjs","names":[],"sources":["../../src/lib/hydration-script.ts"],"sourcesContent":["import { createElement } from 'react';\nimport { hydrateRoot } from 'react-dom/client';\n\nimport type { HydrationStrategy } from '../types.js';\n\n/**\n * Async loader that returns a React component.\n * The registry generator handles extraction from ComponentConfig at build time.\n */\ntype ComponentLoader = () => Promise<React.ComponentType<unknown>>;\n\n/**\n * Registry entry with loader and strategy.\n * Generated by the scanner from withHydration metadata.\n */\ninterface ComponentRegistryEntry {\n loader: ComponentLoader;\n strategy: HydrationStrategy;\n}\n\n/**\n * Registry mapping component names to their loaders and strategies.\n * Generated by virtual:conloca-hydration-registry at build time.\n */\nexport type ComponentRegistry = Record<string, ComponentRegistryEntry>;\n\n/**\n * Hydrate a single element with its corresponding React component.\n */\nasync function hydrateElement(element: HTMLElement, entry: ComponentRegistryEntry): Promise<void> {\n const componentName = element.dataset.hydrate;\n const propsJson = element.dataset.props || '{}';\n\n if (!componentName) {\n console.warn('[Conloca Hydration] Element missing data-hydrate attribute');\n return;\n }\n\n try {\n const props = JSON.parse(propsJson);\n const Component = await entry.loader();\n hydrateRoot(element, createElement(Component, props));\n\n // Clean up data attributes after successful hydration\n delete element.dataset.hydrate;\n delete element.dataset.hydrateStrategy;\n delete element.dataset.props;\n } catch (error) {\n console.error(`[Conloca Hydration] Failed to hydrate ${componentName}:`, error);\n }\n}\n\n/**\n * Hydrate immediately on page load.\n */\nfunction hydrateOnLoad(element: HTMLElement, entry: ComponentRegistryEntry): void {\n hydrateElement(element, entry);\n}\n\n/**\n * Hydrate when element becomes visible in viewport.\n */\nfunction hydrateOnVisible(element: HTMLElement, entry: ComponentRegistryEntry): void {\n const observer = new IntersectionObserver(\n (entries, obs) => {\n for (const ioEntry of entries) {\n if (ioEntry.isIntersecting) {\n obs.unobserve(ioEntry.target);\n hydrateElement(ioEntry.target as HTMLElement, entry);\n }\n }\n },\n { rootMargin: '50px' },\n );\n observer.observe(element);\n}\n\n/**\n * Hydrate when browser is idle.\n * Uses requestIdleCallback with setTimeout fallback for Safari.\n */\nfunction hydrateOnIdle(element: HTMLElement, entry: ComponentRegistryEntry): void {\n const scheduleIdle =\n window.requestIdleCallback ??\n ((cb: IdleRequestCallback) => window.setTimeout(() => cb({ didTimeout: false, timeRemaining: () => 50 }), 1));\n\n scheduleIdle(() => hydrateElement(element, entry), { timeout: 2000 });\n}\n\n/**\n * Initialize hydration for all marked components on the page.\n *\n * Finds all elements with [data-hydrate] attribute and hydrates them\n * according to their strategy from the registry.\n */\nexport function initHydration(registry: ComponentRegistry): void {\n const elements = document.querySelectorAll<HTMLElement>('[data-hydrate]');\n\n for (const element of elements) {\n const componentName = element.dataset.hydrate;\n if (!componentName) continue;\n\n const entry = registry[componentName];\n if (!entry) {\n console.warn(`[Conloca Hydration] Unknown component: ${componentName}`);\n continue;\n }\n\n // Use strategy from registry (set at build time via withHydration)\n const strategy = entry.strategy;\n\n switch (strategy) {\n case 'load':\n hydrateOnLoad(element, entry);\n break;\n case 'visible':\n hydrateOnVisible(element, entry);\n break;\n case 'idle':\n hydrateOnIdle(element, entry);\n break;\n default:\n hydrateOnLoad(element, entry);\n }\n }\n}\n"],"mappings":";;;;;;AA6BA,eAAe,eAAe,SAAsB,OAA8C;CAChG,MAAM,gBAAgB,QAAQ,QAAQ;CACtC,MAAM,YAAY,QAAQ,QAAQ,SAAS;CAE3C,IAAI,CAAC,eAAe;EAClB,QAAQ,K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AC5B;GACF,SACE,cAAc,SAAS,KAAK;EAChC;CACF;AACF"}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//#region src/locales-helpers.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Conloca's view of a site's locales.
|
|
4
|
+
*
|
|
5
|
+
* `list` is the full set of locales the site supports; `defaultLocale`
|
|
6
|
+
* is the one that lives at the root in the `'directory'` mdx-pages
|
|
7
|
+
* strategy. Pass this shape into `conlocaCMS({ locales })`.
|
|
8
|
+
*/
|
|
9
|
+
interface ConlocaLocales {
|
|
10
|
+
list: string[];
|
|
11
|
+
defaultLocale: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Translate Astro's native `i18n` config into Conloca's locale shape.
|
|
15
|
+
*
|
|
16
|
+
* Astro 4+ accepts both bare strings and `{ codes, path }` objects in
|
|
17
|
+
* its `locales` array — this helper flattens both forms.
|
|
18
|
+
*
|
|
19
|
+
* Usage:
|
|
20
|
+
* ```ts
|
|
21
|
+
* import { conlocaCMS, localesFromAstroI18n } from '@conloca/astro-cms/node';
|
|
22
|
+
* const i18n = { defaultLocale: 'en', locales: ['en', 'de'] };
|
|
23
|
+
* defineConfig({
|
|
24
|
+
* i18n,
|
|
25
|
+
* integrations: [conlocaCMS({ locales: localesFromAstroI18n(i18n) })],
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
declare function localesFromAstroI18n(i18n: {
|
|
30
|
+
defaultLocale: string;
|
|
31
|
+
locales: ReadonlyArray<string | {
|
|
32
|
+
codes: string[];
|
|
33
|
+
path: string;
|
|
34
|
+
}>;
|
|
35
|
+
}): ConlocaLocales;
|
|
36
|
+
/**
|
|
37
|
+
* Translate Starlight's i18n config into Conloca's locale shape.
|
|
38
|
+
*
|
|
39
|
+
* Starlight shape: `{ defaultLocale: 'en', locales: { en: { label, lang? }, de: { ... } } }`.
|
|
40
|
+
* The default locale falls back to the first key in `locales` if unset,
|
|
41
|
+
* then to `'en'`.
|
|
42
|
+
*
|
|
43
|
+
* Usage:
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { conlocaCMS, localesFromStarlight } from '@conloca/astro-cms/node';
|
|
46
|
+
* const starlightConfig = { defaultLocale: 'en', locales: { en: { label: 'English' } } };
|
|
47
|
+
* defineConfig({
|
|
48
|
+
* integrations: [
|
|
49
|
+
* starlight(starlightConfig),
|
|
50
|
+
* conlocaCMS({ locales: localesFromStarlight(starlightConfig) }),
|
|
51
|
+
* ],
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function localesFromStarlight(starlight: {
|
|
56
|
+
defaultLocale?: string;
|
|
57
|
+
locales?: Record<string, {
|
|
58
|
+
label?: string;
|
|
59
|
+
lang?: string;
|
|
60
|
+
}>;
|
|
61
|
+
}): ConlocaLocales;
|
|
62
|
+
//#endregion
|
|
63
|
+
export { localesFromAstroI18n as n, localesFromStarlight as r, ConlocaLocales as t };
|
|
64
|
+
//# sourceMappingURL=locales-helpers-BvYYqnJ5.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"locales-helpers-BvYYqnJ5.d.mts","names":[],"sources":["../src/locales-helpers.ts"],"mappings":";;;;;;;;UAOiB;EACf;EACA;;;;;;;;;;;;;;;;;;iBAmBc,qBAAqB;EACnC;EACA,SAAS;IAAyB;IAAiB;;IACjD;;;;;;;;;;;;;;;;;;;;iBA0BY,qBAAqB;EACnC;EACA,UAAU;IAAiB;IAAgB;;IACzC"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
//#region src/locales-helpers.ts
|
|
2
|
+
/**
|
|
3
|
+
* Translate Astro's native `i18n` config into Conloca's locale shape.
|
|
4
|
+
*
|
|
5
|
+
* Astro 4+ accepts both bare strings and `{ codes, path }` objects in
|
|
6
|
+
* its `locales` array — this helper flattens both forms.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { conlocaCMS, localesFromAstroI18n } from '@conloca/astro-cms/node';
|
|
11
|
+
* const i18n = { defaultLocale: 'en', locales: ['en', 'de'] };
|
|
12
|
+
* defineConfig({
|
|
13
|
+
* i18n,
|
|
14
|
+
* integrations: [conlocaCMS({ locales: localesFromAstroI18n(i18n) })],
|
|
15
|
+
* });
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
function localesFromAstroI18n(i18n) {
|
|
19
|
+
return {
|
|
20
|
+
defaultLocale: i18n.defaultLocale,
|
|
21
|
+
list: i18n.locales.flatMap((l) => typeof l === "string" ? [l] : l.codes)
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Translate Starlight's i18n config into Conloca's locale shape.
|
|
26
|
+
*
|
|
27
|
+
* Starlight shape: `{ defaultLocale: 'en', locales: { en: { label, lang? }, de: { ... } } }`.
|
|
28
|
+
* The default locale falls back to the first key in `locales` if unset,
|
|
29
|
+
* then to `'en'`.
|
|
30
|
+
*
|
|
31
|
+
* Usage:
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { conlocaCMS, localesFromStarlight } from '@conloca/astro-cms/node';
|
|
34
|
+
* const starlightConfig = { defaultLocale: 'en', locales: { en: { label: 'English' } } };
|
|
35
|
+
* defineConfig({
|
|
36
|
+
* integrations: [
|
|
37
|
+
* starlight(starlightConfig),
|
|
38
|
+
* conlocaCMS({ locales: localesFromStarlight(starlightConfig) }),
|
|
39
|
+
* ],
|
|
40
|
+
* });
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
function localesFromStarlight(starlight) {
|
|
44
|
+
const list = Object.keys(starlight.locales ?? {});
|
|
45
|
+
const fallback = starlight.defaultLocale ?? list[0] ?? "en";
|
|
46
|
+
return {
|
|
47
|
+
defaultLocale: fallback,
|
|
48
|
+
list: list.length > 0 ? list : [fallback]
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
export { localesFromStarlight as n, localesFromAstroI18n as t };
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=locales-helpers-qiwh7nxS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"locales-helpers-qiwh7nxS.mjs","names":[],"sources":["../src/locales-helpers.ts"],"sourcesContent":["/**\n * Conloca's view of a site's locales.\n *\n * `list` is the full set of locales the site supports; `defaultLocale`\n * is the one that lives at the root in the `'directory'` mdx-pages\n * strategy. Pass this shape into `conlocaCMS({ locales })`.\n */\nexport interface ConlocaLocales {\n list: string[];\n defaultLocale: string;\n}\n\n/**\n * Translate Astro's native `i18n` config into Conloca's locale shape.\n *\n * Astro 4+ accepts both bare strings and `{ codes, path }` objects in\n * its `locales` array — this helper flattens both forms.\n *\n * Usage:\n * ```ts\n * import { conlocaCMS, localesFromAstroI18n } from '@conloca/astro-cms/node';\n * const i18n = { defaultLocale: 'en', locales: ['en', 'de'] };\n * defineConfig({\n * i18n,\n * integrations: [conlocaCMS({ locales: localesFromAstroI18n(i18n) })],\n * });\n * ```\n */\nexport function localesFromAstroI18n(i18n: {\n defaultLocale: string;\n locales: ReadonlyArray<string | { codes: string[]; path: string }>;\n}): ConlocaLocales {\n return {\n defaultLocale: i18n.defaultLocale,\n list: i18n.locales.flatMap((l) => (typeof l === 'string' ? [l] : l.codes)),\n };\n}\n\n/**\n * Translate Starlight's i18n config into Conloca's locale shape.\n *\n * Starlight shape: `{ defaultLocale: 'en', locales: { en: { label, lang? }, de: { ... } } }`.\n * The default locale falls back to the first key in `locales` if unset,\n * then to `'en'`.\n *\n * Usage:\n * ```ts\n * import { conlocaCMS, localesFromStarlight } from '@conloca/astro-cms/node';\n * const starlightConfig = { defaultLocale: 'en', locales: { en: { label: 'English' } } };\n * defineConfig({\n * integrations: [\n * starlight(starlightConfig),\n * conlocaCMS({ locales: localesFromStarlight(starlightConfig) }),\n * ],\n * });\n * ```\n */\nexport function localesFromStarlight(starlight: {\n defaultLocale?: string;\n locales?: Record<string, { label?: string; lang?: string }>;\n}): ConlocaLocales {\n const list = Object.keys(starlight.locales ?? {});\n const fallback = starlight.defaultLocale ?? list[0] ?? 'en';\n return {\n defaultLocale: fallback,\n list: list.length > 0 ? list : [fallback],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,SAAgB,qBAAqB,MAGlB;CACjB,OAAO;EACL,eAAe,KAAK;EACpB,MAAM,KAAK,QAAQ,SAAS,MAAO,OAAO,MAAM,WAAW,CAAC,CAAC,IAAI,EAAE,KAAM;CAC3E;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,qBAAqB,WAGlB;CACjB,MAAM,OAAO,OAAO,KAAK,UAAU,WAAW,CAAC,CAAC;CAChD,MAAM,WAAW,UAAU,iBAAiB,KAAK,MAAM;CACvD,OAAO;EACL,eAAe;EACf,MAAM,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ;CAC1C;AACF"}
|
package/dist/node/content.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { ALL_BLOCKS_COLLECTION, ConlocaCollectionsResult, CreateConlocaCollectionsOptions, createConlocaCollections } from "../collections.mjs";
|
|
2
2
|
import { Loader } from "astro/loaders";
|
|
3
|
-
|
|
4
3
|
//#region src/loader.d.ts
|
|
5
4
|
interface ConlocaLoaderOptions {
|
|
6
5
|
collection?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"content.d.mts","names":[],"sources":["../../src/loader.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"content.d.mts","names":[],"sources":["../../src/loader.ts"],"mappings":";;;UAGiB;EACf;EACA;EACA;;EAEA;;;;;;iBAOc,cAAc,SAAS,uBAAuB"}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { ALL_BLOCKS_COLLECTION, type ConlocaCollectionsResult, type CreateConlocaCollectionsOptions, createConlocaCollections, } from '../src/collections.js';
|
|
2
|
+
export { type ConlocaLoaderOptions, conlocaLoader } from '../src/loader.js';
|
|
3
|
+
//# sourceMappingURL=content.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"content.d.ts","sourceRoot":"","sources":["../../node/content.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,KAAK,wBAAwB,EAC7B,KAAK,+BAA+B,EACpC,wBAAwB,GACzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,KAAK,oBAAoB,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC"}
|
package/dist/node/content.mjs
CHANGED
|
@@ -1,4 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export { ALL_BLOCKS_COLLECTION, conlocaLoader, createConlocaCollections };
|
|
1
|
+
import { n as createConlocaCollections, r as conlocaLoader, t as ALL_BLOCKS_COLLECTION } from "../collections-Bd7EME4b.mjs";
|
|
2
|
+
export { ALL_BLOCKS_COLLECTION, conlocaLoader, createConlocaCollections };
|