{"version":3,"file":"transforms.mjs","names":[],"sources":["../src/transforms.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport MagicString from \"magic-string\";\n\nexport type AstNode = {\n  type: string;\n  start: number;\n  end: number;\n  [key: string]: unknown;\n};\n\nexport type AstProgram = AstNode & {\n  body: AstNode[];\n};\n\nexport type UseClientDirective = {\n  node: AstNode;\n  directive: AstNode;\n  name: string;\n  parent?: AstNode;\n  parentKey?: string;\n};\n\nexport type UseClientAnalysis = {\n  moduleDirective?: AstNode;\n  inlineDirectives: UseClientDirective[];\n};\n\nexport type ClientReference = {\n  mod: string;\n  deps: string[];\n};\n\nexport type TransformResult = {\n  code: string;\n  map: ReturnType<MagicString[\"generateMap\"]>;\n};\n\nexport type TransformReferenceOptions = {\n  id: string;\n  root?: string;\n  base?: string;\n  references?: ReadonlyMap<string, ClientReference>;\n  placeholders?: boolean;\n};\n\ntype BindCapture = {\n  code: string;\n  nodes: AstNode[];\n};\n\nconst jsExtensions = new Set([\".cjs\", \".cts\", \".js\", \".jsx\", \".mjs\", \".mts\", \".ts\", \".tsx\"]);\nconst clientReferenceHelperName = \"__srv_jsx_define_client_reference\";\nconst clientReferenceHelperImport = `import { defineClientReference as ${clientReferenceHelperName} } from \"srv-jsx\";`;\n\nconst ignoredAstKeys = new Set([\n  \"accessibility\",\n  \"declare\",\n  \"decorators\",\n  \"end\",\n  \"loc\",\n  \"optional\",\n  \"range\",\n  \"readonly\",\n  \"returnType\",\n  \"start\",\n  \"static\",\n  \"type\",\n  \"typeAnnotation\",\n  \"typeArguments\",\n  \"typeParameters\",\n]);\n\nexport function analyzeUseClientDirectives(code: string, ast: AstProgram): UseClientAnalysis {\n  const moduleDirective = findUseClientDirective(ast.body);\n  const inlineDirectives: UseClientDirective[] = [];\n\n  walkAst(ast, (node, parent, parentKey) => {\n    if (!isFunctionLike(node)) return;\n\n    const body = node.body as AstNode | undefined;\n    if (!body || body.type !== \"BlockStatement\") return;\n\n    const directive = findUseClientDirective((body.body as AstNode[] | undefined) ?? []);\n    if (!directive) return;\n\n    inlineDirectives.push({\n      node,\n      directive,\n      name: \"\",\n      parent,\n      parentKey,\n    });\n  });\n\n  inlineDirectives.sort((left, right) => left.node.start - right.node.start);\n  for (const [index, directive] of inlineDirectives.entries()) {\n    directive.name = `__srv_jsx_client_${index}`;\n  }\n\n  assertValidDirectives(Boolean(moduleDirective), inlineDirectives);\n\n  return {\n    moduleDirective,\n    inlineDirectives,\n  };\n}\n\nexport function transformUseClientForServer(\n  code: string,\n  ast: AstProgram,\n  options: TransformReferenceOptions,\n): TransformResult | null {\n  const analysis = analyzeUseClientDirectives(code, ast);\n  if (!analysis.moduleDirective && analysis.inlineDirectives.length === 0) return null;\n\n  const magicString = new MagicString(code);\n  if (analysis.moduleDirective) {\n    magicString.overwrite(0, code.length, moduleReferenceExports(ast, options));\n  } else {\n    const moduleNames = collectModuleNames(collectModuleScope(ast));\n    const declarations = analysis.inlineDirectives\n      .map(\n        (directive) =>\n          `const ${directive.name} = ${clientReferenceCodeForServer(options, directive.name)};`,\n      )\n      .join(\"\\n\");\n    const exports = `export { ${analysis.inlineDirectives\n      .map((directive) => directive.name)\n      .join(\", \")} };`;\n\n    magicString.prepend(`${clientReferenceHelperImport}\\n${declarations}\\n${exports}\\n`);\n\n    for (const directive of analysis.inlineDirectives.toReversed()) {\n      const bindCaptures = collectBindCaptures(code, directive.node, moduleNames);\n      replaceInlineImplementation(\n        magicString,\n        directive,\n        clientReferenceExpression(directive.name, bindCaptures),\n      );\n    }\n  }\n\n  return magicStringResult(magicString, options.id);\n}\n\nexport function transformUseClientForClient(\n  code: string,\n  ast: AstProgram,\n  options: TransformReferenceOptions,\n): TransformResult | null {\n  const analysis = analyzeUseClientDirectives(code, ast);\n  if (!analysis.moduleDirective && analysis.inlineDirectives.length === 0) return null;\n\n  const magicString = new MagicString(code);\n\n  if (analysis.moduleDirective) {\n    magicString.remove(\n      analysis.moduleDirective.start,\n      endIncludingLineBreak(code, analysis.moduleDirective.end),\n    );\n    return magicStringResult(magicString, options.id);\n  }\n\n  const moduleScope = collectModuleScope(ast);\n  const moduleNames = collectModuleNames(moduleScope);\n  const neededNames = collectNeededNames(analysis.inlineDirectives, moduleScope);\n  const imports = collectNeededImports(moduleScope.imports, neededNames);\n  const declarations = collectNeededDeclarations(moduleScope.declarations, neededNames);\n  const output = [\n    ...imports.map((node) => printImportDeclaration(node, neededNames)),\n    ...declarations.map((node) => code.slice(node.start, node.end)),\n    ...analysis.inlineDirectives.map((directive) => {\n      const bindCaptures = collectBindCaptures(code, directive.node, moduleNames);\n      return `export const ${directive.name} = ${sourceWithoutDirective(\n        code,\n        directive.node,\n        directive.directive,\n        bindCaptures,\n      )};`;\n    }),\n  ]\n    .filter(Boolean)\n    .join(\"\\n\\n\");\n\n  magicString.overwrite(0, code.length, `${output}\\n`);\n\n  return magicStringResult(magicString, options.id);\n}\n\nfunction assertValidDirectives(\n  hasModuleDirective: boolean,\n  inlineDirectives: UseClientDirective[],\n) {\n  if (hasModuleDirective && inlineDirectives.length > 0) {\n    throw new Error('Cannot use module-level and inline \"use client\" directives in the same file.');\n  }\n\n  for (const directive of inlineDirectives) {\n    for (const other of inlineDirectives) {\n      if (directive === other) continue;\n      if (directive.node.start < other.node.start && directive.node.end > other.node.end) {\n        throw new Error('Nested inline \"use client\" directives are not supported.');\n      }\n    }\n  }\n}\n\nfunction findUseClientDirective(body: AstNode[]) {\n  for (const statement of body) {\n    if (!isExpressionStatement(statement)) break;\n\n    const expression = statement.expression as AstNode | undefined;\n    if (!expression || !isStringLiteral(expression)) break;\n    if (expression.value === \"use client\") return statement;\n  }\n\n  return undefined;\n}\n\nfunction isExpressionStatement(node: AstNode) {\n  return node.type === \"ExpressionStatement\";\n}\n\nfunction isStringLiteral(node: AstNode) {\n  return (\n    (node.type === \"Literal\" || node.type === \"StringLiteral\") && typeof node.value === \"string\"\n  );\n}\n\nfunction isFunctionLike(node: AstNode) {\n  return (\n    node.type === \"ArrowFunctionExpression\" ||\n    node.type === \"FunctionDeclaration\" ||\n    node.type === \"FunctionExpression\"\n  );\n}\n\nfunction walkAst(\n  node: AstNode,\n  enter: (node: AstNode, parent: AstNode | undefined, parentKey: string | undefined) => void,\n  parent?: AstNode,\n  parentKey?: string,\n) {\n  enter(node, parent, parentKey);\n\n  for (const [key, value] of Object.entries(node)) {\n    if (ignoredAstKeys.has(key)) continue;\n\n    if (Array.isArray(value)) {\n      for (const item of value) {\n        if (isAstNode(item)) walkAst(item, enter, node, key);\n      }\n    } else if (isAstNode(value)) {\n      walkAst(value, enter, node, key);\n    }\n  }\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n  return Boolean(value && typeof value === \"object\" && typeof (value as AstNode).type === \"string\");\n}\n\nfunction resolveClientReference(options: TransformReferenceOptions): ClientReference {\n  const id = cleanId(options.id);\n  const reference = options.references?.get(id);\n  if (reference) return reference;\n\n  return {\n    mod: devModulePath(id, options.root, options.base),\n    deps: [],\n  };\n}\n\nfunction clientReferenceCodeForServer(options: TransformReferenceOptions, name: string) {\n  if (options.placeholders) return clientReferencePlaceholderCode(options.id, name);\n  return clientReferenceCode(resolveClientReference(options), name);\n}\n\nfunction clientReferenceCode(reference: ClientReference, name: string) {\n  return `${clientReferenceHelperName}({ id: ${JSON.stringify(\n    clientReferenceId(reference.mod, name),\n  )}, name: ${JSON.stringify(name)}, mod: ${JSON.stringify(reference.mod)}, deps: ${JSON.stringify(\n    reference.deps,\n  )} })`;\n}\n\nfunction clientReferencePlaceholderCode(id: string, name: string) {\n  const placeholders = clientReferencePlaceholders(id);\n  return `${clientReferenceHelperName}({ id: ${clientReferenceIdPlaceholder(\n    id,\n    name,\n  )}, name: ${JSON.stringify(name)}, mod: ${placeholders.mod}, deps: ${placeholders.deps} })`;\n}\n\nfunction clientReferenceId(mod: string, name: string) {\n  return hashString(`${mod}#${name}`).padStart(6, \"0\").slice(0, 6);\n}\n\nfunction clientReferenceIdPlaceholder(id: string, name: string) {\n  return `__SRV_JSX_CLIENT_REFERENCE_${hashString(cleanId(id))}_ID_${hexEncode(name)}__`;\n}\n\nfunction clientReferencePlaceholders(id: string) {\n  const hash = hashString(cleanId(id));\n  return {\n    mod: `__SRV_JSX_CLIENT_REFERENCE_${hash}_MOD__`,\n    deps: `__SRV_JSX_CLIENT_REFERENCE_${hash}_DEPS__`,\n  };\n}\n\nexport function replaceClientReferencePlaceholders(\n  code: string,\n  references: ReadonlyMap<string, ClientReference>,\n) {\n  let output = code;\n\n  for (const [id, reference] of references) {\n    const placeholders = clientReferencePlaceholders(id);\n    const moduleHash = hashString(cleanId(id));\n    output = output\n      .replaceAll(placeholders.mod, JSON.stringify(reference.mod))\n      .replaceAll(placeholders.deps, JSON.stringify(reference.deps))\n      .replace(\n        new RegExp(`\\\\b__SRV_JSX_CLIENT_REFERENCE_${moduleHash}_ID_([a-f0-9]+)__\\\\b`, \"g\"),\n        (_placeholder, encodedName: string) =>\n          JSON.stringify(clientReferenceId(reference.mod, hexDecode(encodedName))),\n      );\n  }\n\n  const leftover = output.match(\n    /\\b__SRV_JSX_CLIENT_REFERENCE_[a-z0-9]+_(?:MOD|DEPS|ID_[a-f0-9]+)__\\b/,\n  );\n  if (leftover) {\n    throw new Error(`Missing client reference for placeholder ${leftover[0]}.`);\n  }\n\n  return output;\n}\n\nexport function patchClientReferencePlaceholdersInBundle(\n  bundle: Record<string, unknown>,\n  references: ReadonlyMap<string, ClientReference>,\n) {\n  for (const output of Object.values(bundle)) {\n    if (!isOutputChunk(output)) continue;\n    output.code = replaceClientReferencePlaceholders(output.code, references);\n  }\n}\n\nfunction isOutputChunk(value: unknown): value is { type: \"chunk\"; code: string } {\n  return (\n    Boolean(value) &&\n    typeof value === \"object\" &&\n    (value as { type?: unknown }).type === \"chunk\" &&\n    typeof (value as { code?: unknown }).code === \"string\"\n  );\n}\n\nfunction moduleReferenceExports(ast: AstProgram, options: TransformReferenceOptions) {\n  const exports = collectModuleExports(ast);\n  const references = new Map<string, string>();\n\n  const referenceName = (name: string) => {\n    const existing = references.get(name);\n    if (existing) return existing;\n\n    const local = `__srv_jsx_client_reference_${references.size}`;\n    references.set(name, local);\n    return local;\n  };\n\n  for (const name of exports.named) referenceName(name);\n  if (exports.hasDefault) referenceName(\"default\");\n\n  const lines = references.size === 0 ? [] : [clientReferenceHelperImport];\n\n  lines.push(\n    ...[...references].map(\n      ([name, local]) => `const ${local} = ${clientReferenceCodeForServer(options, name)};`,\n    ),\n  );\n\n  if (exports.named.length > 0) {\n    lines.push(\n      `export { ${exports.named\n        .map((name) => `${referenceName(name)} as ${formatExportName(name)}`)\n        .join(\", \")} };`,\n    );\n  }\n\n  if (exports.hasDefault) {\n    lines.push(`export default ${referenceName(\"default\")};`);\n  }\n\n  if (exports.named.length === 0 && !exports.hasDefault) {\n    lines.push(\"export {};\");\n  }\n\n  return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction collectModuleExports(ast: AstProgram) {\n  const named = new Set<string>();\n  let hasDefault = false;\n\n  for (const statement of ast.body) {\n    if (statement.type === \"ExportDefaultDeclaration\") {\n      hasDefault = true;\n      continue;\n    }\n\n    if (statement.type === \"ExportAllDeclaration\") {\n      throw new Error('Module-level \"use client\" cannot rewrite export-all declarations.');\n    }\n\n    if (statement.type !== \"ExportNamedDeclaration\") continue;\n    if (statement.exportKind === \"type\") continue;\n\n    const declaration = statement.declaration as AstNode | null | undefined;\n    if (declaration) {\n      for (const name of declaredNames(declaration)) {\n        named.add(name);\n      }\n      continue;\n    }\n\n    const specifiers = (statement.specifiers as AstNode[] | undefined) ?? [];\n    for (const specifier of specifiers) {\n      if (specifier.exportKind === \"type\") continue;\n\n      const exported = specifier.exported as AstNode | undefined;\n      const name = exportedName(exported);\n      if (!name) continue;\n\n      if (name === \"default\") {\n        hasDefault = true;\n      } else {\n        named.add(name);\n      }\n    }\n  }\n\n  return { named: [...named], hasDefault };\n}\n\nfunction exportedName(node: AstNode | undefined) {\n  if (!node) return undefined;\n  if (typeof node.name === \"string\") return node.name;\n  if (typeof node.value === \"string\") return node.value;\n  return undefined;\n}\n\nfunction formatExportName(name: string) {\n  return isIdentifierName(name) ? name : JSON.stringify(name);\n}\n\nfunction isIdentifierName(name: string) {\n  return /^[A-Za-z_$][\\w$]*$/.test(name);\n}\n\nfunction clientReferenceExpression(referenceName: string, bindCaptures: BindCapture[]) {\n  if (bindCaptures.length === 0) return referenceName;\n  return `${referenceName}.bind(null,${bindCaptures.map((capture) => capture.code).join(\",\")})`;\n}\n\nfunction replaceInlineImplementation(\n  magicString: MagicString,\n  directive: UseClientDirective,\n  replacement: string,\n) {\n  const parent = directive.parent;\n\n  if (parent?.type === \"VariableDeclarator\" && directive.parentKey === \"init\") {\n    magicString.overwrite(directive.node.start, directive.node.end, replacement);\n    return;\n  }\n\n  if (directive.node.type === \"FunctionDeclaration\") {\n    const localName = functionName(directive.node) ?? directive.name;\n\n    if (parent?.type === \"ExportNamedDeclaration\") {\n      magicString.overwrite(\n        parent.start,\n        parent.end,\n        `export const ${localName} = ${replacement};`,\n      );\n    } else {\n      magicString.overwrite(\n        directive.node.start,\n        directive.node.end,\n        `const ${localName} = ${replacement};`,\n      );\n    }\n    return;\n  }\n\n  magicString.overwrite(directive.node.start, directive.node.end, replacement);\n}\n\nfunction functionName(node: AstNode) {\n  const id = node.id as AstNode | null | undefined;\n  return typeof id?.name === \"string\" ? id.name : undefined;\n}\n\nfunction sourceWithoutDirective(\n  code: string,\n  node: AstNode,\n  directive: AstNode,\n  bindCaptures: BindCapture[] = [],\n) {\n  const magicString = new MagicString(code.slice(node.start, node.end));\n  addBindParameters(magicString, code, node, bindCaptures);\n\n  for (const [index, capture] of bindCaptures.entries()) {\n    for (const captureNode of capture.nodes.toReversed()) {\n      magicString.overwrite(\n        captureNode.start - node.start,\n        captureNode.end - node.start,\n        bindParameterName(index),\n      );\n    }\n  }\n\n  magicString.remove(\n    directive.start - node.start,\n    endIncludingLineBreak(code, directive.end) - node.start,\n  );\n  return magicString.toString();\n}\n\nfunction addBindParameters(\n  magicString: MagicString,\n  code: string,\n  node: AstNode,\n  bindCaptures: BindCapture[],\n) {\n  if (bindCaptures.length === 0) return;\n\n  const params = bindCaptures.map((_, index) => bindParameterName(index)).join(\", \");\n  const existingParams = (node.params as AstNode[] | undefined) ?? [];\n\n  if (node.type === \"FunctionDeclaration\" || node.type === \"FunctionExpression\") {\n    const openParen = code.indexOf(\"(\", node.start);\n    if (openParen === -1 || openParen > node.end) return;\n    magicString.appendLeft(\n      openParen - node.start + 1,\n      existingParams.length > 0 ? `${params}, ` : params,\n    );\n    return;\n  }\n\n  if (node.type !== \"ArrowFunctionExpression\") return;\n\n  if (existingParams.length === 0) {\n    const openParen = code.indexOf(\"(\", node.start);\n    if (openParen === -1 || openParen > node.end) return;\n    magicString.appendLeft(openParen - node.start + 1, params);\n    return;\n  }\n\n  const firstParam = existingParams[0]!;\n  const beforeFirstParam = code.slice(node.start, firstParam.start);\n  if (beforeFirstParam.includes(\"(\")) {\n    magicString.appendLeft(firstParam.start - node.start, `${params}, `);\n    return;\n  }\n\n  magicString.prependLeft(firstParam.start - node.start, `(${params}, `);\n  magicString.appendRight(firstParam.end - node.start, \")\");\n}\n\nfunction bindParameterName(index: number) {\n  return `__srv_jsx_bind_${index}`;\n}\n\nfunction endIncludingLineBreak(code: string, end: number) {\n  if (code.charCodeAt(end) === 13 && code.charCodeAt(end + 1) === 10) return end + 2;\n  if (code.charCodeAt(end) === 10) return end + 1;\n  return end;\n}\n\nfunction magicStringResult(magicString: MagicString, source: string): TransformResult {\n  return {\n    code: magicString.toString(),\n    map: magicString.generateMap({\n      hires: true,\n      includeContent: true,\n      source,\n    }),\n  };\n}\n\ntype ModuleScope = {\n  imports: AstNode[];\n  declarations: Map<string, AstNode>;\n};\n\nfunction collectModuleScope(ast: AstProgram): ModuleScope {\n  const imports: AstNode[] = [];\n  const declarations = new Map<string, AstNode>();\n\n  for (const statement of ast.body) {\n    if (statement.type === \"ImportDeclaration\") {\n      imports.push(statement);\n      continue;\n    }\n\n    const declaration =\n      statement.type === \"ExportNamedDeclaration\"\n        ? (statement.declaration as AstNode | null | undefined)\n        : statement;\n    if (!declaration) continue;\n\n    for (const name of declaredNames(declaration)) {\n      declarations.set(name, statement);\n    }\n  }\n\n  return { imports, declarations };\n}\n\nfunction collectNeededNames(directives: UseClientDirective[], moduleScope: ModuleScope) {\n  const neededNames = new Set<string>();\n  const includedDeclarations = new Set<AstNode>();\n  const queue: string[] = [];\n\n  const addName = (name: string) => {\n    if (neededNames.has(name)) return;\n    neededNames.add(name);\n    queue.push(name);\n  };\n\n  for (const directive of directives) {\n    for (const name of collectFreeReferences(directive.node)) {\n      addName(name);\n    }\n  }\n\n  for (let name = queue.shift(); name; name = queue.shift()) {\n    const declaration = moduleScope.declarations.get(name);\n    if (!declaration || includedDeclarations.has(declaration)) continue;\n\n    includedDeclarations.add(declaration);\n\n    for (const reference of collectFreeReferences(declaration)) {\n      addName(reference);\n    }\n  }\n\n  return neededNames;\n}\n\nfunction collectNeededImports(imports: AstNode[], neededNames: Set<string>) {\n  return imports.filter((node) => {\n    if (node.importKind === \"type\") return false;\n\n    const specifiers = (node.specifiers as AstNode[] | undefined) ?? [];\n    return specifiers.some(\n      (specifier) =>\n        importSpecifierName(specifier, true) !== undefined &&\n        neededNames.has(importSpecifierName(specifier, true)!),\n    );\n  });\n}\n\nfunction collectNeededDeclarations(declarations: Map<string, AstNode>, neededNames: Set<string>) {\n  const neededDeclarations = new Set<AstNode>();\n\n  for (const [name, declaration] of declarations) {\n    if (neededNames.has(name)) neededDeclarations.add(declaration);\n  }\n\n  return [...neededDeclarations].sort((left, right) => left.start - right.start);\n}\n\nfunction printImportDeclaration(node: AstNode, neededNames: Set<string>) {\n  const specifiers = ((node.specifiers as AstNode[] | undefined) ?? []).filter((specifier) => {\n    const local = importSpecifierName(specifier, true);\n    return local && neededNames.has(local);\n  });\n\n  const defaultSpecifier = specifiers.find(\n    (specifier) => specifier.type === \"ImportDefaultSpecifier\",\n  );\n  const namespaceSpecifier = specifiers.find(\n    (specifier) => specifier.type === \"ImportNamespaceSpecifier\",\n  );\n  const namedSpecifiers = specifiers.filter((specifier) => specifier.type === \"ImportSpecifier\");\n  const parts: string[] = [];\n\n  if (defaultSpecifier) {\n    parts.push(importSpecifierName(defaultSpecifier, true)!);\n  }\n\n  if (namespaceSpecifier) {\n    parts.push(`* as ${importSpecifierName(namespaceSpecifier, true)!}`);\n  }\n\n  if (namedSpecifiers.length > 0) {\n    parts.push(\n      `{ ${namedSpecifiers\n        .map((specifier) => {\n          const imported = importSpecifierName(specifier, false)!;\n          const local = importSpecifierName(specifier, true)!;\n          return imported === local ? imported : `${imported} as ${local}`;\n        })\n        .join(\", \")} }`,\n    );\n  }\n\n  const source = node.source as AstNode | undefined;\n  const sourceCode =\n    typeof source?.raw === \"string\"\n      ? source.raw\n      : JSON.stringify(typeof source?.value === \"string\" ? source.value : \"\");\n\n  return `import ${parts.join(\", \")} from ${sourceCode};`;\n}\n\nfunction importSpecifierName(specifier: AstNode, local: boolean) {\n  const node =\n    specifier.type === \"ImportSpecifier\"\n      ? ((local ? specifier.local : specifier.imported) as AstNode | undefined)\n      : (specifier.local as AstNode | undefined);\n  if (typeof node?.name === \"string\") return node.name;\n  if (typeof node?.value === \"string\") return node.value;\n  return undefined;\n}\n\nfunction collectModuleNames(moduleScope: ModuleScope) {\n  const names = new Set(moduleScope.declarations.keys());\n\n  for (const node of moduleScope.imports) {\n    for (const specifier of (node.specifiers as AstNode[] | undefined) ?? []) {\n      const local = importSpecifierName(specifier, true);\n      if (local) names.add(local);\n    }\n  }\n\n  return names;\n}\n\nfunction collectBindCaptures(code: string, root: AstNode, moduleNames: Set<string>) {\n  const parents = new WeakMap<AstNode, { parent: AstNode; parentKey: string | undefined }>();\n  walkAst(root, (node, parent, parentKey) => {\n    if (parent) parents.set(node, { parent, parentKey });\n  });\n\n  const captures = new Map<string, BindCapture>();\n  const scopes: Set<string>[] = [new Set()];\n\n  const isDeclared = (name: string) => scopes.some((scope) => scope.has(name));\n  const declare = (name: string) => scopes[0]!.add(name);\n\n  const addCapture = (node: AstNode) => {\n    const captureCode = code.slice(node.start, node.end);\n    const capture = captures.get(captureCode);\n    if (capture) {\n      capture.nodes.push(node);\n    } else {\n      captures.set(captureCode, { code: captureCode, nodes: [node] });\n    }\n  };\n\n  const visit = (node: AstNode, parent?: AstNode, parentKey?: string) => {\n    if (node.type === \"Identifier\") {\n      if (!isReferenceIdentifier(node, parent, parentKey)) return;\n\n      const name = node.name as string;\n      if (!isDeclared(name) && !moduleNames.has(name) && !isKnownGlobal(name)) {\n        addCapture(bindExpressionNode(node, parents));\n      }\n      return;\n    }\n\n    if (node.type === \"VariableDeclaration\") {\n      for (const declaration of (node.declarations as AstNode[] | undefined) ?? []) {\n        collectPatternNames(declaration.id as AstNode | undefined, scopes[0]!);\n        if (isAstNode(declaration.init)) visit(declaration.init, declaration, \"init\");\n      }\n      return;\n    }\n\n    if (node.type === \"FunctionDeclaration\") {\n      const name = functionName(node);\n      if (name) declare(name);\n      visitFunctionBody(node);\n      return;\n    }\n\n    if (node.type === \"FunctionExpression\" || node.type === \"ArrowFunctionExpression\") {\n      visitFunctionBody(node);\n      return;\n    }\n\n    if (node.type === \"ClassDeclaration\") {\n      const id = node.id as AstNode | null | undefined;\n      if (typeof id?.name === \"string\") declare(id.name);\n    }\n\n    for (const [key, value] of Object.entries(node)) {\n      if (ignoredAstKeys.has(key)) continue;\n\n      if (Array.isArray(value)) {\n        for (const item of value) {\n          if (isAstNode(item)) visit(item, node, key);\n        }\n      } else if (isAstNode(value)) {\n        visit(value, node, key);\n      }\n    }\n  };\n\n  const visitFunctionBody = (node: AstNode) => {\n    const scope = new Set<string>();\n    scopes.unshift(scope);\n\n    const id = node.id as AstNode | null | undefined;\n    if (typeof id?.name === \"string\") scope.add(id.name);\n\n    for (const parameter of (node.params as AstNode[] | undefined) ?? []) {\n      collectPatternNames(parameter, scope);\n    }\n\n    const body = node.body as AstNode | undefined;\n    if (body) visit(body, node, \"body\");\n\n    scopes.shift();\n  };\n\n  visit(root);\n  return [...captures.values()];\n}\n\nfunction bindExpressionNode(\n  node: AstNode,\n  parents: WeakMap<AstNode, { parent: AstNode; parentKey: string | undefined }>,\n) {\n  let expression = node;\n  let current = node;\n  let link = parents.get(current);\n\n  while (\n    link?.parent.type === \"MemberExpression\" &&\n    link.parentKey === \"object\" &&\n    link.parent.object === current\n  ) {\n    expression = link.parent;\n    current = link.parent;\n    link = parents.get(current);\n  }\n\n  return expression;\n}\n\nconst commonGlobalNames = new Set([\n  \"AbortController\",\n  \"Blob\",\n  \"CustomEvent\",\n  \"Document\",\n  \"Element\",\n  \"Event\",\n  \"EventTarget\",\n  \"File\",\n  \"FormData\",\n  \"HTMLElement\",\n  \"Headers\",\n  \"Location\",\n  \"Request\",\n  \"Response\",\n  \"URL\",\n  \"URLSearchParams\",\n  \"WebSocket\",\n  \"Window\",\n  \"crypto\",\n  \"document\",\n  \"fetch\",\n  \"globalThis\",\n  \"location\",\n  \"navigator\",\n  \"self\",\n  \"window\",\n]);\n\nfunction isKnownGlobal(name: string) {\n  return name in globalThis || commonGlobalNames.has(name);\n}\n\nfunction collectFreeReferences(root: AstNode) {\n  const references = new Set<string>();\n  const scopes: Set<string>[] = [new Set()];\n\n  const isDeclared = (name: string) => scopes.some((scope) => scope.has(name));\n  const declare = (name: string) => scopes[0]!.add(name);\n\n  const visit = (node: AstNode, parent?: AstNode, parentKey?: string) => {\n    if (node.type === \"Identifier\") {\n      if (!isReferenceIdentifier(node, parent, parentKey)) return;\n\n      const name = node.name as string;\n      if (!isDeclared(name)) references.add(name);\n      return;\n    }\n\n    if (node.type === \"JSXIdentifier\") {\n      const name = node.name as string;\n      if (isJSXComponentName(name) && !isDeclared(name)) references.add(name);\n      return;\n    }\n\n    if (node.type === \"VariableDeclaration\") {\n      for (const declaration of (node.declarations as AstNode[] | undefined) ?? []) {\n        collectPatternNames(declaration.id as AstNode | undefined, scopes[0]!);\n        if (isAstNode(declaration.init)) visit(declaration.init, declaration, \"init\");\n      }\n      return;\n    }\n\n    if (node.type === \"FunctionDeclaration\") {\n      const name = functionName(node);\n      if (name) declare(name);\n      visitFunctionBody(node);\n      return;\n    }\n\n    if (node.type === \"FunctionExpression\" || node.type === \"ArrowFunctionExpression\") {\n      visitFunctionBody(node);\n      return;\n    }\n\n    if (node.type === \"ClassDeclaration\") {\n      const id = node.id as AstNode | null | undefined;\n      if (typeof id?.name === \"string\") declare(id.name);\n    }\n\n    for (const [key, value] of Object.entries(node)) {\n      if (ignoredAstKeys.has(key)) continue;\n\n      if (Array.isArray(value)) {\n        for (const item of value) {\n          if (isAstNode(item)) visit(item, node, key);\n        }\n      } else if (isAstNode(value)) {\n        visit(value, node, key);\n      }\n    }\n  };\n\n  const visitFunctionBody = (node: AstNode) => {\n    const scope = new Set<string>();\n    scopes.unshift(scope);\n\n    const id = node.id as AstNode | null | undefined;\n    if (typeof id?.name === \"string\") scope.add(id.name);\n\n    for (const parameter of (node.params as AstNode[] | undefined) ?? []) {\n      collectPatternNames(parameter, scope);\n    }\n\n    const body = node.body as AstNode | undefined;\n    if (body) visit(body, node, \"body\");\n\n    scopes.shift();\n  };\n\n  visit(root);\n  return references;\n}\n\nfunction isReferenceIdentifier(node: AstNode, parent?: AstNode, parentKey?: string) {\n  if (!parent) return true;\n  if (parentKey === \"id\") return false;\n  if (parentKey === \"params\") return false;\n  if (parent.type === \"ImportSpecifier\" || parent.type === \"ImportDefaultSpecifier\") return false;\n  if (parent.type === \"ImportNamespaceSpecifier\" || parent.type === \"ExportSpecifier\") return false;\n  if (parent.type === \"LabeledStatement\" || parent.type === \"BreakStatement\") return false;\n  if (parent.type === \"ContinueStatement\") return false;\n  if (parent.type === \"MemberExpression\" && parentKey === \"property\" && !parent.computed)\n    return false;\n  if (parent.type === \"Property\" && parentKey === \"key\" && !parent.computed) return false;\n  if (parent.type === \"MethodDefinition\" && parentKey === \"key\") return false;\n  return node.type === \"Identifier\";\n}\n\nfunction isJSXComponentName(name: string) {\n  return /^[A-Z_$]/.test(name);\n}\n\nfunction declaredNames(node: AstNode) {\n  const names = new Set<string>();\n\n  if (node.type === \"FunctionDeclaration\" || node.type === \"ClassDeclaration\") {\n    const id = node.id as AstNode | null | undefined;\n    if (typeof id?.name === \"string\") names.add(id.name);\n    return names;\n  }\n\n  if (node.type === \"VariableDeclaration\") {\n    for (const declaration of (node.declarations as AstNode[] | undefined) ?? []) {\n      collectPatternNames(declaration.id as AstNode | undefined, names);\n    }\n  }\n\n  return names;\n}\n\nfunction collectPatternNames(pattern: AstNode | undefined, names: Set<string>) {\n  if (!pattern) return;\n\n  if (pattern.type === \"Identifier\") {\n    names.add(pattern.name as string);\n    return;\n  }\n\n  if (pattern.type === \"RestElement\") {\n    collectPatternNames(pattern.argument as AstNode | undefined, names);\n    return;\n  }\n\n  if (pattern.type === \"AssignmentPattern\") {\n    collectPatternNames(pattern.left as AstNode | undefined, names);\n    return;\n  }\n\n  if (pattern.type === \"ArrayPattern\") {\n    for (const element of (pattern.elements as Array<AstNode | null> | undefined) ?? []) {\n      if (element) collectPatternNames(element, names);\n    }\n    return;\n  }\n\n  if (pattern.type === \"ObjectPattern\") {\n    for (const property of (pattern.properties as AstNode[] | undefined) ?? []) {\n      if (property.type === \"RestElement\") {\n        collectPatternNames(property.argument as AstNode | undefined, names);\n      } else {\n        collectPatternNames(property.value as AstNode | undefined, names);\n      }\n    }\n  }\n}\n\nexport function cleanId(id: string) {\n  return normalizePath(id.replace(/[?#].*$/, \"\"));\n}\n\nexport function isJavaScriptId(id: string) {\n  return jsExtensions.has(path.extname(id));\n}\n\nfunction devModulePath(id: string, root = process.cwd(), base = \"/\") {\n  const relative = normalizePath(path.relative(root, id));\n  const publicPath = relative.startsWith(\"..\") ? `/@fs/${id}` : `/${relative}`;\n  return joinPublicBase(publicPath, base);\n}\n\nexport function publicOutputPath(fileName: string, base = \"/\") {\n  return joinPublicBase(`/${normalizePath(fileName)}`, base);\n}\n\nfunction joinPublicBase(publicPath: string, base: string) {\n  if (base === \"\" || base === \"/\" || base === \"./\") return publicPath;\n  return `${base.replace(/\\/$/, \"\")}${publicPath}`;\n}\n\nfunction normalizePath(file: string) {\n  return file.replaceAll(path.sep, \"/\");\n}\n\nfunction hexEncode(value: string) {\n  let output = \"\";\n  for (let index = 0; index < value.length; index++) {\n    output += value.charCodeAt(index).toString(16).padStart(4, \"0\");\n  }\n  return output;\n}\n\nfunction hexDecode(value: string) {\n  let output = \"\";\n  for (let index = 0; index < value.length; index += 4) {\n    output += String.fromCharCode(Number.parseInt(value.slice(index, index + 4), 16));\n  }\n  return output;\n}\n\nfunction hashString(value: string) {\n  let hash = 5381;\n  for (let index = 0; index < value.length; index++) {\n    hash = (hash * 33) ^ value.charCodeAt(index);\n  }\n  return (hash >>> 0).toString(36);\n}\n"],"mappings":"qDAmDA,MAAM,EAAe,IAAI,IAAI,CAAC,OAAQ,OAAQ,MAAO,OAAQ,OAAQ,OAAQ,MAAO,MAAM,CAAC,EACrF,EAA4B,oCAC5B,EAA8B,qCAAqC,EAA0B,oBAE7F,EAAiB,IAAI,IAAI,CAC7B,gBACA,UACA,aACA,MACA,MACA,WACA,QACA,WACA,aACA,QACA,SACA,OACA,iBACA,gBACA,gBACF,CAAC,EAED,SAAgB,EAA2B,EAAc,EAAoC,CAC3F,IAAM,EAAkB,EAAuB,EAAI,IAAI,EACjD,EAAyC,CAAC,EAEhD,EAAQ,GAAM,EAAM,EAAQ,IAAc,CACxC,GAAI,CAAC,EAAe,CAAI,EAAG,OAE3B,IAAM,EAAO,EAAK,KAClB,GAAI,CAAC,GAAQ,EAAK,OAAS,iBAAkB,OAE7C,IAAM,EAAY,EAAwB,EAAK,MAAkC,CAAC,CAAC,EAC9E,GAEL,EAAiB,KAAK,CACpB,OACA,YACA,KAAM,GACN,SACA,WACF,CAAC,CACH,CAAC,EAED,EAAiB,MAAM,EAAM,IAAU,EAAK,KAAK,MAAQ,EAAM,KAAK,KAAK,EACzE,IAAK,GAAM,CAAC,EAAO,KAAc,EAAiB,QAAQ,E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