anumat-engine 0.1.2__tar.gz → 0.1.3__tar.gz

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.
Files changed (43) hide show
  1. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/PKG-INFO +6 -4
  2. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/README.md +5 -3
  3. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/hatch_build.py +4 -0
  4. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/platforms.json +1 -1
  5. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/pyproject.toml +1 -1
  6. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/scripts/build-wheel.sh +4 -0
  7. anumat_engine-0.1.3/scripts/ci-convert-smoke.sh +40 -0
  8. anumat_engine-0.1.3/scripts/ci-smoke.sh +43 -0
  9. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/scripts/compile-sidecar.ts +34 -2
  10. anumat_engine-0.1.3/scripts/convert_smoke.py +76 -0
  11. anumat_engine-0.1.3/scripts/fetch-anydoc-native.mjs +126 -0
  12. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/_binary.py +14 -0
  13. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/cli.py +2 -3
  14. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/engine.py +2 -3
  15. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/fake_sidecar.py +16 -0
  16. anumat_engine-0.1.3/tests/release_fakes.py +73 -0
  17. anumat_engine-0.1.3/tests/test_binary.py +33 -0
  18. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/test_engine.py +14 -4
  19. anumat_engine-0.1.3/tests/test_release_ci_bundle.py +611 -0
  20. anumat_engine-0.1.3/tests/test_release_npm.py +227 -0
  21. anumat_engine-0.1.3/tests/test_release_pypi_publish.py +317 -0
  22. anumat_engine-0.1.3/tests/test_release_registry.py +227 -0
  23. anumat_engine-0.1.3/tests/test_release_scripts_contract.py +199 -0
  24. anumat_engine-0.1.3/tests/test_release_tags_and_wheels.py +160 -0
  25. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/test_release_version.py +26 -49
  26. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/test_smoke_venv.py +59 -19
  27. anumat_engine-0.1.2/scripts/ci-smoke.sh +0 -52
  28. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/.gitignore +0 -0
  29. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/LICENSE +0 -0
  30. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/NOTICE +0 -0
  31. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/THIRD_PARTY_NOTICES +0 -0
  32. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/platform_error.py +0 -0
  33. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/scripts/check-sidecar-syntax.py +0 -0
  34. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/scripts/smoke.py +0 -0
  35. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/__init__.py +0 -0
  36. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/__main__.py +0 -0
  37. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/errors.py +0 -0
  38. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/py.typed +0 -0
  39. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/src/anumat_engine/slug.py +0 -0
  40. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/crash_sidecar.py +0 -0
  41. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/test_parity.py +0 -0
  42. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/test_policy_cases.py +0 -0
  43. {anumat_engine-0.1.2 → anumat_engine-0.1.3}/tests/test_require_local_postgres.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: anumat-engine
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Run the Anumat engine on your machine
5
5
  Project-URL: Repository, https://github.com/AmitMirgal/anumat
6
6
  License-Expression: Apache-2.0
@@ -19,7 +19,7 @@ Description-Content-Type: text/markdown
19
19
  pip install anumat-engine
