@zimmerstack/connect 0.6.0 → 0.9.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.
Files changed (51) hide show
  1. package/AGENTS.md +269 -15
  2. package/README.md +451 -18
  3. package/dist/cjs/client.d.ts +503 -13
  4. package/dist/cjs/client.js +743 -45
  5. package/dist/cjs/doctor.d.ts +86 -0
  6. package/dist/cjs/doctor.js +689 -0
  7. package/dist/cjs/errors.d.ts +6 -2
  8. package/dist/cjs/errors.js +7 -2
  9. package/dist/cjs/generated.d.ts +2921 -207
  10. package/dist/cjs/generated.js +222 -8
  11. package/dist/cjs/grid.d.ts +6 -1
  12. package/dist/cjs/grid.js +8 -0
  13. package/dist/cjs/index.d.ts +14 -5
  14. package/dist/cjs/index.js +41 -1
  15. package/dist/cjs/key.d.ts +39 -0
  16. package/dist/cjs/key.js +85 -0
  17. package/dist/cjs/money.d.ts +81 -0
  18. package/dist/cjs/money.js +172 -0
  19. package/dist/cjs/notices.d.ts +44 -0
  20. package/dist/cjs/notices.js +64 -0
  21. package/dist/cjs/shownOnce.d.ts +42 -0
  22. package/dist/cjs/shownOnce.js +83 -0
  23. package/dist/cjs/webhooks.d.ts +182 -3
  24. package/dist/cjs/webhooks.js +75 -1
  25. package/dist/esm/client.d.ts +503 -13
  26. package/dist/esm/client.js +741 -45
  27. package/dist/esm/doctor.d.ts +86 -0
  28. package/dist/esm/doctor.js +685 -0
  29. package/dist/esm/errors.d.ts +6 -2
  30. package/dist/esm/errors.js +7 -2
  31. package/dist/esm/generated.d.ts +2921 -207
  32. package/dist/esm/generated.js +221 -7
  33. package/dist/esm/grid.d.ts +6 -1
  34. package/dist/esm/grid.js +7 -0
  35. package/dist/esm/index.d.ts +14 -5
  36. package/dist/esm/index.js +8 -3
  37. package/dist/esm/key.d.ts +39 -0
  38. package/dist/esm/key.js +81 -0
  39. package/dist/esm/mcp/cli.js +88 -9
  40. package/dist/esm/mcp/reference.generated.js +4464 -974
  41. package/dist/esm/mcp/server.d.ts +14 -6
  42. package/dist/esm/mcp/server.js +451 -25
  43. package/dist/esm/money.d.ts +81 -0
  44. package/dist/esm/money.js +161 -0
  45. package/dist/esm/notices.d.ts +44 -0
  46. package/dist/esm/notices.js +56 -0
  47. package/dist/esm/shownOnce.d.ts +42 -0
  48. package/dist/esm/shownOnce.js +77 -0
  49. package/dist/esm/webhooks.d.ts +182 -3
  50. package/dist/esm/webhooks.js +69 -0
  51. package/package.json +1 -1
@@ -1,6 +1,25 @@
1
1
  import { ZimmerStackError, ZimmerStackUsageError } from "./errors.js";
2
2
  import { API_ORIGIN, API_PREFIX, IDEMPOTENCY_HEADER, OPERATIONS, PROPERTY_HEADER, SDK_VERSION, } from "./generated.js";
3
- import { buildGrid, chunk, toRanges } from "./grid.js";
3
+ import { checkKey } from "./key.js";
4
+ import { buildGrid, cellsOf, chunk, toRanges } from "./grid.js";
5
+ /** The header a company key sends with what it writes ahead of go-live (`beforeGoLive: true` on a call). */
6
+ export const BEFORE_GO_LIVE_HEADER = "x-zs-before-go-live";
7
+ /**
8
+ * The body of a real close or reopen. A caller without types may have put `dryRun` in it, meaning "do not
9
+ * do it": that is refused here, never silently done for real.
10
+ */
11
+ function realOnly(method, body) {
12
+ if (body !== null && typeof body === "object" && "dryRun" in body) {
13
+ throw new ZimmerStackUsageError(`zs.availability.${method} does it for real and takes no dryRun. To see what it would do, call zs.availability.${method}DryRun with the same room type and nights. Nothing was sent.`);
14
+ }
15
+ return body;
16
+ }
17
+ /** A dry run that came back as anything but a preview is never passed on as one. */
18
+ function previewOnly(operation, answer) {
19
+ if (answer?.dryRun === true)
20
+ return answer;
21
+ throw new Error(`${operation} was sent as a dry run and the answer is not a preview. Treat it as a real write: read zs.sync.get() and the calendar before you send anything else.`);
22
+ }
4
23
  /** One entity was sent, so the answer names exactly one. */
