npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@haneinfo/instance-analytics

v0.4.8

Published

Permission-filtered live aggregates and state durations over state-machine instances, with private or shared saved reports.

Downloads

1,943

Readme

@haneinfo/instance-analytics

Live, permission-filtered aggregates over the instances of one state machine, built-in state durations, and private or shared saved reports. Implementation of approved decision 202610-c7b4.

The module provides haneinfo.instance-analytics / INSTANCE_ANALYTICS / ReportsPort and exports ReportsService, ReportsMcpTools and InstanceAnalyticsModule. It reads state_machine_instances and state_machine_transitions directly and owns one table, reports. There is no cache, no pre-aggregated table and no frontend; exports, charts and dashboards are separate decisions.

Installation

Upgrade plugin-api (contract 1.28.0), state-machine 0.19 and list-view 0.9 together. Apply prisma/reports.sql in an ordinary App migration and include prisma/reports.prisma in the App schema (the Report model has no relation to instances). Enable the plugin with configRef instanceAnalytics, then register ReportsMcpTools in the App's existing MCP registry:

this.reports.commands({ scopeNamespace: 'my-app' });

The manifest requires haneinfo.prisma, haneinfo.principal-context, haneinfo.definition-registry and haneinfo.state-machine-runtime; RBAC and identity-store are optional (without RBAC nobody has state-machine:instance:read; without identity-store submitter labels are null).

Declaring fields

Form fields are never aggregated by default. A machine declares them in spec.reporting (validated by state-machine):

"reporting": {
  "dimensions": [{ "fieldId": "equipmentType" }, { "fieldId": "startDate" }],
  "measures": [{ "fieldId": "days" }, { "fieldId": "totalQuantity", "ops": ["sum", "avg"] }]
}

Field ids follow the list rules (stable id, key fallback). Dimensions accept top-level text, select, number, date, datetime and switch fields that are not formulas; measures accept top-level number fields, stored formula results included; ops limits the allowed operations (all five when omitted). Queries address declared fields as data.<fieldId>. Declarations are re-resolved against the latest published machine and subject Form on every call; an invalid or removed declaration behaves as undeclared.

Built-ins need no declaration:

| Kind | Id | Notes | | --- | --- | --- | | dimension | $state | Current state; label from the machine definition. | | dimension | $submitterId | Label is the submitter's active display name (or null). | | dimension | $createdAt | bucket: day (default), week, month, quarter, year. | | dimension | $archived | Boolean. | | measure | count without fieldId | Number of instances. | | measure | $leadTime | Seconds from creation to entering the final state; finished instances only. |

Never declare identity numbers, salaries or other sensitive fields for convenience.

Aggregate query

POST /reports/machines/:code/query (interactive login), body:

{
  "measures": [{ "op": "count", "as": "n" }, { "op": "avg", "fieldId": "data.days", "as": "avgDays" }],
  "groupBy": [{ "fieldId": "$createdAt", "bucket": "month" }, { "fieldId": "data.equipmentType" }],
  "filter": { "kind": "PREDICATE", "operator": "GT", "left": { "kind": "FIELD", "fieldId": "data.days" }, "right": { "kind": "LITERAL", "value": 1 } },
  "archived": "exclude",
  "orderBy": [{ "key": "n", "direction": "desc" }],
  "limit": 100
}
  • measures: 1–8; op is count, sum, avg, min or max. count without fieldId counts instances; with a field it counts usable values. sum/avg/min/max need a declared measure (with that op) or $leadTime. as is 1–64 letters, digits or underscores, unique.
  • groupBy: up to 3 distinct dimensions; bucket only on $createdAt.
  • filter: list-view condition syntax, validated and compiled by list-view itself, over the list fields (system fields and filterable spec.listView.fields).
  • archived: exclude (default), include or only. Soft-deleted instances are never counted.
  • orderBy: groupBy keys or measure names; remaining group keys follow ascending. Nulls last.
  • limit: 1–200 groups (default 100). Without groupBy the result is one total row.

The machine comes from the path; a body machineCode, if present, must match it.

Response: { kind: "aggregate", machineCode, columns, rows, truncated, timeZone, generatedAt }. Each row is { group, labels, values }: group maps groupBy ids to values (buckets are local YYYY-MM-DD start dates; select values keep their stored type), labels holds state labels, submitter names and select option labels, values maps measure names to numbers or null. truncated is true when more groups exist than limit.

Values are read with list-view's strict JSONB typing: only a value of the declared JSON type counts (numbers for number fields and measures, strings for text/date/datetime, booleans for switch, strings or numbers for select). Nulls, mistyped and legacy values become a null group or are skipped by measures; they never fail the query. Formula fields use their stored values.

Time buckets read UTC timestamps, convert to the configured zone (default Asia/Taipei) and truncate there; weeks start on Monday. reportBucketStart and REPORT_BUCKET_TEST_VECTORS in plugin-api are the reference the SQL is tested against.

State durations

POST /reports/machines/:code/state-durations with optional filter and archived returns { kind: "stateDurations", machineCode, states, generatedAt }; each state is { state, label, stays, open, avgSeconds, p50Seconds, p90Seconds } in definition order (states no longer in the definition follow with a null label). A stay starts when history records entering a state (START, USER, ASSIGNMENT, TIMER or CHOICE) and ends at the next state change; comments, tags, access, attachments, documents, lifecycle and CHOICE-decision rows are not stays. Instances still in a state count up to generatedAt (open); the final state of a finished instance is not a stay. Each entry, including a self-transition, is one stay. Early instances without complete history are skipped for the stays whose entry is missing, so their time may be under-reported. Percentiles are PostgreSQL percentile_cont.

