This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
+28 -17
View File
@@ -2,10 +2,21 @@
import { raw } from "../helper/html/index.js";
import { escapeToBuffer, resolveCallbackSync, stringBufferToString } from "../utils/html.js";
import { DOM_RENDERER, DOM_MEMO } from "./constants.js";
import { createContext, globalContexts, useContext } from "./context.js";
import {
captureRenderContext,
createContext,
globalContexts,
runWithRenderContext,
useContext
} from "./context.js";
import { domRenderers } from "./intrinsic-element/common.js";
import * as intrinsicElementTags from "./intrinsic-element/components.js";
import { normalizeIntrinsicElementKey, styleObjectForEach } from "./utils.js";
import {
isValidAttributeName,
isValidTagName,
normalizeIntrinsicElementKey,
styleObjectForEach
} from "./utils.js";
var nameSpaceContext = void 0;
var getNameSpaceContext = () => nameSpaceContext;
var toSVGAttributeName = (key) => /[A-Z]/.test(key) && // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.
@@ -83,8 +94,11 @@ var JSXNode = class {
key;
children;
isEscaped = true;
localContexts;
suspendedContext;
constructor(tag, props, children) {
if (typeof tag !== "function" && !isValidTagName(tag)) {
throw new Error(`Invalid JSX tag name: ${tag}`);
}
this.tag = tag;
this.props = props;
this.children = children;
@@ -98,27 +112,24 @@ var JSXNode = class {
return this.props.ref || null;
}
toString() {
const buffer = [""];
this.localContexts?.forEach(([context, value]) => {
context.values.push(value);
});
try {
const render = () => {
const buffer = [""];
this.toStringToBuffer(buffer);
} finally {
this.localContexts?.forEach(([context]) => {
context.values.pop();
});
}
return buffer.length === 1 ? "callbacks" in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0] : stringBufferToString(buffer, buffer.callbacks);
return buffer.length === 1 ? "callbacks" in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0] : stringBufferToString(buffer, buffer.callbacks);
};
return this.suspendedContext ? this.suspendedContext(render) : runWithRenderContext(render);
}
toStringToBuffer(buffer) {
const tag = this.tag;
const props = this.props;
let { children } = this;
buffer[0] += `<${tag}`;
const normalizeKey = nameSpaceContext && useContext(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key)) : (key) => normalizeIntrinsicElementKey(key);
const normalizeKey = tag === "svg" || nameSpaceContext && useContext(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key)) : (key) => normalizeIntrinsicElementKey(key);
for (let [key, v] of Object.entries(props)) {
key = normalizeKey(key);
if (!isValidAttributeName(key)) {
continue;
}
if (key === "children") {
} else if (key === "style" && typeof v === "object") {
let styleStr = "";
@@ -182,12 +193,12 @@ var JSXFunctionNode = class extends JSXNode {
if (globalContexts.length === 0) {
buffer.unshift("", res);
} else {
const currentContexts = globalContexts.map((c) => [c, c.values.at(-1)]);
const suspendedContext = captureRenderContext();
buffer.unshift(
"",
res.then((childRes) => {
if (childRes instanceof JSXNode) {
childRes.localContexts = currentContexts;
childRes.suspendedContext = suspendedContext;
}
return childRes;
})
+42 -22
View File
@@ -3,7 +3,7 @@ import { raw } from "../helper/html/index.js";
import { HtmlEscapedCallbackPhase, resolveCallback } from "../utils/html.js";
import { jsx, Fragment } from "./base.js";
import { DOM_RENDERER } from "./constants.js";
import { useContext } from "./context.js";
import { captureRenderContext, useContext } from "./context.js";
import { ErrorBoundary as ErrorBoundaryDomRenderer } from "./dom/components.js";
import { StreamingContext } from "./streaming.js";
var errorBoundaryCounter = 0;
@@ -12,8 +12,9 @@ var childrenToString = async (children) => {
return children.flat().map((c) => c == null || typeof c === "boolean" ? "" : c.toString());
} catch (e) {
if (e instanceof Promise) {
const resume = captureRenderContext();
await e;
return childrenToString(children);
return resume(() => childrenToString(children));
} else {
throw e;
}
@@ -41,51 +42,68 @@ var ErrorBoundary = async ({ children, fallback, fallbackRender, onError }) => {
children = [children];
}
const nonce = useContext(StreamingContext)?.scriptNonce;
let fallbackStr;
const resolveFallbackStr = async () => {
let resume;
const getResume = () => resume ||= captureRenderContext();
let fallbackStrPromise;
const resolveFallbackStr = () => fallbackStrPromise ||= (async () => {
const awaitedFallback = await fallback;
if (typeof awaitedFallback === "string") {
fallbackStr = awaitedFallback;
return awaitedFallback;
} else {
fallbackStr = await awaitedFallback?.toString();
if (typeof fallbackStr === "string") {
fallbackStr = raw(fallbackStr);
const fallbackResult = await getResume()(() => awaitedFallback?.toString());
if (typeof fallbackResult === "string") {
return raw(
fallbackResult,
fallbackResult.callbacks || awaitedFallback?.callbacks
);
}
}
};
const fallbackRes = (error) => {
onError?.(error);
return fallbackStr || fallbackRender && jsx(Fragment, {}, fallbackRender(error)) || "";
})();
const renderFallback = async (error) => {
const fallbackStr = await resolveFallbackStr();
return getResume()(async () => {
onError?.(error);
const fallbackRes = fallbackStr !== void 0 ? fallbackStr : fallbackRender && jsx(Fragment, {}, fallbackRender(error)) || "";
const fallbackResString = await Fragment({
children: fallbackRes
}).toString();
return raw(
fallbackResString,
fallbackResString.callbacks || fallbackRes.callbacks
);
});
};
let resArray = [];
try {
resArray = children.map(resolveChildEarly);
} catch (e) {
await resolveFallbackStr();
const resume2 = getResume();
if (e instanceof Promise) {
resArray = [
e.then(() => childrenToString(children)).catch((e2) => fallbackRes(e2))
e.then(() => resume2(() => childrenToString(children))).catch((e2) => renderFallback(e2))
];
} else {
resArray = [fallbackRes(e)];
resArray = [await renderFallback(e)];
}
}
if (resArray.some((res) => res instanceof Promise)) {
await resolveFallbackStr();
getResume();
const index = errorBoundaryCounter++;
const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`);
const caught = false;
let caught = false;
const catchCallback = async ({ error: error2, buffer }) => {
if (caught) {
return "";
}
const fallbackResString = await Fragment({
children: fallbackRes(error2)
}).toString();
caught = true;
const fallbackResString = await renderFallback(error2);
const fallbackCallbacks = fallbackResString.callbacks;
if (buffer) {
buffer[0] = buffer[0].replace(replaceRe, fallbackResString);
return fallbackCallbacks?.length ? raw("", fallbackCallbacks) : "";
}
return buffer ? "" : `<template data-hono-target="E:${index}">${fallbackResString}</template><script>
return raw(
`<template data-hono-target="E:${index}">${fallbackResString}</template><script>
((d,c,n) => {
c=d.currentScript.previousSibling
d=d.getElementById('E:${index}')
@@ -93,7 +111,9 @@ if(!d)return
do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${index}')
d.replaceWith(c.content)
})(document)
</script>`;
</script>`,
fallbackCallbacks
);
};
let error;
const promiseAll = Promise.all(resArray).catch((e) => error = e);
+129 -5
View File
@@ -4,21 +4,143 @@ import { JSXFragmentNode } from "./base.js";
import { DOM_RENDERER } from "./constants.js";
import { createContextProviderFunction } from "./dom/context.js";
var globalContexts = [];
var alsProbed = false;
var asyncLocalStorage;
var fallbackStore;
var fallbackRendersInFlight = 0;
var warnedFallbackDefault = false;
var loadAsyncLocalStorage = () => {
if (alsProbed) {
return asyncLocalStorage;
}
alsProbed = true;
const global = globalThis;
let AsyncLocalStorage;
for (const probe of [
// Node.js >= 20.16, Deno, Bun, Cloudflare Workers (nodejs_compat). Property
// access only, so bundlers don't statically resolve `node:async_hooks`.
() => global.process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage,
// Node.js < 20.16 has no `process.getBuiltinModule`, but a CJS entrypoint
// exposes the main module's `require` here.
() => global.process?.mainModule?.require?.("node:async_hooks")?.AsyncLocalStorage
]) {
try {
AsyncLocalStorage = probe();
} catch {
}
if (AsyncLocalStorage) {
break;
}
}
if (AsyncLocalStorage) {
asyncLocalStorage = new AsyncLocalStorage();
}
return asyncLocalStorage;
};
var getCurrentStore = () => {
return loadAsyncLocalStorage()?.getStore() || fallbackStore;
};
var warnIfStorelessAccess = () => {
if (fallbackRendersInFlight > 0 && !warnedFallbackDefault) {
warnedFallbackDefault = true;
console.warn(
"hono/jsx: AsyncLocalStorage is unavailable in this runtime, so useContext() after an await in an async component falls back to the context default value during server-side rendering. To get provided values across await boundaries, use a runtime with AsyncLocalStorage (Node.js >= 20.16, Deno, Bun, or Cloudflare Workers with the nodejs_compat flag)."
);
}
};
var getContextValuesIn = (store, context) => {
if (!store) {
warnIfStorelessAccess();
return context.values;
}
let values = store.get(context);
if (!values) {
values = [context.values[0]];
store.set(context, values);
}
return values;
};
var readContextValueIn = (store, context) => {
if (!store) {
warnIfStorelessAccess();
return context.values.at(-1);
}
const values = store.get(context);
return values?.length ? values.at(-1) : context.values[0];
};
var captureContextValues = (store) => (store ? globalContexts.filter((c) => store.has(c)) : globalContexts).map((c) => [
c,
readContextValueIn(store, c)
]);
var resumeWithContextValues = (callback, store, contexts) => runWithRenderContext(() => {
const currentStore = getCurrentStore();
const valuesPerContext = contexts.map(([context, value]) => {
const values = getContextValuesIn(currentStore, context);
values.push(value);
return values;
});
const popContextValues = () => {
valuesPerContext.forEach((values) => {
values.pop();
});
};
try {
const result = callback();
if (result instanceof Promise) {
return result.finally(popContextValues);
}
popContextValues();
return result;
} catch (e) {
popContextValues();
throw e;
}
}, store);
var runWithRenderContext = (callback, resumeStore) => {
if (getCurrentStore()) {
return callback();
}
const store = resumeStore ?? /* @__PURE__ */ new WeakMap();
const storage = loadAsyncLocalStorage();
if (storage) {
return storage.run(store, callback);
}
fallbackStore = store;
let result;
try {
result = callback();
} finally {
fallbackStore = void 0;
}
if (!warnedFallbackDefault && result instanceof Promise) {
fallbackRendersInFlight++;
result = result.finally(() => {
fallbackRendersInFlight--;
});
}
return result;
};
var captureRenderContext = () => {
const store = getCurrentStore();
const contexts = captureContextValues(store);
return (callback) => resumeWithContextValues(callback, store, contexts);
};
var createContext = (defaultValue) => {
const values = [defaultValue];
const context = ((props) => {
values.push(props.value);
const contextValues = getContextValuesIn(getCurrentStore(), context);
contextValues.push(props.value);
let string;
try {
string = props.children ? (Array.isArray(props.children) ? new JSXFragmentNode("", {}, props.children) : props.children).toString() : "";
} catch (e) {
values.pop();
contextValues.pop();
throw e;
}
if (string instanceof Promise) {
return string.finally(() => values.pop()).then((resString) => raw(resString, resString.callbacks));
return string.finally(() => contextValues.pop()).then((resString) => raw(resString, resString.callbacks));
} else {
values.pop();
contextValues.pop();
return raw(string);
}
});
@@ -29,10 +151,12 @@ var createContext = (defaultValue) => {
return context;
};
var useContext = (context) => {
return context.values.at(-1);
return readContextValueIn(getCurrentStore(), context);
};
export {
captureRenderContext,
createContext,
globalContexts,
runWithRenderContext,
useContext
};
+11 -4
View File
@@ -100,22 +100,29 @@ var createCssJsxDomObjects = ({ id }) => {
});
return [cssObject, Style2];
};
var createCssContext = ({ id }) => {
var createCssContext = ({
id,
classNameSlug,
onInvalidSlug
}) => {
const [cssObject, Style2] = createCssJsxDomObjects({ id });
const newCssClassNameObject = (cssClassName) => {
cssClassName.toString = cssObject.toString;
return cssClassName;
};
const css2 = (strings, ...values) => {
return newCssClassNameObject(cssCommon(strings, values));
return newCssClassNameObject(cssCommon(strings, values, classNameSlug, onInvalidSlug));
};
const cx2 = (...args) => {
args = cxCommon(args);
return css2(Array(args.length).fill(""), ...args);
};
const keyframes2 = keyframesCommon;
const keyframes2 = (strings, ...values) => keyframesCommon(strings, values, classNameSlug, onInvalidSlug);
const viewTransition2 = ((strings, ...values) => {
return newCssClassNameObject(viewTransitionCommon(strings, values));
return newCssClassNameObject(
viewTransitionCommon(strings, values, classNameSlug, onInvalidSlug)
// eslint-disable-line @typescript-eslint/no-explicit-any
);
});
return {
css: css2,
+47 -10
View File
@@ -1,7 +1,13 @@
// src/jsx/dom/intrinsic-element/components.ts
import { useContext } from "../../context.js";
import { use, useCallback, useMemo, useState } from "../../hooks/index.js";
import { dataPrecedenceAttr, deDupeKeyMap, domRenderers } from "../../intrinsic-element/common.js";
import {
dataPrecedenceAttr,
deDupeKeyMap,
domRenderers,
isStylesheetLinkWithPrecedence,
shouldDeDupeByKey
} from "../../intrinsic-element/common.js";
import { FormContext, registerAction } from "../hooks/index.js";
import { createPortal, getNameSpaceContext } from "../render.js";
var clearCache = () => {
@@ -49,11 +55,16 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
let element = null;
let created = false;
const deDupeKeys = deDupeKeyMap[tag];
const deDupeByKey = shouldDeDupeByKey(tag, supportSort);
const isDeDupeCandidateLink = (e) => e.getAttribute("rel") === "stylesheet" && e.getAttribute(dataPrecedenceAttr) !== null;
let existingElements = void 0;
if (deDupeKeys.length > 0) {
if (deDupeByKey) {
const tags = head.querySelectorAll(tag);
LOOP: for (const e of tags) {
for (const key of deDupeKeyMap[tag]) {
if (tag === "link" && !isDeDupeCandidateLink(e)) {
continue;
}
for (const key of deDupeKeys) {
if (e.getAttribute(key) === props[key]) {
element = e;
break LOOP;
@@ -72,9 +83,9 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
if (props[key] !== void 0) {
e.setAttribute(key, props[key]);
}
if (props.rel) {
e.setAttribute("rel", props.rel);
}
}
if (props.rel) {
e.setAttribute("rel", props.rel);
}
return e;
})();
@@ -88,7 +99,26 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
}
const insert = useCallback(
(e) => {
if (deDupeKeys.length > 0) {
if (deDupeByKey) {
if (tag === "link" && precedence !== void 0) {
let found2 = false;
for (const existingElement of head.querySelectorAll(tag)) {
const existingPrecedence = existingElement.getAttribute(dataPrecedenceAttr);
if (existingPrecedence === null) {
head.insertBefore(e, existingElement);
return;
}
if (found2 && existingPrecedence !== precedence) {
head.insertBefore(e, existingElement);
return;
}
if (existingPrecedence === precedence) {
found2 = true;
}
}
head.appendChild(e);
return;
}
let found = false;
for (const existingElement of head.querySelectorAll(tag)) {
if (found && existingElement.getAttribute(dataPrecedenceAttr) !== precedence) {
@@ -100,6 +130,10 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
}
}
head.appendChild(e);
} else if (tag === "link") {
if (!head.contains(e)) {
head.appendChild(e);
}
} else if (existingElements) {
let found = false;
for (const existingElement of existingElements) {
@@ -117,7 +151,7 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
existingElements = void 0;
}
},
[precedence]
[deDupeByKey, precedence, tag]
);
const ref = composeRef(props.ref, (e) => {
const key = deDupeKeys[0];
@@ -130,6 +164,9 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
if (!onError && !onLoad) {
return;
}
if (!key) {
return;
}
let promise = blockingPromiseMap[e.getAttribute(key)] ||= new Promise(
(resolve, reject) => {
e.addEventListener("load", resolve);
@@ -147,7 +184,7 @@ var documentMetadataTag = (tag, props, preserveNodeType, supportSort, supportBlo
});
if (supportBlocking && blocking === "render") {
const key = deDupeKeyMap[tag][0];
if (props[key]) {
if (key && props[key]) {
const value = props[key];
const promise = blockingPromiseMap[value] ||= new Promise((resolve, reject) => {
insert(element);
@@ -223,7 +260,7 @@ var link = (props) => {
ref: props.ref
};
}
return documentMetadataTag("link", props, 1, "precedence" in props, true);
return documentMetadataTag("link", props, 1, isStylesheetLinkWithPrecedence(props), true);
};
var meta = (props) => {
return documentMetadataTag("meta", props, void 0, false, false);
+39 -17
View File
@@ -45,6 +45,17 @@ var getEventSpec = (key) => {
};
var toAttributeName = (element, key) => nameSpaceContext && element instanceof SVGElement && /[A-Z]/.test(key) && (key in element.style || // Presentation attributes are findable in style object. "clip-path", "font-size", "stroke-width", etc.
key.match(/^(?:o|pai|str|u|ve)/)) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key;
var normalizeFormValue = (value) => value === null || value === void 0 || value === false ? null : value;
var applySelectValue = (select, props) => {
if (!("value" in props)) {
return;
}
select.value = normalizeFormValue(props["value"]);
if (!select.multiple && select.selectedIndex === -1) {
select.selectedIndex = 0;
}
};
var isIgnorableAttributeError = (error) => error instanceof DOMException && error.name === "InvalidCharacterError";
var applyProps = (container, attributes, oldAttributes) => {
attributes ||= {};
for (let key in attributes) {
@@ -88,18 +99,14 @@ var applyProps = (container, attributes, oldAttributes) => {
} else {
if (key === "value") {
const nodeName = container.nodeName;
if (nodeName === "INPUT" || nodeName === "TEXTAREA" || nodeName === "SELECT") {
if (nodeName === "SELECT") {
continue;
} else if (nodeName === "INPUT" || nodeName === "TEXTAREA") {
;
container.value = value === null || value === void 0 || value === false ? null : value;
container.value = normalizeFormValue(value);
if (nodeName === "TEXTAREA") {
container.textContent = value;
continue;
} else if (nodeName === "SELECT") {
if (container.selectedIndex === -1) {
;
container.selectedIndex = 0;
}
continue;
}
}
} else if (key === "checked" && container.nodeName === "INPUT" || key === "selected" && container.nodeName === "OPTION") {
@@ -107,14 +114,20 @@ var applyProps = (container, attributes, oldAttributes) => {
container[key] = value;
}
const k = toAttributeName(container, key);
if (value === null || value === void 0 || value === false) {
container.removeAttribute(k);
} else if (value === true) {
container.setAttribute(k, "");
} else if (typeof value === "string" || typeof value === "number") {
container.setAttribute(k, value);
} else {
container.setAttribute(k, value.toString());
try {
if (value === null || value === void 0 || value === false) {
container.removeAttribute(k);
} else if (value === true) {
container.setAttribute(k, "");
} else if (typeof value === "string" || typeof value === "number") {
container.setAttribute(k, value);
} else {
container.setAttribute(k, value.toString());
}
} catch (e) {
if (!isIgnorableAttributeError(e)) {
throw e;
}
}
}
}
@@ -130,7 +143,13 @@ var applyProps = (container, attributes, oldAttributes) => {
} else if (key === "ref") {
refCleanupMap.get(container)?.();
} else {
container.removeAttribute(toAttributeName(container, key));
try {
container.removeAttribute(toAttributeName(container, key));
} catch (e) {
if (!isIgnorableAttributeError(e)) {
throw e;
}
}
}
}
}
@@ -268,6 +287,9 @@ var applyNodeObject = (node, container, isNew) => {
el = child.e ||= child.n ? document.createElementNS(child.n, child.tag) : document.createElement(child.tag);
applyProps(el, child.props, child.pP);
applyNodeObject(child, el, isNewLocal);
if (child.tag === "select") {
applySelectValue(el, child.props);
}
}
}
if (child.tag === HONO_PORTAL_ELEMENT) {
+10 -1
View File
@@ -8,8 +8,17 @@ var deDupeKeyMap = {
};
var domRenderers = {};
var dataPrecedenceAttr = "data-precedence";
var isStylesheetLinkWithPrecedence = (props) => props.rel === "stylesheet" && "precedence" in props;
var shouldDeDupeByKey = (tagName, supportSort) => {
if (tagName === "link") {
return supportSort;
}
return deDupeKeyMap[tagName].length > 0;
};
export {
dataPrecedenceAttr,
deDupeKeyMap,
domRenderers
domRenderers,
isStylesheetLinkWithPrecedence,
shouldDeDupeByKey
};
+24 -12
View File
@@ -4,7 +4,12 @@ import { JSXNode, getNameSpaceContext } from "../base.js";
import { toArray } from "../children.js";
import { PERMALINK } from "../constants.js";
import { useContext } from "../context.js";
import { dataPrecedenceAttr, deDupeKeyMap } from "./common.js";
import {
dataPrecedenceAttr,
deDupeKeyMap,
isStylesheetLinkWithPrecedence,
shouldDeDupeByKey
} from "./common.js";
var metaTagMap = /* @__PURE__ */ new WeakMap();
var insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context }) => {
if (!buffer) {
@@ -15,8 +20,12 @@ var insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context })
const tags = map[tagName] ||= [];
let duped = false;
const deDupeKeys = deDupeKeyMap[tagName];
if (deDupeKeys.length > 0) {
const deDupeByKey = shouldDeDupeByKey(tagName, precedence !== void 0);
if (deDupeByKey) {
LOOP: for (const [, tagProps] of tags) {
if (tagName === "link" && !(tagProps.rel === "stylesheet" && tagProps[dataPrecedenceAttr] !== void 0)) {
continue;
}
for (const key of deDupeKeys) {
if ((tagProps?.[key] ?? null) === props?.[key]) {
duped = true;
@@ -27,25 +36,28 @@ var insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context })
}
if (duped) {
buffer[0] = buffer[0].replaceAll(tag, "");
} else if (deDupeKeys.length > 0) {
} else if (deDupeByKey || tagName === "link") {
tags.push([tag, props, precedence]);
} else {
tags.unshift([tag, props, precedence]);
}
if (buffer[0].indexOf("</head>") !== -1) {
let insertTags;
if (precedence === void 0) {
insertTags = tags.map(([tag2]) => tag2);
} else {
if (tagName === "link" || precedence !== void 0) {
const precedences = [];
insertTags = tags.map(([tag2, , precedence2]) => {
let order = precedences.indexOf(precedence2);
insertTags = tags.map(([tag2, , tagPrecedence], index) => {
if (tagPrecedence === void 0) {
return [tag2, Number.MAX_SAFE_INTEGER, index];
}
let order = precedences.indexOf(tagPrecedence);
if (order === -1) {
precedences.push(precedence2);
precedences.push(tagPrecedence);
order = precedences.length - 1;
}
return [tag2, order];
}).sort((a, b) => a[1] - b[1]).map(([tag2]) => tag2);
return [tag2, order, index];
}).sort((a, b) => a[1] - b[1] || a[2] - b[2]).map(([tag2]) => tag2);
} else {
insertTags = tags.map(([tag2]) => tag2);
}
insertTags.forEach((tag2) => {
buffer[0] = buffer[0].replaceAll(tag2, "");
@@ -114,7 +126,7 @@ var link = ({ children, ...props }) => {
if (["onLoad", "onError"].some((k) => k in props) || props.rel === "stylesheet" && (!("precedence" in props) || "disabled" in props)) {
return returnWithoutSpecialBehavior("link", children, props);
}
return documentMetadataTag("link", children, props, "precedence" in props);
return documentMetadataTag("link", children, props, isStylesheetLinkWithPrecedence(props));
};
var meta = ({ children, ...props }) => {
const nameSpaceContext = getNameSpaceContext();
+4 -1
View File
@@ -3,8 +3,11 @@ import { jsxDEV, Fragment } from "./jsx-dev-runtime.js";
import { jsxDEV as jsxDEV2 } from "./jsx-dev-runtime.js";
import { html, raw } from "../helper/html/index.js";
import { escapeToBuffer, stringBufferToString } from "../utils/html.js";
import { styleObjectForEach } from "./utils.js";
import { isValidAttributeName, styleObjectForEach } from "./utils.js";
var jsxAttr = (key, v) => {
if (!isValidAttributeName(key)) {
return raw("");
}
const buffer = [`${key}="`];
if (key === "style" && typeof v === "object") {
let styleStr = "";
+10 -8
View File
@@ -4,7 +4,7 @@ import { HtmlEscapedCallbackPhase, resolveCallback } from "../utils/html.js";
import { JSXNode } from "./base.js";
import { childrenToString } from "./components.js";
import { DOM_RENDERER, DOM_STASH } from "./constants.js";
import { createContext, useContext } from "./context.js";
import { captureRenderContext, createContext, useContext } from "./context.js";
import { Suspense as SuspenseDomRenderer } from "./dom/components.js";
import { buildDataStack } from "./dom/render.js";
var StreamingContext = createContext(null);
@@ -19,9 +19,8 @@ var Suspense = async ({
const nonce = useContext(StreamingContext)?.scriptNonce;
let resArray = [];
const stackNode = { [DOM_STASH]: [0, []] };
const popNodeStack = (value) => {
const popNodeStack = () => {
buildDataStack.pop();
return value;
};
try {
stackNode[DOM_STASH][0] = 0;
@@ -31,12 +30,15 @@ var Suspense = async ({
);
} catch (e) {
if (e instanceof Promise) {
const resume = captureRenderContext();
resArray = [
e.then(() => {
stackNode[DOM_STASH][0] = 0;
buildDataStack.push([[], stackNode]);
return childrenToString(children).then(popNodeStack);
})
e.then(
() => resume(() => {
stackNode[DOM_STASH][0] = 0;
buildDataStack.push([[], stackNode]);
return childrenToString(children).finally(popNodeStack);
})
)
];
} else {
throw e;
+153 -5
View File
@@ -10,18 +10,166 @@ var normalizeElementKeyMap = /* @__PURE__ */ new Map([
["formAction", "formaction"]
]);
var normalizeIntrinsicElementKey = (key) => normalizeElementKeyMap.get(key) || key;
var invalidAttributeNameCharRe = /[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/;
var validAttributeNameCache = /* @__PURE__ */ new Set();
var validAttributeNameCacheMax = 1024;
var invalidTagNameCharRe = /^[!?]|[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/;
var validTagNameCache = /* @__PURE__ */ new Set();
var validTagNameCacheMax = 256;
var cacheValidName = (cache, max, name) => {
if (cache.size >= max) {
cache.clear();
}
cache.add(name);
};
var isValidTagName = (name) => {
if (validTagNameCache.has(name)) {
return true;
}
if (typeof name !== "string") {
return false;
}
if (name.length === 0) {
return true;
}
if (invalidTagNameCharRe.test(name)) {
return false;
}
cacheValidName(validTagNameCache, validTagNameCacheMax, name);
return true;
};
var isValidAttributeName = (name) => {
if (validAttributeNameCache.has(name)) {
return true;
}
const len = name.length;
if (len === 0) {
return false;
}
for (let i = 0; i < len; i++) {
const c = name.charCodeAt(i);
if (!(c >= 97 && c <= 122 || // a-z
c >= 65 && c <= 90 || // A-Z
c >= 48 && c <= 57 || // 0-9
c === 45 || // -
c === 95 || // _
c === 46 || // .
c === 58)) {
if (!invalidAttributeNameCharRe.test(name)) {
cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name);
return true;
} else {
return false;
}
}
}
cacheValidName(validAttributeNameCache, validAttributeNameCacheMax, name);
return true;
};
var invalidStylePropertyNameCharRe = /[\s"'():;\\/\[\]{}\x00-\x1f\x7f-\x9f]/;
var validStylePropertyNameCache = /* @__PURE__ */ new Set();
var validStylePropertyNameCacheMax = 1024;
var isValidStylePropertyName = (name) => {
if (validStylePropertyNameCache.has(name)) {
return true;
}
const len = name.length;
if (len === 0) {
return false;
}
for (let i = 0; i < len; i++) {
const c = name.charCodeAt(i);
if (!(c >= 97 && c <= 122 || // a-z
c >= 65 && c <= 90 || // A-Z
c >= 48 && c <= 57 || // 0-9
c === 45 || // -
c === 95)) {
if (!invalidStylePropertyNameCharRe.test(name)) {
cacheValidName(validStylePropertyNameCache, validStylePropertyNameCacheMax, name);
return true;
} else {
return false;
}
}
}
cacheValidName(validStylePropertyNameCache, validStylePropertyNameCacheMax, name);
return true;
};
var unsafeStyleValueCharRe = /[;"'\\/\[\](){}]/;
var hasUnsafeStyleValue = (value) => {
if (!unsafeStyleValueCharRe.test(value)) {
return false;
}
let quote = 0;
const blockStack = [];
for (let i = 0, len = value.length; i < len; i++) {
const c = value.charCodeAt(i);
if (c === 92) {
if (i === len - 1) {
return true;
}
i++;
} else if (quote !== 0) {
if (c === 10 || c === 12 || c === 13) {
return true;
}
if (c === quote) {
quote = 0;
}
} else if (c === 47 && value.charCodeAt(i + 1) === 42) {
const end = value.indexOf("*/", i + 2);
if (end === -1) {
return true;
}
i = end + 1;
} else if (c === 34 || c === 39) {
quote = c;
} else if (c === 40) {
blockStack.push(41);
} else if (c === 91) {
blockStack.push(93);
} else if (c === 123 || c === 125) {
return true;
} else if (c === 41 || c === 93) {
if (blockStack[blockStack.length - 1] !== c) {
return true;
}
blockStack.pop();
} else if (c === 59 && blockStack.length === 0) {
return true;
}
}
return quote !== 0 || blockStack.length !== 0;
};
var styleObjectForEach = (style, fn) => {
for (const [k, v] of Object.entries(style)) {
const key = k[0] === "-" || !/[A-Z]/.test(k) ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
fn(
key,
v == null ? null : typeof v === "number" ? !key.match(
if (!isValidStylePropertyName(key)) {
continue;
}
if (v == null) {
fn(key, null);
continue;
}
let value;
if (typeof v === "number") {
value = !key.match(
/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/
) ? `${v}px` : `${v}` : v
);
) ? `${v}px` : `${v}`;
} else if (typeof v === "string") {
if (hasUnsafeStyleValue(v)) {
continue;
}
value = v;
} else {
continue;
}
fn(key, value);
}
};
export {
isValidAttributeName,
isValidTagName,
normalizeIntrinsicElementKey,
styleObjectForEach
};