5
24
  function savedOne(result) {
6
25
  const item = result.items[0];
@@ -9,13 +28,45 @@ function savedOne(result) {
9
28
  return { ...item, channelManager: result.channelManager };
10
29
  }
11
30
  /* ───────────────────────────── the shared core ───────────────────────────── */
12
- /** Requests in flight at once. Writes go one at a time on top of that. */
31
+ /** Requests in flight at once. Writes go one at a time per hotel on top of that. */
13
32
  const PARALLEL = 4;
14
33
  const KEY_SHAPE = /^zsk_(live|test)_[A-Za-z0-9_-]{16,}$/;
15
34
  const IDEMPOTENCY_SHAPE = /^[A-Za-z0-9_-]{10,64}$/;
16
35
  /** After one of these the key will never work again: every later call is refused here, not sent. */
17
36
  const KEY_IS_DEAD = new Set(["API_KEY_INVALID", "API_KEY_REVOKED", "API_KEY_EXPIRED"]);
18
37
  const CATALOG_TTL_MS = 10 * 60_000;
38
+ /**
39
+ * Writes whose route keeps an idempotency key on the server although the contract copy this package was
40
+ * generated from did not say so yet (the API booking's cancel, the sandbox booking's cancel and modify).
41
+ * The client sends a key for them, so a cancel whose answer was lost can be sent again and never lands
42
+ * twice. Once the generated table (`OPERATIONS`) says the same, this list changes nothing.
43
+ */
44
+ export const KEYED_WRITES = new Set(["POST /bookings/{bookingId}/cancel", "POST /sandbox/bookings/{bookingId}/cancel", "POST /sandbox/bookings/{bookingId}/modify"]);
45
+ /** Routes about the partner's own company: they read no X-ZS-Property, so the client sends none. */
46
+ const COMPANY_ROUTES = ["/webhook-endpoints", "/connect-links", "/billing", "/support-tickets"];
47
+ /** The three writes that name cells: the `cells` budget counts every night of every row they carry. */
48
+ const CELL_WRITES = new Set(["PUT /availability", "PUT /rates", "PUT /restrictions"]);
49
+ /**
50
+ * Whose budget a name in the `RateLimit` headers is.
51
+ *
52
+ * Under a company key every hotel runs under its own key and property budgets, so those belong to that
53
+ * hotel alone: when one hotel's budget is nearly out, only that hotel's calls wait. What every hotel of the
54
+ * client shares waits for everyone: the company's budget, everyone's ceiling and the address's budgets.
55
+ */
56
+ const SHARED_BUDGETS = new Set(["company", "global", "ip", "ip-auth", "key-auth", "global-unauthenticated", "api-address"]);
57
+ /** Budgets that count every request, and the two that count every write. Any other budget is its own operation's. */
58
+ const EVERY_REQUEST = new Set(["key", "property", ...SHARED_BUDGETS]);
59
+ const EVERY_WRITE = new Set(["key-writes", "property-writes"]);
60
+ /** What a refusal's `data.scope` is called in the headers: only the key's own two differ. */
61
+ const HEADER_OF_SCOPE = { requests: "key", writes: "key-writes" };
62
+ /**
63
+ * The channel shield's budgets over an hour and a day, and its pause. A write that only CLOSES inventory is
64
+ * still accepted while they are used up (the safety lane), and only the server can tell which write that
65
+ * is. So the client never holds a write back for one of these: it sends, and reports what the API answers.
66
+ */
67
+ const NEVER_HELD_BACK = new Set(["cells-hour", "cells-day", "vendor-cells-day", "shield-pause", "shield-lane"]);
68
+ /** A wait this long or shorter is the pace of a minute's budget: always waited out, whatever `maxWaitSeconds` says. */
69
+ const SHORT_WAIT_MS = 65_000;
19
70
  function sleep(ms, signal) {
20
71
  return new Promise((resolve, reject) => {
21
72
  if (signal?.aborted)
@@ -53,6 +104,40 @@ function resolveBase(baseUrl) {
53
104
  }
54
105
  return url.origin;
55
106
  }
107
+ /** "about 40 seconds", "about 2 minutes", "about 3 hours": how long a wait is, for a person. */
108
+ export function aboutHowLong(ms) {
109
+ const seconds = Math.max(1, Math.round(ms / 1000));
110
+ if (seconds < 90)
111
+ return `about ${seconds} second${seconds === 1 ? "" : "s"}`;
112
+ const minutes = Math.round(seconds / 60);
113
+ if (minutes < 90)
114
+ return `about ${minutes} minutes`;
115
+ const hours = Math.round(minutes / 60);
116
+ return `about ${hours} hour${hours === 1 ? "" : "s"}`;
117
+ }
118
+ /** Read `RateLimit-Policy` and `RateLimit` into one list. Unknown names are kept: a new budget is paced like any other. */
119
+ export function readBudgets(policy, state) {
120
+ const quotas = new Map();
121
+ for (const part of (policy ?? "").split(",")) {
122
+ const name = /"([^"]+)"/.exec(part)?.[1];
123
+ if (!name)
124
+ continue;
125
+ const q = /;\s*q=(\d+)/.exec(part);
126
+ const w = /;\s*w=(\d+)/.exec(part);
127
+ quotas.set(name, { quota: q ? Number(q[1]) : undefined, windowSeconds: w ? Number(w[1]) : 60 });
128
+ }
129
+ const out = [];
130
+ for (const part of (state ?? "").split(",")) {
131
+ const name = /"([^"]+)"/.exec(part)?.[1];
132
+ const left = /;\s*r=(\d+)/.exec(part);
133
+ const refill = /;\s*t=(\d+)/.exec(part);
134
+ if (!name || !left || !refill)
135
+ continue;
136
+ const known = quotas.get(name);
137
+ out.push({ name, quota: known?.quota, windowSeconds: known?.windowSeconds ?? 60, remaining: Number(left[1]), resetSeconds: Number(refill[1]) });
138
+ }
139
+ return out;
140
+ }
56
141
  /**
57
142
  * Operations that do a long thing while you wait: adding a hotel creates its account, and removing one takes
58
143
  * it off its booking sites one step at a time. One attempt of these is given at least this long, however
@@ -67,6 +152,50 @@ const PATIENCE_MS = {
67
152
  export function attemptTimeoutMs(operation, timeoutMs) {
68
153
  return Math.max(timeoutMs, PATIENCE_MS[operation] ?? 0);
69
154
  }
155
+ /**
156
+ * A wait too long to hold a call open for (a day's budget that is used up) is trusted this long after it
157
+ * was learned: calls it holds are not sent, and come back saying when the budget frees. After that one call
158
+ * goes out again, so a budget that was raised or freed early is noticed.
159
+ */
160
+ const LONG_HOLD_TRUST_MS = 5 * 60_000;
161
+ /**
162
+ * The pace of one hotel, or of what every hotel of the client shares. A hold says "nothing of this kind
163
+ * before `until`": on every request, on every write, or on one operation.
164
+ */
165
+ class Pace {
166
+ all;
167
+ writes;
168
+ operations = new Map();
169
+ /** The cells budget as last seen, less what this client has sent since: a write of more cells than are left waits for the window. */
170
+ cells;
171
+ /** Writes of this hotel go one after another. */
172
+ writeTail = Promise.resolve();
173
+ hold(kind, hold) {
174
+ // Fresh news of the same budget replaces what was known; between two budgets the later one decides.
175
+ const pick = (current) => (!current || current.budget === hold.budget || hold.until >= current.until ? hold : current);
176
+ if (kind === "all")
177
+ this.all = pick(this.all);
178
+ else if (kind === "writes")
179
+ this.writes = pick(this.writes);
180
+ else
181
+ this.operations.set(kind, pick(this.operations.get(kind)));
182
+ }
183
+ /** The latest hold that applies to this call. */
184
+ holdFor(wire, now) {
185
+ let latest;
186
+ const consider = (h) => {
187
+ if (h && h.until > now && (!latest || h.until > latest.until))
188
+ latest = h;
189
+ };
190
+ consider(this.all);
191
+ if (wire.write)
192
+ consider(this.writes);
193
+ consider(this.operations.get(wire.operation));
194
+ if (wire.cells > 0 && this.cells && this.cells.until > now && wire.cells > this.cells.remaining)
195
+ consider({ until: this.cells.until, budget: "cells", learnedAt: now });
196
+ return latest;
197
+ }
198
+ }
70
199
  class Core {
71
200
  #key;
72
201
  mode;
@@ -77,17 +206,20 @@ class Core {
77
206
  #maxWaitSeconds;
78
207
  #allowLiveWritesInTests;
79
208
  #onEvent;
80
- #resumeAll = 0;
81
- #resumeWrites = 0;
209
+ /** What every hotel of this client shares: the company's budget, everyone's ceiling, the address. */
210
+ #shared = new Pace();
211
+ /** One pace and one queue of writes per hotel, so one hotel's budget never holds up another's calls. */
212
+ #hotels = new Map();
82
213
  #active = 0;
83
214
  #queue = [];
84
- #writeTail = Promise.resolve();
85
215
  #dead;
86
216
  catalogs = new Map();
87
217
  /** A sandbox company key's one hotel, found once when a call asked for a hotel and none was named. */
88
218
  soleSandboxProperty;
89
219
  /** The same, once known: sent with every later call that names no hotel, so the refusal is met once. */
90
220
  soleSandboxId;
221
+ /** What the key's own checksum says is wrong with it, when something is (never the key). */
222
+ keyHint;
91
223
  constructor(options) {
92
224
  const g = globalThis;
93
225
  if ((typeof g.window !== "undefined" && typeof g.window.document !== "undefined") || g.navigator?.product === "ReactNative") {
@@ -100,6 +232,10 @@ class Core {
100
232
  if (!shape)
101
233
  throw new ZimmerStackUsageError("The API key does not look like a ZimmerStack key (zsk_test_… or zsk_live_…). It was not sent anywhere.");
102
234
  this.#key = key.trim();
235
+ // Checked offline, by the key's own checksum (src/key.ts): kept for the day the API refuses the key, so
236
+ // the refusal can say "it was mistyped" instead of leaving the person to guess. Never the key itself.
237
+ const check = checkKey(this.#key);
238
+ this.keyHint = check.ok ? undefined : check.message;
103
239
  this.mode = shape[1];
104
240
  this.base = resolveBase(options.baseUrl);
105
241
  const f = options.fetch ?? globalThis.fetch;
@@ -123,6 +259,14 @@ class Core {
123
259
  /* a logger must never break a request */
124
260
  }
125
261
  }
262
+ #hotel(id) {
263
+ let pace = this.#hotels.get(id);
264
+ if (!pace) {
265
+ pace = new Pace();
266
+ this.#hotels.set(id, pace);
267
+ }
268
+ return pace;
269
+ }
126
270
  send(wire) {
127
271
  if (this.#dead) {
128
272
  const d = this.#dead;
@@ -145,11 +289,12 @@ class Core {
145
289
  }
146
290
  if (!wire.write)
147
291
  return this.#attempts(wire);
148
- // Writes go one after another: a burst spends the write budget at once, and two writes to one
149
- // night must reach the record in the order they were made.
292
+ // Writes to one hotel go one after another: a burst spends its write budget at once, and two writes to
293
+ // one night must reach the record in the order they were made. Another hotel's writes do not wait for these.
294
+ const hotel = this.#hotel(wire.hotel);
150
295
  const run = () => this.#attempts(wire);
151
- const result = this.#writeTail.then(run, run);
152
- this.#writeTail = result.catch(() => undefined);
296
+ const result = hotel.writeTail.then(run, run);
297
+ hotel.writeTail = result.catch(() => undefined);
153
298
  return result;
154
299
  }
155
300
  #slot() {
@@ -168,30 +313,102 @@ class Core {
168
313
  return Promise.resolve(take());
169
314
  return new Promise((resolve) => this.#queue.push(() => resolve(take())));
170
315
  }
171
- /** Wait until the budgets the last answers reported have room again, instead of earning a 429. */
316
+ #maxWaitMs(wire) {
317
+ return Math.max(0, wire.maxWaitSeconds ?? this.#maxWaitSeconds) * 1000;
318
+ }
319
+ /** What a call that will not be held open comes back as: the API's own refusal shape, saying when the budget frees. */
320
+ #notNow(wire, budget, waitMs, sent) {
321
+ const retryAfterSeconds = Math.max(1, Math.ceil(waitMs / 1000));
322
+ const message = `${wire.operation} ${sent ? "was refused" : "was not sent"}: the ${budget} budget is used up and has room again in ${aboutHowLong(waitMs)}. Send it again then.`;
323
+ this.#emit({ type: "deferred", operation: wire.operation, scope: budget, retryAfterSeconds, freesAt: new Date(Date.now() + waitMs).toISOString(), message });
324
+ return new ZimmerStackError({ status: 429, code: "RATE_LIMITED", message, operation: wire.operation, scope: budget, retryAfterSeconds, retryable: true });
325
+ }
326
+ /**
327
+ * Wait until every budget the last answers reported has room again, instead of earning a 429: the hotel's
328
+ * own budgets and what every hotel shares. The pace of a minute's budget is always waited out. A longer
329
+ * wait (a day's budget that is used up) is waited out only inside `maxWaitSeconds`; past that the call is
330
+ * not sent and comes back as a retryable RATE_LIMITED that says when the budget frees.
331
+ */
172
332
  async #pace(wire) {
173
333
  for (;;) {
174
- const wait = Math.max(this.#resumeAll, wire.write ? this.#resumeWrites : 0) - Date.now();
175
- if (wait <= 0)
334
+ const now = Date.now();
335
+ const own = this.#hotel(wire.hotel).holdFor(wire, now);
336
+ const shared = this.#shared.holdFor(wire, now);
337
+ const hold = own && shared ? (own.until >= shared.until ? own : shared) : (own ?? shared);
338
+ if (!hold)
176
339
  return;
177
- this.#emit({ type: "pace", operation: wire.operation, waitMs: wait });
340
+ const wait = hold.until - now;
341
+ if (wait > SHORT_WAIT_MS && wait > this.#maxWaitMs(wire)) {
342
+ // Too long to hold the call open. While the news is fresh the call is not sent; once it is older,
343
+ // this one goes out to learn whether the budget is still used up.
344
+ if (now - hold.learnedAt < LONG_HOLD_TRUST_MS)
345
+ throw this.#notNow(wire, hold.budget, wait, false);
346
+ hold.until = 0;
347
+ continue;
348
+ }
349
+ this.#emit({ type: "pace", operation: wire.operation, waitMs: wait, scope: hold.budget });
350
+ if (wait > SHORT_WAIT_MS)
351
+ this.#lands(wire, hold.budget, wait);
178
352
  await sleep(wait, wire.signal);
179
353
  }
180
354
  }
181
- /** RateLimit: "key";r=117;t=42, "key-writes";r=29;t=42 (r = requests left, t = seconds until the window has room). */
182
- #notePace(res) {
183
- for (const part of (res.headers.get("ratelimit") ?? "").split(",")) {
184
- const left = /;\s*r=(\d+)/.exec(part);
185
- const refill = /;\s*t=(\d+)/.exec(part);
186
- if (!left || !refill || Number(left[1]) > PARALLEL)
355
+ /** A wait worth telling a person about: the call is held and lands when the budget frees. */
356
+ #lands(wire, budget, waitMs) {
357
+ this.#emit({
358
+ type: "wait",
359
+ operation: wire.operation,
360
+ scope: budget,
361
+ waitMs,
362
+ landsAt: new Date(Date.now() + waitMs).toISOString(),
363
+ message: `${wire.operation} lands in ${aboutHowLong(waitMs)}${budget ? ` (waiting for the ${budget} budget)` : ""}.`,
364
+ });
365
+ }
366
+ /** Whose pace a budget moves: what every hotel shares, or this call's hotel alone. */
367
+ #paceOf(budget, wire) {
368
+ return SHARED_BUDGETS.has(budget) ? this.#shared : this.#hotel(wire.hotel);
369
+ }
370
+ /** Which calls a budget holds: every request, every write, or the one operation it was reported on. */
371
+ #holds(budget, wire) {
372
+ return EVERY_REQUEST.has(budget) ? "all" : EVERY_WRITE.has(budget) ? "writes" : wire.operation;
373
+ }
374
+ /**
375
+ * Read every budget of the answer's headers.
376
+ * RateLimit-Policy: "key";q=120;w=60, "key-writes";q=30;w=60, "property";q=300;w=60, "cells";q=20000;w=60
377
+ * RateLimit: "key";r=117;t=42, "key-writes";r=29;t=42, "property";r=296;t=42, "cells";r=20000;t=0
378
+ * A minute's budget that is nearly out holds the calls it counts until it refills. A budget with a longer
379
+ * window, should the headers carry one, holds only once nothing is left. The cells budget is counted in cells, so it is
380
+ * remembered with what this write just used and compared with the size of the next one.
381
+ */
382
+ #notePace(res, wire) {
383
+ const now = Date.now();
384
+ for (const b of readBudgets(res.headers.get("ratelimit-policy"), res.headers.get("ratelimit"))) {
385
+ if (NEVER_HELD_BACK.has(b.name))
386
+ continue;
387
+ const pace = this.#paceOf(b.name, wire);
388
+ if (b.name === "cells") {
389
+ // The header was read before this write's own cells were counted: take them off.
390
+ const used = res.ok ? wire.cells : 0;
391
+ pace.cells = { remaining: Math.max(0, b.remaining - used), until: now + (b.resetSeconds > 0 ? Math.min(b.resetSeconds, 65) : Math.min(b.windowSeconds, 65)) * 1000 };
187
392
  continue;
188
- const at = Date.now() + Math.min(Number(refill[1]), 65) * 1000;
189
- if (/"[^"]*(writes|bookings|cells)[^"]*"/.test(part))
190
- this.#resumeWrites = Math.max(this.#resumeWrites, at);
191
- else
192
- this.#resumeAll = Math.max(this.#resumeAll, at);
393
+ }
394
+ if (b.windowSeconds <= 60) {
395
+ if (b.remaining > PARALLEL)
396
+ continue;
397
+ pace.hold(this.#holds(b.name, wire), { until: now + Math.min(Math.max(b.resetSeconds, 1), 65) * 1000, budget: b.name, learnedAt: now });
398
+ }
399
+ else if (b.remaining <= 0 && b.resetSeconds > 0) {
400
+ pace.hold(this.#holds(b.name, wire), { until: now + b.resetSeconds * 1000, budget: b.name, learnedAt: now });
401
+ }
193
402
  }
194
403
  }
404
+ /** A refusal names its budget and its wait: later calls of the same kind do not go out to earn the same 429. */
405
+ #noteRefusal(wire, scope, retryAfterSeconds) {
406
+ if (!scope || !retryAfterSeconds || NEVER_HELD_BACK.has(scope))
407
+ return;
408
+ const budget = HEADER_OF_SCOPE[scope] ?? scope;
409
+ const now = Date.now();
410
+ this.#paceOf(budget, wire).hold(this.#holds(budget, wire), { until: now + retryAfterSeconds * 1000, budget, learnedAt: now });
411
+ }
195
412
  async #attempts(wire) {
196
413
  for (let attempt = 1;; attempt++) {
197
414
  await this.#pace(wire);
@@ -234,7 +451,7 @@ class Core {
234
451
  continue;
235
452
  }
236
453
  release();
237
- this.#notePace(res);
454
+ this.#notePace(res, wire);
238
455
  this.#emit({ type: "response", operation: wire.operation, status: res.status, attempt, ms: Date.now() - started });
239
456
  if (res.ok)
240
457
  return json && typeof json === "object" ? json.data : undefined;
@@ -242,6 +459,7 @@ class Core {
242
459
  const code = typeof data.code === "string" ? data.code : `HTTP_${res.status}`;
243
460
  const headerSeconds = Number(res.headers.get("retry-after"));
244
461
  const retryAfter = Number.isFinite(headerSeconds) && headerSeconds > 0 ? headerSeconds : typeof data.retryAfterSeconds === "number" ? data.retryAfterSeconds : undefined;
462
+ const scope = typeof data.scope === "string" ? data.scope : undefined;
245
463
  // What passes with time: a used-up budget, a fault on ZimmerStack's side, a duplicate of a request
246
464
  // still running. Every other answer is a verdict on the request itself.
247
465
  const passesWithTime = res.status === 429 || res.status >= 500 || code === "IDEMPOTENCY_IN_FLIGHT";
@@ -251,21 +469,41 @@ class Core {
251
469
  message: typeof json?.message === "string" && json.message ? json.message : `${wire.operation} answered ${res.status}`,
252
470
  operation: wire.operation,
253
471
  details: data.details,
254
- scope: typeof data.scope === "string" ? data.scope : undefined,
472
+ scope,
255
473
  retryAfterSeconds: retryAfter,
256
474
  retryable: passesWithTime,
257
475
  });
258
476
  if (KEY_IS_DEAD.has(code)) {
259
- this.#dead = error;
260
- throw error;
477
+ // A key the API does not know, whose own checksum does not hold: say so, it is the likeliest reason.
478
+ const refused = code === "API_KEY_INVALID" && this.keyHint
479
+ ? new ZimmerStackError({ status: error.status, code, message: `${error.message} ${this.keyHint}`, operation: wire.operation, details: error.details, retryable: false })
480
+ : error;
481
+ this.#dead = refused;
482
+ throw refused;
261
483
  }
484
+ if (res.status === 429)
485
+ this.#noteRefusal(wire, scope, retryAfter);
262
486
  // A 429 was refused before anything ran, so sending it again is always safe. A 5xx may have run.
263
487
  const safeToResend = res.status === 429 || code === "IDEMPOTENCY_IN_FLIGHT" || wire.resendable;
264
- // A long Retry-After (an hourly or daily budget, a pause) is not worth holding a request open for.
265
- if (!passesWithTime || !safeToResend || attempt > this.#maxRetries || (retryAfter ?? 0) > this.#maxWaitSeconds)
488
+ if (!passesWithTime || !safeToResend || attempt > this.#maxRetries)
489
+ throw error;
490
+ // A long Retry-After (an hour's or a day's budget, a pause) is held open only inside maxWaitSeconds;
491
+ // past that the refusal comes back with the time the budget frees, and an event says so.
492
+ if ((retryAfter ?? 0) * 1000 > this.#maxWaitMs(wire)) {
493
+ this.#emit({
494
+ type: "deferred",
495
+ operation: wire.operation,
496
+ scope,
497
+ retryAfterSeconds: retryAfter,
498
+ freesAt: new Date(Date.now() + retryAfter * 1000).toISOString(),
499
+ message: `${wire.operation} was refused${scope ? ` by the ${scope} budget` : ""}: it can pass in ${aboutHowLong(retryAfter * 1000)}. Send it again then.`,
500
+ });
266
501
  throw error;
502
+ }
267
503
  const waitMs = ((retryAfter ?? 2 ** (attempt - 1)) + Math.random()) * 1000;
268
504
  this.#emit({ type: "retry", operation: wire.operation, attempt, waitMs, reason: code });
505
+ if (waitMs > SHORT_WAIT_MS)
506
+ this.#lands(wire, scope, waitMs);
269
507
  await sleep(waitMs, wire.signal);
270
508
  }
271
509
  }