Permissions and safety

Every query applies list-view's readableInstancePredicates in SQL before aggregating: submitter, effective state-machine:instance:read, or a reader / access-list entry (USER or ROLE, ASSIGNED, DELEGATED), roles expanded once per call. Authorization is read on every call, so grants and revocations apply immediately. A person without access sees zero rows or a zero count, never an error, and nothing in totals, groups or messages depends on unreadable instances. There is no separate "statistics only" permission and no small-group suppression (results only ever cover instances the caller can already read).

All user values (machine code, data keys, filter literals, time zone, limit, roles) are bound parameters. Field ids select from a whitelist of built-ins and valid declarations; SQL text only contains fixed fragments. Each query runs read-only in its own RepeatableRead transaction with a transaction-local statement_timeout (5,000 ms by default); on timeout the API returns REPORT_TIMEOUT / 503 with a fixed message.

External BI (haneinfo-cube, metadata-schema Cube annotations and a read-only database connection) does not go through this mechanism and is not protected by these readership rules; spec.reporting and Cube annotations are independent of each other.

Saved reports

| Route | Who | | --- | --- | | GET /reports | Visible reports: own, ALL, or ROLES matching the caller's roles. | | POST /reports | Create { name, machineCode, query, display? }; always PRIVATE. | | GET /reports/:id | Visible report. | | PATCH /reports/:id | Creator only: { name?, query?, display? } (machine is fixed). | | DELETE /reports/:id | Creator only; 204. | | PATCH /reports/:id/sharing | System ADMIN only: { visibility: PRIVATE \| ALL \| ROLES, roles? }. | | POST /reports/:id/run | Visible report; returns { report, result }. |

The stored definition is { query, display }: the query without machineCode (with kind: "aggregate" or "stateDurations") and display { type: table | bar | line | pie | number, x?, y? }, where x names a group column (state for state durations) and y measure columns. Creating or changing a report validates it against the current declarations without reading instances. Visibility is not readership: every run re-validates the declarations and counts only what the caller can read. Hidden or missing ids are REPORT_NOT_FOUND / 404; a visible report changed or deleted by someone other than its creator is FORBIDDEN / 403. Each person keeps at most 100 reports (REPORT_LIMIT_EXCEEDED / 409). Responses add canShare (system ADMIN).

Errors

| Code | Status | When | | --- | --- | --- | | REPORT_QUERY_INVALID | 400 | Query, filter, name or display invalid; the message and suggestion name the path. | | UNDECLARED_REPORT_FIELD | 400 | A field is not declared for that use (or not filterable). | | REPORT_TIMEOUT | 503 | The statement timeout was reached. | | REPORT_NOT_FOUND | 404 | The report does not exist or is not visible. | | INVALID_REPORT_SHARING | 400 | Bad visibility or role names. | | REPORT_LIMIT_EXCEEDED | 409 | The per-person report limit is reached. | | MACHINE_NOT_FOUND | 404 | No published machine with that code. | | FORBIDDEN | 403 | Sharing without ADMIN, changing someone else's report, or no user. |

MCP

| Tool | Scope | Notes | | --- | --- | --- | | run_report_query | <namespace>:reports:read | Same input as the HTTP query plus machineCode. | | run_state_durations | <namespace>:reports:read | { machineCode, filter?, archived? }. | | list_my_reports | <namespace>:reports:read | Own reports only, even if others shared theirs. | | get_my_report | <namespace>:reports:read | Own report only. | | create_my_report | <namespace>:reports:write | Always PRIVATE. |

Every tool requires a user-bound credential (actingUserId). Group values, labels, state labels, report names and definitions are wrapped as $userContent. Agents cannot share, change or delete reports; a definition an agent creates is private JSON a person can inspect and run.

Configuration

runtime.instanceAnalytics (no secrets):

| Key | Default | Range | | --- | --- | --- | | timeZone | Asia/Taipei | IANA zone | | maxGroupRows | 200 | 1–10,000 | | maxMeasures | 8 | 1–32 | | maxGroupBy | 3 | 1–8 | | queryTimeoutMs | 5000 | 10–60,000 | | maxNameLength | 200 | 1–1,000 code points | | maxReportsPerUser | 100 | 1–10,000 |

Performance

Aggregation runs live on JSONB. machine_code, state and readership use the existing instance indexes; $createdAt buckets scan the machine's instances. If a declared dimension becomes a bottleneck, add an expression index in the App. Large machines may reach the timeout; narrow the filter or the grouping.

Localized labels (approved decision 202610-a8d3)

Implemented under the approved decision. GET …/fields, POST …/query, POST …/state-durations and POST /reports/:id/run read ?locale= (zh-TW or en, else INVALID_LOCALE/400) or Accept-Language, zh-TW by default. Built-in labels (REPORT_SYSTEM_LABELS), declared field and option labels and state labels are resolved in it; the service methods take an optional { locale }. MCP tools use zh-TW. Requires plugin API 1.26.0.