@zimmerstack/connect 0.7.0 → 0.9.1

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 +305 -25
  2. package/README.md +572 -56
  3. package/dist/cjs/client.d.ts +528 -13
  4. package/dist/cjs/client.js +778 -46
  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 +2873 -203
  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 +528 -13
  26. package/dist/esm/client.js +776 -46
  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 +2873 -203
  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 +95 -11
  40. package/dist/esm/mcp/reference.generated.js +5741 -1008
  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 +2 -2
@@ -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,21 +206,24 @@ 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") {
94
- throw new ZimmerStackUsageError("@zimmerstack/connect runs on a server only. A key in a browser or a mobile app can be read by anyone and can change a hotel's prices on every channel: call your own server from here, and ZimmerStack from your server (https://docs.zimmerstack.com/sdk#no-server shows the smallest one). If a key was built into this page, anyone can read it now: revoke it and make a new one.");
226
+ throw new ZimmerStackUsageError("@zimmerstack/connect runs on a server only. A key in a browser or a mobile app can be read by anyone and can change a hotel's prices on every channel: call your own server from here, and ZimmerStack from your server (https://docs.zimmerstack.com/guides/node-package#no-server shows the smallest one). If a key was built into this page, anyone can read it now: revoke it and make a new one.");
95
227
  }
96
228
  const key = options.apiKey ?? env("ZIMMERSTACK_CONNECT_KEY");
97
229
  if (!key)
