/** * Prefix that marks a serialized function in the theme data * * 标记序列化后函数的主题数据前缀 */ const FUNCTION_PLACEHOLDER_PREFIX = '_vp-fn_' /** * Source code of the deserializer inlined into the generated theme data module * * The functions are emitted as plain code next to the deserializer, which only * looks them up by index. Therefore no `new Function` is needed, and strict CSP * without `unsafe-eval` keeps working. * * 内联进生成的「主题数据模块」的反序列化器源码 * * 函数会以普通代码的形式与反序列化器一起输出,反序列化器只按下标查表还原。因此无需 `new Function`,禁止 `unsafe-eval` 的严格 * CSP 也能正常工作。 */ export const DESERIALIZE_FUNCTIONS = `function deserializeFunctions(value, fns) { if (Array.isArray(value)) return value.map((item) => deserializeFunctions(item, fns)) if (typeof value === 'object' && value !== null) return Object.keys(value).reduce((result, key) => { result[key] = deserializeFunctions(value[key], fns) return result }, {}) if (typeof value === 'string') { const match = /^${FUNCTION_PLACEHOLDER_PREFIX}(\\d+)$/u.exec(value) if (match) return fns[+match[1]] ?? value } return value }` /* * `fn.toString()` of an object method shorthand returns `pattern(payload) { … }`, * which is not a valid expression, and the source is wrapped in parentheses * before it is emitted. Rewrite the shorthand forms — plain, `async`, generator, * and the computed or quoted keys — into a function expression, and leave the * sources that are already valid expressions untouched. */ const toFunctionExpression = (source: string): string => { if ( source.includes('=>') || /^(?:async\s+)?function\b/u.test(source) || source.startsWith('class ') ) return source const paramsIndex = source.indexOf('(') if (paramsIndex < 1) return source const isAsync = /^async\s/u.test(source) const isGenerator = /^(?:async\s+)?\*/u.test(source) return `${isAsync ? 'async ' : ''}function${ isGenerator ? '*' : '' }${source.slice(paramsIndex)}` } /** * Replace the functions of a theme data object with placeholders, and collect * their source into `fns` * * A function is wrapped as an expression, so an object method shorthand — which * is not a valid expression on its own — is rewritten to a function expression. * A `Date` becomes an ISO string, which is what JSON would have produced. The * keys starting with an underscore are skipped, as they are reserved by the * clients. * * 把主题数据对象中的函数替换为占位符,并把它们的源码收集到 `fns` 中 * * 函数会被包裹为表达式,因此本身不是合法表达式的对象方法简写会被改写为函数表达式。`Date` 会转换为 ISO 字符串,与 JSON * 的输出一致。以下划线开头的键会被跳过,它们被客户端保留使用。 * * @param value - The value to serialize / 需要序列化的值 * @param fns - The collected function sources / 收集到的函数源码 * @returns The value with the functions replaced by placeholders / 函数被替换为占位符的值 */ export const serializeFunctions = (value: unknown, fns: string[]): unknown => { if (Array.isArray(value)) return value.map((item) => serializeFunctions(item, fns)) // `JSON.stringify` calls `toJSON` on a `Date`, the object branch below would // drop it instead if (value instanceof Date) return value.toISOString() if (typeof value === 'object' && value != null) { return Object.keys(value).reduce>( (result, itemKey) => { // the keys with an underscore prefix are reserved if (itemKey[0] === '_') return result result[itemKey] = serializeFunctions( (value as Record)[itemKey], fns, ) return result }, {}, ) } if (typeof value === 'function') { const source = toFunctionExpression(value.toString()) return `${FUNCTION_PLACEHOLDER_PREFIX}${fns.push(`(${source})`) - 1}` } return value }