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