@@ -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
  /**
@@ -443,6 +703,35 @@ export class ZimmerStack {
443
703
  this.#forgetWhichHotels();
444
704
  return created;
445
705
  },
706
+ /**
707
+ * Change a hotel YOU ADDED: its name, its address, or both. A company key with the scope properties:write.
708
+ *
709
+ * Send only what changes: `name`, and under `address` any of `line1`, `city`, `state` and `postalCode`. A
710
+ * field you leave out stays as it is. It never changes the hotel's country, currency, time zone, owner or
711
+ * tax id (sending one is refused with VALIDATION), and it changes the hotel's record in ZimmerStack, not
712
+ * the name of its listing on a booking site.
713
+ *
714
+ * The answer is the hotel with its `address` and `changed`: the fields whose stored value moved. An empty
715
+ * `changed` means everything you sent was already stored. A hotel whose owner let you in is refused with
716
+ * PROPERTY_NOT_CHANGEABLE: its owner changes it. With a test key it changes one of your sandboxes, whose
717
+ * name keeps its ending, "(sandbox)". Safe to retry: the call carries an idempotency key.
718
+ *
719
+ * After a new name, `zs.properties.delete` wants that new name in `confirm`.
720
+ *
721
+ * @example
722
+ * const hotel = await zs.properties.update(61, { name: "Sea Breeze Suites", address: { line1: "14 Beach Road" } });
723
+ * hotel.changed; // ["name", "address.line1"]
724
+ */
725
+ update: async (propertyId, changes, options) => {
726
+ if (!Number.isInteger(propertyId) || propertyId <= 0) {
727
+ throw new ZimmerStackUsageError("zs.properties.update needs the hotel's numeric id (zs.properties.list() names them)");
728
+ }
729
+ const sent = changes?.name !== undefined || Object.values(changes?.address ?? {}).some((value) => value !== undefined);
730
+ if (!sent) {
731
+ throw new ZimmerStackUsageError("zs.properties.update needs something to change: name, or line1, city, state or postalCode under address.");
732
+ }
733
+ return this.request("PATCH /properties/{propertyId}", { path: { propertyId }, body: changes, ...options });
734
+ },
446
735
  /**
447
736
  * Remove a hotel YOU ADDED, for good. A company key with the scope properties:write.
448
737
  *
@@ -493,6 +782,300 @@ export class ZimmerStack {
493
782
  /** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
494
783
  get: (options) => this.request("GET /property", options),
495
784
  };
785
+ limits = {
786
+ /**
787
+ * Every budget this key sits under, with what is left and when it refills: the key's, its hotel's and,
788
+ * on a company key, your company's, plus the budgets over an hour and a day with this hotel's own
789
+ * figures. Any key may call it, and reading uses up nothing but one request.
790
+ *
791
+ * You do not need it to stay inside the limits: the client paces itself from every answer. Use it to
792
+ * size a job before you start it, or to show a person why something waits.
793
+ *
794
+ * @example
795
+ * const { budgets, shield } = await zs.limits.get();
796
+ * const cells = shield?.budgets.find((b) => b.scope === "cells-day");
797
+ * if (cells?.remaining != null && cells.remaining < plannedCells) console.log(`Room again in ${cells.resetSeconds} s`);
798
+ */
799
+ get: (options) => this.request("GET /limits", options),
800
+ };
801
+ /* ── what this key did: its own request log ── */
802
+ requests = {
803
+ /**
804
+ * This key's own requests of the last 7 days, newest first: when, the route's pattern, the status, the
805
+ * error code, the address it came from, how long it took and the request id. Never a body, a query or a
806
+ * guest's data. Any key may call it. A company key reads every call made with it across its hotels, or
807
+ * one hotel's through `zs.forProperty(id)`.
808
+ *
809
+ * `since` defaults to the last 24 hours. `status` is one code ("429"), a family ("4xx") or "errors"
810
+ * (400 and above). Use it to answer "did my push arrive" yourself, and to look for an address that is
811
+ * not yours: that is the first sign of a leaked key.
812
+ *
813
+ * @example
814
+ * const { items } = await zs.requests.list({ status: "errors" });
815
+ * for (const r of items) console.log(r.at, r.method, r.route, r.status, r.errorCode, r.requestId);
816
+ */
817
+ list: (query, options) => this.request("GET /requests", { query, ...options }),
818
+ /**
819
+ * The same, page by page to the last one: every request since `since`, newest first.
820
+ *
821
+ * @example
822
+ * for await (const r of zs.requests.all({ status: "errors", since: yesterday })) count[r.errorCode ?? r.status]++;
823
+ */
824
+ all: (query, options) => this.#pages((cursor) => this.requests.list({ limit: 200, ...query, cursor }, options)),
825
+ };
826
+ /* ── the hotel's ordered event log: the webhooks are the nudge, this is the truth ── */
827
+ events = {
828
+ /**
829
+ * One page of the hotel's event log: every event a webhook can carry for it (OTA bookings, website
830
+ * bookings, channel alerts, drift), once, oldest first, starting after the sequence you pass. Each item
831
+ * is the webhook's own envelope with its `sequence`, so one parser serves both.
832
+ *
833
+ * Keep `nextAfter` as your place. `more: true` means ask again at once. When `earliestSequence` is more
834
+ * than one above the `after` you sent, the events in between are older than the log keeps (90 days):
835
+ * reconcile with `zs.channelBookings.all` and `zs.directBookings.all`, then carry on. Scope
836
+ * channel-bookings:read (the channel events) or direct-bookings:read (the website's). `all` does the paging.
837
+ *
838
+ * @example
839
+ * const page = await zs.events.list({ after: lastSequence });
840
+ */
841
+ list: (query, options) => this.request("GET /events", { query, ...options }),
842
+ /**
843
+ * Every event after a sequence you saved, in order, to the end of the log. Apply each one, then save its
844
+ * `sequence`: that is your place, and the next run starts from it. A webhook only tells you there is
845
+ * something to read; nothing depends on it having arrived, or on the order deliveries arrived in.
846
+ *
847
+ * `onGap` is called once, before the first event, when the log no longer holds what follows `after`
848
+ * (events are kept 90 days): read the bookings again with `zs.channelBookings.all({ since })` and
849
+ * `zs.directBookings.all({ since })` before you go on. A first run with `after: 0` is told too.
850
+ *
851
+ * @example
852
+ * for await (const event of zs.events.all({ after: await loadPlace() })) {
853
+ * await apply(event); // dedupe on event.id if your apply is not idempotent
854
+ * await savePlace(event.sequence);
855
+ * }
856
+ */
857
+ all: (query, options) => this.#eventsAfter(query?.after ?? 0, query?.limit, options),
858
+ };
859
+ async *#eventsAfter(after, limit, options) {
860
+ if (!Number.isInteger(after) || after < 0)
861
+ 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");
862
+ let place = after;
863
+ let first = true;
864
+ for (;;) {
865
+ const page = await this.events.list({ after: place, limit: limit ?? 100 }, { signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds });
866
+ if (first && page.earliestSequence !== null && page.earliestSequence > after + 1)
867
+ options?.onGap?.({ after, earliestSequence: page.earliestSequence });
868
+ first = false;
869
+ yield* page.items;
870
+ // nextAfter moves past events this key's scopes do not show, so an empty page can still move the place.
871
+ if (!page.more || page.nextAfter <= place)
872
+ return;
873
+ place = page.nextAfter;
874
+ }
875
+ }
876
+ /* ── your company webhook endpoints (a software partner's company key, scope webhooks:manage) ── */
877
+ webhookEndpoints = {
878
+ /** Your company webhook endpoints of this key's mode (a live key: live ones; a test key: test ones), each with its health. */
879
+ list: (options) => this.request("GET /webhook-endpoints", options),
880
+ /**
881
+ * Create a company webhook endpoint. `dataAck: true` confirms that guest booking details will be sent
882
+ * to that address. Guest contact (phone, email) is off unless `includeGuestContact` is true.
883
+ *
884
+ * THE ANSWER'S `secret` IS SHOWN ONCE: store it in your server's settings at once (never in code or a
885
+ * log). No call reads it back; `rotateSecret` makes a new one. The call carries an idempotency key, so
886
+ * a retry after a lost answer gets the same endpoint and the same secret, never a second endpoint.
887
+ *
888
+ * @example
889
+ * const { endpoint, secret } = await zs.webhookEndpoints.create({ url: "https://pms.example/zimmerstack", dataAck: true });
890
+ */
891
+ create: (body, options) => this.request("POST /webhook-endpoints", { body, ...options }),
892
+ get: (endpointId, options) => this.request("GET /webhook-endpoints/{endpointId}", { path: { endpointId }, ...options }),
893
+ /** Change an endpoint: its address, its event types, the notify email or the guest-contact switch. Send only what changes. */
894
+ update: (endpointId, body, options) => this.request("PATCH /webhook-endpoints/{endpointId}", { path: { endpointId }, body, ...options }),
895
+ /**
896
+ * Delete an endpoint for good; its deliveries and their log go with it. THERE IS NO UNDO: call it when
897
+ * a person chose to, never from a loop or a cleanup script. To stop events for a while, `pause`.
898
+ */
899
+ delete: (endpointId, options) => this.request("DELETE /webhook-endpoints/{endpointId}", { path: { endpointId }, ...options }),
900
+ /** Hold an endpoint's events (before planned downtime). Nothing is dropped: `resume` sends them, oldest first. */
901
+ pause: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/pause", { path: { endpointId }, ...options }),
902
+ /** Resume a paused endpoint. `heldEvents` says how many held events are going out now. */
903
+ resume: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/resume", { path: { endpointId }, ...options }),
904
+ /**
905
+ * A new signing secret, in this answer only. Both secrets sign every delivery until `previousExpiresAt`
906
+ * (24 hours), so switch your receiver to the new one inside that day and nothing is lost.
907
+ */
908
+ rotateSecret: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/rotate-secret", { path: { endpointId }, ...options }),
909
+ /**
910
+ * Send the endpoint a signed sample of any event type (`zimmerstack.ping` when none is named). The
911
+ * sample says `mode: "test"` and has no `sequence`: it is in no log. On a sandbox, make a real event
912
+ * instead with `zs.sandbox.bookings.create` and `zs.sandbox.syncEvents.create`.
913
+ *
914
+ * @example
915
+ * const { deliveryId } = await zs.webhookEndpoints.test(endpoint.id, { eventType: "channel.booking.created" });
916
+ * const delivery = await zs.webhookEndpoints.deliveries.get(endpoint.id, deliveryId); // what your receiver answered
917
+ */
918
+ test: (endpointId, body = {}, options) => this.request("POST /webhook-endpoints/{endpointId}/test", { path: { endpointId }, body, ...options }),
919
+ /**
920
+ * Queue again every subscribed event since an instant that failed or never had a delivery: at most 90
921
+ * days back and 10,000 events a run (`truncated: true` means run it again for the rest). Reading the
922
+ * log with `zs.events.all` is the other way to catch up, and needs no endpoint.
923
+ */
924
+ recover: (endpointId, since, options) => this.request("POST /webhook-endpoints/{endpointId}/recover", { path: { endpointId }, body: { since: since instanceof Date ? since.toISOString() : since }, ...options }),
925
+ deliveries: {
926
+ /** An endpoint's delivery log, newest first. Filter with status, eventType, mode (TEST: what a test made), from and to. */
927
+ list: (endpointId, query, options) => this.request("GET /webhook-endpoints/{endpointId}/deliveries", { path: { endpointId }, query, ...options }),
928
+ /** One delivery: the body as it was sent, and every attempt with what your receiver answered. */
929
+ get: (endpointId, deliveryId, options) => this.request("GET /webhook-endpoints/{endpointId}/deliveries/{deliveryId}", { path: { endpointId, deliveryId }, ...options }),
930
+ /** Send one delivery again: the same event, the same id and sequence. */
931
+ redeliver: (endpointId, deliveryId, options) => this.request("POST /webhook-endpoints/{endpointId}/deliveries/{deliveryId}/redeliver", { path: { endpointId, deliveryId }, ...options }),
932
+ },
933
+ };
934
+ /* ── one-time connect links: the hotel's own person connects a booking site (company key, scope channels:connect) ── */
935
+ connectLinks = {
936
+ /** Your connect links, newest first; `propertyId` narrows them to one hotel. */
937
+ list: (query, options) => this.request("GET /connect-links", { query, ...options }),
938
+ /**
939
+ * Make a one-time link for ONE hotel and ONE booking site. Only Airbnb is connected from the link alone
940
+ * (the host signs in on Airbnb's own page). Every other booking site must FIRST accept our connectivity
941
+ * partner for the hotel, in its extranet or through its support: send `hotelStep` to the hotel first, and
942
+ * the answer's `url` once that step is done. On ZimmerStack's hosted page the hotel's own person types
943
+ * the hotel's id at the booking site (MakeMyTrip also its access token), confirms every room and rate
944
+ * match and presses Start selling. The call takes no booking-site detail and no match. You hear
945
+ * `channel.connect.completed`, or `channel.connect.expired` if the link ran out.
946
+ *
947
+ * THE `url` IS SHOWN ONCE: it is in this answer only, and null on a replay of the same request
948
+ * (`shownOnce(answer)` returns it or says what to do). `hotelStep` is what the hotel does at the booking
949
+ * site first (null for Airbnb), for your own screen or message; it can take days. A LIVE key only: a
950
+ * sandbox has no booking site, so a test key is refused (LIVE_KEY_REQUIRED). The hotel is `propertyId`
951
+ * in the body; `forProperty` is not read.
952
+ *
953
+ * @example
954
+ * const made = await zs.connectLinks.create({ propertyId: 61, channel: "bookingcom", returnUrl: "https://pms.example/hotels/61" });
955
+ * await tellTheHotel(made.hotelStep); // first
956
+ * await sendOnceTheStepIsDone(shownOnce(made)); // then the link
957
+ */
958
+ create: (body, options) => this.request("POST /connect-links", { body, ...options }),
959
+ /** Where one link stands: pending, opened, completed, expired or revoked. Never its address again. */
960
+ get: (linkId, options) => this.request("GET /connect-links/{linkId}", { path: { linkId }, ...options }),
961
+ /** Withdraw a link. A page that is open stops at its next step. */
962
+ revoke: (linkId, options) => this.request("POST /connect-links/{linkId}/revoke", { path: { linkId }, ...options }),
963
+ };
964
+ /* ── going live: is this hotel ready for your software to be its source of truth ── */
965
+ readiness = {
966
+ /**
967
+ * Is this hotel ready for your software to be its source of truth? Four checks, each passed or not,
968
+ * with a sentence and what to do: it is on the channel manager, every room type and rate plan is
969
+ * linked, ZimmerStack's own pricing will not overwrite your prices, and nothing stale would go out
970
+ * (the record matches the channels, or you sent a price for every rate plan and night of the year
971
+ * first). Room counts are no part of it: the report only says how many room-type nights your software
972
+ * has not written yet. Any key may read it, as often as you like. A hotel you added yourself is live
973
+ * from the start (`live: true`).
974
+ *
975
+ * @example
976
+ * const report = await zs.forProperty(61).readiness.get();
977
+ * for (const check of report.checks) if (!check.passed) console.log(check.id, check.summary, check.action);
978
+ */
979
+ get: (options) => this.request("GET /readiness", options),
980
+ /**
981
+ * Make your software this hotel's source of truth: from then on every price, stay rule and room count
982
+ * you send is pushed to its booking sites, and what you sent ahead (`beforeGoLive: true`) goes out.
983
+ * Scope ari:write. Not ready is 409 NOT_READY with the checks that did not pass in `error.details`;
984
+ * that refusal is never kept under an idempotency key, so call again once they pass. Already live
985
+ * answers `replay: true`. Call it when a person decided to; only ZimmerStack support switches a hotel back.
986
+ *
987
+ * @example
988
+ * const hotel = zs.forProperty(61);
989
+ * await hotel.rates.set(aYearOfPrices, { beforeGoLive: true }); // stored, and waits
990
+ * // 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.
991
+ * if ((await hotel.readiness.get()).ready) await hotel.readiness.goLive();
992
+ * await hotel.availability.set(aYearOfCounts); // right after going live: your room counts
993
+ */
994
+ goLive: (options) => this.request("POST /go-live", options),
995
+ };
996
+ /* ── the keys you made on a hotel (company key, scope keys:manage) ── */
997
+ hotelKeys = {
998
+ /** The keys YOU made on a hotel you added. The hotel's own keys are its owner's and are never listed here. */
999
+ list: (propertyId, options) => this.request("GET /properties/{propertyId}/keys", { path: { propertyId }, ...options }),
1000
+ /**
1001
+ * Mint a key on a hotel you added (or, with a test key, on one of your sandboxes): any scope a
1002
+ * hotel's own key may hold, never a company key's own.
1003
+ *
1004
+ * THE ANSWER'S `key` IS SHOWN ONCE: store it in the server's settings at once, never in code or a log.
1005
+ * It is null on a replay of the same request: `shownOnce(answer)` returns it or says to rotate.
1006
+ *
1007
+ * @example
1008
+ * const minted = await zs.hotelKeys.create(61, { name: "Night audit job", scopes: ["ari:read", "channel-bookings:read"] });
1009
+ * await vault.put(`zimmerstack/hotel-61`, shownOnce(minted));
1010
+ */
1011
+ create: (propertyId, body, options) => this.request("POST /properties/{propertyId}/keys", { path: { propertyId }, body, ...options }),
1012
+ /**
1013
+ * A new key with the same name, scopes, addresses and expiry, its secret shown once; the old key keeps
1014
+ * answering for 24 hours (`retired.retireAt`), so switch inside that day and nothing stops.
1015
+ */
1016
+ rotate: (propertyId, keyId, options) => this.request("POST /properties/{propertyId}/keys/{keyId}/rotate", { path: { propertyId, keyId }, ...options }),
1017
+ /** 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. */
1018
+ revoke: (propertyId, keyId, body, options) => this.request("POST /properties/{propertyId}/keys/{keyId}/revoke", { path: { propertyId, keyId }, body, ...options }),
1019
+ };
1020
+ /* ── your bills, read only (company key, scope billing:read) ── */
1021
+ billing = {
1022
+ /**
1023
+ * Your bills at a glance: what is owed, the one-time onboarding fee, your hotel quota and what opens
1024
+ * the next level, what is left of money paid ahead, the days of an unpaid invoice, and `atCost`: what
1025
+ * the channel manager charged above its included room types and rate plans for a hotel whose limit
1026
+ * ZimmerStack raised. An at-cost line is a record: `status` says RECORDED until ZimmerStack's team has
1027
+ * put it on one of your invoices (INVOICED) or waived it. Nothing here pays or changes anything.
1028
+ */
1029
+ get: (options) => this.request("GET /billing", options),
1030
+ /** Your 24 most recent issued invoices, newest first, each before and after tax with its lines, then the recent payments. */
1031
+ invoices: (options) => this.request("GET /billing/invoices", options),
1032
+ /**
1033
+ * What your next monthly invoice is made of, hotel by hotel, read today: the rooms counted, the room
1034
+ * band, the price list, the unit price. The invoice reads rooms, prices and the exchange rate again on
1035
+ * the day it is made, and that is the bill.
1036
+ */
1037
+ nextInvoice: (options) => this.request("GET /billing/next-invoice", options),
1038
+ };
1039
+ /* ── support tickets (company key, scope support:write) ── */
1040
+ supportTickets = {
1041
+ /** Your tickets of this key's mode, newest first. `status`: OPEN (waiting for ZimmerStack), ANSWERED (waiting for you), CLOSED. */
1042
+ list: (query, options) => this.request("GET /support-tickets", { query, ...options }),
1043
+ /** The same, page by page to the last one. */
1044
+ all: (query, options) => this.#pages((cursor) => this.supportTickets.list({ limit: 100, ...query, cursor }, options)),
1045
+ /**
1046
+ * Open a support ticket. `severity` follows from the hotels you name: `many_hotels` needs two or more
1047
+ * `propertyIds` or `allProperties: true`, `one_hotel` exactly one, `question` any or none. ZimmerStack
1048
+ * attaches what its own records show at that moment (`diagnostic`: ids, counts, states and times), so
1049
+ * never paste a key, a secret or a guest's details into `message`. It opens whatever your
1050
+ * integration's standing. The call carries an idempotency key: a retry never opens a second ticket.
1051
+ *
1052
+ * @example
1053
+ * 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] });
1054
+ * console.log(ticket.id, ticket.firstReply.target, ticket.firstReply.dueAt);
1055
+ */
1056
+ create: (body, options) => this.request("POST /support-tickets", { body, ...options }),
1057
+ /** One ticket: its thread, oldest first, and the diagnostic taken when it opened. */
1058
+ get: (ticketId, options) => this.request("GET /support-tickets/{ticketId}", { path: { ticketId }, ...options }),
1059
+ /** 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. */
1060
+ reply: (ticketId, message, options) => this.request("POST /support-tickets/{ticketId}/messages", { path: { ticketId }, body: { message }, ...options }),
1061
+ /** Close your own ticket. */
1062
+ close: (ticketId, options) => this.request("POST /support-tickets/{ticketId}/close", { path: { ticketId }, ...options }),
1063
+ };
1064
+ /* ── is something wrong on ZimmerStack's side ── */
1065
+ status = {
1066
+ /**
1067
+ * The components (the API, bookings coming in, prices and availability going out, each booking site),
1068
+ * each operational or named in an open incident, and the incidents that touch YOUR hotels: the open
1069
+ * ones and those resolved in the last 7 days. Any key. A company key reads all its hotels', or one
1070
+ * hotel's through `zs.forProperty(id)`. An incident is opened and closed by ZimmerStack's staff:
1071
+ * `operational` means nobody has reported a problem, not that a monitor measured none.
1072
+ *
1073
+ * @example
1074
+ * const { overall, incidents } = await zs.status.get();
1075
+ * for (const incident of incidents.open) console.log(incident.title, incident.status, incident.updates[0]?.message);
1076
+ */
1077
+ get: (options) => this.request("GET /status", options),
1078
+ };
496
1079
  /* ── room types and rate plans ── */
