@conloca/astro-cms 0.2.2 → 0.2.4
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 +12 -0
- package/dist/ts/.build-inputs.json +90 -0
- package/dist/ts/node/content.d.ts +1 -1
- package/dist/ts/node/content.d.ts.map +1 -1
- package/dist/ts/node/content.js +1 -1
- package/dist/ts/node/content.js.map +1 -1
- package/dist/ts/node/index.d.ts +1 -1
- package/dist/ts/node/index.d.ts.map +1 -1
- package/dist/ts/node/index.js +3 -3
- package/dist/ts/node/index.js.map +1 -1
- package/dist/ts/src/checks.d.ts +7 -3
- package/dist/ts/src/checks.d.ts.map +1 -1
- package/dist/ts/src/checks.js +7 -3
- package/dist/ts/src/checks.js.map +1 -1
- package/dist/ts/src/collections.d.ts +1 -1
- package/dist/ts/src/collections.d.ts.map +1 -1
- package/dist/ts/src/collections.js +1 -1
- package/dist/ts/src/collections.js.map +1 -1
- package/dist/ts/src/editor-descriptors.d.ts +23 -5
- package/dist/ts/src/editor-descriptors.d.ts.map +1 -1
- package/dist/ts/src/editor-descriptors.js +30 -5
- package/dist/ts/src/editor-descriptors.js.map +1 -1
- package/dist/ts/src/entries.d.ts +5 -0
- package/dist/ts/src/entries.d.ts.map +1 -1
- package/dist/ts/src/entries.js +20 -0
- package/dist/ts/src/entries.js.map +1 -1
- package/dist/ts/src/lib/static-page-routes.d.ts +34 -0
- package/dist/ts/src/lib/static-page-routes.d.ts.map +1 -0
- package/dist/ts/src/lib/static-page-routes.js +57 -0
- package/dist/ts/src/lib/static-page-routes.js.map +1 -0
- package/dist/ts/src/lib/static-routes-endpoint.d.ts +9 -0
- package/dist/ts/src/lib/static-routes-endpoint.d.ts.map +1 -0
- package/dist/ts/src/lib/static-routes-endpoint.js +27 -0
- package/dist/ts/src/lib/static-routes-endpoint.js.map +1 -0
- package/dist/ts/src/lib/unknown-components.d.ts +8 -0
- package/dist/ts/src/lib/unknown-components.d.ts.map +1 -1
- package/dist/ts/src/lib/unknown-components.js +1 -1
- package/dist/ts/src/lib/unknown-components.js.map +1 -1
- package/dist/ts/src/plugin-spa.d.ts.map +1 -1
- package/dist/ts/src/plugin-spa.js +60 -18
- package/dist/ts/src/plugin-spa.js.map +1 -1
- package/dist/ts/src/sandbox-frame-handler.d.ts +4 -1
- package/dist/ts/src/sandbox-frame-handler.d.ts.map +1 -1
- package/dist/ts/src/sandbox-frame-handler.js +22 -11
- package/dist/ts/src/sandbox-frame-handler.js.map +1 -1
- package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts +3 -62
- package/dist/ts/src/site-styles/content-wrapper-endpoint.d.ts.map +1 -1
- package/dist/ts/src/site-styles/content-wrapper-endpoint.js +12 -193
- package/dist/ts/src/site-styles/content-wrapper-endpoint.js.map +1 -1
- package/node/content.ts +1 -0
- package/node/index.ts +7 -7
- package/package.json +6 -7
- package/src/checks.ts +13 -3
- package/src/collections.ts +1 -0
- package/src/editor-descriptors.ts +51 -5
- package/src/entries.ts +30 -0
- package/src/lib/static-page-routes.ts +89 -0
- package/src/lib/static-routes-endpoint.ts +28 -0
- package/src/lib/unknown-components.ts +1 -1
- package/src/plugin-spa.ts +68 -18
- package/src/sandbox-frame-handler.ts +16 -5
- package/src/site-styles/content-wrapper-endpoint.ts +4 -285
package/src/plugin-spa.ts
CHANGED
|
@@ -15,6 +15,8 @@ import { deriveComponentPaths, type HydrationDiscovery, scanForHydratableCompone
|
|
|
15
15
|
import { resolveLocale } from './lib/resolve-locale.js';
|
|
16
16
|
import { resolveSiteName } from './lib/resolve-site-name.js';
|
|
17
17
|
import { normalizeRoutingConfig, resolveRouteConfig, toEditorDataBindings } from './lib/routing-config.js';
|
|
18
|
+
import { nonDefaultLocalesOf, type StaticPageRoutesInput } from './lib/static-page-routes.js';
|
|
19
|
+
import { createStaticRoutesEndpoint } from './lib/static-routes-endpoint.js';
|
|
18
20
|
import type { ConlocaLocales } from './locales-helpers.js';
|
|
19
21
|
import { createComponentsEndpoint, endpointReaderOptions } from './puck-manifest/components-endpoint.js';
|
|
20
22
|
import { createContentWrapperEndpoint } from './site-styles/content-wrapper-endpoint.js';
|
|
@@ -561,6 +563,7 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
|
|
|
561
563
|
assetsBasePath: string;
|
|
562
564
|
assetRefBase?: string;
|
|
563
565
|
dataBindings?: EditorDataBindings;
|
|
566
|
+
pageConversion?: UIConfig['pageConversion'];
|
|
564
567
|
} = {
|
|
565
568
|
basename: cmsRoute,
|
|
566
569
|
apiBaseUrl: `${cmsRoute}/api`,
|
|
@@ -606,6 +609,14 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
|
|
|
606
609
|
projectRoot,
|
|
607
610
|
};
|
|
608
611
|
|
|
612
|
+
// The site's pages, for `/api/static-routes`; re-pointed at Astro's own
|
|
613
|
+
// config in config:setup and read per request.
|
|
614
|
+
let staticRoutesInput = (): StaticPageRoutesInput => ({
|
|
615
|
+
pagesDir: join(projectRoot, 'src', 'pages'),
|
|
616
|
+
serverOutput: false,
|
|
617
|
+
nonDefaultLocales: [],
|
|
618
|
+
});
|
|
619
|
+
|
|
609
620
|
let refreshConlocaContent: (() => Promise<void>) | undefined;
|
|
610
621
|
|
|
611
622
|
return {
|
|
@@ -662,6 +673,14 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
|
|
|
662
673
|
spaConfig.dataBindings = resolvedRoutingConfig?.enabled
|
|
663
674
|
? toEditorDataBindings(resolvedRoutingConfig)
|
|
664
675
|
: undefined;
|
|
676
|
+
// The editor's prompt for making existing Astro pages editable runs the
|
|
677
|
+
// newest CLI against this site; the routes come from the dev server.
|
|
678
|
+
spaConfig.pageConversion = { cliVersion: 'latest', site: siteName };
|
|
679
|
+
staticRoutesInput = () => ({
|
|
680
|
+
pagesDir: fileURLToPath(new URL('pages/', config.srcDir)),
|
|
681
|
+
serverOutput: config.output === 'server',
|
|
682
|
+
nonDefaultLocales: nonDefaultLocalesOf(sitesConfig, siteName, config.i18n),
|
|
683
|
+
});
|
|
665
684
|
|
|
666
685
|
registryScan = { ...registryScan, contentRoot: resolvedMdxPages ?? options.contentRoot };
|
|
667
686
|
// Publish the resolved editor descriptors for other integrations in
|
|
@@ -669,12 +688,47 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
|
|
|
669
688
|
// descriptors dev loads from `schemasPath`, `/api/registry` and
|
|
670
689
|
// `virtual:conloca-config` instead of taking these options again.
|
|
671
690
|
// schemasPath is absolutized because a reader may use it as an import
|
|
672
|
-
// specifier.
|
|
691
|
+
// specifier. Readers inherit the puck config, the site and editor
|
|
692
|
+
// stylesheets, the editor CSS and the fragment preview route from here
|
|
693
|
+
// too, so the site writes each of them once. The stylesheets resolve
|
|
694
|
+
// against the Astro root, where the dev editor's Vite imports find
|
|
695
|
+
// them, so a build started from another folder (`astro build --root
|
|
696
|
+
// site`) still hands on the same files.
|
|
697
|
+
const configuredStyles = options.siteStyles;
|
|
698
|
+
const siteStyles = configuredStyles
|
|
699
|
+
? (Array.isArray(configuredStyles) ? configuredStyles : [configuredStyles]).map((path) =>
|
|
700
|
+
resolve(fileURLToPath(config.root), path),
|
|
701
|
+
)
|
|
702
|
+
: undefined;
|
|
703
|
+
const configuredEditorStyles = options.editorStyles;
|
|
704
|
+
const editorStyles = configuredEditorStyles
|
|
705
|
+
? (Array.isArray(configuredEditorStyles) ? configuredEditorStyles : [configuredEditorStyles]).map((path) =>
|
|
706
|
+
resolve(fileURLToPath(config.root), path),
|
|
707
|
+
)
|
|
708
|
+
: undefined;
|
|
709
|
+
// Uploaded images go to the configured media folder, else `<publicDir>/assets`; the workspace editor reads
|
|
710
|
+
// both from here. Derived once, so a configured folder the site cannot serve fails the build here.
|
|
711
|
+
const mediaFolder = options.assetsPath
|
|
712
|
+
? resolve(options.assetsPath)
|
|
713
|
+
: join(fileURLToPath(config.publicDir), 'assets');
|
|
714
|
+
const assetRefBase = deriveAssetRefBase(mediaFolder, config.publicDir, config.base);
|
|
673
715
|
const editorDescriptors: EditorDescriptorChannel = {
|
|
674
716
|
...(options.schemasPath ? { schemasPath: resolve(options.schemasPath) } : {}),
|
|
717
|
+
puckConfigPath: resolve(options.puckConfigPath),
|
|
718
|
+
...(siteStyles === undefined ? {} : { siteStyles }),
|
|
719
|
+
...(editorStyles === undefined ? {} : { editorStyles }),
|
|
720
|
+
...(options.editorCSS ? { editorCSS: options.editorCSS } : {}),
|
|
675
721
|
registry: registryScan,
|
|
676
722
|
...(options.templates ? { templates: options.templates } : {}),
|
|
677
723
|
...(spaConfig.dataBindings ? { dataBindings: spaConfig.dataBindings } : {}),
|
|
724
|
+
// Every folder the content API writes to, resolved as it resolves them (the build's working directory).
|
|
725
|
+
contentPaths: [
|
|
726
|
+
resolve(options.contentRoot),
|
|
727
|
+
...(resolvedMdxPages ? [resolve(resolvedMdxPages)] : []),
|
|
728
|
+
mediaFolder,
|
|
729
|
+
],
|
|
730
|
+
assetsPath: mediaFolder,
|
|
731
|
+
assetRefBase,
|
|
678
732
|
};
|
|
679
733
|
process.env[EDITOR_DESCRIPTORS_ENV_VAR] = JSON.stringify(editorDescriptors);
|
|
680
734
|
|
|
@@ -713,12 +767,8 @@ export function conlocaCMS(options: ConlocaCMSOptions): AstroIntegration {
|
|
|
713
767
|
logger.warn(hint);
|
|
714
768
|
}
|
|
715
769
|
|
|
716
|
-
// Every image the editor picks is stored under this base and served
|
|
717
|
-
|
|
718
|
-
// folder the site cannot serve fails there as well as in dev.
|
|
719
|
-
if (options.assetsPath) {
|
|
720
|
-
spaConfig.assetRefBase = deriveAssetRefBase(options.assetsPath, config.publicDir, config.base);
|
|
721
|
-
}
|
|
770
|
+
// Every image the local editor picks is stored under this base and served as-is by the published site.
|
|
771
|
+
if (options.assetsPath) spaConfig.assetRefBase = assetRefBase;
|
|
722
772
|
|
|
723
773
|
if (command === 'dev' && !contentAbsolute.startsWith(astroRoot)) {
|
|
724
774
|
logger.info(`Auto-allowing contentRoot in Vite fs.allow: ${options.contentRoot}`);
|
|
@@ -913,17 +963,12 @@ initHydration(componentRegistry)
|
|
|
913
963
|
}
|
|
914
964
|
}
|
|
915
965
|
|
|
916
|
-
// The sandbox frame document ContentSandbox loads for MDX previews
|
|
917
|
-
// Root-absolute by contract (SANDBOX_FRAME_PATH in
|
|
918
|
-
//
|
|
919
|
-
//
|
|
920
|
-
//
|
|
921
|
-
|
|
922
|
-
// On-demand by necessity — the response carries the sandbox CSP, which
|
|
923
|
-
// a prerendered file cannot — so injecting it into a fully static site
|
|
924
|
-
// fails that build with NoAdapterInstalled. Such a site has no runtime
|
|
925
|
-
// editor to serve it to; dev serves it whatever the output mode.
|
|
926
|
-
if (command === 'dev' || config.output !== 'static') {
|
|
966
|
+
// The sandbox frame document ContentSandbox loads for MDX previews in
|
|
967
|
+
// the dev editor. Root-absolute by contract (SANDBOX_FRAME_PATH in
|
|
968
|
+
// @conloca/mdx). On-demand by necessity — the response carries the
|
|
969
|
+
// sandbox CSP, which a prerendered file cannot. A built site never
|
|
970
|
+
// gets it: its editor page ships the frame as a static file.
|
|
971
|
+
if (command === 'dev') {
|
|
927
972
|
injectRoute({
|
|
928
973
|
pattern: '/api/v1/mdx/sandbox-frame',
|
|
929
974
|
entrypoint: SANDBOX_FRAME_HANDLER_PATH,
|
|
@@ -1187,6 +1232,11 @@ if (import.meta.hot) {
|
|
|
1187
1232
|
configureServer(server) {
|
|
1188
1233
|
const registry = createRegistryEndpoint(registryScan);
|
|
1189
1234
|
server.middlewares.use(`${cmsRoute}/api/registry`, registry.handler);
|
|
1235
|
+
// The editor offers these pages for conversion; scanned per request.
|
|
1236
|
+
server.middlewares.use(
|
|
1237
|
+
`${cmsRoute}/api/static-routes`,
|
|
1238
|
+
createStaticRoutesEndpoint(() => staticRoutesInput()),
|
|
1239
|
+
);
|
|
1190
1240
|
server.middlewares.use(
|
|
1191
1241
|
`${cmsRoute}/api/render`,
|
|
1192
1242
|
createRenderEndpoint(server, registry.getAllowedSources),
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { buildSandboxSrcdoc,
|
|
1
|
+
import { buildSandboxSrcdoc, MDX_SANDBOX_FRAME_POLICY } from '@conloca/mdx/sandbox-frame';
|
|
2
2
|
import type { APIRoute } from 'astro';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -11,7 +11,8 @@ import type { APIRoute } from 'astro';
|
|
|
11
11
|
* that serves the editor must serve this path too. astro-cms routes otherwise
|
|
12
12
|
* live under the cmsRoute prefix, so without this route the frame 404s and
|
|
13
13
|
* chips render the site's 404 page. Response headers are the frame's contract
|
|
14
|
-
* (`
|
|
14
|
+
* (`MDX_SANDBOX_FRAME_POLICY`); any other server of the frame must match them,
|
|
15
|
+
* including the 403 for anything but an iframe load.
|
|
15
16
|
*
|
|
16
17
|
* No auth gate: the document is static boilerplate — content only ever enters
|
|
17
18
|
* the frame via postMessage from the editor.
|
|
@@ -19,13 +20,23 @@ import type { APIRoute } from 'astro';
|
|
|
19
20
|
|
|
20
21
|
export const prerender = false;
|
|
21
22
|
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
/** The frame route's answer to a request with these headers. */
|
|
24
|
+
export function sandboxFrameResponse(request: Pick<Request, 'headers'>): Response {
|
|
25
|
+
if (request.headers.get('sec-fetch-dest') !== 'iframe') {
|
|
26
|
+
return new Response('The MDX preview frame loads only inside an editor frame.', {
|
|
27
|
+
status: 403,
|
|
28
|
+
headers: { 'cache-control': 'no-store' },
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return new Response(buildSandboxSrcdoc(), {
|
|
24
32
|
status: 200,
|
|
25
33
|
headers: {
|
|
26
34
|
'content-type': 'text/html; charset=utf-8',
|
|
27
|
-
'content-security-policy':
|
|
35
|
+
'content-security-policy': MDX_SANDBOX_FRAME_POLICY,
|
|
28
36
|
'x-content-type-options': 'nosniff',
|
|
29
37
|
'cache-control': 'no-store',
|
|
30
38
|
},
|
|
31
39
|
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export const GET: APIRoute = ({ request }) => sandboxFrameResponse(request);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { findContentWrapper } from '@conloca/cms-spa/content-wrapper';
|
|
1
2
|
import type { Connect } from 'vite';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -7,63 +8,10 @@ import type { Connect } from 'vite';
|
|
|
7
8
|
* contenteditable inside a clone of whatever element the host wraps
|
|
8
9
|
* its page content in. This endpoint fetches the live HTML the dev
|
|
9
10
|
* server serves at `?url=<route>`, locates the relevant wrappers
|
|
10
|
-
* (prose content + code-block chrome)
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* {
|
|
15
|
-
* content: { tagName, className } | null,
|
|
16
|
-
* codeBlock: { tagName, className }[] | null,
|
|
17
|
-
* }
|
|
18
|
-
*
|
|
19
|
-
* - `content` is the wrapper for prose (h1-h6, p, lists, etc.). The
|
|
20
|
-
* editor wraps its contenteditable in a clone so the host's prose
|
|
21
|
-
* CSS reaches via the cascade.
|
|
22
|
-
* - `codeBlock` is the ORDERED chain of classed wrappers around the
|
|
23
|
-
* host's `<pre>`, outermost first. For Starlight's expressive-code:
|
|
24
|
-
* `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
|
|
25
|
-
* The editor's CodeMirror frame renders each link as a nested
|
|
26
|
-
* element (outer→inner) so the host's code-block CSS reaches via
|
|
27
|
-
* the cascade including descendant selectors (`.expressive-code
|
|
28
|
-
* .frame .header`, etc.) — not just single-class targets.
|
|
29
|
-
*
|
|
30
|
-
* Discovery priorities (content):
|
|
31
|
-
*
|
|
32
|
-
* 1. `[data-conloca-content-root]` — explicit opt-in.
|
|
33
|
-
* 2. The smallest classed wrapper inside `<main>` containing the
|
|
34
|
-
* majority of prose tags.
|
|
35
|
-
* 3. `<main>` itself.
|
|
36
|
-
* 4. `null`.
|
|
37
|
-
*
|
|
38
|
-
* Discovery (codeBlock): walk up from a `<pre>` inside `<main>` and
|
|
39
|
-
* collect classed ancestors between the content wrapper and `<pre>`,
|
|
40
|
-
* preserving their nesting order. Returns null when no `<pre>` exists,
|
|
41
|
-
* or when there are no classed wrappers between the prose wrapper and
|
|
42
|
-
* the `<pre>`.
|
|
11
|
+
* (prose content + code-block chrome) with `findContentWrapper`, and
|
|
12
|
+
* returns them as JSON. An editor page without this endpoint runs the
|
|
13
|
+
* same function on the page its style probe loads.
|
|
43
14
|
*/
|
|
44
|
-
export interface ContentWrapperInfo {
|
|
45
|
-
/** Lower-case HTML tag name as it appeared in source, eg `'article'`. */
|
|
46
|
-
tagName: string;
|
|
47
|
-
/** Space-separated class list from the source element. Preserved
|
|
48
|
-
* verbatim so Astro-scoped hashes (`astro-e3flfouy`) survive — host
|
|
49
|
-
* scoped CSS only matches when those hashes are present on the
|
|
50
|
-
* element. */
|
|
51
|
-
className: string;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface DiscoveredWrappers {
|
|
55
|
-
/** The element wrapping the page's prose content (h1-h6, p, etc.).
|
|
56
|
-
* For Starlight: `.sl-markdown-content`. For Tailwind Typography:
|
|
57
|
-
* `.prose`. Null when no prose wrapper exists on the page. */
|
|
58
|
-
content: ContentWrapperInfo | null;
|
|
59
|
-
/** Ordered chain of classed wrappers between the content wrapper
|
|
60
|
-
* and the `<pre>`, outermost first. For Starlight:
|
|
61
|
-
* `[{ div, 'expressive-code' }, { figure, 'frame has-title …' }]`.
|
|
62
|
-
* Null when the page has no code blocks or no classed wrappers
|
|
63
|
-
* between the prose wrapper and the `<pre>`. */
|
|
64
|
-
codeBlock: ContentWrapperInfo[] | null;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
15
|
export function createContentWrapperEndpoint(): Connect.NextHandleFunction {
|
|
68
16
|
return async (req, res, _next) => {
|
|
69
17
|
try {
|
|
@@ -96,232 +44,3 @@ export function createContentWrapperEndpoint(): Connect.NextHandleFunction {
|
|
|
96
44
|
}
|
|
97
45
|
};
|
|
98
46
|
}
|
|
99
|
-
|
|
100
|
-
/** Tags whose presence signals "this element holds prose content."
|
|
101
|
-
* We walk up from the first such element we find inside `<main>` to
|
|
102
|
-
* locate the wrapper. Headings + paragraphs cover every prose-styling
|
|
103
|
-
* convention we've seen — every CSS framework scopes typography
|
|
104
|
-
* through descendant selectors on `h1`–`h6` and `p`. */
|
|
105
|
-
const PROSE_TAGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p']);
|
|
106
|
-
|
|
107
|
-
/** Tag that anchors code-block wrapper discovery. The host's code-
|
|
108
|
-
* block library (Starlight's expressive-code, Tailwind's `pre`
|
|
109
|
-
* styling, etc.) always renders a `<pre>` containing the code,
|
|
110
|
-
* often wrapped in additional classed elements. */
|
|
111
|
-
const CODE_BLOCK_ANCHOR = 'pre';
|
|
112
|
-
|
|
113
|
-
/** HTML5 void elements — never push onto the open-tag stack since they
|
|
114
|
-
* have no closing tag. */
|
|
115
|
-
const VOID_TAGS = new Set([
|
|
116
|
-
'area',
|
|
117
|
-
'base',
|
|
118
|
-
'br',
|
|
119
|
-
'col',
|
|
120
|
-
'embed',
|
|
121
|
-
'hr',
|
|
122
|
-
'img',
|
|
123
|
-
'input',
|
|
124
|
-
'link',
|
|
125
|
-
'meta',
|
|
126
|
-
'source',
|
|
127
|
-
'track',
|
|
128
|
-
'wbr',
|
|
129
|
-
]);
|
|
130
|
-
|
|
131
|
-
interface OpenTag {
|
|
132
|
-
tag: string;
|
|
133
|
-
className: string;
|
|
134
|
-
attrs: Record<string, string>;
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Locate the host's content + code-block wrappers in raw HTML. Single-
|
|
139
|
-
* pass regex walk with a stack so we can recover ancestor chains for
|
|
140
|
-
* both prose tags and `<pre>` tags without a full DOM parser dep.
|
|
141
|
-
*
|
|
142
|
-
* Exported for unit testing.
|
|
143
|
-
*/
|
|
144
|
-
export function findContentWrapper(html: string): DiscoveredWrappers {
|
|
145
|
-
// Strip comments and scripts so opening-tag-shaped strings inside
|
|
146
|
-
// them don't pollute the walk.
|
|
147
|
-
const cleaned = html
|
|
148
|
-
.replace(/<!--[\s\S]*?-->/g, '')
|
|
149
|
-
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
|
150
|
-
.replace(/<style[\s\S]*?<\/style>/gi, '');
|
|
151
|
-
|
|
152
|
-
const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^>]*)?)\s*(\/?)>/g;
|
|
153
|
-
const stack: OpenTag[] = [];
|
|
154
|
-
|
|
155
|
-
let explicit: ContentWrapperInfo | null = null;
|
|
156
|
-
let mainEl: OpenTag | null = null;
|
|
157
|
-
const proseAncestorChains: OpenTag[][] = [];
|
|
158
|
-
const preAncestorChains: OpenTag[][] = [];
|
|
159
|
-
|
|
160
|
-
for (const match of cleaned.matchAll(tagRe)) {
|
|
161
|
-
const isClose = match[1] === '/';
|
|
162
|
-
const tagName = match[2].toLowerCase();
|
|
163
|
-
const attrBlob = match[3] ?? '';
|
|
164
|
-
const explicitlySelfClosing = match[4] === '/';
|
|
165
|
-
|
|
166
|
-
if (isClose) {
|
|
167
|
-
for (let i = stack.length - 1; i >= 0; i--) {
|
|
168
|
-
if (stack[i].tag === tagName) {
|
|
169
|
-
stack.length = i;
|
|
170
|
-
break;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
const attrs = parseAttributes(attrBlob);
|
|
177
|
-
const className = attrs.class ?? '';
|
|
178
|
-
const el: OpenTag = { tag: tagName, className, attrs };
|
|
179
|
-
|
|
180
|
-
// Priority 1 (content only): explicit opt-in. Capture and keep
|
|
181
|
-
// walking — we still need to discover the code-block wrapper.
|
|
182
|
-
if (!explicit && 'data-conloca-content-root' in attrs) {
|
|
183
|
-
explicit = { tagName, className };
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
if (!mainEl && tagName === 'main') {
|
|
187
|
-
mainEl = el;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
if (mainEl && PROSE_TAGS.has(tagName)) {
|
|
191
|
-
const mainIdx = stack.indexOf(mainEl);
|
|
192
|
-
if (mainIdx >= 0) {
|
|
193
|
-
proseAncestorChains.push(stack.slice(mainIdx + 1));
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
if (mainEl && tagName === CODE_BLOCK_ANCHOR) {
|
|
198
|
-
const mainIdx = stack.indexOf(mainEl);
|
|
199
|
-
if (mainIdx >= 0) {
|
|
200
|
-
preAncestorChains.push(stack.slice(mainIdx + 1));
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
const isVoid = VOID_TAGS.has(tagName);
|
|
205
|
-
if (!isVoid && !explicitlySelfClosing) {
|
|
206
|
-
stack.push(el);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
const content = resolveContentWrapper(explicit, mainEl, proseAncestorChains);
|
|
211
|
-
const codeBlock = resolveCodeBlockWrapper(content, preAncestorChains);
|
|
212
|
-
|
|
213
|
-
return { content, codeBlock };
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Pick the content wrapper from the walk's collected data.
|
|
218
|
-
*
|
|
219
|
-
* Priority: explicit opt-in > majority-prose-wrapper-inside-main >
|
|
220
|
-
* `<main>` fallback > null.
|
|
221
|
-
*/
|
|
222
|
-
function resolveContentWrapper(
|
|
223
|
-
explicit: ContentWrapperInfo | null,
|
|
224
|
-
mainEl: OpenTag | null,
|
|
225
|
-
proseAncestorChains: OpenTag[][],
|
|
226
|
-
): ContentWrapperInfo | null {
|
|
227
|
-
if (explicit) return explicit;
|
|
228
|
-
if (!mainEl) return null;
|
|
229
|
-
|
|
230
|
-
if (proseAncestorChains.length === 0) {
|
|
231
|
-
return { tagName: 'main', className: mainEl.className };
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// Tally classed-ancestor occurrences across all prose chains.
|
|
235
|
-
const scores = new Map<OpenTag, number>();
|
|
236
|
-
for (const chain of proseAncestorChains) {
|
|
237
|
-
for (const ancestor of chain) {
|
|
238
|
-
if (!ancestor.className) continue;
|
|
239
|
-
scores.set(ancestor, (scores.get(ancestor) ?? 0) + 1);
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// Majority threshold rules out partial-coverage classed ancestors
|
|
244
|
-
// (single Cards holding one of many prose blocks).
|
|
245
|
-
const threshold = proseAncestorChains.length / 2;
|
|
246
|
-
const candidates = [...scores.entries()].filter(([, count]) => count > threshold);
|
|
247
|
-
|
|
248
|
-
if (candidates.length === 0) {
|
|
249
|
-
return { tagName: 'main', className: mainEl.className };
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// Tie-break by depth: the candidate that appears deepest in any
|
|
253
|
-
// chain is the most specific (closest to the prose tags).
|
|
254
|
-
const maxChainIndex = (el: OpenTag) => Math.max(...proseAncestorChains.map((c) => c.indexOf(el)));
|
|
255
|
-
candidates.sort((a, b) => {
|
|
256
|
-
if (b[1] !== a[1]) return b[1] - a[1];
|
|
257
|
-
return maxChainIndex(b[0]) - maxChainIndex(a[0]);
|
|
258
|
-
});
|
|
259
|
-
|
|
260
|
-
const winner = candidates[0][0];
|
|
261
|
-
return { tagName: winner.tag, className: winner.className };
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* Derive the code-block wrapper chain from a representative `<pre>`'s
|
|
266
|
-
* ancestor chain. We strip everything at or above the content wrapper
|
|
267
|
-
* (its styles are already handled by the content-wrapper mirror) and
|
|
268
|
-
* return the remaining classed elements in nesting order, outermost
|
|
269
|
-
* first.
|
|
270
|
-
*
|
|
271
|
-
* Returning a chain (instead of one collapsed element) preserves the
|
|
272
|
-
* shape host CSS expects:
|
|
273
|
-
*
|
|
274
|
-
* - Single-class selectors (`.frame { ... }`) hit on whichever link
|
|
275
|
-
* carries that class.
|
|
276
|
-
* - Descendant selectors (`.expressive-code .frame { ... }`,
|
|
277
|
-
* `.frame .header > .title`) hit because the editor's renderer
|
|
278
|
-
* materialises the chain as nested elements with the host's
|
|
279
|
-
* expected tag names.
|
|
280
|
-
*
|
|
281
|
-
* The editor's code-block frame component (`code-block-frame.tsx` in
|
|
282
|
-
* `@conloca/mdx`) treats the LAST link as the "frame" element (where
|
|
283
|
-
* figcaption/pre/copy children render) and wraps it with the earlier
|
|
284
|
-
* links from inside out. This matches the host's authoring shape for
|
|
285
|
-
* libraries like ExpressiveCode (`.expressive-code > figure.frame >
|
|
286
|
-
* figcaption + pre + .copy`).
|
|
287
|
-
*/
|
|
288
|
-
function resolveCodeBlockWrapper(
|
|
289
|
-
content: ContentWrapperInfo | null,
|
|
290
|
-
preAncestorChains: OpenTag[][],
|
|
291
|
-
): ContentWrapperInfo[] | null {
|
|
292
|
-
if (preAncestorChains.length === 0) return null;
|
|
293
|
-
|
|
294
|
-
// Pick the first <pre>'s chain as representative. Code blocks on a
|
|
295
|
-
// single page are uniformly wrapped, so chains are interchangeable.
|
|
296
|
-
const chain = preAncestorChains[0];
|
|
297
|
-
|
|
298
|
-
// Strip everything at-or-above the content wrapper; the rest is
|
|
299
|
-
// code-block-specific chrome that this endpoint is responsible for.
|
|
300
|
-
const contentIdx = content
|
|
301
|
-
? chain.findIndex((el) => el.tag === content.tagName && el.className === content.className)
|
|
302
|
-
: -1;
|
|
303
|
-
const codeBlockChain = chain.slice(contentIdx + 1);
|
|
304
|
-
|
|
305
|
-
const classedAncestors = codeBlockChain.filter((el) => el.className);
|
|
306
|
-
if (classedAncestors.length === 0) return null;
|
|
307
|
-
|
|
308
|
-
return classedAncestors.map((el) => ({ tagName: el.tag, className: el.className }));
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/**
|
|
312
|
-
* Parse the attribute blob inside an opening tag. Handles `name="v"`,
|
|
313
|
-
* `name='v'`, `name=v`, and boolean (no-value) attributes. Doesn't
|
|
314
|
-
* handle entity decoding (`&` → `&`) since the values we read
|
|
315
|
-
* (tag name, class list, the marker attribute) don't carry entities
|
|
316
|
-
* in practice.
|
|
317
|
-
*/
|
|
318
|
-
function parseAttributes(s: string): Record<string, string> {
|
|
319
|
-
const out: Record<string, string> = {};
|
|
320
|
-
const re = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|(\S+)))?/g;
|
|
321
|
-
for (const match of s.matchAll(re)) {
|
|
322
|
-
const name = match[1];
|
|
323
|
-
const value = match[2] ?? match[3] ?? match[4] ?? '';
|
|
324
|
-
out[name] = value;
|
|
325
|
-
}
|
|
326
|
-
return out;
|
|
327
|
-
}
|