isr-engine 2.0.0 → 3.0.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.
- package/README.md +4 -10
- package/dist/{abVariantContext-Cqp-uxtd.cjs → abVariantContext-BcnxBn4V.cjs} +17 -257
- package/dist/abVariantContext-BcnxBn4V.cjs.map +1 -0
- package/dist/{abVariantContext-CWCdRSdG.js → abVariantContext-BmZZi1YZ.js} +12 -205
- package/dist/abVariantContext-BmZZi1YZ.js.map +1 -0
- package/dist/cli/cli.cjs +1 -1
- package/dist/cli/cli.js +1 -1
- package/dist/{createCacheInspectorMiddleware-B0Eiy7nh.js → createCacheInspectorMiddleware-BY6MX88X.js} +2 -2
- package/dist/{createCacheInspectorMiddleware-B0Eiy7nh.js.map → createCacheInspectorMiddleware-BY6MX88X.js.map} +1 -1
- package/dist/{createCacheInspectorMiddleware-1ZChBvIw.cjs → createCacheInspectorMiddleware-DZr98Zfn.cjs} +2 -2
- package/dist/{createCacheInspectorMiddleware-1ZChBvIw.cjs.map → createCacheInspectorMiddleware-DZr98Zfn.cjs.map} +1 -1
- package/dist/{createISRApp-DBichmCL.cjs → createISRApp-CHiiWF3P.cjs} +251 -22
- package/dist/createISRApp-CHiiWF3P.cjs.map +1 -0
- package/dist/{createISRApp-9PZON4FE.js → createISRApp-CS6XfjHl.js} +217 -18
- package/dist/createISRApp-CS6XfjHl.js.map +1 -0
- package/dist/{createImagePlugin-ClEnkrXE.cjs → createImagePlugin-BtJzr0t-.cjs} +2 -2
- package/dist/{createImagePlugin-ClEnkrXE.cjs.map → createImagePlugin-BtJzr0t-.cjs.map} +1 -1
- package/dist/{createImagePlugin-D15Xb8hZ.js → createImagePlugin-Ddo5t3dJ.js} +2 -2
- package/dist/{createImagePlugin-D15Xb8hZ.js.map → createImagePlugin-Ddo5t3dJ.js.map} +1 -1
- package/dist/isr-engine.cjs +47 -27
- package/dist/isr-engine.cjs.map +1 -1
- package/dist/isr-engine.js +42 -22
- package/dist/isr-engine.js.map +1 -1
- package/dist/metrics/PromMetrics.d.ts.map +1 -1
- package/dist/plugin/createDevCssHandoffPlugin.d.ts.map +1 -1
- package/dist/plugin/createIsrPlugin.d.ts.map +1 -1
- package/dist/rsc/index.cjs +2 -2
- package/dist/rsc/index.js +2 -2
- package/dist/rsc/revalidate.d.ts.map +1 -1
- package/dist/rsc/revalidationMetrics.d.ts +6 -0
- package/dist/rsc/revalidationMetrics.d.ts.map +1 -0
- package/dist/{rsc-lvWPTuVD.js → rsc-BSxvkPHd.js} +2 -2
- package/dist/{rsc-lvWPTuVD.js.map → rsc-BSxvkPHd.js.map} +1 -1
- package/dist/{rsc-H7D_meHu.cjs → rsc-NB-Uka7j.cjs} +2 -2
- package/dist/{rsc-H7D_meHu.cjs.map → rsc-NB-Uka7j.cjs.map} +1 -1
- package/package.json +7 -10
- package/src/defaults/runtime/dev-style-resource-dispatcher.server.ts +1 -1
- package/dist/abVariantContext-CWCdRSdG.js.map +0 -1
- package/dist/abVariantContext-Cqp-uxtd.cjs.map +0 -1
- package/dist/createISRApp-9PZON4FE.js.map +0 -1
- package/dist/createISRApp-DBichmCL.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"abVariantContext-BmZZi1YZ.js","names":[],"sources":["../src/logger/Logger.ts","../src/rsc/revalidationMetrics.ts","../src/rsc/revalidate.ts","../src/rsc/cacheTag.ts","../src/middlewares/abVariantContext.ts"],"sourcesContent":["import chalk from 'chalk';\nimport ora, { Ora } from 'ora';\nimport fs from 'fs';\nimport path from 'path';\nimport { getTraceId, getRequestId } from '../context/RequestContext';\n\nexport enum LogLevel {\n VERBOSE = 'verbose',\n DEBUG = 'debug',\n INFO = 'info',\n WARN = 'warn',\n ERROR = 'error',\n SUCCESS = 'success',\n}\n\nexport interface LoggerOptions {\n verbose?: boolean;\n logFile?: string;\n}\n\nexport class Logger {\n private static instance: Logger;\n private verboseMode: boolean = false;\n private logFile: string | null = null;\n private spinner: Ora | null = null;\n\n public static getInstance(options: LoggerOptions = {}): Logger {\n if (!Logger.instance) {\n Logger.instance = new Logger();\n }\n\n if (options.verbose !== undefined) {\n Logger.instance.verboseMode = options.verbose;\n }\n\n if (options.logFile !== undefined) {\n Logger.instance.logFile = options.logFile;\n try {\n const dir = path.dirname(options.logFile);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n } catch (error) {\n console.error('Failed to create log directory:', error);\n }\n }\n\n return Logger.instance;\n }\n\n private formatMessage(level: LogLevel, colorize: boolean, ...args: unknown[]): string {\n const timestamp = new Date().toISOString();\n const levelName = level.toUpperCase();\n const traceId = getTraceId();\n const requestId = getRequestId();\n\n let levelTag = `[${levelName}]`;\n let traceTag = `[${escapeLogValue(traceId)}]`;\n let requestTag = requestId !== 'unknown' ? `[${escapeLogValue(requestId)}]` : '';\n\n const message = args\n .map(arg => {\n if (arg instanceof Error) {\n return arg.stack || arg.message;\n }\n return typeof arg === 'object' ? (JSON.stringify(arg, null, 2) ?? '') : String(arg);\n })\n .map(escapeLogValue)\n .join(' ');\n\n if (colorize) {\n const levelColor = this.getLevelColor(level);\n levelTag = levelColor(levelTag);\n traceTag = chalk.cyan(traceTag);\n requestTag = requestTag ? chalk.blue(requestTag) : '';\n return `${chalk.gray(timestamp)} ${traceTag} ${requestTag} ${levelTag} ${message}`;\n }\n\n return `${timestamp} ${traceTag} ${requestTag} ${levelTag} ${message}`;\n }\n\n private getLevelColor(level: LogLevel) {\n switch (level) {\n case LogLevel.ERROR:\n return chalk.red.bold;\n case LogLevel.WARN:\n return chalk.yellow.bold;\n case LogLevel.SUCCESS:\n return chalk.green.bold;\n case LogLevel.INFO:\n return chalk.blue.bold;\n case LogLevel.DEBUG:\n return chalk.magenta;\n case LogLevel.VERBOSE:\n return chalk.gray;\n default:\n return chalk.white;\n }\n }\n\n private writeToFile(message: string) {\n if (this.logFile) {\n try {\n fs.appendFileSync(this.logFile, message + '\\n');\n } catch (error) {\n // Prevent infinite loop if logging fails\n process.stderr.write(`Failed to write to log file: ${error}\\n`);\n }\n }\n }\n\n public log(level: LogLevel, ...args: unknown[]) {\n if (this.spinner && this.spinner.isSpinning) {\n this.spinner.stop();\n }\n\n if (level === LogLevel.VERBOSE && !this.verboseMode) return;\n if (level === LogLevel.DEBUG && !this.verboseMode) return;\n\n // Console output\n console.log(this.formatMessage(level, true, ...args));\n\n // File output\n if (this.logFile) {\n this.writeToFile(this.formatMessage(level, false, ...args));\n }\n\n if (this.spinner && !this.spinner.isSpinning) {\n this.spinner.start();\n }\n }\n\n public error(...args: unknown[]) {\n this.log(LogLevel.ERROR, ...args);\n }\n\n public warn(...args: unknown[]) {\n this.log(LogLevel.WARN, ...args);\n }\n\n public info(...args: unknown[]) {\n this.log(LogLevel.INFO, ...args);\n }\n\n public success(...args: unknown[]) {\n this.log(LogLevel.SUCCESS, ...args);\n }\n\n public debug(...args: unknown[]) {\n this.log(LogLevel.DEBUG, ...args);\n }\n\n public verbose(...args: unknown[]) {\n this.log(LogLevel.VERBOSE, ...args);\n }\n\n public spin(message: string): Ora {\n if (this.spinner) {\n this.spinner.succeed();\n }\n this.spinner = ora(message).start();\n return this.spinner;\n }\n\n public stopSpinner(message?: string, success: boolean = true) {\n if (this.spinner) {\n if (success) {\n this.spinner.succeed(message);\n } else {\n this.spinner.fail(message);\n }\n this.spinner = null;\n }\n }\n}\n\nfunction escapeLogValue(value: string): string {\n return Array.from(value, character => {\n const code = character.charCodeAt(0);\n if (character === '\\n') return '\\\\n';\n if (character === '\\r') return '\\\\r';\n if (code < 0x20 || (code >= 0x7f && code <= 0x9f) || code === 0x2028 || code === 0x2029) {\n return `\\\\u${code.toString(16).padStart(4, '0')}`;\n }\n return character;\n }).join('');\n}\n","type RevalidationMetricRecorder = (\n event: 'run' | 'failure',\n kind: 'path' | 'tag',\n target: string\n) => void;\n\nconst RECORDER_KEY = Symbol.for('isr-engine:revalidation-metric-recorder');\nconst runtime = globalThis as typeof globalThis & {\n [RECORDER_KEY]?: RevalidationMetricRecorder;\n};\n\n/** The Node origin owns the metrics registry, including events from the separate Vite RSC graph. */\nexport function setRevalidationMetricRecorder(recorder: RevalidationMetricRecorder): void {\n runtime[RECORDER_KEY] = recorder;\n}\n\nexport function recordRevalidationMetric(...args: Parameters<RevalidationMetricRecorder>): void {\n runtime[RECORDER_KEY]?.(...args);\n}\n","/**\n * 缓存失效契约 —— `revalidatePath(path)` 按路径精准失效;`revalidateTag(tag)` 按渲染期声明的 tag 失效\n *\n * 跨环境状态共享:\n * Server Action 在 Vite 的 `rsc` 环境中执行(模块图 A),\n * 而 ISR 缓存中间件注册 invalidator 在 Node 上下文(模块图 B),\n * 两份模块图下,同名模块可能各自持有独立的 ES 模块状态。\n * 因此本模块把 invalidator 注册表挂在 `globalThis` 上作为跨环境单例,\n * 确保 `revalidatePath/Tag` 调用能分发到所有已注册的 invalidator。\n *\n * 失败语义(v2.0.x 起):\n * 过去版本用 `Promise.all`,**首个失败的 invalidator 会抛出,剩余的可能仍在执行\n * 但 reject 被吞**——多 invalidator 场景下出现\"看似成功但部分缓存没清\"的脏状态。\n * 现在改为:\n * 1. `Promise.allSettled` 让所有 invalidator 都跑到底\n * 2. 每个失败单独打 metric + log(含 trace 上下文)\n * 3. 整体 ≥ 1 个失败 → 抛聚合 `RevalidationError`(含 successCount/failureCount/causes)\n * 调用方(Server Action)务必 `try { await revalidateTag(...) } catch (e) { ... }`,\n * 否则用户提交后看到的是 200 但底层有部分 cache 未清——这种\"沉默错误\"比抛错更危险。\n *\n * 用法:\n * 1. Server Action 内部调用 `revalidatePath('/books')` 或 `revalidateTag('books')`\n * 2. ISR cache 中间件 / ISREngine 启动时通过 `registerInvalidator(fn)` 注册\n * 3. 分发到所有注册的 invalidator,清理对应缓存条目\n *\n * 注意:\n * - 本模块不持有任何缓存实现,纯做路由分发\n * - 若未注册 invalidator(例如脱离 engine 的纯 RSC 场景),调用静默为 no-op\n */\n\nimport { Logger } from '../logger/Logger';\nimport { recordRevalidationMetric } from './revalidationMetrics';\n\nconst logger = Logger.getInstance();\n\n/** Invalidator 签名:接收失效目标描述 */\nexport interface RevalidateInvalidator {\n (target: { kind: 'path'; value: string } | { kind: 'tag'; value: string }): Promise<void> | void;\n}\n\n/** 全局单例 key(Symbol.for 保证跨模块图复用同一注册表) */\nconst REGISTRY_KEY = Symbol.for('isr-engine:revalidate-registry');\n\ntype GlobalWithRegistry = typeof globalThis & {\n [REGISTRY_KEY]?: Set<RevalidateInvalidator>;\n};\n\nfunction getRegistry(): Set<RevalidateInvalidator> {\n const g = globalThis as GlobalWithRegistry;\n if (!g[REGISTRY_KEY]) {\n g[REGISTRY_KEY] = new Set<RevalidateInvalidator>();\n }\n return g[REGISTRY_KEY];\n}\n\n/**\n * 注册一个 invalidator 实例(通常由 ISR 缓存中间件 / ISREngine 调用)\n * 返回取消注册的函数\n */\nexport function registerInvalidator(fn: RevalidateInvalidator): () => void {\n const registry = getRegistry();\n registry.add(fn);\n return () => {\n registry.delete(fn);\n };\n}\n\n/**\n * 聚合失效错误 —— 当一个或多个 invalidator 失败时抛出。\n *\n * 含:\n * - successCount / failureCount:方便调用方决定补偿策略\n * - causes:每个失败的原始 Error(按注册顺序)\n * - target:触发本次 revalidate 的描述('tag:books' / 'path:/books')\n *\n * 注意:用 `extends Error` 而非 `AggregateError`,因为 AggregateError 在某些 Node\n * 版本对 stack/message 序列化不稳,自定义 class 更可控且 instanceof 检测可靠。\n */\nexport class RevalidationError extends Error {\n public readonly target: string;\n public readonly successCount: number;\n public readonly failureCount: number;\n public readonly causes: readonly Error[];\n\n constructor(\n target: string,\n successCount: number,\n failureCount: number,\n causes: readonly Error[]\n ) {\n super(\n `revalidate(${target}) —— ${failureCount} invalidator(s) failed, ` +\n `${successCount} succeeded. First cause: ${causes[0]?.message ?? '(unknown)'}`\n );\n this.name = 'RevalidationError';\n this.target = target;\n this.successCount = successCount;\n this.failureCount = failureCount;\n this.causes = causes;\n }\n}\n\ntype RevalidateTarget = { kind: 'path'; value: string } | { kind: 'tag'; value: string };\n\n/**\n * 内部统一分发:跑所有 invalidator,把失败聚合成 RevalidationError 抛出。\n *\n * `Promise.allSettled` 保证任意 invalidator 抛错都不会中断其他 invalidator 的执行——\n * 这样即使 Redis 回源失败,进程内 LRU 至少能清干净;进程内 LRU 失败也不会拖累 Redis。\n */\nasync function dispatch(target: RevalidateTarget): Promise<void> {\n const registry = getRegistry();\n const targetLabel = `${target.kind}:${target.value}`;\n if (registry.size === 0) {\n logger.debug(`revalidate(${targetLabel}) —— 无 invalidator 注册,忽略`);\n return;\n }\n\n recordRevalidationMetric('run', target.kind, target.value);\n\n // 包一层 async 函数:把同步抛错也转成 Promise rejection,让 allSettled 能统一处理\n // (直接 `fn(target)` 在 fn 同步抛错时会在 `.map` 里 escape,allSettled 收不到)\n const invalidators = Array.from(registry);\n const results = await Promise.allSettled(invalidators.map(async fn => fn(target)));\n\n const causes: Error[] = [];\n let successCount = 0;\n let failureCount = 0;\n\n results.forEach((r, idx) => {\n if (r.status === 'fulfilled') {\n successCount++;\n return;\n }\n failureCount++;\n const err = r.reason instanceof Error ? r.reason : new Error(String(r.reason));\n causes.push(err);\n recordRevalidationMetric('failure', target.kind, target.value);\n // 单独 log 每个失败,方便从 stack 定位是哪个 invalidator\n logger.error(`[revalidate] invalidator #${idx} failed for ${targetLabel}: ${err.message}`, err);\n });\n\n if (failureCount > 0) {\n throw new RevalidationError(targetLabel, successCount, failureCount, causes);\n }\n\n logger.debug(\n `✅ revalidate(${targetLabel}) —— 已分发到 ${registry.size} 个 invalidator(全部成功)`\n );\n}\n\n/**\n * 使指定路径的缓存失效\n *\n * @param path 形如 '/books' / '/posts/42' 的路径\n * @throws {RevalidationError} 任意 invalidator 失败时(其余仍执行完毕)\n */\nexport async function revalidatePath(path: string): Promise<void> {\n await dispatch({ kind: 'path', value: path });\n}\n\n/**\n * 使指定 tag 标记的所有缓存条目失效\n *\n * @param tag 业务语义 tag(如 'books' / `book:${id}`)\n * @throws {RevalidationError} 任意 invalidator 失败时(其余仍执行完毕)\n */\nexport async function revalidateTag(tag: string): Promise<void> {\n await dispatch({ kind: 'tag', value: tag });\n}\n","/**\n * 缓存 Tag 上下文 —— 支持 Server Component 在渲染期声明 tag,便于后续 revalidateTag 精细失效\n *\n * 协作模型:\n * 1. ISR 缓存中间件在进入 handler 前 `runWithTagStore(() => rscHandler(request))`\n * —— 给本次请求开一个 AsyncLocalStorage 作用域,内部放 `{ tags: Set<string> }`\n * 2. Server Component 体内任意位置调用 `cacheTag('books', `book:${id}`)`\n * → 写入当前作用域的 tags Set\n * 3. 响应捕获阶段 `collectTags()` 读出 tag 列表,写入 CachedEntry.tags\n * 4. `revalidateTag('books')` 被 invalidator 接收后,遍历 cache 条目,\n * 命中 tags 列表的精准清除(无副作用污染其他条目)\n *\n * 跨环境状态共享:\n * Server Component 在 Vite `rsc` 环境执行(模块图 A),\n * ISR 缓存中间件在 Node(模块图 B)。\n * ES 模块作用域的 `new AsyncLocalStorage()` 会被双模块图各持有一份副本,\n * 导致 cacheTag 写入的 store 与 collectTags 读取的 store 不互通。\n * 故本模块把 ALS 实例挂在 `globalThis` 上作为跨模块图单例(Symbol.for key)\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { Logger } from '../logger/Logger';\n\nconst logger = Logger.getInstance();\n\ninterface TagStore {\n tags: Set<string>;\n /** 本次渲染过程中是否被显式标记为不可缓存(例如上游 fetch 失败) */\n uncacheable: boolean;\n}\n\nconst ALS_KEY = Symbol.for('isr-engine:cache-tag-als');\n\ntype GlobalWithALS = typeof globalThis & {\n [ALS_KEY]?: AsyncLocalStorage<TagStore>;\n};\n\nfunction getALS(): AsyncLocalStorage<TagStore> {\n const g = globalThis as GlobalWithALS;\n if (!g[ALS_KEY]) {\n g[ALS_KEY] = new AsyncLocalStorage<TagStore>();\n }\n return g[ALS_KEY];\n}\n\n/**\n * 在独立的 tag 作用域中执行 fn —— 通常由 ISR 缓存中间件在每次请求前调用\n *\n * fn 内部以及 fn 启动的任何 async/Promise 链路内,调用 cacheTag(...) 都会\n * 写入本作用域,不会污染父作用域或兄弟请求\n */\nexport function runWithTagStore<T>(fn: () => T | Promise<T>): T | Promise<T> {\n return getALS().run({ tags: new Set<string>(), uncacheable: false }, fn);\n}\n\n/**\n * 在 Server Component / loader 内显式声明本次渲染产物**不应入缓存**。\n * 适用场景:上游接口失败、降级渲染了一段错误提示 UI、命中风控/限流等\n * —— 渲染结果是 200,但内容会让用户困惑或马上过期,不应被 ISR HIT 反复回放。\n *\n * 调用一次即可;后续 cacheTag(...) 仍可继续调用但不会改变 uncacheable 决定。\n */\nexport function markUncacheable(): void {\n const store = getALS().getStore();\n if (store) {\n store.uncacheable = true;\n }\n}\n\n/** 读取本次渲染是否被标记为不可缓存(ISR 缓存中间件在响应捕获阶段调用) */\nexport function isUncacheable(): boolean {\n return getALS().getStore()?.uncacheable === true;\n}\n\n/**\n * Server Component / server action / server-only util 内声明:\n * 本次渲染/调用产出的缓存条目应关联以下 tag\n *\n * 多次调用会合并 tag;无 tag 作用域(例如脱离缓存中间件时)静默忽略\n */\nexport function cacheTag(...tags: string[]): void {\n const store = getALS().getStore();\n if (!store) {\n return;\n }\n for (const tag of tags) {\n if (typeof tag === 'string' && tag.length > 0) {\n store.tags.add(tag);\n }\n }\n}\n\n/**\n * 读取当前 tag 作用域的 tag 列表(ISR 缓存中间件在响应捕获阶段调用)\n */\nexport function collectTags(): string[] {\n const store = getALS().getStore();\n return store ? Array.from(store.tags) : [];\n}\n\n/**\n * 调试:打印当前 tag store 状态\n */\nexport function debugTagStore(label = ''): void {\n const store = getALS().getStore();\n logger.debug(\n `[cacheTag] ${label} store=${store ? JSON.stringify(Array.from(store.tags)) : '<none>'}`\n );\n}\n","/**\n * A/B variant 在 Server Component 里读取的 helper —— 与 express middleware 解耦\n *\n * RSC 环境通过本文件 import(不引入 express 类型,bundle 更轻);\n * Express 中间件在 ABVariantMiddleware.ts。\n */\nimport { getRequestContext } from '../context/RequestContext';\n\n/**\n * 在 Server Component 里读取 variant\n *\n * 不在 A/B middleware 后调用 → 返回 undefined\n */\nexport function getVariant(experimentName: string): string | undefined {\n const ctx = getRequestContext();\n const v = ctx?.flags?.[experimentName];\n return typeof v === 'string' ? v : undefined;\n}\n"],"mappings":";;;;;;;AAoBA,IAAa,SAAb,MAAa,OAAO;CAClB,OAAe;CACf,cAA+B;CAC/B,UAAiC;CACjC,UAA8B;CAE9B,OAAc,YAAY,UAAyB,CAAC,GAAW;EAC7D,IAAI,CAAC,OAAO,UACV,OAAO,WAAW,IAAI,OAAO;EAG/B,IAAI,QAAQ,YAAY,KAAA,GACtB,OAAO,SAAS,cAAc,QAAQ;EAGxC,IAAI,QAAQ,YAAY,KAAA,GAAW;GACjC,OAAO,SAAS,UAAU,QAAQ;GAClC,IAAI;IACF,MAAM,MAAM,KAAK,QAAQ,QAAQ,OAAO;IACxC,IAAI,CAAC,GAAG,WAAW,GAAG,GACpB,GAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;GAEzC,SAAS,OAAO;IACd,QAAQ,MAAM,mCAAmC,KAAK;GACxD;EACF;EAEA,OAAO,OAAO;CAChB;CAEA,cAAsB,OAAiB,UAAmB,GAAG,MAAyB;EACpF,MAAM,6BAAY,IAAI,KAAK,EAAA,CAAE,YAAY;EACzC,MAAM,YAAY,MAAM,YAAY;EACpC,MAAM,UAAU,WAAW;EAC3B,MAAM,YAAY,aAAa;EAE/B,IAAI,WAAW,IAAI,UAAU;EAC7B,IAAI,WAAW,IAAI,eAAe,OAAO,EAAE;EAC3C,IAAI,aAAa,cAAc,YAAY,IAAI,eAAe,SAAS,EAAE,KAAK;EAE9E,MAAM,UAAU,KACb,KAAI,QAAO;GACV,IAAI,eAAe,OACjB,OAAO,IAAI,SAAS,IAAI;GAE1B,OAAO,OAAO,QAAQ,WAAY,KAAK,UAAU,KAAK,MAAM,CAAC,KAAK,KAAM,OAAO,GAAG;EACpF,CAAC,CAAC,CACD,IAAI,cAAc,CAAC,C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QAAQ,OAAO,CAAC,CAAC,SAAS;CAChC,OAAO,QAAQ,MAAM,KAAK,MAAM,IAAI,IAAI,CAAC;AAC3C;;;;AAKA,SAAgB,cAAc,QAAQ,IAAU;CAC9C,MAAM,QAAQ,OAAO,CAAC,CAAC,SAAS;CAChC,OAAO,MACL,cAAc,MAAM,SAAS,QAAQ,KAAK,UAAU,MAAM,KAAK,MAAM,IAAI,CAAC,IAAI,UAChF;AACF;;;;;;;;;;;;;;AChGA,SAAgB,WAAW,gBAA4C;CAErE,MAAM,IADM,kBACF,CAAA,EAAK,QAAQ;CACvB,OAAO,OAAO,MAAM,WAAW,IAAI,KAAA;AACrC"}
|
package/dist/cli/cli.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
const require_rolldown_runtime = require("../rolldown-runtime-DakpK96I.cjs");
|
|
3
|
-
const require_createISRApp = require("../createISRApp-
|
|
3
|
+
const require_createISRApp = require("../createISRApp-CHiiWF3P.cjs");
|
|
4
4
|
let node_path = require("node:path");
|
|
5
5
|
let node_fs_promises = require("node:fs/promises");
|
|
6
6
|
let node_http = require("node:http");
|
package/dist/cli/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { B as logger, C as loadConfig, H as package_default, V as DEFAULT_PORT, d as startServer, f as createProductionRuntime, p as prepareProductionBuild, t as createISRApp, u as closeServer } from "../createISRApp-CS6XfjHl.js";
|
|
3
3
|
import { extname, join, resolve, sep } from "node:path";
|
|
4
4
|
import { open, readFile } from "node:fs/promises";
|
|
5
5
|
import http from "node:http";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as createOpsAuthMiddleware } from "./createISRApp-
|
|
1
|
+
import { S as createOpsAuthMiddleware } from "./createISRApp-CS6XfjHl.js";
|
|
2
2
|
/** L1 单次响应最多条目数(硬上限),避免极端情况返回 5MB+ JSON */
|
|
3
3
|
var HARD_LIMIT = 1e3;
|
|
4
4
|
/** L1 默认 limit */
|
|
@@ -102,4 +102,4 @@ function createCacheInspectorMiddleware(handler, opsConfig) {
|
|
|
102
102
|
//#endregion
|
|
103
103
|
export { createCacheInspectorMiddleware };
|
|
104
104
|
|
|
105
|
-
//# sourceMappingURL=createCacheInspectorMiddleware-
|
|
105
|
+
//# sourceMappingURL=createCacheInspectorMiddleware-BY6MX88X.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCacheInspectorMiddleware-
|
|
1
|
+
{"version":3,"file":"createCacheInspectorMiddleware-BY6MX88X.js","names":[],"sources":["../src/plugin/createCacheInspectorMiddleware.ts"],"sourcesContent":["/**\n * ISR cache inventory 端点 —— 暴露当前 L1 缓存条目元数据 + 最近 invalidate 时间。\n *\n * 用途:回答 “这一刻,哪些页面的缓存是 stale?某 path/tag 上次什么时候被 revalidate?”\n * 这类 *库存视角* 问题。流量视角(按路由 cache 状态分布)走 Prometheus\n * `isr_http_requests_total{cache=\"STALE\",route=...}`;本端点是补充而非替代。\n *\n * 边界(明确写在这里防止滑坡):\n * ✅ 只读 L1(in-process LRU),永不 SCAN Redis(SCAN 阻塞,量大不该走 engine)\n * ✅ 只返回元数据:key / 时间戳 / size / tags;body 一字节都不返回\n * ✅ 只给 JSON,不给 HTML 浏览器(漂亮 UI 走业务自建或单独包)\n * ✅ 鉴权复用 opsConfig.authToken,不引入 SSO/RBAC(那是业务网关的事)\n * ✅ 端点路径 /__isr/cache/inventory 已在 isrCacheMiddleware.isBypassPath 列表,\n * 自身永远不会被 ISR 缓存\n *\n * 查询参数:\n * ?status=fresh|stale|expired|all 过滤 L1 条目状态(默认 all)\n * ?limit=N L1 条目数上限(默认 100,硬上限 1000)\n * ?l2=true|false 是否包含 L2(Redis)SCAN 视图(默认 true,\n * hybrid 模式才有内容;memory 模式恒为 [] 不发请求)\n * ?l2Limit=N L2 SCAN 条目数上限(默认 200,硬上限 500,防 SCAN 流量过大)\n *\n * 响应示例(hybrid 模式):\n * {\n * \"now\": 1715760000000,\n * \"backend\": \"hybrid\",\n * \"size\": 234, // L1 条目数\n * \"max\": 1000, // L1 容量\n * \"filtered\": 12, // L1 过滤后条目数\n * \"entries\": [...], // L1 条目(含 fresh/stale/expired 状态)\n * \"invalidations\": [...], // 最近 invalidate 时间\n * \"l2\": {\n * \"scanned\": 234,\n * \"items\": [\n * { \"key\": \"GET:/books/1\", \"sizeBytes\": 12450, \"ttlSecondsRemaining\": 1800, \"onlyInL2\": false },\n * { \"key\": \"GET:/cold-page\", \"sizeBytes\": 800, \"ttlSecondsRemaining\": 7200, \"onlyInL2\": true }\n * ]\n * }\n * }\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Connect } from 'vite';\nimport type { IsrCacheHandler, IsrCacheInspectionEntry } from './isrCacheMiddleware';\nimport type { ResolvedOpsConfig } from '../server/opsConfig';\nimport { createOpsAuthMiddleware } from '../server/opsConfig';\n\n/** Inventory 端点路径常量 —— 与 isrCacheMiddleware.isBypassPath 中的 /__isr 前缀对齐 */\nexport const CACHE_INVENTORY_PATH = '/__isr/cache/inventory';\n\n/** L1 单次响应最多条目数(硬上限),避免极端情况返回 5MB+ JSON */\nconst HARD_LIMIT = 1000;\n/** L1 默认 limit */\nconst DEFAULT_LIMIT = 100;\n/** L2 SCAN 单次返回硬上限 —— 比 L1 更严,因为每个 entry 一次 STRLEN+TTL 是 2 个 Redis 命令 */\nconst L2_HARD_LIMIT = 500;\n/** L2 默认 limit */\nconst L2_DEFAULT_LIMIT = 200;\n\ntype StatusFilter = 'fresh' | 'stale' | 'expired' | 'all';\n\nfunction parseStatusFilter(raw: string | null): StatusFilter {\n if (raw === 'fresh' || raw === 'stale' || raw === 'expired' || raw === 'all') return raw;\n return 'all';\n}\n\nfunction parseLimit(raw: string | null): number {\n if (!raw) return DEFAULT_LIMIT;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n <= 0) return DEFAULT_LIMIT;\n return Math.min(n, HARD_LIMIT);\n}\n\nfunction parseL2Limit(raw: string | null): number {\n if (!raw) return L2_DEFAULT_LIMIT;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n <= 0) return L2_DEFAULT_LIMIT;\n return Math.min(n, L2_HARD_LIMIT);\n}\n\nfunction parseBoolFlag(raw: string | null, defaultValue: boolean): boolean {\n if (raw === null) return defaultValue;\n const v = raw.toLowerCase();\n if (v === 'true' || v === '1' || v === 'yes') return true;\n if (v === 'false' || v === '0' || v === 'no') return false;\n return defaultValue;\n}\n\n/**\n * 创建 inventory 中间件。\n *\n * 必须在 ISR cache middleware 之前挂(路径已在 isBypassPath 但提前挂可以避开\n * cache handler 内部 metric 记录这次 admin 请求)。\n *\n * @param handler ISR cache handler,必须支持 getCacheInspection()\n * @param opsConfig resolveOpsConfig 的输出 —— inventory.enabled 控制端点是否生效\n */\nexport function createCacheInspectorMiddleware(\n handler: IsrCacheHandler,\n opsConfig: ResolvedOpsConfig\n): Connect.NextHandleFunction {\n // disabled 时直接返回 no-op,运行期不引入任何分支开销\n if (!opsConfig.inventory.enabled) {\n return (_req, _res, next) => next();\n }\n\n const auth = createOpsAuthMiddleware('inventory', opsConfig);\n\n return (req: IncomingMessage, res: ServerResponse, next: Connect.NextFunction) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n // 用 URL 解析路径(剥 query string)。req.url 一定有,但形态可能含 query。\n const url = req.url ?? '/';\n const pathOnly = url.split('?')[0];\n if (pathOnly !== CACHE_INVENTORY_PATH) {\n next();\n return;\n }\n\n // 鉴权 —— public=true 时 createOpsAuthMiddleware 返回 noop next()\n auth(req as never, res as never, () => {\n void respond(req, res, handler);\n });\n };\n\n async function respond(\n req: IncomingMessage,\n res: ServerResponse,\n h: IsrCacheHandler\n ): Promise<void> {\n try {\n const snapshot = h.getCacheInspection();\n const params = new URLSearchParams((req.url ?? '').split('?')[1] ?? '');\n const statusFilter = parseStatusFilter(params.get('status'));\n const limit = parseLimit(params.get('limit'));\n const includeL2 = parseBoolFlag(params.get('l2'), true);\n const l2Limit = parseL2Limit(params.get('l2Limit'));\n\n const filtered: IsrCacheInspectionEntry[] =\n statusFilter === 'all'\n ? snapshot.entries\n : snapshot.entries.filter(e => e.status === statusFilter);\n\n // 排序:fresh 先返回最新入缓存的;stale/expired 先返回最旧的(最该被关注)。\n // 对于 all:按 ageSeconds 降序(旧的优先),方便排错时一眼看到长期未刷新的条目。\n const sorted = [...filtered].sort((a, b) => b.ageSeconds - a.ageSeconds);\n const limited = sorted.slice(0, limit);\n\n const sortedInvalidations = [...snapshot.invalidations].sort(\n (a, b) => b.lastInvalidatedMs - a.lastInvalidatedMs\n );\n\n // L2 视图(仅 hybrid 模式有内容)—— 异步 SCAN 拉取\n const l2Items =\n includeL2 && snapshot.backend === 'hybrid' ? await h.getL2Inspection(l2Limit) : [];\n\n const body = JSON.stringify(\n {\n now: snapshot.now,\n backend: snapshot.backend,\n size: snapshot.size,\n max: snapshot.max,\n filter: { status: statusFilter, limit, l2: includeL2, l2Limit },\n filtered: filtered.length,\n entries: limited,\n invalidations: sortedInvalidations,\n l2: { scanned: l2Items.length, items: l2Items },\n },\n null,\n 2\n );\n\n if (res.headersSent) return;\n res.statusCode = 200;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(body);\n } catch (err) {\n if (res.headersSent) return;\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.end(JSON.stringify({ error: (err as Error).message }));\n }\n }\n}\n"],"mappings":";;AAkDA,IAAM,aAAa;;AAEnB,IAAM,gBAAgB;;AAEtB,IAAM,gBAAgB;;AAEtB,IAAM,mBAAmB;AAIzB,SAAS,kBAAkB,KAAkC;CAC3D,IAAI,QAAQ,WAAW,QAAQ,WAAW,QAAQ,aAAa,QAAQ,OAAO,OAAO;CACrF,OAAO;AACT;AAEA,SAAS,WAAW,KAA4B;CAC9C,IAAI,CAAC,KAAK,OAAO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响应最多条目数(硬上限),避免极端情况返回 5MB+ JSON */
|
|
3
3
|
var HARD_LIMIT = 1e3;
|
|
4
4
|
/** L1 默认 limit */
|
|
@@ -102,4 +102,4 @@ function createCacheInspectorMiddleware(handler, opsConfig) {
|
|
|
102
102
|
//#endregion
|
|
103
103
|
exports.createCacheInspectorMiddleware = createCacheInspectorMiddleware;
|
|
104
104
|
|
|
105
|
-
//# sourceMappingURL=createCacheInspectorMiddleware-
|
|
105
|
+
//# sourceMappingURL=createCacheInspectorMiddleware-DZr98Zfn.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createCacheInspectorMiddleware-
|
|
1
|
+
{"version":3,"file":"createCacheInspectorMiddleware-DZr98Zfn.cjs","names":[],"sources":["../src/plugin/createCacheInspectorMiddleware.ts"],"sourcesContent":["/**\n * ISR cache inventory 端点 —— 暴露当前 L1 缓存条目元数据 + 最近 invalidate 时间。\n *\n * 用途:回答 “这一刻,哪些页面的缓存是 stale?某 path/tag 上次什么时候被 revalidate?”\n * 这类 *库存视角* 问题。流量视角(按路由 cache 状态分布)走 Prometheus\n * `isr_http_requests_total{cache=\"STALE\",route=...}`;本端点是补充而非替代。\n *\n * 边界(明确写在这里防止滑坡):\n * ✅ 只读 L1(in-process LRU),永不 SCAN Redis(SCAN 阻塞,量大不该走 engine)\n * ✅ 只返回元数据:key / 时间戳 / size / tags;body 一字节都不返回\n * ✅ 只给 JSON,不给 HTML 浏览器(漂亮 UI 走业务自建或单独包)\n * ✅ 鉴权复用 opsConfig.authToken,不引入 SSO/RBAC(那是业务网关的事)\n * ✅ 端点路径 /__isr/cache/inventory 已在 isrCacheMiddleware.isBypassPath 列表,\n * 自身永远不会被 ISR 缓存\n *\n * 查询参数:\n * ?status=fresh|stale|expired|all 过滤 L1 条目状态(默认 all)\n * ?limit=N L1 条目数上限(默认 100,硬上限 1000)\n * ?l2=true|false 是否包含 L2(Redis)SCAN 视图(默认 true,\n * hybrid 模式才有内容;memory 模式恒为 [] 不发请求)\n * ?l2Limit=N L2 SCAN 条目数上限(默认 200,硬上限 500,防 SCAN 流量过大)\n *\n * 响应示例(hybrid 模式):\n * {\n * \"now\": 1715760000000,\n * \"backend\": \"hybrid\",\n * \"size\": 234, // L1 条目数\n * \"max\": 1000, // L1 容量\n * \"filtered\": 12, // L1 过滤后条目数\n * \"entries\": [...], // L1 条目(含 fresh/stale/expired 状态)\n * \"invalidations\": [...], // 最近 invalidate 时间\n * \"l2\": {\n * \"scanned\": 234,\n * \"items\": [\n * { \"key\": \"GET:/books/1\", \"sizeBytes\": 12450, \"ttlSecondsRemaining\": 1800, \"onlyInL2\": false },\n * { \"key\": \"GET:/cold-page\", \"sizeBytes\": 800, \"ttlSecondsRemaining\": 7200, \"onlyInL2\": true }\n * ]\n * }\n * }\n */\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Connect } from 'vite';\nimport type { IsrCacheHandler, IsrCacheInspectionEntry } from './isrCacheMiddleware';\nimport type { ResolvedOpsConfig } from '../server/opsConfig';\nimport { createOpsAuthMiddleware } from '../server/opsConfig';\n\n/** Inventory 端点路径常量 —— 与 isrCacheMiddleware.isBypassPath 中的 /__isr 前缀对齐 */\nexport const CACHE_INVENTORY_PATH = '/__isr/cache/inventory';\n\n/** L1 单次响应最多条目数(硬上限),避免极端情况返回 5MB+ JSON */\nconst HARD_LIMIT = 1000;\n/** L1 默认 limit */\nconst DEFAULT_LIMIT = 100;\n/** L2 SCAN 单次返回硬上限 —— 比 L1 更严,因为每个 entry 一次 STRLEN+TTL 是 2 个 Redis 命令 */\nconst L2_HARD_LIMIT = 500;\n/** L2 默认 limit */\nconst L2_DEFAULT_LIMIT = 200;\n\ntype StatusFilter = 'fresh' | 'stale' | 'expired' | 'all';\n\nfunction parseStatusFilter(raw: string | null): StatusFilter {\n if (raw === 'fresh' || raw === 'stale' || raw === 'expired' || raw === 'all') return raw;\n return 'all';\n}\n\nfunction parseLimit(raw: string | null): number {\n if (!raw) return DEFAULT_LIMIT;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n <= 0) return DEFAULT_LIMIT;\n return Math.min(n, HARD_LIMIT);\n}\n\nfunction parseL2Limit(raw: string | null): number {\n if (!raw) return L2_DEFAULT_LIMIT;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n <= 0) return L2_DEFAULT_LIMIT;\n return Math.min(n, L2_HARD_LIMIT);\n}\n\nfunction parseBoolFlag(raw: string | null, defaultValue: boolean): boolean {\n if (raw === null) return defaultValue;\n const v = raw.toLowerCase();\n if (v === 'true' || v === '1' || v === 'yes') return true;\n if (v === 'false' || v === '0' || v === 'no') return false;\n return defaultValue;\n}\n\n/**\n * 创建 inventory 中间件。\n *\n * 必须在 ISR cache middleware 之前挂(路径已在 isBypassPath 但提前挂可以避开\n * cache handler 内部 metric 记录这次 admin 请求)。\n *\n * @param handler ISR cache handler,必须支持 getCacheInspection()\n * @param opsConfig resolveOpsConfig 的输出 —— inventory.enabled 控制端点是否生效\n */\nexport function createCacheInspectorMiddleware(\n handler: IsrCacheHandler,\n opsConfig: ResolvedOpsConfig\n): Connect.NextHandleFunction {\n // disabled 时直接返回 no-op,运行期不引入任何分支开销\n if (!opsConfig.inventory.enabled) {\n return (_req, _res, next) => next();\n }\n\n const auth = createOpsAuthMiddleware('inventory', opsConfig);\n\n return (req: IncomingMessage, res: ServerResponse, next: Connect.NextFunction) => {\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n next();\n return;\n }\n // 用 URL 解析路径(剥 query string)。req.url 一定有,但形态可能含 query。\n const url = req.url ?? '/';\n const pathOnly = url.split('?')[0];\n if (pathOnly !== CACHE_INVENTORY_PATH) {\n next();\n return;\n }\n\n // 鉴权 —— public=true 时 createOpsAuthMiddleware 返回 noop next()\n auth(req as never, res as never, () => {\n void respond(req, res, handler);\n });\n };\n\n async function respond(\n req: IncomingMessage,\n res: ServerResponse,\n h: IsrCacheHandler\n ): Promise<void> {\n try {\n const snapshot = h.getCacheInspection();\n const params = new URLSearchParams((req.url ?? '').split('?')[1] ?? '');\n const statusFilter = parseStatusFilter(params.get('status'));\n const limit = parseLimit(params.get('limit'));\n const includeL2 = parseBoolFlag(params.get('l2'), true);\n const l2Limit = parseL2Limit(params.get('l2Limit'));\n\n const filtered: IsrCacheInspectionEntry[] =\n statusFilter === 'all'\n ? snapshot.entries\n : snapshot.entries.filter(e => e.status === statusFilter);\n\n // 排序:fresh 先返回最新入缓存的;stale/expired 先返回最旧的(最该被关注)。\n // 对于 all:按 ageSeconds 降序(旧的优先),方便排错时一眼看到长期未刷新的条目。\n const sorted = [...filtered].sort((a, b) => b.ageSeconds - a.ageSeconds);\n const limited = sorted.slice(0, limit);\n\n const sortedInvalidations = [...snapshot.invalidations].sort(\n (a, b) => b.lastInvalidatedMs - a.lastInvalidatedMs\n );\n\n // L2 视图(仅 hybrid 模式有内容)—— 异步 SCAN 拉取\n const l2Items =\n includeL2 && snapshot.backend === 'hybrid' ? await h.getL2Inspection(l2Limit) : [];\n\n const body = JSON.stringify(\n {\n now: snapshot.now,\n backend: snapshot.backend,\n size: snapshot.size,\n max: snapshot.max,\n filter: { status: statusFilter, limit, l2: includeL2, l2Limit },\n filtered: filtered.length,\n entries: limited,\n invalidations: sortedInvalidations,\n l2: { scanned: l2Items.length, items: l2Items },\n },\n null,\n 2\n );\n\n if (res.headersSent) return;\n res.statusCode = 200;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.setHeader('cache-control', 'no-store');\n res.end(body);\n } catch (err) {\n if (res.headersSent) return;\n res.statusCode = 500;\n res.setHeader('content-type', 'application/json; charset=utf-8');\n res.end(JSON.stringify({ error: (err as Error).message }));\n }\n }\n}\n"],"mappings":";;AAkDA,IAAM,aAAa;;AAEnB,IAAM,gBAAgB;;AAEtB,IAAM,gBAAgB;;AAEtB,IAAM,mBAAmB;AAIzB,SAAS,kBAAkB,KAAkC;CAC3D,IAAI,QAAQ,WAAW,QAAQ,WAAW,QAAQ,aAAa,QAAQ,OAAO,OAAO;C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("./rolldown-runtime-DakpK96I.cjs");
|
|
2
2
|
const require_RequestContext = require("./RequestContext-DgGEAxcW.cjs");
|
|
3
|
-
const require_abVariantContext = require("./abVariantContext-
|
|
3
|
+
const require_abVariantContext = require("./abVariantContext-BcnxBn4V.cjs");
|
|
4
4
|
const require_i18n = require("./i18n-CyJIoYJT.cjs");
|
|
5
5
|
let node_fs = require("node:fs");
|
|
6
6
|
node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
|
|
@@ -33,6 +33,7 @@ node_os = require_rolldown_runtime.__toESM(node_os, 1);
|
|
|
33
33
|
let node_http = require("node:http");
|
|
34
34
|
node_http = require_rolldown_runtime.__toESM(node_http, 1);
|
|
35
35
|
let lru_cache = require("lru-cache");
|
|
36
|
+
let prom_client = require("prom-client");
|
|
36
37
|
let url = require("url");
|
|
37
38
|
let crypto = require("crypto");
|
|
38
39
|
let esbuild = require("esbuild");
|
|
@@ -1338,7 +1339,7 @@ function resolveFetchHandler(module) {
|
|
|
1338
1339
|
}
|
|
1339
1340
|
var package_default = {
|
|
1340
1341
|
name: "isr-engine",
|
|
1341
|
-
version: "
|
|
1342
|
+
version: "3.0.0",
|
|
1342
1343
|
description: "ISR/SSG/Fallback rendering orchestration on Vite + React 19 RSC.",
|
|
1343
1344
|
license: "UNLICENSED",
|
|
1344
1345
|
repository: {
|
|
@@ -1445,7 +1446,7 @@ var package_default = {
|
|
|
1445
1446
|
engines: { "node": "24.15.0" },
|
|
1446
1447
|
packageManager: "pnpm@9.15.9",
|
|
1447
1448
|
dependencies: {
|
|
1448
|
-
"@vitejs/plugin-rsc": "0.5.
|
|
1449
|
+
"@vitejs/plugin-rsc": "0.5.39",
|
|
1449
1450
|
"chalk": "^6.0.1",
|
|
1450
1451
|
"commander": "^12.1.0",
|
|
1451
1452
|
"compression": "^1.8.2",
|
|
@@ -1458,15 +1459,14 @@ var package_default = {
|
|
|
1458
1459
|
"ora": "^10.0.0",
|
|
1459
1460
|
"parse5": "^8.0.1",
|
|
1460
1461
|
"prom-client": "^15.1.3",
|
|
1462
|
+
"rsc-html-stream": "0.0.7",
|
|
1461
1463
|
"sharp": "^0.35.5",
|
|
1462
1464
|
"sitemap": "^10.0.0",
|
|
1463
1465
|
"typescript": "^6.0.3"
|
|
1464
1466
|
},
|
|
1465
1467
|
peerDependencies: {
|
|
1466
|
-
"react": "19.3.
|
|
1467
|
-
"react-dom": "19.3.
|
|
1468
|
-
"react-server-dom-webpack": "19.3.0-canary-bd6ea412-20260824",
|
|
1469
|
-
"rsc-html-stream": "^0.0.7",
|
|
1468
|
+
"react": "19.3.1",
|
|
1469
|
+
"react-dom": "19.3.1",
|
|
1470
1470
|
"vite": "8.1.6"
|
|
1471
1471
|
},
|
|
1472
1472
|
optionalDependencies: { "ioredis": "^5.11.1" },
|
|
@@ -1498,11 +1498,9 @@ var package_default = {
|
|
|
1498
1498
|
"ioredis-mock": "^8.9.0",
|
|
1499
1499
|
"miniflare": "4.20260730.0",
|
|
1500
1500
|
"prettier": "^3.10.1",
|
|
1501
|
-
"react": "19.3.
|
|
1502
|
-
"react-dom": "19.3.
|
|
1503
|
-
"react-server-dom-webpack": "19.3.0-canary-bd6ea412-20260824",
|
|
1501
|
+
"react": "19.3.1",
|
|
1502
|
+
"react-dom": "19.3.1",
|
|
1504
1503
|
"rimraf": "^6.1.4",
|
|
1505
|
-
"rsc-html-stream": "^0.0.7",
|
|
1506
1504
|
"sass-embedded": "^1.108.2",
|
|
1507
1505
|
"semantic-release": "25.0.9",
|
|
1508
1506
|
"tsc-alias": "^1.9.10",
|
|
@@ -2329,6 +2327,207 @@ function createHybridCacheStore(opts) {
|
|
|
2329
2327
|
};
|
|
2330
2328
|
}
|
|
2331
2329
|
//#endregion
|
|
2330
|
+
//#region src/metrics/PromMetrics.ts
|
|
2331
|
+
/**
|
|
2332
|
+
* PromMetrics —— prom-client 包装,导出 Prometheus 文本格式
|
|
2333
|
+
*
|
|
2334
|
+
* 设计:
|
|
2335
|
+
* - prom-client 是 Node 生态的事实标准(Grafana / Datadog / Prometheus 直接抓取)
|
|
2336
|
+
* - 单 Registry,避免污染全局;用户业务可拿 `promRegistry` 自行注册自家 metric
|
|
2337
|
+
* - 响应时间用 Histogram(带桶),不是平均值 —— 才能正确算 P95/P99
|
|
2338
|
+
* - 默认采集 process_*(CPU / RSS / event-loop lag)—— 一行 collectDefaultMetrics
|
|
2339
|
+
*/
|
|
2340
|
+
var PromMetrics_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
|
|
2341
|
+
cacheEntriesGauge: () => cacheEntriesGauge,
|
|
2342
|
+
cacheHitsTotal: () => cacheHitsTotal,
|
|
2343
|
+
cacheRevalidatingGauge: () => cacheRevalidatingGauge,
|
|
2344
|
+
createPrometheusMetricsMiddleware: () => createPrometheusMetricsMiddleware,
|
|
2345
|
+
httpRequestDurationSeconds: () => httpRequestDurationSeconds,
|
|
2346
|
+
httpRequestsTotal: () => httpRequestsTotal,
|
|
2347
|
+
invalidatorFailuresTotal: () => invalidatorFailuresTotal,
|
|
2348
|
+
invalidatorRunsTotal: () => invalidatorRunsTotal,
|
|
2349
|
+
l2ReadTimeoutsTotal: () => l2ReadTimeoutsTotal,
|
|
2350
|
+
normalizeRoute: () => normalizeRoute,
|
|
2351
|
+
promRegistry: () => promRegistry,
|
|
2352
|
+
recordHttpRequest: () => recordHttpRequest
|
|
2353
|
+
});
|
|
2354
|
+
var promRegistry = new prom_client.Registry();
|
|
2355
|
+
(0, prom_client.collectDefaultMetrics)({
|
|
2356
|
+
register: promRegistry,
|
|
2357
|
+
prefix: "isr_"
|
|
2358
|
+
});
|
|
2359
|
+
var httpRequestsTotal = new prom_client.Counter({
|
|
2360
|
+
name: "isr_http_requests_total",
|
|
2361
|
+
help: "Total ISR HTTP requests",
|
|
2362
|
+
labelNames: [
|
|
2363
|
+
"method",
|
|
2364
|
+
"route",
|
|
2365
|
+
"status",
|
|
2366
|
+
"mode",
|
|
2367
|
+
"cache"
|
|
2368
|
+
],
|
|
2369
|
+
registers: [promRegistry]
|
|
2370
|
+
});
|
|
2371
|
+
var httpRequestDurationSeconds = new prom_client.Histogram({
|
|
2372
|
+
name: "isr_http_request_duration_seconds",
|
|
2373
|
+
help: "ISR HTTP request duration",
|
|
2374
|
+
labelNames: [
|
|
2375
|
+
"method",
|
|
2376
|
+
"route",
|
|
2377
|
+
"mode",
|
|
2378
|
+
"cache"
|
|
2379
|
+
],
|
|
2380
|
+
buckets: [
|
|
2381
|
+
.001,
|
|
2382
|
+
.005,
|
|
2383
|
+
.01,
|
|
2384
|
+
.025,
|
|
2385
|
+
.05,
|
|
2386
|
+
.1,
|
|
2387
|
+
.25,
|
|
2388
|
+
.5,
|
|
2389
|
+
1,
|
|
2390
|
+
2.5,
|
|
2391
|
+
5
|
|
2392
|
+
],
|
|
2393
|
+
registers: [promRegistry]
|
|
2394
|
+
});
|
|
2395
|
+
var cacheEntriesGauge = new prom_client.Gauge({
|
|
2396
|
+
name: "isr_cache_entries",
|
|
2397
|
+
help: "Current ISR cache entries (L1 LRU size)",
|
|
2398
|
+
labelNames: ["backend"],
|
|
2399
|
+
registers: [promRegistry]
|
|
2400
|
+
});
|
|
2401
|
+
var cacheRevalidatingGauge = new prom_client.Gauge({
|
|
2402
|
+
name: "isr_cache_revalidating_inflight",
|
|
2403
|
+
help: "Number of in-flight background revalidations",
|
|
2404
|
+
registers: [promRegistry]
|
|
2405
|
+
});
|
|
2406
|
+
var cacheHitsTotal = new prom_client.Counter({
|
|
2407
|
+
name: "isr_cache_hits_total",
|
|
2408
|
+
help: "ISR cache hits",
|
|
2409
|
+
labelNames: ["status"],
|
|
2410
|
+
registers: [promRegistry]
|
|
2411
|
+
});
|
|
2412
|
+
var invalidatorRunsTotal = new prom_client.Counter({
|
|
2413
|
+
name: "isr_invalidator_runs_total",
|
|
2414
|
+
help: "Total revalidate dispatches (one increment per revalidatePath/Tag call with ≥1 invalidator)",
|
|
2415
|
+
labelNames: ["kind", "target"],
|
|
2416
|
+
registers: [promRegistry]
|
|
2417
|
+
});
|
|
2418
|
+
var invalidatorFailuresTotal = new prom_client.Counter({
|
|
2419
|
+
name: "isr_invalidator_failures_total",
|
|
2420
|
+
help: "Per-invalidator failures during revalidate dispatch (one increment per failing invalidator)",
|
|
2421
|
+
labelNames: ["kind", "target"],
|
|
2422
|
+
registers: [promRegistry]
|
|
2423
|
+
});
|
|
2424
|
+
var l2ReadTimeoutsTotal = new prom_client.Counter({
|
|
2425
|
+
name: "isr_l2_read_timeouts_total",
|
|
2426
|
+
help: "L2 cache async read timeouts (raceWithTimeout fired before underlying promise resolved)",
|
|
2427
|
+
registers: [promRegistry]
|
|
2428
|
+
});
|
|
2429
|
+
/**
|
|
2430
|
+
* 路由归一化 —— 防 Prometheus label 基数爆炸。
|
|
2431
|
+
*
|
|
2432
|
+
* 动态段(id / uuid / hex / 长 hash)直接作为 label 值会让时间序列数爆炸
|
|
2433
|
+
* (每个 /books/123 都是新序列),Prometheus 存储成本线性暴涨、查询变慢。
|
|
2434
|
+
*
|
|
2435
|
+
* 规则:
|
|
2436
|
+
* - 纯数字段(1 ~ 20 位) → `:id`
|
|
2437
|
+
* - UUID v1-v5 → `:uuid`
|
|
2438
|
+
* - 长 hex(≥16 字符全 hex)→ `:hash`
|
|
2439
|
+
* - base64url/大小写混合长串(≥24 字符,含数字和字母)→ `:hash`
|
|
2440
|
+
*
|
|
2441
|
+
* 命中任意规则即替换;其他保留原样(`/books` `/about` 保留)。
|
|
2442
|
+
*
|
|
2443
|
+
* 可用 `addRouteNormalizeRule(pattern, replacement)` 扩展业务特有规则。
|
|
2444
|
+
*/
|
|
2445
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
2446
|
+
var LONG_HEX_RE = /^[0-9a-f]{16,}$/i;
|
|
2447
|
+
var OPAQUE_ID_RE = /^[A-Za-z0-9_-]{24,}$/;
|
|
2448
|
+
var PURE_DIGIT_RE = /^\d{1,20}$/;
|
|
2449
|
+
var customRules = [];
|
|
2450
|
+
function normalizeRoute(route) {
|
|
2451
|
+
if (!route || route === "/") return "/";
|
|
2452
|
+
const segments = route.split("/");
|
|
2453
|
+
for (let i = 0; i < segments.length; i++) {
|
|
2454
|
+
const seg = segments[i];
|
|
2455
|
+
if (!seg) continue;
|
|
2456
|
+
let replaced = null;
|
|
2457
|
+
for (const rule of customRules) {
|
|
2458
|
+
replaced = rule(seg);
|
|
2459
|
+
if (replaced) break;
|
|
2460
|
+
}
|
|
2461
|
+
if (replaced) {
|
|
2462
|
+
segments[i] = replaced;
|
|
2463
|
+
continue;
|
|
2464
|
+
}
|
|
2465
|
+
if (PURE_DIGIT_RE.test(seg)) segments[i] = ":id";
|
|
2466
|
+
else if (UUID_RE.test(seg)) segments[i] = ":uuid";
|
|
2467
|
+
else if (LONG_HEX_RE.test(seg)) segments[i] = ":hash";
|
|
2468
|
+
else if (OPAQUE_ID_RE.test(seg)) segments[i] = ":hash";
|
|
2469
|
+
}
|
|
2470
|
+
return segments.join("/");
|
|
2471
|
+
}
|
|
2472
|
+
require_abVariantContext.setRevalidationMetricRecorder((event, kind, target) => {
|
|
2473
|
+
(event === "run" ? invalidatorRunsTotal : invalidatorFailuresTotal).inc({
|
|
2474
|
+
kind,
|
|
2475
|
+
target: kind === "path" ? normalizeRoute(target) : target
|
|
2476
|
+
});
|
|
2477
|
+
});
|
|
2478
|
+
/** 一行调用更新所有计数 —— 给 isrCacheMiddleware / 中间件用 */
|
|
2479
|
+
function recordHttpRequest(opts) {
|
|
2480
|
+
const route = normalizeRoute(opts.route);
|
|
2481
|
+
httpRequestsTotal.inc({
|
|
2482
|
+
method: opts.method,
|
|
2483
|
+
route,
|
|
2484
|
+
status: String(opts.status),
|
|
2485
|
+
mode: opts.mode,
|
|
2486
|
+
cache: opts.cache
|
|
2487
|
+
});
|
|
2488
|
+
httpRequestDurationSeconds.observe({
|
|
2489
|
+
method: opts.method,
|
|
2490
|
+
route,
|
|
2491
|
+
mode: opts.mode,
|
|
2492
|
+
cache: opts.cache
|
|
2493
|
+
}, opts.durationMs / 1e3);
|
|
2494
|
+
if (opts.cache) cacheHitsTotal.inc({ status: opts.cache });
|
|
2495
|
+
}
|
|
2496
|
+
/**
|
|
2497
|
+
* Express / connect 中间件:暴露 /metrics 端点(Prometheus text exposition format)
|
|
2498
|
+
*
|
|
2499
|
+
* 认证:可选 Bearer token —— 未设 token 时保持旧行为(匿名可访问)。
|
|
2500
|
+
* 生产建议:`createPrometheusMetricsMiddleware({ token: process.env.METRICS_TOKEN })`。
|
|
2501
|
+
*/
|
|
2502
|
+
function createPrometheusMetricsMiddleware(pathOrOptions = {}) {
|
|
2503
|
+
const options = typeof pathOrOptions === "string" ? { path: pathOrOptions } : pathOrOptions;
|
|
2504
|
+
const path = options.path ?? "/metrics";
|
|
2505
|
+
const token = options.token && options.token !== "" ? options.token : null;
|
|
2506
|
+
const unauthorizedStatus = options.unauthorizedStatus ?? 401;
|
|
2507
|
+
return async function(req, res, next) {
|
|
2508
|
+
if (req.url !== path || req.method !== "GET") return next();
|
|
2509
|
+
if (token) {
|
|
2510
|
+
const authHeader = req.headers?.["authorization"];
|
|
2511
|
+
const raw = Array.isArray(authHeader) ? authHeader[0] : authHeader;
|
|
2512
|
+
if (!(typeof raw === "string" && raw === `Bearer ${token}`)) {
|
|
2513
|
+
res.statusCode = unauthorizedStatus;
|
|
2514
|
+
res.setHeader("WWW-Authenticate", "Bearer realm=\"metrics\"");
|
|
2515
|
+
res.end("Unauthorized");
|
|
2516
|
+
return;
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
try {
|
|
2520
|
+
const body = await promRegistry.metrics();
|
|
2521
|
+
res.setHeader("content-type", promRegistry.contentType);
|
|
2522
|
+
res.statusCode = 200;
|
|
2523
|
+
res.end(body);
|
|
2524
|
+
} catch (err) {
|
|
2525
|
+
res.statusCode = 500;
|
|
2526
|
+
res.end(`metrics error: ${err instanceof Error ? err.message : String(err)}`);
|
|
2527
|
+
}
|
|
2528
|
+
};
|
|
2529
|
+
}
|
|
2530
|
+
//#endregion
|
|
2332
2531
|
//#region src/config/loadConfig.ts
|
|
2333
2532
|
/**
|
|
2334
2533
|
* 配置加载工具
|
|
@@ -4416,13 +4615,13 @@ function createIsrCacheMiddleware(explicitConfig, options = {}) {
|
|
|
4416
4615
|
development: true
|
|
4417
4616
|
}));
|
|
4418
4617
|
try {
|
|
4419
|
-
const inspector = opsConfig.inventory.enabled ? (await Promise.resolve().then(() => require("./createCacheInspectorMiddleware-
|
|
4618
|
+
const inspector = opsConfig.inventory.enabled ? (await Promise.resolve().then(() => require("./createCacheInspectorMiddleware-DZr98Zfn.cjs"))).createCacheInspectorMiddleware(nextHandler, opsConfig) : void 0;
|
|
4420
4619
|
handler = nextHandler;
|
|
4421
4620
|
server.middlewares.use((req, res, next) => {
|
|
4422
4621
|
if (handler !== nextHandler) return next();
|
|
4423
4622
|
if (opsConfig.metrics.enabled && req.url === "/metrics" && req.method === "GET") {
|
|
4424
4623
|
createOpsAuthMiddleware("metrics", opsConfig)(req, res, () => {
|
|
4425
|
-
Promise.resolve().then(() =>
|
|
4624
|
+
Promise.resolve().then(() => PromMetrics_exports).then(async ({ promRegistry }) => {
|
|
4426
4625
|
const body = await promRegistry.metrics();
|
|
4427
4626
|
res.setHeader("content-type", promRegistry.contentType);
|
|
4428
4627
|
res.end(body);
|
|
@@ -4478,7 +4677,7 @@ async function handleRequest(req, res, next, ctx) {
|
|
|
4478
4677
|
const route = stripRscSuffix(stripQuery$1(url)) || "/";
|
|
4479
4678
|
const cache = String(res.getHeader("X-Cache-Status") || "BYPASS");
|
|
4480
4679
|
const mode = String(res.getHeader("X-Resolved-Mode") || "unknown");
|
|
4481
|
-
|
|
4680
|
+
recordHttpRequest({
|
|
4482
4681
|
method,
|
|
4483
4682
|
route,
|
|
4484
4683
|
status: res.statusCode,
|
|
@@ -4486,8 +4685,8 @@ async function handleRequest(req, res, next, ctx) {
|
|
|
4486
4685
|
cache,
|
|
4487
4686
|
durationMs
|
|
4488
4687
|
});
|
|
4489
|
-
|
|
4490
|
-
|
|
4688
|
+
cacheEntriesGauge.set({ backend: ctx.cache.backend }, ctx.cache.size);
|
|
4689
|
+
cacheRevalidatingGauge.set(ctx.revalidating.size);
|
|
4491
4690
|
} catch {}
|
|
4492
4691
|
});
|
|
4493
4692
|
if (method !== "GET" && method !== "HEAD" || isBypassPath(url)) {
|
|
@@ -4534,7 +4733,7 @@ async function handleRequest(req, res, next, ctx) {
|
|
|
4534
4733
|
let entry = ctx.cache.get(cacheKey);
|
|
4535
4734
|
if (!entry && ctx.cache.getAsync) try {
|
|
4536
4735
|
entry = await raceWithTimeout(ctx.cache.getAsync(cacheKey), ctx.l2ReadTimeoutMs, () => {
|
|
4537
|
-
|
|
4736
|
+
l2ReadTimeoutsTotal.inc();
|
|
4538
4737
|
});
|
|
4539
4738
|
} catch (err) {
|
|
4540
4739
|
logger$5.warn(`ISR cache L2 read 失败 ${cacheKey}: ${err.message}`);
|
|
@@ -4611,7 +4810,7 @@ async function handleRequest(req, res, next, ctx) {
|
|
|
4611
4810
|
let recheck = ctx.cache.get(cacheKey);
|
|
4612
4811
|
if (!recheck && ctx.cache.getAsync) try {
|
|
4613
4812
|
recheck = await raceWithTimeout(ctx.cache.getAsync(cacheKey), ctx.l2ReadTimeoutMs, () => {
|
|
4614
|
-
|
|
4813
|
+
l2ReadTimeoutsTotal.inc();
|
|
4615
4814
|
});
|
|
4616
4815
|
} catch {}
|
|
4617
4816
|
if (!isActive()) return;
|
|
@@ -5595,7 +5794,7 @@ async function createProductionRuntime(config, options = {}) {
|
|
|
5595
5794
|
app.use("/assets", (_req, res) => {
|
|
5596
5795
|
res.status(404).set("Cache-Control", "no-store").end();
|
|
5597
5796
|
});
|
|
5598
|
-
const { createImageMiddleware } = await Promise.resolve().then(() => require("./createImagePlugin-
|
|
5797
|
+
const { createImageMiddleware } = await Promise.resolve().then(() => require("./createImagePlugin-BtJzr0t-.cjs")).then((n) => n.createImagePlugin_exports);
|
|
5599
5798
|
const { resolveImageOptions } = await Promise.resolve().then(() => resolveImageOptions_exports);
|
|
5600
5799
|
app.use(createImageMiddleware(resolveImageOptions(config.runtime.images), {}, clientDir));
|
|
5601
5800
|
const { createAutoCacheStore } = await Promise.resolve().then(() => createAutoCacheStore_exports);
|
|
@@ -5667,7 +5866,7 @@ async function createProductionRuntime(config, options = {}) {
|
|
|
5667
5866
|
});
|
|
5668
5867
|
cleanups.push(() => cache.destroy());
|
|
5669
5868
|
if (opsConfig.inventory.enabled) {
|
|
5670
|
-
const { createCacheInspectorMiddleware } = await Promise.resolve().then(() => require("./createCacheInspectorMiddleware-
|
|
5869
|
+
const { createCacheInspectorMiddleware } = await Promise.resolve().then(() => require("./createCacheInspectorMiddleware-DZr98Zfn.cjs"));
|
|
5671
5870
|
app.use(createCacheInspectorMiddleware(cache, opsConfig));
|
|
5672
5871
|
logger$8.info("🔍 ISR cache inventory 已启用:GET /__isr/cache/inventory");
|
|
5673
5872
|
}
|
|
@@ -5692,7 +5891,7 @@ async function createProductionRuntime(config, options = {}) {
|
|
|
5692
5891
|
if (res.getHeader("X-Resolved-Mode") === "ssg" || ssgAliases.has(decodeHtmlPathname(req.path)) && explicitRoutes.has(decodeHtmlPathname(req.path))) return next();
|
|
5693
5892
|
staticHtml(req, res, next);
|
|
5694
5893
|
});
|
|
5695
|
-
const { promRegistry } = await Promise.resolve().then(() =>
|
|
5894
|
+
const { promRegistry } = await Promise.resolve().then(() => PromMetrics_exports);
|
|
5696
5895
|
if (opsConfig.metrics.enabled) app.get("/metrics", createOpsAuthMiddleware("metrics", opsConfig), async (_req, res) => {
|
|
5697
5896
|
try {
|
|
5698
5897
|
res.set("content-type", promRegistry.contentType);
|
|
@@ -7472,6 +7671,12 @@ Object.defineProperty(exports, "createProductionRuntime", {
|
|
|
7472
7671
|
return createProductionRuntime;
|
|
7473
7672
|
}
|
|
7474
7673
|
});
|
|
7674
|
+
Object.defineProperty(exports, "createPrometheusMetricsMiddleware", {
|
|
7675
|
+
enumerable: true,
|
|
7676
|
+
get: function() {
|
|
7677
|
+
return createPrometheusMetricsMiddleware;
|
|
7678
|
+
}
|
|
7679
|
+
});
|
|
7475
7680
|
Object.defineProperty(exports, "createSEOEngine", {
|
|
7476
7681
|
enumerable: true,
|
|
7477
7682
|
get: function() {
|
|
@@ -7508,6 +7713,18 @@ Object.defineProperty(exports, "getRouteFallbackChain", {
|
|
|
7508
7713
|
return getRouteFallbackChain;
|
|
7509
7714
|
}
|
|
7510
7715
|
});
|
|
7716
|
+
Object.defineProperty(exports, "invalidatorFailuresTotal", {
|
|
7717
|
+
enumerable: true,
|
|
7718
|
+
get: function() {
|
|
7719
|
+
return invalidatorFailuresTotal;
|
|
7720
|
+
}
|
|
7721
|
+
});
|
|
7722
|
+
Object.defineProperty(exports, "invalidatorRunsTotal", {
|
|
7723
|
+
enumerable: true,
|
|
7724
|
+
get: function() {
|
|
7725
|
+
return invalidatorRunsTotal;
|
|
7726
|
+
}
|
|
7727
|
+
});
|
|
7511
7728
|
Object.defineProperty(exports, "isCodeFile", {
|
|
7512
7729
|
enumerable: true,
|
|
7513
7730
|
get: function() {
|
|
@@ -7592,12 +7809,24 @@ Object.defineProperty(exports, "prepareProductionBuild", {
|
|
|
7592
7809
|
return prepareProductionBuild;
|
|
7593
7810
|
}
|
|
7594
7811
|
});
|
|
7812
|
+
Object.defineProperty(exports, "promRegistry", {
|
|
7813
|
+
enumerable: true,
|
|
7814
|
+
get: function() {
|
|
7815
|
+
return promRegistry;
|
|
7816
|
+
}
|
|
7817
|
+
});
|
|
7595
7818
|
Object.defineProperty(exports, "readDirRecursive", {
|
|
7596
7819
|
enumerable: true,
|
|
7597
7820
|
get: function() {
|
|
7598
7821
|
return readDirRecursive;
|
|
7599
7822
|
}
|
|
7600
7823
|
});
|
|
7824
|
+
Object.defineProperty(exports, "recordHttpRequest", {
|
|
7825
|
+
enumerable: true,
|
|
7826
|
+
get: function() {
|
|
7827
|
+
return recordHttpRequest;
|
|
7828
|
+
}
|
|
7829
|
+
});
|
|
7601
7830
|
Object.defineProperty(exports, "resolveFetchHandler", {
|
|
7602
7831
|
enumerable: true,
|
|
7603
7832
|
get: function() {
|
|
@@ -7659,4 +7888,4 @@ Object.defineProperty(exports, "startServer", {
|
|
|
7659
7888
|
}
|
|
7660
7889
|
});
|
|
7661
7890
|
|
|
7662
|
-
//# sourceMappingURL=createISRApp-
|
|
7891
|
+
//# sourceMappingURL=createISRApp-CHiiWF3P.cjs.map
|