497
1080
  catalog = {
498
1081
  /** Room types and rate plans, with the numeric ids every write uses. */
@@ -618,10 +1201,25 @@ export class ZimmerStack {
618
1201
  const accepted = [];
619
1202
  for (const [i, part] of parts.entries()) {
620
1203
  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 }));
1204
+ // The body carries no dryRun, so the answer is the accepted write, never a preview.
1205
+ const answer = await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds, beforeGoLive: options?.beforeGoLive });
1206
+ accepted.push(answer);
622
1207
  }
623
1208
  return accepted;
624
1209
  }
1210
+ /**
1211
+ * The same request with `dryRun: true`: checked and judged exactly as the write, and nothing is written.
1212
+ * One preview per request the write would be split into. No idempotency key of yours is taken: the
1213
+ * server keeps none for a dry run, so the real write may carry any key afterwards.
1214
+ */
1215
+ async #previewAll(operation, updates, options) {
1216
+ const previews = [];
1217
+ for (const part of chunk(updates)) {
1218
+ const answer = await this.request(operation, { body: { dryRun: true, updates: part }, signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds, beforeGoLive: options?.beforeGoLive });
1219
+ previews.push(previewOnly(operation, answer));
1220
+ }
1221
+ return previews;
1222
+ }
625
1223
  availability = {
626
1224
  /** Rooms left to sell per room type per night, as ZimmerStack's record holds them. Up to 500 days. */
627
1225
  get: (range, options) => this.request("GET /availability", { query: range, ...options }),
@@ -630,14 +1228,63 @@ export class ZimmerStack {
630
1228
  * ZimmerStack's record (one answer per request sent; a large write is split for you).
631
1229
  */
632
1230
  set: (updates, options) => this.#writeAll("PUT /availability", updates, options),
1231
+ /**
1232
+ * What `set` WOULD do with these updates, and nothing is written, queued or sent. The answer is a
1233
+ * `WritePreview` (`dryRun: true`), never a `WriteAccepted`: `verdict` (would-write, nothing-to-write,
1234
+ * would-refuse with the refusal a real write would get now), the ranges that would change, the ones
1235
+ * already held, the ones held after a refusal, and the same `notices` the real write carries.
1236
+ *
1237
+ * It is not a free read: it spends the minute budgets like the write it previews (one request, one
1238
+ * write, the same cells), and under a test runner a live key may not send it, like any write. It
1239
+ * counts nothing against the hour and day budgets. To read the calendar use `get`.
1240
+ *
1241
+ * @example
1242
+ * const [preview] = await zs.availability.dryRun([{ roomTypeId: 412, dateFrom: "2026-12-31", dateTo: "2026-12-31", available: 0 }]);
1243
+ * if (preview?.verdict === "would-write") await zs.availability.set(updates);
1244
+ */
1245
+ dryRun: (updates, options) => this.#previewAll("PUT /availability", updates, options),
1246
+ /**
1247
+ * Close one room type on a range of nights EVERYWHERE, in one call: its room count goes to 0 and
1248
+ * stop-sell is switched on for every one of its rate plans. You do not need to know the hotel's
1249
+ * plans. The count closes every rate of the room on every booking site; the stop-sell keeps it closed
1250
+ * when a cancellation puts a room back.
1251
+ *
1252
+ * READ `notReached`: every plan that is not linked or that no booking site sells, and the one thing no
1253
+ * stop-sell reaches, a rate a booking site links on its own side (only the count closes that).
1254
+ * `batches` names the writes to watch land (`zs.batches.wait`). A close is accepted while your
1255
+ * integration is paused or out of budget (`lane: true`): a hotel must never oversell.
1256
+ *
1257
+ * @example
1258
+ * const closed = await zs.availability.close({ roomTypeId: 412, dateFrom: "2026-12-30", dateTo: "2027-01-02" });
1259
+ * for (const gap of closed.notReached) console.log(gap.what, gap.reason, gap.message);
1260
+ */
1261
+ close: async (body, options) => (await this.request("POST /availability/close", { body: realOnly("close", body), ...options })),
1262
+ /** What `close` would do, and nothing is done: the same answer with `dryRun: true` and no batches. Spends the minute budgets like the close. */
1263
+ closeDryRun: async (body, options) => previewOnly("POST /availability/close", (await this.request("POST /availability/close", { body: { ...body, dryRun: true }, ...options }))),
1264
+ /**
1265
+ * Undo exactly what `close` did on these nights, and nothing else: the stop-sell is lifted on the plans
1266
+ * the close switched on (a plan that was stop-sold before stays stopped), and each night gets back the
1267
+ * count it held before. Pass `available` to put your own count on sale instead: only your software
1268
+ * knows how many rooms are free now. A night whose count changed after the close is left as it is, and
1269
+ * a night the close had not closed is skipped (`skippedNights`). A reopen opens inventory, so it waits
1270
+ * like any other write while your integration is paused.
1271
+ *
1272
+ * @example
1273
+ * const reopened = await zs.availability.reopen({ roomTypeId: 412, dateFrom: "2026-12-30", dateTo: "2027-01-02", available: 3 });
1274
+ */
1275
+ reopen: async (body, options) => (await this.request("POST /availability/reopen", { body: realOnly("reopen", body), ...options })),
1276
+ /** What `reopen` would do, and nothing is done. */
1277
+ reopenDryRun: async (body, options) => previewOnly("POST /availability/reopen", (await this.request("POST /availability/reopen", { body: { ...body, dryRun: true }, ...options }))),
633
1278
  };
634
1279
  rates = {
635
- /** Nightly prices per rate plan, in MINOR units (`rateMinor`), before any channel's modifier. */
1280
+ /** 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
1281
  get: (range, options) => this.request("GET /rates", { query: range, ...options }),
637
1282
  /**
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.
1283
+ * Set nightly prices in MAJOR units over date ranges: a number or a decimal string with the
1284
+ * currency's own decimals (4500.5 or "4500.50"). `currency` may be left out: the hotel's own is
1285
+ * filled in. What could not be kept as sent is named in the answer's `rounded` list. Never a zero
1286
+ * price to stop selling: `restrictions.set` with stopSell closes one rate plan on a night, and
1287
+ * `availability.set` with 0 rooms closes the room type on every booking site.
641
1288
  */
642
1289
  set: async (updates, options) => {
643
1290
  if (updates.length === 0)
@@ -645,6 +1292,17 @@ export class ZimmerStack {
645
1292
  const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
646
1293
  return this.#writeAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
647
1294
  },
1295
+ /**
1296
+ * What `set` WOULD do with these prices, and nothing is written: a `WritePreview` per request, with what
1297
+ * would change, what is already held, what would be rounded and the notices (a plan no booking site
1298
+ * sells, an engine that will reprice). See `zs.availability.dryRun` for what it costs.
1299
+ */
1300
+ dryRun: async (updates, options) => {
1301
+ if (updates.length === 0)
1302
+ return [];
1303
+ const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
1304
+ return this.#previewAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
1305
+ },
648
1306
  /**
649
1307
  * Send the hotel's prices to its channels again, unchanged, so nights already there pick the
650
1308
  * current modifiers up. A hotel may ask a few times a day: make it a deliberate button, never
@@ -657,6 +1315,36 @@ export class ZimmerStack {
657
1315
  get: (range, options) => this.request("GET /restrictions", { query: range, ...options }),
658
1316
  /** Set stay rules over date ranges: stopSell, closedToArrival, closedToDeparture, minStayArrival, minStayThrough, maxStay. */
659
1317
  set: (updates, options) => this.#writeAll("PUT /restrictions", updates, options),
1318
+ /**
1319
+ * What `set` WOULD do with these stay rules, and nothing is written. The notices are the point: a
1320
+ * stop-sell on one rate plan answers ROOM_STILL_ON_SALE when the room keeps selling through its other
1321
+ * plans. See `zs.availability.dryRun` for what it costs.
1322
+ *
1323
+ * @example
1324
+ * const [preview] = await zs.restrictions.dryRun([{ ratePlanId: 901, dateFrom: "2026-12-31", dateTo: "2026-12-31", stopSell: true }]);
1325
+ * for (const notice of noticesOf(preview)) console.log(notice.code, notice.message, notice.action);
1326
+ */
1327
+ dryRun: (updates, options) => this.#previewAll("PUT /restrictions", updates, options),
1328
+ };
1329
+ /* ── one night's whole story ── */
1330
+ explain = {
1331
+ /**
1332
+ * Explain one night of one room type (optionally one of its rate plans), from ZimmerStack's record:
1333
+ * what your software last sent, what the record holds and who set it, what the channel manager was
1334
+ * last seen holding, every send still on file and how it ended, a held value in the channel manager's
1335
+ * own words, which connections sell each plan, the rules in force, the bookings that moved the count
1336
+ * (ids and times, never a guest), and `summary`: the same in plain sentences, for a person.
1337
+ *
1338
+ * What it cannot know: it reads the channel manager's copy as last seen, never a booking site's own
1339
+ * screen. `seenAt: null` means that night was never read back; `lastSent: null` means the write is older
1340
+ * than the ones whose values are kept (`searched` says how far it looked); `channels.known: false` means
1341
+ * the hotel's connections have not been read yet. Scope ari:read; it calls no channel, so ask freely.
1342
+ *
1343
+ * @example
1344
+ * const night = await zs.explain.night({ roomTypeId: 412, date: "2026-12-31" });
1345
+ * for (const sentence of night.summary) console.log(sentence);
1346
+ */
1347
+ night: (query, options) => this.request("GET /explain", { query, ...options }),
660
1348
  };
661
1349
  /* ── has it reached the channels? ── */
662
1350
  sync = {
@@ -765,12 +1453,16 @@ export class ZimmerStack {
765
1453
  cancel: (bookingId, body = {}, options) => this.request("POST /direct-bookings/{bookingId}/cancel", { path: { bookingId }, body, ...options }),
766
1454
  };
767
1455
  /** Follow a booking list's `nextCursor` to its last page. */
768
- async *#allPages(read) {
1456
+ #allPages(read) {
1457
+ return this.#pages(read);
1458
+ }
1459
+ /** Follow any list's `nextCursor` to its last page. A list that says `more: false` is at its end, whatever cursor it hands back. */
1460
+ async *#pages(read) {
769
1461
  let cursor;
770
1462
  do {
771
1463
  const page = await read(cursor);
772
1464
  yield* page.items;
773
- cursor = page.nextCursor ?? undefined;
1465
+ cursor = page.more === false ? undefined : (page.nextCursor ?? undefined);
774
1466
  } while (cursor);
775
1467
  }
776
1468
  /* ── the sandbox (zsk_test_ keys only) ── */
@@ -785,6 +1477,44 @@ export class ZimmerStack {
785
1477
  create: (body, options) => this.request("POST /sandbox/bookings", { body, ...options }),
786
1478
  cancel: (bookingId, options) => this.request("POST /sandbox/bookings/{bookingId}/cancel", { path: { bookingId }, ...options }),
787
1479
  modify: (bookingId, body, options) => this.request("POST /sandbox/bookings/{bookingId}/modify", { path: { bookingId }, body, ...options }),
1480
+ /**
1481
+ * Pretend the hotel recorded that a WEBSITE booking's guest did not arrive (one made with
1482
+ * `otaName: "Website"`): the stay and its rooms go NOSHOW, the nights come back on the sandbox's
1483
+ * availability, and your endpoint receives the real `direct.booking.modified`. `{ undo: true }` takes
1484
+ * it back. The booking is not cancelled.
1485
+ */
1486
+ noShow: (bookingId, body = {}, options) => this.request("POST /sandbox/bookings/{bookingId}/no-show", { path: { bookingId }, body, ...options }),
1487
+ },
1488
+ syncEvents: {
1489
+ /**
1490
+ * Pretend a channel problem, or its end: the real `channel.sync.alert` or `channel.sync.recovered`
1491
+ * to your endpoint, and a line in the event log. `event` says which problem (rate_error when left
1492
+ * out); the problem sits on one of the sandbox's pretend channels and `zs.channels.list()` shows it
1493
+ * until a recovered clears it.
1494
+ *
1495
+ * @example
1496
+ * await zs.sandbox.syncEvents.create({ type: "channel.sync.alert", event: "disconnect_channel" });
1497
+ * await zs.sandbox.syncEvents.create({ type: "channel.sync.recovered" });
1498
+ */
1499
+ create: (body, options) => this.request("POST /sandbox/sync-events", { body, ...options }),
1500
+ },
1501
+ faults: {
1502
+ /** The fault in force on this sandbox's pretend channel; `active: false` when there is none. */
1503
+ get: (options) => this.request("GET /sandbox/faults", options),
1504
+ /**
1505
+ * Make the sandbox's pretend channel misbehave, to watch your software meet a bad day: `refuse` (the
1506
+ * next `values` nights of prices or stay rules are refused, with your `message` as the channel
1507
+ * manager's words), `throttle` ("too many requests" for `minutes`) or `outage` (no answer for
1508
+ * `minutes`). One fault at a time: a new one replaces it. Prices and stay rules only: room counts land
1509
+ * as before. The answer's `watch` says what to do next and what you should then see, step by step.
1510
+ *
1511
+ * @example
1512
+ * const fault = await zs.sandbox.faults.set({ kind: "refuse", values: 2, message: "Rate is below the channel's minimum" });
1513
+ * for (const step of fault.watch) console.log(step);
1514
+ */
1515
+ set: (body, options) => this.request("POST /sandbox/faults", { body, ...options }),
1516
+ /** End the fault: the pretend channel answers normally from the next push. Values already held stay held until a different value is sent. */
1517
+ clear: (options) => this.request("DELETE /sandbox/faults", options),
788
1518
  },
789
1519
  };
790
1520
  /* ── the rate grid ── */