@knighted/jsx 1.1.0 → 1.2.0-rc.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,138 @@
1
+ import { parseSync } from 'oxc-parser';
2
+ import { buildTemplate, evaluateExpression, extractRootNode, formatParserError, getIdentifierName, normalizeJsxText, parserOptions, } from '../runtime/shared.js';
3
+ import { Fragment, createElement, } from 'react';
4
+ const isIterable = (value) => {
5
+ if (!value || typeof value === 'string') {
6
+ return false;
7
+ }
8
+ return typeof value[Symbol.iterator] === 'function';
9
+ };
10
+ const isPromiseLike = (value) => {
11
+ if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
12
+ return false;
13
+ }
14
+ return typeof value.then === 'function';
15
+ };
16
+ const appendReactChild = (bucket, value) => {
17
+ if (value === null || value === undefined) {
18
+ return;
19
+ }
20
+ if (typeof value === 'boolean') {
21
+ return;
22
+ }
23
+ if (isPromiseLike(value)) {
24
+ throw new Error('Async values are not supported inside reactJsx template results.');
25
+ }
26
+ if (Array.isArray(value)) {
27
+ value.forEach(entry => appendReactChild(bucket, entry));
28
+ return;
29
+ }
30
+ if (isIterable(value)) {
31
+ for (const entry of value) {
32
+ appendReactChild(bucket, entry);
33
+ }
34
+ return;
35
+ }
36
+ bucket.push(value);
37
+ };
38
+ const evaluateExpressionForReact = (expression, ctx) => evaluateExpression(expression, ctx, node => evaluateReactJsxNode(node, ctx));
39
+ const resolveAttributes = (attributes, ctx) => {
40
+ const props = {};
41
+ attributes.forEach(attribute => {
42
+ if (attribute.type === 'JSXSpreadAttribute') {
43
+ const spreadValue = evaluateExpressionForReact(attribute.argument, ctx);
44
+ if (spreadValue && typeof spreadValue === 'object' && !Array.isArray(spreadValue)) {
45
+ Object.assign(props, spreadValue);
46
+ }
47
+ return;
48
+ }
49
+ const name = getIdentifierName(attribute.name);
50
+ if (!attribute.value) {
51
+ props[name] = true;
52
+ return;
53
+ }
54
+ if (attribute.value.type === 'Literal') {
55
+ props[name] = attribute.value.value;
56
+ return;
57
+ }
58
+ if (attribute.value.type === 'JSXExpressionContainer') {
59
+ if (attribute.value.expression.type === 'JSXEmptyExpression') {
60
+ return;
61
+ }
62
+ props[name] = evaluateExpressionForReact(attribute.value.expression, ctx);
63
+ }
64
+ });
65
+ return props;
66
+ };
67
+ const evaluateReactJsxChildren = (children, ctx) => {
68
+ const resolved = [];
69
+ children.forEach(child => {
70
+ switch (child.type) {
71
+ case 'JSXText': {
72
+ const text = normalizeJsxText(child.value);
73
+ if (text) {
74
+ resolved.push(text);
75
+ }
76
+ break;
77
+ }
78
+ case 'JSXExpressionContainer': {
79
+ if (child.expression.type === 'JSXEmptyExpression') {
80
+ break;
81
+ }
82
+ appendReactChild(resolved, evaluateExpressionForReact(child.expression, ctx));
83
+ break;
84
+ }
85
+ case 'JSXSpreadChild': {
86
+ const spreadValue = evaluateExpressionForReact(child.expression, ctx);
87
+ if (spreadValue !== undefined && spreadValue !== null) {
88
+ appendReactChild(resolved, spreadValue);
89
+ }
90
+ break;
91
+ }
92
+ case 'JSXElement':
93
+ case 'JSXFragment': {
94
+ resolved.push(evaluateReactJsxNode(child, ctx));
95
+ break;
96
+ }
97
+ }
98
+ });
99
+ return resolved;
100
+ };
101
+ const createReactElement = (type, props, children) => {
102
+ return createElement(type, props, ...children);
103
+ };
104
+ const evaluateReactJsxElement = (element, ctx) => {
105
+ const opening = element.openingElement;
106
+ const tagName = getIdentifierName(opening.name);
107
+ const component = ctx.components.get(tagName);
108
+ const props = resolveAttributes(opening.attributes, ctx);
109
+ const childValues = evaluateReactJsxChildren(element.children, ctx);
110
+ if (component) {
111
+ return createReactElement(component, props, childValues);
112
+ }
113
+ if (/[A-Z]/.test(tagName[0] ?? '')) {
114
+ throw new Error(`Unknown component "${tagName}". Did you interpolate it with the template literal?`);
115
+ }
116
+ return createReactElement(tagName, props, childValues);
117
+ };
118
+ const evaluateReactJsxNode = (node, ctx) => {
119
+ if (node.type === 'JSXFragment') {
120
+ const children = evaluateReactJsxChildren(node.children, ctx);
121
+ return createElement(Fragment, null, ...children);
122
+ }
123
+ return evaluateReactJsxElement(node, ctx);
124
+ };
125
+ export const reactJsx = (templates, ...values) => {
126
+ const build = buildTemplate(templates, values);
127
+ const result = parseSync('inline.jsx', build.source, parserOptions);
128
+ if (result.errors.length > 0) {
129
+ throw new Error(formatParserError(result.errors[0]));
130
+ }
131
+ const root = extractRootNode(result.program);
132
+ const ctx = {
133
+ source: build.source,
134
+ placeholders: build.placeholders,
135
+ components: new Map(build.bindings.map(binding => [binding.name, binding.value])),
136
+ };
137
+ return evaluateReactJsxNode(root, ctx);
138
+ };
@@ -0,0 +1,38 @@
1
+ import type { Expression, JSXElement, JSXFragment, JSXIdentifier, JSXMemberExpression, JSXNamespacedName, Program } from '@oxc-project/types';
2
+ import type { OxcError, ParserOptions } from 'oxc-parser';
3
+ type AnyTemplateFunction = (...args: any[]) => unknown;
4
+ type AnyTemplateConstructor = abstract new (...args: any[]) => unknown;
5
+ export type TemplateComponent = (AnyTemplateFunction | AnyTemplateConstructor) & {
6
+ displayName?: string;
7
+ name?: string;
8
+ };
9
+ export type BindingEntry<TComponent extends TemplateComponent> = {
10
+ name: string;
11
+ value: TComponent;
12
+ };
13
+ export type TemplateBuildResult<TComponent extends TemplateComponent> = {
14
+ source: string;
15
+ placeholders: Map<string, unknown>;
16
+ bindings: BindingEntry<TComponent>[];
17
+ };
18
+ export type TemplateContext<TComponent extends TemplateComponent> = {
19
+ source: string;
20
+ placeholders: Map<string, unknown>;
21
+ components: Map<string, TComponent>;
22
+ };
23
+ export declare const parserOptions: ParserOptions;
24
+ export declare const formatParserError: (error: OxcError) => string;
25
+ export declare const extractRootNode: (program: Program) => JSXElement | JSXFragment;
26
+ export declare const getIdentifierName: (identifier: JSXIdentifier | JSXNamespacedName | JSXMemberExpression) => string;
27
+ type AnyOxcNode = {
28
+ type: string;
29
+ [key: string]: unknown;
30
+ };
31
+ export declare const walkAst: (node: unknown, visitor: (target: AnyOxcNode) => void) => void;
32
+ export declare const normalizeJsxText: (value: string) => string;
33
+ export declare const collectPlaceholderNames: <TComponent extends TemplateComponent>(expression: Expression | JSXElement | JSXFragment, ctx: TemplateContext<TComponent>) => string[];
34
+ export declare const evaluateExpression: <TComponent extends TemplateComponent>(expression: Expression | JSXElement | JSXFragment, ctx: TemplateContext<TComponent>, evaluateJsxNode: (node: JSXElement | JSXFragment) => unknown) => unknown;
35
+ export declare const sanitizeIdentifier: (value: string) => string;
36
+ export declare const ensureBinding: <TComponent extends TemplateComponent>(value: TComponent, bindings: BindingEntry<TComponent>[], bindingLookup: Map<TComponent, BindingEntry<TComponent>>) => BindingEntry<TComponent>;
37
+ export declare const buildTemplate: <TComponent extends TemplateComponent>(strings: TemplateStringsArray, values: unknown[]) => TemplateBuildResult<TComponent>;
38
+ export {};
@@ -0,0 +1,156 @@
1
+ const OPEN_TAG_RE = /<\s*$/;
2
+ const CLOSE_TAG_RE = /<\/\s*$/;
3
+ const PLACEHOLDER_PREFIX = '__KX_EXPR__';
4
+ let invocationCounter = 0;
5
+ export const parserOptions = {
6
+ lang: 'jsx',
7
+ sourceType: 'module',
8
+ range: true,
9
+ preserveParens: true,
10
+ };
11
+ export const formatParserError = (error) => {
12
+ let message = `[oxc-parser] ${error.message}`;
13
+ if (error.labels?.length) {
14
+ const label = error.labels[0];
15
+ if (label.message) {
16
+ message += `\n${label.message}`;
17
+ }
18
+ }
19
+ if (error.codeframe) {
20
+ message += `\n${error.codeframe}`;
21
+ }
22
+ return message;
23
+ };
24
+ export const extractRootNode = (program) => {
25
+ for (const statement of program.body) {
26
+ if (statement.type === 'ExpressionStatement') {
27
+ const expression = statement.expression;
28
+ if (expression.type === 'JSXElement' || expression.type === 'JSXFragment') {
29
+ return expression;
30
+ }
31
+ }
32
+ }
33
+ throw new Error('The jsx template must contain a single JSX element or fragment.');
34
+ };
35
+ export const getIdentifierName = (identifier) => {
36
+ switch (identifier.type) {
37
+ case 'JSXIdentifier':
38
+ return identifier.name;
39
+ case 'JSXNamespacedName':
40
+ return `${identifier.namespace.name}:${identifier.name.name}`;
41
+ case 'JSXMemberExpression':
42
+ return `${getIdentifierName(identifier.object)}.${identifier.property.name}`;
43
+ default:
44
+ return '';
45
+ }
46
+ };
47
+ export const walkAst = (node, visitor) => {
48
+ if (!node || typeof node !== 'object') {
49
+ return;
50
+ }
51
+ const candidate = node;
52
+ if (typeof candidate.type !== 'string') {
53
+ return;
54
+ }
55
+ visitor(candidate);
56
+ Object.values(candidate).forEach(value => {
57
+ if (!value) {
58
+ return;
59
+ }
60
+ if (Array.isArray(value)) {
61
+ value.forEach(child => walkAst(child, visitor));
62
+ return;
63
+ }
64
+ if (typeof value === 'object') {
65
+ walkAst(value, visitor);
66
+ }
67
+ });
68
+ };
69
+ export const normalizeJsxText = (value) => {
70
+ const collapsed = value.replace(/\r/g, '').replace(/\n\s+/g, ' ');
71
+ const trimmed = collapsed.trim();
72
+ return trimmed.length > 0 ? trimmed : '';
73
+ };
74
+ export const collectPlaceholderNames = (expression, ctx) => {
75
+ const placeholders = new Set();
76
+ walkAst(expression, node => {
77
+ if (node.type === 'Identifier' && ctx.placeholders.has(node.name)) {
78
+ placeholders.add(node.name);
79
+ }
80
+ });
81
+ return Array.from(placeholders);
82
+ };
83
+ export const evaluateExpression = (expression, ctx, evaluateJsxNode) => {
84
+ if (expression.type === 'JSXElement' || expression.type === 'JSXFragment') {
85
+ return evaluateJsxNode(expression);
86
+ }
87
+ if (!('range' in expression) || !expression.range) {
88
+ throw new Error('Unable to evaluate expression: missing source range information.');
89
+ }
90
+ const [start, end] = expression.range;
91
+ const source = ctx.source.slice(start, end);
92
+ const placeholders = collectPlaceholderNames(expression, ctx);
93
+ try {
94
+ const evaluator = new Function(...placeholders, `"use strict"; return (${source});`);
95
+ const args = placeholders.map(name => ctx.placeholders.get(name));
96
+ return evaluator(...args);
97
+ }
98
+ catch (error) {
99
+ throw new Error(`Failed to evaluate expression ${source}: ${error.message}`);
100
+ }
101
+ };
102
+ export const sanitizeIdentifier = (value) => {
103
+ const cleaned = value.replace(/[^a-zA-Z0-9_$]/g, '');
104
+ if (!cleaned) {
105
+ return 'Component';
106
+ }
107
+ if (!/[A-Za-z_$]/.test(cleaned[0])) {
108
+ return `Component${cleaned}`;
109
+ }
110
+ return cleaned;
111
+ };
112
+ export const ensureBinding = (value, bindings, bindingLookup) => {
113
+ const existing = bindingLookup.get(value);
114
+ if (existing) {
115
+ return existing;
116
+ }
117
+ const descriptor = value.displayName || value.name || `Component${bindings.length}`;
118
+ const baseName = sanitizeIdentifier(descriptor ?? '');
119
+ let candidate = baseName;
120
+ let suffix = 1;
121
+ while (bindings.some(binding => binding.name === candidate)) {
122
+ candidate = `${baseName}${suffix++}`;
123
+ }
124
+ const binding = { name: candidate, value };
125
+ bindings.push(binding);
126
+ bindingLookup.set(value, binding);
127
+ return binding;
128
+ };
129
+ export const buildTemplate = (strings, values) => {
130
+ const raw = strings.raw ?? strings;
131
+ const placeholders = new Map();
132
+ const bindings = [];
133
+ const bindingLookup = new Map();
134
+ let source = raw[0] ?? '';
135
+ const templateId = invocationCounter++;
136
+ let placeholderIndex = 0;
137
+ for (let idx = 0; idx < values.length; idx++) {
138
+ const chunk = raw[idx] ?? '';
139
+ const nextChunk = raw[idx + 1] ?? '';
140
+ const value = values[idx];
141
+ const isTagNamePosition = OPEN_TAG_RE.test(chunk) || CLOSE_TAG_RE.test(chunk);
142
+ if (isTagNamePosition && typeof value === 'function') {
143
+ const binding = ensureBinding(value, bindings, bindingLookup);
144
+ source += binding.name + nextChunk;
145
+ continue;
146
+ }
147
+ if (isTagNamePosition && typeof value === 'string') {
148
+ source += value + nextChunk;
149
+ continue;
150
+ }
151
+ const placeholder = `${PLACEHOLDER_PREFIX}${templateId}_${placeholderIndex++}__`;
152
+ placeholders.set(placeholder, value);
153
+ source += placeholder + nextChunk;
154
+ }
155
+ return { source, placeholders, bindings };
156
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knighted/jsx",
3
- "version": "1.1.0",
3
+ "version": "1.2.0-rc.0",
4
4
  "description": "A simple JSX transpiler that runs in node.js or the browser.",
5
5
  "keywords": [
6
6
  "jsx browser transform",
@@ -25,6 +25,11 @@
25
25
  "import": "./dist/lite/index.js",
26
26
  "default": "./dist/lite/index.js"
27
27
  },
28
+ "./react": {
29
+ "types": "./dist/react/index.d.ts",
30
+ "import": "./dist/react/index.js",
31
+ "default": "./dist/react/index.js"
32
+ },
28
33
  "./loader": {
29
34
  "import": "./dist/loader/jsx.js",
30
35
  "default": "./dist/loader/jsx.js"
@@ -79,6 +84,14 @@
79
84
  "magic-string": "^0.30.21",
80
85
  "oxc-parser": "^0.99.0"
81
86
  },
87
+ "peerDependencies": {
88
+ "react": ">=18"
89
+ },
90
+ "peerDependenciesMeta": {
91
+ "react": {
92
+ "optional": true
93
+ }
94
+ },
82
95
  "optionalDependencies": {
83
96
  "@oxc-parser/binding-darwin-arm64": "^0.99.0",
84
97
  "@oxc-parser/binding-linux-x64-gnu": "^0.99.0",