@knighted/jsx 1.0.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,357 @@
1
+ import MagicString from 'magic-string';
2
+ import { parseSync } from 'oxc-parser';
3
+ const stripTrailingWhitespace = (value) => value.replace(/\s+$/g, '');
4
+ const stripLeadingWhitespace = (value) => value.replace(/^\s+/g, '');
5
+ const getTemplateExpressionContext = (left, right) => {
6
+ const trimmedLeft = stripTrailingWhitespace(left);
7
+ const trimmedRight = stripLeadingWhitespace(right);
8
+ if (trimmedLeft.endsWith('<') || trimmedLeft.endsWith('</')) {
9
+ return { type: 'tag' };
10
+ }
11
+ if (/{\s*\.\.\.$/.test(trimmedLeft) && trimmedRight.startsWith('}')) {
12
+ return { type: 'spread' };
13
+ }
14
+ const attrStringMatch = trimmedLeft.match(/=\s*(["'])$/);
15
+ if (attrStringMatch) {
16
+ const quoteChar = attrStringMatch[1];
17
+ if (trimmedRight.startsWith(quoteChar)) {
18
+ return { type: 'attributeString', quote: quoteChar };
19
+ }
20
+ }
21
+ if (trimmedLeft.endsWith('={') && trimmedRight.startsWith('}')) {
22
+ return { type: 'attributeExisting' };
23
+ }
24
+ if (/=\s*$/.test(trimmedLeft)) {
25
+ return { type: 'attributeUnquoted' };
26
+ }
27
+ if (trimmedLeft.endsWith('{') && trimmedRight.startsWith('}')) {
28
+ return { type: 'childExisting' };
29
+ }
30
+ return { type: 'childText' };
31
+ };
32
+ const TEMPLATE_EXPR_PLACEHOLDER_PREFIX = '__JSX_LOADER_TEMPLATE_EXPR_';
33
+ const MODULE_PARSER_OPTIONS = {
34
+ lang: 'tsx',
35
+ sourceType: 'module',
36
+ range: true,
37
+ preserveParens: true,
38
+ };
39
+ const TEMPLATE_PARSER_OPTIONS = {
40
+ lang: 'tsx',
41
+ sourceType: 'module',
42
+ range: true,
43
+ preserveParens: true,
44
+ };
45
+ const DEFAULT_TAGS = ['jsx', 'reactJsx'];
46
+ const escapeTemplateChunk = (chunk) => chunk.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\${/g, '\\${');
47
+ const formatParserError = (error) => {
48
+ let message = `[jsx-loader] ${error.message}`;
49
+ if (error.labels?.length) {
50
+ const label = error.labels[0];
51
+ if (label.message) {
52
+ message += `\n${label.message}`;
53
+ }
54
+ }
55
+ if (error.codeframe) {
56
+ message += `\n${error.codeframe}`;
57
+ }
58
+ return message;
59
+ };
60
+ const walkAst = (node, visitor) => {
61
+ if (!node || typeof node !== 'object') {
62
+ return;
63
+ }
64
+ const current = node;
65
+ if (typeof current.type === 'string') {
66
+ visitor(current);
67
+ }
68
+ for (const value of Object.values(current)) {
69
+ if (!value) {
70
+ continue;
71
+ }
72
+ if (Array.isArray(value)) {
73
+ value.forEach(child => walkAst(child, visitor));
74
+ continue;
75
+ }
76
+ if (typeof value === 'object') {
77
+ walkAst(value, visitor);
78
+ }
79
+ }
80
+ };
81
+ const shouldInterpolateName = (name) => /^[A-Z]/.test(name.name);
82
+ const addSlot = (slots, source, range) => {
83
+ if (!range) {
84
+ return;
85
+ }
86
+ const [start, end] = range;
87
+ if (start === end) {
88
+ return;
89
+ }
90
+ slots.push({
91
+ start,
92
+ end,
93
+ code: source.slice(start, end),
94
+ });
95
+ };
96
+ const collectSlots = (program, source) => {
97
+ const slots = [];
98
+ const recordComponentName = (name) => {
99
+ if (!name) {
100
+ return;
101
+ }
102
+ switch (name.type) {
103
+ case 'JSXIdentifier': {
104
+ if (!shouldInterpolateName(name)) {
105
+ return;
106
+ }
107
+ addSlot(slots, source, name.range);
108
+ break;
109
+ }
110
+ case 'JSXMemberExpression': {
111
+ addSlot(slots, source, name.range);
112
+ break;
113
+ }
114
+ default:
115
+ break;
116
+ }
117
+ };
118
+ walkAst(program, node => {
119
+ switch (node.type) {
120
+ case 'JSXExpressionContainer': {
121
+ const expression = node.expression;
122
+ if (expression.type === 'JSXEmptyExpression') {
123
+ break;
124
+ }
125
+ if (isLoaderPlaceholderIdentifier(expression)) {
126
+ break;
127
+ }
128
+ addSlot(slots, source, (expression.range ?? node.range));
129
+ break;
130
+ }
131
+ case 'JSXSpreadAttribute': {
132
+ const argument = node.argument;
133
+ if (isLoaderPlaceholderIdentifier(argument)) {
134
+ break;
135
+ }
136
+ addSlot(slots, source, argument?.range);
137
+ break;
138
+ }
139
+ case 'JSXSpreadChild': {
140
+ const expression = node.expression;
141
+ if (isLoaderPlaceholderIdentifier(expression)) {
142
+ break;
143
+ }
144
+ addSlot(slots, source, expression?.range);
145
+ break;
146
+ }
147
+ case 'JSXElement': {
148
+ const opening = node.openingElement;
149
+ recordComponentName(opening.name);
150
+ const closing = node.closingElement;
151
+ if (closing?.name) {
152
+ recordComponentName(closing.name);
153
+ }
154
+ break;
155
+ }
156
+ default:
157
+ break;
158
+ }
159
+ });
160
+ return slots.sort((a, b) => a.start - b.start);
161
+ };
162
+ const renderTemplateWithSlots = (source, slots) => {
163
+ let cursor = 0;
164
+ let output = '';
165
+ slots.forEach(slot => {
166
+ if (slot.start < cursor) {
167
+ throw new Error('Overlapping JSX expressions detected inside template literal.');
168
+ }
169
+ output += escapeTemplateChunk(source.slice(cursor, slot.start));
170
+ output += `\${${slot.code}}`;
171
+ cursor = slot.end;
172
+ });
173
+ output += escapeTemplateChunk(source.slice(cursor));
174
+ return { code: output, changed: slots.length > 0 };
175
+ };
176
+ const transformTemplateLiteral = (templateSource, resourcePath) => {
177
+ const result = parseSync(`${resourcePath}?jsx-template`, templateSource, TEMPLATE_PARSER_OPTIONS);
178
+ if (result.errors.length > 0) {
179
+ throw new Error(formatParserError(result.errors[0]));
180
+ }
181
+ const slots = collectSlots(result.program, templateSource);
182
+ return renderTemplateWithSlots(templateSource, slots);
183
+ };
184
+ const getTaggedTemplateName = (node) => {
185
+ if (node.type !== 'TaggedTemplateExpression') {
186
+ return null;
187
+ }
188
+ const tagNode = node.tag;
189
+ if (tagNode.type !== 'Identifier') {
190
+ return null;
191
+ }
192
+ return tagNode.name;
193
+ };
194
+ const TAG_PLACEHOLDER_PREFIX = '__JSX_LOADER_TAG_EXPR_';
195
+ const buildTemplateSource = (quasis, expressions, source, tag) => {
196
+ const placeholderMap = new Map();
197
+ const tagPlaceholderMap = new Map();
198
+ let template = '';
199
+ let placeholderIndex = 0;
200
+ let trimStartNext = 0;
201
+ let mutated = false;
202
+ const registerMarker = (code, isTag) => {
203
+ if (isTag) {
204
+ const existing = tagPlaceholderMap.get(code);
205
+ if (existing) {
206
+ return existing;
207
+ }
208
+ const marker = `${TAG_PLACEHOLDER_PREFIX}${tagPlaceholderMap.size}__`;
209
+ tagPlaceholderMap.set(code, marker);
210
+ placeholderMap.set(marker, code);
211
+ return marker;
212
+ }
213
+ const marker = `${TEMPLATE_EXPR_PLACEHOLDER_PREFIX}${placeholderIndex++}__`;
214
+ placeholderMap.set(marker, code);
215
+ return marker;
216
+ };
217
+ quasis.forEach((quasi, index) => {
218
+ let chunk = quasi.value.cooked;
219
+ if (typeof chunk !== 'string') {
220
+ chunk = quasi.value.raw ?? '';
221
+ }
222
+ if (trimStartNext > 0) {
223
+ chunk = chunk.slice(trimStartNext);
224
+ trimStartNext = 0;
225
+ }
226
+ template += chunk;
227
+ const expression = expressions[index];
228
+ if (!expression) {
229
+ return;
230
+ }
231
+ const start = expression.start ?? null;
232
+ const end = expression.end ?? null;
233
+ if (start === null || end === null) {
234
+ throw new Error('Unable to read template expression source range.');
235
+ }
236
+ const nextChunk = quasis[index + 1];
237
+ const nextValue = nextChunk?.value;
238
+ const rightText = nextValue?.cooked ?? nextValue?.raw ?? '';
239
+ const context = getTemplateExpressionContext(chunk, rightText);
240
+ const code = source.slice(start, end);
241
+ const marker = registerMarker(code, context.type === 'tag');
242
+ const appendMarker = (wrapper) => {
243
+ template += wrapper ? wrapper(marker) : marker;
244
+ };
245
+ switch (context.type) {
246
+ case 'tag':
247
+ case 'spread':
248
+ case 'attributeExisting':
249
+ case 'childExisting': {
250
+ appendMarker();
251
+ break;
252
+ }
253
+ case 'attributeString': {
254
+ const quoteChar = context.quote;
255
+ if (!template.endsWith(quoteChar)) {
256
+ throw new Error(`[jsx-loader] Expected attribute quote ${quoteChar} before template expression inside ${tag}\`\` block.`);
257
+ }
258
+ template = template.slice(0, -1);
259
+ appendMarker(identifier => `{${identifier}}`);
260
+ mutated = true;
261
+ if (rightText.startsWith(quoteChar)) {
262
+ trimStartNext = 1;
263
+ }
264
+ break;
265
+ }
266
+ case 'attributeUnquoted': {
267
+ appendMarker(identifier => `{${identifier}}`);
268
+ mutated = true;
269
+ break;
270
+ }
271
+ case 'childText': {
272
+ appendMarker(identifier => `{${identifier}}`);
273
+ mutated = true;
274
+ break;
275
+ }
276
+ }
277
+ });
278
+ return {
279
+ source: template,
280
+ mutated,
281
+ placeholders: Array.from(placeholderMap.entries()).map(([marker, code]) => ({
282
+ marker,
283
+ code,
284
+ })),
285
+ };
286
+ };
287
+ const restoreTemplatePlaceholders = (code, placeholders) => placeholders.reduce((result, placeholder) => {
288
+ return result.split(placeholder.marker).join(`\${${placeholder.code}}`);
289
+ }, code);
290
+ const isLoaderPlaceholderIdentifier = (node) => {
291
+ if (node?.type !== 'Identifier' || typeof node.name !== 'string') {
292
+ return false;
293
+ }
294
+ return (node.name.startsWith(TEMPLATE_EXPR_PLACEHOLDER_PREFIX) ||
295
+ node.name.startsWith(TAG_PLACEHOLDER_PREFIX));
296
+ };
297
+ const transformSource = (source, config) => {
298
+ const ast = parseSync(config.resourcePath, source, MODULE_PARSER_OPTIONS);
299
+ if (ast.errors.length > 0) {
300
+ throw new Error(formatParserError(ast.errors[0]));
301
+ }
302
+ const taggedTemplates = [];
303
+ walkAst(ast.program, node => {
304
+ const tagName = getTaggedTemplateName(node);
305
+ if (tagName && config.tags.includes(tagName)) {
306
+ taggedTemplates.push({ node, tagName });
307
+ }
308
+ });
309
+ if (!taggedTemplates.length) {
310
+ return source;
311
+ }
312
+ const magic = new MagicString(source);
313
+ let mutated = false;
314
+ taggedTemplates
315
+ .sort((a, b) => b.node.start - a.node.start)
316
+ .forEach(entry => {
317
+ const { node, tagName } = entry;
318
+ const quasi = node.quasi;
319
+ const templateSource = buildTemplateSource(quasi.quasis, quasi.expressions, source, tagName);
320
+ const { code, changed } = transformTemplateLiteral(templateSource.source, config.resourcePath);
321
+ const restored = restoreTemplatePlaceholders(code, templateSource.placeholders);
322
+ const templateChanged = changed || templateSource.mutated;
323
+ if (!templateChanged) {
324
+ return;
325
+ }
326
+ const tagSource = source.slice(node.tag.start, node.tag.end);
327
+ const replacement = `${tagSource}\`${restored}\``;
328
+ magic.overwrite(node.start, node.end, replacement);
329
+ mutated = true;
330
+ });
331
+ return mutated ? magic.toString() : source;
332
+ };
333
+ export default function jsxLoader(input) {
334
+ const callback = this.async();
335
+ try {
336
+ const options = this.getOptions?.() ?? {};
337
+ const explicitTags = Array.isArray(options.tags)
338
+ ? options.tags.filter((value) => typeof value === 'string' && value.length > 0)
339
+ : null;
340
+ const legacyTag = typeof options.tag === 'string' && options.tag.length > 0 ? options.tag : null;
341
+ const tagList = explicitTags?.length
342
+ ? explicitTags
343
+ : legacyTag
344
+ ? [legacyTag]
345
+ : DEFAULT_TAGS;
346
+ const tags = Array.from(new Set(tagList));
347
+ const source = typeof input === 'string' ? input : input.toString('utf8');
348
+ const output = transformSource(source, {
349
+ resourcePath: this.resourcePath,
350
+ tags,
351
+ });
352
+ callback(null, output);
353
+ }
354
+ catch (error) {
355
+ callback(error);
356
+ }
357
+ }
@@ -0,0 +1,2 @@
1
+ export { reactJsx } from './react-jsx.js';
2
+ export type { ReactJsxComponent } from './react-jsx.js';
@@ -0,0 +1 @@
1
+ export { reactJsx } from './react-jsx.js';
@@ -0,0 +1,5 @@
1
+ import { type ComponentType, type ReactElement, type ReactNode } from 'react';
2
+ export type ReactJsxComponent<Props = Record<string, unknown>> = ComponentType<Props & {
3
+ children?: ReactNode;
4
+ }>;
5
+ export declare const reactJsx: (templates: TemplateStringsArray, ...values: unknown[]) => ReactElement;
@@ -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 {};