@knighted/jsx 1.1.0 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,15 +1,18 @@
1
1
  {
2
2
  "name": "@knighted/jsx",
3
- "version": "1.1.0",
4
- "description": "A simple JSX transpiler that runs in node.js or the browser.",
3
+ "version": "1.2.0-rc.1",
4
+ "description": "Runtime JSX tagged template that renders DOM or React trees anywhere without a build step.",
5
5
  "keywords": [
6
- "jsx browser transform",
7
- "jsx transpiler",
8
- "jsx compiler",
9
- "jsx parser",
10
6
  "jsx runtime",
11
- "jsx node",
12
- "jsx"
7
+ "jsx template literal",
8
+ "tagged template",
9
+ "no-build jsx",
10
+ "dom runtime",
11
+ "react runtime",
12
+ "ssr",
13
+ "lit",
14
+ "webpack loader",
15
+ "oxc parser"
13
16
  ],
14
17
  "type": "module",
15
18
  "main": "./dist/index.js",
@@ -25,6 +28,21 @@
25
28
  "import": "./dist/lite/index.js",
26
29
  "default": "./dist/lite/index.js"
27
30
  },
31
+ "./react": {
32
+ "types": "./dist/react/index.d.ts",
33
+ "import": "./dist/react/index.js",
34
+ "default": "./dist/react/index.js"
35
+ },
36
+ "./node": {
37
+ "types": "./dist/node/index.d.ts",
38
+ "import": "./dist/node/index.js",
39
+ "default": "./dist/node/index.js"
40
+ },
41
+ "./node/react": {
42
+ "types": "./dist/node/react/index.d.ts",
43
+ "import": "./dist/node/react/index.js",
44
+ "default": "./dist/node/react/index.js"
45
+ },
28
46
  "./loader": {
29
47
  "import": "./dist/loader/jsx.js",
30
48
  "default": "./dist/loader/jsx.js"
@@ -46,6 +64,7 @@
46
64
  "test": "vitest run --coverage",
47
65
  "test:watch": "vitest",
48
66
  "build:fixture": "node scripts/build-rspack-fixture.mjs",
67
+ "demo:node-ssr": "node test/fixtures/node-ssr/render.mjs",
49
68
  "dev": "vite dev --config vite.config.ts",
50
69
  "build:demo": "vite build --config vite.config.ts",
51
70
  "preview": "vite preview --config vite.config.ts",
@@ -56,15 +75,19 @@
56
75
  "devDependencies": {
57
76
  "@eslint/js": "^9.39.1",
58
77
  "@knighted/duel": "^2.1.6",
78
+ "@types/node": "^22.10.1",
59
79
  "@rspack/core": "^1.0.5",
60
80
  "@types/jsdom": "^27.0.0",
61
81
  "@types/react": "^19.2.7",
62
82
  "@types/react-dom": "^19.2.3",
63
83
  "@vitest/coverage-v8": "^4.0.14",
64
84
  "eslint": "^9.39.1",
85
+ "eslint-plugin-n": "^17.10.3",
86
+ "@oxc-project/types": "^0.99.0",
65
87
  "http-server": "^14.1.1",
66
88
  "jsdom": "^27.2.0",
67
89
  "lit": "^3.2.1",
90
+ "next": "^16.0.0",
68
91
  "prettier": "^3.7.3",
69
92
  "react": "^19.0.0",
70
93
  "react-dom": "^19.0.0",
@@ -79,6 +102,22 @@
79
102
  "magic-string": "^0.30.21",
80
103
  "oxc-parser": "^0.99.0"
81
104
  },
105
+ "peerDependencies": {
106
+ "react": ">=18",
107
+ "jsdom": "*",
108
+ "linkedom": "*"
109
+ },
110
+ "peerDependenciesMeta": {
111
+ "react": {
112
+ "optional": true
113
+ },
114
+ "jsdom": {
115
+ "optional": true
116
+ },
117
+ "linkedom": {
118
+ "optional": true
119
+ }
120
+ },
82
121
  "optionalDependencies": {
83
122
  "@oxc-parser/binding-darwin-arm64": "^0.99.0",
84
123
  "@oxc-parser/binding-linux-x64-gnu": "^0.99.0",