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

@blotout/qinto-sdk-app

v0.1.37

Published

Qinto app SDK: the authoring surfaces for Qinto platform apps — defineApp (server) and defineBrowserApp (browser) plus their hook, context, and action types. Zero runtime dependencies.

Readme

@blotout/qinto-sdk-app

The authoring surface for Qinto platform apps: defineApp for the server, defineBrowserApp for the page, createAppUi for the settings panel, and the types each one hands your handlers. Zero runtime dependencies.

Why we built it

A Qinto app is code that runs on the platform, inside the site's own edge. A site sends each visitor action once, and every app installed on it receives that action server-side: a transform app rewrites, enriches, or drops the event before destinations see it, and a destination app forwards it onward. The site's own tracking code never changes when a site adds your app.

That is a very different place to write code than either end you are used to:

  • It is not a server you host. There is no origin to run, scale, or pay for. You declare what your app needs in qinto.app.jsonc — a KV namespace, a D1 database, a workflow, an HTTP endpoint, a cron schedule — and the platform builds the Worker, provisions the bindings, and dispatches into your handlers.
  • It is not a script in the customer's page. The event reaches you one hop from where it was recorded, with the visitor already resolved to an identity, the site's consent already applied, and the site's settings already filled in. You never ask a customer to paste anything.
  • Everything your app can do is declared. Capabilities, captured names, published topics, and settings a panel may write are what a site manager reads and accepts before installing — and again whenever a later version widens them.

This package is the contract between your handlers and that runtime. It exists as a package, rather than as a shape you guess at, for three reasons:

  • The types are the documentation. What a transform hook may return, what rides on ctx in a scheduled run versus a visitor action, which context is a value and which is a call — all of it is on hover.
  • It ships app.schema.json. Point your manifest's $schema at it and your editor completes and validates qinto.app.jsonc offline, against the exact SDK version you installed.
  • The definitions are checked before you publish. defineApp records which hooks you actually declared, and the CLI compares that against the manifest at publish and at dev — so a hook the manifest promises and the bundle does not export fails on your machine, not at dispatch on a customer's site.

Install

npm i @blotout/qinto-sdk-app
npm i -g @blotout/qinto-cli

Usually you do not: qinto app create my-app scaffolds a manifest, a server entry, and this dependency for you, and offers to register the app under your organization.

What you import

| Entry | Exports | Runs | | --- | --- | --- | | @blotout/qinto-sdk-app/server | defineApp, defineRpc, RpcError, defineVisitorEndpoint, defineWorkflow, runAi, runAiBytes, atLeast | In your app's Worker, on the platform. | | @blotout/qinto-sdk-app/browser | defineBrowserApp | In the visitor's page, inside the site's tag. | | @blotout/qinto-sdk-app/ui | createAppUi, atLeast | In your settings panel, framed by the Qinto platform. |

The package also ships app.schema.json for your manifest's $schema.

The server app

import { defineApp } from '@blotout/qinto-sdk-app/server'

type Env = { PURCHASES: D1Database }

export default defineApp<Env>({
  transform: {
    track: async (action, ctx) => {
      if (action.payload.event === 'Blocked Event') {
        return ctx.drop()
      }

      return ctx.replace({ ...action.payload, properties: { ...action.payload.properties, siteTag: ctx.variables.SITE_TAG } })
    }
  },
  onEvent: {
    track: async (action, ctx) => {
      const response = await fetch(String(ctx.variables.ENDPOINT_URL), {
        method: 'POST',
        headers: { 'content-type': 'application/json', authorization: `Bearer ${ctx.secrets.API_KEY}` },
        body: JSON.stringify({ event: action.payload.event, properties: action.payload.properties, userId: action.userId })
      })
      if (!response.ok) {
        ctx.observability.error('delivery refused', undefined, { status: response.status })

        return
      }

      ctx.observability.log('track delivered', { event: action.payload.event })
    }
  },
  onDeleteRequest: async (event, ctx) => {
    await ctx.env.PURCHASES.prepare('DELETE FROM purchases WHERE anon_id IN (SELECT value FROM json_each(?))')
      .bind(JSON.stringify(event.anonIds))
      .run()
  }
})

defineApp takes one object. Every key below is optional except onDeleteRequest, and an unknown key is refused rather than ignored.

