{"version":3,"file":"view-compiler.es.mjs","names":[],"sources":["../src/view/compiler/expression.ts","../src/view/compiler/compile.ts","../src/view/compiler/emit.ts","../src/view/compiler/cli.ts"],"sourcesContent":["/**\n * Ahead-of-time expression compiler.\n *\n * Rewrites a `bq-*` directive expression into a `with`-free arrow function that\n * reads free identifiers from a context parameter — e.g. `count + 1` becomes\n * `($c) => ($c.count + 1)`. Because the output contains no `with` and no\n * `new Function()`, the emitted module is safe under a strict CSP that omits\n * `'unsafe-eval'`, and it skips the runtime parse on the hot path.\n *\n * The transform is intentionally conservative: any construct it cannot prove\n * safe to rewrite (assignments other than `++`/`--`, arrow/function bodies,\n * `new`, spread, regex/template literals, comments, …) makes it bail, and the\n * caller falls back to the runtime evaluator for that expression. This keeps\n * the compiled and runtime paths behaviourally identical.\n *\n * @module bquery/view/compiler\n */\n\nimport type { CompiledExpression } from './types';\n\n/** Default context parameter name — unlikely to collide with author vars. */\nexport const DEFAULT_PARAM = '__bq_ctx';\n\n/**\n * Globals left un-prefixed so they resolve from the JS global scope (mirroring\n * the runtime `with(ctx)` behaviour, where a name absent from the context falls\n * through to the global). A context value shadowing one of these is the rare\n * case the author can resolve with the `globals` option.\n */\nexport const DEFAULT_GLOBALS: ReadonlySet<string> = new Set([\n  'Math',\n  'JSON',\n  'Object',\n  'Array',\n  'String',\n  'Number',\n  'Boolean',\n  'Date',\n  'RegExp',\n  'Map',\n  'Set',\n  'Symbol',\n  'Promise',\n  'parseInt',\n  'parseFloat',\n  'isNaN',\n  'isFinite',\n  'encodeURIComponent',\n  'decodeURIComponent',\n  'encodeURI',\n  'decodeURI',\n  'console',\n  'Intl',\n]);\n\n/** Keywords that are values/operators and must not be prefixed. */\nconst PASS_THROUGH_WORDS: ReadonlySet<string> = new Set([\n  'true',\n  'false',\n  'null',\n  'undefined',\n  'this',\n  'NaN',\n  'Infinity',\n  'typeof',\n  'instanceof',\n  'in',\n  'of',\n  'void',\n]);\n\n/** Keywords whose presence means the expression is not a safe value expression. */\nconst BAIL_WORDS: ReadonlySet<string> = new Set([\n  'function',\n  'class',\n  'new',\n  'delete',\n  'yield',\n  'await',\n  'super',\n  'do',\n  'var',\n  'let',\n  'const',\n  'return',\n  'if',\n  'else',\n  'for',\n  'while',\n  'switch',\n  'throw',\n  'try',\n  'catch',\n  'with',\n  'import',\n  'export',\n  'extends',\n]);\n\n/** Operator runs ending in `=` that are comparisons, not assignments. */\nconst COMPARISON_OPS: ReadonlySet<string> = new Set(['==', '===', '!=', '!==', '<=', '>=']);\n\nconst isWs = (c: string): boolean =>\n  c === ' ' || c === '\\t' || c === '\\n' || c === '\\r' || c === '\\f';\nconst isIdentStart = (c: string): boolean => /[A-Za-z_$]/.test(c);\nconst isIdentPart = (c: string): boolean => /[A-Za-z0-9_$]/.test(c);\nconst isDigit = (c: string): boolean => c >= '0' && c <= '9';\n/** Characters that, as the previous significant token, mean a `/` is division. */\nconst isValueEnder = (c: string): boolean => /[)\\]A-Za-z0-9_$\"']/.test(c);\n/** Operator characters scanned as a maximal run (note: `/` is handled apart). */\nconst isOpChar = (c: string): boolean => '-+*%<>=!&|^~'.includes(c);\n\nclass Bail extends Error {}\n\n/**\n * Scans a single/double-quoted string literal starting at `start` (the opening\n * quote), respecting backslash escapes. Returns the index past the closing\n * quote (or end of input).\n */\nconst scanStringLiteral = (src: string, start: number): number => {\n  const quote = src[start];\n  let i = start + 1;\n  while (i < src.length && src[i] !== quote) {\n    if (src[i] === '\\\\') i += 1;\n    i += 1;\n  }\n  return i + 1;\n};\n\n/**\n * Scans a numeric literal (hex/float/exponent/separators) starting at `start`,\n * returning the end index. A `.` is consumed only as a single decimal point\n * followed by a digit, so a member-access dot (`1.5.toFixed`) ends the literal.\n */\nconst scanNumericLiteral = (src: string, start: number): number => {\n  let i = start;\n  let seenDot = false;\n  while (i < src.length) {\n    const ch = src[i];\n    if (ch === '.') {\n      if (seenDot || !isDigit(src[i + 1])) break;\n      seenDot = true;\n      i += 1;\n      continue;\n    }\n    if (/[0-9a-fA-FxXoObBeE_]/.test(ch)) {\n      i += 1;\n      continue;\n    }\n    break;\n  }\n  return i;\n};\n\n/**\n * Rewrites an expression into a `with`-free body string (no arrow wrapper).\n * Throws {@link Bail} with a reason when the expression cannot be compiled.\n */\nconst rewrite = (src: string, param: string, globals: ReadonlySet<string>): string => {\n  const n = src.length;\n  let out = '';\n  let i = 0;\n  // Last significant emitted char (whitespace excluded). Drives member-access\n  // detection (`.`/`?.`) and object-key position detection (`{`/`,`).\n  let prev = '';\n  // Bracket stack tracks whether we are inside an object literal `{`.\n  const stack: string[] = [];\n\n  while (i < n) {\n    const c = src[i];\n\n    if (isWs(c)) {\n      out += c;\n      i++;\n      continue;\n    }\n\n    // Comments are unexpected in directive expressions.\n    if (c === '/' && (src[i + 1] === '/' || src[i + 1] === '*')) {\n      throw new Bail('comments are not supported');\n    }\n\n    // Single/double-quoted strings: copy verbatim (respecting escapes).\n    if (c === '\"' || c === \"'\") {\n      const start = i;\n      i = scanStringLiteral(src, i);\n      out += src.slice(start, i);\n      prev = '\"';\n      continue;\n    }\n\n    // Template literals fall back to runtime (keeps the transform simple/safe).\n    if (c === '`') {\n      throw new Bail('template literals fall back to runtime');\n    }\n\n    // Spread/rest is not a safe value reference to rewrite.\n    if (c === '.' && src[i + 1] === '.' && src[i + 2] === '.') {\n      throw new Bail('spread/rest is not supported');\n    }\n\n    // Optional chaining `?.`\n    if (c === '?' && src[i + 1] === '.') {\n      out += '?.';\n      i += 2;\n      prev = '.';\n      continue;\n    }\n    // Nullish coalescing `??`\n    if (c === '?' && src[i + 1] === '?') {\n      out += '??';\n      i += 2;\n      prev = '?';\n      continue;\n    }\n\n    // `/` — division, or a regex we decline to rewrite.\n    if (c === '/') {\n      if (src[i + 1] === '=') throw new Bail('assignment is not supported');\n      if (!isValueEnder(prev)) throw new Bail('regular expression literals are not supported');\n      out += '/';\n      i++;\n      prev = '/';\n      continue;\n    }\n\n    // Member-access dot.\n    if (c === '.') {\n      out += '.';\n      i++;\n      prev = '.';\n      continue;\n    }\n\n    // Numbers (incl. hex/float/exponent). A member-access dot ends the literal\n    // (see {@link scanNumericLiteral}) so the property is not mis-prefixed.\n    if (isDigit(c) || (c === '.' && isDigit(src[i + 1]))) {\n      const start = i;\n      i = scanNumericLiteral(src, i);\n      out += src.slice(start, i);\n      prev = '0';\n      continue;\n    }\n\n    // Brackets.\n    if (c === '(' || c === '[' || c === '{') {\n      stack.push(c);\n      out += c;\n      i++;\n      prev = c;\n      continue;\n    }\n    if (c === ')' || c === ']' || c === '}') {\n      const open = stack.pop();\n      const expected = c === ')' ? '(' : c === ']' ? '[' : '{';\n      // Bail on a closing bracket that has no matching opener (or the wrong\n      // one) rather than emitting unbalanced — and therefore unparsable — code\n      // that would break the whole generated module.\n      if (open !== expected) throw new Bail('unbalanced brackets');\n      out += c;\n      i++;\n      prev = c;\n      continue;\n    }\n\n    // Statement separators / unexpected punctuation.\n    if (c === ';' || c === '@' || c === '#') {\n      throw new Bail(`unexpected \"${c}\"`);\n    }\n\n    // Identifiers.\n    if (isIdentStart(c)) {\n      const start = i;\n      while (i < n && isIdentPart(src[i])) i++;\n      const name = src.slice(start, i);\n\n      // Property name after a member dot — never prefixed.\n      if (prev === '.') {\n        out += name;\n        prev = 'a';\n        continue;\n      }\n      if (BAIL_WORDS.has(name)) {\n        throw new Bail(`unsupported keyword \"${name}\"`);\n      }\n      if (PASS_THROUGH_WORDS.has(name) || globals.has(name)) {\n        out += name;\n        prev = 'a';\n        continue;\n      }\n\n      const inObjectLiteral = stack[stack.length - 1] === '{';\n      const atKeyPosition = inObjectLiteral && (prev === '{' || prev === ',');\n      if (atKeyPosition) {\n        let j = i;\n        while (j < n && isWs(src[j])) j++;\n        const next = src[j];\n        if (next === ':') {\n          // Explicit key — leave the key name unprefixed.\n          out += name;\n          prev = 'a';\n          continue;\n        }\n        if (next === ',' || next === '}') {\n          // Shorthand `{ name }` ≡ `{ name: ctx.name }`.\n          out += `${name}: ${param}.${name}`;\n          prev = 'a';\n          continue;\n        }\n        // Method shorthand `{ name() {} }` etc. — not supported.\n        throw new Bail('unsupported object literal form');\n      }\n\n      // Free reference — read from the context.\n      out += `${param}.${name}`;\n      prev = 'a';\n      continue;\n    }\n\n    // Operator runs.\n    if (isOpChar(c)) {\n      const start = i;\n      while (i < n && isOpChar(src[i])) i++;\n      const run = src.slice(start, i);\n      if (run.includes('=>')) throw new Bail('arrow functions are not supported');\n      if (run.endsWith('=') && !COMPARISON_OPS.has(run)) {\n        throw new Bail('assignment is not supported');\n      }\n      out += run;\n      prev = run[run.length - 1];\n      continue;\n    }\n\n    if (c === ',') {\n      out += ',';\n      i++;\n      prev = ',';\n      continue;\n    }\n    if (c === '?' || c === ':') {\n      out += c;\n      i++;\n      prev = c;\n      continue;\n    }\n\n    // Anything else is unrecognised — bail rather than risk a wrong rewrite.\n    throw new Bail(`unrecognised character \"${c}\"`);\n  }\n\n  // Unclosed brackets would emit unbalanced, unparsable code — bail instead.\n  if (stack.length > 0) throw new Bail('unbalanced brackets');\n\n  return out;\n};\n\n/**\n * Compiles a single directive expression to a `with`-free arrow function.\n *\n * @example\n * ```ts\n * compileExpression('count + 1');\n * // → { ok: true, expression: 'count + 1', code: '($c) => ($c.count + 1)' }\n * ```\n */\nexport const compileExpression = (\n  expression: string,\n  options: { param?: string; globals?: Iterable<string> } = {}\n): CompiledExpression => {\n  const param = options.param ?? DEFAULT_PARAM;\n  const globals = options.globals\n    ? new Set([...DEFAULT_GLOBALS, ...options.globals])\n    : DEFAULT_GLOBALS;\n\n  const trimmed = expression.trim();\n  if (trimmed === '') {\n    return { ok: false, expression, reason: 'empty expression' };\n  }\n\n  try {\n    const body = rewrite(expression, param, globals);\n    return { ok: true, expression, code: `(${param}) => (${body})` };\n  } catch (error) {\n    const reason = error instanceof Bail ? error.message : 'could not compile expression';\n    return { ok: false, expression, reason };\n  }\n};\n","/**\n * Template walker for the optional view compiler.\n *\n * Discovers every `bq-*` directive expression that reaches the runtime\n * evaluator and compiles each one ahead of time. The walker mirrors each\n * directive's evaluation strategy exactly — object syntax for\n * `bq-class`/`bq-style`/`bq-aria` is split through the same\n * `parseObjectExpression()` the runtime uses, and `bq-for` contributes its list\n * and `:key` sub-expressions — so the compiled set is a faithful subset of what\n * the runtime would evaluate.\n *\n * @module bquery/view/compiler\n */\n\nimport { parseTemplate, type SSRNode } from '../../ssr/html-parser';\nimport { parseObjectExpression } from '../evaluate';\nimport { parseDirective } from '../parse-directive';\nimport { compileExpression } from './expression';\nimport type { CompiledView, CompileOptions, DirectiveExpression } from './types';\n\n/** Directives whose entire attribute value is one expression for the evaluator. */\nconst WHOLE_VALUE_DIRECTIVES = new Set([\n  'text',\n  'html',\n  'html-safe',\n  'if',\n  'show',\n  'bind',\n  'error',\n  'once',\n  'init',\n  'memo',\n  'model',\n  'ref',\n  'on',\n]);\n\n/** Directives that accept object syntax (`{ key: expr }`) or a whole expression. */\nconst OBJECT_OR_WHOLE_DIRECTIVES = new Set(['class', 'style', 'aria']);\n\n/** `bq-for` list-expression matcher (kept in sync with `directives/for.ts`). */\nconst FOR_RE = /^\\(?(\\w+)(?:\\s*,\\s*(\\w+))?\\)?\\s+in\\s+(\\S.*)$/;\n\n/**\n * Collects directive expressions from a single element's attributes, appending\n * to `found`.\n */\nconst collectFromElement = (\n  tag: string,\n  attributes: Record<string, string>,\n  attributeOrder: string[],\n  prefix: string,\n  found: DirectiveExpression[]\n): void => {\n  const head = `${prefix}-`;\n  for (const attrName of attributeOrder) {\n    if (!attrName.startsWith(head)) continue;\n    const { directive } = parseDirective(attrName.slice(head.length));\n    const value = attributes[attrName] ?? '';\n\n    if (directive === 'for') {\n      const match = value.match(FOR_RE);\n      if (match) {\n        found.push({ tag, directive, expression: match[3] });\n      }\n      const keyExpr = attributes[':key'] ?? attributes[`${prefix}-key`];\n      if (keyExpr) {\n        found.push({ tag, directive: 'key', expression: keyExpr });\n      }\n      continue;\n    }\n\n    if (OBJECT_OR_WHOLE_DIRECTIVES.has(directive)) {\n      if (value.trimStart().startsWith('{')) {\n        const map = parseObjectExpression(value);\n        for (const valueExpr of Object.values(map)) {\n          found.push({ tag, directive, expression: valueExpr });\n        }\n      } else if (value.trim() !== '') {\n        found.push({ tag, directive, expression: value });\n      }\n      continue;\n    }\n\n    if (WHOLE_VALUE_DIRECTIVES.has(directive) && value.trim() !== '') {\n      found.push({ tag, directive, expression: value });\n    }\n  }\n};\n\n/** Recursively walks a parsed node tree, collecting directive expressions. */\nconst walk = (node: SSRNode, prefix: string, found: DirectiveExpression[]): void => {\n  if (node.type === 'element') {\n    collectFromElement(node.tag, node.attributes, node.attributeOrder, prefix, found);\n    for (const child of node.children) walk(child, prefix, found);\n  } else if (node.type === 'fragment') {\n    for (const child of node.children) walk(child, prefix, found);\n  }\n};\n\n/**\n * Compiles every `bq-*` expression in an HTML template ahead of time.\n *\n * Returns the compiled subset (expression → emitted function source) plus\n * coverage statistics. Expressions that cannot be statically compiled are\n * listed in `stats.skipped` with a reason and transparently fall back to the\n * runtime evaluator — so a partially compiled template still behaves\n * identically.\n *\n * @example\n * ```ts\n * import { compileViews } from '@bquery/bquery/view/compiler';\n *\n * const { expressions, stats } = compileViews('<p bq-text=\"count + 1\"></p>');\n * // expressions['count + 1'] === '(__bq_ctx) => (__bq_ctx.count + 1)'\n * ```\n */\nexport const compileViews = (template: string, options: CompileOptions = {}): CompiledView => {\n  const prefix = options.prefix ?? 'bq';\n  const fragment = parseTemplate(template);\n\n  const found: DirectiveExpression[] = [];\n  walk(fragment, prefix, found);\n\n  const expressions: Record<string, string> = {};\n  const skipped: Array<{ expression: string; reason: string }> = [];\n  const seen = new Set<string>();\n  let total = 0;\n\n  for (const { expression } of found) {\n    if (seen.has(expression)) continue;\n    seen.add(expression);\n    total++;\n\n    const result = compileExpression(expression, { globals: options.globals });\n    if (result.ok) {\n      expressions[expression] = result.code;\n    } else {\n      skipped.push({ expression, reason: result.reason });\n    }\n  }\n\n  return {\n    expressions,\n    stats: { total, compiled: Object.keys(expressions).length, skipped },\n  };\n};\n","/**\n * ES-module emitter for the optional view compiler.\n *\n * Turns a {@link CompiledView} into an importable side-effect module that\n * registers the precompiled expressions at startup. The emitted code contains\n * no `with` and no `new Function()`, so importing it is safe under a strict CSP.\n *\n * @module bquery/view/compiler\n */\n\nimport { compileViews } from './compile';\nimport type { CompiledView, CompileOptions, CompileStats } from './types';\n\n/** Default module specifier the emitted code imports the runtime hook from. */\nexport const DEFAULT_IMPORT_SPECIFIER = '@bquery/bquery/view';\n\n/** Options for {@link emitModule} / {@link compileToModule}. */\nexport type EmitOptions = CompileOptions & {\n  /**\n   * Module specifier to import `registerCompiledExpressions` from. Defaults to\n   * `'@bquery/bquery/view'`; override it for monorepos or custom aliases.\n   */\n  importSpecifier?: string;\n};\n\n/**\n * Emits an importable ES module from an already-compiled view.\n */\nexport const emitModule = (\n  compiled: CompiledView,\n  importSpecifier: string = DEFAULT_IMPORT_SPECIFIER\n): string => {\n  const entries = Object.keys(compiled.expressions);\n  const lines = entries.map(\n    (expression) => `  ${JSON.stringify(expression)}: ${compiled.expressions[expression]},`\n  );\n\n  const header =\n    '// Auto-generated by @bquery/bquery/view/compiler. Do not edit by hand.\\n' +\n    `// Compiled ${compiled.stats.compiled}/${compiled.stats.total} expression(s); ` +\n    `${compiled.stats.skipped.length} fall back to the runtime evaluator.\\n`;\n\n  if (entries.length === 0) {\n    // Nothing compiled — emit a valid no-op module so the build step never\n    // produces a broken import.\n    return `${header}export {};\\n`;\n  }\n\n  return (\n    `${header}import { registerCompiledExpressions } from ${JSON.stringify(importSpecifier)};\\n\\n` +\n    `registerCompiledExpressions({\\n${lines.join('\\n')}\\n});\\n`\n  );\n};\n\n/**\n * Compiles a template and emits an importable ES module in one step.\n *\n * @returns The module source and the compile statistics (so a build tool can\n *   report or assert on coverage).\n *\n * @example\n * ```ts\n * import { compileToModule } from '@bquery/bquery/view/compiler';\n *\n * const { code, stats } = compileToModule('<p bq-text=\"count\"></p>');\n * // write `code` next to your template and import it before mounting\n * ```\n */\nexport const compileToModule = (\n  template: string,\n  options: EmitOptions = {}\n): { code: string; stats: CompileStats } => {\n  const compiled = compileViews(template, options);\n  return {\n    code: emitModule(compiled, options.importSpecifier),\n    stats: compiled.stats,\n  };\n};\n","/**\n * Build-tool-agnostic CLI for the optional view compiler.\n *\n * This is thin glue around {@link compileToModule}: it reads template files,\n * emits the precompiled-expression module beside them (or into `--out-dir`),\n * and prints a coverage summary. It is dependency-free — pass explicit file\n * paths (let your shell expand globs) — and is meant to be wired into an\n * existing build, not to become a build tool of its own.\n *\n * Node's `fs`/`path` are imported lazily so the compiler barrel stays\n * environment-neutral; only the CLI functions touch the filesystem.\n *\n * @module bquery/view/compiler\n */\n\nimport { compileToModule, type EmitOptions } from './emit';\nimport type { CompileStats } from './types';\n\n/** Options controlling where compiled modules are written. */\nexport type CompileFilesOptions = EmitOptions & {\n  /** Directory to write outputs into. Defaults to alongside each input file. */\n  outDir?: string;\n  /** Suffix appended before the output extension. Default: `'.bq-compiled'`. */\n  suffix?: string;\n  /** Output file extension. Default: `'.js'`. */\n  ext?: string;\n};\n\n/** Per-file compilation result. */\nexport type CompiledFileResult = {\n  input: string;\n  output: string;\n  stats: CompileStats;\n};\n\n/**\n * Compiles a list of template files to precompiled-expression modules.\n *\n * @example\n * ```ts\n * import { compileFiles } from '@bquery/bquery/view/compiler';\n *\n * await compileFiles(['src/views/home.html'], { outDir: 'src/views/.compiled' });\n * ```\n */\nexport const compileFiles = async (\n  files: string[],\n  options: CompileFilesOptions = {}\n): Promise<CompiledFileResult[]> => {\n  const { readFile, writeFile, mkdir } = await import('node:fs/promises');\n  const path = await import('node:path');\n\n  const suffix = options.suffix ?? '.bq-compiled';\n  const ext = options.ext ?? '.js';\n  const results: CompiledFileResult[] = [];\n\n  for (const input of files) {\n    const source = await readFile(input, 'utf8');\n    const { code, stats } = compileToModule(source, options);\n\n    const base = path.basename(input, path.extname(input));\n    const dir = options.outDir ?? path.dirname(input);\n    const output = path.join(dir, `${base}${suffix}${ext}`);\n\n    await mkdir(dir, { recursive: true });\n    await writeFile(output, code, 'utf8');\n\n    results.push({ input, output, stats });\n  }\n\n  return results;\n};\n\n/** Minimal console-shaped sink so the CLI is testable without globals. */\nexport type CliIO = { log: (msg: string) => void; error: (msg: string) => void };\n\n/**\n * Parses argv and runs {@link compileFiles}. Returns a process exit code\n * (`0` success, `1` usage error / failure).\n *\n * Usage: `bquery-view-compile [options] <file...>`\n *   --prefix <p>     directive prefix (default: bq)\n *   --out-dir <dir>  output directory (default: beside each input)\n *   --suffix <s>     output filename suffix (default: .bq-compiled)\n *   --ext <e>        output extension (default: .js)\n *   --import <spec>  import specifier (default: @bquery/bquery/view)\n */\nexport const runCompileCli = async (\n  argv: string[],\n  io: CliIO = { log: (m) => console.log(m), error: (m) => console.error(m) }\n): Promise<number> => {\n  const files: string[] = [];\n  const options: CompileFilesOptions = {};\n\n  for (let i = 0; i < argv.length; i++) {\n    const arg = argv[i];\n    switch (arg) {\n      case '--prefix':\n        options.prefix = argv[++i];\n        break;\n      case '--out-dir':\n        options.outDir = argv[++i];\n        break;\n      case '--suffix':\n        options.suffix = argv[++i];\n        break;\n      case '--ext':\n        options.ext = argv[++i];\n        break;\n      case '--import':\n        options.importSpecifier = argv[++i];\n        break;\n      case '-h':\n      case '--help':\n        io.log('Usage: bquery-view-compile [options] <file...>');\n        return 0;\n      default:\n        if (arg.startsWith('-')) {\n          io.error(`Unknown option: ${arg}`);\n          return 1;\n        }\n        files.push(arg);\n    }\n  }\n\n  if (files.length === 0) {\n    io.error('No input files. Usage: bquery-view-compile [options] <file...>');\n    return 1;\n  }\n\n  try {\n    const results = await compileFiles(files, options);\n    for (const { input, output, stats } of results) {\n      io.log(\n        `${input} → ${output}  (${stats.compiled}/${stats.total} compiled, ` +\n          `${stats.skipped.length} runtime fallback)`\n      );\n    }\n    return 0;\n  } catch (error) {\n    io.error(`view compile failed: ${error instanceof Error ? error.message : String(error)}`);\n    return 1;\n  }\n};\n"],"mappings":";;AAqBA,IAAa,IAAgB,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