20
20
  ```
21
21
 
22
- Each wheel contains the binary for one platform.
22
+ Each wheel contains the sidecar binary for one platform and the matching `@firecrawl/anydoc` native binding (`anydoc.node`) next to it. The compiled sidecar cannot load that `.node` from Bun's virtual `$bunfs`, so the wheel ships a real file and the process sets `NAPI_RS_NATIVE_LIBRARY_PATH`.
23
23
 
24
24
  ## Extract without a database
25
25
 
@@ -87,7 +87,9 @@ For local files, pass `storage={"kind": "local", "data_dir": "data/policies"}`.
87
87
 
88
88
  `endpoint` on S3 is the custom URL for an S3-compatible store. Prefer `kind` `gcs` or `supabase` when you want the native SDK. The HTTP API uses `ANUMAT_STORAGE` and the matching `ANUMAT_*` variables instead of these arguments, and it requires `DATABASE_URL`.
89
89
 
90
- Pass `llm={"strong": "anthropic/claude-sonnet-4-5", "cheap": "anthropic/claude-haiku-4-5"}` when extract or a check should call a model. Omit `llm` until a call needs one.
90
+ Pass `llm={"strong": "anthropic/claude-sonnet-4-5", "cheap": "anthropic/claude-haiku-4-5"}` when extract or a check should call a model. Omit `llm` until a call needs one. Google: `{"strong": "google/gemini-2.5-pro", "cheap": "google/gemini-2.5-flash"}` with `GOOGLE_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY` in the environment.
91
+
92
+ Text PDFs convert inside the sidecar with local `@firecrawl/anydoc`. That does not need a Firecrawl API key. Two-column policy-name / CPT tables convert to Markdown tables and extract as structured codes. Python `create_engine` has no `firecrawl` argument, so a scanned PDF that needs OCR fails with `ocr_not_configured`. Empty or code-dropping conversions fail with `conversion_failed`. A `not_a_policy` `EngineError` includes `details` with the character count and outline sections triage saw.
91
93
 
92
94
  Engine methods use snake_case names for the functions exported by `@anumat/engine`. `engine.list_payers()` calls `listPayers`. `slugify` is the same slug function the JavaScript package exports.
93
95
 
@@ -111,6 +113,6 @@ The engine object has these methods besides `close`.
111
113
 
112
114
  Installing the source distribution on a platform without a wheel fails with the list of wheel tags. It does not leave a partial install that imports.
113
115
 
114
- Package tests include a catalog path against Postgres. Runtime extract without `database_url` does not need a database; those tests do. Start the repository README disposable server (`anumat-postgres`, role `anumat` / `anumat` on `127.0.0.1:5432`) and keep `psql` on `PATH`. `test_python_policy_cases_match_the_shared_fixture` drops and recreates only `anumat_engine_parity`. It does not drop `anumat` or `anumat_test`. Do not point it at a database you need to keep. `pnpm release:engine-py` checks that port before pytest and does not start Docker for you.
116
+ Package tests include a catalog path against Postgres. Runtime extract without `database_url` does not need a database; those tests do. Start the repository README disposable server (`anumat-postgres`, role `anumat` / `anumat` on `127.0.0.1:5432`) and keep `psql` on `PATH`. `test_python_policy_cases_match_the_shared_fixture` drops and recreates only `anumat_engine_parity`. It does not drop `anumat` or `anumat_test`. Do not point it at a database you need to keep. `pnpm release:engine-py` checks that port before pytest, downloads the Engine wheels CI bundle for this commit, and does not compile wheels on the laptop or start Docker.
115
117
 
116
118
  `create_engine()` with no arguments is valid. Catalog methods then raise `EngineError` with code `database_not_configured` until you pass `database_url`.
@@ -8,7 +8,7 @@
8
8
  pip install anumat-engine
9
9
  ```
10
10
 
11
- Each wheel contains the binary for one platform.
11
+ Each wheel contains the sidecar binary for one platform and the matching `@firecrawl/anydoc` native binding (`anydoc.node`) next to it. The compiled sidecar cannot load that `.node` from Bun's virtual `$bunfs`, so the wheel ships a real file and the process sets `NAPI_RS_NATIVE_LIBRARY_PATH`.
12
12
 
13
13
  ## Extract without a database
14
14
 
@@ -76,7 +76,9 @@ For local files, pass `storage={"kind": "local", "data_dir": "data/policies"}`.
76
76
 
77
77
  `endpoint` on S3 is the custom URL for an S3-compatible store. Prefer `kind` `gcs` or `supabase` when you want the native SDK. The HTTP API uses `ANUMAT_STORAGE` and the matching `ANUMAT_*` variables instead of these arguments, and it requires `DATABASE_URL`.
78
78
 
79
- Pass `llm={"strong": "anthropic/claude-sonnet-4-5", "cheap": "anthropic/claude-haiku-4-5"}` when extract or a check should call a model. Omit `llm` until a call needs one.
79
+ Pass `llm={"strong": "anthropic/claude-sonnet-4-5", "cheap": "anthropic/claude-haiku-4-5"}` when extract or a check should call a model. Omit `llm` until a call needs one. Google: `{"strong": "google/gemini-2.5-pro", "cheap": "google/gemini-2.5-flash"}` with `GOOGLE_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY` in the environment.
80
+
81
+ Text PDFs convert inside the sidecar with local `@firecrawl/anydoc`. That does not need a Firecrawl API key. Two-column policy-name / CPT tables convert to Markdown tables and extract as structured codes. Python `create_engine` has no `firecrawl` argument, so a scanned PDF that needs OCR fails with `ocr_not_configured`. Empty or code-dropping conversions fail with `conversion_failed`. A `not_a_policy` `EngineError` includes `details` with the character count and outline sections triage saw.
80
82
 