Every visitor action includes receivedAt and source — where it came from: website (the browser SDK), api (the site's own server), app (an app's emit or install-token call), or scheduled, webhook, tool, workflow or queue (an app handler's ctx.track). source is undefined only on a site whose worker predates the field. action.observed additionally carries occurredAt, source/page/network data, and a browser session as { id, isNew, startedAt } when available. A session ends after 30 minutes with no page load or reconnect. All tabs of a visitor on one site share it. isNew is true only on its first action, and startedAt is fixed when Qinto starts the session, so destinations can make stable session-cutoff decisions.

| Key | What it is for | | --- | --- | | transform | track and identify hooks that run before destinations, and return ctx.pass(), ctx.drop(), or ctx.replace(payload). A track transform can pass { installs: { mode, installIds } }, { apps: { mode, slugs } } or both as the last argument of pass or replace to keep the event from some installs or apps, with the same rules ctx.track takes. Every transform's rule and the one on the action apply together: an install receives the event only if every rule allows it. Every install still runs its own transform. On track or identify, replace can also take { page: { url, referrer } } to replace action.observed.page (needs the eventContext capability; a left-out referrer is removed) and { unchangedApps: [slug] } to keep sending those apps the action as it stood before this transform. Transforms later in the chain and other apps get the replacement, and later edits never reach the original. | | onEvent | track, identify, and consent hooks that run after the transform chain — where a destination does its work. | | onConnect | Runs once when a visitor's page connects, before any action. A reconnect from the same page does not run it again. ctx.page names that page and ctx.session the visit session it joined, the one its actions carry, when the manifest declares the eventContext data bucket. | | onLifecycle | Advisory notices that the install changed: installed, configurationChanged, enabled, disabled, versionChanged, uninstalled. They observe; they never approve. | | onDeleteRequest | Required. The manifest declares nothing for it, and the build refuses a bundle without it. Erases a person after a site manager handles a delete request: one delivery per install, disabled installs included, with the person id, every linked anon id, and the raw identifiers when the manifest declares the pii data bucket. A throw is retried with backoff, so the handler must be safe to run twice. | | schedules | Cron handlers, keyed by the ids the manifest declares. | | endpoints | HTTP handlers served at https://<site>/app/<slug><path>. Webhooks have a 60-second total deadline; API handlers must return headers within 60 seconds and may then stream for up to five minutes, with a 150-second idle deadline. An auth: "visitor" endpoint is built with defineVisitorEndpoint and called from your browser code with app.fetch. | | rpc | Functions other apps on the same site may call, each built with defineRpc and keyed by the name the manifest's rpc.exposes declares. | | ui | The server side of your settings panel, reached at <siteOrigin>/apps/<slug>/ui<path>. | | workflows | Durable runs built with defineWorkflow, keyed by the class name the manifest declares. | | queues | Queue consumers, keyed by the identifier of each queue resource the manifest declares. A handler gets the messages of one install, with that install's ctx. See Queues. | | migrations | Resumable backfill handlers named by a D1 migration. |

What each handler is handed

You name none of these for a handler written inline — defineApp infers every one. They are the names to reach for when a handler is lifted into its own function or file:

| Hook | Handler receives | Must return | | --- | --- | --- | | transform.track | AppTrackAction, AppTransformContext<Env, AppTrackPayload> | TransformResult | | transform.identify | AppIdentifyAction, AppTransformContext<Env, AppIdentifyPayload> | TransformResult | | onEvent.track | AppTrackAction, AppContext<Env> | nothing | | onEvent.identify | AppIdentifyAction, AppContext<Env> | nothing | | onEvent.consent | AppConsentAction, AppContext<Env> | nothing | | onConnect | AppConnectContext<Env> | nothing | | onLifecycle.<type> | that type's event — AppInstalledEvent, AppConfigurationChangedEvent, AppEnabledEvent, AppDisabledEvent, AppVersionChangedEvent, AppUninstalledEvent — and AppLifecycleContext<Env> | nothing | | onDeleteRequest | AppDeleteRequestEvent, AppLifecycleContext<Env> | nothing | | schedules.<id> | AppScheduleEvent, AppScheduleContext<Env> | nothing | | endpoints.<path> | Request, AppEndpointContext<Env> | Response, or ctx.skip() as EndpointSkip | | endpoints.<path> built with defineVisitorEndpoint | Request, AppVisitorEndpointContext<Env>, whose user is the calling visitor's { anonId } | Response | | tools.<name> | the validated arguments as Record<string, unknown>, AppToolContext<Env> | AppToolResult, or ctx.fail() as AppToolFailure | | rpc.<fn> | the caller's arguments, parsed by the input schema defineRpc was given, and AppRpcContext<Env> | a value the output schema accepts | | ui | Request, AppUiContext<Env> | Response | | migrations.<id> | { id, checkpoint }, AppMigrationContext<Env> | AppMigrationResult | | workflows.<Class> | AppWorkflowEvent<Params>, AppWorkflowStep, AppWorkflowContext<Env> | anything | | queues.<identifier> | readonly AppQueueMessage[], AppQueueContext<Env> (the context of one install, with no visitor and no query) | nothing |

A transform context is the one that takes a second argument: replace accepts the payload of the action being transformed, so a track handler and an identify handler carry different contexts and neither can be written against both. Only the track context's pass and replace take AppTransformOptions. A workflow event takes the payload you declare, which defineWorkflow<Env, Params> supplies.

What rides on ctx

| | | | --- | --- | | ctx.env | The bindings your manifest's resources declared — typed by the Env you pass to defineApp<Env>. A pipeline binding's send is retried for you on a transient Cloudflare failure; the manifest reference says what that means for a sink. A browser_run binding is the real Browser Run binding on cold traffic only (a panel, a tool, a schedule, a workflow, an rpc call that cold traffic started); everywhere else, reading it throws browser_run_hot_path, so start a workflow there. | | ctx.variables, ctx.secrets | This install's settings, filled in by the site manager. | | ctx.appVariables, ctx.appSecrets | Your own settings, one value for every site that installs the app. | | ctx.install, ctx.site | Which install this invocation is for, and which site it is on: site.origin is the customer's site (https://<root domain>), site.domain the first-party hostname the site's worker answers on, site.devUrl the origin of its workers.dev development URL or null. | | ctx.geo | The current request's location (country, city, region, regionCode, timezone, postalCode, continent, latitude, longitude, isEUCountry) and Cloudflare Bot Management (botManagement.score, verifiedBot, ja4, ja3Hash), when the app declares the geo data capability. On an endpoint this describes the endpoint caller, not a stored visitor. | | ctx.user | The visitor: anonId, globalId, createdAt (first seen, epoch ms; hooks only), stored properties (snake_case keys such as first_name and postal_code, every value a string), and, when granted, the stored geo: the same location fields plus ip, userAgent, ja4, ja3 and botScore, flat and every value a string. | | ctx.consent | { enabled, categories, apps }, when consentState is granted. categories always holds all five: necessary, functional, analytics, marketing and salesOfData. A consent action's payload holds only the categories and apps that save changed. Your manifest's category is already enforced before you are called. | | ctx.emit | Emit a track of your own back into the pipeline. Your app never receives its own emission. Pass { installs: { mode, installIds } } or { apps: { mode, slugs } } as a second argument to pick the installs or apps that receive it, with the same rules as ctx.track. | | ctx.push | Send a message down the visitor's live connection, to your browser code. | | ctx.captures | Read the click ids and cookies your manifest captures for this visitor, typed attribution or identity, and write derived ones. With the facts data capability, byApp also holds every app's live capture rows, keyed by slug. | | ctx.facts | Read stable, paginated retained visitor facts with list(filters) and opaque continuation cursors; requires the facts data capability. Check fact.kind first: each kind fills its own columns (for a conversion, key is the order id and value the event name). A transform sees the last committed page, not the event it is rewriting. | | ctx.currency | Exchange rates, the same on every site: convert(amount, from, to), rate(from, to), list() and updatedAt(), all async. Codes are trimmed and uppercased, an unknown code gives null, and convert does not round. The first call in an invocation reads the rates from the site, and the calls after it are local. When the platform has no rates, every call rejects, and the next call asks the site again. On transforms, onEvent, onConnect, rpc, schedules, lifecycle and delete request hooks, migrations, tools, endpoints, workflows and the ui handler. Not in your Durable Objects. Needs no capability. | | ctx.billing | usage(key, value) adds value to this install's usage of a meter that your manifest's billing.meters declares, and the Qinto platform records it for the site. The key is typed from the declared meters, so with none declared no key typechecks. The call is synchronous and drops a value that is not finite, is 0 or less or is above 1e12, and a key that is not a meter key, with a warning. Decimals are accepted, and calls in one invocation add up. On transforms, onEvent, onConnect, rpc, schedules, lifecycle and delete request hooks, tools, endpoints and the ui handler, where it never throws. In a workflow, call it inside a step.do callback: the usage of the step counts once, after the step is successful, and not again when the step replays from the cache. A call outside a step throws. Not in migrations or your Durable Objects. | | ctx.context | Per-visitor state your app keeps: a private level only you read, and a shared level every app on the site can. | | ctx.apps | Call another installed app's exposed rpc functions through the site's broker. A failed call rejects with <code>: <reason>; see Functions for other apps for the codes and deadlines. Not on transforms — an RPC from inside the ingest turn would wait on work queued behind itself. | | ctx.track | On a scheduled run, an endpoint, a tool and a workflow step: record a track for a visitor you name by anon_… id. It arrives at every app on the site, yours included, with action.source naming the handler kind. Pass { installs: { mode, installIds } } as a third argument to pick the installs that receive it: except keeps it from the listed installs, only sends it to them alone. An id that names no install is ignored, and { mode: 'only', installIds: [] } reaches no install while the event is still stored. { apps: { mode, slugs } } does the same by app slug, for every install of each listed app; with both, an install receives the track only if both allow it. | | ctx.startWorkflow | Start one of your declared workflows, carrying this install — and the visitor — into the run. | | ctx.resources | await ctx.resources.state(identifier) says whether a resource your manifest declares is waiting or active, on every server context. A panel handler also has activate and update. See Resources that wait for your app. | | ctx.queues | send(identifier, body, { delaySeconds }) and sendBatch(identifier, [{ body, delaySeconds }]) put messages on a queue your manifest declares, carrying this install. The identifier is typed from the declared queues, so with none declared no identifier typechecks. On hooks, endpoints, each install of a schedule, workflow steps and queue consumers. See Queues. | | ctx.observability | log, error, and span. Everything you record shows up in the site's real-time console, next to the platform's own spans; a plain fetch is traced for you. In a workflow, this holds only inside a step.do callback. |

A scheduled run, MCP tool, endpoint, and workflow step carry a narrower context — they have no visitor, so there is no user, consent, or emit there. track(userId, event) names its subject instead, and on a scheduled run and an endpoint so do push and context. An endpoint still carries the current caller's location and bot fields in ctx.geo when the app declares the geo data capability. Scheduled runs and MCP tools can query a catalog-enabled R2 resource with ctx.query.catalog(resourceIdentifier, sql) and an Analytics Engine dataset with ctx.query.analytics(resourceIdentifier, sql) — name the dataset by its resource identifier in FROM; Qinto keeps the physical bucket, the dataset name, and the credential out of the app worker. An rpc handler has ctx.query too, on cold traffic only (see below). The types say which capability is available where.

ctx.context(userId) takes an anon_… id. Context is stored per device, so to act for a person you know only by an identifier, resolve it (this needs the identity data capability) and write to each visitor. A visitor that links to the person later does not receive an earlier write.

let cursor: string | undefined
do {
  const person = await ctx.identity.resolve('[email protected]', { cursor })
  for (const anonId of person.anonIds) {
    await ctx.context(anonId).shared.set({ kv: { tier: 'gold' } })
    await ctx.track(anonId, { type: 'track', payload: { event: 'Tier Upgraded', properties: { tier: 'gold' } } })
  }

  cursor = person.nextCursor ?? undefined
} while (cursor !== undefined)

To attribute a server-side event to someone the graph may not know yet, such as the buyer of an order, call ctx.identity.upsert with their identifiers and PII. It resolves through the email, then the phone, then the custom id, creates a new anon id when that identifier has none (created: true), and links the other identifiers unless another person already owns them. Transforms run on it as on any identify, but no app receives an identify for it. A new anon has no consent yet, so on a site that enforces consent only necessary apps receive its events.

const { anonId } = await ctx.identity.upsert({ email: order.email, phone: order.phone, firstName: order.firstName, observedAt: order.createdAt })
await ctx.track(anonId, { type: 'track', occurredAt: order.createdAt, payload: { event: 'Purchase', properties: { eventId: order.id, value: order.total } } })

Resources that wait for your app

Cloudflare fixes a sink's batch values, a stream's schema and a sink's select when it creates them. A pipeline deploys at install by default, so to collect those values first, mark it "activation": "manual" in the manifest. The bucket and your app worker still deploy at install. Only the pipeline waits, until your panel sends the signal, or a site admin presses "Create pipeline" on the app page. That button uses the manifest values, so a pipeline with no manifest schema has no button.

// In your `ui` handler. `schema` and `select` are only for a pipeline whose manifest leaves them out.
await ctx.resources.activate('stream', {
  schema: [
    { name: 'id', type: 'string', required: true },
    { name: 'plan', type: 'string', required: false }
  ],
  sinks: {
    events: { select: "SELECT id, plan FROM {{stream}} WHERE plan = 'pro'", fileSizeMb: 20, intervalSeconds: 60 }
  }
})

await ctx.resources.update('lake', { minSnapshotsToKeep: 20, maxSnapshotAge: '30d' })
await ctx.resources.update('lake', { maxSnapshotAge: null })

await ctx.resources.state('stream')
// { status: 'waiting', error: "column 'plan' not found" }
// { status: 'active', settings: { sinks: { events: { fileSizeMb: 20, intervalSeconds: 60 } } } }

| Group | Settings | Set with | Can change | | --- | --- | --- | --- | | At creation | A pipeline's schema and sinks.*.select | The manifest, or activate when the manifest has none | Until Cloudflare holds the SQL pipeline | | At creation | A sink's fileSizeMb and intervalSeconds | activate, or the manifest batch | Until Cloudflare holds that sink | | Any time | A catalog bucket's compactionTargetSizeMb, minSnapshotsToKeep and maxSnapshotAge | update, the app page form, or the manifest maintenance | Always. update and the form write the same values, so the last save wins |

  • activate and update exist only in a panel handler. They need ui.writesSettings and throw for a read-only viewer. They resolve when the values are saved and the deploy is queued, and state shows waiting until that deploy lands. A check of SQL your app wrote adds about 6 seconds to activate.
  • The same values again change nothing. A different value Cloudflare already holds throws resource_settings_fixed. A batch value left out falls back to the manifest and then to the platform default.
  • env.<BINDING>.send() throws an error that names the pipeline while it waits, and nothing is buffered. Call state first.
  • state is async everywhere. Outside a panel handler it reads what the last deploy wrote, so it makes no network call and an event handler can call it per event. It has no error there, because a failed deploy does not update the worker.
  • In a panel handler, state reads from the platform and a waiting resource can carry error, the reason its last deploy failed. The site issues that credential only for a viewer with write access and a request other than GET, so call it from a POST to see error. Any other panel request reads what the last deploy wrote, with no error.
  • The pipeline belongs to the app on the site, not to one install, so on an app with several installs the first signal decides the values.
  • state leaves out the schema, because the binding that carries it has a 5 KB limit. Keep the schema you built in your own storage.
  • With a schema you built, a deployed stream silently drops an event that does not match it, so your code must send matching rows.
  • Under qinto app dev a marked pipeline starts waiting and activate makes it active at once, so send() checks each record against the given schema. activate refuses a select that cannot run on an empty SQLite table of that schema, such as one that names a missing column. SQLite is not Cloudflare's dialect, so a select can pass locally and be refused on deploy. A local signal creates the pipeline, so a different value is refused from then on. Delete the local dev root, under ~/.qinto/dev/, to start again. A local deploy cannot fail, so state never has error locally.

Functions for other apps

import { defineApp, defineRpc } from '@blotout/qinto-sdk-app/server'
import { z } from 'zod'

export default defineApp<Env>({
  onDeleteRequest: async () => {},
  rpc: {
    send: defineRpc({
      input: z.object({ to: z.email(), subject: z.string() }),
      output: z.object({ id: z.string() }),
      handler: async (args, ctx) => {
        return { id: await deliver(args, ctx.secrets.API_KEY) }
      }
    })
  }
})

input and output are any schemas implementing the Standard Schema and Standard JSON Schema interfaces — zod 4 does. The handler receives the parsed arguments and its result is parsed before it reaches the caller; a result the output schema rejects fails the call on the callee's side. qinto app publish extracts both schemas as JSON Schema into the version's RPC contract, which is what qinto app dev turns into a typed mock for the apps that call you.

A call takes the traffic class of the work that started it:

| Class | Started by | Deadline | ctx.query in the callee | | --- | --- | --- | --- | | hot | an event or connect hook, an endpoint | 10 s | throws | | cold | a panel (ui), a tool, a schedule, a workflow | 40 s | works, against the callee's own resources |

An rpc handler passes its own class on to the calls it makes. Arguments and result are capped at 128 KB each way for both classes; to return more rows, page with LIMIT and a time range.

A failed ctx.apps.call rejects with an Error whose message starts with a code:

| Code | Meaning | | --- | --- | | invalid_arguments: <path>: <message> | the callee's input schema refused the arguments | | result_too_large: <reason> | the result is over 128 KB | | callee_timeout: <reason> | the callee did not answer within its class deadline | | rpc_error: <message> | the handler threw RpcError with this message | | callee_failed | any other failure; the reason is only in the callee's logs |

Throw RpcError to tell the caller why a call failed. The platform keeps the first 1,024 characters and redacts URL query values. Any other throw reaches the caller as callee_failed, so a vendor error that quotes a credential stays in your logs.

import { defineRpc, RpcError } from '@blotout/qinto-sdk-app/server'

const query = defineRpc({
  input: z.object({ sql: z.string() }),
  output: z.object({ rows: z.array(z.record(z.string(), z.unknown())) }),
  handler: async ({ sql }, ctx) => {
    if (!sql.trimStart().toUpperCase().startsWith('SELECT')) {
      throw new RpcError('only SELECT statements are accepted')
    }

    return { rows: (await ctx.query.catalog('lake', sql)).rows }
  }
})

Durable work

import { defineApp, defineWorkflow } from '@blotout/qinto-sdk-app/server'

export default defineApp<Env>({
  onDeleteRequest: async () => {},
  endpoints: {
    '/webhook': async (request, ctx) => {
      await ctx.startWorkflow(ctx.env.ORDER_SYNC, { orderId: '123' }, { id: 'order-123' })

      return new Response('queued', { status: 202 })
    }
  },
  workflows: {
    OrderSync: defineWorkflow<Env, { orderId: string }>(async (event, step, ctx) => {
      const order = await step.do('fetch', async () => {
        return fetchOrder(event.payload.orderId, ctx.secrets.API_KEY)
      })

      await step.sleep('settle', '1 hour')
      await step.do('notify', async () => {
        await ctx.push({ topic: 'order:synced', data: order })
      })
    })
  }
})

Cloudflare owns the retries, the sleeps, and the per-step persistence, so a destination does not hand-roll its own retry loop. Passing options.id names the instance, which is how a retried vendor webhook avoids starting a second run.

Queues

import { defineApp } from '@blotout/qinto-sdk-app/server'

export default defineApp<Env>({
  onDeleteRequest: async () => {},
  onEvent: {
    track: async (action, ctx) => {
      await ctx.queues.send('vendor-events', { event: action.payload.event, at: action.receivedAt })
    }
  },
  queues: {
    'vendor-events': async (messages, ctx) => {
      const response = await fetch('https://vendor.example/batch', {
        method: 'POST',
        headers: { authorization: `Bearer ${ctx.secrets.API_KEY}` },
        body: JSON.stringify(messages.map((message) => message.body))
      })
      if (!response.ok) {
        throw new Error(`vendor answered ${response.status}`)
      }
    }
  }
})

A queue resource in the manifest gets a queues handler under the same identifier; publish refuses one without the other. Each handler call gets the messages of one install, with that install's ctx, so the vendor request above uses that install's secret. Each message has id, body, timestamp (when it was sent), attempts (1 on the first delivery), ack() and retry({ delaySeconds }). When the handler returns, each message it did not ack() or retry() is acked. When it throws, each message of that install it did not ack is retried, up to the manifest's maxRetries; the other installs in the batch are not affected. A message retried on its last attempt is dropped, and the install gets an app error with the dropped message ids. The messages of a removed or disabled install are dropped without a handler call. ctx has no query: a queue consumer cannot run analytics or catalog queries. Delivery is at least once and in no fixed order, so put your own id in the body and deduplicate on it when the vendor needs it. The batch settings, limits, defaults and delivery rules are in the manifest reference.

Workers AI

Qinto hands out no AI binding. runAi calls Cloudflare's /ai/run endpoint over REST with a token you supply, so the run bills your account.

import { runAi } from '@blotout/qinto-sdk-app/server'

const { response } = await runAi<{ response: string }>({
  accountId: ctx.appVariables.CF_ACCOUNT_ID,
  apiToken: ctx.appSecrets.CF_AI_TOKEN,
  model: '@cf/meta/llama-3.1-8b-instruct',
  input: { prompt: 'Summarise this basket' }
})

The token needs Account → Workers AI → Read; one holding only an AI Gateway permission is refused, and runAi says so rather than passing on Cloudflare's bare Authentication error. It also unwraps the response envelope and raises the refusals Cloudflare returns under HTTP 200.

Some models answer bytes rather than an envelope — @cf/myshell-ai/melotts documents both application/json and a raw audio/mpeg body, and picks per run. runAiBytes reads those, returning the content type alongside the bytes:

const { contentType, bytes } = await runAiBytes({
  accountId: ctx.appVariables.CF_ACCOUNT_ID,
  apiToken: ctx.appSecrets.CF_AI_TOKEN,
  model: '@cf/myshell-ai/melotts',
  input: { prompt: 'Your order has shipped', lang: 'en' }
})

The two read the same run and disagree only about the body, so each says which one the answer wanted: runAi raises ai_invalid_response naming the content type it got, and runAiBytes raises ai_json_response when the run answered an envelope after all. Refusals map to the same errors from either.

Both read one buffered answer, so both refuse input.stream: true rather than sending a run whose server-sent events neither can parse — the refusal comes before the request, so a stream you meant to consume is never billed. Call /ai/run yourself when you want to stream.

Cloudflare refuses a @cf/ model that names no gateway, so runAi sends default for one — the single gateway id Cloudflare creates on first use, with logging on, caching off, and Standard billing. Pass gatewayId to route through one of your own instead, which is where spend limits and per-model settings live; any id other than default must exist before you use it. A third-party model (openai/…, anthropic/…) needs no gateway and gets no header.

Declare both values in the manifest's appVariables so they are yours and set once, not asked of every site that installs the app — the token with qinto app secret set, the account id with qinto app var set.

For chat completions, point the OpenAI SDK at the account's /ai/v1/chat/completions instead; that path is OpenAI-compatible and needs nothing from us. The gateway rule still applies there, so a @cf/ model needs the header set on the client:

const client = new OpenAI({
  apiKey: ctx.appSecrets.CF_AI_TOKEN,
  baseURL: `https://api.cloudflare.com/client/v4/accounts/${ctx.appVariables.CF_ACCOUNT_ID}/ai/v1`,
  defaultHeaders: { 'cf-aig-gateway-id': 'default' }
})

The browser app

An app may also ship code that runs in the page, inside the site's tag. The factory runs once per active install, and only for a visitor whose consent covers your app.

import { defineBrowserApp } from '@blotout/qinto-sdk-app/browser'

export default defineBrowserApp((app) => {
  app.onEvent((event) => {
    return { observedAt: Date.now(), siteTag: app.variables.SITE_TAG }
  })

  app.onPush((message) => {
    console.info('server push', message.from, message.topic, message.data)
  })
})

The factory receives BrowserAppApi:

| | | Type | | --- | --- | --- | | app.variables, app.install | This install's browser-exposed plain settings, and which install it is. Secrets never reach the page. | BrowserAppInstall | | app.visitor | The visitor's anonId and linked globalId, already known when the factory runs, so a pixel can init with it synchronously. Each read is current: a reconnect that minted a new visitor shows through. Apps declaring the geo data capability also receive the server-observed ip and geo: { country, region, state, isEU }; otherwise both location fields are null. | BrowserAppVisitor | | app.consent | The consent this install runs under on this page, already known when the factory runs. Each read is current, also inside an onConsent handler. categories applies the site's settings on top of the stored state: every category is granted while the site does not enforce consent, Global Privacy Control denies marketing and salesOfData where the site honors it, and an install the visitor switched off in apps reads every category but necessary as denied. | BrowserConsentState | | app.page | The page the visitor sees, as { url, referrer }. Each read is current. In a sandboxed frame, such as a Shopify custom pixel, window.location names the frame and this names the page. | BrowserAppPage | | app.onEvent | Every action on the page. What you return reaches your own server hook for that same action as action.browser, when the manifest allows it — treat it as untrusted page input. | BrowserAppEvent | | app.onTransform | A synchronous hook on every page track, before any install's onEvent. It receives the track and the page URL. Return nothing to let the event through, { installs }, { apps } or both to keep the installs those rules exclude from running onEvent (the event is still sent), or false to cancel the event on the page. A hook that throws lets the event through, and two transform installs combine by intersection. Identify, consent and an app's own track skip it. Needs flows: ["transform"] and browser.hooks: ["transform"]. The server never reads the result. | BrowserTrackEvent, BrowserTransformResult | | app.onConsent | Every change to the visitor's consent after the factory ran, whether this page, another tab or another device made it. The factory itself runs only once consent covers the app. The handler receives the stored state; read app.consent for what applies on this page. | BrowserConsentState | | app.onPush | Messages your server code sent with ctx.push. A page that was closed missed them; pushes are never replayed. | BrowserPushMessage | | app.onSharedContext | What every contributing app knows about this visitor, where both sides declared the capability. | BrowserSharedContext | | app.track | Send an event of your own. | — | | app.fetch | Call one of your own auth: "visitor" endpoints as this visitor and install: app.fetch('/ask', { method: 'POST', body }). The response may stream; the body is capped at 2 MiB. | Response |

The settings panel

A panel is a static page the Qinto platform frames when a site manager configures your app. createAppUi is the bridge to the page around it.

import { createAppUi } from '@blotout/qinto-sdk-app/ui'

const ui = createAppUi()
const context = await ui.getContext()

const response = await ui.fetch('/analytics', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ installId: context.appInstallId })
})

