{"version":3,"file":"transform.js","names":[],"sources":["esm/worklets/transform.js"],"sourcesContent":["import path from \"node:path\";\nimport MagicString from \"magic-string\";\nimport remapping from \"@jridgewell/remapping\";\nimport { parseSync } from \"oxc-parser\";\nimport {\n  bodyStartAfterDirectives,\n  findWorkletCandidates,\n  hasDirective\n} from \"./autoworklet\";\nimport { createGlobalsSet } from \"./globals\";\nimport { calculateWorkletHash } from \"./hash\";\nimport { getClosureVariables } from \"./scope\";\nimport { buildLocalFunction, serializeWorkletForUI } from \"./serialize\";\nconst FUNCTION_TYPES = /* @__PURE__ */ new Set([\n  \"FunctionDeclaration\",\n  \"FunctionExpression\",\n  \"ArrowFunctionExpression\"\n]);\nfunction prepareWorkletsForReactCompiler(id, code, sourceMaps = false) {\n  const cleanId = id.split(\"?\")[0];\n  const parsed = parseSync(cleanId, code, {\n    sourceType: \"module\",\n    lang: /\\.[cm]?ts$/.test(cleanId) ? \"ts\" : cleanId.endsWith(\".tsx\") ? \"tsx\" : \"jsx\"\n  });\n  if (parsed.errors.length) {\n    const error = parsed.errors[0];\n    throw new Error(\n      error.codeframe || error.message || \"Syntax Error while parsing worklet\"\n    );\n  }\n  const candidates = findWorkletCandidates(parsed.program).filter(\n    (candidate) => candidate.isAutoWorklet && !hasDirective(candidate.fnNode, \"worklet\")\n  );\n  if (!candidates.length) return null;\n  const output = new MagicString(code);\n  for (const { fnNode } of candidates) {\n    const body = fnNode.body;\n    if (body.type === \"BlockStatement\") {\n      output.appendLeft(body.start + 1, \"'worklet';\");\n    } else {\n      output.appendLeft(body.start, \"{ 'worklet'; return (\");\n      output.appendLeft(body.end, \"); }\");\n    }\n  }\n  return {\n    code: output.toString(),\n    map: sourceMaps ? output.generateMap({ source: cleanId, hires: true, includeContent: true }) : void 0\n  };\n}\nfunction findEnclosingFunction(program, node) {\n  let best = void 0;\n  const walk = (n) => {\n    if (!n || typeof n !== \"object\") return;\n    if (Array.isArray(n)) {\n      for (const c of n) walk(c);\n      return;\n    }\n    if (typeof n.type !== \"string\") return;\n    if (typeof n.start === \"number\" && (n.start > node.start || n.end < node.end)) return;\n    if (FUNCTION_TYPES.has(n.type) && n !== node && n.body?.type === \"BlockStatement\" && n.body.start < node.start && n.body.end > node.end && (!best || n.body.start > best.body.start)) {\n      best = n;\n    }\n    for (const key in n) {\n      if (key === \"parent\") continue;\n      walk(n[key]);\n    }\n  };\n  walk(program);\n  return best;\n}\nfunction executeWorkletTransform(id, code, sourceMaps = false, options, resolveVersionFn) {\n  const cleanId = id.split(\"?\")[0];\n  const lang = /\\.[cm]?ts$/.test(cleanId) ? \"ts\" : cleanId.endsWith(\".tsx\") ? \"tsx\" : \"jsx\";\n  const initialParse = parseSync(cleanId, code, {\n    sourceType: \"module\",\n    lang\n  });\n  if (initialParse.errors && initialParse.errors.length > 0) {\n    const err = initialParse.errors[0];\n    throw new Error(err.codeframe || err.message || \"Syntax Error while parsing worklet\");\n  }\n  const initialCandidates = findWorkletCandidates(initialParse.program);\n  if (initialCandidates.length === 0) {\n    let map2 = void 0;\n    if (sourceMaps) {\n      const ms = new MagicString(code);\n      map2 = ms.generateMap({\n        source: cleanId,\n        file: cleanId,\n        hires: true,\n        includeContent: true\n      });\n    }\n    return { code, map: map2 };\n  }\n  const pluginVersion = options?.pluginVersion || (resolveVersionFn ? resolveVersionFn(options?.projectRoot, cleanId) : \"0.0.0\");\n  const globals = createGlobalsSet(options?.globals, options?.strictGlobal);\n  let location = cleanId;\n  if (options?.relativeSourceLocation && options?.projectRoot) {\n    location = path.relative(options.projectRoot, cleanId).replace(/\\\\/g, \"/\");\n  }\n  let currentCode = code;\n  const initDataDefs = /* @__PURE__ */ new Map();\n  const passMaps = [];\n  let remainingPassBudget = 100;\n  while (remainingPassBudget-- > 0) {\n    const parseResult = parseSync(cleanId, currentCode, {\n      sourceType: \"module\",\n      lang\n    });\n    if (parseResult.errors && parseResult.errors.length > 0) {\n      const err = parseResult.errors[0];\n      throw new Error(\n        err.codeframe || err.message || \"Syntax Error while parsing worklet\"\n      );\n    }\n    const candidates = findWorkletCandidates(parseResult.program);\n    if (candidates.length === 0) {\n      break;\n    }\n    const innermostCandidates = candidates.filter((c) => {\n      return !candidates.some(\n        (other) => other !== c && other.fnNode.start >= c.fnNode.start && other.fnNode.end <= c.fnNode.end\n      );\n    });\n    if (innermostCandidates.length === 0) {\n      throw new Error(\n        `[worklets] Cyclic or unresolvable worklet nesting detected in ${cleanId}`\n      );\n    }\n    const ms = new MagicString(currentCode);\n    const inlinedInitData = /* @__PURE__ */ new Map();\n    for (const candidate of innermostCandidates) {\n      const closureVars = hasDirective(candidate.fnNode, \"no-worklet-closure\") ? [] : getClosureVariables(candidate.fnNode, globals);\n      const fnName = candidate.name;\n      const serializedCode = serializeWorkletForUI(\n        candidate.fnNode,\n        currentCode,\n        fnName,\n        closureVars\n      );\n      const workletHash = calculateWorkletHash(serializedCode);\n      const initDataVar = `_worklet_${workletHash}_init_data`;\n      const initDataDecl = `var ${initDataVar} = {\n    code: ${JSON.stringify(serializedCode)},\n    location: ${JSON.stringify(location)}\n};`;\n      const enclosingFn = hasDirective(candidate.fnNode, \"limit-init-data-hoisting\") ? findEnclosingFunction(parseResult.program, candidate.fnNode) : void 0;\n      if (enclosingFn) {\n        const insertAt = bodyStartAfterDirectives(enclosingFn, currentCode);\n        let declared = inlinedInitData.get(insertAt);\n        if (!declared) {\n          declared = /* @__PURE__ */ new Set();\n          inlinedInitData.set(insertAt, declared);\n        }\n        if (!declared.has(initDataVar)) {\n          declared.add(initDataVar);\n          ms.appendLeft(insertAt, `\n${initDataDecl}\n`);\n        }\n      } else if (!initDataDefs.has(initDataVar)) {\n        initDataDefs.set(initDataVar, initDataDecl);\n      }\n      const localFnCode = buildLocalFunction(candidate.fnNode, currentCode, fnName);\n      const localName = fnName || \"_worklet\";\n      const closureValues = closureVars.join(\", \");\n      const iife = `(function () {\n    var _e = [new (typeof global !== 'undefined' ? global : globalThis).Error(), 1, -27];\n    var ${localName} = ${localFnCode};\n    ${localName}.__closure = [${closureValues}];\n    ${localName}.__workletHash = ${workletHash};\n    ${localName}.__pluginVersion = ${JSON.stringify(pluginVersion)};\n    ${localName}.__initData = ${initDataVar};\n    ${localName}.__stackDetails = _e;\n    return ${localName};\n})()`;\n      if (candidate.kind === \"function_declaration\") {\n        if (candidate.parent?.type === \"ExportNamedDeclaration\") {\n          ms.overwrite(\n            candidate.parent.start,\n            candidate.parent.end,\n            `export var ${candidate.name} = ${iife};`\n          );\n        } else if (candidate.parent?.type === \"ExportDefaultDeclaration\") {\n          ms.overwrite(\n            candidate.parent.start,\n            candidate.parent.end,\n            `var ${candidate.name || \"_defaultWorklet\"} = ${iife};\nexport default ${candidate.name || \"_defaultWorklet\"};`\n          );\n        } else {\n          ms.overwrite(\n            candidate.node.start,\n            candidate.node.end,\n            `var ${candidate.name} = ${iife};`\n          );\n        }\n      } else if (candidate.kind === \"object_method\") {\n        ms.overwrite(\n          candidate.node.start,\n          candidate.node.end,\n          `${candidate.name}: ${iife}`\n        );\n      } else {\n        ms.overwrite(candidate.node.start, candidate.node.end, iife);\n      }\n    }\n    if (sourceMaps) {\n      passMaps.push(\n        ms.generateMap({\n          source: cleanId,\n          file: cleanId,\n          hires: true,\n          includeContent: true\n        })\n      );\n    }\n    currentCode = ms.toString();\n  }\n  const finalCheck = parseSync(cleanId, currentCode, { sourceType: \"module\", lang });\n  const remaining = findWorkletCandidates(finalCheck.program);\n  if (remaining.length > 0) {\n    throw new Error(\n      `[worklets] Exceeded maximum pass budget while transforming worklets in ${cleanId}. ${remaining.length} worklet(s) remained untransformed.`\n    );\n  }\n  if (initDataDefs.size > 0) {\n    const initDataCode = Array.from(initDataDefs.values()).join(\"\\n\") + \"\\n\";\n    const msPrepend = new MagicString(currentCode);\n    msPrepend.prepend(initDataCode);\n    if (sourceMaps) {\n      passMaps.push(\n        msPrepend.generateMap({\n          source: cleanId,\n          file: cleanId,\n          hires: true,\n          includeContent: true\n        })\n      );\n    }\n    currentCode = msPrepend.toString();\n  }\n  let map = void 0;\n  if (sourceMaps && passMaps.length > 0) {\n    if (passMaps.length === 1) {\n      map = passMaps[0];\n    } else {\n      map = remapping(passMaps.slice().reverse(), () => null);\n    }\n    if (map) {\n      map.sources = [cleanId];\n      map.file = cleanId;\n    }\n  }\n  return {\n    code: currentCode,\n    map\n  };\n}\nexport {\n  executeWorkletTransform,\n  prepareWorkletsForReactCompiler\n};\n//# sourceMappingURL=transform.js.map\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,iCAAiC,IAAI,IAAI;CAC7C;CACA;CACA;AACF,CAAC;AACD,SAAS,gCAAgC,IAAI,MAAM,aAAa,OAAO;CACrE,MAAM,UAAU,GAAG,MAAM,GAAG,CAAC,CAAC;CAC9B,MAAM,SAAS,UAAU,SAAS,MAAM;EACtC,YAAY;EACZ,MAAM,aAAa,KAAK,OAAO,IAAI,OAAO,QAAQ,SAAS,MAAM,IAAI,QAAQ;CAC/E,CAAC;CACD,IAAI,OAAO,OAAO,QAAQ;EACxB,MAAM,QAAQ,OAAO,OAAO;EAC5B,MAAM,IAAI,MACR,MAAM,aAAa,MAAM,WAAW,oCACtC;CACF;CACA,MAAM,aAAa,sBAAsB,OAAO,OAAO,CAAC,CAAC,QACtD,cAAc,UAAU,iBAAiB,CAAC,aAAa,UAAU,QAAQ,SAAS,CACrF;CACA,IAAI,CAAC,WAAW,QAAQ,OAAO;CAC/B,MAAM,SAAS,IAAI,YAAY,IAAI;CACnC,KAAK,MAAM,EAAE,YAAY,YAAY;EACnC,MAAM,OAAO,OAAO;EACpB,IAAI,KAAK,SAAS,kBAAkB;GAClC,OAAO,WAAW,KAAK,QAAQ,GAAG,YAAY;EAChD,OAAO;GACL,OAAO,WAAW,KAAK,OAAO,uBAAuB;GACrD,OAAO,WAAW,KAAK,KAAK,MAAM;EACpC;CACF;CACA,OAAO;EACL,MAAM,OAAO,SAAS;EACtB,KAAK,aAAa,OAAO,YAAY;GAAE,QAAQ;GAAS,OAAO;GAAM,gBAAgB;EAAK,CAAC,IAAI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