@trytilde/ontology 3.1.1 → 4.0.0

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.
package/dist/catalog.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Every `kind` of a ducktail pipeline. */
2
- export type PipelineKind = "postgres" | "kafka" | "webhook" | "linear" | "sentry" | "cloudwatch" | "plaid" | "quickbooks" | "xero" | "gmail" | "google_calendar" | "google_contacts" | "slack" | "cell_edits";
2
+ export type PipelineKind = "postgres" | "kafka" | "webhook" | "linear" | "sentry" | "github" | "cloudwatch" | "plaid" | "quickbooks" | "xero" | "gmail" | "google_calendar" | "google_contacts" | "slack" | "cell_edits";
3
3
  /** Polled kinds (one leased task each). */
4
4
  export type PolledKind = "linear" | "sentry" | "cloudwatch" | "plaid" | "quickbooks" | "xero" | "gmail" | "google_calendar" | "google_contacts" | "slack";
5
5
  /** Each polled kind's streams. */
@@ -15,7 +15,7 @@ export interface PolledStreams {
15
15
  google_contacts: "contacts" | "other_contacts" | "contact_groups";
16
16
  slack: "conversations" | "users" | "messages" | "replies";
17
17
  }
18
- /** The Tilde connection provider each polled kind takes its slot of. */
18
+ /** The Tilde connection provider each polled kind takes its connection from. */
19
19
  export interface PolledProvider {
20
20
  linear: "linear";
21
21
  sentry: "sentry";
@@ -28,6 +28,26 @@ export interface PolledProvider {
28
28
  google_contacts: "google";
29
29
  slack: "slack";
30
30
  }
31
+ /** Sync kinds: webhook plus backfill (plus a reconciling poll where it reconciles), one stream per entity. */
32
+ export type SyncKind = "linear" | "sentry" | "github";
33
+ /** Each sync kind's streams. */
34
+ export interface SyncStreams {
35
+ linear: "teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments";
36
+ sentry: "projects" | "issues";
37
+ github: "pull_requests" | "pull_request_reviews" | "check_runs" | "releases";
38
+ }
39
+ /** The Tilde connection provider each sync kind takes its connection from. */
40
+ export interface SyncProvider {
41
+ linear: "linear";
42
+ sentry: "sentry";
43
+ github: "github";
44
+ }
45
+ /** Whether a sync kind takes `reconcile` (a slow full poll). */
46
+ export interface SyncReconciles {
47
+ linear: true;
48
+ sentry: true;
49
+ github: false;
50
+ }
31
51
  /** Providers whose webhooks a webhook pipeline routes by event. */
32
52
  export type WebhookProvider = "github" | "linear" | "sentry";
33
53
  /** Each provider's event names (the values of its event header). */
package/dist/mod.d.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * - **verbs**: `action` (txWrite) and `read` (txRead in a view, or `read` against the lake),
10
10
  * with zod input and output and declared `edits` and `reads` (enforced). Handlers call
11
11
  * third parties with plain `fetch` or SDKs; `ctx.deferredFetch` sends a request durably after
12
- * the action commits, with credentials from a `connection` slot (a third-party account the
12
+ * the action commits, with credentials from a declared connection (a third-party account the
13
13
  * environment binds, never visible to handlers) or an `auth` resolver over declared `secrets`;
14
14
  * - **realtime views**: `realtime` reads whose results are pushed to subscribers when they
15
15
  * change (per view instance in its cell, or across cells from the lake);
@@ -41,8 +41,8 @@
41
41
  * ```
42
42
  */
43
43
  import { z } from "zod";
44
- import { type PolledKind, type PolledProvider, type PolledStreams, type WebhookEvents } from "./catalog.ts";
45
- export type { PipelineKind, PolledKind, PolledProvider, PolledStreams, WebhookEvents, WebhookProvider } from "./catalog.ts";
44
+ import { type PolledKind, type PolledProvider, type PolledStreams, type SyncStreams, type WebhookEvents, type WebhookProvider } from "./catalog.js";
45
+ export type { PipelineKind, PolledKind, PolledProvider, PolledStreams, WebhookEvents, WebhookProvider } from "./catalog.js";
46
46
  export type Json = null | boolean | number | string | Json[] | {
47
47
  [key: string]: Json;
48
48
  };
@@ -517,54 +517,37 @@ export interface EnvDef {
517
517
  export declare const secret: () => EnvDef;
518
518
  export declare const setting: (defaultValue?: string) => EnvDef;
519
519
  /**
520
- * A connection slot: a third-party account the project needs (`connection("linear")`), which
521
- * each environment binds to one of its organization's Tilde connections of that provider (and
522
- * type, when given). Name it as a request's `auth` (`deferredFetch(url, init, { auth: linear })`,
523
- * a read's `ctx.authHeaders(linear)`): the runtime gets the account's current credentials from
524
- * the control plane when the request is sent (fresh, refreshed tokens; cached briefly) and sets
525
- * them as headers. Handlers never see them. Pipelines name the same slot (`linear.poll({ slot })`).
526
- * Declare slots with `defineSlots` and `ontology({ slots })` (or `connection()` and `connections`).
520
+ * A third-party account the project needs, which each environment binds to one of its
521
+ * organization's Tilde connections of that provider (and type, when given). Declared as plain
522
+ * data, keyed by name: `export const connections = { linear: { provider: "linear" } } satisfies
523
+ * Connections`, passed to `ontology({ connections })`. Name one as a request's `auth`
524
+ * (`deferredFetch(url, init, { auth: connections.linear })`, a read's
525
+ * `ctx.authHeaders(connections.linear)`): the runtime gets the account's current credentials
526
+ * from the control plane when the request is sent and sets them as headers. Handlers never see
527
+ * them. Pipelines take the same object (`linear.poll({ connection: connections.linear })`).
527
528
  */
528
- export interface ConnectionDef {
529
- readonly kind: "connection";
530
- /** The slot's name (snake_case), unique among slots and `auth` resolvers. */
531
- readonly name: string;
529
+ export interface Connection<P extends string = string> {
532
530
  /** The Tilde connection provider (`linear`, `github`, `sentry`, `aws`, ...). */
533
- readonly provider: string;
534
- /** One of the provider's connection types (`api_key`, `oauth`, ...); null accepts any. */
535
- readonly type: string | null;
536
- readonly loc: string | null;
537
- }
538
- /** A connection slot; `provider` defaults to the slot's name. */
539
- export declare function connection(name: string, options?: {
540
- provider?: string;
541
- type?: string;
542
- }): ConnectionDef;
543
- /** A slot as `slot()` makes it, named by `defineSlots`. */
544
- export interface SlotSpec<P extends string = string> {
545
- readonly kind: "slot";
546
- readonly provider: P;
547
- readonly type: string | null;
548
- readonly loc: string | null;
549
- }
550
- /** A declared connection slot whose provider is `P` (`defineSlots`). */
551
- export interface Slot<P extends string = string> extends ConnectionDef {
552
531
  readonly provider: P;
532
+ /** One of the provider's connection types (`api_key`, `oauth`, ...); absent accepts any. */
533
+ readonly type?: string;
534
+ /**
535
+ * An environment may leave it unbound: it deploys without it, the pipelines that name it are
536
+ * skipped until it is bound and the project deployed again, and a request sent through it
537
+ * meanwhile fails saying so. A required connection (the default) must be bound before a deploy.
538
+ */
539
+ readonly optional?: boolean;
553
540
  }
554
- /** A connection slot of a Tilde connection provider (and optionally one of its types), named by
555
- * its key in `defineSlots`. */
556
- export declare function slot<const P extends string>(provider: P, options?: {
557
- type?: string;
558
- }): SlotSpec<P>;
559
541
  /**
560
- * The connection slots the ontology needs, by name: `defineSlots({ linear: slot("linear"),
561
- * github: slot("github") })`. Pipelines and requests name them as `slots.linear` (a pipeline
562
- * helper takes only a slot of its provider), each environment binds them to its organization's
563
- * connections, and `ontology({ slots })` declares them.
542
+ * An ontology's connections by name. `satisfies Connections` keeps each provider's literal type
543
+ * (the catalog's providers in the union give TypeScript a literal context; `string & {}` admits
544
+ * any other), so a pipeline helper takes only a connection of its provider.
564
545
  */
565
- export declare function defineSlots<const S extends Record<string, SlotSpec>>(slots: S): {
566
- readonly [K in keyof S]: Slot<S[K]["provider"]>;
546
+ export type Connections = {
547
+ readonly [name: string]: Connection<PolledProvider[PolledKind] | WebhookProvider | (string & {})>;
567
548
  };
549
+ /** The name of a connection `ontology({ connections })` declares, or of an `auth` resolver. */
550
+ export declare function authName(auth: Connection | AuthDef): string;
568
551
  /** A declared raw secret (`defineSecrets`), which pipelines take where ducktail wants a secret. */
569
552
  export interface SecretRef<N extends string = string> {
570
553
  readonly kind: "secretRef";
@@ -594,13 +577,13 @@ export type PipelineValue = string | number | boolean | SecretRef | SecretText |
594
577
  };
595
578
  /**
596
579
  * What feeds a source's raw streams (`lake.raw.<source>__<stream>`): one ducktail pipeline of
597
- * `type`, optionally through a connection slot, with its streams and ducktail's own config keys
580
+ * `type`, optionally through a connection, with its streams and ducktail's own config keys
598
581
  * (`options`, snake_case as ducktail's README writes them). Made by the helpers below; the build
599
582
  * compiles it into the version and the environment's rollout gives it to ducktail.
600
583
  */
601
584
  export declare class Pipeline<S extends string = string> {
602
585
  readonly type: string;
603
- readonly slot: ConnectionDef | null;
586
+ readonly connection: Connection | null;
604
587
  readonly streams: readonly S[];
605
588
  readonly options: {
606
589
  readonly [key: string]: PipelineValue | undefined;
@@ -609,7 +592,7 @@ export declare class Pipeline<S extends string = string> {
609
592
  /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
610
593
  readonly name: string | null;
611
594
  readonly kind = "pipeline";
612
- constructor(type: string, slot: ConnectionDef | null, streams: readonly S[], options: {
595
+ constructor(type: string, connection: Connection | null, streams: readonly S[], options: {
613
596
  readonly [key: string]: PipelineValue | undefined;
614
597
  }, loc: string | null,
615
598
  /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
@@ -647,7 +630,7 @@ interface PollOptions<St extends string> {
647
630
  }
648
631
  /** A provider webhook's routing: event name -> stream, the rest to `fallback`. */
649
632
  interface WebhookOptions<P extends keyof WebhookEvents, S extends string> {
650
- slot: Slot<P>;
633
+ connection: Connection<P>;
651
634
  /** The pipeline's streams. */
652
635
  streams: readonly S[];
653
636
  /** Event -> stream; events not listed go to `fallback` (without one, ducktail answers 422). */
@@ -659,7 +642,7 @@ interface WebhookOptions<P extends keyof WebhookEvents, S extends string> {
659
642
  /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
660
643
  export declare const linear: {
661
644
  poll: <const St extends PolledStreams["linear"] = "teams" | "users" | "workflow_states" | "projects" | "cycles" | "issues" | "comments">(o: PollOptions<St> & {
662
- slot: Slot<"linear">;
645
+ connection: Connection<"linear">;
663
646
  pageSize?: number;
664
647
  /** A stream's GraphQL selection, replacing the built-in one. */
665
648
  fields?: { readonly [K in PolledStreams["linear"]]?: string; };
@@ -670,7 +653,7 @@ export declare const linear: {
670
653
  /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
671
654
  export declare const sentry: {
672
655
  poll: <const St extends PolledStreams["sentry"] = "projects" | "issues">(o: PollOptions<St> & {
673
- slot: Slot<"sentry">;
656
+ connection: Connection<"sentry">;
674
657
  organization: string;
675
658
  /** Project slugs whose issues are polled. */
676
659
  projects?: readonly string[];
@@ -681,17 +664,31 @@ export declare const sentry: {
681
664
  }) => Pipeline<St>;
682
665
  webhook: <const S extends string>(o: WebhookOptions<"sentry", S>) => WebhookPipeline<S, "installation" | "comment" | "error" | "event_alert" | "issue" | "metric_alert" | "seer">;
683
666
  };
684
- /** GitHub: the connection's webhooks (a GitHub App's), with an optional backfill of history. */
667
+ /** GitHub: the connection's webhooks (a GitHub App's). */
685
668
  export declare const github: {
686
- webhook: <const S extends string>(o: WebhookOptions<"github", S> & {
687
- /** On the pipeline's first run, fetch the repositories' history as the webhook delivers it. */
669
+ /**
670
+ * One stream per entity (ducktail's `github` sync pipeline): the connection's webhooks for
671
+ * the repositories, after a backfill of their recent pull requests, reviews, check runs and
672
+ * releases on the first run (default 30 days). Each row's `_key` is the entity
673
+ * (`{repository, number}` for pull requests, else `{id}`) and `_source_ts` its own time; the
674
+ * payload is the webhook body. Never reconciles: GitHub's webhooks are complete.
675
+ */
676
+ sync: <const St extends SyncStreams["github"] = "pull_requests" | "pull_request_reviews" | "check_runs" | "releases">(o: {
677
+ connection: Connection<"github">;
678
+ /** `owner/name`: backfilled, and the only repositories whose deliveries are written. */
679
+ repositories: readonly string[];
680
+ /** The streams to write (default: all). */
681
+ streams?: readonly St[];
682
+ /** Where the backfill starts: a date, an RFC 3339 time or a duration before now. */
688
683
  backfill?: {
689
- repositories: readonly string[];
690
- start?: string;
691
- baseUrl?: string;
692
- pageSize?: number;
684
+ start: string;
693
685
  };
694
- }) => WebhookPipeline<S, "issues" | "check_run" | "check_suite" | "code_scanning_alert" | "create" | "delete" | "dependabot_alert" | "deployment" | "deployment_status" | "discussion" | "discussion_comment" | "fork" | "installation" | "installation_repositories" | "issue_comment" | "label" | "member" | "merge_group" | "milestone" | "ping" | "pull_request" | "pull_request_review" | "pull_request_review_comment" | "pull_request_review_thread" | "push" | "release" | "repository" | "secret_scanning_alert" | "status" | "workflow_job" | "workflow_run">;
686
+ baseUrl?: string;
687
+ pageSize?: number;
688
+ requestTimeout?: Duration;
689
+ }) => Pipeline<St>;
690
+ /** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
691
+ webhook: <const S extends string>(o: WebhookOptions<"github", S>) => WebhookPipeline<S, "issues" | "check_run" | "check_suite" | "code_scanning_alert" | "create" | "delete" | "dependabot_alert" | "deployment" | "deployment_status" | "discussion" | "discussion_comment" | "fork" | "installation" | "installation_repositories" | "issue_comment" | "label" | "member" | "merge_group" | "milestone" | "ping" | "pull_request" | "pull_request_review" | "pull_request_review_comment" | "pull_request_review_thread" | "push" | "release" | "repository" | "secret_scanning_alert" | "status" | "workflow_job" | "workflow_run">;
695
692
  };
696
693
  /** A CloudWatch metric (`AWS/RDS` `CPUUtilization` ...). */
697
694
  export interface CloudwatchMetric {
@@ -706,7 +703,7 @@ export interface CloudwatchMetric {
706
703
  /** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
707
704
  export declare const cloudwatch: {
708
705
  poll: <const St extends PolledStreams["cloudwatch"] = "ecs_clusters" | "ecs_services" | "load_balancers" | "target_groups" | "target_health" | "metric_data" | "alarms" | "alarm_history">(o: PollOptions<St> & {
709
- slot: Slot<PolledProvider["cloudwatch"]>;
706
+ connection: Connection<PolledProvider["cloudwatch"]>;
710
707
  region: string;
711
708
  discoveryInterval?: Duration;
712
709
  period?: Duration;
@@ -729,7 +726,7 @@ export declare const cloudwatch: {
729
726
  /** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
730
727
  * `options` are ducktail's keys for it (README, "Polled sources"). */
731
728
  export declare function polled<K extends Exclude<PolledKind, "linear" | "sentry" | "cloudwatch">, const St extends PolledStreams[K] = PolledStreams[K]>(kind: K, o: PollOptions<St> & {
732
- slot: Slot<PolledProvider[K]>;
729
+ connection: Connection<PolledProvider[K]>;
733
730
  options?: {
734
731
  readonly [key: string]: PipelineValue | undefined;
735
732
  };
@@ -810,8 +807,8 @@ export interface DeferredOptions {
810
807
  values: Record<string, Json>;
811
808
  };
812
809
  /** Headers resolved when the request is sent (fresh credentials on every attempt): a
813
- * connection slot's or an `auth` resolver's. The outbox stores only the name. */
814
- auth?: AuthDef | ConnectionDef;
810
+ * connection's or an `auth` resolver's. The outbox stores only the name. */
811
+ auth?: AuthDef | Connection;
815
812
  /** An action of the same view to run once the request is delivered (2xx), with the
816
813
  * response as its input (`deferredResponse`); declare it in the action's `continuations`. */
817
814
  then?: HandlerDef;
@@ -903,11 +900,11 @@ export interface BaseCtx {
903
900
  /** Headers from an `auth` resolver, for live calls (cached like the outbox's). A connection's
904
901
  * credentials are never handed to handlers: send with `fetch`. */
905
902
  authHeaders(auth: AuthDef): Promise<Record<string, string>>;
906
- /** `fetch`, with the headers of a connection slot or an `auth` resolver set by the runtime
903
+ /** `fetch`, with the headers of a connection or an `auth` resolver set by the runtime
907
904
  * (replacing the request's): the handler gets the response, never the credentials. A 401 or
908
905
  * 403 drops the cached credentials. */
909
906
  fetch(input: string | URL | Request, init?: RequestInit, options?: {
910
- auth?: AuthDef | ConnectionDef;
907
+ auth?: AuthDef | Connection;
911
908
  }): Promise<Response>;
912
909
  /** Fail with `message` unless `condition` holds (a precondition). To narrow a value, use
913
910
  * `if (!x) return ctx.fail(...)` (assertion signatures do not survive destructuring). */
@@ -936,7 +933,7 @@ export interface ReadCtx extends BaseCtx {
936
933
  }
937
934
  /** An action's ctx. No `authHeaders` or `fetch`: credentials an action could read could end up
938
935
  * in a deferred request and be stored, and its calls to third parties are deferred; deferred
939
- * requests name their slot or resolver (`{ auth }`). */
936
+ * requests name their connection or resolver (`{ auth }`). */
940
937
  export interface TxCtx extends Omit<ReadCtx, "authHeaders" | "fetch"> {
941
938
  readonly invocationId: string;
942
939
  readonly deferredFetch: DeferredFetch;
@@ -960,7 +957,66 @@ export interface HandlerDef<N extends string = string, I extends z.ZodType = z.Z
960
957
  readonly output: O;
961
958
  readonly idempotency?: (input: any) => string;
962
959
  readonly handler: (args: any) => unknown;
960
+ /** A list realtime view's parts (see `realtime`); the runtime runs these, not `handler`. */
961
+ readonly list?: ListDef;
962
+ }
963
+ /** A value a list row sorts by (see `realtime`). */
964
+ export type OrderValue = string | number | boolean | null;
965
+ /** Which rows a list view's `rows` returns: those of `keys` the query matches (any order), or
966
+ * the first `limit` rows in order after the row whose `order` is `after` (null: from the top). */
967
+ export type ListSelect = {
968
+ keys: string[];
969
+ after?: undefined;
970
+ limit?: undefined;
971
+ } | {
972
+ keys?: undefined;
973
+ after: OrderValue[] | null;
974
+ limit: number;
975
+ };
976
+ export interface ListDef {
977
+ key: string;
978
+ row: z.ZodType;
979
+ order: (query: any) => {
980
+ by: (row: any) => OrderValue[];
981
+ desc?: boolean;
982
+ };
983
+ rows: (args: any) => unknown;
984
+ summary?: {
985
+ output: z.ZodType;
986
+ handler: (args: any) => unknown;
987
+ };
963
988
  }
989
+ /** The most rows a list view's window holds. */
990
+ export declare const LIST_MAX = 1000;
991
+ /** What a list view's subscriber sends: its query, how many rows from the top it shows, and
992
+ * `resume` (the last update's), when widening a window it already has or reconnecting. */
993
+ export declare const listInput: <I extends z.ZodType>(query: I) => z.ZodObject<{
994
+ query: I;
995
+ limit: z.ZodNumber;
996
+ resume: z.ZodDefault<z.ZodString>;
997
+ }, z.core.$strip>;
998
+ declare const listUpdateShape: <R extends z.ZodType>(row: R) => {
999
+ /** Drop the rows held: this update holds the whole window (the first, unless resumed). */
1000
+ reset: z.ZodBoolean;
1001
+ /** Rows that entered or changed, each at its index in the new window. */
1002
+ upserts: z.ZodArray<z.ZodObject<{
1003
+ key: z.ZodString;
1004
+ index: z.ZodNumber;
1005
+ row: R;
1006
+ }, z.core.$strip>>;
1007
+ /** Keys of rows that left the window. */
1008
+ removes: z.ZodArray<z.ZodString>;
1009
+ /** Rows exist past the window. */
1010
+ more: z.ZodBoolean;
1011
+ /** Pass back as `resume` to widen this window without starting over. */
1012
+ resume: z.ZodString;
1013
+ };
1014
+ type ListUpdateShape<R extends z.ZodType, S extends z.ZodType | undefined> = ReturnType<typeof listUpdateShape<R>> & (S extends z.ZodType ? {
1015
+ summary: z.ZodOptional<S>;
1016
+ } : Record<never, never>);
1017
+ /** A list view's update: what changed in the window since the last one (see `realtime`).
1018
+ * `summary` is present on a reset and when it changed. */
1019
+ export declare const listUpdate: <R extends z.ZodType, S extends z.ZodType | undefined>(row: R, summary?: S) => z.ZodObject<ListUpdateShape<R, S>>;
964
1020
  /** A transactional write in one view instance. `edits` and `reads` are hard limits. */
965
1021
  export declare function action<const N extends string, V extends ViewDef, I extends z.ZodType, O extends z.ZodType>(name: N, spec: {
966
1022
  description?: string;
@@ -1045,6 +1101,44 @@ export declare function realtime<const N extends string, I extends z.ZodType, O
1045
1101
  ctx: LakeReadCtx;
1046
1102
  }) => z.input<O> | Promise<z.input<O>>;
1047
1103
  }): HandlerDef<N, I, O, false>;
1104
+ /**
1105
+ * - **list** (`watch` with `row`, `key`, `order` and `rows` instead of `output` and `handler`): a
1106
+ * window of rows from the top of an ordered list, kept by deltas. A subscriber sends `{ query,
1107
+ * limit, resume }`; the first update holds the window (`reset`), later ones only the rows that
1108
+ * entered or changed (`upserts`, each with its index in the new window), the keys that left
1109
+ * (`removes`), whether more rows follow (`more`) and the `summary` when it changed. On Postgres
1110
+ * storage a commit to a watched model re-reads only the keys it changed (from the model's
1111
+ * change feed; `rows` with `keys`), as the subscriber, so Cedar and masking hold; anything
1112
+ * else it watches re-reads the window. A window that loses a row is topped up from below
1113
+ * (`rows` with `after`). Widening is a new subscription with the larger `limit` and the last
1114
+ * update's `resume`: it gets only the new rows. `order` sorts rows the way `rows` does (null
1115
+ * first, then booleans, numbers, strings by code unit; reversed by `desc`); end it with the
1116
+ * key so no two rows tie. Every watched model's key is the row's `key`.
1117
+ */
1118
+ export declare function realtime<const N extends string, I extends z.ZodType, R extends z.ZodObject, S extends z.ZodType | undefined = undefined>(name: N, spec: {
1119
+ description?: string;
1120
+ watch: Watchable[];
1121
+ input: I;
1122
+ row: R;
1123
+ key: keyof z.infer<R> & string;
1124
+ order: (query: z.infer<I>) => {
1125
+ by: (row: z.infer<R>) => OrderValue[];
1126
+ desc?: boolean;
1127
+ };
1128
+ reads: Readable[];
1129
+ rows: (args: {
1130
+ input: z.infer<I>;
1131
+ ctx: LakeReadCtx;
1132
+ select: ListSelect;
1133
+ }) => z.input<R>[] | Promise<z.input<R>[]>;
1134
+ summary?: {
1135
+ output: S;
1136
+ handler: (args: {
1137
+ input: z.infer<I>;
1138
+ ctx: LakeReadCtx;
1139
+ }) => S extends z.ZodType ? z.input<S> | Promise<z.input<S>> : never;
1140
+ };
1141
+ }): HandlerDef<N, ReturnType<typeof listInput<I>>, ReturnType<typeof listUpdate<R, S>>, false>;
1048
1142
  /** Cedar policy text, built with `cedar`...``. */
1049
1143
  export interface CedarText {
1050
1144
  readonly kind: "cedar";
@@ -1073,6 +1167,11 @@ export declare const lake: CedarText;
1073
1167
  export declare const openSpace: CedarText;
1074
1168
  /** A space of the project (`spaces/<id>/`), a Cedar resource. */
1075
1169
  export declare function space(id: string): CedarText;
1170
+ /** Who may chat with a registry agent from a space (`<AgentChat>` in `@trytilde/spaces`), in which
1171
+ * registry thread (`context.thread`): `permit(principal, action == ${chatWithAgent}, resource == ${agent(id)}) when { ... };`. */
1172
+ export declare const chatWithAgent: CedarText;
1173
+ /** A Tilde registry agent by its id, a Cedar resource. */
1174
+ export declare function agent(id: string): CedarText;
1076
1175
  /** A group: the token's subject is in each group its `groups` attribute lists (comma-separated). */
1077
1176
  export declare function group(name: string): CedarText;
1078
1177
  export interface PolicyDef {
@@ -1099,15 +1198,11 @@ export interface OntologySpec {
1099
1198
  policies?: PolicyDef[];
1100
1199
  /** Credential resolvers for deferred (and live) requests. */
1101
1200
  auths?: AuthDef[];
1102
- /** Third-party accounts each environment binds (`connection`), for deferred (and live)
1103
- * requests and pipelines. Prefer `slots` (`defineSlots`). */
1104
- connections?: ConnectionDef[];
1201
+ /** Third-party accounts each environment binds, by name (`satisfies Connections`), for
1202
+ * deferred (and live) requests and pipelines. */
1203
+ connections?: Connections;
1105
1204
  /** Custom streams records are written to through Tilde's Ingress (`stream`). */
1106
1205
  streams?: StreamDef[];
1107
- /** Connection slots (`defineSlots`): third-party accounts each environment binds. */
1108
- slots?: {
1109
- readonly [name: string]: ConnectionDef;
1110
- };
1111
1206
  /** Raw secrets the pipelines take (`defineSecrets`), supplied by each environment. */
1112
1207
  secrets?: {
1113
1208
  readonly [name: string]: SecretRef;
package/dist/mod.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * - **verbs**: `action` (txWrite) and `read` (txRead in a view, or `read` against the lake),
10
10
  * with zod input and output and declared `edits` and `reads` (enforced). Handlers call
11
11
  * third parties with plain `fetch` or SDKs; `ctx.deferredFetch` sends a request durably after
12
- * the action commits, with credentials from a `connection` slot (a third-party account the
12
+ * the action commits, with credentials from a declared connection (a third-party account the
13
13
  * environment binds, never visible to handlers) or an `auth` resolver over declared `secrets`;
14
14
  * - **realtime views**: `realtime` reads whose results are pushed to subscribers when they
15
15
  * change (per view instance in its cell, or across cells from the lake);
@@ -395,23 +395,16 @@ export function transactionalView(name, spec) {
395
395
  }
396
396
  export const secret = () => ({ kind: "secret", default: null });
397
397
  export const setting = (defaultValue) => ({ kind: "setting", default: defaultValue ?? null });
398
- /** A connection slot; `provider` defaults to the slot's name. */
399
- export function connection(name, options = {}) {
400
- return { kind: "connection", name, provider: options.provider ?? name, type: options.type ?? null, loc: callSite() };
401
- }
402
- /** A connection slot of a Tilde connection provider (and optionally one of its types), named by
403
- * its key in `defineSlots`. */
404
- export function slot(provider, options = {}) {
405
- return { kind: "slot", provider, type: options.type ?? null, loc: callSite() };
406
- }
407
- /**
408
- * The connection slots the ontology needs, by name: `defineSlots({ linear: slot("linear"),
409
- * github: slot("github") })`. Pipelines and requests name them as `slots.linear` (a pipeline
410
- * helper takes only a slot of its provider), each environment binds them to its organization's
411
- * connections, and `ontology({ slots })` declares them.
412
- */
413
- export function defineSlots(slots) {
414
- return Object.fromEntries(Object.entries(slots).map(([name, s]) => [name, { kind: "connection", name, provider: s.provider, type: s.type, loc: s.loc }]));
398
+ /** Each declared connection's name: `ontology()` records them, at build time and in the Worker. */
399
+ const connectionNames = new WeakMap();
400
+ /** The name of a connection `ontology({ connections })` declares, or of an `auth` resolver. */
401
+ export function authName(auth) {
402
+ if ("kind" in auth && auth.kind === "auth")
403
+ return auth.name;
404
+ const name = connectionNames.get(auth);
405
+ if (!name)
406
+ throw new ActionError(`a connection (${auth.provider}) not declared in ontology({ connections }): declare it`);
407
+ return name;
415
408
  }
416
409
  /**
417
410
  * The raw secrets the ontology's pipelines need, by name: `defineSecrets({ PG_PASSWORD:
@@ -430,23 +423,23 @@ export function defineSecrets(secrets) {
430
423
  }
431
424
  /**
432
425
  * What feeds a source's raw streams (`lake.raw.<source>__<stream>`): one ducktail pipeline of
433
- * `type`, optionally through a connection slot, with its streams and ducktail's own config keys
426
+ * `type`, optionally through a connection, with its streams and ducktail's own config keys
434
427
  * (`options`, snake_case as ducktail's README writes them). Made by the helpers below; the build
435
428
  * compiles it into the version and the environment's rollout gives it to ducktail.
436
429
  */
437
430
  export class Pipeline {
438
431
  type;
439
- slot;
432
+ connection;
440
433
  streams;
441
434
  options;
442
435
  loc;
443
436
  name;
444
437
  kind = "pipeline";
445
- constructor(type, slot, streams, options, loc,
438
+ constructor(type, connection, streams, options, loc,
446
439
  /** The name the source must have (Tilde's registry events post to `tilde`), else null. */
447
440
  name = null) {
448
441
  this.type = type;
449
- this.slot = slot;
442
+ this.connection = connection;
450
443
  this.streams = streams;
451
444
  this.options = options;
452
445
  this.loc = loc;
@@ -454,7 +447,7 @@ export class Pipeline {
454
447
  }
455
448
  /** More streams, beyond those this SDK's catalog knows (validated by ducktail when it starts). */
456
449
  untypedStreams(...names) {
457
- return new Pipeline(this.type, this.slot, [...this.streams, ...names], this.options, this.loc, this.name);
450
+ return new Pipeline(this.type, this.connection, [...this.streams, ...names], this.options, this.loc, this.name);
458
451
  }
459
452
  }
460
453
  /** A webhook pipeline routing a provider's deliveries by event (`E`) to its streams. */
@@ -463,7 +456,7 @@ export class WebhookPipeline extends Pipeline {
463
456
  untypedEvents(routes) {
464
457
  const route = this.options.route;
465
458
  const options = { ...this.options, route: { ...route, streams: { ...route.streams, ...routes } } };
466
- return new WebhookPipeline(this.type, this.slot, this.streams, options, this.loc, this.name);
459
+ return new WebhookPipeline(this.type, this.connection, this.streams, options, this.loc, this.name);
467
460
  }
468
461
  }
469
462
  /** A declared source: a pipeline under its name, whose streams are sources. */
@@ -482,7 +475,7 @@ export class PipelineSource {
482
475
  return new SourceDef(this.name, stream, callSite());
483
476
  }
484
477
  }
485
- const poll = (kind, slot, o, extra) => new Pipeline(kind, slot, o.streams ?? [], {
478
+ const poll = (kind, connection, o, extra) => new Pipeline(kind, connection, o.streams ?? [], {
486
479
  interval: o.interval,
487
480
  backfill: o.backfill,
488
481
  request_timeout: o.requestTimeout,
@@ -491,7 +484,7 @@ const poll = (kind, slot, o, extra) => new Pipeline(kind, slot, o.streams ?? [],
491
484
  function providerWebhook(provider, o, extra = {}) {
492
485
  const headers = webhookHeaders[provider];
493
486
  const routes = Object.fromEntries(Object.entries(o.route).filter(([, v]) => v !== undefined));
494
- return new WebhookPipeline("webhook", o.slot, o.streams, {
487
+ return new WebhookPipeline("webhook", o.connection, o.streams, {
495
488
  key_header: headers.key,
496
489
  route: { header: headers.event, streams: routes, fallback: o.fallback },
497
490
  ...extra,
@@ -499,12 +492,12 @@ function providerWebhook(provider, o, extra = {}) {
499
492
  }
500
493
  /** Linear: polled GraphQL (history, then changes) and the connection's webhooks. */
501
494
  export const linear = {
502
- poll: (o) => poll("linear", o.slot, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
495
+ poll: (o) => poll("linear", o.connection, o, { page_size: o.pageSize, fields: o.fields, endpoint: o.endpoint }),
503
496
  webhook: (o) => providerWebhook("linear", o),
504
497
  };
505
498
  /** Sentry: polled issues (and projects) and the connection's integration webhooks. */
506
499
  export const sentry = {
507
- poll: (o) => poll("sentry", o.slot, o, {
500
+ poll: (o) => poll("sentry", o.connection, o, {
508
501
  organization: o.organization,
509
502
  projects: o.projects,
510
503
  base_url: o.baseUrl,
@@ -513,21 +506,29 @@ export const sentry = {
513
506
  }),
514
507
  webhook: (o) => providerWebhook("sentry", o),
515
508
  };
516
- /** GitHub: the connection's webhooks (a GitHub App's), with an optional backfill of history. */
509
+ /** GitHub: the connection's webhooks (a GitHub App's). */
517
510
  export const github = {
518
- webhook: (o) => providerWebhook("github", o, {
519
- backfill: o.backfill && {
520
- provider: "github",
521
- repositories: o.backfill.repositories,
522
- start: o.backfill.start,
523
- base_url: o.backfill.baseUrl,
524
- page_size: o.backfill.pageSize,
525
- },
526
- }),
511
+ /**
512
+ * One stream per entity (ducktail's `github` sync pipeline): the connection's webhooks for
513
+ * the repositories, after a backfill of their recent pull requests, reviews, check runs and
514
+ * releases on the first run (default 30 days). Each row's `_key` is the entity
515
+ * (`{repository, number}` for pull requests, else `{id}`) and `_source_ts` its own time; the
516
+ * payload is the webhook body. Never reconciles: GitHub's webhooks are complete.
517
+ */
518
+ sync: (o) => new Pipeline("github", o.connection, o.streams ?? [], {
519
+ repositories: o.repositories,
520
+ webhook: {},
521
+ backfill: o.backfill,
522
+ base_url: o.baseUrl,
523
+ page_size: o.pageSize,
524
+ request_timeout: o.requestTimeout,
525
+ }, callSite()),
526
+ /** The connection's webhooks as raw event streams, routed by `X-GitHub-Event`. */
527
+ webhook: (o) => providerWebhook("github", o),
527
528
  };
528
529
  /** AWS: ECS and ELBv2 discovery, CloudWatch metrics and alarms, through an `aws` connection. */
529
530
  export const cloudwatch = {
530
- poll: (o) => poll("cloudwatch", o.slot, o, {
531
+ poll: (o) => poll("cloudwatch", o.connection, o, {
531
532
  region: o.region,
532
533
  discovery_interval: o.discoveryInterval,
533
534
  period: o.period,
@@ -542,7 +543,7 @@ export const cloudwatch = {
542
543
  /** Another polled kind (Plaid, QuickBooks, Xero, Gmail, Google Calendar and Contacts, Slack):
543
544
  * `options` are ducktail's keys for it (README, "Polled sources"). */
544
545
  export function polled(kind, o) {
545
- return poll(kind, o.slot, o, o.options ?? {});
546
+ return poll(kind, o.connection, o, o.options ?? {});
546
547
  }
547
548
  /** ducktail's raw stream of a Postgres table or a Kafka topic. */
548
549
  const streamName = (name) => name.replace(/[^A-Za-z0-9]/g, "_").toLowerCase();
@@ -627,6 +628,26 @@ export function prop(ref) {
627
628
  }
628
629
  /** Every `prop()` schema, to find tags the output's JSON Schema loses (transforms, ...). */
629
630
  const propSchemas = new WeakMap();
631
+ /** The most rows a list view's window holds. */
632
+ export const LIST_MAX = 1000;
633
+ /** What a list view's subscriber sends: its query, how many rows from the top it shows, and
634
+ * `resume` (the last update's), when widening a window it already has or reconnecting. */
635
+ export const listInput = (query) => z.object({ query, limit: z.number().int().min(1).max(LIST_MAX), resume: z.string().max(256).default("") });
636
+ const listUpdateShape = (row) => ({
637
+ /** Drop the rows held: this update holds the whole window (the first, unless resumed). */
638
+ reset: z.boolean(),
639
+ /** Rows that entered or changed, each at its index in the new window. */
640
+ upserts: z.array(z.object({ key: z.string(), index: z.number().int(), row })),
641
+ /** Keys of rows that left the window. */
642
+ removes: z.array(z.string()),
643
+ /** Rows exist past the window. */
644
+ more: z.boolean(),
645
+ /** Pass back as `resume` to widen this window without starting over. */
646
+ resume: z.string(),
647
+ });
648
+ /** A list view's update: what changed in the window since the last one (see `realtime`).
649
+ * `summary` is present on a reset and when it changed. */
650
+ export const listUpdate = (row, summary) => z.object({ ...listUpdateShape(row), ...(summary ? { summary: summary.optional() } : {}) });
630
651
  function refIr(r) {
631
652
  if ("kind" in r && r.kind === "prop")
632
653
  return { object: r.object, property: r.property };
@@ -731,6 +752,13 @@ spec) {
731
752
  export function realtime(name,
732
753
  // deno-lint-ignore no-explicit-any
733
754
  spec) {
755
+ if (spec.rows) {
756
+ const input = listInput(spec.input);
757
+ const output = listUpdate(spec.row, spec.summary?.output);
758
+ const ir = handlerIr(name, "read", null, { ...spec, input, output, watch: spec.watch ?? [] });
759
+ const list = { key: spec.key, row: spec.row, order: spec.order, rows: spec.rows, summary: spec.summary };
760
+ return { kind: "realtime", name, ir, input, output, list, handler: () => { throw new Error(`${name} is a list view`); } };
761
+ }
734
762
  const ir = handlerIr(name, spec.view ? "txRead" : "read", spec.view ?? null, { ...spec, watch: spec.watch ?? [] });
735
763
  return { kind: "realtime", name, ir, input: spec.input, output: spec.output, handler: spec.handler };
736
764
  }
@@ -789,6 +817,13 @@ export const openSpace = { kind: "cedar", text: 'Action::"OpenSpace"' };
789
817
  export function space(id) {
790
818
  return { kind: "cedar", text: `Space::${JSON.stringify(id)}` };
791
819
  }
820
+ /** Who may chat with a registry agent from a space (`<AgentChat>` in `@trytilde/spaces`), in which
821
+ * registry thread (`context.thread`): `permit(principal, action == ${chatWithAgent}, resource == ${agent(id)}) when { ... };`. */
822
+ export const chatWithAgent = { kind: "cedar", text: 'Action::"ChatWithAgent"' };
823
+ /** A Tilde registry agent by its id, a Cedar resource. */
824
+ export function agent(id) {
825
+ return { kind: "cedar", text: `Agent::${JSON.stringify(id)}` };
826
+ }
792
827
  /** A group: the token's subject is in each group its `groups` attribute lists (comma-separated). */
793
828
  export function group(name) {
794
829
  return { kind: "cedar", text: `Group::${JSON.stringify(name)}` };
@@ -799,6 +834,8 @@ export function policy(id, text) {
799
834
  }
800
835
  /** The default export of `<root>/ontology.ts`. */
801
836
  export function ontology(spec) {
837
+ for (const [name, connection] of Object.entries(spec.connections ?? {}))
838
+ connectionNames.set(connection, name);
802
839
  return {
803
840
  kind: "ontology",
804
841
  models: [],
@@ -812,9 +849,8 @@ export function ontology(spec) {
812
849
  env: {},
813
850
  policies: [],
814
851
  auths: [],
815
- connections: [],
852
+ connections: {},
816
853
  streams: [],
817
- slots: {},
818
854
  secrets: {},
819
855
  pipelines: [],
820
856
  storage: "cell",
@@ -934,7 +970,7 @@ function pipelineIR(p) {
934
970
  return {
935
971
  name: p.name,
936
972
  kind: p.pipeline.type,
937
- slot: p.pipeline.slot?.name ?? null,
973
+ connection: p.pipeline.connection ? authName(p.pipeline.connection) : null,
938
974
  streams: [...p.pipeline.streams],
939
975
  secrets: [...secrets].sort(),
940
976
  options,
@@ -1063,7 +1099,7 @@ export function toIR(o, root, readFile) {
1063
1099
  env: Object.entries(o.env).map(([name, e]) => ({ name, kind: e.kind, default: e.default })),
1064
1100
  policies: o.policies.map((p) => ({ id: p.id, text: p.text, loc: p.loc })),
1065
1101
  auths: o.auths.map((a) => ({ name: a.name, loc: a.loc })),
1066
- connections: [...o.connections, ...Object.values(o.slots)].map((c) => ({ name: c.name, provider: c.provider, type: c.type, loc: c.loc })),
1102
+ connections: Object.entries(o.connections).map(([name, c]) => ({ name, provider: c.provider, type: c.type ?? null, ...(c.optional ? { optional: true } : {}), loc: null })),
1067
1103
  // Only when declared, so the IR of a project without them is unchanged.
1068
1104
  ...(Object.keys(o.secrets).length ? { secrets: Object.values(o.secrets).map((x) => ({ name: x.name, loc: x.loc })) } : {}),
1069
1105
  ...(o.pipelines.length ? { pipelines: o.pipelines.map(pipelineIR) } : {}),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trytilde/ontology",
3
- "version": "3.1.1",
3
+ "version": "4.0.0",
4
4
  "description": "Tilde Cloud ontologies in TypeScript: the definitions and the client build tilde deploy runs",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -22,7 +22,7 @@
22
22
  "runtime": 1
23
23
  },
24
24
  "scripts": {
25
- "build": "tsc -p tsconfig.json"
25
+ "build": "tsc -p tsconfig.json && node dts-extensions.mjs"
26
26
  },
27
27
  "peerDependencies": {
28
28
  "zod": "^4.1.0"