diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2a4235e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,44 @@ +name: CI + +on: + pull_request: + branches: [main] + push: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + node-version: [20, 22] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - run: npm ci + - run: npm test + + typecheck: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npx tsc --noEmit + + format: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npx prettier --config .prettierrc 'src/**/*.ts' 'test/**/*.ts' --check diff --git a/package.json b/package.json index 95884e0..ae12c59 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ ], "engines": { "npm": ">=8.0.0", - "node": ">=18.0.0" + "node": ">=20.0.0" }, "bin": "lib/cli.js", "type": "module", diff --git a/src/collection.ts b/src/collection.ts index 0138824..94d4a0e 100644 --- a/src/collection.ts +++ b/src/collection.ts @@ -8,6 +8,7 @@ const slugify = (_slugify as any).default as (str: string) => string; import Data from './helpers/Data.ts'; import { mergeTree } from './helpers/dom-diff.ts'; import { ASTNode } from './types.ts'; +import VariationMap, { remapData, remapASTReferences } from './helpers/variation-map.ts'; export interface CollectionConfig { name: string; @@ -65,6 +66,8 @@ export default class Collection { } async build(): Promise { + const variationMap = new VariationMap(); + const documents = await Promise.all( this.files.map(async (file) => { const html = await file.read(); @@ -76,7 +79,8 @@ export default class Collection { content: this.content }, processorConfig: this.processorConfig || {}, - logger: this.logger + logger: this.logger, + variationMap }); }) ); @@ -105,8 +109,7 @@ export default class Collection { await this.logger.writeLog('layout.json', JSON.stringify(current.layout, null, '\t')); for (let i = 2; i < documents.length; i++) { await this.logger.rotateLog(); - try - { + try { const next = baseDoc.diff(documents[i]); await this.logger.writeLog( `${slugify(documents[i].pathname)}.json`, @@ -117,7 +120,6 @@ export default class Collection { const currentPreMergeData = structuredClone(current.base.data.data); const nextPreMergeData = structuredClone(next.base.data.data); - // Merge the next and current bases const layout = mergeTree( current.base.data, next.base.data, @@ -130,12 +132,14 @@ export default class Collection { for (let i = 0; i < current.pages.length; i++) { const page = current.pages[i]; const nextData = new Data([], structuredClone(nextPreMergeData)); + nextData.variationMap = variationMap; mergeTree(page.data, nextData, current.layout, next.layout, [], this.logger); } for (let i = 0; i < next.pages.length; i++) { const page = next.pages[i]; const currentData = new Data([], structuredClone(currentPreMergeData)); + currentData.variationMap = variationMap; mergeTree(page.data, currentData, next.layout, current.layout, [], this.logger); } @@ -146,18 +150,28 @@ export default class Collection { pages: [...current.pages, ...next.pages], layout }; - } - catch(err){ - console.error("Error hit exporting log") + } catch (err) { + console.error('Error hit exporting log'); await this.logger.rotateLog(); throw err; } } await this.logger.rotateLog(); + const displayNames = variationMap.generateDisplayNames(); + const remappedLayout = remapASTReferences(current.layout, displayNames); + const remappedPages = [ + current.base.toJSON(), + ...current.pages.map((page) => page.toJSON()) + ].map((page) => ({ + ...page, + data: remapData(page.data, displayNames), + content: remapASTReferences(page.content, displayNames) + })); + return { - pages: [current.base.toJSON(), ...current.pages.map((page) => page.toJSON())], - layout: current.layout + pages: remappedPages, + layout: remappedLayout }; } } diff --git a/src/document.ts b/src/document.ts index f98d698..6c16eff 100644 --- a/src/document.ts +++ b/src/document.ts @@ -5,6 +5,7 @@ import htmlToAST, { HtmlProcessorConfig, PageContentsConfig } from './helpers/ht import { ASTNode } from './types.ts'; import Data from './helpers/Data.ts'; import { Logger } from './logger.ts'; +import VariationMap from './helpers/variation-map.ts'; export interface ASTTree { base: Page; @@ -22,6 +23,7 @@ export interface DocumentOptions { config: DocumentConfig; processorConfig: HtmlProcessorConfig; logger: Logger; + variationMap?: VariationMap; } export default class Document { @@ -30,10 +32,12 @@ export default class Document { data: Data; layout: ASTNode[]; contents: ASTNode[]; + variationMap?: VariationMap; constructor(options: DocumentOptions) { this.logger = options.logger; this.pathname = options.pathname; + this.variationMap = options.variationMap; const { layout, contents } = htmlToAST( options.content, options.config, @@ -42,10 +46,12 @@ export default class Document { this.layout = layout; this.contents = contents; this.data = new Data([], {}); + this.data.variationMap = this.variationMap; } diff(other: Document): ASTTree { this.data = new Data([], {}); + this.data.variationMap = this.variationMap; this.logger.log(`Comparing ${this.pathname} and ${other.pathname}`); const tree = mergeTree(this.data, other.data, this.layout, other.layout, [], this.logger); diff --git a/src/export-engines/html.ts b/src/export-engines/html.ts index 2f36904..f79b719 100644 --- a/src/export-engines/html.ts +++ b/src/export-engines/html.ts @@ -96,7 +96,7 @@ export default class HtmlExportEngine { throw new Error(`${node.type} render: not yet implemented`); } - renderDoctype(doctype: ASTDoctypeNode, variableScope: string): string { + renderDoctype(doctype: ASTDoctypeNode, _variableScope: string): string { return ``; } @@ -119,15 +119,18 @@ export default class HtmlExportEngine { .join(' ')}`; } - renderAttribute(attr: ASTStaticAttribute, variableScope: string): string { + renderAttribute(attr: ASTStaticAttribute, _variableScope: string): string { return [attr.name, `"${attr.value}"`].join('='); } - renderVariableAttribute(_attr: ASTVariableAttribute | ASTConditionalAttribute, variableScope: string): string { + renderVariableAttribute( + _attr: ASTVariableAttribute | ASTConditionalAttribute, + _variableScope: string + ): string { throw new Error('Not yet implemented'); } - renderConditionalAttribute(_attr: ASTConditionalAttribute, variableScope: string): string { + renderConditionalAttribute(_attr: ASTConditionalAttribute, _variableScope: string): string { throw new Error('Not yet implemented'); } @@ -138,53 +141,54 @@ export default class HtmlExportEngine { name = name.substring(5); } - // Elements that don't need closing tags - if(name === "meta" || name === "link" || name === "img"){ + // Elements that don't need closing tags + if (name === 'meta' || name === 'link' || name === 'img') { return `<${name}${this.renderAttributes(element.attrs, variableScope)}>${this.renderAST(element.children, variableScope)}`; } - // // TODO: Fix style tags + // // TODO: Fix style tags // if(name === "style"){ // return ``; // } // TODO: Fix scripts - if(name === "script"){ + if (name === 'script') { return ``; } return `<${name}${this.renderAttributes(element.attrs, variableScope)}>${this.renderAST( - element.children, variableScope + element.children, + variableScope )}`; } - renderText(text: ASTTextNode, variableScope: string): string { + renderText(text: ASTTextNode, _variableScope: string): string { return text.value; } - renderComment(text: ASTCommentNode, variableScope: string): string { + renderComment(text: ASTCommentNode, _variableScope: string): string { return ``; } - renderVariable(_node: ASTVariableNode, variableScope: string): string { + renderVariable(_node: ASTVariableNode, _variableScope: string): string { throw new Error('Variable render not yet implemented'); } - renderMarkdownVariable(_node: ASTMarkdownNode, variableScope: string): string { + renderMarkdownVariable(_node: ASTMarkdownNode, _variableScope: string): string { throw new Error('Markdown render not yet implemented'); } - renderInlineMarkdownVariable(_node: ASTInlineMarkdownNode, variableScope: string): string { + renderInlineMarkdownVariable(_node: ASTInlineMarkdownNode, _variableScope: string): string { throw new Error('Inline markdown render not yet implemented'); } - renderConditional(_node: ASTConditionalNode, variableScope: string): string { + renderConditional(_node: ASTConditionalNode, _variableScope: string): string { throw new Error('Conditional render not yet implemented'); } - renderLoop(_node: ASTLoopNode, variableScope: string): string { + renderLoop(_node: ASTLoopNode, _variableScope: string): string { throw new Error('Loop render not yet implemented'); } - renderContent(_node: ASTContentNode, variableScope: string): string { + renderContent(_node: ASTContentNode, _variableScope: string): string { throw new Error('Content render not yet implemented'); } } diff --git a/src/export-engines/hugo.ts b/src/export-engines/hugo.ts index 5ddac22..f20c277 100644 --- a/src/export-engines/hugo.ts +++ b/src/export-engines/hugo.ts @@ -21,11 +21,20 @@ function renderFrontMatter(data: Record) { } /** - * - * @param node + * + * @param node * @returns a string that is hugo formatted */ -function formatParam(node: ASTVariableNode | ASTMarkdownNode | ASTInlineMarkdownNode | ASTConditionalNode | ASTLoopNode | ASTVariableAttribute | ASTConditionalAttribute){ +function formatParam( + node: + | ASTVariableNode + | ASTMarkdownNode + | ASTInlineMarkdownNode + | ASTConditionalNode + | ASTLoopNode + | ASTVariableAttribute + | ASTConditionalAttribute +) { return node.reference.join('.').replaceAll(/([\-\:\s\@])+/g, '_'); } @@ -50,19 +59,19 @@ export default class HugoExportEngine extends HtmlExportEngine { exportLayout( layout: ASTNode[], - collection: CollectionResponse, + _collection: CollectionResponse, collectionKey: string ): FileExport { return { // TODO: this logic is currently fixed to use a default layout (list.html) pathname: `layouts/${collectionKey}/list.html`, - contents: this.renderAST(layout, ".Params.") + contents: this.renderAST(layout, '.Params.') }; } exportCollectionItem( item: Record, - collection: CollectionResponse, + _collection: CollectionResponse, collectionKey: string ): FileExport { const folder = collectionKey !== 'pages' ? `${collectionKey}/` : ''; @@ -73,10 +82,13 @@ export default class HugoExportEngine extends HtmlExportEngine { }; return { pathname: `content/${folder}${item.pathname.replace('index', '_index')}`, - contents: [renderFrontMatter(frontMatter), this.renderAST(item.content, ".Params.")].join('\n') + contents: [ + renderFrontMatter(frontMatter), + this.renderAST(item.content, '.Params.') + ].join('\n') }; } - + renderVariable(node: ASTVariableNode, variableScope: string): string { return `{{ ${variableScope}${formatParam(node)} }}`; } @@ -89,29 +101,33 @@ export default class HugoExportEngine extends HtmlExportEngine { // return `{{ .Params.${formatParam(node)} | fake_inline_markdownify_filter }}`; // TODO: fix fake_inline_markdownify_filter return `{{ ${variableScope}${formatParam(node)} | markdownify }}`; - } renderConditional(node: ASTConditionalNode, variableScope: string): string { return `{{ with ${variableScope}${formatParam(node)} }} ${this.renderASTNode( - node.template, "." + node.template, + '.' )}{{ end }}`; } renderLoop(node: ASTLoopNode, variableScope: string): string { return `{{ range ${variableScope}${formatParam(node)} }}${this.renderASTNode( - node.template, "." + node.template, + '.' )}{{ end }}`; } - renderContent(_node: ASTContentNode, variableScope: string): string { - return `{{ .Content }}`; + renderContent(_node: ASTContentNode, _variableScope: string): string { + return `{{ .Content }}`; } - renderVariableAttribute(attr: ASTVariableAttribute | ASTConditionalAttribute, variableScope: string): string { + renderVariableAttribute( + attr: ASTVariableAttribute | ASTConditionalAttribute, + variableScope: string + ): string { return [attr.name, `"{{ ${variableScope}${formatParam(attr)} }}"`].join('='); } - + renderConditionalAttribute(attr: ASTConditionalAttribute, variableScope: string): string { return `{{ with ${variableScope}${formatParam(attr)} }}{{ . }}{{ end }}`; } diff --git a/src/helpers/Data.ts b/src/helpers/Data.ts index e384418..a89f83e 100644 --- a/src/helpers/Data.ts +++ b/src/helpers/Data.ts @@ -1,6 +1,7 @@ import { ASTAttribute, ASTElementNode } from '../types.ts'; import { getElementSignature } from './getElementSignature.ts'; import { getClassList } from './node-helper.ts'; +import VariationMap, { extractStaticContext } from './variation-map.ts'; const htmlTagToVariableSuffix: Record = { ol: 'list', @@ -27,11 +28,11 @@ function getAttributeSignature(attr: ASTAttribute | undefined): string | null { } /** - * - * @param variable string containing a variable name. + * + * @param variable string containing a variable name. * @returns a string that is formatted to work across various ssgs. */ -function formatVariable(variable: String){ +function formatVariable(variable: String) { return variable.replaceAll(/([\[\]\(\)%—,\-\:])+/g, '_'); } @@ -119,14 +120,19 @@ export function joinNameParts(parts: string[]) { export default class Data { chain: string[]; data: Record; + variationMap?: VariationMap; + variationScope: string; constructor(chain: string[], data: Record) { this.chain = chain; this.data = data; + this.variationScope = ''; } set(variableName: string, value: any): void { - this.data[formatVariable(variableName)] = value; + const formatted = formatVariable(variableName); + this.data[formatted] = value; + this.variationMap?.recordValue(formatted, value, this.variationScope); } delete(variableName: string): void { @@ -163,12 +169,23 @@ export default class Data { } getVariableName(parentElements: ASTElementNode[], prefix?: string, suffix?: string): string { - const length = parentElements.length; + const lastElement = length > 0 ? parentElements[length - 1] : undefined; + + const signature = lastElement ? getElementSignature(lastElement) : ''; + const key = this.versionedVarableName( + joinNameParts([prefix || '', signature, suffix || '']) + ); + + if (this.variationMap && lastElement) { + this.variationMap.record(key, { + sourceElement: extractStaticContext(lastElement), + suffix: suffix || undefined, + scope: this.variationScope + }); + } - const signature = - length > 0 ? getElementSignature(parentElements[parentElements.length - 1]) : ''; - return this.versionedVarableName(joinNameParts([prefix || '', signature, suffix || ''])); + return key; } versionedVarableName(variableName: string): string { @@ -195,11 +212,27 @@ export default class Data { merge(other: Data): Data { const clone = mergeHash(this.data, other.data); - return new Data(this.chain, clone); + const merged = new Data(this.chain, clone); + merged.variationMap = this.variationMap ?? other.variationMap; + merged.variationScope = this.variationScope; + return merged; } createSubdata(variableName: string, data?: Record): Data { - return new Data(this.getChain(formatVariable(variableName)), data || {}); + const sub = new Data(this.getChain(formatVariable(variableName)), data || {}); + sub.variationMap = this.variationMap; + sub.variationScope = formatVariable(variableName); + return sub; + } + + withVariationMap(map: VariationMap): Data { + this.variationMap = map; + return this; + } + + withScope(scope: string): Data { + this.variationScope = scope; + return this; } toJSON(): Record { diff --git a/src/helpers/component-builder.ts b/src/helpers/component-builder.ts index 1938886..7162c5b 100644 --- a/src/helpers/component-builder.ts +++ b/src/helpers/component-builder.ts @@ -13,6 +13,7 @@ import { import { diffNodes } from './dom-diff.ts'; import { Logger, nodeDebugString } from '../logger.ts'; import { liftVariables } from './variable-lifting.ts'; +import { extractStaticContext } from './variation-map.ts'; export interface ComponentBuilderConfig { disableMarkdown?: boolean; @@ -41,6 +42,13 @@ export function convertAttrsToVariables( const attr = element.attrs[attrName]; if (attr && attr.type === 'attribute' && editableAttrs[attrName]) { const variableName = data.getVariableName([element], '', attrName); + if (data.variationMap) { + data.variationMap.record(variableName, { + sourceElement: extractStaticContext(element), + attrName, + scope: data.variationScope + }); + } data.set(variableName, attr.value); converted[attrName] = { type: 'variable-attribute', @@ -96,15 +104,16 @@ function buildLoop( parentElements: ASTElementNode[], inputData: Data, outputData: Data, - config: ComponentBuilderConfig, - logger: Logger + _config: ComponentBuilderConfig, + logger: Logger, + scopeHint?: string ): Loop | null { const data = [] as Data[]; const base = elements[0]; let current: LoopState | null = null; let inputBaseData: Record = {}; - + const baseLiftedVariables = liftVariables(base, inputData); Object.keys(baseLiftedVariables).forEach((variableName) => { inputBaseData[variableName] = inputData.getKey(variableName); @@ -114,6 +123,8 @@ function buildLoop( for (let i = 1; i < elements.length; i++) { const loopEl = elements[i]; const newBaseData = new Data([], structuredClone(inputBaseData)); + newBaseData.variationMap = outputData.variationMap; + if (scopeHint) newBaseData.variationScope = scopeHint; const inputLoopData: Record = {}; const liftedVariables = liftVariables(loopEl, inputData); Object.keys(liftedVariables).forEach((variableName) => { @@ -122,6 +133,8 @@ function buildLoop( }); const otherData = new Data([], structuredClone(inputLoopData)); + otherData.variationMap = outputData.variationMap; + if (scopeHint) otherData.variationScope = scopeHint; const template = diffNodes( newBaseData, otherData, @@ -276,17 +289,23 @@ export function convertTreeToComponents( .filter((node) => node.type === 'element') as ASTElementNode[]; if (repeatedElements.length > 1) { + const anticipatedLoopVar = data.getVariableName( + parentElements, + '', + 'items' + ); const loopData = buildLoop( repeatedElements, parentElements, existingData, data, config, - logger + logger, + anticipatedLoopVar ); if (loopData) { const { itemData, template } = loopData; - const variableName = data.getVariableName(parentElements, '', 'items'); + const variableName = anticipatedLoopVar; data.set( variableName, itemData.map((item: Data) => item.toJSON()) diff --git a/src/helpers/dom-diff.ts b/src/helpers/dom-diff.ts index 2b58c82..a3f564b 100644 --- a/src/helpers/dom-diff.ts +++ b/src/helpers/dom-diff.ts @@ -29,6 +29,7 @@ import { booleanAttributes } from './attributes.ts'; import { Logger, nodeDebugString } from '../logger.ts'; import { convertTreeToComponents, convertElementToComponent } from './component-builder.ts'; import { liftVariables } from './variable-lifting.ts'; +import { extractStaticContext } from './variation-map.ts'; export function diffBasicNode( firstData: Data, @@ -36,7 +37,7 @@ export function diffBasicNode( firstNode: ASTValueNode, secondNode: ASTValueNode, parentElements: ASTElementNode[], - logger: Logger + _logger: Logger ): ASTNode { const valuesMatch = firstNode.value.trim() === secondNode.value.trim(); if (valuesMatch) { @@ -278,7 +279,11 @@ function diffConditionalAndElementNode( }); const existingData = new Data([], structuredClone(existingValue)); + existingData.variationMap = conditionalData.variationMap; + existingData.variationScope = variableName; const newData = new Data([], structuredClone(liftedVariables)); + newData.variationMap = elementData.variationMap; + newData.variationScope = variableName; const template = diffElementNode( existingData, @@ -338,10 +343,14 @@ function diffConditionalNodes( [], firstSubData === null || typeof firstSubData !== 'object' ? {} : firstSubData ); + newData.variationMap = firstData.variationMap; + newData.variationScope = variableName; const otherData = new Data( [], secondSubData === null || typeof secondSubData !== 'object' ? {} : secondSubData ); + otherData.variationMap = secondData.variationMap; + otherData.variationScope = variableName; const template = diffElementNode( newData, @@ -398,7 +407,11 @@ function diffLoopAndElementNode( }); const existingData = new Data([], existingItems[0]); + existingData.variationMap = loopData.variationMap; + existingData.variationScope = variableName; const newData = new Data([], structuredClone(liftedVariables)); + newData.variationMap = elementData.variationMap; + newData.variationScope = variableName; diffElementNode(existingData, newData, loopNode.template, elementNode, parentElements, logger); elementData.chainSet(loopNode.reference, [newData.toJSON()]); @@ -416,10 +429,7 @@ function diffConditionalAndLoopNode( const variableName = conditionalNode.reference[0]; if (conditionalData.hasKey(variableName)) { const existingValue = conditionalData.getKey(variableName); - conditionalData.set( - variableName, - existingValue != null ? [existingValue] : [] - ); + conditionalData.set(variableName, existingValue != null ? [existingValue] : []); } const promotedLoop: ASTLoopNode = { @@ -448,6 +458,13 @@ function mergeAttribute( logger: Logger ): ASTAttribute { const variableName = firstData.getVariableName([element], '', attrName); + if (firstData.variationMap) { + firstData.variationMap.record(variableName, { + sourceElement: extractStaticContext(element), + attrName, + scope: firstData.variationScope + }); + } if (firstAttr.type !== 'attribute') { logger?.warn('TODO: add relevant null state for !secondAttr'); if (secondAttr?.type === 'attribute') { @@ -575,7 +592,9 @@ function buildLoop( firstEls: ASTElementNode[], secondEls: ASTElementNode[], parentElements: ASTElementNode[], - logger: Logger + logger: Logger, + variationMap?: import('./variation-map.ts').default, + scopeHint?: string ): Loop | null { const firstItems = [] as Data[]; const secondItems = [] as Data[]; @@ -599,7 +618,11 @@ function buildLoop( for (let i = 1; i < elements.length; i++) { const loopEl = elements[i]; const newBaseData = new Data([], {}); + newBaseData.variationMap = variationMap; + if (scopeHint) newBaseData.variationScope = scopeHint; const otherData = new Data([], {}); + otherData.variationMap = variationMap; + if (scopeHint) otherData.variationScope = scopeHint; const template = diffNodes( newBaseData, otherData, @@ -742,7 +765,10 @@ export function mergeTree( const parents = [...parentElements]; if (node.type === 'element') { parents.push(node); + const variableName = firstData.getVariableName(parents); const newData = new Data([], {}); + newData.variationMap = firstData.variationMap; + newData.variationScope = variableName; const config = {}; // TODO pass component config const template = convertElementToComponent( newData, @@ -752,7 +778,6 @@ export function mergeTree( firstData, logger ); - const variableName = firstData.getVariableName(parents); firstData.set(variableName, newData.toJSON()); secondData.set(variableName, null); merged.push({ @@ -828,19 +853,22 @@ export function mergeTree( // TODO: Object building if (!isExactMatch) { + const anticipatedLoopVar = firstData.getVariableName( + parentElements, + '', + 'items' + ); const loopData = buildLoop( firstEls, secondEls, parentElements, - logger + logger, + firstData.variationMap, + anticipatedLoopVar ); if (loopData) { const { firstItems, secondItems, template } = loopData; - const variableName = firstData.getVariableName( - parentElements, - '', - 'items' - ); + const variableName = anticipatedLoopVar; firstData.set( variableName, firstItems.map((item: Data) => item.toJSON()) @@ -897,7 +925,14 @@ export function mergeTree( .slice(0, repeatedIndex + 1) .filter((node) => node.type === 'element') as ASTElementNode[]; if (elements.length > 1) { - const loopData = buildLoop(elements, [], parentElements, logger); + const loopData = buildLoop( + elements, + [], + parentElements, + logger, + firstData.variationMap, + other.reference[0] + ); if (loopData) { const { firstItems, template } = loopData; firstData.chainSet( @@ -939,7 +974,14 @@ export function mergeTree( .slice(0, repeatedIndex + 1) .filter((node) => node.type === 'element') as ASTElementNode[]; if (elements.length > 1) { - const loopData = buildLoop(elements, [], parentElements, logger); + const loopData = buildLoop( + elements, + [], + parentElements, + logger, + secondData.variationMap, + current.reference[0] + ); if (loopData) { const { secondItems, template } = loopData; secondData.chainSet( @@ -980,7 +1022,7 @@ export function mergeTree( '\nvs\n', JSON.stringify(other), '?????????????????????????' - ); + ); } merged.push(diffNodes(firstData, secondData, current, other, parentElements, logger)); diff --git a/src/helpers/html-parser.ts b/src/helpers/html-parser.ts index 497b8c6..63ceaec 100644 --- a/src/helpers/html-parser.ts +++ b/src/helpers/html-parser.ts @@ -11,7 +11,16 @@ import { } from '../types.ts'; import { DocumentConfig } from '../document.ts'; -type NodeType = 'element' | 'attribute' | 'text' | 'cdata' | 'PROCESSING_INSTRUCTION_NODE' | 'comment' | 'DOCUMENT_NODE' | 'docType' | 'DOCUMENT_FRAGMENT_NODE'; +type NodeType = + | 'element' + | 'attribute' + | 'text' + | 'cdata' + | 'PROCESSING_INSTRUCTION_NODE' + | 'comment' + | 'DOCUMENT_NODE' + | 'docType' + | 'DOCUMENT_FRAGMENT_NODE'; // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType const nodeTypes = { @@ -180,7 +189,11 @@ interface HTMLProcessorResponse { contents: ASTNode[]; } -export default function htmlToAST(html: string, documentConfig: DocumentConfig, processorConfig: HtmlProcessorConfig): HTMLProcessorResponse { +export default function htmlToAST( + html: string, + documentConfig: DocumentConfig, + processorConfig: HtmlProcessorConfig +): HTMLProcessorResponse { const processor = new htmlProcessor(documentConfig.content || {}, processorConfig); const layout = processor.parse(html); diff --git a/src/helpers/markdown.ts b/src/helpers/markdown.ts index ce54555..708e8c9 100644 --- a/src/helpers/markdown.ts +++ b/src/helpers/markdown.ts @@ -1,6 +1,5 @@ import HtmlExportEngine from '../export-engines/html.ts'; import { ASTElementNode, ASTNode } from '../types.ts'; -import { findLastNonWhitespaceIndex } from './node-helper.ts'; import * as Turndown from 'turndown'; const TurndownService = (Turndown as any).default; @@ -106,8 +105,7 @@ export function isMarkdownInlineTree( } export function isMarkdownTree(nodes: ASTNode[]): boolean { - const nonWhitespaceIndex = findLastNonWhitespaceIndex(nodes); - const { lastElIndex, lastCheckedIndex } = findEndOfMarkdownIndex(nodes); + const { lastCheckedIndex } = findEndOfMarkdownIndex(nodes); return lastCheckedIndex === nodes.length - 1; } diff --git a/src/helpers/node-equivalency.ts b/src/helpers/node-equivalency.ts index f9b3f52..e0ca45e 100644 --- a/src/helpers/node-equivalency.ts +++ b/src/helpers/node-equivalency.ts @@ -139,7 +139,9 @@ export function nodeTreeEquivalencyScore(firstTree: ASTNode[], secondTree: ASTNo export function nodeEquivalencyScore(first: ASTNode, second: ASTNode): number { if (first.type === 'conditional' && second.type === 'conditional') { - return first.reference.join('') === second.reference.join('') ? (1 + nodeEquivalencyScore(first.template, second.template))/2 : 0; + return first.reference.join('') === second.reference.join('') + ? (1 + nodeEquivalencyScore(first.template, second.template)) / 2 + : 0; } if (second.type === 'conditional') { diff --git a/src/helpers/variation-map.ts b/src/helpers/variation-map.ts new file mode 100644 index 0000000..29f5001 --- /dev/null +++ b/src/helpers/variation-map.ts @@ -0,0 +1,417 @@ +import { ASTElementNode } from '../types.ts'; +import { normalizeClassList } from './node-helper.ts'; + +export interface SourceElementContext { + tag: string; + staticId?: string; + staticClasses?: string[]; + identifyingAttrs?: Record; +} + +export interface VariationEntry { + internalKey: string; + values: any[]; + sourceElement?: SourceElementContext; + attrName?: string; + suffix?: string; + scope: string; +} + +const htmlTagToSemanticName: Record = { + h1: ['heading', 'subheading'], + h2: ['heading', 'subheading'], + h3: ['heading', 'subheading'], + h4: ['heading', 'subheading'], + h5: ['heading', 'subheading'], + h6: ['heading', 'subheading'], + li: ['item'], + nav: ['navigation'], + img: ['image'] +}; + +function formatForSSG(variable: string): string { + return variable.replaceAll(/([\[\]\(\)%—,\-\:])+/g, '_'); +} + +export function extractStaticContext(element: ASTElementNode): SourceElementContext { + const context: SourceElementContext = { tag: element.name }; + + const idAttr = element.attrs['id']; + if (idAttr?.type === 'attribute' && idAttr.value) { + context.staticId = idAttr.value.trim(); + } + + const classAttr = element.attrs['class']; + if (classAttr?.type === 'attribute' && classAttr.value) { + context.staticClasses = normalizeClassList(classAttr.value); + } + + if (element.name === 'meta') { + const identifying: Record = {}; + for (const attr of ['name', 'property', 'http-equiv']) { + const a = element.attrs[attr]; + if (a?.type === 'attribute' && a.value) { + identifying[attr] = a.value.trim(); + } + } + if (Object.keys(identifying).length > 0) { + context.identifyingAttrs = identifying; + } + } + + if (element.name === 'link') { + const relAttr = element.attrs['rel']; + if (relAttr?.type === 'attribute' && relAttr.value) { + context.identifyingAttrs = { rel: relAttr.value.trim() }; + } + } + + return context; +} + +export type ScopedNameMap = Map>; + +export default class VariationMap { + private scopes: Map> = new Map(); + + record(key: string, meta: Partial>): void { + const scope = meta.scope ?? ''; + if (!this.scopes.has(scope)) this.scopes.set(scope, new Map()); + const scopeMap = this.scopes.get(scope)!; + + if (!scopeMap.has(key)) { + scopeMap.set(key, { + internalKey: key, + values: [], + scope, + ...meta + }); + } else { + const existing = scopeMap.get(key)!; + if (meta.attrName && !existing.attrName) existing.attrName = meta.attrName; + if (meta.sourceElement && !existing.sourceElement) + existing.sourceElement = meta.sourceElement; + if (meta.suffix && !existing.suffix) existing.suffix = meta.suffix; + } + } + + recordValue(key: string, value: any, scope: string): void { + const scopeMap = this.scopes.get(scope); + if (scopeMap) { + const entry = scopeMap.get(key); + if (entry) { + entry.values.push(value); + return; + } + } + for (const sm of this.scopes.values()) { + const entry = sm.get(key); + if (entry) { + entry.values.push(value); + return; + } + } + } + + generateDisplayNames(): ScopedNameMap { + const result: ScopedNameMap = new Map(); + const flatLookup = new Map(); + + const processed = new Set(); + const queue = ['']; + + while (queue.length > 0) { + const scope = queue.shift()!; + if (processed.has(scope)) continue; + processed.add(scope); + + const scopeEntries = this.scopes.get(scope); + if (!scopeEntries) continue; + + const parentDisplayName = scope === '' ? undefined : flatLookup.get(scope); + const scopeNames = this.generateScopeNames( + [...scopeEntries.values()], + parentDisplayName + ); + + result.set(scope, scopeNames); + for (const [internalKey, displayName] of scopeNames) { + flatLookup.set(internalKey, displayName); + if (this.scopes.has(internalKey)) { + queue.push(internalKey); + } + } + } + + for (const scope of this.scopes.keys()) { + if (!processed.has(scope)) { + const scopeEntries = this.scopes.get(scope)!; + const parentDisplayName = flatLookup.get(scope); + const scopeNames = this.generateScopeNames( + [...scopeEntries.values()], + parentDisplayName + ); + result.set(scope, scopeNames); + for (const [internalKey, displayName] of scopeNames) { + flatLookup.set(internalKey, displayName); + } + } + } + + return result; + } + + private generateScopeNames( + entries: VariationEntry[], + parentDisplayName?: string + ): Map { + const result = new Map(); + const taken = new Set(); + + const entriesWithCandidates = entries.map((entry) => ({ + entry, + candidates: this.generateCandidateNames(entry) + })); + + entriesWithCandidates.sort((a, b) => { + const diff = a.candidates.length - b.candidates.length; + if (diff !== 0) return diff; + return a.entry.internalKey.localeCompare(b.entry.internalKey); + }); + + for (const { entry, candidates } of entriesWithCandidates) { + let chosen: string | null = null; + for (const candidate of candidates) { + const formatted = formatForSSG(candidate); + if (formatted && !taken.has(formatted) && formatted !== parentDisplayName) { + chosen = formatted; + break; + } + } + + if (!chosen) { + const base = formatForSSG(candidates[0] || entry.internalKey); + let i = 0; + while (taken.has(`${base}_${i}`)) i++; + chosen = `${base}_${i}`; + } + + taken.add(chosen); + result.set(entry.internalKey, chosen); + } + + return result; + } + + private generateCandidateNames(entry: VariationEntry): string[] { + const candidates: string[] = []; + const el = entry.sourceElement; + const suffix = entry.suffix; + const attrName = entry.attrName; + const isNonRootScope = entry.scope !== ''; + + if (!el) { + candidates.push(entry.internalKey); + return candidates; + } + + if (attrName === 'class') { + const stableClasses = this.findStableClasses(entry); + const sorted = stableClasses.sort((a, b) => a.length - b.length); + for (const cls of sorted) { + candidates.push(`${cls}_class`); + } + if (el.staticClasses?.length) { + const elSorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + for (const cls of elSorted) { + if (!stableClasses.includes(cls)) { + candidates.push(`${cls}_class`); + } + } + } + candidates.push(`${el.tag}_class`); + candidates.push(entry.internalKey); + return candidates; + } + + if (attrName) { + if (el.identifyingAttrs) { + for (const value of Object.values(el.identifyingAttrs)) { + candidates.push(value); + } + } + candidates.push(attrName); + if (el.staticId) candidates.push(`${el.staticId}_${attrName}`); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + for (const cls of sorted) { + candidates.push(`${cls}_${attrName}`); + } + } + const semanticNames = htmlTagToSemanticName[el.tag]; + if (semanticNames) { + for (const name of semanticNames) { + candidates.push(`${name}_${attrName}`); + } + } + candidates.push(`${el.tag}_${attrName}`); + candidates.push(entry.internalKey); + return candidates; + } + + if (suffix === 'items') { + if (el.staticId) candidates.push(`${el.staticId}_items`); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + for (const cls of sorted) { + candidates.push(`${cls}_items`); + } + } + candidates.push('items'); + candidates.push(`${el.tag}_items`); + candidates.push(entry.internalKey); + return candidates; + } + + if (suffix === 'markdown' || suffix === 'inline_markdown') { + candidates.push(suffix); + const semanticNames = htmlTagToSemanticName[el.tag]; + if (semanticNames) { + candidates.push(...semanticNames); + } + if (el.staticId) candidates.push(el.staticId); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + candidates.push(...sorted); + } + candidates.push(`${el.tag}_${suffix}`); + candidates.push(entry.internalKey); + return candidates; + } + + if (isNonRootScope) { + candidates.push('text'); + } + const semanticNames = htmlTagToSemanticName[el.tag]; + if (semanticNames) { + candidates.push(...semanticNames); + } + if (el.staticId) candidates.push(el.staticId); + if (el.staticClasses?.length) { + const sorted = [...el.staticClasses].sort((a, b) => a.length - b.length); + candidates.push(...sorted); + } + candidates.push(el.tag); + candidates.push(entry.internalKey); + return candidates; + } + + private findStableClasses(entry: VariationEntry): string[] { + const stringValues = entry.values.filter((v): v is string => typeof v === 'string'); + if (stringValues.length === 0) { + return entry.sourceElement?.staticClasses ?? []; + } + + const classLists = stringValues.map((v) => normalizeClassList(v)); + return classLists.reduce((acc, list) => acc.filter((cls) => list.includes(cls))); + } +} + +export function remapData( + data: Record, + scopeMap: ScopedNameMap, + scope: string = '' +): Record { + const nameMap = scopeMap.get(scope); + const result: Record = {}; + for (const [key, value] of Object.entries(data)) { + const newKey = nameMap?.get(key) ?? key; + if (Array.isArray(value)) { + result[newKey] = value.map((item) => + typeof item === 'object' && item !== null ? remapData(item, scopeMap, key) : item + ); + } else if (typeof value === 'object' && value !== null) { + result[newKey] = remapData(value, scopeMap, key); + } else { + result[newKey] = value; + } + } + return result; +} + +export function remapASTReferences( + tree: import('../types.ts').ASTNode[], + scopeMap: ScopedNameMap, + scope: string = '' +): import('../types.ts').ASTNode[] { + return tree.map((node) => remapASTNode(node, scopeMap, scope)); +} + +function remapReference(ref: string[], nameMap: Map | undefined): string[] { + if (!nameMap) return ref; + return ref.map((part) => nameMap.get(part) ?? part); +} + +function remapASTNode( + node: import('../types.ts').ASTNode, + scopeMap: ScopedNameMap, + scope: string +): import('../types.ts').ASTNode { + const nameMap = scopeMap.get(scope); + switch (node.type) { + case 'variable': + case 'markdown-variable': + case 'inline-markdown-variable': + return { ...node, reference: remapReference(node.reference, nameMap) }; + case 'conditional': { + const innerScope = node.reference[0]; + return { + ...node, + reference: remapReference(node.reference, nameMap), + template: remapASTNode( + node.template, + scopeMap, + innerScope + ) as import('../types.ts').ASTElementNode + }; + } + case 'loop': { + const innerScope = node.reference[0]; + return { + ...node, + reference: remapReference(node.reference, nameMap), + template: remapASTNode( + node.template, + scopeMap, + innerScope + ) as import('../types.ts').ASTElementNode + }; + } + case 'element': + return { + ...node, + attrs: remapAttrList(node.attrs, nameMap), + children: remapASTReferences(node.children, scopeMap, scope) + }; + default: + return node; + } +} + +function remapAttrList( + attrs: import('../types.ts').ASTAttributeList, + nameMap: Map | undefined +): import('../types.ts').ASTAttributeList { + const result: import('../types.ts').ASTAttributeList = {}; + for (const [key, attr] of Object.entries(attrs)) { + if (attr.type === 'variable-attribute' || attr.type === 'conditional-attribute') { + result[key] = { + ...attr, + reference: remapReference(attr.reference, nameMap) + }; + } else { + result[key] = attr; + } + } + return result; +} diff --git a/test/fixtures/sites/conditional-to-loop/collection.json b/test/fixtures/sites/conditional-to-loop/collection.json index ccb4fcc..b568df7 100644 --- a/test/fixtures/sites/conditional-to-loop/collection.json +++ b/test/fixtures/sites/conditional-to-loop/collection.json @@ -6,10 +6,10 @@ "pathname": "a.html", "data": { "title": "Page A", - "nav": "Nav A", - "div_card": [ + "navigation": "Nav A", + "card": [ { - "div_card": "Card A" + "text": "Card A" } ] }, @@ -19,27 +19,27 @@ "pathname": "b.html", "data": { "title": "Page B", - "nav": "Nav B", - "div_card": [] + "navigation": "Nav B", + "card": [] }, "content": [] }, { "pathname": "c.html", "data": { - "div_items": [ + "items": [ { - "div_card": "Card C1" + "text": "Card C1" }, { - "div_card": "Card C2" + "text": "Card C2" }, { - "div_card": "Card C3" + "text": "Card C3" } ], "title": "Page C", - "nav": "Nav C" + "navigation": "Nav C" }, "content": [] } @@ -112,7 +112,7 @@ { "type": "variable", "reference": [ - "nav" + "navigation" ] } ] @@ -124,7 +124,7 @@ { "type": "loop", "reference": [ - "div_card" + "card" ], "template": { "type": "element", @@ -140,7 +140,7 @@ { "type": "variable", "reference": [ - "div_card" + "text" ] } ] diff --git a/test/fixtures/sites/four-pages-conditional/collection.json b/test/fixtures/sites/four-pages-conditional/collection.json index 320f2c0..3288488 100644 --- a/test/fixtures/sites/four-pages-conditional/collection.json +++ b/test/fixtures/sites/four-pages-conditional/collection.json @@ -5,8 +5,8 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", - "meta_description": null, + "inline_markdown": "About", + "meta": null, "title": "Test" }, "content": [] @@ -14,9 +14,9 @@ { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Contact", - "meta_description": { - "meta_description_content": "Fixed" + "inline_markdown": "Contact", + "meta": { + "description": "Fixed" }, "title": "Test" }, @@ -25,10 +25,10 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test", - "meta_description": { - "meta_description_content": "Home" + "meta": { + "description": "Home" } }, "content": [] @@ -36,10 +36,10 @@ { "pathname": "staff.html", "data": { - "h1_inline_markdown": "Staff", + "inline_markdown": "Staff", "title": "Staff | Test", - "meta_description": { - "meta_description_content": "Fixed" + "meta": { + "description": "Fixed" } }, "content": [] @@ -84,7 +84,7 @@ { "type": "conditional", "reference": [ - "meta_description" + "meta" ], "template": { "type": "element", @@ -99,7 +99,7 @@ "type": "variable-attribute", "name": "content", "reference": [ - "meta_description_content" + "description" ] } }, @@ -133,7 +133,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/loop-to-conditional/collection.json b/test/fixtures/sites/loop-to-conditional/collection.json index 6bf0947..826ed48 100644 --- a/test/fixtures/sites/loop-to-conditional/collection.json +++ b/test/fixtures/sites/loop-to-conditional/collection.json @@ -6,10 +6,10 @@ "pathname": "a.html", "data": { "title": "Page A", - "nav": "Nav A", - "div_items": [ + "navigation": "Nav A", + "items": [ { - "div_card": "Card A" + "text": "Card A" } ] }, @@ -18,19 +18,19 @@ { "pathname": "b.html", "data": { - "div_items": [ + "items": [ { - "div_card": "Card B1" + "text": "Card B1" }, { - "div_card": "Card B2" + "text": "Card B2" }, { - "div_card": "Card B3" + "text": "Card B3" } ], "title": "Page B", - "nav": "Nav B" + "navigation": "Nav B" }, "content": [] }, @@ -38,8 +38,8 @@ "pathname": "c.html", "data": { "title": "Page C", - "nav": "Nav C", - "div_card": [] + "navigation": "Nav C", + "card": [] }, "content": [] } @@ -112,7 +112,7 @@ { "type": "variable", "reference": [ - "nav" + "navigation" ] } ] @@ -124,7 +124,7 @@ { "type": "loop", "reference": [ - "div_card" + "card" ], "template": { "type": "element", @@ -140,7 +140,7 @@ { "type": "variable", "reference": [ - "div_card" + "text" ] } ] diff --git a/test/fixtures/sites/three-pages-attr-variable/collection.json b/test/fixtures/sites/three-pages-attr-variable/collection.json index 3256722..5cb1de6 100644 --- a/test/fixtures/sites/three-pages-attr-variable/collection.json +++ b/test/fixtures/sites/three-pages-attr-variable/collection.json @@ -6,7 +6,7 @@ "pathname": "about.html", "data": { "title": "Goose Admirer", - "img_alt": "Their goose" + "alt": "Their goose" }, "content": [] }, @@ -14,7 +14,7 @@ "pathname": "contact.html", "data": { "title": "Another Goose Admirer", - "img_alt": "Their goose" + "alt": "Their goose" }, "content": [] }, @@ -22,7 +22,7 @@ "pathname": "index.html", "data": { "title": "Goose Owner", - "img_alt": "Our goose" + "alt": "Our goose" }, "content": [] } @@ -91,7 +91,7 @@ "type": "variable-attribute", "name": "alt", "reference": [ - "img_alt" + "alt" ] } }, diff --git a/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json b/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json index 97ad50b..21f25bb 100644 --- a/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json +++ b/test/fixtures/sites/three-pages-conditional-alternative-order/collection.json @@ -5,10 +5,10 @@ { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Contact", + "inline_markdown": "Contact", "title": "Test", - "meta_description": { - "meta_description_content": "Fixed" + "meta": { + "description": "Fixed" } }, "content": [] @@ -16,10 +16,10 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test", - "meta_description": { - "meta_description_content": "Home" + "meta": { + "description": "Home" } }, "content": [] @@ -27,8 +27,8 @@ { "pathname": "zabout.html", "data": { - "h1_inline_markdown": "About", - "meta_description": null, + "inline_markdown": "About", + "meta": null, "title": "Test" }, "content": [] @@ -73,7 +73,7 @@ { "type": "conditional", "reference": [ - "meta_description" + "meta" ], "template": { "type": "element", @@ -88,7 +88,7 @@ "type": "variable-attribute", "name": "content", "reference": [ - "meta_description_content" + "description" ] } }, @@ -122,7 +122,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json b/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json index 236aa96..597e9b5 100644 --- a/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json +++ b/test/fixtures/sites/three-pages-conditional-loop-crash/collection.json @@ -5,21 +5,21 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "Beta", - "ul_items": [ + "inline_markdown": "Beta", + "items": [ { - "li": "Beta description", - "strong": null + "item": "Beta description", + "text": null }, { - "li": "", - "strong": { + "item": "", + "text": { "strong": "Beta closed" } }, { - "li": "Beta time", - "strong": null + "item": "Beta time", + "text": null } ], "title": "Beta | Test" @@ -29,16 +29,16 @@ { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Gamma", - "ul_items": [ + "inline_markdown": "Gamma", + "items": [ { - "li": "Gamma description" + "item": "Gamma description" }, { - "li": "Gamma open" + "item": "Gamma open" }, { - "li": "Gamma time" + "item": "Gamma time" } ], "title": "Gamma | Test" @@ -48,16 +48,16 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Alpha", - "ul_items": [ + "inline_markdown": "Alpha", + "items": [ { - "li": "Alpha description" + "item": "Alpha description" }, { - "li": "Alpha open" + "item": "Alpha open" }, { - "li": "Alpha time" + "item": "Alpha time" } ], "title": "Alpha | Test" @@ -124,7 +124,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] @@ -145,7 +145,7 @@ { "type": "loop", "reference": [ - "ul_items" + "items" ], "template": { "type": "element", @@ -174,13 +174,13 @@ { "type": "variable", "reference": [ - "li" + "item" ] }, { "type": "conditional", "reference": [ - "strong" + "text" ], "template": { "type": "element", diff --git a/test/fixtures/sites/three-pages-conditional/collection.json b/test/fixtures/sites/three-pages-conditional/collection.json index f2a800f..d856097 100644 --- a/test/fixtures/sites/three-pages-conditional/collection.json +++ b/test/fixtures/sites/three-pages-conditional/collection.json @@ -5,8 +5,8 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", - "meta_description": null, + "inline_markdown": "About", + "meta": null, "title": "Test" }, "content": [] @@ -14,9 +14,9 @@ { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Contact", - "meta_description": { - "meta_description_content": "Fixed" + "inline_markdown": "Contact", + "meta": { + "description": "Fixed" }, "title": "Test" }, @@ -25,10 +25,10 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test", - "meta_description": { - "meta_description_content": "Home" + "meta": { + "description": "Home" } }, "content": [] @@ -73,7 +73,7 @@ { "type": "conditional", "reference": [ - "meta_description" + "meta" ], "template": { "type": "element", @@ -88,7 +88,7 @@ "type": "variable-attribute", "name": "content", "reference": [ - "meta_description_content" + "description" ] } }, @@ -122,7 +122,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/three-pages-title-variable/collection.json b/test/fixtures/sites/three-pages-title-variable/collection.json index e311255..4613051 100644 --- a/test/fixtures/sites/three-pages-title-variable/collection.json +++ b/test/fixtures/sites/three-pages-title-variable/collection.json @@ -5,7 +5,7 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", + "inline_markdown": "About", "title": "Test" }, "content": [] @@ -13,7 +13,7 @@ { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Contact", + "inline_markdown": "Contact", "title": "Test" }, "content": [] @@ -21,7 +21,7 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test" }, "content": [] @@ -86,7 +86,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/three-pages/collection.json b/test/fixtures/sites/three-pages/collection.json index 44e026a..a7c0bbb 100644 --- a/test/fixtures/sites/three-pages/collection.json +++ b/test/fixtures/sites/three-pages/collection.json @@ -5,21 +5,21 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About" + "inline_markdown": "About" }, "content": [] }, { "pathname": "contact.html", "data": { - "h1_inline_markdown": "Contact" + "inline_markdown": "Contact" }, "content": [] }, { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home" + "inline_markdown": "Home" }, "content": [] } @@ -81,7 +81,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/two-pages-attr-variable/collection.json b/test/fixtures/sites/two-pages-attr-variable/collection.json index fb97258..bf8d28d 100644 --- a/test/fixtures/sites/two-pages-attr-variable/collection.json +++ b/test/fixtures/sites/two-pages-attr-variable/collection.json @@ -6,7 +6,7 @@ "pathname": "about.html", "data": { "title": "Goose Admirer", - "img_alt": "Their goose" + "alt": "Their goose" }, "content": [] }, @@ -14,7 +14,7 @@ "pathname": "index.html", "data": { "title": "Goose Owner", - "img_alt": "Our goose" + "alt": "Our goose" }, "content": [] } @@ -83,7 +83,7 @@ "type": "variable-attribute", "name": "alt", "reference": [ - "img_alt" + "alt" ] } }, diff --git a/test/fixtures/sites/two-pages-conditional-loop/collection.json b/test/fixtures/sites/two-pages-conditional-loop/collection.json index 9a9a425..dcbe2bb 100644 --- a/test/fixtures/sites/two-pages-conditional-loop/collection.json +++ b/test/fixtures/sites/two-pages-conditional-loop/collection.json @@ -8,13 +8,13 @@ "div": { "div_items": [ { - "div_markdown": "Lorem Ipsum 1\n\n![](https://placebear.com/250/50)" + "markdown": "Lorem Ipsum 1\n\n![](https://placebear.com/250/50)" }, { - "div_markdown": "Lorem Ipsum 2\n\n![](https://placebear.com/150/50)" + "markdown": "Lorem Ipsum 2\n\n![](https://placebear.com/150/50)" }, { - "div_markdown": "Lorem Ipsum 3\n\n![](https://placebear.com/50/50)" + "markdown": "Lorem Ipsum 3\n\n![](https://placebear.com/50/50)" } ] } @@ -109,7 +109,7 @@ { "type": "markdown-variable", "reference": [ - "div_markdown" + "markdown" ] }, { diff --git a/test/fixtures/sites/two-pages-conditional-object/collection.json b/test/fixtures/sites/two-pages-conditional-object/collection.json index e22edb8..89c37fc 100644 --- a/test/fixtures/sites/two-pages-conditional-object/collection.json +++ b/test/fixtures/sites/two-pages-conditional-object/collection.json @@ -5,7 +5,7 @@ { "pathname": "about.html", "data": { - "div_twoColumn": { + "twoColumn": { "div_twoColumn_left_markdown": "Lorem ipsum dolor sit amet", "div_twoColumn_right_markdown": "Etiam nibh metus, imperdiet eu eros vel, congue aliquet eros." } @@ -15,7 +15,7 @@ { "pathname": "index.html", "data": { - "div_twoColumn": null + "twoColumn": null }, "content": [] } @@ -72,7 +72,7 @@ { "type": "conditional", "reference": [ - "div_twoColumn" + "twoColumn" ], "template": { "type": "element", diff --git a/test/fixtures/sites/two-pages-conditional/collection.json b/test/fixtures/sites/two-pages-conditional/collection.json index 76942f2..1d534ea 100644 --- a/test/fixtures/sites/two-pages-conditional/collection.json +++ b/test/fixtures/sites/two-pages-conditional/collection.json @@ -5,18 +5,18 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", + "inline_markdown": "About", "title": "Test", - "meta_description": null + "meta": null }, "content": [] }, { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test", - "meta_description": {} + "meta": {} }, "content": [] } @@ -60,7 +60,7 @@ { "type": "conditional", "reference": [ - "meta_description" + "meta" ], "template": { "type": "element", @@ -107,7 +107,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/two-pages-loop/collection.json b/test/fixtures/sites/two-pages-loop/collection.json index 5918069..91a69ce 100644 --- a/test/fixtures/sites/two-pages-loop/collection.json +++ b/test/fixtures/sites/two-pages-loop/collection.json @@ -5,16 +5,16 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", - "div_items": [ + "inline_markdown": "About", + "items": [ { - "div_block": "About first item" + "text": "About first item" }, { - "div_block": "About second item" + "text": "About second item" }, { - "div_block": "About third item" + "text": "About third item" } ], "title": "About | Test" @@ -24,11 +24,11 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test", - "div_items": [ + "items": [ { - "div_block": "Home first item" + "text": "Home first item" } ] }, @@ -94,7 +94,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] @@ -115,7 +115,7 @@ { "type": "loop", "reference": [ - "div_items" + "items" ], "template": { "type": "element", @@ -131,7 +131,7 @@ { "type": "variable", "reference": [ - "div_block" + "text" ] } ] diff --git a/test/fixtures/sites/two-pages-markdown-variable/collection.json b/test/fixtures/sites/two-pages-markdown-variable/collection.json index 6fba54a..2599689 100644 --- a/test/fixtures/sites/two-pages-markdown-variable/collection.json +++ b/test/fixtures/sites/two-pages-markdown-variable/collection.json @@ -5,8 +5,8 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", - "div_markdown": "## About h2\n\nAbout p", + "inline_markdown": "About", + "markdown": "## About h2\n\nAbout p", "title": "About | Test" }, "content": [] @@ -14,8 +14,8 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", - "div_markdown": "## Home h2\n\nHome p", + "inline_markdown": "Home", + "markdown": "## Home h2\n\nHome p", "title": "Home | Test" }, "content": [] @@ -80,7 +80,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] @@ -101,7 +101,7 @@ { "type": "markdown-variable", "reference": [ - "div_markdown" + "markdown" ] }, { diff --git a/test/fixtures/sites/two-pages-not-loop/collection.json b/test/fixtures/sites/two-pages-not-loop/collection.json index d905957..07a8ba2 100644 --- a/test/fixtures/sites/two-pages-not-loop/collection.json +++ b/test/fixtures/sites/two-pages-not-loop/collection.json @@ -5,7 +5,7 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", + "inline_markdown": "About", "title": "About | Test" }, "content": [] @@ -13,7 +13,7 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test" }, "content": [] @@ -135,7 +135,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/two-pages-recursive-loop/collection.json b/test/fixtures/sites/two-pages-recursive-loop/collection.json index 539c577..6088511 100644 --- a/test/fixtures/sites/two-pages-recursive-loop/collection.json +++ b/test/fixtures/sites/two-pages-recursive-loop/collection.json @@ -5,25 +5,25 @@ { "pathname": "about.html", "data": { - "body_items": [ + "items": [ { - "div_first_class": "first", + "first_class": "first", "div_second_items": [ { - "p_test_inline_markdown": "Test 1" + "inline_markdown": "Test 1" } ] }, { "div_second_items": [ { - "p_test_inline_markdown": "Test 2" + "inline_markdown": "Test 2" }, { - "p_test_inline_markdown": "Test 3" + "inline_markdown": "Test 3" } ], - "div_first_class": "second" + "first_class": "second" } ] }, @@ -32,7 +32,7 @@ { "pathname": "index.html", "data": { - "body_items": [] + "items": [] }, "content": [] } @@ -93,7 +93,7 @@ { "type": "loop", "reference": [ - "body_items" + "items" ], "template": { "type": "element", @@ -103,7 +103,7 @@ "type": "variable-attribute", "name": "class", "reference": [ - "div_first_class" + "first_class" ] } }, @@ -131,7 +131,7 @@ { "type": "inline-markdown-variable", "reference": [ - "p_test_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/two-pages-title-variable/collection.json b/test/fixtures/sites/two-pages-title-variable/collection.json index eff1d23..43abb18 100644 --- a/test/fixtures/sites/two-pages-title-variable/collection.json +++ b/test/fixtures/sites/two-pages-title-variable/collection.json @@ -5,7 +5,7 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About", + "inline_markdown": "About", "title": "About | Test" }, "content": [] @@ -13,7 +13,7 @@ { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home", + "inline_markdown": "Home", "title": "Home | Test" }, "content": [] @@ -78,7 +78,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/fixtures/sites/two-pages/collection.json b/test/fixtures/sites/two-pages/collection.json index 3546616..bea0aaa 100644 --- a/test/fixtures/sites/two-pages/collection.json +++ b/test/fixtures/sites/two-pages/collection.json @@ -5,14 +5,14 @@ { "pathname": "about.html", "data": { - "h1_inline_markdown": "About" + "inline_markdown": "About" }, "content": [] }, { "pathname": "index.html", "data": { - "h1_inline_markdown": "Home" + "inline_markdown": "Home" }, "content": [] } @@ -74,7 +74,7 @@ { "type": "inline-markdown-variable", "reference": [ - "h1_inline_markdown" + "inline_markdown" ] } ] diff --git a/test/layout.ts b/test/layout.ts index 658129b..e01f1e5 100644 --- a/test/layout.ts +++ b/test/layout.ts @@ -24,14 +24,14 @@ async function runTest(testName: string) { ( await fs.promises.readFile(`./test/fixtures/layouts/${testName}/a-data.json`) ).toString('utf-8') - ) + ) : {}; const bDataContents = fs.existsSync(`./test/fixtures/layouts/${testName}/b-data.json`) ? JSON.parse( ( await fs.promises.readFile(`./test/fixtures/layouts/${testName}/b-data.json`) ).toString('utf-8') - ) + ) : {}; let aData = new Data([], structuredClone(aDataContents)); let bData = new Data([], structuredClone(bDataContents)); @@ -63,16 +63,16 @@ async function runTest(testName: string) { assert.deepStrictEqual(forwards, expected); const expectedAData = JSON.parse( - (await fs.promises.readFile(`./test/fixtures/layouts/${testName}/a-data-merged.json`)).toString( - 'utf-8' - ) + ( + await fs.promises.readFile(`./test/fixtures/layouts/${testName}/a-data-merged.json`) + ).toString('utf-8') ); assert.deepStrictEqual(aData.toJSON(), expectedAData); const expectedBData = JSON.parse( - (await fs.promises.readFile(`./test/fixtures/layouts/${testName}/b-data-merged.json`)).toString( - 'utf-8' - ) + ( + await fs.promises.readFile(`./test/fixtures/layouts/${testName}/b-data-merged.json`) + ).toString('utf-8') ); assert.deepStrictEqual(bData.toJSON(), expectedBData); @@ -81,10 +81,22 @@ async function runTest(testName: string) { bData = new Data([], structuredClone(bDataContents)); const backwards = merge(b, a, bData, aData); assert.deepStrictEqual(backwards, expected); - assert.deepStrictEqual(merge(backwards, a, bData, new Data([], structuredClone(aDataContents))), expected); - assert.deepStrictEqual(merge(backwards, b, bData, new Data([], structuredClone(bDataContents))), expected); - assert.deepStrictEqual(merge(forwards, a, bData, new Data([], structuredClone(aDataContents))), expected); - assert.deepStrictEqual(merge(forwards, b, bData, new Data([], structuredClone(bDataContents))), expected); + assert.deepStrictEqual( + merge(backwards, a, bData, new Data([], structuredClone(aDataContents))), + expected + ); + assert.deepStrictEqual( + merge(backwards, b, bData, new Data([], structuredClone(bDataContents))), + expected + ); + assert.deepStrictEqual( + merge(forwards, a, bData, new Data([], structuredClone(aDataContents))), + expected + ); + assert.deepStrictEqual( + merge(forwards, b, bData, new Data([], structuredClone(bDataContents))), + expected + ); assert.deepStrictEqual(merge(forwards, backwards, bData, aData), expected); assert.deepStrictEqual(merge(forwards, forwards, bData, aData), expected); assert.deepStrictEqual(merge(backwards, forwards, bData, aData), expected); diff --git a/test/node-equivalency.ts b/test/node-equivalency.ts index 7d3fc76..1109cc4 100644 --- a/test/node-equivalency.ts +++ b/test/node-equivalency.ts @@ -1,6 +1,10 @@ import { test } from 'node:test'; import * as assert from 'node:assert/strict'; -import { isBestMatch, nodeEquivalencyScore, loopThreshold } from '../src/helpers/node-equivalency.ts'; +import { + isBestMatch, + nodeEquivalencyScore, + loopThreshold +} from '../src/helpers/node-equivalency.ts'; import { ASTElementNode, ASTNode, ASTTextNode } from '../src/types.ts'; import { TestLogger } from './helpers/test-logger.ts'; diff --git a/tsconfig.json b/tsconfig.json index 370ff44..54f2c00 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,6 +5,8 @@ "moduleResolution": "nodenext", "rewriteRelativeImportExtensions": true, "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, "outDir": "./lib" }, "include": ["src"],