@@ -308,8 +546,9 @@ export class ZimmerStack {
308
546
  this.propertyId = propertyId;
309
547
  }
310
548
  /**
311
- * A software vendor's company key: the same client, acting on one hotel. Shares this client's pace,
312
- * so make as many as you have hotels.
549
+ * A software vendor's company key: the same client, acting on one hotel. Each hotel has its own queue
550
+ * of writes and its own pace, so one hotel's budget never holds up another's calls; what all your hotels
551
+ * share (your company's budget) is paced for all of them together. Make as many as you have hotels.
313
552
  *
314
553
  * @example
315
554
  * const { properties } = await zs.properties.list();
@@ -339,10 +578,15 @@ export class ZimmerStack {
339
578
  * const sync = await zs.request("GET /sync");
340
579
  */
341
580
  async request(operation, ...rest) {
342
- const args = (rest[0] ?? {});
343
581
  const meta = OPERATIONS[operation];
344
582
  if (!meta)
345
583
  throw new ZimmerStackUsageError(`"${operation}" is not an operation of the Connect API`);
584
+ return (await this.#call(operation, meta.idempotent || KEYED_WRITES.has(operation), rest[0] ?? {}));
585
+ }
586
+ /** One call of the API. `keyed`: the route keeps an idempotency key, so the write may be sent again after a lost answer. */
587
+ async #call(operation, keyed, args) {
588
+ if (args.beforeGoLive !== undefined && typeof args.beforeGoLive !== "boolean")
589
+ throw new ZimmerStackUsageError("beforeGoLive is true or false");
346
590
  const [method = "", template = ""] = operation.split(" ");
347
591
  const path = template.replace(/\{(\w+)\}/g, (_m, name) => {
348
592
  const value = args.path?.[name];
@@ -357,23 +601,39 @@ export class ZimmerStack {
357
601
  const headers = { authorization: this.#core.authorization(), accept: "application/json", "user-agent": `zimmerstack-connect-node/${SDK_VERSION}` };
358
602
  // Adding a hotel and removing one name no hotel in the header: the one to add does not exist yet, and the
359
603
  // one to remove is in the path. Listing them sends the header only when this client was made for one hotel.
360
- const aboutTheList = operation === "POST /properties" || operation === "DELETE /properties/{propertyId}";
604
+ // A company webhook endpoint belongs to the partner, not to a hotel: those routes read no hotel either.
605
+ // So are your links, your bills and your support tickets; and a hotel's keys name their hotel in the path.
606
+ const aboutTheList = operation === "POST /properties" || template.startsWith("/properties/") || COMPANY_ROUTES.some((prefix) => template === prefix || template.startsWith(prefix + "/"));
361
607
  const hotel = aboutTheList ? undefined : (this.propertyId ?? (operation === "GET /properties" ? undefined : this.#core.soleSandboxId));
362
608
  if (hotel)
363
609
  headers[PROPERTY_HEADER] = String(hotel);
610
+ if (args.beforeGoLive === true)
611
+ headers[BEFORE_GO_LIVE_HEADER] = "true";
364
612
  const body = args.body === undefined ? undefined : JSON.stringify(args.body);
365
613
  if (body !== undefined)
366
614
  headers["content-type"] = "application/json";
367
- if (meta.idempotent) {
615
+ if (keyed) {
368
616
  // One key per write, reused on every retry of it, so a write that timed out can never land twice.
369
617
  if (args.idempotencyKey !== undefined && !IDEMPOTENCY_SHAPE.test(args.idempotencyKey)) {
370
618
  throw new ZimmerStackUsageError("idempotencyKey must be 10 to 64 characters of A-Z a-z 0-9 _ -");
371
619
  }
372
620
  headers[IDEMPOTENCY_HEADER] = args.idempotencyKey ?? crypto.randomUUID();
373
621
  }
374
- const wire = { operation, method, url, headers, body, write: method !== "GET", resendable: method === "GET" || meta.idempotent, signal: args.signal };
622
+ const wire = {
623
+ operation,
624
+ method,
625
+ url,
626
+ headers,
627
+ body,
628
+ write: method !== "GET",
629
+ resendable: method === "GET" || keyed,
630
+ hotel: hotel ? String(hotel) : "",
631
+ cells: CELL_WRITES.has(operation) ? cellsOf(args.body?.updates ?? []) : 0,
632
+ maxWaitSeconds: args.maxWaitSeconds,
633
+ signal: args.signal,
634
+ };
375
635
  try {
376
- return (await this.#core.send(wire));
636
+ return await this.#core.send(wire);
377
637
  }
378
638
  catch (err) {
379
639
  // A company key that named no hotel. The API refused before anything ran, so sending again is safe.
@@ -391,7 +651,7 @@ export class ZimmerStack {
391
651
  });
392
652
  }
393
653
  // The same request (same idempotency key) naming the hotel, on its own copy of the headers.
394
- return (await this.#core.send({ ...wire, headers: { ...headers, [PROPERTY_HEADER]: String(sole) } }));
654
+ return await this.#core.send({ ...wire, hotel: String(sole), headers: { ...headers, [PROPERTY_HEADER]: String(sole) } });
395
655
  }
396
656
  }
397
657
  /**
@@ -493,6 +753,295 @@ export class ZimmerStack {
493
753
  /** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
494
754
  get: (options) => this.request("GET /property", options),
495
755
  };
756
+ limits = {
757
+ /**
758
+ * Every budget this key sits under, with what is left and when it refills: the key's, its hotel's and,
759
+ * on a company key, your company's, plus the budgets over an hour and a day with this hotel's own
760
+ * figures. Any key may call it, and reading uses up nothing but one request.
761
+ *
762
+ * You do not need it to stay inside the limits: the client paces itself from every answer. Use it to
763
+ * size a job before you start it, or to show a person why something waits.
764
+ *
765
+ * @example
766
+ * const { budgets, shield } = await zs.limits.get();
767
+ * const cells = shield?.budgets.find((b) => b.scope === "cells-day");
768
+ * if (cells?.remaining != null && cells.remaining < plannedCells) console.log(`Room again in ${cells.resetSeconds} s`);
769
+ */
770
+ get: (options) => this.request("GET /limits", options),
771
+ };
772
+ /* ── what this key did: its own request log ── */
773
+ requests = {
774
+ /**
775
+ * This key's own requests of the last 7 days, newest first: when, the route's pattern, the status, the
776
+ * error code, the address it came from, how long it took and the request id. Never a body, a query or a
777
+ * guest's data. Any key may call it. A company key reads every call made with it across its hotels, or
778
+ * one hotel's through `zs.forProperty(id)`.
779
+ *
780
+ * `since` defaults to the last 24 hours. `status` is one code ("429"), a family ("4xx") or "errors"
781
+ * (400 and above). Use it to answer "did my push arrive" yourself, and to look for an address that is
782
+ * not yours: that is the first sign of a leaked key.
783
+ *
784
+ * @example
785
+ * const { items } = await zs.requests.list({ status: "errors" });
786
+ * for (const r of items) console.log(r.at, r.method, r.route, r.status, r.errorCode, r.requestId);
787
+ */
788
+ list: (query, options) => this.request("GET /requests", { query, ...options }),
789
+ /**
790
+ * The same, page by page to the last one: every request since `since`, newest first.
791
+ *
792
+ * @example
793
+ * for await (const r of zs.requests.all({ status: "errors", since: yesterday })) count[r.errorCode ?? r.status]++;
794
+ */
795
+ all: (query, options) => this.#pages((cursor) => this.requests.list({ limit: 200, ...query, cursor }, options)),
796
+ };
797
+ /* ── the hotel's ordered event log: the webhooks are the nudge, this is the truth ── */
798
+ events = {
799
+ /**
800
+ * One page of the hotel's event log: every event a webhook can carry for it (OTA bookings, website
801
+ * bookings, channel alerts, drift), once, oldest first, starting after the sequence you pass. Each item
802
+ * is the webhook's own envelope with its `sequence`, so one parser serves both.
803
+ *
804
+ * Keep `nextAfter` as your place. `more: true` means ask again at once. When `earliestSequence` is more
805
+ * than one above the `after` you sent, the events in between are older than the log keeps (90 days):
806
+ * reconcile with `zs.channelBookings.all` and `zs.directBookings.all`, then carry on. Scope
807
+ * channel-bookings:read (the channel events) or direct-bookings:read (the website's). `all` does the paging.
808
+ *
809
+ * @example
810
+ * const page = await zs.events.list({ after: lastSequence });
811
+ */
812
+ list: (query, options) => this.request("GET /events", { query, ...options }),
813
+ /**
814
+ * Every event after a sequence you saved, in order, to the end of the log. Apply each one, then save its
815
+ * `sequence`: that is your place, and the next run starts from it. A webhook only tells you there is
816
+ * something to read; nothing depends on it having arrived, or on the order deliveries arrived in.
817
+ *
818
+ * `onGap` is called once, before the first event, when the log no longer holds what follows `after`
819
+ * (events are kept 90 days): read the bookings again with `zs.channelBookings.all({ since })` and
820
+ * `zs.directBookings.all({ since })` before you go on. A first run with `after: 0` is told too.
821
+ *
822
+ * @example
823
+ * for await (const event of zs.events.all({ after: await loadPlace() })) {
824
+ * await apply(event); // dedupe on event.id if your apply is not idempotent
825
+ * await savePlace(event.sequence);
826
+ * }
827
+ */
828
+ all: (query, options) => this.#eventsAfter(query?.after ?? 0, query?.limit, options),
829
+ };
830
+ async *#eventsAfter(after, limit, options) {
831
+ if (!Number.isInteger(after) || after < 0)
832
+ throw new ZimmerStackUsageError("zs.events.all needs the last sequence you applied as its after: a whole number, 0 to read from the beginning of what is kept");
833
+ let place = after;
834
+ let first = true;
835
+ for (;;) {
836
+ const page = await this.events.list({ after: place, limit: limit ?? 100 }, { signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds });
837
+ if (first && page.earliestSequence !== null && page.earliestSequence > after + 1)
838
+ options?.onGap?.({ after, earliestSequence: page.earliestSequence });
839
+ first = false;
840
+ yield* page.items;
841
+ // nextAfter moves past events this key's scopes do not show, so an empty page can still move the place.
842
+ if (!page.more || page.nextAfter <= place)
843
+ return;
844
+ place = page.nextAfter;
845
+ }
846
+ }
847
+ /* ── your company webhook endpoints (a software partner's company key, scope webhooks:manage) ── */
848
+ webhookEndpoints = {
849
+ /** Your company webhook endpoints of this key's mode (a live key: live ones; a test key: test ones), each with its health. */
850
+ list: (options) => this.request("GET /webhook-endpoints", options),
851
+ /**
852
+ * Create a company webhook endpoint. `dataAck: true` confirms that guest booking details will be sent
853
+ * to that address. Guest contact (phone, email) is off unless `includeGuestContact` is true.
854
+ *
855
+ * THE ANSWER'S `secret` IS SHOWN ONCE: store it in your server's settings at once (never in code or a
856
+ * log). No call reads it back; `rotateSecret` makes a new one. The call carries an idempotency key, so
857
+ * a retry after a lost answer gets the same endpoint and the same secret, never a second endpoint.
858
+ *
859
+ * @example
860
+ * const { endpoint, secret } = await zs.webhookEndpoints.create({ url: "https://pms.example/zimmerstack", dataAck: true });
861
+ */
862
+ create: (body, options) => this.request("POST /webhook-endpoints", { body, ...options }),
863
+ get: (endpointId, options) => this.request("GET /webhook-endpoints/{endpointId}", { path: { endpointId }, ...options }),
864
+ /** Change an endpoint: its address, its event types, the notify email or the guest-contact switch. Send only what changes. */
865
+ update: (endpointId, body, options) => this.request("PATCH /webhook-endpoints/{endpointId}", { path: { endpointId }, body, ...options }),
866
+ /**
867
+ * Delete an endpoint for good; its deliveries and their log go with it. THERE IS NO UNDO: call it when
868
+ * a person chose to, never from a loop or a cleanup script. To stop events for a while, `pause`.
869
+ */
870
+ delete: (endpointId, options) => this.request("DELETE /webhook-endpoints/{endpointId}", { path: { endpointId }, ...options }),
871
+ /** Hold an endpoint's events (before planned downtime). Nothing is dropped: `resume` sends them, oldest first. */
872
+ pause: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/pause", { path: { endpointId }, ...options }),
873
+ /** Resume a paused endpoint. `heldEvents` says how many held events are going out now. */
874
+ resume: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/resume", { path: { endpointId }, ...options }),
875
+ /**
876
+ * A new signing secret, in this answer only. Both secrets sign every delivery until `previousExpiresAt`
877
+ * (24 hours), so switch your receiver to the new one inside that day and nothing is lost.
878
+ */
879
+ rotateSecret: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/rotate-secret", { path: { endpointId }, ...options }),
880
+ /**
881
+ * Send the endpoint a signed sample of any event type (`zimmerstack.ping` when none is named). The
882
+ * sample says `mode: "test"` and has no `sequence`: it is in no log. On a sandbox, make a real event
883
+ * instead with `zs.sandbox.bookings.create` and `zs.sandbox.syncEvents.create`.
884
+ *
885
+ * @example
886
+ * const { deliveryId } = await zs.webhookEndpoints.test(endpoint.id, { eventType: "channel.booking.created" });
887
+ * const delivery = await zs.webhookEndpoints.deliveries.get(endpoint.id, deliveryId); // what your receiver answered
888
+ */
889
+ test: (endpointId, body = {}, options) => this.request("POST /webhook-endpoints/{endpointId}/test", { path: { endpointId }, body, ...options }),
890
+ /**
891
+ * Queue again every subscribed event since an instant that failed or never had a delivery: at most 90
892
+ * days back and 10,000 events a run (`truncated: true` means run it again for the rest). Reading the
893
+ * log with `zs.events.all` is the other way to catch up, and needs no endpoint.
894
+ */
895
+ recover: (endpointId, since, options) => this.request("POST /webhook-endpoints/{endpointId}/recover", { path: { endpointId }, body: { since: since instanceof Date ? since.toISOString() : since }, ...options }),
896
+ deliveries: {
897
+ /** An endpoint's delivery log, newest first. Filter with status, eventType, mode (TEST: what a test made), from and to. */
898
+ list: (endpointId, query, options) => this.request("GET /webhook-endpoints/{endpointId}/deliveries", { path: { endpointId }, query, ...options }),
899
+ /** One delivery: the body as it was sent, and every attempt with what your receiver answered. */
900
+ get: (endpointId, deliveryId, options) => this.request("GET /webhook-endpoints/{endpointId}/deliveries/{deliveryId}", { path: { endpointId, deliveryId }, ...options }),
901
+ /** Send one delivery again: the same event, the same id and sequence. */
902
+ redeliver: (endpointId, deliveryId, options) => this.request("POST /webhook-endpoints/{endpointId}/deliveries/{deliveryId}/redeliver", { path: { endpointId, deliveryId }, ...options }),
903
+ },
904
+ };
905
+ /* ── one-time connect links: the hotel's own person connects a booking site (company key, scope channels:connect) ── */
906
+ connectLinks = {
907
+ /** Your connect links, newest first; `propertyId` narrows them to one hotel. */
908
+ list: (query, options) => this.request("GET /connect-links", { query, ...options }),
909
+ /**
910
+ * Make a one-time link for ONE hotel and ONE booking site. Send the answer's `url` to the hotel's own
911
+ * person: on ZimmerStack's hosted page they sign in to the booking site, confirm every room and rate
912
+ * match and press Start selling. Your software never holds a booking site's password, and the call
913
+ * takes none. You hear `channel.connect.completed`, or `channel.connect.expired` if the link ran out.
914
+ *
915
+ * THE `url` IS SHOWN ONCE: it is in this answer only, and null on a replay of the same request
916
+ * (`shownOnce(answer)` returns it or says what to do). `hotelStep` is what the hotel does at the booking
917
+ * site first, for your own screen or message. A LIVE key only: a sandbox has no booking site, so a test
918
+ * key is refused (LIVE_KEY_REQUIRED). The hotel is `propertyId` in the body; `forProperty` is not read.
919
+ *
920
+ * @example
921
+ * const made = await zs.connectLinks.create({ propertyId: 61, channel: "bookingcom", returnUrl: "https://pms.example/hotels/61" });
922
+ * await sendToTheHotel(shownOnce(made), made.hotelStep);
923
+ */
924
+ create: (body, options) => this.request("POST /connect-links", { body, ...options }),
925
+ /** Where one link stands: pending, opened, completed, expired or revoked. Never its address again. */
926
+ get: (linkId, options) => this.request("GET /connect-links/{linkId}", { path: { linkId }, ...options }),
927
+ /** Withdraw a link. A page that is open stops at its next step. */
928
+ revoke: (linkId, options) => this.request("POST /connect-links/{linkId}/revoke", { path: { linkId }, ...options }),
929
+ };
930
+ /* ── going live: is this hotel ready for your software to be its source of truth ── */
931
+ readiness = {
932
+ /**
933
+ * Is this hotel ready for your software to be its source of truth? Four checks, each passed or not,
934
+ * with a sentence and what to do: it is on the channel manager, every room type and rate plan is
935
+ * linked, ZimmerStack's own pricing will not overwrite your prices, and nothing stale would go out
936
+ * (the record matches the channels, or you sent a price for every rate plan and night of the year
937
+ * first). Room counts are no part of it: the report only says how many room-type nights your software
938
+ * has not written yet. Any key may read it, as often as you like. A hotel you added yourself is live
939
+ * from the start (`live: true`).
940
+ *
941
+ * @example
942
+ * const report = await zs.forProperty(61).readiness.get();
943
+ * for (const check of report.checks) if (!check.passed) console.log(check.id, check.summary, check.action);
944
+ */
945
+ get: (options) => this.request("GET /readiness", options),
946
+ /**
947
+ * Make your software this hotel's source of truth: from then on every price, stay rule and room count
948
+ * you send is pushed to its booking sites, and what you sent ahead (`beforeGoLive: true`) goes out.
949
+ * Scope ari:write. Not ready is 409 NOT_READY with the checks that did not pass in `error.details`;
950
+ * that refusal is never kept under an idempotency key, so call again once they pass. Already live
951
+ * answers `replay: true`. Call it when a person decided to; only ZimmerStack support switches a hotel back.
952
+ *
953
+ * @example
954
+ * const hotel = zs.forProperty(61);
955
+ * await hotel.rates.set(aYearOfPrices, { beforeGoLive: true }); // stored, and waits
956
+ * // Room counts are not sent ahead: until go-live a count may only lower what is on sale (it goes out at once), and a higher one is refused.
957
+ * if ((await hotel.readiness.get()).ready) await hotel.readiness.goLive();
958
+ * await hotel.availability.set(aYearOfCounts); // right after going live: your room counts
959
+ */
960
+ goLive: (options) => this.request("POST /go-live", options),
961
+ };
962
+ /* ── the keys you made on a hotel (company key, scope keys:manage) ── */
963
+ hotelKeys = {
964
+ /** The keys YOU made on a hotel you added. The hotel's own keys are its owner's and are never listed here. */
965
+ list: (propertyId, options) => this.request("GET /properties/{propertyId}/keys", { path: { propertyId }, ...options }),
966
+ /**
967
+ * Mint a key on a hotel you added (or, with a test key, on one of your sandboxes): any scope a
968
+ * hotel's own key may hold, never a company key's own.
969
+ *
970
+ * THE ANSWER'S `key` IS SHOWN ONCE: store it in the server's settings at once, never in code or a log.
971
+ * It is null on a replay of the same request: `shownOnce(answer)` returns it or says to rotate.
972
+ *
973
+ * @example
974
+ * const minted = await zs.hotelKeys.create(61, { name: "Night audit job", scopes: ["ari:read", "channel-bookings:read"] });
975
+ * await vault.put(`zimmerstack/hotel-61`, shownOnce(minted));
976
+ */
977
+ create: (propertyId, body, options) => this.request("POST /properties/{propertyId}/keys", { path: { propertyId }, body, ...options }),
978
+ /**
979
+ * A new key with the same name, scopes, addresses and expiry, its secret shown once; the old key keeps
980
+ * answering for 24 hours (`retired.retireAt`), so switch inside that day and nothing stops.
981
+ */
982
+ rotate: (propertyId, keyId, options) => this.request("POST /properties/{propertyId}/keys/{keyId}/rotate", { path: { propertyId, keyId }, ...options }),
983
+ /** Revoke a key you made: it stops at once. `reason` (3 to 500 characters) is written on the key and on the hotel's activity log. */
984
+ revoke: (propertyId, keyId, body, options) => this.request("POST /properties/{propertyId}/keys/{keyId}/revoke", { path: { propertyId, keyId }, body, ...options }),
985
+ };
986
+ /* ── your bills, read only (company key, scope billing:read) ── */
987
+ billing = {
988
+ /**
989
+ * Your bills at a glance: what is owed, the one-time onboarding fee, your hotel quota and what opens
990
+ * the next level, what is left of money paid ahead, the days of an unpaid invoice, and `atCost`: what
991
+ * the channel manager charged above its included room types and rate plans for a hotel whose limit
992
+ * ZimmerStack raised. An at-cost line is a record: `status` says RECORDED until ZimmerStack's team has
993
+ * put it on one of your invoices (INVOICED) or waived it. Nothing here pays or changes anything.
994
+ */
995
+ get: (options) => this.request("GET /billing", options),
996
+ /** Your 24 most recent issued invoices, newest first, each before and after tax with its lines, then the recent payments. */
997
+ invoices: (options) => this.request("GET /billing/invoices", options),
998
+ /**
999
+ * What your next monthly invoice is made of, hotel by hotel, read today: the rooms counted, the room
1000
+ * band, the price list, the unit price. The invoice reads rooms, prices and the exchange rate again on
1001
+ * the day it is made, and that is the bill.
1002
+ */
1003
+ nextInvoice: (options) => this.request("GET /billing/next-invoice", options),
1004
+ };
1005
+ /* ── support tickets (company key, scope support:write) ── */
1006
+ supportTickets = {
1007
+ /** Your tickets of this key's mode, newest first. `status`: OPEN (waiting for ZimmerStack), ANSWERED (waiting for you), CLOSED. */
1008
+ list: (query, options) => this.request("GET /support-tickets", { query, ...options }),
1009
+ /** The same, page by page to the last one. */
1010
+ all: (query, options) => this.#pages((cursor) => this.supportTickets.list({ limit: 100, ...query, cursor }, options)),
1011
+ /**
1012
+ * Open a support ticket. `severity` follows from the hotels you name: `many_hotels` needs two or more
1013
+ * `propertyIds` or `allProperties: true`, `one_hotel` exactly one, `question` any or none. ZimmerStack
1014
+ * attaches what its own records show at that moment (`diagnostic`: ids, counts, states and times), so
1015
+ * never paste a key, a secret or a guest's details into `message`. It opens whatever your
1016
+ * integration's standing. The call carries an idempotency key: a retry never opens a second ticket.
1017
+ *
1018
+ * @example
1019
+ * const ticket = await zs.supportTickets.create({ severity: "many_hotels", subject: "Prices are not going out", message: "Since 08:10 UTC every PUT /rates is accepted and its batch stays pending.", propertyIds: [61, 62, 70] });
1020
+ * console.log(ticket.id, ticket.firstReply.target, ticket.firstReply.dueAt);
1021
+ */
1022
+ create: (body, options) => this.request("POST /support-tickets", { body, ...options }),
1023
+ /** One ticket: its thread, oldest first, and the diagnostic taken when it opened. */
1024
+ get: (ticketId, options) => this.request("GET /support-tickets/{ticketId}", { path: { ticketId }, ...options }),
1025
+ /** Write again on a ticket; it waits for ZimmerStack from then. A closed ticket takes no more messages (SUPPORT_TICKET_CLOSED): open a new one and name the old one. */
1026
+ reply: (ticketId, message, options) => this.request("POST /support-tickets/{ticketId}/messages", { path: { ticketId }, body: { message }, ...options }),
1027
+ /** Close your own ticket. */
1028
+ close: (ticketId, options) => this.request("POST /support-tickets/{ticketId}/close", { path: { ticketId }, ...options }),
1029
+ };
1030
+ /* ── is something wrong on ZimmerStack's side ── */
1031
+ status = {
1032
+ /**
1033
+ * The components (the API, bookings coming in, prices and availability going out, each booking site),
1034
+ * each operational or named in an open incident, and the incidents that touch YOUR hotels: the open
1035
+ * ones and those resolved in the last 7 days. Any key. A company key reads all its hotels', or one
1036
+ * hotel's through `zs.forProperty(id)`. An incident is opened and closed by ZimmerStack's staff:
1037
+ * `operational` means nobody has reported a problem, not that a monitor measured none.
1038
+ *
1039
+ * @example
1040
+ * const { overall, incidents } = await zs.status.get();
1041
+ * for (const incident of incidents.open) console.log(incident.title, incident.status, incident.updates[0]?.message);
1042
+ */
1043
+ get: (options) => this.request("GET /status", options),
1044
+ };
496
1045
  /* ── room types and rate plans ── */
497
1046
  catalog = {
498
1047
  /** Room types and rate plans, with the numeric ids every write uses. */
@@ -618,10 +1167,25 @@ export class ZimmerStack {
618
1167
  const accepted = [];
619
1168
  for (const [i, part] of parts.entries()) {
620
1169
  const idempotencyKey = options?.idempotencyKey === undefined ? undefined : parts.length > 1 ? `${options.idempotencyKey}-${i + 1}` : options.idempotencyKey;
621
- accepted.push(await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal }));
1170
+ // The body carries no dryRun, so the answer is the accepted write, never a preview.
1171
+ const answer = await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds, beforeGoLive: options?.beforeGoLive });
1172
+ accepted.push(answer);
622
1173
  }
623
1174
  return accepted;
624
1175
  }
1176
+ /**
1177
+ * The same request with `dryRun: true`: checked and judged exactly as the write, and nothing is written.
1178
+ * One preview per request the write would be split into. No idempotency key of yours is taken: the
1179
+ * server keeps none for a dry run, so the real write may carry any key afterwards.
1180
+ */
1181
+ async #previewAll(operation, updates, options) {
1182
+ const previews = [];
1183
+ for (const part of chunk(updates)) {
1184
+ const answer = await this.request(operation, { body: { dryRun: true, updates: part }, signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds, beforeGoLive: options?.beforeGoLive });
1185
+ previews.push(previewOnly(operation, answer));
1186
+ }
1187
+ return previews;
1188
+ }
625
1189
  availability = {
626
1190
  /** Rooms left to sell per room type per night, as ZimmerStack's record holds them. Up to 500 days. */
627
1191
  get: (range, options) => this.request("GET /availability", { query: range, ...options }),
@@ -630,14 +1194,63 @@ export class ZimmerStack {
630
1194
  * ZimmerStack's record (one answer per request sent; a large write is split for you).
631
1195
  */
632
1196
  set: (updates, options) => this.#writeAll("PUT /availability", updates, options),
1197
+ /**
1198
+ * What `set` WOULD do with these updates, and nothing is written, queued or sent. The answer is a
1199
+ * `WritePreview` (`dryRun: true`), never a `WriteAccepted`: `verdict` (would-write, nothing-to-write,
1200
+ * would-refuse with the refusal a real write would get now), the ranges that would change, the ones
1201
+ * already held, the ones held after a refusal, and the same `notices` the real write carries.
1202
+ *
1203
+ * It is not a free read: it spends the minute budgets like the write it previews (one request, one
1204
+ * write, the same cells), and under a test runner a live key may not send it, like any write. It
1205
+ * counts nothing against the hour and day budgets. To read the calendar use `get`.
1206
+ *
1207
+ * @example
1208
+ * const [preview] = await zs.availability.dryRun([{ roomTypeId: 412, dateFrom: "2026-12-31", dateTo: "2026-12-31", available: 0 }]);
1209
+ * if (preview?.verdict === "would-write") await zs.availability.set(updates);
1210
+ */
1211
+ dryRun: (updates, options) => this.#previewAll("PUT /availability", updates, options),
1212
+ /**
1213
+ * Close one room type on a range of nights EVERYWHERE, in one call: its room count goes to 0 and
1214
+ * stop-sell is switched on for every one of its rate plans. You do not need to know the hotel's
1215
+ * plans. The count closes every rate of the room on every booking site; the stop-sell keeps it closed
1216
+ * when a cancellation puts a room back.
1217
+ *
1218
+ * READ `notReached`: every plan that is not linked or that no booking site sells, and the one thing no
1219
+ * stop-sell reaches, a rate a booking site links on its own side (only the count closes that).
1220
+ * `batches` names the writes to watch land (`zs.batches.wait`). A close is accepted while your
1221
+ * integration is paused or out of budget (`lane: true`): a hotel must never oversell.
1222
+ *
1223
+ * @example
1224
+ * const closed = await zs.availability.close({ roomTypeId: 412, dateFrom: "2026-12-30", dateTo: "2027-01-02" });
1225
+ * for (const gap of closed.notReached) console.log(gap.what, gap.reason, gap.message);
1226
+ */
1227
+ close: async (body, options) => (await this.request("POST /availability/close", { body: realOnly("close", body), ...options })),
1228
+ /** What `close` would do, and nothing is done: the same answer with `dryRun: true` and no batches. Spends the minute budgets like the close. */
1229
+ closeDryRun: async (body, options) => previewOnly("POST /availability/close", (await this.request("POST /availability/close", { body: { ...body, dryRun: true }, ...options }))),
1230
+ /**
1231
+ * Undo exactly what `close` did on these nights, and nothing else: the stop-sell is lifted on the plans
1232
+ * the close switched on (a plan that was stop-sold before stays stopped), and each night gets back the
1233
+ * count it held before. Pass `available` to put your own count on sale instead: only your software
1234
+ * knows how many rooms are free now. A night whose count changed after the close is left as it is, and
1235
+ * a night the close had not closed is skipped (`skippedNights`). A reopen opens inventory, so it waits
1236
+ * like any other write while your integration is paused.
1237
+ *
1238
+ * @example
1239
+ * const reopened = await zs.availability.reopen({ roomTypeId: 412, dateFrom: "2026-12-30", dateTo: "2027-01-02", available: 3 });
1240
+ */
1241
+ reopen: async (body, options) => (await this.request("POST /availability/reopen", { body: realOnly("reopen", body), ...options })),
1242
+ /** What `reopen` would do, and nothing is done. */
1243
+ reopenDryRun: async (body, options) => previewOnly("POST /availability/reopen", (await this.request("POST /availability/reopen", { body: { ...body, dryRun: true }, ...options }))),
633
1244
  };
634
1245
  rates = {
635
- /** Nightly prices per rate plan, in MINOR units (`rateMinor`), before any channel's modifier. */
1246
+ /** Nightly prices per rate plan, before any channel's modifier: `rate` (a decimal string in major units, with `currency` and `decimals`) beside `rateMinor` (hundredths of the major unit, in every currency). */
636
1247
  get: (range, options) => this.request("GET /rates", { query: range, ...options }),
637
1248
  /**
638
- * Set nightly prices in MAJOR units over date ranges (4500 = ₹4,500.00). `currency` may be left
639
- * out: the hotel's own is filled in. To close a night use `restrictions.set` with stopSell,
640
- * never a zero price.
1249
+ * Set nightly prices in MAJOR units over date ranges: a number or a decimal string with the
1250
+ * currency's own decimals (4500.5 or "4500.50"). `currency` may be left out: the hotel's own is
1251
+ * filled in. What could not be kept as sent is named in the answer's `rounded` list. Never a zero
1252
+ * price to stop selling: `restrictions.set` with stopSell closes one rate plan on a night, and
1253
+ * `availability.set` with 0 rooms closes the room type on every booking site.
641
1254
  */
642
1255
  set: async (updates, options) => {
643
1256
  if (updates.length === 0)
@@ -645,6 +1258,17 @@ export class ZimmerStack {
645
1258
  const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
646
1259
  return this.#writeAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
647
1260
  },
1261
+ /**
1262
+ * What `set` WOULD do with these prices, and nothing is written: a `WritePreview` per request, with what
1263
+ * would change, what is already held, what would be rounded and the notices (a plan no booking site
1264
+ * sells, an engine that will reprice). See `zs.availability.dryRun` for what it costs.
1265
+ */
1266
+ dryRun: async (updates, options) => {
1267
+ if (updates.length === 0)
1268
+ return [];
1269
+ const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
1270
+ return this.#previewAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
1271
+ },
648
1272
  /**
649
1273
  * Send the hotel's prices to its channels again, unchanged, so nights already there pick the
650
1274
  * current modifiers up. A hotel may ask a few times a day: make it a deliberate button, never
@@ -657,6 +1281,36 @@ export class ZimmerStack {
657
1281
  get: (range, options) => this.request("GET /restrictions", { query: range, ...options }),
658
1282
  /** Set stay rules over date ranges: stopSell, closedToArrival, closedToDeparture, minStayArrival, minStayThrough, maxStay. */
659
1283
  set: (updates, options) => this.#writeAll("PUT /restrictions", updates, options),
1284
+ /**
1285
+ * What `set` WOULD do with these stay rules, and nothing is written. The notices are the point: a
1286
+ * stop-sell on one rate plan answers ROOM_STILL_ON_SALE when the room keeps selling through its other
1287
+ * plans. See `zs.availability.dryRun` for what it costs.
1288
+ *
1289
+ * @example
1290
+ * const [preview] = await zs.restrictions.dryRun([{ ratePlanId: 901, dateFrom: "2026-12-31", dateTo: "2026-12-31", stopSell: true }]);
1291
+ * for (const notice of noticesOf(preview)) console.log(notice.code, notice.message, notice.action);
1292
+ */
1293
+ dryRun: (updates, options) => this.#previewAll("PUT /restrictions", updates, options),
1294
+ };
1295
+ /* ── one night's whole story ── */
1296
+ explain = {
1297
+ /**
1298
+ * Explain one night of one room type (optionally one of its rate plans), from ZimmerStack's record:
1299
+ * what your software last sent, what the record holds and who set it, what the channel manager was
1300
+ * last seen holding, every send still on file and how it ended, a held value in the channel manager's
1301
+ * own words, which connections sell each plan, the rules in force, the bookings that moved the count
1302
+ * (ids and times, never a guest), and `summary`: the same in plain sentences, for a person.
1303
+ *
1304
+ * What it cannot know: it reads the channel manager's copy as last seen, never a booking site's own
1305
+ * screen. `seenAt: null` means that night was never read back; `lastSent: null` means the write is older
1306
+ * than the ones whose values are kept (`searched` says how far it looked); `channels.known: false` means
1307
+ * the hotel's connections have not been read yet. Scope ari:read; it calls no channel, so ask freely.
1308
+ *
1309
+ * @example
1310
+ * const night = await zs.explain.night({ roomTypeId: 412, date: "2026-12-31" });
1311
+ * for (const sentence of night.summary) console.log(sentence);
1312
+ */
1313
+ night: (query, options) => this.request("GET /explain", { query, ...options }),
660
1314
  };
661
1315
  /* ── has it reached the channels? ── */
662
1316
  sync = {
@@ -765,12 +1419,16 @@ export class ZimmerStack {
765
1419
  cancel: (bookingId, body = {}, options) => this.request("POST /direct-bookings/{bookingId}/cancel", { path: { bookingId }, body, ...options }),
766
1420
  };
767
1421
  /** Follow a booking list's `nextCursor` to its last page. */
768
- async *#allPages(read) {
1422
+ #allPages(read) {
1423
+ return this.#pages(read);
1424
+ }
1425
+ /** Follow any list's `nextCursor` to its last page. A list that says `more: false` is at its end, whatever cursor it hands back. */
1426
+ async *#pages(read) {
769
1427
  let cursor;
770
1428
  do {
771
1429
  const page = await read(cursor);
772
1430
  yield* page.items;
773
- cursor = page.nextCursor ?? undefined;
1431
+ cursor = page.more === false ? undefined : (page.nextCursor ?? undefined);
774
1432
  } while (cursor);
775
1433
  }
776
1434
  /* ── the sandbox (zsk_test_ keys only) ── */
@@ -785,6 +1443,44 @@ export class ZimmerStack {
785
1443
  create: (body, options) => this.request("POST /sandbox/bookings", { body, ...options }),
786
1444
  cancel: (bookingId, options) => this.request("POST /sandbox/bookings/{bookingId}/cancel", { path: { bookingId }, ...options }),
787
1445
  modify: (bookingId, body, options) => this.request("POST /sandbox/bookings/{bookingId}/modify", { path: { bookingId }, body, ...options }),
1446
+ /**
1447
+ * Pretend the hotel recorded that a WEBSITE booking's guest did not arrive (one made with
1448
+ * `otaName: "Website"`): the stay and its rooms go NOSHOW, the nights come back on the sandbox's
1449
+ * availability, and your endpoint receives the real `direct.booking.modified`. `{ undo: true }` takes
1450
+ * it back. The booking is not cancelled.
1451
+ */
1452
+ noShow: (bookingId, body = {}, options) => this.request("POST /sandbox/bookings/{bookingId}/no-show", { path: { bookingId }, body, ...options }),
1453
+ },
1454
+ syncEvents: {
1455
+ /**
1456
+ * Pretend a channel problem, or its end: the real `channel.sync.alert` or `channel.sync.recovered`
1457
+ * to your endpoint, and a line in the event log. `event` says which problem (rate_error when left
1458
+ * out); the problem sits on one of the sandbox's pretend channels and `zs.channels.list()` shows it
1459
+ * until a recovered clears it.
1460
+ *
1461
+ * @example
1462
+ * await zs.sandbox.syncEvents.create({ type: "channel.sync.alert", event: "disconnect_channel" });
1463
+ * await zs.sandbox.syncEvents.create({ type: "channel.sync.recovered" });
1464
+ */
1465
+ create: (body, options) => this.request("POST /sandbox/sync-events", { body, ...options }),
1466
+ },
1467
+ faults: {
1468
+ /** The fault in force on this sandbox's pretend channel; `active: false` when there is none. */
1469
+ get: (options) => this.request("GET /sandbox/faults", options),
1470
+ /**
1471
+ * Make the sandbox's pretend channel misbehave, to watch your software meet a bad day: `refuse` (the
1472
+ * next `values` nights of prices or stay rules are refused, with your `message` as the channel
1473
+ * manager's words), `throttle` ("too many requests" for `minutes`) or `outage` (no answer for
1474
+ * `minutes`). One fault at a time: a new one replaces it. Prices and stay rules only: room counts land
1475
+ * as before. The answer's `watch` says what to do next and what you should then see, step by step.
1476
+ *
1477
+ * @example
1478
+ * const fault = await zs.sandbox.faults.set({ kind: "refuse", values: 2, message: "Rate is below the channel's minimum" });
1479
+ * for (const step of fault.watch) console.log(step);
1480
+ */
1481
+ set: (body, options) => this.request("POST /sandbox/faults", { body, ...options }),
1482
+ /** End the fault: the pretend channel answers normally from the next push. Values already held stay held until a different value is sent. */
1483
+ clear: (options) => this.request("DELETE /sandbox/faults", options),
788
1484
  },
789
1485
  };
790
1486
  /* ── the rate grid ── */