const events = await ui.query.catalog(
  'lake',
  'SELECT event_name, event_timestamp FROM lake.events ORDER BY event_timestamp DESC LIMIT 100'
)

const usage = await ui.query.analytics(
  'events',
  'SELECT blob1 AS name, SUM(_sample_interval) AS count FROM events WHERE timestamp > NOW() - INTERVAL \'1\' DAY GROUP BY name'
)

createAppUi returns AppUi:

| | | Resolves to | | --- | --- | --- | | getContext() | The team, the site (its origin and worker hostname, plus the origin this panel fetches from), your app and version, the install the panel was opened for, every live install with its plain variables, the viewer's time zone, and the theme. | AppUiPanelContext | | getToken() | The current panel token, renewed before it expires. | string | | fetch(path, init?) | Calls your own ui server handler with that token attached, and returns the raw Response. Parse it, and decide yourself what a 429 or a 5xx means. | Response | | query.catalog(resourceIdentifier, sql) | Runs R2 SQL against a catalog-enabled R2 resource in the version serving this panel. The same method is available on scheduled-run and MCP-tool contexts. Qinto keeps the physical bucket and host credential server-side and returns { rows, meta }. | AppCatalogQueryResult | | query.analytics(resourceIdentifier, sql) | Runs one single-table SELECT against an analytics_engine resource in the version serving this panel; name the dataset by its resource identifier in FROM. Also on scheduled-run and MCP-tool contexts. Qinto substitutes the real dataset name server-side and returns { rows }; a never-written dataset returns none. | AppAnalyticsQueryResult |