81
83
  Engine methods use snake_case names for the functions exported by `@anumat/engine`. `engine.list_payers()` calls `listPayers`. `slugify` is the same slug function the JavaScript package exports.
82
84
 
@@ -100,6 +102,6 @@ The engine object has these methods besides `close`.
100
102
 
101
103
  Installing the source distribution on a platform without a wheel fails with the list of wheel tags. It does not leave a partial install that imports.
102
104
 
103
- Package tests include a catalog path against Postgres. Runtime extract without `database_url` does not need a database; those tests do. Start the repository README disposable server (`anumat-postgres`, role `anumat` / `anumat` on `127.0.0.1:5432`) and keep `psql` on `PATH`. `test_python_policy_cases_match_the_shared_fixture` drops and recreates only `anumat_engine_parity`. It does not drop `anumat` or `anumat_test`. Do not point it at a database you need to keep. `pnpm release:engine-py` checks that port before pytest and does not start Docker for you.
105
+ Package tests include a catalog path against Postgres. Runtime extract without `database_url` does not need a database; those tests do. Start the repository README disposable server (`anumat-postgres`, role `anumat` / `anumat` on `127.0.0.1:5432`) and keep `psql` on `PATH`. `test_python_policy_cases_match_the_shared_fixture` drops and recreates only `anumat_engine_parity`. It does not drop `anumat` or `anumat_test`. Do not point it at a database you need to keep. `pnpm release:engine-py` checks that port before pytest, downloads the Engine wheels CI bundle for this commit, and does not compile wheels on the laptop or start Docker.
104
106
 
105
107
  `create_engine()` with no arguments is valid. Catalog methods then raise `EngineError` with code `database_not_configured` until you pass `database_url`.
@@ -29,8 +29,11 @@ class CustomBuildHook(BuildHookInterface):
29
29
  raise RuntimeError(_source_install_error())
30
30
  binary_name = "anumat-engine.exe" if platform.startswith("win_") else "anumat-engine"
31
31
  binary = Path(self.root) / "src" / "anumat_engine" / "bin" / binary_name
32
+ native = Path(self.root) / "src" / "anumat_engine" / "bin" / "anydoc.node"
32
33
  if not binary.is_file():
33
34
  raise RuntimeError(f"Missing {binary}")
35
+ if not native.is_file():
36
+ raise RuntimeError(f"Missing {native}")
34
37
  build_data["pure_python"] = False
35
38
  build_data["tag"] = f"py3-none-{platform}"
36
39
  force_include = build_data.get("force_include")
@@ -38,3 +41,4 @@ class CustomBuildHook(BuildHookInterface):
38
41
  force_include = {}
39
42
  build_data["force_include"] = force_include
40
43
  force_include[str(binary)] = f"anumat_engine/bin/{binary_name}"
44
+ force_include[str(native)] = "anumat_engine/bin/anydoc.node"
@@ -32,6 +32,6 @@
32
32
  "target": "bun-windows-x64",
33
33
  "platform": "win_amd64",
34
34
  "binary": "anumat-engine.exe",
35
- "smoke": true
35
+ "smoke": false
36
36
  }
37
37
  ]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "anumat-engine"
3
- version = "0.1.2"
3
+ version = "0.1.3"
4
4
  description = "Run the Anumat engine on your machine"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -28,6 +28,10 @@ if [[ ! -f "$stage/$binary_name" ]]; then
28
28
  echo "Compile did not write $stage/$binary_name" >&2
29
29
  exit 1
30
30
  fi
31
+ if [[ ! -f "$stage/anydoc.node" ]]; then
32
+ echo "Compile did not write $stage/anydoc.node" >&2
33
+ exit 1
34
+ fi
31
35
  chmod +x "$stage/$binary_name" || true
32
36
  if command -v python3 >/dev/null 2>&1; then
