{"files": {"main.ts": "import {run} from './core.ts';\nimport {POLICY} from './policy.ts';\nexport function evaluate(payload: any): any { return run(payload, POLICY); }\n", "core.ts": "import {parseDecimal, addDecimal, formatDecimal} from './helpers.ts';\nexport function run(payload: any, policy: any): any {\n  const now: any = payload ? payload.now : 0;\n  const events: any[] = payload && Array.isArray(payload.events) ? payload.events : [];\n  const maxAge: any = policy.max_age;\n  const inclusiveAge: boolean = !!policy.inclusive_age;\n  const duplicates: any[] = [];\n  const seen: any = new Set();\n  const filtered: any[] = [];\n  for (let i = 0; i < events.length; i++) {\n    const ev: any = events[i];\n    if (maxAge !== undefined && maxAge !== null) {\n      const age: any = now - ev.ts;\n      if (age > maxAge) continue;\n      if (age === maxAge && !inclusiveAge) continue;\n    }\n    const dedupKey: string = policy.scope_key === 'tenant' ? String(ev.tenant) + '\\u0000' + String(ev.id) : String(ev.id);\n    if (seen.has(dedupKey)) {\n      if (policy.audit_duplicate) duplicates.push(ev.id);\n      continue;\n    }\n    seen.add(dedupKey);\n    filtered.push({ev: ev, index: i});\n  }\n  const groups: any = new Map();\n  for (const item of filtered) {\n    const ev: any = item.ev;\n    const gkey: string = String(ev.tenant) + '\\u0000' + String(ev.entity);\n    if (!groups.has(gkey)) groups.set(gkey, {tenant: ev.tenant, entity: ev.entity, items: [], earliest: item.index});\n    const g: any = groups.get(gkey);\n    g.items.push(item);\n    if (item.index < g.earliest) g.earliest = item.index;\n  }\n  const field: string = (policy.latest_by === 'ts' || policy.latest_by === 'timestamp' || policy.latest_by === 'time') ? 'ts' : 'seq';\n  const precision: number = typeof policy.precision === 'number' ? policy.precision : 0;\n  const out: any[] = [];\n  for (const g of groups.values()) {\n    const tieMap: any = new Map();\n    for (const item of g.items) {\n      const tk: string = String(item.ev[field]);\n      if (!tieMap.has(tk)) tieMap.set(tk, item);\n      else if (policy.tie_policy === 'last') tieMap.set(tk, item);\n    }\n    const retained: any[] = Array.from(tieMap.values());\n    const hasDelete: boolean = retained.some((it: any) => it.ev.kind === 'delete');\n    const sorted: any[] = retained.slice().sort((a: any, b: any) => {\n      const av: any = a.ev[field]; const bv: any = b.ev[field];\n      if (av < bv) return -1; if (av > bv) return 1; return 0;\n    });\n    let seqState: any = 0;\n    let value: any = {coeff: (globalThis as any).BigInt(0), scale: 0};\n    let deleted: boolean = false;\n    for (const item of sorted) {\n      const ev: any = item.ev;\n      if (policy.gap_policy === 'ignore') {\n        if (ev.seq !== seqState + 1) continue;\n      }\n      seqState = ev.seq;\n      if (ev.kind === 'delete') {\n        deleted = true;\n      } else if (ev.kind === 'set') {\n        if (!deleted || policy.allow_resurrection) {\n          deleted = false;\n          const amt: any = parseDecimal(ev.amount === undefined || ev.amount === null ? '0' : ev.amount);\n          if (policy.amount_mode === 'delta') value = addDecimal(value, amt); else value = amt;\n        }\n      }\n    }\n    if (policy.delete_wins && hasDelete) deleted = true;\n    out.push({tenant: g.tenant, entity: g.entity, value: formatDecimal(value, precision), deleted: deleted, _earliest: g.earliest});\n  }\n  if (policy.order === 'key') {\n    out.sort((a: any, b: any) => {\n      if (String(a.tenant) < String(b.tenant)) return -1; if (String(a.tenant) > String(b.tenant)) return 1;\n      if (String(a.entity) < String(b.entity)) return -1; if (String(a.entity) > String(b.entity)) return 1; return 0;\n    });\n  } else {\n    out.sort((a: any, b: any) => a._earliest - b._earliest);\n  }\n  const entities: any[] = out.map((e: any) => ({tenant: e.tenant, entity: e.entity, value: e.value, deleted: e.deleted}));\n  return {entities: entities, duplicates: duplicates};\n}\n", "policy.ts": "export const POLICY: any = {\"delete_wins\": true, \"latest_by\": \"sequence\", \"scope_key\": \"tenant\", \"tie_policy\": \"first\", \"allow_resurrection\": true, \"amount_mode\": \"absolute\", \"gap_policy\": \"accept\", \"precision\": 0, \"inclusive_age\": true, \"max_age\": 60, \"audit_duplicate\": true, \"order\": \"key\"};\n", "helpers.ts": "const BI: any = (globalThis as any).BigInt;\nfunction pow10(n: number): any { let r: any = BI(1); for (let i = 0; i < n; i++) r = r * BI(10); return r; }\nexport function parseDecimal(amount: any): any {\n  let s: string = String(amount).trim();\n  let neg: boolean = false;\n  if (s.startsWith('-')) { neg = true; s = s.slice(1); } else if (s.startsWith('+')) s = s.slice(1);\n  let exp: number = 0;\n  const epos: number = s.search(/[eE]/);\n  if (epos >= 0) { exp = parseInt(s.slice(epos + 1), 10); s = s.slice(0, epos); }\n  const dot: number = s.indexOf('.');\n  let digits: string; let scale: number;\n  if (dot >= 0) { digits = s.slice(0, dot) + s.slice(dot + 1); scale = s.length - dot - 1; } else { digits = s; scale = 0; }\n  digits = digits.replace(/^0+(?=\\d)/, '');\n  if (digits === '') digits = '0';\n  let coeff: any = BI(digits);\n  scale = scale - exp;\n  if (scale < 0) { coeff = coeff * pow10(-scale); scale = 0; }\n  if (neg) coeff = -coeff;\n  return {coeff: coeff, scale: scale};\n}\nexport function addDecimal(a: any, b: any): any {\n  const scale: number = Math.max(a.scale, b.scale);\n  const ac: any = a.coeff * pow10(scale - a.scale);\n  const bc: any = b.coeff * pow10(scale - b.scale);\n  return {coeff: ac + bc, scale: scale};\n}\nexport function formatDecimal(v: any, precision: number): string {\n  let coeff: any = v.coeff; const scale: number = v.scale;\n  let neg: boolean = false;\n  if (coeff < BI(0)) { neg = true; coeff = -coeff; }\n  let scaled: any;\n  if (scale <= precision) scaled = coeff * pow10(precision - scale);\n  else { const div: any = pow10(scale - precision); const q: any = coeff / div; const r: any = coeff % div; scaled = (r * BI(2) >= div) ? q + BI(1) : q; }\n  let s: string = scaled.toString();\n  if (precision === 0) return neg && scaled !== BI(0) ? '-' + s : s;\n  s = s.padStart(precision + 1, '0');\n  const out: string = s.slice(0, s.length - precision) + '.' + s.slice(s.length - precision);\n  return neg && scaled !== BI(0) ? '-' + out : out;\n}\n"}}