prizerail 0.1.0 → 0.2.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/README.md CHANGED
@@ -11,7 +11,7 @@ The Prizerail SDK for JavaScript and TypeScript. Send entries, read results and
11
11
  npm install prizerail
12
12
  ```
13
13
 
14
- The API is early (v0.x), so names can change between minor versions. Each change is in the [changelog](https://docs.prizerail.com/changelog).
14
+ The API is early (v0.x), so names can change between minor versions. 0.2.0 says `entries` where 0.1.0 said `weight`: an entrant is `{ entrantId, entries }`, and totals are `entrantCount` and `totalEntries`. The old names still work, marked deprecated. Each change is in the [changelog](https://docs.prizerail.com/changelog).
15
15
 
16
16
  ## Send entries
17
17
 
@@ -24,19 +24,19 @@ const campaign = prizerail.campaign("your-campaign")
24
24
  const entries = await Promise.all(
25
25
  users.map(async user => ({
26
26
  entrantId: await hashEntrant(user.id, process.env.ENTRANT_ID_KEY!),
27
- weight: user.tickets,
27
+ entries: user.tickets,
28
28
  }))
29
29
  )
30
30
 
31
31
  const result = await campaign.entries.send(entries)
32
- // { drawing: { id, drawAt, cutoffAt }, sent, added, updated, unchanged, count, totalWeight, batches }
32
+ // { drawing: { id, drawAt, cutoffAt }, sent, added, updated, unchanged, entrantCount, totalEntries, batches }
33
33
  ```
34
34
 
35
- `count` and `totalWeight` are the drawing's own totals, so reconcile with those. `added`, `updated` and `unchanged` add up what each batch reported, and a batch that was stored before its response was lost comes back as `unchanged` on the retry.
35
+ `entrantCount` and `totalEntries` are the drawing's own totals, so reconcile with those. `added`, `updated` and `unchanged` add up what each batch reported, and a batch that was stored before its response was lost comes back as `unchanged` on the retry.
36
36
 
37
37
  `send` takes any number of entries and sends them in requests of 1,000. It retries a `429`, a `5xx`, a timeout or a network error with a jittered, growing wait, and honors `Retry-After`.
38
38
 
39
- Sending an entrant again before the cutoff only sets their weight, so a retry is safe until then. After the cutoff a retry would go to the next drawing, so every send is pinned to one drawing:
39
+ Sending an entrant again before the cutoff only sets their entries, so a retry is safe until then. After the cutoff a retry would go to the next drawing, so every send is pinned to one drawing:
40
40
 
41
41
  - Before the first batch it reads which drawing is taking entries, or uses the `drawing` you pass.
42
42
  - It sends no batch and starts no retry within the request timeout (30 seconds) of that drawing's cutoff. It throws `PrizerailCutoffError` instead.
@@ -62,8 +62,8 @@ Every locked list is published, hashed. Use an id that can't be guessed or linke
62
62
  ### Check what Prizerail has
63
63
 
64
64
  ```ts
65
- let count = 0
66
- for await (const entry of campaign.entries.all()) count++
65
+ let total = 0
66
+ for await (const entrant of campaign.entries.all()) total += entrant.entries
67
67
  ```
68
68
 
69
69
  `entries.all()` pages through the drawing taking entries now, pinned to it after the first page. Pass `{ drawing: id }` for another drawing.
@@ -84,6 +84,10 @@ for await (const drawing of campaign.drawings.all({ status: "paid" })) {
84
84
  const guarantees = await campaign.guarantees.list()
85
85
  ```
86
86
 
87
+ ## Draw now, in test
88
+
89
+ In the test environment, `campaign.drawings.run(id)` closes a drawing's entries now and draws it, so you can see a whole draw without waiting for its cutoff. It resolves with the drawing, usually settled within seconds. Anywhere else it throws a `PrizerailError` with code `test_only`. See [Draw now](https://docs.prizerail.com/api/drawings#draw-now-test-only).
90
+
87
91
  ## Errors
88
92
 
89
93
  Every API error is a `PrizerailError` with the HTTP `status`, the API's `code` (like `not_found` or `no_open_drawing`) and a `detail`. A request that never got a response has status 0 and code `network_error`. See [Errors](https://docs.prizerail.com/api/errors).
@@ -101,7 +105,7 @@ const result = await verifyDraw(
101
105
  result.ok // true when every check passes
102
106
  result.checks // [{ ok, label, detail }]
103
107
 
104
- wasEntered(entrantId, result.entrants!) // { index, weight } or null
108
+ wasEntered(entrantId, result.entrants!) // { index, entries } or null
105
109
  ```
106
110
 
107
111
  With a client, `campaign.drawings.verify(id)` does the same. The checks are the public [verify script](https://docs.prizerail.com/verification/verify-a-draw), shipped unchanged: the entrant list's Merkle root, the random value, and each winner and prize.
package/dist/client.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Http } from "./http.js";
2
- import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, EntriesPage, Entry, Guarantee, SendEntriesResponse, SentEntry } from "./types.js";
2
+ import type { Campaign, Drawing, DrawingRef, DrawingStatus, DrawingsPage, Entrant, EntriesPage, Guarantee, SendEntriesResponse, SentEntrant } from "./types.js";
3
3
  import { type DrawProof, type VerifyResult } from "./verify.js";
