@kennra/app-sdk 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kennra AS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @kennra/app-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build apps for [Kennra](https://kennra.com), the headless customer memory. An app connects a
4
+ source system to Kennra through the public API: it answers live lookups, polls on a schedule,
5
+ reacts to webhooks and writes facts with stable idempotency keys.
6
+
7
+ The SDK uses web-standard `Request` and `Response`, so an app runs on Node, Bun, Deno, serverless
8
+ functions and edge runtimes.
9
+
10
+ ```sh
11
+ npm install @kennra/app-sdk
12
+ ```
13
+
14
+ ## What it gives you
15
+
16
+ - **Manifest:** types and a validator for `kennra-app.yaml` (`@kennra/app-sdk/manifest`).
17
+ - **Request verification:** checks the signature and timestamp of every call Kennra sends to your
18
+ app (`@kennra/app-sdk/signature`).
19
+ - **Client:** installation tokens, persisted GraphQL operations and batched ingest with retries.
20
+ - **Handlers:** `createApp({ manifest, kennra })` with `.lookup()`, `.schedule()`, `.on()` and
21
+ lifecycle hooks, returned as one `fetch` handler.
22
+ - **Testing:** `FakeKennra`, recorded HTTP fixtures and the conformance checks a listed app must
23
+ pass (`@kennra/app-sdk/testing`).
24
+
25
+ ## Example
26
+
27
+ ```ts
28
+ import { createApp } from '@kennra/app-sdk';
29
+ import manifest from './kennra-app.json';
30
+
31
+ const app = createApp({
32
+ manifest,
33
+ kennra: {
34
+ baseUrl: 'https://api.kennra.com',
35
+ clientId: process.env.KENNRA_CLIENT_ID!,
36
+ clientSecret: process.env.KENNRA_CLIENT_SECRET!,
37
+ },
38
+ }).lookup('order.details', async ({ ref }) => {
39
+ const order = await fetchOrder(ref);
40
+ return order ? { data: order } : { notFound: true };
41
+ });
42
+
43
+ export default { fetch: app.fetch };
44
+ ```
45
+
46
+ The guide and the manifest reference are at [kennra.com/docs/apps](https://kennra.com/docs/apps).
47
+
48
+ ## License
49
+
50
+ MIT. See `LICENSE`. The SDK is open source; Kennra itself is proprietary.
package/dist/app.d.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { type InstallationClient, KennraAppClient, type KennraClientOptions } from './client.js';
2
+ import { type AppManifest } from './manifest.js';
3
+ import type { ConnectionTestRequest, ConnectionTestResult, DisconnectRequest, ErasureReceipt, ErasureRequest, InstallationInfo, LifecycleEvent, LookupRequest, ProgramTargetDelta, ProgramTargetReceipt, ScheduleTick, SegmentSyncDelta, SegmentSyncReceipt, SyncRunReport, SyncRunStatus, WebhookEvent } from './protocol.js';
4
+ /**
5
+ * What a handler gets: the installation, its settings and secrets, its state, a Kennra client and
6
+ * an abort signal. Long loops check `signal.aborted` between pages, save their cursor and return:
7
+ * it fires when the app stops (`app.stop()`, the host's SIGTERM) and, in a schedule handler, when
8
+ * the run reaches its maximum duration or Kennra abandoned it.
9
+ */
10
+ export interface AppContext {
11
+ installationId: string;
12
+ workspace: string;
13
+ config: Record<string, unknown>;
14
+ secrets: Record<string, string>;
15
+ state: InstallationClient['state'];
16
+ kennra: InstallationClient;
17
+ signal: AbortSignal;
18
+ }
19
+ /**
20
+ * Why a run's signal fired (`signal.reason`): `max_duration` (the schedule's `maxRunSeconds`),
21
+ * `shutdown` (the app stops) or `abandoned` (Kennra gave the run up: its lease ran out).
22
+ */
23
+ export type RunStopReason = 'max_duration' | 'shutdown' | 'abandoned';
24
+ /**
25
+ * The status for work whose signal fired (`partial` at its deadline, `interrupted` on shutdown),
26
+ * or null while it may go on. For an app's own runs outside a tick (reportRun with its own id).
27
+ */
28
+ export declare function stoppedStatus(signal: AbortSignal): SyncRunStatus | null;
29
+ /** A schedule run in a handler: its lease and signal. */
30
+ export interface RunHandle {
31
+ runId: string;
32
+ scheduleId: string;
33
+ startedAt: Date;
34
+ /** When the run's signal fires at the latest (its maximum duration). */
35
+ deadline: Date;
36
+ /** The same signal as `ctx.signal`. */
37
+ signal: AbortSignal;
38
+ /** Why the signal fired, or null while the run may go on. */
39
+ readonly stopReason: RunStopReason | null;
40
+ /**
41
+ * Extends the run's lease in Kennra and records its progress so far (shown on the Apps page).
42
+ * The SDK also sends one every minute while the handler runs; calls closer than 5 seconds apart
43
+ * only keep the progress for the next one.
44
+ */
45
+ heartbeat(progress?: Record<string, number>): Promise<void>;
46
+ }
47
+ /** A run in progress in this process (the host's `/healthz`). */
48
+ export interface RunningJob {
49
+ runId: string;
50
+ scheduleId: string;
51
+ installationId: string;
52
+ startedAt: string;
53
+ lastHeartbeatAt: string | null;
54
+ deadline: string;
55
+ progress: Record<string, number> | null;
56
+ stopping: RunStopReason | null;
57
+ }
58
+ export type LookupResult<T> = {
59
+ data: T;
60
+ } | {
61
+ notFound: true;
62
+ } | {
63
+ noAccess: true;
64
+ };
65
+ export type LookupHandler = (a: {
66
+ req: LookupRequest;
67
+ ref: string;
68
+ ctx: AppContext;
69
+ }) => Promise<LookupResult<unknown>>;
70
+ export type ScheduleHandler = (a: {
71
+ tick: ScheduleTick;
72
+ lane: ScheduleTick['lane'];
73
+ ctx: AppContext;
74
+ run: RunHandle;
75
+ }) => Promise<Omit<SyncRunReport, 'runId' | 'scheduleId' | 'status'> & {
76
+ status?: SyncRunStatus;
77
+ }>;
78
+ export type SegmentSyncHandler = (a: {
79
+ delta: SegmentSyncDelta;
80
+ ctx: AppContext;
81
+ }) => Promise<Omit<SegmentSyncReceipt, 'deliveryId'>>;
82
+ export type ProgramTargetHandler = (a: {
83
+ delta: ProgramTargetDelta;
84
+ ctx: AppContext;
85
+ }) => Promise<Omit<ProgramTargetReceipt, 'deliveryId'>>;
86
+ export type EventHandler = (a: {
87
+ event: WebhookEvent;
88
+ ctx: AppContext;
89
+ }) => Promise<void>;
90
+ export type DisconnectHandler = (a: {
91
+ req: DisconnectRequest;
92
+ ctx: AppContext;
93
+ }) => Promise<void>;
94
+ export type LifecycleHandler = (a: {
95
+ event: LifecycleEvent;
96
+ ctx: AppContext | null;
97
+ }) => Promise<void>;
98
+ export type ErasureHandler = (a: {
99
+ request: ErasureRequest;
100
+ ctx: AppContext | null;
101
+ }) => Promise<ErasureReceipt>;
102
+ export type ConnectionTestHandler = (a: {
103
+ request: ConnectionTestRequest;
104
+ ctx: AppContext;
105
+ }) => Promise<ConnectionTestResult>;
106
+ export type RouteHandler = (req: Request, a: {
107
+ client: KennraAppClient;
108
+ manifest: AppManifest;
109
+ }) => Promise<Response>;
110
+ export interface CreateAppOptions {
111
+ /** The manifest: an object or YAML text, validated here (invalid manifests throw). */
112
+ manifest: unknown;
113
+ kennra: KennraClientOptions;
114
+ /** Run schedule handlers after answering the tick (default true), so ticks never time out. */
115
+ background?: boolean;
116
+ /** Timestamp tolerance for signatures in seconds (default 300). */
117
+ toleranceSeconds?: number;
118
+ /** How often a running schedule handler's lease is extended (default 60 s). */
119
+ heartbeatMs?: number;
120
+ }
121
+ /**
122
+ * A Kennra app as one web-standard `fetch` handler (Node, Bun, Deno, edge). Routes come from the
123
+ * manifest (lookup, schedule, webhook, lifecycle and health URLs); every request from Kennra is
124
+ * verified (Standard Webhooks) with the installation's signing secret before a handler runs.
125
+ *
126
+ * ```ts
127
+ * export default createApp({ manifest, kennra: { baseUrl, clientId, clientSecret } })
128
+ * .lookup('order.details', async ({ ref, ctx }) => ({ data: await load(ref, ctx.secrets) }))
129
+ * .schedule('poll', async ({ ctx }) => ({ counters: { orders: 3 } }));
130
+ * ```
131
+ */
132
+ export declare class KennraApp {
133
+ private readonly opts;
134
+ readonly manifest: AppManifest;
135
+ readonly client: KennraAppClient;
136
+ private readonly lookups;
137
+ private readonly schedules;
138
+ private readonly events;
139
+ private readonly routes;
140
+ private readonly disconnects;
141
+ private lifecycleHandler;
142
+ private erasureHandler;
143
+ private segmentSyncHandler;
144
+ private programTargetHandler;
145
+ private connectionTestHandler;
146
+ /** Background work started by ticks (tests await it). */
147
+ readonly pending: Set<Promise<unknown>>;
148
+ /** Fires when the app stops (`stop()`): every handler's `ctx.signal` follows it. */
149
+ private readonly lifetime;
150
+ private readonly active;
151
+ constructor(opts: CreateAppOptions);
152
+ lookup(object: string, handler: LookupHandler): this;
153
+ schedule(id: string, handler: ScheduleHandler): this;
154
+ on(eventType: string, handler: EventHandler): this;
155
+ /** An employee disconnected in Kennra (`userConnections[].disconnectUrl`): revoke and delete the token. */
156
+ onDisconnect(kind: string, handler: DisconnectHandler): this;
157
+ onLifecycle(handler: LifecycleHandler): this;
158
+ /** Erasure of a person (manifest `capabilities.privacy.erasure: receipt`): answer with a receipt. */
159
+ onErasure(handler: ErasureHandler): this;
160
+ /** Segment membership deltas (`capabilities.segmentSync`): apply them idempotently and answer with a receipt. */
161
+ segmentSync(handler: SegmentSyncHandler): this;
162
+ /** "Test connection" on the settings form (`capabilities.connectionTest`): try the typed settings. */
163
+ onConnectionTest(handler: ConnectionTestHandler): this;
164
+ /** Program enrollment deltas (`capabilities.programTargets`): apply them idempotently and answer with a receipt. */
165
+ programTarget(handler: ProgramTargetHandler): this;
166
+ /** An extra route the app serves itself (e.g. an OAuth callback). Not signed by Kennra. */
167
+ route(method: string, path: string, handler: RouteHandler): this;
168
+ /** The context for an installation (settings and secrets from the installation store). */
169
+ context(installationId: string, info?: InstallationInfo): Promise<AppContext>;
170
+ /** Fires when the app stops: for the app's own background work (a sync started by a connect). */
171
+ get signal(): AbortSignal;
172
+ /** True once `stop()` was called: new schedule ticks are refused (503). */
173
+ get stopping(): boolean;
174
+ /**
175
+ * Stops the app (graceful shutdown): new ticks get 503, and every handler's signal fires, so
176
+ * running work saves its cursor and reports `interrupted`. Await `idle()` after it.
177
+ */
178
+ stop(reason?: RunStopReason): void;
179
+ /** The schedule runs in progress in this process, with their last heartbeat and progress. */
180
+ runs(): RunningJob[];
181
+ /** Runs one schedule tick: a lease kept alive by heartbeats, a deadline, a signal and the report. */
182
+ private runTick;
183
+ /** Verifies a request from Kennra and returns the body and the installation's context. */
184
+ private verified;
185
+ /** The fetch handler. */
186
+ fetch: (req: Request) => Promise<Response>;
187
+ /** Waits for background schedule work (tests). */
188
+ idle(): Promise<void>;
189
+ }
190
+ export declare function createApp(opts: CreateAppOptions): KennraApp;