@zimmerstack/connect 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +99 -0
- package/LICENSE +21 -0
- package/README.md +225 -2
- package/dist/cjs/client.d.ts +260 -0
- package/dist/cjs/client.js +562 -0
- package/dist/cjs/errors.d.ts +46 -0
- package/dist/cjs/errors.js +51 -0
- package/dist/cjs/generated.d.ts +1153 -0
- package/dist/cjs/generated.js +135 -0
- package/dist/cjs/grid.d.ts +105 -0
- package/dist/cjs/grid.js +135 -0
- package/dist/cjs/index.d.ts +16 -0
- package/dist/cjs/index.js +30 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/webhooks.d.ts +60 -0
- package/dist/cjs/webhooks.js +103 -0
- package/dist/esm/client.d.ts +260 -0
- package/dist/esm/client.js +558 -0
- package/dist/esm/errors.d.ts +46 -0
- package/dist/esm/errors.js +46 -0
- package/dist/esm/generated.d.ts +1153 -0
- package/dist/esm/generated.js +132 -0
- package/dist/esm/grid.d.ts +105 -0
- package/dist/esm/grid.js +127 -0
- package/dist/esm/index.d.ts +16 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/mcp/cli.d.ts +2 -0
- package/dist/esm/mcp/cli.js +86 -0
- package/dist/esm/mcp/key.d.ts +9 -0
- package/dist/esm/mcp/key.js +31 -0
- package/dist/esm/mcp/reference.d.ts +11 -0
- package/dist/esm/mcp/reference.generated.d.ts +33 -0
- package/dist/esm/mcp/reference.generated.js +2084 -0
- package/dist/esm/mcp/reference.js +137 -0
- package/dist/esm/mcp/server.d.ts +29 -0
- package/dist/esm/mcp/server.js +223 -0
- package/dist/esm/webhooks.d.ts +60 -0
- package/dist/esm/webhooks.js +98 -0
- package/package.json +61 -4
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
import { ZimmerStackError, ZimmerStackUsageError } from "./errors.js";
|
|
2
|
+
import { API_ORIGIN, API_PREFIX, IDEMPOTENCY_HEADER, OPERATIONS, PROPERTY_HEADER, SDK_VERSION, } from "./generated.js";
|
|
3
|
+
import { buildGrid, chunk, toRanges } from "./grid.js";
|
|
4
|
+
/* ───────────────────────────── the shared core ───────────────────────────── */
|
|
5
|
+
/** Requests in flight at once. Writes go one at a time on top of that. */
|
|
6
|
+
const PARALLEL = 4;
|
|
7
|
+
const KEY_SHAPE = /^zsk_(live|test)_[A-Za-z0-9_-]{16,}$/;
|
|
8
|
+
const IDEMPOTENCY_SHAPE = /^[A-Za-z0-9_-]{10,64}$/;
|
|
9
|
+
/** After one of these the key will never work again: every later call is refused here, not sent. */
|
|
10
|
+
const KEY_IS_DEAD = new Set(["API_KEY_INVALID", "API_KEY_REVOKED", "API_KEY_EXPIRED"]);
|
|
11
|
+
const CATALOG_TTL_MS = 10 * 60_000;
|
|
12
|
+
function sleep(ms, signal) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
if (signal?.aborted)
|
|
15
|
+
return reject(signal.reason);
|
|
16
|
+
const timer = setTimeout(() => {
|
|
17
|
+
signal?.removeEventListener("abort", onAbort);
|
|
18
|
+
resolve();
|
|
19
|
+
}, ms);
|
|
20
|
+
const onAbort = () => {
|
|
21
|
+
clearTimeout(timer);
|
|
22
|
+
reject(signal?.reason);
|
|
23
|
+
};
|
|
24
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function env(name) {
|
|
28
|
+
return typeof process !== "undefined" && process.env ? process.env[name] : undefined;
|
|
29
|
+
}
|
|
30
|
+
function underTestRunner() {
|
|
31
|
+
return env("NODE_ENV") === "test" || Boolean(env("VITEST") || env("JEST_WORKER_ID") || env("NODE_TEST_CONTEXT"));
|
|
32
|
+
}
|
|
33
|
+
function resolveBase(baseUrl) {
|
|
34
|
+
if (!baseUrl)
|
|
35
|
+
return API_ORIGIN;
|
|
36
|
+
let url;
|
|
37
|
+
try {
|
|
38
|
+
url = new URL(baseUrl);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new ZimmerStackUsageError("baseUrl is not a URL");
|
|
42
|
+
}
|
|
43
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
44
|
+
if (url.origin !== API_ORIGIN && !local) {
|
|
45
|
+
throw new ZimmerStackUsageError(`baseUrl may only be ${API_ORIGIN} or a local stand-in (http://localhost:…): the key is sent to no other host`);
|
|
46
|
+
}
|
|
47
|
+
return url.origin;
|
|
48
|
+
}
|
|
49
|
+
class Core {
|
|
50
|
+
#key;
|
|
51
|
+
mode;
|
|
52
|
+
base;
|
|
53
|
+
#fetch;
|
|
54
|
+
#timeoutMs;
|
|
55
|
+
#maxRetries;
|
|
56
|
+
#maxWaitSeconds;
|
|
57
|
+
#allowLiveWritesInTests;
|
|
58
|
+
#onEvent;
|
|
59
|
+
#resumeAll = 0;
|
|
60
|
+
#resumeWrites = 0;
|
|
61
|
+
#active = 0;
|
|
62
|
+
#queue = [];
|
|
63
|
+
#writeTail = Promise.resolve();
|
|
64
|
+
#dead;
|
|
65
|
+
catalogs = new Map();
|
|
66
|
+
constructor(options) {
|
|
67
|
+
const g = globalThis;
|
|
68
|
+
if ((typeof g.window !== "undefined" && typeof g.window.document !== "undefined") || g.navigator?.product === "ReactNative") {
|
|
69
|
+
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.");
|
|
70
|
+
}
|
|
71
|
+
const key = options.apiKey ?? env("ZIMMERSTACK_CONNECT_KEY");
|
|
72
|
+
if (!key)
|
|
73
|
+
throw new ZimmerStackUsageError("No API key: set the environment variable ZIMMERSTACK_CONNECT_KEY (zsk_test_… while you build) on your server");
|
|
74
|
+
const shape = KEY_SHAPE.exec(key.trim());
|
|
75
|
+
if (!shape)
|
|
76
|
+
throw new ZimmerStackUsageError("The API key does not look like a ZimmerStack key (zsk_test_… or zsk_live_…). It was not sent anywhere.");
|
|
77
|
+
this.#key = key.trim();
|
|
78
|
+
this.mode = shape[1];
|
|
79
|
+
this.base = resolveBase(options.baseUrl);
|
|
80
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
81
|
+
if (typeof f !== "function")
|
|
82
|
+
throw new ZimmerStackUsageError("No fetch in this runtime: @zimmerstack/connect needs Node 20 or newer");
|
|
83
|
+
this.#fetch = f;
|
|
84
|
+
this.#timeoutMs = options.timeoutMs ?? 30_000;
|
|
85
|
+
this.#maxRetries = Math.min(5, Math.max(0, Math.trunc(options.maxRetries ?? 3)));
|
|
86
|
+
this.#maxWaitSeconds = options.maxWaitSeconds ?? 120;
|
|
87
|
+
this.#allowLiveWritesInTests = options.allowLiveWritesInTests === true;
|
|
88
|
+
this.#onEvent = options.onEvent;
|
|
89
|
+
}
|
|
90
|
+
authorization() {
|
|
91
|
+
return "Bearer " + this.#key;
|
|
92
|
+
}
|
|
93
|
+
#emit(event) {
|
|
94
|
+
try {
|
|
95
|
+
this.#onEvent?.(event);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
/* a logger must never break a request */
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
send(wire) {
|
|
102
|
+
if (this.#dead) {
|
|
103
|
+
const d = this.#dead;
|
|
104
|
+
return Promise.reject(new ZimmerStackError({
|
|
105
|
+
status: d.status,
|
|
106
|
+
code: d.code,
|
|
107
|
+
message: `${d.message} (this key was refused earlier, so ${wire.operation} was not sent; start again with a working key)`,
|
|
108
|
+
operation: wire.operation,
|
|
109
|
+
retryable: false,
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
if (wire.write && this.mode === "live" && !this.#allowLiveWritesInTests && underTestRunner()) {
|
|
113
|
+
return Promise.reject(new ZimmerStackError({
|
|
114
|
+
status: 0,
|
|
115
|
+
code: "LIVE_KEY_IN_TEST",
|
|
116
|
+
message: `${wire.operation} was not sent: this is a live key (zsk_live_) under a test runner, and a test must not change a real hotel. Use a zsk_test_ sandbox key or a fake fetch.`,
|
|
117
|
+
operation: wire.operation,
|
|
118
|
+
retryable: false,
|
|
119
|
+
}));
|
|
120
|
+
}
|
|
121
|
+
if (!wire.write)
|
|
122
|
+
return this.#attempts(wire);
|
|
123
|
+
// Writes go one after another: a burst spends the write budget at once, and two writes to one
|
|
124
|
+
// night must reach the record in the order they were made.
|
|
125
|
+
const run = () => this.#attempts(wire);
|
|
126
|
+
const result = this.#writeTail.then(run, run);
|
|
127
|
+
this.#writeTail = result.catch(() => undefined);
|
|
128
|
+
return result;
|
|
129
|
+
}
|
|
130
|
+
#slot() {
|
|
131
|
+
const take = () => {
|
|
132
|
+
this.#active++;
|
|
133
|
+
let released = false;
|
|
134
|
+
return () => {
|
|
135
|
+
if (released)
|
|
136
|
+
return;
|
|
137
|
+
released = true;
|
|
138
|
+
this.#active--;
|
|
139
|
+
this.#queue.shift()?.();
|
|
140
|
+
};
|
|
141
|
+
};
|
|
142
|
+
if (this.#active < PARALLEL)
|
|
143
|
+
return Promise.resolve(take());
|
|
144
|
+
return new Promise((resolve) => this.#queue.push(() => resolve(take())));
|
|
145
|
+
}
|
|
146
|
+
/** Wait until the budgets the last answers reported have room again, instead of earning a 429. */
|
|
147
|
+
async #pace(wire) {
|
|
148
|
+
for (;;) {
|
|
149
|
+
const wait = Math.max(this.#resumeAll, wire.write ? this.#resumeWrites : 0) - Date.now();
|
|
150
|
+
if (wait <= 0)
|
|
151
|
+
return;
|
|
152
|
+
this.#emit({ type: "pace", operation: wire.operation, waitMs: wait });
|
|
153
|
+
await sleep(wait, wire.signal);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** RateLimit: "key";r=117;t=42, "key-writes";r=29;t=42 (r = requests left, t = seconds until the window has room). */
|
|
157
|
+
#notePace(res) {
|
|
158
|
+
for (const part of (res.headers.get("ratelimit") ?? "").split(",")) {
|
|
159
|
+
const left = /;\s*r=(\d+)/.exec(part);
|
|
160
|
+
const refill = /;\s*t=(\d+)/.exec(part);
|
|
161
|
+
if (!left || !refill || Number(left[1]) > PARALLEL)
|
|
162
|
+
continue;
|
|
163
|
+
const at = Date.now() + Math.min(Number(refill[1]), 65) * 1000;
|
|
164
|
+
if (/"[^"]*(writes|bookings|cells)[^"]*"/.test(part))
|
|
165
|
+
this.#resumeWrites = Math.max(this.#resumeWrites, at);
|
|
166
|
+
else
|
|
167
|
+
this.#resumeAll = Math.max(this.#resumeAll, at);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async #attempts(wire) {
|
|
171
|
+
for (let attempt = 1;; attempt++) {
|
|
172
|
+
await this.#pace(wire);
|
|
173
|
+
const release = await this.#slot();
|
|
174
|
+
const started = Date.now();
|
|
175
|
+
let res;
|
|
176
|
+
let json;
|
|
177
|
+
try {
|
|
178
|
+
const timeout = AbortSignal.timeout(this.#timeoutMs);
|
|
179
|
+
res = await this.#fetch(wire.url, {
|
|
180
|
+
method: wire.method,
|
|
181
|
+
headers: wire.headers,
|
|
182
|
+
body: wire.body,
|
|
183
|
+
// The API never redirects, and the key must not follow one to another address.
|
|
184
|
+
redirect: "manual",
|
|
185
|
+
signal: wire.signal ? AbortSignal.any([timeout, wire.signal]) : timeout,
|
|
186
|
+
});
|
|
187
|
+
json = (await res.json().catch(() => null));
|
|
188
|
+
}
|
|
189
|
+
catch (cause) {
|
|
190
|
+
release();
|
|
191
|
+
if (wire.signal?.aborted)
|
|
192
|
+
throw cause;
|
|
193
|
+
const timedOut = cause?.name === "TimeoutError";
|
|
194
|
+
if (!wire.resendable || attempt > this.#maxRetries) {
|
|
195
|
+
throw new ZimmerStackError({
|
|
196
|
+
status: 0,
|
|
197
|
+
code: timedOut ? "TIMEOUT" : "NETWORK_ERROR",
|
|
198
|
+
message: wire.resendable
|
|
199
|
+
? `${wire.operation} could not reach ZimmerStack after ${attempt} attempts`
|
|
200
|
+
: `${wire.operation} could not reach ZimmerStack, and it is not safe to send again without knowing whether it was applied: read the current state before you retry`,
|
|
201
|
+
operation: wire.operation,
|
|
202
|
+
retryable: wire.resendable,
|
|
203
|
+
cause,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const waitMs = (2 ** (attempt - 1) + Math.random()) * 1000;
|
|
207
|
+
this.#emit({ type: "retry", operation: wire.operation, attempt, waitMs, reason: timedOut ? "TIMEOUT" : "NETWORK_ERROR" });
|
|
208
|
+
await sleep(waitMs, wire.signal);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
release();
|
|
212
|
+
this.#notePace(res);
|
|
213
|
+
this.#emit({ type: "response", operation: wire.operation, status: res.status, attempt, ms: Date.now() - started });
|
|
214
|
+
if (res.ok)
|
|
215
|
+
return json && typeof json === "object" ? json.data : undefined;
|
|
216
|
+
const data = (json && typeof json.data === "object" && json.data !== null ? json.data : {});
|
|
217
|
+
const code = typeof data.code === "string" ? data.code : `HTTP_${res.status}`;
|
|
218
|
+
const headerSeconds = Number(res.headers.get("retry-after"));
|
|
219
|
+
const retryAfter = Number.isFinite(headerSeconds) && headerSeconds > 0 ? headerSeconds : typeof data.retryAfterSeconds === "number" ? data.retryAfterSeconds : undefined;
|
|
220
|
+
// What passes with time: a used-up budget, a fault on ZimmerStack's side, a duplicate of a request
|
|
221
|
+
// still running. Every other answer is a verdict on the request itself.
|
|
222
|
+
const passesWithTime = res.status === 429 || res.status >= 500 || code === "IDEMPOTENCY_IN_FLIGHT";
|
|
223
|
+
const error = new ZimmerStackError({
|
|
224
|
+
status: res.status,
|
|
225
|
+
code,
|
|
226
|
+
message: typeof json?.message === "string" && json.message ? json.message : `${wire.operation} answered ${res.status}`,
|
|
227
|
+
operation: wire.operation,
|
|
228
|
+
details: data.details,
|
|
229
|
+
scope: typeof data.scope === "string" ? data.scope : undefined,
|
|
230
|
+
retryAfterSeconds: retryAfter,
|
|
231
|
+
retryable: passesWithTime,
|
|
232
|
+
});
|
|
233
|
+
if (KEY_IS_DEAD.has(code)) {
|
|
234
|
+
this.#dead = error;
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
// A 429 was refused before anything ran, so sending it again is always safe. A 5xx may have run.
|
|
238
|
+
const safeToResend = res.status === 429 || code === "IDEMPOTENCY_IN_FLIGHT" || wire.resendable;
|
|
239
|
+
// A long Retry-After (an hourly or daily budget, a pause) is not worth holding a request open for.
|
|
240
|
+
if (!passesWithTime || !safeToResend || attempt > this.#maxRetries || (retryAfter ?? 0) > this.#maxWaitSeconds)
|
|
241
|
+
throw error;
|
|
242
|
+
const waitMs = ((retryAfter ?? 2 ** (attempt - 1)) + Math.random()) * 1000;
|
|
243
|
+
this.#emit({ type: "retry", operation: wire.operation, attempt, waitMs, reason: code });
|
|
244
|
+
await sleep(waitMs, wire.signal);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** How `forProperty` hands its core to the view it creates, without a public constructor argument. */
|
|
249
|
+
let handoff;
|
|
250
|
+
/* ───────────────────────────── the client ───────────────────────────── */
|
|
251
|
+
/**
|
|
252
|
+
* The ZimmerStack Connect API, from your server.
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* import { ZimmerStack } from "@zimmerstack/connect";
|
|
256
|
+
*
|
|
257
|
+
* const zs = new ZimmerStack(); // reads ZIMMERSTACK_CONNECT_KEY
|
|
258
|
+
* const grid = await zs.grid.load("2026-12-01", "2026-12-14");
|
|
259
|
+
* await zs.grid.save({ rates: [{ ratePlanId: 901, date: "2026-12-24", rate: 5200 }] });
|
|
260
|
+
*
|
|
261
|
+
* Make one per process and reuse it: the pace it keeps is per instance.
|
|
262
|
+
*/
|
|
263
|
+
export class ZimmerStack {
|
|
264
|
+
#core;
|
|
265
|
+
/** "test" on a sandbox key: nothing you send reaches a channel. */
|
|
266
|
+
mode;
|
|
267
|
+
/** The hotel a company key acts on through this instance. */
|
|
268
|
+
propertyId;
|
|
269
|
+
constructor(options = {}) {
|
|
270
|
+
const shared = handoff;
|
|
271
|
+
handoff = undefined;
|
|
272
|
+
this.#core = shared ?? new Core(options);
|
|
273
|
+
this.mode = this.#core.mode;
|
|
274
|
+
if (options.propertyId !== undefined && (!Number.isInteger(options.propertyId) || options.propertyId <= 0)) {
|
|
275
|
+
throw new ZimmerStackUsageError("propertyId must be a property's numeric id (zs.properties.list() names them)");
|
|
276
|
+
}
|
|
277
|
+
this.propertyId = options.propertyId;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* A software vendor's company key: the same client, acting on one hotel. Shares this client's pace,
|
|
281
|
+
* so make as many as you have hotels.
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* const { properties } = await zs.properties.list();
|
|
285
|
+
* for (const p of properties) await zs.forProperty(p.id).sync.get();
|
|
286
|
+
*/
|
|
287
|
+
forProperty(propertyId) {
|
|
288
|
+
handoff = this.#core;
|
|
289
|
+
try {
|
|
290
|
+
return new ZimmerStack({ propertyId });
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
handoff = undefined;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** Never prints the key. */
|
|
297
|
+
toJSON() {
|
|
298
|
+
return { mode: this.mode, propertyId: this.propertyId };
|
|
299
|
+
}
|
|
300
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
301
|
+
return `ZimmerStack { mode: '${this.mode}'${this.propertyId ? `, propertyId: ${this.propertyId}` : ""} }`;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Any operation of the contract by its name, typed. The methods below are this with friendlier names;
|
|
305
|
+
* use it for an operation they do not cover.
|
|
306
|
+
*
|
|
307
|
+
* @example
|
|
308
|
+
* const sync = await zs.request("GET /sync");
|
|
309
|
+
*/
|
|
310
|
+
async request(operation, ...rest) {
|
|
311
|
+
const args = (rest[0] ?? {});
|
|
312
|
+
const meta = OPERATIONS[operation];
|
|
313
|
+
if (!meta)
|
|
314
|
+
throw new ZimmerStackUsageError(`"${operation}" is not an operation of the Connect API`);
|
|
315
|
+
const [method = "", template = ""] = operation.split(" ");
|
|
316
|
+
const path = template.replace(/\{(\w+)\}/g, (_m, name) => {
|
|
317
|
+
const value = args.path?.[name];
|
|
318
|
+
if (value === undefined || value === null || String(value) === "")
|
|
319
|
+
throw new ZimmerStackUsageError(`${operation} needs ${name}`);
|
|
320
|
+
return encodeURIComponent(String(value));
|
|
321
|
+
});
|
|
322
|
+
const url = new URL(this.#core.base + API_PREFIX + path);
|
|
323
|
+
for (const [name, value] of Object.entries(args.query ?? {}))
|
|
324
|
+
if (value !== undefined && value !== null)
|
|
325
|
+
url.searchParams.set(name, String(value));
|
|
326
|
+
const headers = { authorization: this.#core.authorization(), accept: "application/json", "user-agent": `zimmerstack-connect-node/${SDK_VERSION}` };
|
|
327
|
+
if (this.propertyId)
|
|
328
|
+
headers[PROPERTY_HEADER] = String(this.propertyId);
|
|
329
|
+
const body = args.body === undefined ? undefined : JSON.stringify(args.body);
|
|
330
|
+
if (body !== undefined)
|
|
331
|
+
headers["content-type"] = "application/json";
|
|
332
|
+
if (meta.idempotent) {
|
|
333
|
+
// One key per write, reused on every retry of it, so a write that timed out can never land twice.
|
|
334
|
+
if (args.idempotencyKey !== undefined && !IDEMPOTENCY_SHAPE.test(args.idempotencyKey)) {
|
|
335
|
+
throw new ZimmerStackUsageError("idempotencyKey must be 10 to 64 characters of A-Z a-z 0-9 _ -");
|
|
336
|
+
}
|
|
337
|
+
headers[IDEMPOTENCY_HEADER] = args.idempotencyKey ?? crypto.randomUUID();
|
|
338
|
+
}
|
|
339
|
+
const data = await this.#core.send({ operation, method, url, headers, body, write: method !== "GET", resendable: method === "GET" || meta.idempotent, signal: args.signal });
|
|
340
|
+
return data;
|
|
341
|
+
}
|
|
342
|
+
/* ── which hotel ── */
|
|
343
|
+
properties = {
|
|
344
|
+
/** The hotels this key may act on. A company key names one of them on every other call (`forProperty`). */
|
|
345
|
+
list: (options) => this.request("GET /properties", options),
|
|
346
|
+
};
|
|
347
|
+
property = {
|
|
348
|
+
/** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
|
|
349
|
+
get: (options) => this.request("GET /property", options),
|
|
350
|
+
};
|
|
351
|
+
/* ── room types and rate plans ── */
|
|
352
|
+
catalog = {
|
|
353
|
+
/** Room types and rate plans, with the numeric ids every write uses. */
|
|
354
|
+
get: async (options) => {
|
|
355
|
+
const value = await this.request("GET /catalog", options);
|
|
356
|
+
this.#core.catalogs.set(this.propertyId ?? 0, { at: Date.now(), value });
|
|
357
|
+
return value;
|
|
358
|
+
},
|
|
359
|
+
/** Create or change room types by your own `ref`. Needs the scope catalog:write. */
|
|
360
|
+
upsertRoomTypes: (body, options) => this.#structure("PUT /catalog/room-types", { body, ...options }),
|
|
361
|
+
/** Delete a room type; its rate plans go with it. */
|
|
362
|
+
deleteRoomType: (roomTypeId, options) => this.#structure("DELETE /catalog/room-types/{roomTypeId}", { path: { roomTypeId }, ...options }),
|
|
363
|
+
/** Create or change rate plans by your own `ref`. */
|
|
364
|
+
upsertRatePlans: (body, options) => this.#structure("PUT /catalog/rate-plans", { body, ...options }),
|
|
365
|
+
deleteRatePlan: (ratePlanId, options) => this.#structure("DELETE /catalog/rate-plans/{ratePlanId}", { path: { ratePlanId }, ...options }),
|
|
366
|
+
};
|
|
367
|
+
async #structure(operation, args) {
|
|
368
|
+
try {
|
|
369
|
+
return await this.request(operation, ...[args]);
|
|
370
|
+
}
|
|
371
|
+
finally {
|
|
372
|
+
this.#core.catalogs.delete(this.propertyId ?? 0); // whatever happened, the catalog may have changed
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
/** The catalog, kept ten minutes: it changes when someone adds a room type or a plan, not while a grid is open. */
|
|
376
|
+
async #cachedCatalog(signal) {
|
|
377
|
+
const hit = this.#core.catalogs.get(this.propertyId ?? 0);
|
|
378
|
+
if (hit && Date.now() - hit.at < CATALOG_TTL_MS)
|
|
379
|
+
return hit.value;
|
|
380
|
+
return this.catalog.get({ signal });
|
|
381
|
+
}
|
|
382
|
+
/* ── availability, rates, stay rules ── */
|
|
383
|
+
/** One request per 1,000 updates / 5,000 cells, one after another. */
|
|
384
|
+
async #writeAll(operation, updates, options) {
|
|
385
|
+
if (updates.length === 0)
|
|
386
|
+
return [];
|
|
387
|
+
const parts = chunk(updates);
|
|
388
|
+
if (options?.idempotencyKey !== undefined && parts.length > 1 && options.idempotencyKey.length > 60) {
|
|
389
|
+
throw new ZimmerStackUsageError("This write is split into several requests; give an idempotencyKey of at most 60 characters so each part can carry its own");
|
|
390
|
+
}
|
|
391
|
+
const accepted = [];
|
|
392
|
+
for (const [i, part] of parts.entries()) {
|
|
393
|
+
const idempotencyKey = options?.idempotencyKey === undefined ? undefined : parts.length > 1 ? `${options.idempotencyKey}-${i + 1}` : options.idempotencyKey;
|
|
394
|
+
accepted.push(await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal }));
|
|
395
|
+
}
|
|
396
|
+
return accepted;
|
|
397
|
+
}
|
|
398
|
+
availability = {
|
|
399
|
+
/** Rooms left to sell per room type per night, as ZimmerStack's record holds them. Up to 500 days. */
|
|
400
|
+
get: (range, options) => this.request("GET /availability", { query: range, ...options }),
|
|
401
|
+
/**
|
|
402
|
+
* Set rooms left to sell: absolute numbers over date ranges. Answers when the values are in
|
|
403
|
+
* ZimmerStack's record (one answer per request sent; a large write is split for you).
|
|
404
|
+
*/
|
|
405
|
+
set: (updates, options) => this.#writeAll("PUT /availability", updates, options),
|
|
406
|
+
};
|
|
407
|
+
rates = {
|
|
408
|
+
/** Nightly prices per rate plan, in MINOR units (`rateMinor`), before any channel's modifier. */
|
|
409
|
+
get: (range, options) => this.request("GET /rates", { query: range, ...options }),
|
|
410
|
+
/**
|
|
411
|
+
* Set nightly prices in MAJOR units over date ranges (4500 = ₹4,500.00). `currency` may be left
|
|
412
|
+
* out: the hotel's own is filled in. To close a night use `restrictions.set` with stopSell,
|
|
413
|
+
* never a zero price.
|
|
414
|
+
*/
|
|
415
|
+
set: async (updates, options) => {
|
|
416
|
+
if (updates.length === 0)
|
|
417
|
+
return [];
|
|
418
|
+
const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
|
|
419
|
+
return this.#writeAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
|
|
420
|
+
},
|
|
421
|
+
/**
|
|
422
|
+
* Send the hotel's prices to its channels again, unchanged, so nights already there pick the
|
|
423
|
+
* current modifiers up. A hotel may ask a few times a day: make it a deliberate button, never
|
|
424
|
+
* automatic. Watch `rates.dirtyCells` on `sync.get()` fall to 0.
|
|
425
|
+
*/
|
|
426
|
+
resend: (options) => this.request("POST /rates/resend", options),
|
|
427
|
+
};
|
|
428
|
+
restrictions = {
|
|
429
|
+
/** The stay rules per rate plan per night; null = no rule set for that field. */
|
|
430
|
+
get: (range, options) => this.request("GET /restrictions", { query: range, ...options }),
|
|
431
|
+
/** Set stay rules over date ranges: stopSell, closedToArrival, closedToDeparture, minStayArrival, minStayThrough, maxStay. */
|
|
432
|
+
set: (updates, options) => this.#writeAll("PUT /restrictions", updates, options),
|
|
433
|
+
};
|
|
434
|
+
/* ── has it reached the channels? ── */
|
|
435
|
+
sync = {
|
|
436
|
+
/** How far what you sent has travelled: cells still on their way, the last error, where the integration stands. */
|
|
437
|
+
get: (options) => this.request("GET /sync", options),
|
|
438
|
+
};
|
|
439
|
+
batches = {
|
|
440
|
+
/** One write, by the `batchId` its answer carried. */
|
|
441
|
+
get: (batchId, options) => this.request("GET /batches/{batchId}", { path: { batchId }, ...options }),
|
|
442
|
+
/**
|
|
443
|
+
* Wait for a write to reach the channels, asking no more often than every 15 seconds, for at most
|
|
444
|
+
* five minutes. Returns the last status: if it is still "pending", say "still syncing" and let the
|
|
445
|
+
* person look again later. Availability lands in seconds; a full calendar of prices takes minutes.
|
|
446
|
+
*/
|
|
447
|
+
wait: async (batchId, options = {}) => {
|
|
448
|
+
const interval = Math.max(15_000, options.intervalMs ?? 15_000);
|
|
449
|
+
const deadline = Date.now() + (options.timeoutMs ?? 5 * 60_000);
|
|
450
|
+
for (;;) {
|
|
451
|
+
const batch = await this.batches.get(batchId, { signal: options.signal });
|
|
452
|
+
if (batch.status !== "pending" || Date.now() + interval > deadline)
|
|
453
|
+
return batch;
|
|
454
|
+
await sleep(interval, options.signal);
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
};
|
|
458
|
+
/* ── channels and what each is sent ── */
|
|
459
|
+
channels = {
|
|
460
|
+
/**
|
|
461
|
+
* The connected channels (Booking.com, MakeMyTrip, …), each with the price modifier it holds:
|
|
462
|
+
* `[]` = prices go as they are; `null` = a rule set by hand that this API cannot express.
|
|
463
|
+
*/
|
|
464
|
+
list: (options) => this.request("GET /channels", options),
|
|
465
|
+
/**
|
|
466
|
+
* Replace a channel's modifier with these steps (`[]` removes it). Needs the scope
|
|
467
|
+
* channel-modifiers:write.
|
|
468
|
+
*
|
|
469
|
+
* ONE CALL MOVES EVERY PRICE SENT TO THAT CHANNEL FROM THEN ON. Call it when a person saved the
|
|
470
|
+
* setting; never from a loop, a timer or a test against a live key. Prices already on the channel
|
|
471
|
+
* stay as they are until those nights are sent again (`rates.resend`).
|
|
472
|
+
*/
|
|
473
|
+
setModifier: (channelId, steps, options) => this.request("PUT /channels/{channelId}/modifier", { path: { channelId }, body: { steps }, ...options }),
|
|
474
|
+
};
|
|
475
|
+
/* ── bookings from your own booking engine ── */
|
|
476
|
+
bookings = {
|
|
477
|
+
/** Bookings this integration created, newest first. */
|
|
478
|
+
list: (query, options) => this.request("GET /bookings", { query, ...options }),
|
|
479
|
+
/**
|
|
480
|
+
* Create a booking in the hotel's PMS. Always send `externalReference` (your own reservation id):
|
|
481
|
+
* the same value returns the same booking, which makes every retry safe.
|
|
482
|
+
*/
|
|
483
|
+
create: (body, options) => this.request("POST /bookings", { body, ...options }),
|
|
484
|
+
get: (bookingId, options) => this.request("GET /bookings/{bookingId}", { path: { bookingId }, ...options }),
|
|
485
|
+
/** Cancel a booking this integration created; its nights open again on the channels. */
|
|
486
|
+
cancel: (bookingId, body = {}, options) => this.request("POST /bookings/{bookingId}/cancel", { path: { bookingId }, body, ...options }),
|
|
487
|
+
};
|
|
488
|
+
/* ── bookings the OTAs sent ── */
|
|
489
|
+
channelBookings = {
|
|
490
|
+
/** OTA bookings the channel manager delivered, in the webhook's shape. Follow `nextCursor`, or use `all`. */
|
|
491
|
+
list: (query, options) => this.request("GET /channel-bookings", { query, ...options }),
|
|
492
|
+
get: (bookingId, options) => this.request("GET /channel-bookings/{bookingId}", { path: { bookingId }, ...options }),
|
|
493
|
+
/**
|
|
494
|
+
* Every OTA booking changed since `since`, page by page, for reconciling what your webhook missed.
|
|
495
|
+
*
|
|
496
|
+
* @example
|
|
497
|
+
* for await (const booking of zs.channelBookings.all({ since: lastSeen })) save(booking);
|
|
498
|
+
*/
|
|
499
|
+
all: (query, options) => this.#allChannelBookings(query, options),
|
|
500
|
+
};
|
|
501
|
+
async *#allChannelBookings(query, options) {
|
|
502
|
+
let cursor;
|
|
503
|
+
do {
|
|
504
|
+
const page = await this.channelBookings.list({ limit: 100, ...query, cursor }, options);
|
|
505
|
+
yield* page.items;
|
|
506
|
+
cursor = page.nextCursor ?? undefined;
|
|
507
|
+
} while (cursor);
|
|
508
|
+
}
|
|
509
|
+
/* ── the sandbox (zsk_test_ keys only) ── */
|
|
510
|
+
sandbox = {
|
|
511
|
+
bookings: {
|
|
512
|
+
list: (options) => this.request("GET /sandbox/bookings", options),
|
|
513
|
+
/** Pretend an OTA booked: the booking, the availability moved down, and the real webhook to your endpoint. */
|
|
514
|
+
create: (body, options) => this.request("POST /sandbox/bookings", { body, ...options }),
|
|
515
|
+
cancel: (bookingId, options) => this.request("POST /sandbox/bookings/{bookingId}/cancel", { path: { bookingId }, ...options }),
|
|
516
|
+
modify: (bookingId, body, options) => this.request("POST /sandbox/bookings/{bookingId}/modify", { path: { bookingId }, body, ...options }),
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
/* ── the rate grid ── */
|
|
520
|
+
grid = {
|
|
521
|
+
/**
|
|
522
|
+
* The whole grid for a window, ready for a screen: rows are room types with their rate plans,
|
|
523
|
+
* columns are nights. Three reads (four the first time). A window may span 500 days; a screen
|
|
524
|
+
* needs 14 to 60.
|
|
525
|
+
*/
|
|
526
|
+
load: async (from, to, options) => {
|
|
527
|
+
const query = { from, to };
|
|
528
|
+
const [catalog, availability, rates, restrictions] = await Promise.all([
|
|
529
|
+
this.#cachedCatalog(options?.signal),
|
|
530
|
+
this.availability.get(query, options),
|
|
531
|
+
this.rates.get(query, options),
|
|
532
|
+
this.restrictions.get(query, options),
|
|
533
|
+
]);
|
|
534
|
+
return buildGrid({ from, to, catalog, availability, rates, restrictions });
|
|
535
|
+
},
|
|
536
|
+
/**
|
|
537
|
+
* Save what a person changed: single nights in, the fewest ranges out, one request per resource,
|
|
538
|
+
* one after another. Each answer carries a `batchId`: the values are in ZimmerStack's record and
|
|
539
|
+
* on their way to the channels.
|
|
540
|
+
*/
|
|
541
|
+
save: async (edits, options) => {
|
|
542
|
+
const accepted = [];
|
|
543
|
+
if (edits.availability?.length) {
|
|
544
|
+
const ranges = toRanges(edits.availability.map((e) => ({ id: e.roomTypeId, date: e.date, value: e.available })));
|
|
545
|
+
accepted.push(...(await this.availability.set(ranges.map((r) => ({ roomTypeId: r.id, dateFrom: r.dateFrom, dateTo: r.dateTo, available: r.value })), options)));
|
|
546
|
+
}
|
|
547
|
+
if (edits.rates?.length) {
|
|
548
|
+
const ranges = toRanges(edits.rates.map((e) => ({ id: e.ratePlanId, date: e.date, value: e.rate })));
|
|
549
|
+
accepted.push(...(await this.rates.set(ranges.map((r) => ({ ratePlanId: r.id, dateFrom: r.dateFrom, dateTo: r.dateTo, rate: r.value })), options)));
|
|
550
|
+
}
|
|
551
|
+
if (edits.restrictions?.length) {
|
|
552
|
+
const ranges = toRanges(edits.restrictions.map(({ ratePlanId, date, ...rules }) => ({ id: ratePlanId, date, value: rules })));
|
|
553
|
+
accepted.push(...(await this.restrictions.set(ranges.map((r) => ({ ratePlanId: r.id, dateFrom: r.dateFrom, dateTo: r.dateTo, ...r.value })), options)));
|
|
554
|
+
}
|
|
555
|
+
return accepted;
|
|
556
|
+
},
|
|
557
|
+
};
|
|
558
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ErrorCode } from "./generated.js";
|
|
2
|
+
/**
|
|
3
|
+
* What the API answered when it refused a request, or what stopped a request before it was sent.
|
|
4
|
+
*
|
|
5
|
+
* Branch on `code`: it is stable. `message` is written for a person (show it to them) and may change.
|
|
6
|
+
*/
|
|
7
|
+
export declare class ZimmerStackError extends Error {
|
|
8
|
+
/** The HTTP status; 0 when the request never reached the API (see `code`). */
|
|
9
|
+
readonly status: number;
|
|
10
|
+
/**
|
|
11
|
+
* The API's stable code (RATE_LIMITED, RATE_OUT_OF_BAND, SCOPE_MISSING, …), or one of this client's own:
|
|
12
|
+
* LIVE_KEY_IN_TEST, NETWORK_ERROR, TIMEOUT.
|
|
13
|
+
*/
|
|
14
|
+
readonly code: ErrorCode | LocalErrorCode | (string & {});
|
|
15
|
+
/** What the API said about it: the offending fields of a VALIDATION, the budget of a RATE_LIMITED, … */
|
|
16
|
+
readonly details: unknown;
|
|
17
|
+
/** Seconds until the same request can pass, when the API said so (429 and 503). */
|
|
18
|
+
readonly retryAfterSeconds: number | undefined;
|
|
19
|
+
/** Which budget refused, on a RATE_LIMITED (writes, cells-hour, modifier-changes-day, …). */
|
|
20
|
+
readonly scope: string | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* true when the same request may pass later (a used-up budget, a fault on ZimmerStack's side, a
|
|
23
|
+
* network failure). The client has already retried what was worth holding a request open for;
|
|
24
|
+
* anything false is a verdict on the request itself: fix it, never resend it.
|
|
25
|
+
*/
|
|
26
|
+
readonly retryable: boolean;
|
|
27
|
+
/** The operation that failed, as the contract names it: "PUT /rates". Never contains the key. */
|
|
28
|
+
readonly operation: string;
|
|
29
|
+
constructor(init: {
|
|
30
|
+
status: number;
|
|
31
|
+
code: string;
|
|
32
|
+
message: string;
|
|
33
|
+
operation: string;
|
|
34
|
+
details?: unknown;
|
|
35
|
+
retryAfterSeconds?: number;
|
|
36
|
+
scope?: string;
|
|
37
|
+
retryable: boolean;
|
|
38
|
+
cause?: unknown;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/** Codes this client raises itself, before or instead of an answer from the API. */
|
|
42
|
+
export type LocalErrorCode = "LIVE_KEY_IN_TEST" | "NETWORK_ERROR" | "TIMEOUT";
|
|
43
|
+
/** A mistake in how the client was set up or called. Nothing was sent. */
|
|
44
|
+
export declare class ZimmerStackUsageError extends Error {
|
|
45
|
+
constructor(message: string);
|
|
46
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the API answered when it refused a request, or what stopped a request before it was sent.
|
|
3
|
+
*
|
|
4
|
+
* Branch on `code`: it is stable. `message` is written for a person (show it to them) and may change.
|
|
5
|
+
*/
|
|
6
|
+
export class ZimmerStackError extends Error {
|
|
7
|
+
/** The HTTP status; 0 when the request never reached the API (see `code`). */
|
|
8
|
+
status;
|
|
9
|
+
/**
|
|
10
|
+
* The API's stable code (RATE_LIMITED, RATE_OUT_OF_BAND, SCOPE_MISSING, …), or one of this client's own:
|
|
11
|
+
* LIVE_KEY_IN_TEST, NETWORK_ERROR, TIMEOUT.
|
|
12
|
+
*/
|
|
13
|
+
code;
|
|
14
|
+
/** What the API said about it: the offending fields of a VALIDATION, the budget of a RATE_LIMITED, … */
|
|
15
|
+
details;
|
|
16
|
+
/** Seconds until the same request can pass, when the API said so (429 and 503). */
|
|
17
|
+
retryAfterSeconds;
|
|
18
|
+
/** Which budget refused, on a RATE_LIMITED (writes, cells-hour, modifier-changes-day, …). */
|
|
19
|
+
scope;
|
|
20
|
+
/**
|
|
21
|
+
* true when the same request may pass later (a used-up budget, a fault on ZimmerStack's side, a
|
|
22
|
+
* network failure). The client has already retried what was worth holding a request open for;
|
|
23
|
+
* anything false is a verdict on the request itself: fix it, never resend it.
|
|
24
|
+
*/
|
|
25
|
+
retryable;
|
|
26
|
+
/** The operation that failed, as the contract names it: "PUT /rates". Never contains the key. */
|
|
27
|
+
operation;
|
|
28
|
+
constructor(init) {
|
|
29
|
+
super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
|
|
30
|
+
this.name = "ZimmerStackError";
|
|
31
|
+
this.status = init.status;
|
|
32
|
+
this.code = init.code;
|
|
33
|
+
this.details = init.details;
|
|
34
|
+
this.retryAfterSeconds = init.retryAfterSeconds;
|
|
35
|
+
this.scope = init.scope;
|
|
36
|
+
this.retryable = init.retryable;
|
|
37
|
+
this.operation = init.operation;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** A mistake in how the client was set up or called. Nothing was sent. */
|
|
41
|
+
export class ZimmerStackUsageError extends Error {
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "ZimmerStackUsageError";
|
|
45
|
+
}
|
|
46
|
+
}
|