33
37
  PYTHON=python3
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Install the native wheel in an owned venv, start the sidecar, and convert a
5
+ # text PDF. Does not start Docker or Postgres.
6
+
7
+ root=$(cd "$(dirname "$0")/../../.." && pwd)
8
+ cd "$root"
9
+ dist=${1:-dist}
10
+
11
+ python_bin=python3
12
+ if ! command -v python3 >/dev/null 2>&1; then
13
+ python_bin=python
14
+ fi
15
+ wheel=$("$python_bin" scripts/release/select_native_wheel.py "$dist")
16
+
17
+ smoke_work=
18
+ cleanup() {
19
+ if [[ -n "${smoke_work:-}" ]]; then
20
+ rm -rf "$smoke_work"
21
+ fi
22
+ }
23
+ trap cleanup EXIT
24
+ {
25
+ IFS= read -r smoke_work
26
+ IFS= read -r smoke_python
27
+ } < <(bash scripts/release/make-smoke-venv.sh anumat-engine-convert-smoke)
28
+ if [[ -z "$smoke_work" || -z "${smoke_python:-}" || ! -x "$smoke_python" ]]; then
29
+ echo "failed to create the engine convert-smoke virtualenv" >&2
30
+ exit 1
31
+ fi
32
+ case "$smoke_python" in
33
+ "$smoke_work"/*) ;;
34
+ *)
35
+ echo "convert-smoke python is not inside the owned workspace" >&2
36
+ exit 1
37
+ ;;
38
+ esac
39
+ uv pip install -q --python "$smoke_python" "$wheel"
40
+ "$smoke_python" packages/engine-py/scripts/convert_smoke.py
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ root=$(cd "$(dirname "$0")/../../.." && pwd)
5
+ cd "$root"
6
+ dist=${1:-dist}
7
+
8
+ export DATABASE_URL="${DATABASE_URL:-postgres://anumat:anumat@127.0.0.1:5432/anumat_engine}"
9
+ export ANUMAT_MIGRATION_SQL="${ANUMAT_MIGRATION_SQL:-packages/db/prisma/migrations/20260929061425_init/migration.sql}"
10
+
11
+ bash scripts/require-local-postgres.sh
12
+ node packages/engine/scripts/ensure-smoke-database.mjs
13
+
14
+ python_bin=python3
15
+ if ! command -v python3 >/dev/null 2>&1; then
16
+ python_bin=python
17
+ fi
18
+ wheel=$("$python_bin" scripts/release/select_native_wheel.py "$dist")
19
+
20
+ smoke_work=
21
+ cleanup() {
22
+ if [[ -n "${smoke_work:-}" ]]; then
23
+ rm -rf "$smoke_work"
24
+ fi
25
+ }
26
+ trap cleanup EXIT
27
+ {
28
+ IFS= read -r smoke_work
29
+ IFS= read -r smoke_python
30
+ } < <(bash scripts/release/make-smoke-venv.sh anumat-engine-smoke)
31
+ if [[ -z "$smoke_work" || -z "${smoke_python:-}" || ! -x "$smoke_python" ]]; then
32
+ echo "failed to create the engine smoke virtualenv" >&2
33
+ exit 1
34
+ fi
35
+ case "$smoke_python" in
36
+ "$smoke_work"/*) ;;
37
+ *)
38
+ echo "smoke python is not inside the owned workspace" >&2
39
+ exit 1
40
+ ;;
41
+ esac
42
+ uv pip install -q --python "$smoke_python" "$wheel"
43
+ "$smoke_python" packages/engine-py/scripts/smoke.py
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, readFileSync } from 'node:fs';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
@@ -22,9 +22,41 @@ if (bundled.status !== 0) {
22
22
  const entry = bundled.stdout.trim();
23
23
  assertNoBuildPath('prebundled sidecar', readFileSync(entry), root);
24
24
 
25
+ // bun compile stores JS on $bunfs. dlopen cannot load a napi .node from
26
+ // there, so --asset / embedding the binding inside the binary does not work.
27
+ // Ship anydoc.node next to the executable and point NAPI-RS at that real path.
28
+ const nativeDest = join(dirname(outfile), 'anydoc.node');
29
+ mkdirSync(dirname(nativeDest), { recursive: true });
30
+ const fetched = spawnSync(
31
+ 'node',
32
+ [join(root, 'packages/engine-py/scripts/fetch-anydoc-native.mjs'), target, nativeDest],
33
+ { encoding: 'utf8' },
34
+ );
35
+ if (fetched.status !== 0) {
36
+ process.stderr.write(fetched.stderr);
37
+ process.stderr.write(fetched.stdout);
38
+ process.exit(fetched.status ?? 1);
39
+ }
40
+ process.stdout.write(fetched.stdout);
41
+
42
+ const compileEntry = join(dirname(entry), 'compile-entry.mjs');
43
+ writeFileSync(
44
+ compileEntry,
45
+ `import { existsSync } from 'node:fs';
46
+ import { dirname, join } from 'node:path';
47
+
48
+ if (!process.env.NAPI_RS_NATIVE_LIBRARY_PATH) {
49
+ const candidate = join(dirname(process.execPath), 'anydoc.node');
50
+ if (existsSync(candidate)) process.env.NAPI_RS_NATIVE_LIBRARY_PATH = candidate;
51
+ }
52
+
53
+ await import('./sidecar.mjs');
54
+ `,
55
+ );
56
+
25
57
  const stub = join(root, 'packages/engine/src/optional/empty.ts');
26
58
  const result = await Bun.build({
27
- entrypoints: [entry],
59
+ entrypoints: [compileEntry],
28
60
  compile: {
29
61
  target,
30
62
  outfile,
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import subprocess
5
+ import sys
6
+ import tempfile
7
+ from pathlib import Path
8
+
9
+ from anumat_engine import create_engine
10
+ from anumat_engine._binary import binary_path, sidecar_env
11
+
12
+
13
+ def code_list_pdf() -> bytes:
14
+ content = [
15
+ "BT",
16
+ "/F1 12 Tf",
17
+ "72 740 Td (Prior Authorization Code List) Tj",
18
+ "1 0 0 1 0 0 Tm",
19
+ "72 718 Td (Policy Name) Tj",
20
+ "1 0 0 1 0 0 Tm",
21
+ "360 718 Td (CPT Code) Tj",
22
+ "1 0 0 1 0 0 Tm",
23
+ "72 700 Td (Bariatric Surgery) Tj",
24
+ "1 0 0 1 0 0 Tm",
25
+ "360 700 Td (43644) Tj",
26
+ "ET",
27
+ ]
28
+ stream_body = "\n".join(content)
29
+ objects = [
30
+ "<< /Type /Catalog /Pages 2 0 R >>",
31
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
32
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
33
+ f"<< /Length {len(stream_body.encode())} >>\nstream\n{stream_body}\nendstream",
34
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
35
+ ]
36
+ pdf = "%PDF-1.4\n"
37
+ offsets: list[int] = []
38
+ for index, body in enumerate(objects):
39
+ offsets.append(len(pdf.encode()))
40
+ pdf += f"{index + 1} 0 obj\n{body}\nendobj\n"
41
+ xref = len(pdf.encode())
42
+ pdf += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n"
43
+ pdf += "".join(f"{offset:010d} 00000 n \n" for offset in offsets)
44
+ pdf += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"
45
+ return pdf.encode()
46
+
47
+
48
+ def main() -> None:
49
+ pdf = code_list_pdf()
50
+ with create_engine():
51
+ pass
52
+ with tempfile.TemporaryDirectory(prefix="anumat-convert-smoke-") as tmp:
53
+ path = Path(tmp) / "policy.pdf"
54
+ path.write_bytes(pdf)
55
+ completed = subprocess.run(
56
+ [str(binary_path()), "convert", "--pdf", str(path)],
57
+ check=False,
58
+ capture_output=True,
59
+ text=True,
60
+ env=sidecar_env(),
61
+ )
62
+ sys.stdout.write(completed.stdout)
63
+ sys.stderr.write(completed.stderr)
64
+ if completed.returncode != 0:
65
+ raise SystemExit(f"convert failed ({completed.returncode})")
66
+ payload = json.loads(completed.stdout)
67
+ if payload.get("converter") != "anydoc":
68
+ raise SystemExit(f"expected converter anydoc, got {payload!r}")
69
+ markdown = payload.get("markdown")
70
+ if not isinstance(markdown, str) or "43644" not in markdown:
71
+ raise SystemExit(f"convert markdown did not keep CPT 43644: {payload!r}")
72
+ print("convert smoke ok")
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Place the target-platform @firecrawl/anydoc napi .node next to the sidecar.
4
+ * bun compile cannot dlopen a native addon from $bunfs; NAPI-RS loads
5
+ * NAPI_RS_NATIVE_LIBRARY_PATH from a real file.
6
+ */
7
+ import { spawnSync } from 'node:child_process';
8
+ import { copyFileSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ import { createRequire } from 'node:module';
12
+ import { fileURLToPath, pathToFileURL } from 'node:url';
13
+
14
+ export const ANYDOC_NATIVE_BY_BUN_TARGET = {
15
+ 'bun-darwin-arm64': { pkg: '@firecrawl/anydoc-darwin-arm64', file: 'anydoc.darwin-arm64.node' },
16
+ 'bun-darwin-x64': { pkg: '@firecrawl/anydoc-darwin-x64', file: 'anydoc.darwin-x64.node' },
17
+ 'bun-linux-x64': { pkg: '@firecrawl/anydoc-linux-x64-gnu', file: 'anydoc.linux-x64-gnu.node' },
18
+ 'bun-linux-arm64': { pkg: '@firecrawl/anydoc-linux-arm64-gnu', file: 'anydoc.linux-arm64-gnu.node' },
19
+ 'bun-windows-x64': { pkg: '@firecrawl/anydoc-win32-x64-msvc', file: 'anydoc.win32-x64-msvc.node' },
20
+ };
21
+
22
+ const root = join(dirname(fileURLToPath(import.meta.url)), '../../..');
23
+
24
+ export function anydocVersion(repo = root) {
25
+ try {
26
+ const require = createRequire(join(repo, 'packages/engine/package.json'));
27
+ const installed = JSON.parse(readFileSync(require.resolve('@firecrawl/anydoc/package.json'), 'utf8'));
28
+ if (typeof installed.version === 'string' && /^\d+\.\d+\.\d+/.test(installed.version)) {
29
+ return installed.version;
30
+ }
31
+ } catch {
32
+ // Fall through to the range in packages/engine/package.json.
33
+ }
34
+ const pkg = JSON.parse(readFileSync(join(repo, 'packages/engine/package.json'), 'utf8'));
35
+ const raw = pkg.dependencies?.['@firecrawl/anydoc'];
36
+ if (typeof raw !== 'string' || raw === '') {
37
+ throw new Error('packages/engine/package.json is missing @firecrawl/anydoc');
38
+ }
39
+ const version = raw.replace(/^[^\d]*/, '');
40
+ if (!/^\d+\.\d+\.\d+/.test(version)) {
41
+ throw new Error(`cannot parse @firecrawl/anydoc version from ${raw}`);
42
+ }
43
+ return version;
44
+ }
45
+
46
+ function findInNodeModules(npmPkg, file) {
47
+ try {
48
+ const require = createRequire(join(root, 'packages/engine/package.json'));
49
+ const pkgJson = require.resolve(`${npmPkg}/package.json`);
50
+ const nodePath = join(dirname(pkgJson), file);
51
+ if (existsSync(nodePath)) return nodePath;
52
+ } catch {
53
+ // pnpm does not let the engine package require optional platform addons.
54
+ }
55
+ const pnpmDir = join(root, 'node_modules/.pnpm');
56
+ if (!existsSync(pnpmDir)) return null;
57
+ const prefix = `${npmPkg.replace(/^@/, '').replace('/', '+')}@`;
58
+ for (const entry of readdirSync(pnpmDir)) {
59
+ if (!entry.startsWith(prefix)) continue;
60
+ const nodePath = join(pnpmDir, entry, 'node_modules', npmPkg, file);
61
+ if (existsSync(nodePath)) return nodePath;
62
+ }
63
+ return null;
64
+ }
65
+
66
+ function npmPackNode(npmPkg, file, version) {
67
+ const dir = mkdtempSync(join(tmpdir(), 'anydoc-native-'));
68
+ try {
69
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
70
+ const packed = spawnSync(npm, ['pack', `${npmPkg}@${version}`, '--pack-destination', dir], {
71
+ encoding: 'utf8',
72
+ shell: process.platform === 'win32',
73
+ });
74
+ if (packed.status !== 0) {
75
+ process.stderr.write(packed.stderr || packed.stdout || 'npm pack failed\n');
76
+ throw new Error(`npm pack ${npmPkg}@${version} failed`);
77
+ }
78
+ const tgz = readdirSync(dir).find((name) => name.endsWith('.tgz'));
79
+ if (!tgz) throw new Error(`npm pack did not write a tarball in ${dir}`);
80
+ // GNU tar treats C: in an absolute Windows path as a remote host.
81
+ // Extract by tarball basename with cwd set to the temp dir.
82
+ const tarArgs = process.platform === 'win32' ? ['--force-local', '-xzf', tgz] : ['-xzf', tgz];
83
+ const extracted = spawnSync('tar', tarArgs, { cwd: dir, encoding: 'utf8' });
84
+ if (extracted.status !== 0) {
85
+ process.stderr.write(extracted.stderr || extracted.stdout || 'tar failed\n');
86
+ throw new Error(`failed to extract ${tgz}`);
87
+ }
88
+ const nodePath = join(dir, 'package', file);
89
+ if (!existsSync(nodePath)) {
90
+ throw new Error(`${npmPkg}@${version} is missing ${file}`);
91
+ }
92
+ return { nodePath, cleanup: dir };
93
+ } catch (error) {
94
+ rmSync(dir, { recursive: true, force: true });
95
+ throw error;
96
+ }
97
+ }
98
+
99
+ export function fetchAnydocNative(target, dest) {
100
+ const spec = ANYDOC_NATIVE_BY_BUN_TARGET[target];
101
+ if (!spec) throw new Error(`no @firecrawl/anydoc native package for bun target ${target}`);
102
+ const version = anydocVersion();
103
+ let source = findInNodeModules(spec.pkg, spec.file);
104
+ let cleanup = null;
105
+ if (!source) {
106
+ const packed = npmPackNode(spec.pkg, spec.file, version);
107
+ source = packed.nodePath;
108
+ cleanup = packed.cleanup;
109
+ }
110
+ copyFileSync(source, dest);
111
+ if (cleanup) rmSync(cleanup, { recursive: true, force: true });
112
+ return dest;
113
+ }
114
+
115
+ const invokedAsScript =
116
+ Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;
117
+ if (invokedAsScript) {
118
+ const target = process.argv[2];
119
+ const dest = process.argv[3];
120
+ if (!target || !dest) {
121
+ console.error('Usage: fetch-anydoc-native.mjs <bun-target> <dest-anydoc.node>');
122
+ process.exit(1);
123
+ }
124
+ fetchAnydocNative(target, dest);
125
+ console.log(`wrote ${dest} for ${target}`);
126
+ }
@@ -19,3 +19,17 @@ def binary_path() -> Path:
19
19
  if not path.is_file():
20
20
  raise EngineError(f"anumat-engine binary is not installed at {path}", code="internal")
21
21
  return path
22
+
23
+
24
+ def native_library_path() -> Path | None:
25
+ path = binary_path().parent / "anydoc.node"
26
+ return path if path.is_file() else None
27
+
28
+
29
+ def sidecar_env(base: dict[str, str] | None = None) -> dict[str, str]:
30
+ env = os.environ.copy() if base is None else dict(base)
31
+ env["ANUMAT_ENGINE_SIDECAR"] = "1"
32
+ native = native_library_path()
33
+ if native is not None:
34
+ env["NAPI_RS_NATIVE_LIBRARY_PATH"] = str(native)
35
+ return env
@@ -1,10 +1,9 @@
1
1
  from __future__ import annotations
2
2
 
3
- import os
4
3
  import subprocess
5
4
  import sys
6
5
 
7
- from anumat_engine._binary import binary_path
6
+ from anumat_engine._binary import binary_path, sidecar_env
8
7
 
9
8
  USAGE = "Usage: anumat-engine migrate --db <url>"
10
9
 
@@ -22,7 +21,7 @@ def main(argv: list[str] | None = None) -> None:
22
21
  raise SystemExit(1) from None
23
22
  completed = subprocess.run(
24
23
  [str(binary_path()), "migrate", "--db", database_url],
25
- env={**os.environ, "ANUMAT_ENGINE_SIDECAR": "1"},
24
+ env=sidecar_env(),
26
25
  check=False,
27
26
  )
28
27
  raise SystemExit(completed.returncode)
@@ -15,7 +15,7 @@ import urllib.parse
15
15
  import urllib.request
16
16
  from typing import Any, Literal, TypedDict
17
17
 
18
- from anumat_engine._binary import binary_path
18
+ from anumat_engine._binary import binary_path, sidecar_env
19
19
  from anumat_engine.errors import EngineError
20
20
 
21
21
  JsonObject = dict[str, Any]
@@ -270,8 +270,7 @@ def create_engine(
270
270
 
271
271
 
272
272
  def _spawn(binary: os.PathLike[str]) -> subprocess.Popen[bytes]:
273
- env = os.environ.copy()
274
- env["ANUMAT_ENGINE_SIDECAR"] = "1"
273
+ env = sidecar_env()
275
274
  command = [os.fspath(binary), "serve"]
276
275
  if os.name == "posix":
277
276
  return subprocess.Popen(
@@ -42,6 +42,22 @@ class Handler(BaseHTTPRequestHandler):
42
42
  self._json(200, {"result": {"items": [], "nextCursor": None}})
43
43
  return
44
44
  if method == "extract":
45
+ incoming = payload.get("input") if isinstance(payload.get("input"), dict) else {}
46
+ if incoming.get("title") == "Retired notice":
47
+ self._json(
48
+ 422,
49
+ {
50
+ "error": {
51
+ "code": "not_a_policy",
52
+ "message": "Triage found no prior-auth rules in document x after seeing 12 characters across 1 outline sections [Preamble (12 chars)]: Retired policy notice",
53
+ "details": {
54
+ "total_chars": 12,
55
+ "sections": [{"id": "preamble", "heading": "Preamble", "chars": 12}],
56
+ },
57
+ }
58
+ },
59
+ )
60
+ return
45
61
  self._json(
46
62
  200,
47
63
  {
@@ -0,0 +1,73 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import stat
5
+ import threading
6
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
7
+ from pathlib import Path
8
+ from typing import Any
9
+ from urllib.parse import unquote, urlparse
10
+
11
+
12
+ class FakeRegistry:
13
+ def __init__(self) -> None:
14
+ self.routes: dict[str, tuple[int, bytes]] = {}
15
+ self.requests: list[str] = []
16
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
17
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
18
+
19
+ def _handler(self) -> type[BaseHTTPRequestHandler]:
20
+ registry = self
21
+
22
+ class Handler(BaseHTTPRequestHandler):
23
+ def do_GET(self) -> None: # noqa: N802
24
+ path = unquote(urlparse(self.path).path)
25
+ registry.requests.append(path)
26
+ status, body = registry.routes.get(path, (404, b'{"message":"missing"}'))
27
+ self.send_response(status)
28
+ self.send_header("Content-Type", "application/json")
29
+ self.send_header("Content-Length", str(len(body)))
30
+ self.end_headers()
31
+ self.wfile.write(body)
32
+
33
+ def log_message(self, format: str, *args: object) -> None: # noqa: A003
34
+ return
35
+
36
+ return Handler
37
+
38
+ def start(self) -> None:
39
+ self.thread.start()
40
+
41
+ def stop(self) -> None:
42
+ self.server.shutdown()
43
+ self.thread.join(timeout=5)
44
+
45
+ @property
46
+ def origin(self) -> str:
47
+ host, port = self.server.server_address[:2]
48
+ return f"http://{host}:{port}"
49
+
50
+ def pypi_index(self) -> str:
51
+ return f"{self.origin}/pypi"
52
+
53
+ def npm_registry(self) -> str:
54
+ return f"{self.origin}/npm"
55
+
56
+ def set_pypi(self, name: str, version: str, status: int, payload: dict[str, Any] | None) -> None:
57
+ body = b"" if payload is None else json.dumps(payload).encode()
58
+ self.routes[f"/pypi/{name}/{version}/json"] = (status, body)
59
+
60
+ def set_npm(self, name: str, version: str, status: int, payload: dict[str, Any] | None) -> None:
61
+ body = b"" if payload is None else json.dumps(payload).encode()
62
+ self.routes[f"/npm/{name}/{version}"] = (status, body)
63
+
64
+
65
+ def write_executable(path: Path, text: str) -> None:
66
+ path.write_text(text)
67
+ path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
68
+
69
+
70
+ def sha256_bytes(data: bytes) -> str:
71
+ import hashlib
72
+
73
+ return hashlib.sha256(data).hexdigest()
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from anumat_engine._binary import sidecar_env
8
+
9
+
10
+ def test_sidecar_env_points_napi_at_anydoc_next_to_the_binary(
11
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
12
+ ) -> None:
13
+ binary = tmp_path / "anumat-engine"
14
+ native = tmp_path / "anydoc.node"
15
+ binary.write_bytes(b"")
16
+ native.write_bytes(b"native")
17
+ monkeypatch.setenv("ANUMAT_ENGINE_BINARY", str(binary))
18
+ env = sidecar_env({"KEEP": "1"})
19
+ assert env["ANUMAT_ENGINE_SIDECAR"] == "1"
20
+ assert env["NAPI_RS_NATIVE_LIBRARY_PATH"] == str(native)
21
+ assert env["KEEP"] == "1"
22
+
23
+
24
+ def test_sidecar_env_omits_napi_when_anydoc_is_missing(
25
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
26
+ ) -> None:
27
+ binary = tmp_path / "anumat-engine"
28
+ binary.write_bytes(b"")
29
+ monkeypatch.setenv("ANUMAT_ENGINE_BINARY", str(binary))
30
+ monkeypatch.delenv("NAPI_RS_NATIVE_LIBRARY_PATH", raising=False)
31
+ env = sidecar_env()
32
+ assert env["ANUMAT_ENGINE_SIDECAR"] == "1"
33
+ assert "NAPI_RS_NATIVE_LIBRARY_PATH" not in env