YAML detector rules¶
BizMap ships language engines (Go, Python, and JavaScript/TypeScript) that interpret declarative YAML rules. Adding a framework should mean adding a YAML file, not a parser.
Bundled rules live in src/bizmap/rules/. Pass extra files or directories with
bizmap scan --rules path.
Rule shape¶
id: echo.v4.routes # unique
language: go # go | python | javascript | typescript
framework: echo
description: human text
status: active # active | stub (stubs are documented but not run)
when:
imports:
contains: github.com/labstack/echo
optional: false
detect:
calls: # Go / Python call expressions
method:
in: [GET, POST, PUT, PATCH, DELETE]
# or: regex: "^(Exec|Query|QueryRow)$"
arguments:
path: { index: 0, capture: string }
handler: { index: 1, capture: ident_or_selector }
sql: { index: 1, capture: string_or_ident }
go_statement: true # any `go` statement (v0.1.1)
go_call: # still accepted; engine no longer requires method==Run
method: Run
requires_inside_callee:
calls: { method: { in: [NewTicker, Tick, After] }, receiver: time }
cron_imports: { contains: [github.com/robfig/cron, github.com/go-co-op/gocron] }
cron_methods: { in: [AddFunc, AddJob, Schedule, Start] }
decorators: # Python @app.get("/path")
method: { in: [get, post, put, patch, delete] }
arguments:
path: { index: 0, capture: string }
options:
receiver_path_prefixes: # Echo Group("/api") path join
group_method: Group
path_arg: 0
produce:
entrypoint:
kind: http # http | scheduled_job | firestore | celery_task | worker | ...
method: "{method}"
path: "{path}"
handler: "{handler}"
sql:
dialect: postgres
source: "{sql}"
caller: "{enclosing_function}"
String arguments are resolved from:
- interpreted / raw string literals
- same-package
const(andvar) string values - cross-package
pkg.Constvia the file's import map (including aliases) +concatenation of the above (unresolved pieces become{pkg.Const}placeholders)- local
q := constA + constBthenQuery(ctx, q) - Echo
Groupprefixes, including const prefixes
Anything involving a non-literal identifier is marked unknown. Truncated
paths such as /setup from otherpkg.PendingPath+"/setup" are not emitted.
Python resolution (v0.2)¶
- Function display names are the module path relative to the scan root
(
catalog.db.create_order,python.worker.low_stock). - Route strings resolve from literals, same-module assignments, imported
names (
from .paths import PREFIX),+concatenation, and f-strings. Unresolvable pieces become{module.NAME}placeholders withunresolved: true— never a truncated path such as/hidden. - FastAPI
APIRouter(prefix=)andapp.include_router(router, prefix=)join onto handler paths. Flask@app.route/Blueprint(url_prefix=)use the same string resolver. Factories that returnFastAPI()/APIRouter()/Flask()(and apps imported from another module) keep their@app.get/@app.route/@app.api_route. Otherwise a module-level@name.get("/path")is accepted;@patch("x.y")is not. Route decorators and app/router registrations are never outboundcalls_http. - SQLAlchemy models (
__tablename__,mapped_column,Table(...)) and Alembicop.create_table/add_column/drop_*feed the schema replayer. Alembicupgradefunctions are taggedrole: schema. - Firestore
collection(name).document(...).set/get/...walks the chain; the lastcollection()name is thecollection:node. Nested subcollections are not joined into a single path. - Queue produce sites (
delay,enqueue,create_task,publish) emitenqueues. Cloud Tasks HTTP URLs also becomecalls_httpwhen they match a scanned route. A one-hop helper (create_task(task={'http_request': {'url': _get_url()}})where_get_urlreturns an f-string) is traced to that return value.queues: {queue_name: <entrypoint id or route>}links a producer even without an extractedhttp_url. - Constructor / annotation dispatch:
Drainer(outbox)thenself.outbox.settle(...), ordef run(store: Store): store.save(...), follows the class method (inferred). A single Protocol/ABC implementer is used when the annotation is abstract. Dataclass/attrsCallablefields union every construction site;svc = Svc(fn); svc.go()on a module-level instance resolves to the class method. Unresolvable typed dispatch isunresolved_calls. Non-DB calls inside Firestore.update({...})/.set({...})dicts are not SQL. - Client URLs keep the env/host origin (
os.environ["X_URL"],os.getenv,settings.x_url, a constant, or a hostname) through local assignments (base = os.environ["X_URL"]; post(base+"/p")).services:env matching uses that origin, not the local variable name. Helpers such as_post(self, path)that callself._transport.requestwithself.base_url + pathcompose{base}+pathat the caller; uncomposed calls keepunresolved_http. - SQL dicts via module alias (
from . import queries; queries.Q['k'],import pkg.queries as q) and import-timetextwrap.dedent/.strip()transforms resolve.rpc("list")wrappers that dorun_query(Q[name])bind the literal name at the call site. Dicts derived in another module (Q = {k: _transform(v) for k, v in queries.RAW.items()}) evaluate identity,dedent/strip,.replace('old.', 'new.'), and.format(schema=CONST)with constant args. Unknown transforms keep the raw SQL tables with confidenceinferredand a note. x.request('POST', path)/x.post(path)on a transport whose class is not scanned emitunresolved_httpon the caller (never silent).supabase.rpc("name")becomes acallsedge tofunction:sql.namewhen that SQL function exists.
Go resolution (v0.1.3)¶
- Function display names are the directory relative to the scan root,
always (
internal/services/appointments.Service.Run). Packages are still keyed by import path for resolution. With nogo.mod, a unique scanned-directory suffix of the import path is used and a warning is printed. - Calls and Echo handlers resolve through each file's import aliases.
Outbound helpers that take
path/methodfrom the caller (getJSON(ctx, path, out)withc.baseURL + path) emitcalls_httpfrom the call site. - Method values (
h.Create) use a(import-path, Type, Method)key after inferringhfrom constructors, composite literals, parameters, and struct fields. There is nomatches[0]fallback on name collisions. - Import-alias or unknown-receiver calls (
middleware.Current(c),s.Now()) stay unresolved when the package is unscanned or the type is unknown. Inferred call edges require a unique callee inside that package/type set and do not propagate table edges otherwise. - Injected func fields (
s.ring(...)withService{ring: notify.Send}or a constructor argument) resolve to the single assigned function. - Object / interface dispatch: a call on a field, parameter, or
constructor-injected value (
s.Bell.Changed(e),d.outbox.Settle(ctx)) follows the concrete type assigned in a constructor or composite literal, or every scanned type that has the interface's method set. One implementer →inferredcall edge; several → edges to all,inferred, withcandidates. - Dynamic SQL:
for _, q := range []string{"UPDATE a ...", ...}expands to one SQL site per element. Helpers with aquery/q/sqlstring param bind literals/consts at the call site and attribute tables to the caller.Exec/Query/QueryRowpick the argument that is a SQL literal or const (pgxExec(ctx, sql)anddatabase/sqlExec(sql, args…)/*Context/ sqlxGet/Select/NamedExec) without duplicating sites. - A handler argument that is a call unwraps to an inner func/method
(
wrap(h.Version),mw(handler)). Factories that take data (profile.StaffPhoto(cfg)) still resolve to the factory. - Echo methods match exactly (
GET, notoptions). The path argument must be string-like (literal, const, or concatenation). A const that aliases another scanned package (const PathPrefix = shared.PathPrefix,var Base = shared.Base + "/v1") resolves when both packages are in the scan.bizmap.yamlconstants: { PathPrefix: /api/v1, pkg.Name: /x }fills consts that alias an unscanned package. func mainis not a writer entrypoint unless it is a detected job or route.bizmap.yamlis found via--config, the scan root, or the git toplevel.--exclude GLOB(repeatable) merges with YAMLexclude.--profileprints parse / resolve / sql / propagate timings to stderr.
JavaScript / TypeScript resolution (v0.2.9)¶
.js/.mjs/.cjsuse tree-sitter-javascript;.ts/.tsxuse tree-sitter-typescript (language_typescript/language_tsx).- Express / Fastify / Hono: routes require a known app/router receiver
(
express(),Router(),fastify(),new Hono(), chainednew Hono().use().get(), chained-exportexport const r = new Hono().use(mw).get('/a', h), or typed as such) and a string-literal or resolvable const path..basePath('/v1')and.route('/x', sub)/app.use('/v1/items', importedRouter)apply prefixes across files (default/named exports, nested mounts, chained-export children). Known HTTP clients (fetch,axios+ instances,ky,ofetch,got,superagent) emit outboundcalls_http;Map/Set/Headers/URLSearchParams/searchParams/config.headersdo not.axios.create/ky.create/ofetch.create{baseURL}(exported, factory-built, or passed as a parameter into an object-literal factorymakeOrders = (client) => ({ list: () => client.get('/orders') }), or a class constructornew OrdersApi(api)/this.client.get) compose with later.get('/x'), including`${import.meta.env.VITE_API_URL}/api/v1`bases and/orders/${id}→/orders/:id. Instances returned by a factory (createClient()/makeHttp()that assignsaxios.createthen attaches interceptors) compose the same way forapi.get('/orders'), genericsapi.get<Order[]>('/orders'), and(await api.get(...)).data. Local wrappersget(url)/request(method, url, body)emit the call-site path. Uncomposed parameter clients stayunresolved_http. Chained.get/.postof any length and statement-style sub-apps mounted via.route('/', s)inside a chained export keep the composed prefix.serve({ fetch: app.fetch })is notPOST /. Relativefetch('/x')matches only the same repo; constructor/config{base}URLs may match across repos when the path has 2+ literal segments or aservices:mapping.tsconfig.json/jsconfig.jsoncompilerOptions.paths(baseUrl,extends) resolve aliases such as@/*→src/*; without a config@/still maps tosrc/. Factory parameters inbaseURLtemplates are bound from the call-site argument (createApi(API_URL)). Parameters typedAxiosInstance,Pick<AxiosInstance, …>,Partial<AxiosInstance>,typeof someInstance, orKyInstanceare HTTP clients. Inline-arrow handlers attributesupabase.from('t')access to the route. - Supabase JS:
supabase.from('t').select|insert|update|delete|upsertemits table reads/writes;.rpc('fn')callsfunction:sql.fnwhen that SQL function exists. pg/postgresclient.query('SELECT …')is analyzed as SQL.- Supabase Edge Functions:
Deno.serve/serve(handler)(includingserve(withAuth(async (req) => …))) insupabase/functions/<name>/index.tsbecome HTTPentrypoint:http:POST:/functions/v1/<name>, with call edges from the handler body into imported helpers.
Firebase Functions, callables and built doc paths (0.14)¶
- Entrypoints:
onCall→firebase_call,onRequest→firebase_http,onSchedule/ v1pubsub.schedule().onRun→scheduled_job,onMessagePublished/ v1topic().onPublish→pubsub,onTaskDispatched,beforeUser*/ v1auth.user()→auth, and Firestore triggers (bare or namespaced,document:as a literal or`${COLLECTION}/{id}`). The handler passed to the factory is the function<module>.<export>. - Deployed names: exports are followed from the functions entry file
(
package.jsonmain, mapped back tosrc/) throughexports.orders = require('./orders'),exports.n = mod.n,export { a as b } fromandexport *, sosrc/orders/pay.ts'smarkPaidisorders-markPaid. - Callables:
httpsCallable(fns, 'orders-markPaid')(generic, across lines) andhttpsCallableFromURLbecomecalls_httpwithvia: firebase_callableto that function in any scanned repo; an unknown name isunresolved_httpwith reasoncallable_not_scanned. - Built doc paths:
db.doc(`orders/${id}`),db.doc(`${ORDERS}/${id}`)(same-file string constant),db.doc('notes/' + id)anddb.collection('payments').doc()resolve to the first segment (odd segments for subcollections) — inbatch/tx.set/.update/.delete/.createand in a directdb.doc(path).set(). Anything else iscollection:unknown. - Trigger events: a write fires a Firestore trigger only for its event
(
add/create/set→ created,update/set→ updated,delete→ deleted).
Go helper routes (0.14)¶
A function that takes an interface and mounts a route from it,
is expanded per call site — mount(e, jobs.NewTotals()), mount(e, &jobs.Cleanup{}),
or a variable assigned from one — into one route each
(POST /internal/jobs/order-totals), using the literal returned by the
concrete type's Name() / Path(). Each route triggers that type's other
interface methods (Run, Handle) and gets their tables. Once a helper is
expanded, the template route (/internal/jobs/{job.Name()}) is removed.
Bundled rules (v0.2.9)¶
| File | Status | What it detects |
|---|---|---|
echo.yaml |
active | Echo v4 group.POST("/path", handler) (literals, consts, factories, wrappers; Any/Match) |
pgx.yaml |
active | pgx / database/sql / sqlx SQL (Exec/Query/QueryRow/*Context/Get/Select/NamedExec; SQL arg picked by content) |
go_ticker.yaml |
active | Any go statement whose target uses ticker/cron patterns |
fastapi.yaml |
active | FastAPI @app.get / APIRouter / include_router |
flask.yaml |
active | Flask @app.route / Blueprint(url_prefix=) |
sqlalchemy.yaml |
active | text() / execute() SQL; ORM/Core usage is in the Python engine |
firebase.yaml |
active | Firebase Functions entrypoints + Firestore collection() |
celery.yaml |
active | Celery / RQ / Cloud Tasks / Pub/Sub produce + consume |
httpx.yaml |
active | httpx / requests client calls (calls_http) |
supabase.yaml |
active | supabase.rpc("fn") |
express.yaml |
active | Express / Fastify / Hono routes, fetch(), Supabase .from / .rpc, pg/postgres query() (JS/TS via tree-sitter-typescript). Edge Functions in supabase/functions/<name>/index.ts become HTTP /functions/v1/<name>. |
The engine still walks a simple intra-project call graph in code (not YAML) so
handler → service → repository reads/writes propagate to HTTP/job entrypoints
as table-level inferred edges. HTTP clients and queue producers add
calls_http / enqueues the same way.