custom-rendrer 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Vite Plugin for Frontend Abstraction
3
+ * Injects build-time transformation rules and runtime bootstrap into the Vite development and production bundles.
4
+ */
5
+
6
+ export function frontendAbstractionVitePlugin(options = {}) {
7
+ const {
8
+ rules = [],
9
+ config = {},
10
+ injectRuntime = true,
11
+ autoStart = true,
12
+ } = options;
13
+
14
+ const virtualModuleId = 'virtual:frontend-abstraction';
15
+ const resolvedVirtualModuleId = '\0' + virtualModuleId;
16
+
17
+ return {
18
+ name: 'vite-plugin-frontend-abstraction',
19
+ enforce: 'pre',
20
+
21
+ resolveId(id) {
22
+ if (id === virtualModuleId) {
23
+ return resolvedVirtualModuleId;
24
+ }
25
+ return null;
26
+ },
27
+
28
+ load(id) {
29
+ if (id === resolvedVirtualModuleId) {
30
+ return `
31
+ import { initAbstractionRuntime, runtime } from 'custom-rendrer/runtime';
32
+ export const buildRules = ${JSON.stringify(rules)};
33
+ export const buildConfig = ${JSON.stringify(config)};
34
+
35
+ if (typeof window !== 'undefined') {
36
+ window.__ABSTRACTION_BUILD_RULES__ = buildRules;
37
+ if (${autoStart}) {
38
+ initAbstractionRuntime({ config: buildConfig, ...buildConfig });
39
+ }
40
+ }
41
+
42
+ export { runtime, initAbstractionRuntime };
43
+ export default runtime;
44
+ `.trim();
45
+ }
46
+ return null;
47
+ },
48
+
49
+ transformIndexHtml(html) {
50
+ const tags = [];
51
+
52
+ // 1. Inject build-time rules directly into HTML head
53
+ if (rules && rules.length > 0) {
54
+ tags.push({
55
+ tag: 'script',
56
+ attrs: { id: '__frontend-abstraction-rules__' },
57
+ children: `window.__ABSTRACTION_BUILD_RULES__ = ${JSON.stringify(rules)};`,
58
+ injectTo: 'head-prepend',
59
+ });
60
+ }
61
+
62
+ // 2. Optionally inject runtime auto-import if enabled
63
+ if (injectRuntime) {
64
+ tags.push({
65
+ tag: 'script',
66
+ attrs: {
67
+ type: 'module',
68
+ id: '__frontend-abstraction-runtime-init__',
69
+ },
70
+ children: `
71
+ import { initAbstractionRuntime } from 'custom-rendrer/runtime';
72
+ if (!window.__FRONTEND_ABSTRACTION__) {
73
+ initAbstractionRuntime(${JSON.stringify(config)});
74
+ }
75
+ `.trim(),
76
+ injectTo: 'head',
77
+ });
78
+ }
79
+
80
+ return {
81
+ html,
82
+ tags,
83
+ };
84
+ },
85
+ };
86
+ }
87
+
88
+ export default frontendAbstractionVitePlugin;
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Webpack Plugin for Frontend Abstraction
3
+ * Injects build-time transformation rules into Webpack bundles or HtmlWebpackPlugin output.
4
+ */
5
+
6
+ export class FrontendAbstractionWebpackPlugin {
7
+ constructor(options = {}) {
8
+ this.options = {
9
+ rules: [],
10
+ config: {},
11
+ injectRuntime: true,
12
+ autoStart: true,
13
+ ...options,
14
+ };
15
+ }
16
+
17
+ apply(compiler) {
18
+ const pluginName = 'FrontendAbstractionWebpackPlugin';
19
+ const { rules, config } = this.options;
20
+
21
+ // 1. Hook into Webpack compilation to define global constants if needed
22
+ compiler.hooks.compilation.tap(pluginName, (compilation) => {
23
+ // Check for HtmlWebpackPlugin hooks
24
+ const HtmlWebpackPlugin = compiler.options.plugins
25
+ ? compiler.options.plugins.find(
26
+ (p) => p && p.constructor && p.constructor.name === 'HtmlWebpackPlugin'
27
+ )
28
+ : null;
29
+
30
+ if (HtmlWebpackPlugin && compilation.hooks.htmlWebpackPluginAlterAssetTags) {
31
+ // HtmlWebpackPlugin 3.x
32
+ compilation.hooks.htmlWebpackPluginAlterAssetTags.tapAsync(
33
+ pluginName,
34
+ (data, cb) => {
35
+ const ruleScript = {
36
+ tagName: 'script',
37
+ closeTag: true,
38
+ innerHTML: `window.__ABSTRACTION_BUILD_RULES__ = ${JSON.stringify(rules)};`,
39
+ };
40
+ data.head.unshift(ruleScript);
41
+ cb(null, data);
42
+ }
43
+ );
44
+ } else {
45
+ // HtmlWebpackPlugin 4+ / 5+ hook via compilation.hooks
46
+ const hooks = compilation.constructor && compilation.constructor.getHtmlWebpackPluginHooks
47
+ ? compilation.constructor.getHtmlWebpackPluginHooks(compilation)
48
+ : null;
49
+
50
+ if (hooks && hooks.alterAssetTags) {
51
+ hooks.alterAssetTags.tapAsync(pluginName, (data, cb) => {
52
+ data.assetTags.scripts.unshift({
53
+ tagName: 'script',
54
+ voidTag: false,
55
+ attributes: { type: 'text/javascript' },
56
+ innerHTML: `window.__ABSTRACTION_BUILD_RULES__ = ${JSON.stringify(rules)};`,
57
+ });
58
+ cb(null, data);
59
+ });
60
+ }
61
+ }
62
+ });
63
+
64
+ // 2. Define global fallback in compiler options
65
+ if (compiler.options.plugins) {
66
+ // Injects banner or define constant
67
+ const rulesJson = JSON.stringify(rules);
68
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
69
+ compilation.hooks.processAssets &&
70
+ compilation.hooks.processAssets.tap(
71
+ {
72
+ name: pluginName,
73
+ stage: compilation.PROCESS_ASSETS_STAGE_ADDITIONAL || 0,
74
+ },
75
+ () => {}
76
+ );
77
+ });
78
+ }
79
+ }
80
+ }
81
+
82
+ export default FrontendAbstractionWebpackPlugin;
@@ -0,0 +1,72 @@
1
+ import { VisualLayer } from './visual-layer.js';
2
+
3
+ /**
4
+ * ElementManager
5
+ * Tracks, inspects, and manages the lifecycle of abstracted elements in the DOM.
6
+ */
7
+ export class ElementManager {
8
+ constructor(visualLayer = null) {
9
+ this.visualLayer = visualLayer || new VisualLayer();
10
+ this.managedElements = new Set();
11
+ }
12
+
13
+ /**
14
+ * Registers and decorates an element.
15
+ */
16
+ registerElement(element, originalValue, displayValue) {
17
+ if (!element) return;
18
+ this.visualLayer.applyVisual(element, originalValue, displayValue);
19
+ this.managedElements.add(element);
20
+ }
21
+
22
+ /**
23
+ * Unregisters and removes decoration from an element.
24
+ */
25
+ unregisterElement(element) {
26
+ if (!element) return;
27
+ this.visualLayer.removeVisual(element);
28
+ this.managedElements.delete(element);
29
+ }
30
+
31
+ /**
32
+ * Cleans up elements no longer connected to the DOM.
33
+ */
34
+ pruneDisconnected() {
35
+ for (const el of this.managedElements) {
36
+ if (el.isConnected === false) {
37
+ this.managedElements.delete(el);
38
+ }
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Clears all managed elements.
44
+ */
45
+ clearAll() {
46
+ for (const el of this.managedElements) {
47
+ this.visualLayer.removeVisual(el);
48
+ }
49
+ this.managedElements.clear();
50
+ }
51
+
52
+ /**
53
+ * Finds an abstracted element by original or display value.
54
+ */
55
+ findByOriginal(value) {
56
+ for (const el of this.managedElements) {
57
+ if (this.visualLayer.getOriginalValue(el) === String(value)) {
58
+ return el;
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+
64
+ findByDisplay(value) {
65
+ for (const el of this.managedElements) {
66
+ if (this.visualLayer.getDisplayValue(el) === String(value)) {
67
+ return el;
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+ }
@@ -0,0 +1,130 @@
1
+ import { engine } from '../core/engine.js';
2
+ import { VisualLayer } from './visual-layer.js';
3
+ import { ElementManager } from './element-manager.js';
4
+ import { isExcludedElement } from '../rules/exclusions.js';
5
+
6
+ /**
7
+ * AbstractionRenderer
8
+ * Scans DOM elements, queries engine transformations, and applies visual representations
9
+ * while guaranteeing underlying DOM text values remain 100% untouched.
10
+ */
11
+ export class AbstractionRenderer {
12
+ constructor(options = {}) {
13
+ this.engine = options.engine || engine;
14
+ this.visualLayer = options.visualLayer || new VisualLayer();
15
+ this.elementManager = options.elementManager || new ElementManager(this.visualLayer);
16
+ }
17
+
18
+ /**
19
+ * Processes a single DOM element.
20
+ * If its text matches a transformation rule and it is not excluded,
21
+ * decorates it with the visual presentation layer without modifying text nodes.
22
+ */
23
+ processElement(element, contextOptions = {}) {
24
+ if (!element || element.nodeType !== 1) return false;
25
+
26
+ // Check exclusion
27
+ if (this.engine.isExcluded(element, contextOptions)) {
28
+ return false;
29
+ }
30
+
31
+ // Inspect direct text content
32
+ const originalText = element.textContent ? element.textContent.trim() : '';
33
+ if (!originalText) {
34
+ if (this.visualLayer.isAbstracted(element)) {
35
+ this.elementManager.unregisterElement(element);
36
+ }
37
+ return false;
38
+ }
39
+
40
+ const context = this.engine.createContext({
41
+ elementType: element.tagName.toLowerCase(),
42
+ attributes: this._getElementAttributes(element),
43
+ ...contextOptions,
44
+ });
45
+
46
+ const displayValue = this.engine.transformText(originalText, context);
47
+
48
+ if (displayValue !== originalText) {
49
+ // Check if element is a styled container (e.g. has className, or is a heading/button/div/p/td/th)
50
+ const isStyledContainer = (element.className && String(element.className).trim() !== '' && !element.classList.contains('abstracted-visual-node')) || element.tagName !== 'SPAN';
51
+
52
+ if (isStyledContainer && (element.ownerDocument || (typeof document !== 'undefined' ? document : null))) {
53
+ const doc = element.ownerDocument || document;
54
+ // Wrap text node in an inner visual span to preserve outer background, padding, border, and layout styles
55
+ let innerSpan = Array.from(element.children || []).find(c => c.classList && c.classList.contains('abstracted-visual-node'));
56
+ if (!innerSpan) {
57
+ innerSpan = doc.createElement('span');
58
+ this.visualLayer.applyVisual(innerSpan, originalText, displayValue);
59
+ while (element.firstChild) {
60
+ innerSpan.appendChild(element.firstChild);
61
+ }
62
+ element.appendChild(innerSpan);
63
+ this.elementManager.registerElement(innerSpan, originalText, displayValue);
64
+ return true;
65
+ } else {
66
+ this.visualLayer.applyVisual(innerSpan, originalText, displayValue);
67
+ this.elementManager.registerElement(innerSpan, originalText, displayValue);
68
+ return true;
69
+ }
70
+ }
71
+
72
+ // Plain unstyled span: register element directly
73
+ this.elementManager.registerElement(element, originalText, displayValue);
74
+ return true;
75
+ } else if (this.visualLayer.isAbstracted(element)) {
76
+ // Element was updated (e.g. React re-render) to a non-abstracted value
77
+ this.elementManager.unregisterElement(element);
78
+ return false;
79
+ }
80
+
81
+ return false;
82
+ }
83
+
84
+ /**
85
+ * Recursively scans and renders a DOM subtree.
86
+ */
87
+ scanAndRender(rootNode, contextOptions = {}) {
88
+ if (!rootNode) return;
89
+
90
+ if (rootNode.nodeType === 1) {
91
+ // If root element has only text children (leaf text node)
92
+ const hasOnlyTextChildren = Array.from(rootNode.childNodes).every(
93
+ node => node.nodeType === 3 || node.nodeType === 8
94
+ );
95
+
96
+ if (hasOnlyTextChildren && rootNode.textContent && rootNode.textContent.trim()) {
97
+ this.processElement(rootNode, contextOptions);
98
+ } else {
99
+ // Recurse down children
100
+ for (const child of rootNode.children) {
101
+ this.scanAndRender(child, contextOptions);
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Cleans up all visual layers inside rootNode.
109
+ */
110
+ unrender(rootNode) {
111
+ if (!rootNode) return;
112
+ if (rootNode.nodeType === 1 && this.visualLayer.isAbstracted(rootNode)) {
113
+ this.elementManager.unregisterElement(rootNode);
114
+ }
115
+ for (const child of rootNode.children || []) {
116
+ this.unrender(child);
117
+ }
118
+ }
119
+
120
+ _getElementAttributes(element) {
121
+ const attrs = {};
122
+ if (element.attributes) {
123
+ for (let i = 0; i < element.attributes.length; i++) {
124
+ const attr = element.attributes[i];
125
+ attrs[attr.name] = attr.value;
126
+ }
127
+ }
128
+ return attrs;
129
+ }
130
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * VisualLayer
3
+ * Implements presentation transformation without mutating underlying DOM text nodes.
4
+ * Uses CSS attribute-driven pseudo-elements to visually render display values while
5
+ * keeping textContent and child text nodes strictly equal to their original values.
6
+ */
7
+
8
+ export const VISUAL_CLASS_NAME = 'abstracted-visual-node';
9
+ export const ORIGINAL_ATTR = 'data-abstract-original';
10
+ export const DISPLAY_ATTR = 'data-abstract-display';
11
+
12
+ export const VISUAL_STYLES = `
13
+ .${VISUAL_CLASS_NAME} {
14
+ position: relative !important;
15
+ display: inline !important;
16
+ visibility: hidden !important;
17
+ user-select: text !important;
18
+ padding: 0 !important;
19
+ margin: 0 !important;
20
+ border: none !important;
21
+ background: transparent !important;
22
+ box-shadow: none !important;
23
+ vertical-align: baseline !important;
24
+ }
25
+
26
+ .${VISUAL_CLASS_NAME}::after {
27
+ content: attr(${DISPLAY_ATTR}) !important;
28
+ visibility: visible !important;
29
+ position: absolute !important;
30
+ left: 0 !important;
31
+ top: 0 !important;
32
+ color: inherit !important;
33
+ font-family: inherit !important;
34
+ font-size: inherit !important;
35
+ font-weight: inherit !important;
36
+ font-style: inherit !important;
37
+ letter-spacing: inherit !important;
38
+ line-height: inherit !important;
39
+ text-decoration: inherit !important;
40
+ text-transform: inherit !important;
41
+ white-space: pre !important;
42
+ pointer-events: none !important;
43
+ }
44
+ `;
45
+
46
+ export class VisualLayer {
47
+ constructor(documentInstance = null) {
48
+ this.document = documentInstance || (typeof document !== 'undefined' ? document : null);
49
+ this._styleElement = null;
50
+ this.injected = false;
51
+ }
52
+
53
+ /**
54
+ * Injects the visual abstraction stylesheet into document head.
55
+ */
56
+ injectStyles() {
57
+ if (!this.document || this.injected) return;
58
+
59
+ const existing = this.document.getElementById('frontend-abstraction-styles');
60
+ if (existing) {
61
+ this._styleElement = existing;
62
+ this.injected = true;
63
+ return;
64
+ }
65
+
66
+ const style = this.document.createElement('style');
67
+ style.id = 'frontend-abstraction-styles';
68
+ style.textContent = VISUAL_STYLES;
69
+ (this.document.head || this.document.documentElement).appendChild(style);
70
+ this._styleElement = style;
71
+ this.injected = true;
72
+ }
73
+
74
+ /**
75
+ * Applies the visual representation to an element WITHOUT mutating its text nodes.
76
+ * @param {HTMLElement} element
77
+ * @param {string} originalValue
78
+ * @param {string} displayValue
79
+ */
80
+ applyVisual(element, originalValue, displayValue) {
81
+ if (!element) return;
82
+ this.injectStyles();
83
+
84
+ element.setAttribute(ORIGINAL_ATTR, originalValue);
85
+ element.setAttribute(DISPLAY_ATTR, displayValue);
86
+
87
+ if (element.classList && !element.classList.contains(VISUAL_CLASS_NAME)) {
88
+ element.classList.add(VISUAL_CLASS_NAME);
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Removes visual representation from an element.
94
+ * @param {HTMLElement} element
95
+ */
96
+ removeVisual(element) {
97
+ if (!element) return;
98
+ element.removeAttribute(ORIGINAL_ATTR);
99
+ element.removeAttribute(DISPLAY_ATTR);
100
+ if (element.classList) {
101
+ element.classList.remove(VISUAL_CLASS_NAME);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Checks if an element has active visual abstraction.
107
+ */
108
+ isAbstracted(element) {
109
+ return Boolean(element && element.hasAttribute && element.hasAttribute(DISPLAY_ATTR));
110
+ }
111
+
112
+ /**
113
+ * Gets the display value of an abstracted element.
114
+ */
115
+ getDisplayValue(element) {
116
+ return element?.getAttribute ? element.getAttribute(DISPLAY_ATTR) : null;
117
+ }
118
+
119
+ /**
120
+ * Gets the original value of an abstracted element.
121
+ */
122
+ getOriginalValue(element) {
123
+ return element?.getAttribute ? element.getAttribute(ORIGINAL_ATTR) : null;
124
+ }
125
+ }
@@ -0,0 +1,55 @@
1
+ import { DEFAULT_MAPPINGS } from './mappings.js';
2
+
3
+ export const DEFAULT_CONFIG = {
4
+ enabled: true,
5
+ visualStrategy: 'css-pseudo',
6
+ excludeInputs: true,
7
+ preserveDomText: true,
8
+ debug: false,
9
+ customExclusions: [],
10
+ mappings: [...DEFAULT_MAPPINGS],
11
+ };
12
+
13
+ export class ConfigurationManager {
14
+ constructor(initialOptions = {}) {
15
+ this._config = {
16
+ ...DEFAULT_CONFIG,
17
+ ...initialOptions,
18
+ mappings: Array.isArray(initialOptions.mappings)
19
+ ? [...initialOptions.mappings]
20
+ : [...DEFAULT_CONFIG.mappings],
21
+ };
22
+ }
23
+
24
+ get(key) {
25
+ return this._config[key];
26
+ }
27
+
28
+ set(key, value) {
29
+ this._config[key] = value;
30
+ }
31
+
32
+ update(options = {}) {
33
+ this._config = {
34
+ ...this._config,
35
+ ...options,
36
+ };
37
+ return this.getAll();
38
+ }
39
+
40
+ getAll() {
41
+ return { ...this._config };
42
+ }
43
+
44
+ isEnabled() {
45
+ return Boolean(this._config.enabled);
46
+ }
47
+
48
+ shouldExcludeInputs() {
49
+ return Boolean(this._config.excludeInputs);
50
+ }
51
+
52
+ shouldPreserveDomText() {
53
+ return Boolean(this._config.preserveDomText);
54
+ }
55
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Exclusion Rules
3
+ * Defines elements, attributes, classes, and patterns that are excluded from abstraction.
4
+ */
5
+
6
+ export const DEFAULT_EXCLUDED_TAGS = new Set([
7
+ 'input',
8
+ 'textarea',
9
+ 'select',
10
+ 'option',
11
+ 'script',
12
+ 'style',
13
+ 'code',
14
+ 'pre',
15
+ 'svg',
16
+ 'canvas',
17
+ 'noscript',
18
+ 'iframe',
19
+ 'template',
20
+ ]);
21
+
22
+ export const DEFAULT_EXCLUDED_ATTRIBUTES = [
23
+ 'data-no-abstract',
24
+ 'data-raw',
25
+ 'data-skip-abstraction',
26
+ ];
27
+
28
+ export const DEFAULT_EXCLUDED_CLASSES = [
29
+ 'no-abstract',
30
+ 'raw-display',
31
+ 'skip-abstraction',
32
+ ];
33
+
34
+ /**
35
+ * Checks whether an element or node is excluded from abstraction.
36
+ * @param {HTMLElement|Object} element
37
+ * @param {Object} options
38
+ * @returns {boolean}
39
+ */
40
+ export function isExcludedElement(element, options = {}) {
41
+ if (!element) return false;
42
+
43
+ const excludedTags = options.excludedTags || DEFAULT_EXCLUDED_TAGS;
44
+ const tagName = (element.tagName || element.elementType || '').toLowerCase();
45
+
46
+ if (tagName && excludedTags.has(tagName)) {
47
+ return true;
48
+ }
49
+
50
+ // Check editable elements
51
+ if (element.isContentEditable) {
52
+ return true;
53
+ }
54
+
55
+ // Check attributes
56
+ if (typeof element.hasAttribute === 'function') {
57
+ for (const attr of DEFAULT_EXCLUDED_ATTRIBUTES) {
58
+ if (element.hasAttribute(attr)) return true;
59
+ }
60
+ } else if (element.attributes) {
61
+ for (const attr of DEFAULT_EXCLUDED_ATTRIBUTES) {
62
+ if (element.attributes[attr] !== undefined) return true;
63
+ }
64
+ }
65
+
66
+ // Check classes
67
+ if (element.classList && typeof element.classList.contains === 'function') {
68
+ for (const cls of DEFAULT_EXCLUDED_CLASSES) {
69
+ if (element.classList.contains(cls)) return true;
70
+ }
71
+ } else if (typeof element.className === 'string') {
72
+ for (const cls of DEFAULT_EXCLUDED_CLASSES) {
73
+ if (element.className.split(/\s+/).includes(cls)) return true;
74
+ }
75
+ }
76
+
77
+ return false;
78
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Default Mappings
3
+ * Empty by default. Define user mappings via plugin options, config, or runtime.
4
+ */
5
+ export const DEFAULT_MAPPINGS = [];
6
+
7
+ /**
8
+ * Validates a mapping rule specification.
9
+ */
10
+ export function validateMappingRule(rule) {
11
+ if (!rule || typeof rule !== 'object') {
12
+ throw new Error('Mapping rule must be an object');
13
+ }
14
+
15
+ if (rule.original === undefined && !rule.matcher) {
16
+ throw new Error('Mapping rule requires "original" or "matcher" property');
17
+ }
18
+
19
+ if (rule.display === undefined && !rule.toDisplay && !rule.toDisplayFn) {
20
+ throw new Error('Mapping rule requires "display" or "toDisplay" function');
21
+ }
22
+
23
+ return true;
24
+ }