4
- export declare const VERSION = "0.1.0";
4
+ export declare const VERSION = "0.2.0";
5
5
  /** The API takes up to this many entries per request. */
6
6
  export declare const ENTRIES_PER_REQUEST = 1000;
7
7
  export type PrizerailOptions = {
@@ -29,13 +29,13 @@ export type SendOptions = {
29
29
  cutoffMarginMs?: number;
30
30
  };
31
31
  /**
32
- * `count` and `totalWeight` are the drawing's totals after the last batch.
33
- * `added`, `updated` and `unchanged` sum what each batch reported, so a
34
- * batch stored before its response was lost, then retried, counts as
35
- * unchanged. Reconcile with `count`, not with `added`.
32
+ * `entrantCount` and `totalEntries` are the drawing's totals after the last
33
+ * batch. `added`, `updated` and `unchanged` sum what each batch reported, so
34
+ * a batch stored before its response was lost, then retried, counts as
35
+ * unchanged. Reconcile with `entrantCount`, not with `added`.
36
36
  */
37
37
  export type SendResult = SendEntriesResponse & {
38
- /** Entries in the batches the drawing confirmed. */
38
+ /** Entrants in the batches the drawing confirmed. */
39
39
  sent: number;
40
40
  batches: number;
41
41
  };
@@ -74,7 +74,7 @@ export declare class EntriesClient {
74
74
  * a PrizerailCutoffError rather than send or retry near its cutoff, and
75
75
  * with a PrizerailDrawingChangedError if a batch lands anywhere else.
76
76
  */
77
- send(entries: Entry[], options?: SendOptions): Promise<SendResult>;
77
+ send(entrants: Entrant[], options?: SendOptions): Promise<SendResult>;
78
78
  /** The drawing taking entries now. */
79
79
  openDrawing(): Promise<DrawingRef>;
80
80
  /** One page of a drawing's entries, in arrival order. */
@@ -84,14 +84,14 @@ export declare class EntriesClient {
84
84
  after?: string;
85
85
  }): Promise<EntriesPage>;
86
86
  /**
87
- * Every entry in a drawing, page by page. Without `drawing`, the one
87
+ * Every entrant in a drawing, page by page. Without `drawing`, the one
88
88
  * taking entries now, pinned by id after the first page so a cutoff
89
89
  * mid-read can't mix in the next drawing.
90
90
  */
91
91
  all(query?: {
92
92
  drawing?: string;
93
93
  pageSize?: number;
94
- }): AsyncGenerator<SentEntry>;
94
+ }): AsyncGenerator<SentEntrant>;
95
95
  }
96
96
  export declare class DrawingsClient {
97
97
  private readonly campaign;
@@ -112,6 +112,14 @@ export declare class DrawingsClient {
112
112
  pageSize?: number;
113
113
  }): AsyncGenerator<Drawing>;
114
114
  get(id: string): Promise<Drawing>;
115
+ /**
116
+ * Test environment only: closes the drawing's entries now and draws it,
117
+ * instead of waiting for its cutoff. Resolves with the drawing, settled or
118
+ * paid, or still `entropy_requested` if the random value is on its way, in
119
+ * which case read it again with `get(id)`. Elsewhere it throws a
120
+ * PrizerailError with code `test_only`.
121
+ */
122
+ run(id: string): Promise<Drawing>;
115
123
  /**
116
124
  * The newest drawing with final winners, `settled` or `paid`, or null.
117
125
  * A large prize paid by hand can keep a newer draw at `settled`, so this
package/dist/client.js CHANGED
@@ -1,10 +1,69 @@
1
1
  import { PrizerailCutoffError, PrizerailDrawingChangedError, PrizerailError, } from "./errors.js";
2
2
  import { Http } from "./http.js";
3
3
  import { verifyDraw } from "./verify.js";
4
- export const VERSION = "0.1.0";
4
+ export const VERSION = "0.2.0";
5
5
  const badPage = (detail) => new PrizerailError(0, "invalid_response", `Paging stopped: ${detail}.`);
6
6
  /** The API takes up to this many entries per request. */
