@ongov/ontario-design-system-component-html-generator 8.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,138 @@
1
+ #!/usr/bin/env node
2
+ import { mkdirSync, writeFileSync } from 'fs';
3
+ import { existsSync } from 'fs';
4
+ import { readFile } from 'fs/promises';
5
+ import path from 'path';
6
+ import { fileURLToPath, pathToFileURL } from 'url';
7
+ import { Command } from 'commander';
8
+ import { generateSamples } from './index.js';
9
+ const INIT_TEMPLATE = `/*
10
+ * Ontario Design System — Sample Generator config
11
+ *
12
+ * Each entry in the \`samples\` array defines one HTML sample to generate.
13
+ * Run the generator with:
14
+ *
15
+ * odscompgen --samplesFile ./samples.config.js --outputDirectory ./output
16
+ */
17
+
18
+ export const samples = [
19
+ {
20
+ component: 'ontario-button',
21
+ html: '<ontario-button type="primary" label="Click me"></ontario-button>',
22
+ outputFile: 'ontario-button.html',
23
+ description: 'Primary button from Ontario Design System',
24
+ includeStyles: true,
25
+ },
26
+ // Add more component samples here:
27
+ // {
28
+ // component: 'ontario-input',
29
+ // html: '<ontario-input name="email" label="Email address"></ontario-input>',
30
+ // outputFile: 'ontario-input.html',
31
+ // description: 'Text input from Ontario Design System',
32
+ // includeStyles: true,
33
+ // },
34
+ ];
35
+ `;
36
+ const INIT_TEMPLATE_JSON = `{
37
+ "samples": [
38
+ {
39
+ "component": "ontario-button",
40
+ "html": "<ontario-button type=\\"primary\\" label=\\"Click me\\"></ontario-button>",
41
+ "outputFile": "ontario-button.html",
42
+ "description": "Primary button from Ontario Design System",
43
+ "includeStyles": true
44
+ }
45
+ ]
46
+ }
47
+ `;
48
+ const DEFAULT_SAMPLES_PATH = fileURLToPath(new URL('./sample-config.js', import.meta.url));
49
+ async function loadSamples(samplesFilePath) {
50
+ var _a;
51
+ const resolvedPath = path.resolve(samplesFilePath);
52
+ if (resolvedPath.toLowerCase().endsWith('.json')) {
53
+ const raw = await readFile(resolvedPath, 'utf8');
54
+ const parsed = JSON.parse(raw);
55
+ if (Array.isArray(parsed)) {
56
+ return parsed;
57
+ }
58
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.samples)) {
59
+ return parsed.samples;
60
+ }
61
+ return null;
62
+ }
63
+ const samplesUrl = pathToFileURL(resolvedPath).href;
64
+ const samplesModule = await import(samplesUrl);
65
+ const samples = (_a = samplesModule.samples) !== null && _a !== void 0 ? _a : samplesModule.default;
66
+ if (!Array.isArray(samples)) {
67
+ return null;
68
+ }
69
+ return samples;
70
+ }
71
+ const program = new Command();
72
+ program
73
+ .name('odscompgen')
74
+ .description('Generate static HTML samples for Ontario Design System web components.')
75
+ .version('1.0.0');
76
+ program
77
+ .command('init')
78
+ .description('Scaffold a starter samples config file that you can customise and expand upon.')
79
+ .argument('[output]', 'Path to write the config file to')
80
+ .option('-f, --force', 'Overwrite the file if it already exists')
81
+ .option('--format <format>', 'Output format: "js" or "json"', 'js')
82
+ .action((output, options) => {
83
+ const format = options.format === 'json' ? 'json' : 'js';
84
+ const defaultFilename = format === 'json' ? 'samples.json' : 'samples.config.js';
85
+ const resolvedOutput = output !== null && output !== void 0 ? output : defaultFilename;
86
+ const dest = path.resolve(resolvedOutput);
87
+ if (existsSync(dest) && !options.force) {
88
+ console.error(`File already exists: ${dest}\nUse --force to overwrite.`);
89
+ process.exitCode = 1;
90
+ return;
91
+ }
92
+ const template = format === 'json' ? INIT_TEMPLATE_JSON : INIT_TEMPLATE;
93
+ mkdirSync(path.dirname(dest), { recursive: true });
94
+ writeFileSync(dest, template, 'utf8');
95
+ console.info(`Created samples config: ${dest}`);
96
+ console.info(`Edit it, then run:\n odscompgen --samplesFile ${resolvedOutput}`);
97
+ });
98
+ program
99
+ .command('generate', { isDefault: true })
100
+ .description('Generate HTML samples (default command).')
101
+ .option('-o, --outputDirectory <path>', 'Directory to write generated HTML samples to', path.resolve(process.cwd(), 'generated-samples'))
102
+ .option('-s, --samplesFile <path>', 'Path to a JS/TS module exporting `samples` (or default) or a JSON file containing `samples` or an array', DEFAULT_SAMPLES_PATH)
103
+ .option('--no-strip-outer-component', 'Keep the outer component tag in formatted markup')
104
+ .option('--no-remove-styles', 'Keep inline <style> tags from renderer output during formatting')
105
+ .option('--full-document', 'Wrap generated output in a full HTML document with DOCTYPE/html/head/body')
106
+ .action(async (options) => {
107
+ var _a;
108
+ const outputDirectory = path.resolve(options.outputDirectory);
109
+ mkdirSync(outputDirectory, { recursive: true });
110
+ const samples = await loadSamples(options.samplesFile);
111
+ if (!Array.isArray(samples)) {
112
+ console.error(`Could not load samples from: ${options.samplesFile}. Expected one of: JS/TS module with \`samples\` export, default array export, JSON array, or JSON object with \`samples\` array.`);
113
+ process.exitCode = 1;
114
+ return;
115
+ }
116
+ const formatterOptions = {
117
+ stripOuterComponent: options.stripOuterComponent,
118
+ removeStyles: options.removeStyles,
119
+ fullDocument: options.fullDocument,
120
+ };
121
+ const result = await generateSamples({ samples, formatterOptions });
122
+ for (const item of result.items) {
123
+ if (!item.success || !item.renderedHtml) {
124
+ console.error(`Failed to render ${item.sample.component}: ${(_a = item.error) !== null && _a !== void 0 ? _a : 'Unknown error'}`);
125
+ continue;
126
+ }
127
+ const outputPath = path.join(outputDirectory, item.sample.outputFile);
128
+ writeFileSync(outputPath, `${item.renderedHtml}\n`, 'utf8');
129
+ }
130
+ if (result.summary.failed > 0) {
131
+ console.warn(`Sample generation completed with ${result.summary.failed} failures.`);
132
+ process.exitCode = 1;
133
+ }
134
+ else {
135
+ console.info(`Generated ${result.summary.succeeded} samples in ${outputDirectory}.`);
136
+ }
137
+ });
138
+ program.parse();
@@ -0,0 +1,6 @@
1
+ import type { SampleGeneratorConfig, SampleGeneratorResult } from './types.js';
2
+ export type { ComponentSample, GeneratedSampleItem, SampleFormatterOptions, SampleGeneratorConfig, SampleGeneratorResult, } from './types.js';
3
+ /**
4
+ * Orchestrates the sample generation process.
5
+ */
6
+ export declare function generateSamples(config: SampleGeneratorConfig): Promise<SampleGeneratorResult>;
package/dist/index.js ADDED
@@ -0,0 +1,130 @@
1
+ /*
2
+ * Library entrypoint for sample generation.
3
+ *
4
+ * Responsibilities:
5
+ * - Render input sample HTML using a pluggable renderer.
6
+ * - Normalize/clean the rendered markup.
7
+ * - Resolve and transform component styles.
8
+ * - Return a deterministic result object (`items` + `summary`) without doing filesystem I/O.
9
+ *
10
+ * Filesystem writes and batch orchestration are intentionally handled by the CLI layer.
11
+ */
12
+ import { readFileSync } from 'fs';
13
+ import path from 'path';
14
+ import { renderToString } from '@ongov/ontario-design-system-component-library/hydrate';
15
+ import { buildDocument, extractOntarioComponents, flattenShadowRoot, formatHtml, stripCssComments, stripHydrationArtifacts, transformHostSelectors, } from './utils.js';
16
+ /**
17
+ * Dynamically generates CSS file paths for Ontario components.
18
+ * All Ontario components follow the same directory structure in the component library.
19
+ */
20
+ function getComponentStylePath(tagName) {
21
+ return path.join(process.cwd(), 'node_modules', '@ongov', 'ontario-design-system-component-library', 'dist', 'collection', 'components', tagName, `${tagName}.css`);
22
+ }
23
+ async function defaultRenderer(html) {
24
+ var _a;
25
+ const hydrated = await renderToString(html, {
26
+ prettyHtml: true,
27
+ });
28
+ return (_a = hydrated.html) !== null && _a !== void 0 ? _a : '';
29
+ }
30
+ function defaultStyleLoader(tagName) {
31
+ const cssPath = getComponentStylePath(tagName);
32
+ if (!cssPath) {
33
+ return '';
34
+ }
35
+ try {
36
+ const css = readFileSync(cssPath, 'utf8');
37
+ const transformed = transformHostSelectors(css, tagName);
38
+ return stripCssComments(transformed);
39
+ }
40
+ catch {
41
+ return '';
42
+ }
43
+ }
44
+ /**
45
+ * Loads CSS file for a component, transforms :host selectors, and strips comments.
46
+ */
47
+ async function loadComponentStyles(tagName, styleLoader) {
48
+ try {
49
+ const css = await styleLoader(tagName);
50
+ if (!css) {
51
+ return '';
52
+ }
53
+ const transformed = transformHostSelectors(css, tagName);
54
+ return stripCssComments(transformed);
55
+ }
56
+ catch {
57
+ return '';
58
+ }
59
+ }
60
+ /**
61
+ * Resolves CSS for a sample and nested Ontario components (e.g., icons).
62
+ */
63
+ async function buildStyles(sample, markup, styleLoader) {
64
+ if (sample.includeStyles !== false) {
65
+ const mainCss = await loadComponentStyles(sample.component, styleLoader);
66
+ const nestedComponents = extractOntarioComponents(markup);
67
+ const nestedCss = (await Promise.all(nestedComponents.filter((tag) => tag !== sample.component).map((tag) => loadComponentStyles(tag, styleLoader))))
68
+ .filter((css) => css.length > 0)
69
+ .join('\n\n');
70
+ const allCss = [mainCss, nestedCss].filter(Boolean).join('\n\n');
71
+ return allCss;
72
+ }
73
+ return '';
74
+ }
75
+ /**
76
+ * Renders Ontario Design System components using server-side rendering (renderToString)
77
+ * for fast, clean HTML output.
78
+ */
79
+ async function renderSample(sample, renderer, styleLoader, formatterOptions) {
80
+ var _a, _b, _c;
81
+ const hydratedHtml = await renderer(sample.html);
82
+ const renderedMarkup = stripHydrationArtifacts(flattenShadowRoot(hydratedHtml));
83
+ const markup = formatHtml(renderedMarkup, (_a = formatterOptions.stripOuterComponent) !== null && _a !== void 0 ? _a : true, (_b = formatterOptions.removeStyles) !== null && _b !== void 0 ? _b : true);
84
+ const styles = await buildStyles(sample, markup, styleLoader);
85
+ const renderedHtml = buildDocument(markup, styles, (_c = formatterOptions.fullDocument) !== null && _c !== void 0 ? _c : false);
86
+ return {
87
+ markup,
88
+ styles,
89
+ renderedHtml,
90
+ };
91
+ }
92
+ /**
93
+ * Orchestrates the sample generation process.
94
+ */
95
+ export async function generateSamples(config) {
96
+ var _a, _b, _c;
97
+ const renderer = (_a = config.renderer) !== null && _a !== void 0 ? _a : defaultRenderer;
98
+ const styleLoader = (_b = config.styleLoader) !== null && _b !== void 0 ? _b : defaultStyleLoader;
99
+ const formatterOptions = (_c = config.formatterOptions) !== null && _c !== void 0 ? _c : {};
100
+ const items = [];
101
+ for (const sample of config.samples) {
102
+ try {
103
+ const renderedSample = await renderSample(sample, renderer, styleLoader, formatterOptions);
104
+ items.push({
105
+ sample,
106
+ success: true,
107
+ markup: renderedSample.markup,
108
+ styles: renderedSample.styles,
109
+ renderedHtml: renderedSample.renderedHtml,
110
+ });
111
+ }
112
+ catch (error) {
113
+ items.push({
114
+ sample,
115
+ success: false,
116
+ error: error instanceof Error ? error.message : String(error),
117
+ });
118
+ }
119
+ }
120
+ const succeeded = items.filter((item) => item.success).length;
121
+ const failed = items.length - succeeded;
122
+ return {
123
+ items,
124
+ summary: {
125
+ total: items.length,
126
+ succeeded,
127
+ failed,
128
+ },
129
+ };
130
+ }
@@ -0,0 +1,3 @@
1
+ import type { ComponentSample } from './types.js';
2
+ export type { ComponentSample } from './types.js';
3
+ export declare const samples: ComponentSample[];
@@ -0,0 +1,26 @@
1
+ export const samples = [
2
+ {
3
+ component: 'ontario-button',
4
+ html: '<ontario-button type="primary" label="Click me"></ontario-button>',
5
+ outputFile: 'ontario-button.html',
6
+ description: 'Primary button from Ontario Design System',
7
+ includeStyles: true,
8
+ },
9
+ {
10
+ component: 'ontario-accordion',
11
+ html: `<ontario-accordion
12
+ name="My Accordion"
13
+ expand-collapse-button='{
14
+ "expandAllSectionsLabel": "Expand All",
15
+ "collapseAllSectionsLabel": "Collapse All"
16
+ }'
17
+ accordion-data='[
18
+ {"label": "Section 1", "content": "Content for section 1"},
19
+ {"label": "Section 2", "content": "Content for section 2"}
20
+ ]'
21
+ ></ontario-accordion>`,
22
+ outputFile: 'ontario-accordion.html',
23
+ description: 'Accordion component from Ontario Design System',
24
+ includeStyles: true,
25
+ },
26
+ ];
@@ -0,0 +1,103 @@
1
+ /**
2
+ * A single sample definition provided to the generator.
3
+ *
4
+ * This describes what should be rendered and how output should be named,
5
+ * without prescribing where or how the output is consumed.
6
+ */
7
+ export interface ComponentSample {
8
+ /** Ontario component tag name (for example: `ontario-button`). */
9
+ component: string;
10
+ /** Input HTML snippet to render/hydrate. */
11
+ html: string;
12
+ /** Output filename consumers can use when persisting generated results. */
13
+ outputFile: string;
14
+ /** Optional human-readable description for tooling or docs. */
15
+ description?: string;
16
+ /**
17
+ * Controls whether component styles are collected for this sample.
18
+ * Defaults to `true` when omitted.
19
+ */
20
+ includeStyles?: boolean;
21
+ }
22
+ /**
23
+ * Configuration contract for the library API.
24
+ *
25
+ * The library accepts this shape and always returns a `SampleGeneratorResult`.
26
+ * Callers decide where to write or display the returned data.
27
+ */
28
+ export interface SampleGeneratorConfig {
29
+ /** List of samples to process in this invocation. */
30
+ samples: ComponentSample[];
31
+ /**
32
+ * Optional formatter behavior used when cleaning rendered HTML.
33
+ * Defaults preserve existing CLI behavior when omitted.
34
+ */
35
+ formatterOptions?: SampleFormatterOptions;
36
+ /**
37
+ * Optional rendering strategy override.
38
+ * Use this to plug in a custom renderer instead of the default hydrate renderer.
39
+ */
40
+ renderer?: (html: string) => Promise<string>;
41
+ /**
42
+ * Optional style loading strategy override.
43
+ * Use this to source CSS from custom locations or pipelines.
44
+ */
45
+ styleLoader?: (tagName: string) => string | Promise<string>;
46
+ }
47
+ /**
48
+ * Controls post-render HTML cleanup behavior.
49
+ */
50
+ export interface SampleFormatterOptions {
51
+ /**
52
+ * When true, unwraps the outer Ontario component and returns only inner content.
53
+ * Defaults to `true`.
54
+ */
55
+ stripOuterComponent?: boolean;
56
+ /**
57
+ * When true, removes `<style>` tags from rendered markup before formatting.
58
+ * Defaults to `true`.
59
+ */
60
+ removeStyles?: boolean;
61
+ /**
62
+ * When true, wraps output in a full HTML document for browser preview:
63
+ * `<!DOCTYPE html>`, `<html>`, `<head>`, and `<body>`.
64
+ * Defaults to `false`.
65
+ */
66
+ fullDocument?: boolean;
67
+ }
68
+ /**
69
+ * Per-sample generation outcome.
70
+ *
71
+ * On success, `markup`/`styles`/`renderedHtml` are populated.
72
+ * On failure, `error` is populated.
73
+ */
74
+ export interface GeneratedSampleItem {
75
+ /** Original input sample associated with this result item. */
76
+ sample: ComponentSample;
77
+ /** Whether generation succeeded for this sample. */
78
+ success: boolean;
79
+ /** Clean rendered markup with framework artifacts removed. */
80
+ markup?: string;
81
+ /** Collected CSS for the sample and nested Ontario components. */
82
+ styles?: string;
83
+ /** Combined document string (style block + markup) for convenience/legacy consumers. */
84
+ renderedHtml?: string;
85
+ /** Error message when generation fails. */
86
+ error?: string;
87
+ }
88
+ /**
89
+ * Aggregate library response for a generation run.
90
+ */
91
+ export interface SampleGeneratorResult {
92
+ /** Per-sample outcomes in the same processing order as input. */
93
+ items: GeneratedSampleItem[];
94
+ /** Quick run-level counts for reporting and CI checks. */
95
+ summary: {
96
+ /** Number of samples attempted. */
97
+ total: number;
98
+ /** Number of successful sample generations. */
99
+ succeeded: number;
100
+ /** Number of failed sample generations. */
101
+ failed: number;
102
+ };
103
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Removes Stencil hydration artifacts from rendered markup:
3
+ * - `data-*` attributes
4
+ * - `s-id` / `c-id` attributes
5
+ * - `s-*` / `c-*` scope attributes
6
+ * - `hydrated` and `sc-*` class names
7
+ */
8
+ export declare function stripHydrationArtifacts(markup: string): string;
9
+ /**
10
+ * Removes mock shadow DOM wrappers that Stencil injects during testing,
11
+ * and strips declarative shadow DOM `<template shadowroot>` elements.
12
+ */
13
+ export declare function flattenShadowRoot(markup: string): string;
14
+ /**
15
+ * Replaces `:host` CSS selectors with the actual component tag name so that
16
+ * scoped styles work correctly when inlined into a static HTML document.
17
+ */
18
+ export declare function transformHostSelectors(css: string, tagName: string): string;
19
+ /**
20
+ * Strips block CSS comments (`/* ... *\/`) and normalises excessive blank lines.
21
+ */
22
+ export declare function stripCssComments(css: string): string;
23
+ /**
24
+ * Extracts unique Ontario component tag names from an HTML string.
25
+ * All `ontario-icon-*` variants are normalised to `ontario-icon`.
26
+ */
27
+ export declare function extractOntarioComponents(markup: string): string[];
28
+ /**
29
+ * Wraps markup in a `<style>` block when styles are provided.
30
+ * Returns bare markup when there are no styles.
31
+ * Optionally emits a complete HTML document when `fullDocument` is true.
32
+ */
33
+ export declare function buildDocument(markup: string, styles: string, fullDocument?: boolean): string;
34
+ /**
35
+ * Formats rendered HTML with consistent indentation and removes framework boilerplate:
36
+ * - Strips `<!doctype>`, `<html>`, `<head>`, `<body>` wrappers
37
+ * - Optionally removes `<style>` tags
38
+ * - Optionally unwraps the outermost Ontario component tag
39
+ * - Re-indents content with tabs
40
+ */
41
+ export declare function formatHtml(html: string, stripOuterComponent?: boolean, removeStyles?: boolean): string;
package/dist/utils.js ADDED
@@ -0,0 +1,139 @@
1
+ /*
2
+ * Pure utility functions for HTML and CSS processing.
3
+ *
4
+ * These are isolated from I/O and rendering so they can be unit-tested directly.
5
+ * All functions are stateless and deterministic.
6
+ */
7
+ /**
8
+ * Removes Stencil hydration artifacts from rendered markup:
9
+ * - `data-*` attributes
10
+ * - `s-id` / `c-id` attributes
11
+ * - `s-*` / `c-*` scope attributes
12
+ * - `hydrated` and `sc-*` class names
13
+ */
14
+ export function stripHydrationArtifacts(markup) {
15
+ let cleaned = markup;
16
+ // Remove all data-* attributes
17
+ cleaned = cleaned.replace(/\sdata-[^=\s]+="[^"]*"/g, '');
18
+ // Remove Stencil hydration attributes (s-id, c-id, etc.)
19
+ cleaned = cleaned.replace(/\s[sc]-id="[^"]*"/g, '');
20
+ // Remove Stencil scope attributes
21
+ cleaned = cleaned.replace(/\s[sc]-[a-z0-9-]+(?:="[^"]*")?/g, '');
22
+ // Clean up class attributes — remove `hydrated` and `sc-*` classes
23
+ cleaned = cleaned.replace(/\sclass="([^"]*)"/g, (_match, classValue) => {
24
+ const filtered = classValue.split(/\s+/).filter((name) => name && name !== 'hydrated' && !name.startsWith('sc-'));
25
+ return filtered.length ? ` class="${filtered.join(' ')}"` : '';
26
+ });
27
+ // Remove extra whitespace before closing angle brackets
28
+ return cleaned.replace(/\s+>/g, '>').replace(/\s+/g, ' ');
29
+ }
30
+ /**
31
+ * Removes mock shadow DOM wrappers that Stencil injects during testing,
32
+ * and strips declarative shadow DOM `<template shadowroot>` elements.
33
+ */
34
+ export function flattenShadowRoot(markup) {
35
+ return markup
36
+ .replace(/<mock:shadow-root\b[^>]*>/g, '')
37
+ .replace(/<\/mock:shadow-root>/g, '')
38
+ .replace(/<template\b[^>]*shadowroot[^>]*>/gi, '')
39
+ .replace(/<\/template>/gi, '');
40
+ }
41
+ /**
42
+ * Replaces `:host` CSS selectors with the actual component tag name so that
43
+ * scoped styles work correctly when inlined into a static HTML document.
44
+ */
45
+ export function transformHostSelectors(css, tagName) {
46
+ return css.replace(/:host\b/g, tagName);
47
+ }
48
+ /**
49
+ * Strips block CSS comments (`/* ... *\/`) and normalises excessive blank lines.
50
+ */
51
+ export function stripCssComments(css) {
52
+ let cleaned = css.replace(/\/\*[\s\S]*?\*\//g, '');
53
+ cleaned = cleaned.replace(/^\s*[\r\n]/gm, '');
54
+ cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
55
+ return cleaned.trim();
56
+ }
57
+ /**
58
+ * Extracts unique Ontario component tag names from an HTML string.
59
+ * All `ontario-icon-*` variants are normalised to `ontario-icon`.
60
+ */
61
+ export function extractOntarioComponents(markup) {
62
+ const componentRegex = /<(ontario-[a-z-]+)/gi;
63
+ const matches = markup.matchAll(componentRegex);
64
+ const components = new Set();
65
+ for (const match of matches) {
66
+ let component = match[1].toLowerCase();
67
+ if (component.startsWith('ontario-icon-')) {
68
+ component = 'ontario-icon';
69
+ }
70
+ components.add(component);
71
+ }
72
+ return Array.from(components);
73
+ }
74
+ /**
75
+ * Wraps markup in a `<style>` block when styles are provided.
76
+ * Returns bare markup when there are no styles.
77
+ * Optionally emits a complete HTML document when `fullDocument` is true.
78
+ */
79
+ export function buildDocument(markup, styles, fullDocument = false) {
80
+ if (fullDocument) {
81
+ const styleBlock = styles ? `\n\t\t<style>\n${styles}\n\t\t</style>` : '';
82
+ return `<!DOCTYPE html>\n<html lang="en">\n\t<head>\n\t\t<meta charset="utf-8">\n\t\t<meta name="viewport" content="width=device-width, initial-scale=1">${styleBlock}\n\t</head>\n\t<body>\n${markup}\n\t</body>\n</html>`;
83
+ }
84
+ if (!styles) {
85
+ return markup;
86
+ }
87
+ return `<style>\n${styles}\n</style>\n\n${markup}`;
88
+ }
89
+ /**
90
+ * Formats rendered HTML with consistent indentation and removes framework boilerplate:
91
+ * - Strips `<!doctype>`, `<html>`, `<head>`, `<body>` wrappers
92
+ * - Optionally removes `<style>` tags
93
+ * - Optionally unwraps the outermost Ontario component tag
94
+ * - Re-indents content with tabs
95
+ */
96
+ export function formatHtml(html, stripOuterComponent = false, removeStyles = true) {
97
+ let cleaned = html;
98
+ if (removeStyles) {
99
+ cleaned = cleaned.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
100
+ }
101
+ cleaned = cleaned.replace(/<!doctype[^>]*>/i, '');
102
+ cleaned = cleaned.replace(/<html[^>]*>/i, '');
103
+ cleaned = cleaned.replace(/<\/html>/i, '');
104
+ cleaned = cleaned.replace(/<head[^>]*>[\s\S]*?<\/head>/i, '');
105
+ cleaned = cleaned.replace(/<body[^>]*>/i, '');
106
+ cleaned = cleaned.replace(/<\/body>/i, '');
107
+ cleaned = cleaned.replace(/<!--[\s\S]*?-->/g, '');
108
+ if (stripOuterComponent) {
109
+ cleaned = cleaned.replace(/^[\s]*<[a-z]+-[a-z-]*[^>]*>[\s]*([\s\S]*?)[\s]*<\/[a-z]+-[a-z-]*>[\s]*$/i, '$1');
110
+ }
111
+ cleaned = cleaned.trim();
112
+ const parts = cleaned.split(/(<[^>]+>)/);
113
+ const lines = [];
114
+ let indentLevel = 0;
115
+ for (const part of parts) {
116
+ if (!part.trim())
117
+ continue;
118
+ if (part.startsWith('</')) {
119
+ indentLevel = Math.max(0, indentLevel - 1);
120
+ lines.push('\t'.repeat(indentLevel) + part);
121
+ }
122
+ else if (part.endsWith('/>') || /^<(br|hr|img|input|meta|link)[\s>]/i.test(part)) {
123
+ lines.push('\t'.repeat(indentLevel) + part);
124
+ }
125
+ else if (part.startsWith('<')) {
126
+ lines.push('\t'.repeat(indentLevel) + part);
127
+ if (!part.match(/^<(br|hr|img|input|meta|link|area|base|embed|source|track|wbr)[\s>]/i)) {
128
+ indentLevel++;
129
+ }
130
+ }
131
+ else {
132
+ const trimmed = part.trim();
133
+ if (trimmed) {
134
+ lines.push('\t'.repeat(indentLevel) + trimmed);
135
+ }
136
+ }
137
+ }
138
+ return lines.join('\n');
139
+ }
@@ -0,0 +1 @@
1
+ export {};