The two sides of a panel each have a context, and they are different objects: AppUiPanelContext is what getContext() gives the page, and AppUiContext<Env> is what your own ui handler receives on the other end of fetch. The page one carries no secret and no binding; the server one carries both.

appRole is the viewer's app role on this site — full or a role your manifest's roles declares. Use atLeast(context, 'editor') to show or hide features, buttons and navigation, and refuse on the server with atLeast(ctx.viewer, 'editor') in your ui handler: the panel runs in the viewer's browser, so a check made only there is not security. full passes every atLeast.

siteInstalls lists the other apps' enabled installs on the site as { id, appSlug, appName, label }, on both getContext() and the server handler's ctx. It is there only when your manifest declares the siteInstalls data capability, and absent otherwise. Use it to let the site manager pick installs, then pass their ids to ctx.track in its installs rule. Check a posted id against ctx.siteInstalls on the server, as with ctx.installs.

timeZone is the IANA zone the viewing user set in their Qinto profile (UTC until they have one). Format times with it — new Intl.DateTimeFormat(undefined, { timeZone }) — instead of shipping a zone picker of your own.

The platform gives the panel the whole area under the site's header and nothing else — size your page to it and let it scroll inside, the way any page in a window does.

A link to another site opens a new tab: give it target="_blank", or call window.open. The tab is a normal one, outside the sandbox. The frame itself stays on your panel's own origin — the platform refuses any other origin inside it, and it never leaves the page on the panel's behalf except through connect and changeTier.