7
7
  export const ENTRIES_PER_REQUEST = 1000;
8
+ /** An entrant as the API takes it: `entries`, never the older `weight`. */
9
+ function toWire(entrant) {
10
+ if (typeof entrant === "string")
11
+ return entrant;
12
+ const { weight, ...rest } = entrant;
13
+ if (weight === undefined)
14
+ return rest;
15
+ if (rest.entries !== undefined) {
16
+ throw new TypeError(`Entrant ${rest.entrantId} has both entries and weight. Send entries.`);
17
+ }
18
+ return { ...rest, entries: weight };
19
+ }
20
+ const badResponse = (detail) => new PrizerailError(0, "invalid_response", detail);
21
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
22
+ /** One of a pair of names for the same total, which must agree if both came. */
23
+ function pick(r, current, old) {
24
+ const a = r[current];
25
+ const b = r[old];
26
+ if (a !== undefined && b !== undefined && a !== b) {
27
+ throw badResponse(`${String(current)} ${a} and ${String(old)} ${b} disagree.`);
28
+ }
29
+ const value = a ?? b;
30
+ if (!isCount(value)) {
31
+ throw badResponse(`The response has no valid ${String(current)}.`);
32
+ }
33
+ return value;
34
+ }
35
+ /** Both names for the totals, from whichever the server sent. */
36
+ function totals(r) {
37
+ const entrantCount = pick(r, "entrantCount", "count");
38
+ const totalEntries = pick(r, "totalEntries", "totalWeight");
39
+ return {
40
+ entrantCount,
41
+ totalEntries,
42
+ count: entrantCount,
43
+ totalWeight: totalEntries,
44
+ };
45
+ }
46
+ /** A page with the current names filled in, from either server shape. */
47
+ function normalizePage(page) {
48
+ const rows = page.entrants ?? page.entries;
49
+ if (!Array.isArray(rows)) {
50
+ throw badResponse("The response has no entrants list.");
51
+ }
52
+ const entrants = rows.map(e => {
53
+ const n = e.entries ?? e.weight;
54
+ if (!isCount(n) || n < 1 || typeof e.entrantId !== "string") {
55
+ throw badResponse("An entrant in the response has no valid id or entries.");
56
+ }
57
+ return { ...e, entries: n, weight: n };
58
+ });
59
+ return {
60
+ drawing: page.drawing,
61
+ ...totals(page),
62
+ entrants,
63
+ entries: entrants,
64
+ next: page.next,
65
+ };
66
+ }
8
67
  export class Prizerail {
9
68
  siteUrl;
10
69
  /** @internal */
@@ -83,7 +142,8 @@ export class EntriesClient {
83
142
  * a PrizerailCutoffError rather than send or retry near its cutoff, and
84
143
  * with a PrizerailDrawingChangedError if a batch lands anywhere else.
85
144
  */
86
- async send(entries, options = {}) {
145
+ async send(entrants, options = {}) {
146
+ const entries = entrants.map(toWire);
87
147
  if (entries.length === 0)
88
148
  throw new Error("send() needs entries.");
89
149
  const margin = options.cutoffMarginMs ?? this.campaign.http.options.timeoutMs;
@@ -112,7 +172,7 @@ export class EntriesClient {
112
172
  }
113
173
  const batch = entries.slice(i, i + ENTRIES_PER_REQUEST);
114
174
  const res = await this.campaign.http.request("POST", this.campaign.path("/entries"), {
115
- body: { entries: batch },
175
+ body: { entrants: batch },
116
176
  deadline: cutoff - margin,
117
177
  onDeadline: cause => stop(`A batch failed and a retry would reach drawing ${target.id}'s cutoff. Check what it has before sending again.`, cause),
118
178
  });
@@ -132,8 +192,7 @@ export class EntriesClient {
132
192
  added: progress.added,
133
193
  updated: progress.updated,
134
194
  unchanged: progress.unchanged,
135
- count: final.count,
136
- totalWeight: final.totalWeight,
195
+ ...totals(final),
137
196
  sent: progress.sent,
138
197
  batches,
139
198
  };
@@ -148,11 +207,11 @@ export class EntriesClient {
148
207
  };
149
208
  }
150
209
  /** One page of a drawing's entries, in arrival order. */
151
- list(query = {}) {
152
- return this.campaign.http.request("GET", this.campaign.path("/entries"), { query });
210
+ async list(query = {}) {
211
+ return normalizePage(await this.campaign.http.request("GET", this.campaign.path("/entries"), { query }));
153
212
  }
154
213
  /**
155
- * Every entry in a drawing, page by page. Without `drawing`, the one
214
+ * Every entrant in a drawing, page by page. Without `drawing`, the one
156
215
  * taking entries now, pinned by id after the first page so a cutoff
157
216
  * mid-read can't mix in the next drawing.
158
217
  */
@@ -169,7 +228,7 @@ export class EntriesClient {
169
228
  if (page.drawing.id !== drawing) {
170
229
  throw badPage(`a page came from drawing ${page.drawing.id}, not ${drawing}`);
171
230
  }
172
- yield* page.entries;
231
+ yield* page.entrants;
173
232
  if (page.next === null)
174
233
  return;
175
234
  // Each cursor must move forward, or a bad page would loop forever.
@@ -224,6 +283,19 @@ export class DrawingsClient {
224
283
  async get(id) {
225
284
  return (await this.campaign.http.request("GET", this.campaign.path(`/drawings/${encodeURIComponent(id)}`))).drawing;
226
285
  }
286
+ /**
287
+ * Test environment only: closes the drawing's entries now and draws it,
288
+ * instead of waiting for its cutoff. Resolves with the drawing, settled or
289
+ * paid, or still `entropy_requested` if the random value is on its way, in
290
+ * which case read it again with `get(id)`. Elsewhere it throws a
291
+ * PrizerailError with code `test_only`.
292
+ */
293
+ async run(id) {
294
+ return (await this.campaign.http.request("POST", this.campaign.path(`/drawings/${encodeURIComponent(id)}/run`),
295
+ // A repeat after a lost answer would only be refused, so never retry,
296
+ // and wait out the route's own 90 seconds rather than the default 30.
297
+ { maxRetries: 0, timeoutMs: 90_000 })).drawing;
298
+ }
227
299
  /**
228
300
  * The newest drawing with final winners, `settled` or `paid`, or null.
229
301
  * A large prize paid by hand can keep a newer draw at `settled`, so this
package/dist/http.d.ts CHANGED
@@ -17,6 +17,10 @@ export type RequestOptions = {
17
17
  */
18
18
  deadline?: number;
19
19
  onDeadline?: (error: unknown) => Error;
20
+ /** For a request that isn't safe to repeat. Defaults to the client's maxRetries. */
21
+ maxRetries?: number;
22
+ /** For a request the server may take longer over. Defaults to the client's. */
23
+ timeoutMs?: number;
20
24
  };
21
25
  /** A server that asks for a longer wait than this gets the error instead. */
22
26
  export declare const MAX_RETRY_AFTER_MS: number;
@@ -29,7 +33,7 @@ export declare class Http {
29
33
  constructor(options: HttpOptions);
30
34
  url(path: string, query?: RequestOptions["query"]): string;
31
35
  /** JSON from the partner API, with retries. Throws PrizerailError. */
32
- request<T>(method: "GET" | "POST", path: string, { query, body, deadline, onDeadline }?: RequestOptions): Promise<T>;
36
+ request<T>(method: "GET" | "POST", path: string, { query, body, deadline, onDeadline, ...rest }?: RequestOptions): Promise<T>;
33
37
  /** Public JSON, like a draw's proof, with no key and no retries. */
34
38
  getPublic<T>(url: string): Promise<T>;
35
39
  }
package/dist/http.js CHANGED
@@ -63,8 +63,10 @@ export class Http {
63
63
  return url.href;
64
64
  }
65
65
  /** JSON from the partner API, with retries. Throws PrizerailError. */
66
- async request(method, path, { query, body, deadline, onDeadline } = {}) {
67
- const { apiKey, fetch, timeoutMs, maxRetries, userAgent } = this.options;
66
+ async request(method, path, { query, body, deadline, onDeadline, ...rest } = {}) {
67
+ const { apiKey, fetch, userAgent } = this.options;
68
+ const maxRetries = rest.maxRetries ?? this.options.maxRetries;
69
+ const timeoutMs = rest.timeoutMs ?? this.options.timeoutMs;
68
70
  if (!apiKey) {
69
71
  throw new PrizerailError(0, "no_api_key", "Pass apiKey to new Prizerail() to call the partner API.");
70
72
  }
package/dist/types.d.ts CHANGED
@@ -113,27 +113,40 @@ export type DrawingsPage = {
113
113
  nextBefore: string | null;
114
114
  nextAfter: string | null;
115
115
  };
116
- /** An entrant id, or an id with a weight and how they show if they win. */
117
- export type Entry = string | {
116
+ /** An entrant id, with one entry, or an id with their entries and how they show if they win. */
117
+ export type Entrant = string | {
118
118
  entrantId: string;
119
- /** Whole number from 1. Leave it out and it's 1. */
119
+ /** Their number of entries, a whole number from 1. Leave it out and it's 1. */
120
+ entries?: number;
121
+ /** @deprecated Use `entries`. Still sent as `entries`. */
120
122
  weight?: number;
121
123
  /** Up to 40 characters. */
122
124
  displayName?: string;
123
125
  /** https, up to 2,048 characters. */
124
126
  avatarUrl?: string;
125
127
  };
128
+ /** @deprecated Use `Entrant`. */
129
+ export type Entry = Entrant;
126
130
  export type SendEntriesResponse = {
127
131
  drawing: DrawingRef;
132
+ /** Entrants in this request that were new, changed or the same. */
128
133
  added: number;
129
134
  updated: number;
130
135
  unchanged: number;
131
- /** The drawing's totals so far. */
136
+ /** The drawing's entrants so far. */
137
+ entrantCount: number;
138
+ /** The drawing's total entries so far. */
139
+ totalEntries: number;
140
+ /** @deprecated Use `entrantCount`. */
132
141
  count: number;
142
+ /** @deprecated Use `totalEntries`. */
133
143
  totalWeight: number;
134
144
  };
135
- export type SentEntry = {
145
+ export type SentEntrant = {
136
146
  entrantId: string;
147
+ /** Their number of entries. */
148
+ entries: number;
149
+ /** @deprecated Use `entries`. */
137
150
  weight: number;
138
151
  displayName: string | null;
139
152
  avatarUrl: string | null;
@@ -141,13 +154,22 @@ export type SentEntry = {
141
154
  position: number | null;
142
155
  receivedAt: string;
143
156
  };
157
+ /** @deprecated Use `SentEntrant`. */
158
+ export type SentEntry = SentEntrant;
144
159
  export type EntriesPage = {
145
160
  drawing: DrawingRef & {
146
161
  status: DrawingStatus;
147
162
  };
163
+ entrantCount: number;
164
+ totalEntries: number;
165
+ /** In arrival order, the order the list locks in. */
166
+ entrants: SentEntrant[];
167
+ /** @deprecated Use `entrantCount`. */
148
168
  count: number;
169
+ /** @deprecated Use `totalEntries`. */
149
170
  totalWeight: number;
150
- entries: SentEntry[];
171
+ /** @deprecated Use `entrants`, the same list. */
172
+ entries: SentEntrant[];
151
173
  /** Pass as `after` for the next page. Null on the last. */
152
174
  next: string | null;
153
175
  };
package/dist/verify.d.ts CHANGED
@@ -60,5 +60,6 @@ export declare function verifyDraw(source: string | DrawProof, { entrants, proof
60
60
  */
61
61
  export declare function wasEntered(entrantId: string, rows: EntrantRow[]): {
62
62
  index: number;
63
+ entries: number;
63
64
  weight: number;
64
65
  } | null;
package/dist/verify.js CHANGED
@@ -65,5 +65,6 @@ export async function verifyDraw(source, { entrants, proofUrl, fetch: fetchImpl
65
65
  export function wasEntered(entrantId, rows) {
66
66
  const hash = winnerHash(entrantId);
67
67
  const row = rows.find(r => r[1].toLowerCase() === hash);
68
- return row ? { index: row[0], weight: row[2] } : null;
68
+ // The proof calls an entrant's entries their weight. Both names, for now.
69
+ return row ? { index: row[0], entries: row[2], weight: row[2] } : null;
69
70
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prizerail",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The Prizerail SDK: send entries, read draws and verify them.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.prizerail.com",