html.ts
This file
Path
src/utils/html.ts
182 lines · 5.0 KiB · TypeScript
Last changed by
Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b
History of this fileTake it
The walk stopped after 200 commits: lines older than 7ee829b point at it.
v4.4.7Yusuke Wadabefore adoption7ee829b
lines 1–37why, one step back1/**2 * @module3 * HTML utility.4 */56export const HtmlEscapedCallbackPhase = {7 Stringify: 1,8 BeforeStream: 2,9 Stream: 3,10} as const11type HtmlEscapedCallbackOpts = {12 buffer?: [string]13 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase]14 context: object // An object unique to each JSX tree. This object is used as the WeakMap key.15}16export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string> | undefined17export type HtmlEscaped = {18 isEscaped: true19 callbacks?: HtmlEscapedCallback[]20}21export type HtmlEscapedString = string & HtmlEscaped2223/**24 * StringBuffer contains string and Promise<string> alternately25 * The length of the array will be odd, the odd numbered element will be a string,26 * and the even numbered element will be a Promise<string>.27 * When concatenating into a single string, it must be processed from the tail.28 * @example29 * [30 * 'framework.',31 * Promise.resolve('ultra fast'),32 * 'a ',33 * Promise.resolve('is '),34 * 'Hono',35 * ]36 */37export type StringBuffer = (string | Promise<string>)[]Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e
line 38why, one step back38export type StringBufferWithCallbacks = StringBuffer & { callbacks: HtmlEscapedCallback[] }v4.4.7Yusuke Wadabefore adoption7ee829b
lines 39–52why, one step back3940export const raw = (value: unknown, callbacks?: HtmlEscapedCallback[]): HtmlEscapedString => {41 const escapedString = new String(value) as HtmlEscapedString42 escapedString.isEscaped = true43 escapedString.callbacks = callbacks4445 return escapedString46}4748// The `escapeToBuffer` implementation is based on code from the MIT licensed `react-dom` package.49// https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/server/escapeTextForBrowser.js5051const escapeRe = /[&<>'"]/52Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e
lines 53–56why, one step back53export const stringBufferToString = async (54 buffer: StringBuffer,55 callbacks: HtmlEscapedCallback[] | undefined56): Promise<HtmlEscapedString> => {v4.4.7Yusuke Wadabefore adoption7ee829b
line 57why, one step back57 let str = ''Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e
line 58why, one step back58 callbacks ||= []fix(jsx): await all promises at once to avoid race condition (#3274)Taku Amanobefore adoptiona5b2382
lines 59–61why, one step back59 const resolvedBuffer = await Promise.all(buffer)60 for (let i = resolvedBuffer.length - 1; ; i--) {61 str += resolvedBuffer[i]v4.4.7Yusuke Wadabefore adoption7ee829b
lines 62–66why, one step back62 i--63 if (i < 0) {64 break65 }66fix(jsx): await all promises at once to avoid race condition (#3274)Taku Amanobefore adoptiona5b2382
line 67why, one step back67 let r = resolvedBuffer[i]v4.4.7Yusuke Wadabefore adoption7ee829b
lines 68–126why, one step back68 if (typeof r === 'object') {69 callbacks.push(...((r as HtmlEscapedString).callbacks || []))70 }7172 const isEscaped = (r as HtmlEscapedString).isEscaped73 r = await (typeof r === 'object' ? (r as HtmlEscapedString).toString() : r)74 if (typeof r === 'object') {75 callbacks.push(...((r as HtmlEscapedString).callbacks || []))76 }7778 if ((r as HtmlEscapedString).isEscaped ?? isEscaped) {79 str += r80 } else {81 const buf = [str]82 escapeToBuffer(r, buf)83 str = buf[0]84 }85 }8687 return raw(str, callbacks)88}8990export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {91 const match = str.search(escapeRe)92 if (match === -1) {93 buffer[0] += str94 return95 }9697 let escape98 let index99 let lastIndex = 0100101 for (index = match; index < str.length; index++) {102 switch (str.charCodeAt(index)) {103 case 34: // "104 escape = '"'105 break106 case 39: // '107 escape = '''108 break109 case 38: // &110 escape = '&'111 break112 case 60: // <113 escape = '<'114 break115 case 62: // >116 escape = '>'117 break118 default:119 continue120 }121122 buffer[0] += str.substring(lastIndex, index) + escape123 lastIndex = index + 1124 }125126 buffer[0] += str.substring(lastIndex, index)Merge pull request #3144 from honojs/nextYusuke Wadabefore adoption2f4bb3e
lines 127–139why, one step back127}128129export const resolveCallbackSync = (str: string | HtmlEscapedString): string => {130 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]131 if (!callbacks?.length) {132 return str133 }134 const buffer: [string] = [str]135 const context = {}136137 callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }))138139 return buffer[0]v4.4.7Yusuke Wadabefore adoption7ee829b
lines 140–142why, one step back140}141142export const resolveCallback = async (Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b
line 143why, one step back143 str: string | HtmlEscapedString | Promise<string>,v4.4.7Yusuke Wadabefore adoption7ee829b
lines 144–148why, one step back144 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase],145 preserveCallbacks: boolean,146 context: object,147 buffer?: [string]148): Promise<string> => {Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b
lines 149–157why, one step back149 if (typeof str === 'object' && !(str instanceof String)) {150 if (!((str as unknown) instanceof Promise)) {151 str = (str as unknown as string).toString() // HtmlEscapedString object to string152 }153 if ((str as string | Promise<string>) instanceof Promise) {154 str = await (str as unknown as Promise<string>)155 }156 }157v4.4.7Yusuke Wadabefore adoption7ee829b
lines 158–164why, one step back158 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]159 if (!callbacks?.length) {160 return Promise.resolve(str)161 }162 if (buffer) {163 buffer[0] += str164 } else {Merge pull request #3394 from honojs/nextYusuke Wadabefore adoption2da003b
line 165why, one step back165 buffer = [str as string]v4.4.7Yusuke Wadabefore adoption7ee829b
lines 166–182why, one step back166 }167168 const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>169 Promise.all(170 res171 // eslint-disable-next-line @typescript-eslint/no-explicit-any172 .filter<string>(Boolean as any)173 .map((str) => resolveCallback(str, phase, false, context, buffer))174 ).then(() => (buffer as [string])[0])175 )176177 if (preserveCallbacks) {178 return raw(await resStr, callbacks)179 } else {180 return resStr181 }182}