Your panel runs in the viewer's browser, so it never receives a secret. The install id it posts is input, not authority — resolve it against ctx.installs in the server handler, which the platform built from the site's own registry.

The manifest

qinto.app.jsonc is the app: it names it, says where it plugs into the pipeline, and declares everything it may reach. Point $schema at the file this package ships and your editor does the rest:

{
  "$schema": "./node_modules/@blotout/qinto-sdk-app/app.schema.json",
  "slug": "my-app",
  "name": "My App",
  "flows": ["destination"],
  "consent": { "category": "analytics" },
  "legal": { "termsUrl": "https://example.com/terms", "privacyUrl": "https://example.com/privacy" },
  "server": {
    "entry": "src/server.ts",
    "hooks": { "transform": [], "onEvent": ["track"], "onConnect": false }
  }
}

The manifest is authoritative: server.hooks must match the hooks your entry exports, every declared schedule, workflow class, queue, and backfill handler must exist, and a ui block needs a ui handler. The CLI checks all of it before anything is uploaded.

The loop

qinto app create my-app      # scaffold, install, register
qinto app dev                # run it against a local Qinto — real platform bundles, no account, no login
qinto app publish            # build, upload, and publish an immutable version
qinto app install my-app --site example.com
qinto app status my-app --site example.com

qinto app dev boots the released site worker and app runtime in workerd, with a console, a demo site, and a live trace of every request — so the transform chain, the consent gate, and the dispatch into your hooks are the real ones.

A browser_run binding is a local Chrome by default. Puppeteer, Playwright and Stagehand work against it, but Quick Actions (.quickAction()) do not. qinto app dev --remote-browser gives the binding a real Browser Run session in your own Cloudflare account instead, so Quick Actions work locally. Browser time is billed to that account. Set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN; the token needs Account > Workers Scripts > Edit.

Documentation

The manifest reference, the app limits, the standard events, and the CLI are at docs.blotout.io.