@ziffr/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 +21 -0
- package/README.md +50 -2
- package/dist/index.d.ts +363 -0
- package/dist/index.js +183 -0
- package/package.json +42 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Stefan Sonntag
|
|
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,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ziffr/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Call the [Ziffr](https://github.com/ziffr/ziffr) API from TypeScript or JavaScript: read the Metrics an Access Key may see and their values, and submit values. MIT licensed, no dependencies, Node 20 or later (or any runtime with `fetch`).
|
|
4
|
+
|
|
5
|
+
## A first call
|
|
6
|
+
|
|
7
|
+
1. In Ziffr, open the Team page and create an Access Key. Give it "Read metrics", and "Submit values" if your program records values. Copy the key: it is shown once.
|
|
8
|
+
2. Install and call:
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @ziffr/sdk
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { Ziffr } from "@ziffr/sdk";
|
|
16
|
+
|
|
17
|
+
const ziffr = new Ziffr({ url: "https://ziffr.example.com", accessKey: process.env.ZIFFR_ACCESS_KEY! });
|
|
18
|
+
|
|
19
|
+
for await (const metric of ziffr.metrics.all()) console.log(metric.slug, metric.name);
|
|
20
|
+
|
|
21
|
+
const { items } = await ziffr.observations.list("revenue", { from: "2026-01-01", to: "2026-03-01" });
|
|
22
|
+
console.log(items.map((o) => `${o.period}: ${o.value}`));
|
|
23
|
+
|
|
24
|
+
const result = await ziffr.observations.submit("orders", { value: 42 });
|
|
25
|
+
console.log(result.status); // "recorded", or "awaiting_approval" for an unusual value
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## What it does for you
|
|
29
|
+
|
|
30
|
+
- **Pages for you.** Every list has `list({ limit, cursor })` for one page and `all()` to iterate over every item.
|
|
31
|
+
- **Waits out limits.** On a 429 it waits as long as the server's `Retry-After` says and tries again, up to `maxRetries` (default 3) and `maxRetryWait` seconds (default 60). A longer wait, such as the daily limit on values, throws at once.
|
|
32
|
+
- **Never makes a Metric twice.** `metrics.create` sends a fresh idempotency key too; it needs a key with "Create metrics", and the Metric belongs to the key's creator.
|
|
33
|
+
- **Never records a value twice.** Each `submit` sends a fresh idempotency key, so its own retries are safe. To make retries across runs of your program safe too, pass your own: `submit("orders", { value: 42 }, { idempotencyKey: "orders-2026-11" })`. A repeat with the same key and value gets the first answer back, with `replayed: true`.
|
|
34
|
+
- **One kind of error.** Every failure is a `ZiffrError` with the HTTP `status` and the API's stable `code` (`not_found`, `forbidden`, `locked`, `rate_limited`, and so on; `network` when Ziffr could not be reached).
|
|
35
|
+
|
|
36
|
+
A key sees exactly what the person who made it sees, no more. A Metric it may not see is `not_found`, the same as one that does not exist.
|
|
37
|
+
|
|
38
|
+
## Calls
|
|
39
|
+
|
|
40
|
+
| Call | API |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `metrics.list(options)`, `metrics.all()` | `GET /api/v1/metrics` |
|
|
43
|
+
| `metrics.get(slug)` | `GET /api/v1/metrics/{slug}` |
|
|
44
|
+
| `metrics.create({ name, period, unit, submit, ... }, { idempotencyKey })` | `POST /api/v1/metrics` |
|
|
45
|
+
| `observations.list(slug, { from, to, limit, cursor })`, `observations.all(slug, { from, to })` | `GET /api/v1/metrics/{slug}/observations` |
|
|
46
|
+
| `observations.submit(slug, { value, period, breakdown }, { idempotencyKey })` | `POST /api/v1/metrics/{slug}/observations` |
|
|
47
|
+
| `workspace()` | `GET /api/v1/workspace`: the month the fiscal year starts in, where quarters and years begin |
|
|
48
|
+
| `people.list(options)`, `people.all()` | `GET /api/v1/people` |
|
|
49
|
+
| `groups.list(options)`, `groups.all()` | `GET /api/v1/groups` |
|
|
50
|
+
|
|
51
|
+
Fields, limits and errors of each are in the [API reference](https://github.com/ziffr/ziffr/blob/next/docs/reference/api.md).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/** How often a Metric has a value: a day, an ISO week, a month, or a quarter or year of the workspace's fiscal year. */
|
|
2
|
+
export type Period = "day" | "week" | "month" | "quarter" | "year";
|
|
3
|
+
/** A Metric's description, as `GET /metrics/{slug}` answers it. */
|
|
4
|
+
export type Metric = {
|
|
5
|
+
slug: string;
|
|
6
|
+
name: string;
|
|
7
|
+
description: string;
|
|
8
|
+
period: Period;
|
|
9
|
+
format: "number" | "currency" | "percent";
|
|
10
|
+
unit: string;
|
|
11
|
+
decimals: number;
|
|
12
|
+
polarity: "higher" | "lower" | "target";
|
|
13
|
+
aggregation: "sum" | "average" | "last" | "none";
|
|
14
|
+
target_min: number | null;
|
|
15
|
+
target_max: number | null;
|
|
16
|
+
/** A Derived Metric: computed from others, takes no values. */
|
|
17
|
+
derived: boolean;
|
|
18
|
+
};
|
|
19
|
+
/** One labelled part of a value (GLOSSARY: Breakdown). */
|
|
20
|
+
export type BreakdownRow = {
|
|
21
|
+
label: string;
|
|
22
|
+
value: number;
|
|
23
|
+
};
|
|
24
|
+
/** A Metric's value for one period. */
|
|
25
|
+
export type Observation = {
|
|
26
|
+
/** The period's first day, YYYY-MM-DD. */
|
|
27
|
+
period: string;
|
|
28
|
+
value: number;
|
|
29
|
+
state: "recorded" | "awaiting_approval" | "locked";
|
|
30
|
+
/** The submitter's person id (see `people`), or null. */
|
|
31
|
+
submitter: string | null;
|
|
32
|
+
breakdown: BreakdownRow[] | null;
|
|
33
|
+
};
|
|
34
|
+
/** A person or Contact: id and name only. */
|
|
35
|
+
export type Person = {
|
|
36
|
+
id: string;
|
|
37
|
+
name: string;
|
|
38
|
+
contact: boolean;
|
|
39
|
+
};
|
|
40
|
+
/** A Group: id and name. */
|
|
41
|
+
export type Group = {
|
|
42
|
+
id: number;
|
|
43
|
+
name: string;
|
|
44
|
+
everyone: boolean;
|
|
45
|
+
};
|
|
46
|
+
/** One page of a list; pass `next` as `cursor` for the following page (null on the last). */
|
|
47
|
+
export type Page<T> = {
|
|
48
|
+
items: T[];
|
|
49
|
+
next: string | null;
|
|
50
|
+
};
|
|
51
|
+
/** What creating a Metric sends (scope metrics:write): a name, and as much of its description as you want to set;
|
|
52
|
+
* `submit` makes the key's creator its Submitter. */
|
|
53
|
+
export type NewMetric = {
|
|
54
|
+
name: string;
|
|
55
|
+
description?: string;
|
|
56
|
+
unit?: string;
|
|
57
|
+
format?: Metric["format"];
|
|
58
|
+
decimals?: number;
|
|
59
|
+
period?: Metric["period"];
|
|
60
|
+
submission_rule?: "reject" | "overwrite" | "add" | "keep_both";
|
|
61
|
+
polarity?: Metric["polarity"];
|
|
62
|
+
aggregation?: Metric["aggregation"];
|
|
63
|
+
target_min?: number | null;
|
|
64
|
+
target_max?: number | null;
|
|
65
|
+
submit?: boolean;
|
|
66
|
+
};
|
|
67
|
+
/** What a submission sends. */
|
|
68
|
+
export type SubmitValue = {
|
|
69
|
+
value: number;
|
|
70
|
+
period?: string;
|
|
71
|
+
breakdown?: BreakdownRow[];
|
|
72
|
+
};
|
|
73
|
+
/** What became of a value that was taken. */
|
|
74
|
+
export type Submission = {
|
|
75
|
+
status: "recorded" | "awaiting_approval";
|
|
76
|
+
period: string;
|
|
77
|
+
value: number;
|
|
78
|
+
detail: string;
|
|
79
|
+
replayed: boolean;
|
|
80
|
+
};
|
|
81
|
+
/** A Metric as its Feed sees it (spec 0012): what to fetch and which periods already have a value, never a value. */
|
|
82
|
+
export type FeedMetric = {
|
|
83
|
+
slug: string;
|
|
84
|
+
name: string;
|
|
85
|
+
period: Period;
|
|
86
|
+
unit: string;
|
|
87
|
+
format: "number" | "currency" | "percent";
|
|
88
|
+
decimals: number;
|
|
89
|
+
/** The current period's first day as Ziffr counts it. */
|
|
90
|
+
current: string;
|
|
91
|
+
/** Working days after a period ends by which its value is due, if its Workflow sets one. */
|
|
92
|
+
due_working_days: number | null;
|
|
93
|
+
/** First days of the periods that already have a value, oldest first. */
|
|
94
|
+
filled: string[];
|
|
95
|
+
};
|
|
96
|
+
/** The Feed a Feed Key acts for, the month the workspace's year starts in, and its Metrics. */
|
|
97
|
+
export type FeedOverview = {
|
|
98
|
+
name: string;
|
|
99
|
+
year_start_month: number;
|
|
100
|
+
metrics: Page<FeedMetric>;
|
|
101
|
+
};
|
|
102
|
+
/** What GET /workspace answers: the month the workspace's fiscal year starts in, 1 (January) to 12. */
|
|
103
|
+
export type Workspace = {
|
|
104
|
+
year_start_month: number;
|
|
105
|
+
};
|
|
106
|
+
/** One value in a Feed's batch; `period` is the period's first day, the current period if left out. */
|
|
107
|
+
export type FeedItem = {
|
|
108
|
+
metric: string;
|
|
109
|
+
period?: string;
|
|
110
|
+
value: number;
|
|
111
|
+
breakdown?: BreakdownRow[];
|
|
112
|
+
};
|
|
113
|
+
/** What became of one item of a batch. `imported` marks an Import: a past period that had no value, recorded
|
|
114
|
+
* without the Unusual Value check. `code` says why an item was refused. */
|
|
115
|
+
export type FeedItemResult = {
|
|
116
|
+
metric: string;
|
|
117
|
+
period: string | null;
|
|
118
|
+
status: "recorded" | "awaiting_approval" | "locked" | "refused";
|
|
119
|
+
imported?: boolean;
|
|
120
|
+
code?: string;
|
|
121
|
+
detail: string;
|
|
122
|
+
};
|
|
123
|
+
/** At most this many items in one batch. */
|
|
124
|
+
export declare const FEED_BATCH_MAX = 500;
|
|
125
|
+
/** A dashboard in a list (spec 0014): the key's creator's role on it and where to open it. */
|
|
126
|
+
export type DashboardSummary = {
|
|
127
|
+
id: number;
|
|
128
|
+
name: string;
|
|
129
|
+
role: "owner" | "editor" | "viewer";
|
|
130
|
+
url: string;
|
|
131
|
+
};
|
|
132
|
+
/** A Finding's words; Placeholders such as {metric} or {change yoy} are filled in when it is drawn. */
|
|
133
|
+
export type FindingWords = {
|
|
134
|
+
kicker?: string;
|
|
135
|
+
headline?: string;
|
|
136
|
+
subline?: string;
|
|
137
|
+
footnote?: string;
|
|
138
|
+
source?: string;
|
|
139
|
+
};
|
|
140
|
+
/** One widget: its view, the slugs of the Metrics it draws and where it sits; a Finding has its words too. */
|
|
141
|
+
export type Widget = {
|
|
142
|
+
id: number;
|
|
143
|
+
view: string;
|
|
144
|
+
title: string | null;
|
|
145
|
+
metrics: string[];
|
|
146
|
+
x: number;
|
|
147
|
+
y: number;
|
|
148
|
+
w: number;
|
|
149
|
+
h: number;
|
|
150
|
+
words?: FindingWords;
|
|
151
|
+
display?: DisplayPeriod;
|
|
152
|
+
};
|
|
153
|
+
/** A dashboard with its introduction and its widgets in reading order. */
|
|
154
|
+
export type Dashboard = DashboardSummary & {
|
|
155
|
+
intro: string;
|
|
156
|
+
widgets: Widget[];
|
|
157
|
+
};
|
|
158
|
+
/** The built-in views a key may place. */
|
|
159
|
+
export type View = "number" | "line" | "bars" | "gauge" | "table" | "forecast" | "correlation" | "matrix" | "drivers" | "ranked" | "share" | "pictogram" | "story-line";
|
|
160
|
+
/** The few widget settings a key may set. */
|
|
161
|
+
export type WidgetSettings = {
|
|
162
|
+
window?: number;
|
|
163
|
+
showTarget?: boolean;
|
|
164
|
+
showForecast?: boolean;
|
|
165
|
+
rows?: number;
|
|
166
|
+
/** Show by: a period longer than the Metric's own, its values combined by its Aggregation; null for its own. */
|
|
167
|
+
display?: DisplayPeriod | null;
|
|
168
|
+
};
|
|
169
|
+
/** A period a widget can show a Metric by (GLOSSARY: Display Period). */
|
|
170
|
+
export type DisplayPeriod = "week" | "month" | "quarter" | "half" | "year";
|
|
171
|
+
/** What adding a widget sends: a view with Metrics, or a team Widget Template with Metric slugs per Slot. */
|
|
172
|
+
export type NewWidget = {
|
|
173
|
+
view?: View;
|
|
174
|
+
metrics: string[];
|
|
175
|
+
title?: string;
|
|
176
|
+
settings?: WidgetSettings;
|
|
177
|
+
} | {
|
|
178
|
+
template: number;
|
|
179
|
+
fills: string[][];
|
|
180
|
+
title?: string;
|
|
181
|
+
};
|
|
182
|
+
/** A template to build with: a built-in view, a team Widget Template or a Dashboard Template, with its Slots. */
|
|
183
|
+
export type Template = {
|
|
184
|
+
id: string | number;
|
|
185
|
+
kind: "view" | "widget" | "dashboard";
|
|
186
|
+
name: string;
|
|
187
|
+
description: string;
|
|
188
|
+
slots: {
|
|
189
|
+
label: string;
|
|
190
|
+
multiple: boolean;
|
|
191
|
+
suggested: string[];
|
|
192
|
+
}[];
|
|
193
|
+
};
|
|
194
|
+
/** Paging options of every list. */
|
|
195
|
+
export type PageOptions = {
|
|
196
|
+
limit?: number;
|
|
197
|
+
cursor?: string;
|
|
198
|
+
};
|
|
199
|
+
/** Options of a Metric's values: the periods from `from` to `to` (first days, YYYY-MM-DD, both included). */
|
|
200
|
+
export type ObservationOptions = PageOptions & {
|
|
201
|
+
from?: string;
|
|
202
|
+
to?: string;
|
|
203
|
+
};
|
|
204
|
+
/** Settings of a client. */
|
|
205
|
+
export type ZiffrOptions = {
|
|
206
|
+
/** Where Ziffr runs, such as https://ziffr.example.com (the API is under /api/v1). */
|
|
207
|
+
url: string;
|
|
208
|
+
/** An Access Key, made in Settings, or a Feed Key, made for a Feed (then use `feed` only). */
|
|
209
|
+
accessKey: string;
|
|
210
|
+
/** How often to retry a 429 before giving up (default 3). */
|
|
211
|
+
maxRetries?: number;
|
|
212
|
+
/** Longest wait for one retry, in seconds (default 60); a longer Retry-After fails at once. */
|
|
213
|
+
maxRetryWait?: number;
|
|
214
|
+
/** A fetch to use instead of the global one. */
|
|
215
|
+
fetch?: typeof fetch;
|
|
216
|
+
};
|
|
217
|
+
/** An error answer of the API, or a failure to reach it (status 0). `code` is stable; handle errors by it. */
|
|
218
|
+
export declare class ZiffrError extends Error {
|
|
219
|
+
/** The HTTP status; 0 when Ziffr could not be reached. */
|
|
220
|
+
readonly status: number;
|
|
221
|
+
/** The API's stable error code. */
|
|
222
|
+
readonly code: string;
|
|
223
|
+
/** Seconds the server asked to wait, for `rate_limited`. */
|
|
224
|
+
readonly retryAfter: number | null;
|
|
225
|
+
constructor(status: number, code: string, message: string, retryAfter?: number | null);
|
|
226
|
+
}
|
|
227
|
+
/** A client for one Ziffr and one Access Key. */
|
|
228
|
+
export declare class Ziffr {
|
|
229
|
+
private readonly base;
|
|
230
|
+
private readonly key;
|
|
231
|
+
private readonly maxRetries;
|
|
232
|
+
private readonly maxRetryWait;
|
|
233
|
+
private readonly fetcher;
|
|
234
|
+
constructor(options: ZiffrOptions);
|
|
235
|
+
/** The Metrics the key's creator sees. */
|
|
236
|
+
readonly metrics: {
|
|
237
|
+
/** One page of Metrics. */
|
|
238
|
+
list: (options?: PageOptions) => Promise<Page<Metric>>;
|
|
239
|
+
/** Every Metric, page by page. */
|
|
240
|
+
all: () => AsyncGenerator<Metric, any, any>;
|
|
241
|
+
/** One Metric's description. */
|
|
242
|
+
get: (slug: string) => Promise<Metric>;
|
|
243
|
+
/** Creates a Metric owned by the key's creator (scope metrics:write). A fresh idempotency key is sent unless one is
|
|
244
|
+
* given; pass your own to make retries across runs of your program safe too. */
|
|
245
|
+
create: (metric: NewMetric, options?: {
|
|
246
|
+
idempotencyKey?: string;
|
|
247
|
+
}) => Promise<Metric & {
|
|
248
|
+
replayed: boolean;
|
|
249
|
+
}>;
|
|
250
|
+
/** Deletes a Metric the key's creator owns (scope metrics:write), repeating its exact name to confirm. Refused
|
|
251
|
+
* (ZiffrError 422) while another Metric's formula, a widget, a deck or a working View Link uses it. */
|
|
252
|
+
delete: (slug: string, confirmName: string) => Promise<{
|
|
253
|
+
deleted: string;
|
|
254
|
+
values: number;
|
|
255
|
+
}>;
|
|
256
|
+
};
|
|
257
|
+
/** A Metric's values. */
|
|
258
|
+
readonly observations: {
|
|
259
|
+
/** One page of a Metric's values, oldest first. */
|
|
260
|
+
list: (slug: string, options?: ObservationOptions) => Promise<Page<Observation>>;
|
|
261
|
+
/** All of a Metric's values in a range, page by page. */
|
|
262
|
+
all: (slug: string, options?: Omit<ObservationOptions, "cursor" | "limit">) => AsyncGenerator<Observation, any, any>;
|
|
263
|
+
/** Submits a value. A fresh idempotency key is sent unless one is given; pass your own to make retries across
|
|
264
|
+
* runs of your program safe too. A locked period, or one a rule refuses, throws a ZiffrError (422). */
|
|
265
|
+
submit: (slug: string, value: SubmitValue, options?: {
|
|
266
|
+
idempotencyKey?: string;
|
|
267
|
+
}) => Promise<Submission>;
|
|
268
|
+
};
|
|
269
|
+
/** The month the workspace's fiscal year starts in (1 is January): where quarterly and yearly Metrics' periods start. */
|
|
270
|
+
workspace: () => Promise<Workspace>;
|
|
271
|
+
/** The workspace's people and Contacts. */
|
|
272
|
+
readonly people: {
|
|
273
|
+
/** One page of people. */
|
|
274
|
+
list: (options?: PageOptions) => Promise<Page<Person>>;
|
|
275
|
+
/** Everyone, page by page. */
|
|
276
|
+
all: () => AsyncGenerator<Person, any, any>;
|
|
277
|
+
};
|
|
278
|
+
/** The workspace's Groups. */
|
|
279
|
+
readonly groups: {
|
|
280
|
+
/** One page of Groups. */
|
|
281
|
+
list: (options?: PageOptions) => Promise<Page<Group>>;
|
|
282
|
+
/** Every Group, page by page. */
|
|
283
|
+
all: () => AsyncGenerator<Group, any, any>;
|
|
284
|
+
};
|
|
285
|
+
/** For a Feed Key (spec 0012): the Feed's Metrics, and recording values for them in batches. */
|
|
286
|
+
readonly feed: {
|
|
287
|
+
/** The Feed's name and one page of its Metrics. */
|
|
288
|
+
get: (options?: PageOptions) => Promise<FeedOverview>;
|
|
289
|
+
/** Every Metric of the Feed, page by page. */
|
|
290
|
+
metrics: () => AsyncGenerator<FeedMetric, any, any>;
|
|
291
|
+
/** Records up to FEED_BATCH_MAX values, with one result per item in order. A fresh idempotency key is sent unless
|
|
292
|
+
* one is given; pass your own (made from the values) to make a repeated run record nothing twice. */
|
|
293
|
+
submit: (items: FeedItem[], options?: {
|
|
294
|
+
idempotencyKey?: string;
|
|
295
|
+
}) => Promise<{
|
|
296
|
+
results: FeedItemResult[];
|
|
297
|
+
replayed: boolean;
|
|
298
|
+
}>;
|
|
299
|
+
};
|
|
300
|
+
/** The dashboards the key's creator sees (scope dashboards:read), and building them as the creator (scope
|
|
301
|
+
* dashboards:write). A key changes only what its creator may change, and never shares or deletes. */
|
|
302
|
+
readonly dashboards: {
|
|
303
|
+
/** One page of dashboards. */
|
|
304
|
+
list: (options?: PageOptions) => Promise<Page<DashboardSummary>>;
|
|
305
|
+
/** Every dashboard, page by page. */
|
|
306
|
+
all: () => AsyncGenerator<DashboardSummary, any, any>;
|
|
307
|
+
/** One dashboard with its introduction and widgets. */
|
|
308
|
+
get: (id: number) => Promise<Dashboard>;
|
|
309
|
+
/** Creates an empty dashboard, with an introduction if given. A fresh idempotency key is sent unless one is given. */
|
|
310
|
+
create: (input: {
|
|
311
|
+
name: string;
|
|
312
|
+
intro?: string;
|
|
313
|
+
}, options?: {
|
|
314
|
+
idempotencyKey?: string;
|
|
315
|
+
}) => Promise<Dashboard & {
|
|
316
|
+
replayed: boolean;
|
|
317
|
+
}>;
|
|
318
|
+
/** Makes a dashboard from a Dashboard Template, with Metric slugs for each Slot in order. */
|
|
319
|
+
fromTemplate: (input: {
|
|
320
|
+
template: string | number;
|
|
321
|
+
name?: string;
|
|
322
|
+
fills: string[][];
|
|
323
|
+
}, options?: {
|
|
324
|
+
idempotencyKey?: string;
|
|
325
|
+
}) => Promise<Dashboard & {
|
|
326
|
+
replayed: boolean;
|
|
327
|
+
}>;
|
|
328
|
+
/** Adds a widget in the first free place. */
|
|
329
|
+
addWidget: (dashboardId: number, widget: NewWidget) => Promise<Widget>;
|
|
330
|
+
/** Changes a widget's view, Metrics, title or settings. */
|
|
331
|
+
updateWidget: (dashboardId: number, widgetId: number, patch: {
|
|
332
|
+
view?: View;
|
|
333
|
+
metrics?: string[];
|
|
334
|
+
title?: string | null;
|
|
335
|
+
settings?: WidgetSettings;
|
|
336
|
+
}) => Promise<Widget>;
|
|
337
|
+
/** Removes a widget or a Finding. */
|
|
338
|
+
removeWidget: (dashboardId: number, widgetId: number) => Promise<{
|
|
339
|
+
removed: number;
|
|
340
|
+
}>;
|
|
341
|
+
/** Changes a dashboard's name or introduction. */
|
|
342
|
+
update: (dashboardId: number, patch: {
|
|
343
|
+
name?: string;
|
|
344
|
+
intro?: string;
|
|
345
|
+
}) => Promise<Dashboard>;
|
|
346
|
+
/** Adds a Finding about one Metric below everything on the dashboard, full width. */
|
|
347
|
+
addFinding: (dashboardId: number, finding: FindingWords & {
|
|
348
|
+
metric: string;
|
|
349
|
+
}) => Promise<Widget>;
|
|
350
|
+
/** Changes a Finding's words. */
|
|
351
|
+
updateFinding: (dashboardId: number, findingId: number, words: FindingWords) => Promise<Widget>;
|
|
352
|
+
};
|
|
353
|
+
/** What a key can build with (scope dashboards:read). */
|
|
354
|
+
readonly templates: {
|
|
355
|
+
/** The built-in views, the team's Widget Templates and the Dashboard Templates, or one kind of them. */
|
|
356
|
+
all: (options?: {
|
|
357
|
+
kind?: Template["kind"];
|
|
358
|
+
}) => Promise<Template[]>;
|
|
359
|
+
};
|
|
360
|
+
private get;
|
|
361
|
+
private every;
|
|
362
|
+
private request;
|
|
363
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// @ziffr/sdk (spec 0002, ticket #51; GLOSSARY: Access Key, Metric, Observation): typed calls to the Ziffr API. It
|
|
2
|
+
// knows only HTTP and the API's published shapes, nothing of the server. Safe by default: it waits out a 429 as the
|
|
3
|
+
// server's Retry-After says, and every submission carries an idempotency key, so a retry never records a value twice.
|
|
4
|
+
/** At most this many items in one batch. */
|
|
5
|
+
export const FEED_BATCH_MAX = 500;
|
|
6
|
+
/** An error answer of the API, or a failure to reach it (status 0). `code` is stable; handle errors by it. */
|
|
7
|
+
export class ZiffrError extends Error {
|
|
8
|
+
/** The HTTP status; 0 when Ziffr could not be reached. */
|
|
9
|
+
status;
|
|
10
|
+
/** The API's stable error code. */
|
|
11
|
+
code;
|
|
12
|
+
/** Seconds the server asked to wait, for `rate_limited`. */
|
|
13
|
+
retryAfter;
|
|
14
|
+
// Plain fields, not parameter properties, so Node can run this file with its built-in type stripping.
|
|
15
|
+
constructor(status, code, message, retryAfter = null) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ZiffrError";
|
|
18
|
+
this.status = status;
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.retryAfter = retryAfter;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
24
|
+
const newIdempotencyKey = () => globalThis.crypto.randomUUID();
|
|
25
|
+
/** A client for one Ziffr and one Access Key. */
|
|
26
|
+
export class Ziffr {
|
|
27
|
+
base;
|
|
28
|
+
key;
|
|
29
|
+
maxRetries;
|
|
30
|
+
maxRetryWait;
|
|
31
|
+
fetcher;
|
|
32
|
+
constructor(options) {
|
|
33
|
+
if (!options?.url)
|
|
34
|
+
throw new Error("Ziffr needs the url where it runs.");
|
|
35
|
+
if (!options.accessKey)
|
|
36
|
+
throw new Error("Ziffr needs an Access Key.");
|
|
37
|
+
this.base = `${options.url.replace(/\/+$/, "")}/api/v1`;
|
|
38
|
+
this.key = options.accessKey;
|
|
39
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
40
|
+
this.maxRetryWait = options.maxRetryWait ?? 60;
|
|
41
|
+
this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
42
|
+
}
|
|
43
|
+
/** The Metrics the key's creator sees. */
|
|
44
|
+
metrics = {
|
|
45
|
+
/** One page of Metrics. */
|
|
46
|
+
list: (options = {}) => this.get("/metrics", options),
|
|
47
|
+
/** Every Metric, page by page. */
|
|
48
|
+
all: () => this.every((cursor) => this.metrics.list({ cursor, limit: 100 })),
|
|
49
|
+
/** One Metric's description. */
|
|
50
|
+
get: (slug) => this.get(`/metrics/${encodeURIComponent(slug)}`),
|
|
51
|
+
/** Creates a Metric owned by the key's creator (scope metrics:write). A fresh idempotency key is sent unless one is
|
|
52
|
+
* given; pass your own to make retries across runs of your program safe too. */
|
|
53
|
+
create: async (metric, options = {}) => {
|
|
54
|
+
const { body, headers } = await this.request("POST", "/metrics", undefined, metric, options.idempotencyKey ?? newIdempotencyKey());
|
|
55
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
56
|
+
},
|
|
57
|
+
/** Deletes a Metric the key's creator owns (scope metrics:write), repeating its exact name to confirm. Refused
|
|
58
|
+
* (ZiffrError 422) while another Metric's formula, a widget, a deck or a working View Link uses it. */
|
|
59
|
+
delete: async (slug, confirmName) => (await this.request("DELETE", `/metrics/${encodeURIComponent(slug)}`, { confirm: confirmName })).body,
|
|
60
|
+
};
|
|
61
|
+
/** A Metric's values. */
|
|
62
|
+
observations = {
|
|
63
|
+
/** One page of a Metric's values, oldest first. */
|
|
64
|
+
list: (slug, options = {}) => this.get(`/metrics/${encodeURIComponent(slug)}/observations`, options),
|
|
65
|
+
/** All of a Metric's values in a range, page by page. */
|
|
66
|
+
all: (slug, options = {}) => this.every((cursor) => this.observations.list(slug, { ...options, cursor, limit: 100 })),
|
|
67
|
+
/** Submits a value. A fresh idempotency key is sent unless one is given; pass your own to make retries across
|
|
68
|
+
* runs of your program safe too. A locked period, or one a rule refuses, throws a ZiffrError (422). */
|
|
69
|
+
submit: async (slug, value, options = {}) => {
|
|
70
|
+
const { body, headers } = await this.request("POST", `/metrics/${encodeURIComponent(slug)}/observations`, undefined, value, options.idempotencyKey ?? newIdempotencyKey());
|
|
71
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
/** The month the workspace's fiscal year starts in (1 is January): where quarterly and yearly Metrics' periods start. */
|
|
75
|
+
workspace = () => this.get("/workspace");
|
|
76
|
+
/** The workspace's people and Contacts. */
|
|
77
|
+
people = {
|
|
78
|
+
/** One page of people. */
|
|
79
|
+
list: (options = {}) => this.get("/people", options),
|
|
80
|
+
/** Everyone, page by page. */
|
|
81
|
+
all: () => this.every((cursor) => this.people.list({ cursor, limit: 100 })),
|
|
82
|
+
};
|
|
83
|
+
/** The workspace's Groups. */
|
|
84
|
+
groups = {
|
|
85
|
+
/** One page of Groups. */
|
|
86
|
+
list: (options = {}) => this.get("/groups", options),
|
|
87
|
+
/** Every Group, page by page. */
|
|
88
|
+
all: () => this.every((cursor) => this.groups.list({ cursor, limit: 100 })),
|
|
89
|
+
};
|
|
90
|
+
/** For a Feed Key (spec 0012): the Feed's Metrics, and recording values for them in batches. */
|
|
91
|
+
feed = {
|
|
92
|
+
/** The Feed's name and one page of its Metrics. */
|
|
93
|
+
get: (options = {}) => this.get("/feed", options),
|
|
94
|
+
/** Every Metric of the Feed, page by page. */
|
|
95
|
+
metrics: () => this.every(async (cursor) => (await this.feed.get({ cursor, limit: 100 })).metrics),
|
|
96
|
+
/** Records up to FEED_BATCH_MAX values, with one result per item in order. A fresh idempotency key is sent unless
|
|
97
|
+
* one is given; pass your own (made from the values) to make a repeated run record nothing twice. */
|
|
98
|
+
submit: async (items, options = {}) => {
|
|
99
|
+
if (!items.length || items.length > FEED_BATCH_MAX)
|
|
100
|
+
throw new Error(`A batch holds 1 to ${FEED_BATCH_MAX} items.`);
|
|
101
|
+
const { body, headers } = await this.request("POST", "/feed/observations", undefined, { items }, options.idempotencyKey ?? newIdempotencyKey());
|
|
102
|
+
return { results: body.results, replayed: headers.get("idempotent-replayed") === "true" };
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
/** The dashboards the key's creator sees (scope dashboards:read), and building them as the creator (scope
|
|
106
|
+
* dashboards:write). A key changes only what its creator may change, and never shares or deletes. */
|
|
107
|
+
dashboards = {
|
|
108
|
+
/** One page of dashboards. */
|
|
109
|
+
list: (options = {}) => this.get("/dashboards", options),
|
|
110
|
+
/** Every dashboard, page by page. */
|
|
111
|
+
all: () => this.every((cursor) => this.dashboards.list({ cursor, limit: 100 })),
|
|
112
|
+
/** One dashboard with its introduction and widgets. */
|
|
113
|
+
get: (id) => this.get(`/dashboards/${id}`),
|
|
114
|
+
/** Creates an empty dashboard, with an introduction if given. A fresh idempotency key is sent unless one is given. */
|
|
115
|
+
create: async (input, options = {}) => {
|
|
116
|
+
const { body, headers } = await this.request("POST", "/dashboards", undefined, input, options.idempotencyKey ?? newIdempotencyKey());
|
|
117
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
118
|
+
},
|
|
119
|
+
/** Makes a dashboard from a Dashboard Template, with Metric slugs for each Slot in order. */
|
|
120
|
+
fromTemplate: async (input, options = {}) => {
|
|
121
|
+
const { body, headers } = await this.request("POST", "/dashboards/from-template", undefined, input, options.idempotencyKey ?? newIdempotencyKey());
|
|
122
|
+
return { ...body, replayed: headers.get("idempotent-replayed") === "true" };
|
|
123
|
+
},
|
|
124
|
+
/** Adds a widget in the first free place. */
|
|
125
|
+
addWidget: async (dashboardId, widget) => (await this.request("POST", `/dashboards/${dashboardId}/widgets`, undefined, widget)).body,
|
|
126
|
+
/** Changes a widget's view, Metrics, title or settings. */
|
|
127
|
+
updateWidget: async (dashboardId, widgetId, patch) => (await this.request("PATCH", `/dashboards/${dashboardId}/widgets/${widgetId}`, undefined, patch)).body,
|
|
128
|
+
/** Removes a widget or a Finding. */
|
|
129
|
+
removeWidget: async (dashboardId, widgetId) => (await this.request("DELETE", `/dashboards/${dashboardId}/widgets/${widgetId}`)).body,
|
|
130
|
+
/** Changes a dashboard's name or introduction. */
|
|
131
|
+
update: async (dashboardId, patch) => (await this.request("PATCH", `/dashboards/${dashboardId}`, undefined, patch)).body,
|
|
132
|
+
/** Adds a Finding about one Metric below everything on the dashboard, full width. */
|
|
133
|
+
addFinding: async (dashboardId, finding) => (await this.request("POST", `/dashboards/${dashboardId}/findings`, undefined, finding)).body,
|
|
134
|
+
/** Changes a Finding's words. */
|
|
135
|
+
updateFinding: async (dashboardId, findingId, words) => (await this.request("PATCH", `/dashboards/${dashboardId}/findings/${findingId}`, undefined, words)).body,
|
|
136
|
+
};
|
|
137
|
+
/** What a key can build with (scope dashboards:read). */
|
|
138
|
+
templates = {
|
|
139
|
+
/** The built-in views, the team's Widget Templates and the Dashboard Templates, or one kind of them. */
|
|
140
|
+
all: async (options = {}) => (await this.get("/templates", options)).items,
|
|
141
|
+
};
|
|
142
|
+
async get(path, query = {}) {
|
|
143
|
+
return (await this.request("GET", path, query)).body;
|
|
144
|
+
}
|
|
145
|
+
async *every(page) {
|
|
146
|
+
let cursor;
|
|
147
|
+
do {
|
|
148
|
+
const p = await page(cursor);
|
|
149
|
+
yield* p.items;
|
|
150
|
+
cursor = p.next ?? undefined;
|
|
151
|
+
} while (cursor);
|
|
152
|
+
}
|
|
153
|
+
async request(method, path, query, body, idempotencyKey) {
|
|
154
|
+
const url = new URL(this.base + path);
|
|
155
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
156
|
+
if (v !== undefined)
|
|
157
|
+
url.searchParams.set(k, String(v));
|
|
158
|
+
const headers = { authorization: `Bearer ${this.key}`, accept: "application/json" };
|
|
159
|
+
if (body !== undefined)
|
|
160
|
+
headers["content-type"] = "application/json";
|
|
161
|
+
if (idempotencyKey)
|
|
162
|
+
headers["idempotency-key"] = idempotencyKey;
|
|
163
|
+
for (let attempt = 0;; attempt++) {
|
|
164
|
+
let res;
|
|
165
|
+
try {
|
|
166
|
+
res = await this.fetcher(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
167
|
+
}
|
|
168
|
+
catch (e) {
|
|
169
|
+
throw new ZiffrError(0, "network", `Could not reach Ziffr: ${e.message}`);
|
|
170
|
+
}
|
|
171
|
+
if (res.ok)
|
|
172
|
+
return { body: (await res.json()), headers: res.headers };
|
|
173
|
+
const err = await res.json().catch(() => null);
|
|
174
|
+
const retryAfter = res.headers.has("retry-after") ? Number(res.headers.get("retry-after")) : null;
|
|
175
|
+
const error = new ZiffrError(res.status, err?.error?.code ?? "unknown", err?.error?.message ?? `Ziffr answered ${res.status}.`, retryAfter);
|
|
176
|
+
// Only a 429 is retried, and only GETs or submissions with an idempotency key: both are safe to repeat.
|
|
177
|
+
const wait = retryAfter ?? 1;
|
|
178
|
+
if (res.status !== 429 || attempt >= this.maxRetries || wait > this.maxRetryWait || (method !== "GET" && !idempotencyKey))
|
|
179
|
+
throw error;
|
|
180
|
+
await sleep(wait * 1000);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ziffr/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Call the Ziffr API from TypeScript: read Metrics and their values, submit values.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/ziffr/ziffr.git",
|
|
9
|
+
"directory": "packages/sdk"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=20"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^20",
|
|
31
|
+
"eslint": "^9.39.5",
|
|
32
|
+
"eslint-plugin-jsdoc": "^65.4.5",
|
|
33
|
+
"typescript": "^5",
|
|
34
|
+
"typescript-eslint": "^8.72.2",
|
|
35
|
+
"vitest": "^4.1.12",
|
|
36
|
+
"@ziffr/core": "0.8.0"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"build": "tsc -p tsconfig.build.json",
|
|
40
|
+
"typecheck": "tsc --noEmit",
|
|
41
|
+
"lint": "eslint",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"test:app": "vitest run --config vitest.app.config.ts"
|
|
44
|
+
}
|
|
6
45
|
}
|