@kite-sa/sdk 0.6.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  Formerly `@darak-app/sdk`, which is deprecated. Versions before 0.5.0 were published under that name.
4
4
 
5
+ ## 0.7.0
6
+
7
+ - Writes are safe to retry. A POST without an `Idempotency-Key` now gets one,
8
+ made once per call and reused on every retry, so a lost response can no longer
9
+ create a second API key, webhook or export. Pass your own as before
10
+ (`kite.organization.keys.create(body, { "Idempotency-Key": myKey })`); the
11
+ header name is matched case-insensitively. GET requests carry none.
12
+ - `kite.paginate(fetchPage, params)` (also exported as `paginate`) follows the
13
+ cursor of any list endpoint, e.g.
14
+ `kite.paginate((p) => kite.transactions.search(p), { city: "riyadh" })`.
15
+ `listings.searchAll` now uses it.
16
+ - `@kite-sa/sdk/webhooks` exports `verifyWebhookSignature(header, rawBody, secret)`
17
+ for the `Kite-Signature` header: HMAC-SHA256 over `t.body`, constant-time
18
+ compare, a five-minute window, and an array of secrets during a rotation. It is
19
+ a separate entry point because it needs `node:crypto`.
20
+ - New method `projects.availability(id, params)` for `GET /projects/{id}/availability`: a project's unit
21
+ count and source-reported available units over time, as daily, weekly or
22
+ monthly points with the units absorbed since the previous point.
23
+ - New webhook management methods: `organization.webhooks.update()`
24
+ (`POST /organization/webhooks/{webhook_id}/update`), `organization.webhooks.enable()`
25
+ (`.../enable`) and `organization.webhooks.rotateSecret()` (`.../rotate-secret`).
26
+ `organization.webhooks.deliveries()` takes `cursor` and its response has `pagination`.
27
+ - `verifyWebhookSignature` accepts a header with several `v1` entries, which
28
+ deliveries carry while a rotated secret's overlap lasts; any entry may match.
29
+
5
30
  ## 0.6.0
6
31
 
7
32
  - New methods for the endpoints added since 0.5.0:
package/README.md CHANGED
@@ -31,6 +31,9 @@ Get a key at [platform.kite.sa](https://platform.kite.sa). Keys are secret: call
31
31
 
32
32
  - Types for every parameter and response, generated from the API's OpenAPI spec.
33
33
  - Retries for `429` and `5xx` (and network errors) that honor `Retry-After`. A monthly-quota `429` isn't waited out; it throws.
34
+ - Safe write retries: a POST is sent with an `Idempotency-Key`, generated for you unless you pass one (`kite.organization.keys.create(body, { "Idempotency-Key": myKey })`), and every retry reuses it, so a lost response never creates a second key, webhook or export.
35
+ - `kite.paginate((p) => kite.transactions.search(p), { city: "riyadh" })` follows the cursor of any list endpoint (path arguments go in the closure: `(p) => kite.projects.units(42, p)`); `listings.searchAll` is the same for listings.
36
+ - Webhook verification: `import { verifyWebhookSignature } from "@kite-sa/sdk/webhooks"` and call it with the `Kite-Signature` header, the raw body and your signing secret (or an array of secrets during a rotation). It checks the HMAC in constant time and rejects signatures older than five minutes. Node only (it uses `node:crypto`).
34
37
  - `KiteError` with `status`, `code`, `message`, `param` and `requestId`. Branch on `code`; quote `requestId` to support.
35
38
 
36
39
  - Namespaces generated from the API's OpenAPI spec, so they track it exactly:
@@ -1067,6 +1067,24 @@ export declare function createEndpoints(request: Request): {
1067
1067
  delivered_at: unknown;
1068
1068
  created_at: string;
1069
1069
  }[];
1070
+ pagination: import("./openapi-zod/models.js").Pagination;
1071
+ }>;
1072
+ /**
1073
+ * Re-enable a webhook endpoint. Turns a disabled endpoint back on and resets
1074
+ * its failure count.
1075
+ */
1076
+ readonly enable: (webhookId: string | number, headers?: HeaderOf<"organization.webhooks.enable">) => Promise<{
1077
+ data: {
1078
+ id: string;
1079
+ url: string;
1080
+ event_types: string[];
1081
+ filters: Record<string, unknown>;
1082
+ description: string | null;
1083
+ status: string;
1084
+ disabled_reason: string | null;
1085
+ consecutive_failures: number;
1086
+ created_at: string;
1087
+ };
1070
1088
  }>;
1071
1089
  /** List webhook endpoints. Every endpoint this organization has subscribed. */
1072
1090
  readonly list: () => Promise<{
@@ -1092,9 +1110,69 @@ export declare function createEndpoints(request: Request): {
1092
1110
  status: string;
1093
1111
  };
1094
1112
  }>;
1113
+ /**
1114
+ * Rotate a webhook signing secret. Issues a new signing secret, shown once in
1115
+ * the response.
1116
+ */
1117
+ readonly rotateSecret: (webhookId: string | number, body: BodyOf<"organization.webhooks.rotate_secret">, headers?: HeaderOf<"organization.webhooks.rotate_secret">) => Promise<{
1118
+ data: {
1119
+ id: string;
1120
+ secret: string;
1121
+ previous_secret_expires_at: unknown;
1122
+ };
1123
+ }>;
1124
+ /**
1125
+ * Update a webhook endpoint. Changes the URL, event types, filters or
1126
+ * description of an endpoint; send only what changes.
1127
+ */
1128
+ readonly update: (webhookId: string | number, body: BodyOf<"organization.webhooks.update">, headers?: HeaderOf<"organization.webhooks.update">) => Promise<{
1129
+ data: {
1130
+ id: string;
1131
+ url: string;
1132
+ event_types: string[];
1133
+ filters: Record<string, unknown>;
1134
+ description: string | null;
1135
+ status: string;
1136
+ disabled_reason: string | null;
1137
+ consecutive_failures: number;
1138
+ created_at: string;
1139
+ };
1140
+ }>;
1095
1141
  };
1096
1142
  };
1097
1143
  readonly projects: {
1144
+ /**
1145
+ * Get a project's unit availability over time. Daily snapshots of a project's
1146
+ * unit count and the availability its source reports, as daily, weekly or
1147
+ * monthly points, each with the units absorbed since the previous point. This is
1148
+ * **listed availability**, not contracts: it comes from what the project's
1149
+ * source page showed on the day, so a unit counts as absorbed when the source
1150
+ * stops showing it, not when it is sold or leased.
1151
+ */
1152
+ readonly availability: (id: string | number, params?: QueryOf<"projects.availability">) => Promise<{
1153
+ data: {
1154
+ project_id: number;
1155
+ interval: string;
1156
+ from: string;
1157
+ to: string;
1158
+ unit_type: string | null;
1159
+ coverage: {
1160
+ first_snapshot: string | null;
1161
+ last_snapshot: string | null;
1162
+ snapshots: number;
1163
+ };
1164
+ points: {
1165
+ date: string;
1166
+ project_status: string | null;
1167
+ total_units: unknown;
1168
+ available_units: unknown;
1169
+ absorbed_since_previous: unknown;
1170
+ unit_types: unknown;
1171
+ starting_price: unknown;
1172
+ source: string;
1173
+ }[];
1174
+ };
1175
+ }>;
1098
1176
  /** List developers. Developers with active projects on Kite, most projects first. */
1099
1177
  readonly developers: (params?: QueryOf<"projects.developers">) => Promise<{
1100
1178
  data: {
package/dist/generated.js CHANGED
@@ -257,6 +257,11 @@ export function createEndpoints(request) {
257
257
  * answered.
258
258
  */
259
259
  deliveries: (webhookId, params) => request("GET", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/deliveries`, { query: (params ?? {}) }),
260
+ /**
261
+ * Re-enable a webhook endpoint. Turns a disabled endpoint back on and resets
262
+ * its failure count.
263
+ */
264
+ enable: (webhookId, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/enable`, { headers: headers }),
260
265
  /** List webhook endpoints. Every endpoint this organization has subscribed. */
261
266
  list: () => request("GET", "/organization/webhooks"),
262
267
  /**
@@ -264,9 +269,28 @@ export function createEndpoints(request) {
264
269
  * `event_id` so a receiver that already handled it can recognise the repeat.
265
270
  */
266
271
  replay: (webhookId, deliveryId, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/deliveries/${encodeURIComponent(String(deliveryId))}/replay`, { headers: headers }),
272
+ /**
273
+ * Rotate a webhook signing secret. Issues a new signing secret, shown once in
274
+ * the response.
275
+ */
276
+ rotateSecret: (webhookId, body, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/rotate-secret`, { body, headers: headers }),
277
+ /**
278
+ * Update a webhook endpoint. Changes the URL, event types, filters or
279
+ * description of an endpoint; send only what changes.
280
+ */
281
+ update: (webhookId, body, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/update`, { body, headers: headers }),
267
282
  },
268
283
  },
269
284
  projects: {
285
+ /**
286
+ * Get a project's unit availability over time. Daily snapshots of a project's
287
+ * unit count and the availability its source reports, as daily, weekly or
288
+ * monthly points, each with the units absorbed since the previous point. This is
289
+ * **listed availability**, not contracts: it comes from what the project's
290
+ * source page showed on the day, so a unit counts as absorbed when the source
291
+ * stops showing it, not when it is sold or leased.
292
+ */
293
+ availability: (id, params) => request("GET", `/projects/${encodeURIComponent(String(id))}/availability`, { query: (params ?? {}) }),
270
294
  /** List developers. Developers with active projects on Kite, most projects first. */
271
295
  developers: (params) => request("GET", "/developers", {
272
296
  query: (params ?? {}),
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { type Endpoints } from "./generated.js";
2
2
  import type { operations } from "./openapi.js";
3
+ import { type Page } from "./paginate.js";
3
4
  export type { operations } from "./openapi.js";
4
5
  export type { Endpoints } from "./generated.js";
6
+ export { paginate, type Page } from "./paginate.js";
5
7
  type Op = keyof operations;
6
8
  type QueryOf<K extends Op> = operations[K]["parameters"] extends {
7
9
  query?: infer Q;
@@ -34,7 +36,11 @@ export interface KiteOptions {
34
36
  /** Defaults to the KITE_API_KEY environment variable. */
35
37
  apiKey?: string;
36
38
  baseUrl?: string;
37
- /** Retries for 429, 5xx and network errors (default 2). */
39
+ /**
40
+ * Retries for 429, 5xx and network errors (default 2). A POST is retried
41
+ * under one Idempotency-Key, which the client generates when you pass none,
42
+ * so a retry can never run a create twice.
43
+ */
38
44
  maxRetries?: number;
39
45
  /** Per-attempt timeout in milliseconds (default 30000). */
40
46
  timeoutMs?: number;
@@ -43,7 +49,7 @@ export interface KiteOptions {
43
49
  }
44
50
  type Query = Record<string, string | number | boolean | readonly (string | number)[] | undefined>;
45
51
  /** Kept in step with package.json by src/index.test.ts. */
46
- export declare const VERSION = "0.6.0";
52
+ export declare const VERSION = "0.7.0";
47
53
  /** Arrays go comma-separated, as the API expects; unset values are dropped. */
48
54
  export declare function toSearchParams(query?: Query): string;
49
55
  /**
@@ -67,7 +73,25 @@ export declare class Kite {
67
73
  private readonly timeoutMs;
68
74
  private readonly fetchImpl;
69
75
  constructor(options?: KiteOptions);
70
- /** Low-level call for any endpoint; prefer the typed helpers below. */
76
+ /**
77
+ * Follows `pagination.next_cursor` for any cursor-paginated list endpoint and
78
+ * yields every item, fetching pages as you iterate:
79
+ *
80
+ * for await (const t of kite.paginate((p) => kite.transactions.search(p), { city: "riyadh" })) {}
81
+ *
82
+ * Path arguments go in the closure: `(p) => kite.projects.units(42, p)`.
83
+ * Stops at the end of the results or at your plan's paging depth.
84
+ */
85
+ paginate<P extends {
86
+ cursor?: string;
87
+ }, T>(fetchPage: (params: P) => Promise<Page<T>>, params: Omit<P, "cursor">): AsyncGenerator<T>;
88
+ /**
89
+ * Low-level call for any endpoint; prefer the typed helpers below.
90
+ *
91
+ * A POST without an `Idempotency-Key` header gets a fresh one, made once here
92
+ * and sent again on every retry, so a lost response can't run the write twice
93
+ * (a second API key whose secret the caller never saw).
94
+ */
71
95
  request<T>(method: "GET" | "POST", path: string, options?: {
72
96
  query?: Query;
73
97
  body?: unknown;
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { createEndpoints } from "./generated.js";
2
+ import { paginate } from "./paginate.js";
3
+ export { paginate } from "./paginate.js";
2
4
  // ── Errors ────────────────────────────────────────────────────────────────
3
5
  /** Any non-2xx response. Branch on `code`; `message` is for humans. */
4
6
  export class KiteError extends Error {
@@ -22,7 +24,7 @@ export class KiteError extends Error {
22
24
  }
23
25
  }
24
26
  /** Kept in step with package.json by src/index.test.ts. */
25
- export const VERSION = "0.6.0";
27
+ export const VERSION = "0.7.0";
26
28
  const USER_AGENT = `kite-sa-js/${VERSION}`;
27
29
  /** Longest Retry-After worth waiting for; anything longer (a monthly quota) throws. */
28
30
  const MAX_RETRY_WAIT_S = 60;
@@ -59,16 +61,7 @@ export class Kite {
59
61
  Object.assign(this, endpoints);
60
62
  this.listings = {
61
63
  ...endpoints.listings,
62
- searchAll: async function* (params) {
63
- let cursor;
64
- do {
65
- const page = await this.listings.search({ ...params, cursor });
66
- yield* page.data;
67
- cursor = page.pagination.has_more
68
- ? (page.pagination.next_cursor ?? undefined)
69
- : undefined;
70
- } while (cursor);
71
- }.bind(this),
64
+ searchAll: (params) => paginate((p) => this.listings.search(p), params),
72
65
  };
73
66
  this.cities = {
74
67
  list: endpoints.reference.cities,
@@ -76,9 +69,30 @@ export class Kite {
76
69
  directions: endpoints.reference.directions,
77
70
  };
78
71
  }
79
- /** Low-level call for any endpoint; prefer the typed helpers below. */
72
+ /**
73
+ * Follows `pagination.next_cursor` for any cursor-paginated list endpoint and
74
+ * yields every item, fetching pages as you iterate:
75
+ *
76
+ * for await (const t of kite.paginate((p) => kite.transactions.search(p), { city: "riyadh" })) {}
77
+ *
78
+ * Path arguments go in the closure: `(p) => kite.projects.units(42, p)`.
79
+ * Stops at the end of the results or at your plan's paging depth.
80
+ */
81
+ paginate(fetchPage, params) {
82
+ return paginate(fetchPage, params);
83
+ }
84
+ /**
85
+ * Low-level call for any endpoint; prefer the typed helpers below.
86
+ *
87
+ * A POST without an `Idempotency-Key` header gets a fresh one, made once here
88
+ * and sent again on every retry, so a lost response can't run the write twice
89
+ * (a second API key whose secret the caller never saw).
90
+ */
80
91
  async request(method, path, options = {}) {
81
92
  const url = `${this.baseUrl}${path}${toSearchParams(options.query)}`;
93
+ const callerHeaders = Object.fromEntries(Object.entries(options.headers ?? {}).filter((entry) => entry[1] !== undefined));
94
+ const hasKey = Object.keys(callerHeaders).some((k) => k.toLowerCase() === "idempotency-key");
95
+ const idempotency = method === "POST" && !hasKey ? { "Idempotency-Key": newIdempotencyKey() } : {};
82
96
  for (let attempt = 0;; attempt++) {
83
97
  let res;
84
98
  try {
@@ -86,7 +100,8 @@ export class Kite {
86
100
  method,
87
101
  headers: {
88
102
  // Caller-supplied optional headers cannot replace the SDK key.
89
- ...Object.fromEntries(Object.entries(options.headers ?? {}).filter((entry) => entry[1] !== undefined)),
103
+ ...callerHeaders,
104
+ ...idempotency,
90
105
  Authorization: `Bearer ${this.apiKey}`,
91
106
  Accept: "application/json",
92
107
  // Browsers forbid setting User-Agent, and the request fails outright
@@ -132,6 +147,15 @@ export class Kite {
132
147
  return this.reference.enums();
133
148
  }
134
149
  }
150
+ function newIdempotencyKey() {
151
+ const c = globalThis.crypto;
152
+ if (c?.randomUUID)
153
+ return c.randomUUID();
154
+ // Node 18 has no global `crypto` without a flag. Keys are scoped to one API key,
155
+ // so collision resistance, not unpredictability, is what matters here.
156
+ const rand = () => Math.random().toString(36).slice(2);
157
+ return `${Date.now().toString(36)}-${rand()}-${rand()}`;
158
+ }
135
159
  /** Exponential backoff with jitter, in milliseconds: ~0.5s, 1s, 2s, … */
136
160
  function backoff(attempt) {
137
161
  return Math.min(8000, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5);
@@ -1442,6 +1442,43 @@ export declare function projectsUnits(id: number, params?: {
1442
1442
  }[];
1443
1443
  pagination: Pagination;
1444
1444
  }>;
1445
+ /**
1446
+ * @throws {ApiError<400, Error>}
1447
+ * @throws {ApiError<401, Error>}
1448
+ * @throws {ApiError<403, Error>}
1449
+ * @throws {ApiError<404, Error>}
1450
+ * @throws {ApiError<429, Error>}
1451
+ * @throws {ApiError<500, Error>}
1452
+ */
1453
+ export declare function projectsAvailability(id: number, params?: {
1454
+ interval?: "daily" | "weekly" | "monthly";
1455
+ from?: string;
1456
+ to?: string;
1457
+ unitType?: string;
1458
+ }, config?: Partial<ClientConfig>): Promise<{
1459
+ data: {
1460
+ project_id: number;
1461
+ interval: string;
1462
+ from: string;
1463
+ to: string;
1464
+ unit_type: string | null;
1465
+ coverage: {
1466
+ first_snapshot: string | null;
1467
+ last_snapshot: string | null;
1468
+ snapshots: number;
1469
+ };
1470
+ points: {
1471
+ date: string;
1472
+ project_status: string | null;
1473
+ total_units: unknown;
1474
+ available_units: unknown;
1475
+ absorbed_since_previous: unknown;
1476
+ unit_types: unknown;
1477
+ starting_price: unknown;
1478
+ source: string;
1479
+ }[];
1480
+ };
1481
+ }>;
1445
1482
  /**
1446
1483
  * @throws {ApiError<400, Error>}
1447
1484
  * @throws {ApiError<401, Error>}
@@ -1828,6 +1865,91 @@ export declare function organizationWebhooksCreate(body: {
1828
1865
  secret: string;
1829
1866
  };
1830
1867
  }>;
1868
+ /**
1869
+ * @throws {ApiError<400, Error>}
1870
+ * @throws {ApiError<401, Error>}
1871
+ * @throws {ApiError<403, Error>}
1872
+ * @throws {ApiError<404, Error>}
1873
+ * @throws {ApiError<409, Error>}
1874
+ * @throws {ApiError<429, Error>}
1875
+ * @throws {ApiError<500, Error>}
1876
+ */
1877
+ export declare function organizationWebhooksUpdate(webhookId: string, body: {
1878
+ url?: string;
1879
+ event_types?: string[];
1880
+ filters?: {
1881
+ city: string;
1882
+ listing_type?: string;
1883
+ listing_category?: string;
1884
+ property_type?: string;
1885
+ neighborhood?: string;
1886
+ beds?: string;
1887
+ beds_min?: string;
1888
+ price_min?: string;
1889
+ price_max?: string;
1890
+ area_min?: string;
1891
+ area_max?: string;
1892
+ };
1893
+ description?: unknown;
1894
+ }, params?: {
1895
+ idempotencyKey?: string;
1896
+ }, config?: Partial<ClientConfig>): Promise<{
1897
+ data: {
1898
+ id: string;
1899
+ url: string;
1900
+ event_types: string[];
1901
+ filters: Record<string, unknown>;
1902
+ description: string | null;
1903
+ status: string;
1904
+ disabled_reason: string | null;
1905
+ consecutive_failures: number;
1906
+ created_at: string;
1907
+ };
1908
+ }>;
1909
+ /**
1910
+ * @throws {ApiError<400, Error>}
1911
+ * @throws {ApiError<401, Error>}
1912
+ * @throws {ApiError<403, Error>}
1913
+ * @throws {ApiError<404, Error>}
1914
+ * @throws {ApiError<409, Error>}
1915
+ * @throws {ApiError<429, Error>}
1916
+ * @throws {ApiError<500, Error>}
1917
+ */
1918
+ export declare function organizationWebhooksEnable(webhookId: string, params?: {
1919
+ idempotencyKey?: string;
1920
+ }, config?: Partial<ClientConfig>): Promise<{
1921
+ data: {
1922
+ id: string;
1923
+ url: string;
1924
+ event_types: string[];
1925
+ filters: Record<string, unknown>;
1926
+ description: string | null;
1927
+ status: string;
1928
+ disabled_reason: string | null;
1929
+ consecutive_failures: number;
1930
+ created_at: string;
1931
+ };
1932
+ }>;
1933
+ /**
1934
+ * @throws {ApiError<400, Error>}
1935
+ * @throws {ApiError<401, Error>}
1936
+ * @throws {ApiError<403, Error>}
1937
+ * @throws {ApiError<404, Error>}
1938
+ * @throws {ApiError<409, Error>}
1939
+ * @throws {ApiError<429, Error>}
1940
+ * @throws {ApiError<500, Error>}
1941
+ */
1942
+ export declare function organizationWebhooksRotateSecret(webhookId: string, body: {
1943
+ overlap_seconds?: number;
1944
+ }, params?: {
1945
+ idempotencyKey?: string;
1946
+ }, config?: Partial<ClientConfig>): Promise<{
1947
+ data: {
1948
+ id: string;
1949
+ secret: string;
1950
+ previous_secret_expires_at: unknown;
1951
+ };
1952
+ }>;
1831
1953
  /**
1832
1954
  * @throws {ApiError<400, Error>}
1833
1955
  * @throws {ApiError<401, Error>}
@@ -1855,6 +1977,7 @@ export declare function organizationWebhooksDelete(webhookId: string, params?: {
1855
1977
  */
1856
1978
  export declare function organizationWebhooksDeliveries(webhookId: string, params?: {
1857
1979
  limit?: number;
1980
+ cursor?: string;
1858
1981
  }, config?: Partial<ClientConfig>): Promise<{
1859
1982
  data: {
1860
1983
  id: number;
@@ -1868,6 +1991,7 @@ export declare function organizationWebhooksDeliveries(webhookId: string, params
1868
1991
  delivered_at: unknown;
1869
1992
  created_at: string;
1870
1993
  }[];
1994
+ pagination: Pagination;
1871
1995
  }>;
1872
1996
  /**
1873
1997
  * @throws {ApiError<400, Error>}
@@ -1001,6 +1001,27 @@ export async function projectsUnits(id, params, config) {
1001
1001
  const res = await _request("GET", `/projects/${encodeURIComponent(id)}/units`, { searchParams }, config);
1002
1002
  return res.json();
1003
1003
  }
1004
+ /**
1005
+ * @throws {ApiError<400, Error>}
1006
+ * @throws {ApiError<401, Error>}
1007
+ * @throws {ApiError<403, Error>}
1008
+ * @throws {ApiError<404, Error>}
1009
+ * @throws {ApiError<429, Error>}
1010
+ * @throws {ApiError<500, Error>}
1011
+ */
1012
+ export async function projectsAvailability(id, params, config) {
1013
+ const searchParams = new URLSearchParams();
1014
+ if (params?.interval != null)
1015
+ searchParams.set("interval", String(params.interval));
1016
+ if (params?.from != null)
1017
+ searchParams.set("from", String(params.from));
1018
+ if (params?.to != null)
1019
+ searchParams.set("to", String(params.to));
1020
+ if (params?.unitType != null)
1021
+ searchParams.set("unit_type", String(params.unitType));
1022
+ const res = await _request("GET", `/projects/${encodeURIComponent(id)}/availability`, { searchParams }, config);
1023
+ return res.json();
1024
+ }
1004
1025
  /**
1005
1026
  * @throws {ApiError<400, Error>}
1006
1027
  * @throws {ApiError<401, Error>}
@@ -1283,6 +1304,54 @@ export async function organizationWebhooksCreate(body, params, config) {
1283
1304
  const res = await _request("POST", "/organization/webhooks", { body, extraHeaders }, config);
1284
1305
  return res.json();
1285
1306
  }
1307
+ /**
1308
+ * @throws {ApiError<400, Error>}
1309
+ * @throws {ApiError<401, Error>}
1310
+ * @throws {ApiError<403, Error>}
1311
+ * @throws {ApiError<404, Error>}
1312
+ * @throws {ApiError<409, Error>}
1313
+ * @throws {ApiError<429, Error>}
1314
+ * @throws {ApiError<500, Error>}
1315
+ */
1316
+ export async function organizationWebhooksUpdate(webhookId, body, params, config) {
1317
+ const extraHeaders = {
1318
+ ...(params?.idempotencyKey != null ? { "Idempotency-Key": String(params.idempotencyKey) } : {}),
1319
+ };
1320
+ const res = await _request("POST", `/organization/webhooks/${encodeURIComponent(webhookId)}/update`, { body, extraHeaders }, config);
1321
+ return res.json();
1322
+ }
1323
+ /**
1324
+ * @throws {ApiError<400, Error>}
1325
+ * @throws {ApiError<401, Error>}
1326
+ * @throws {ApiError<403, Error>}
1327
+ * @throws {ApiError<404, Error>}
1328
+ * @throws {ApiError<409, Error>}
1329
+ * @throws {ApiError<429, Error>}
1330
+ * @throws {ApiError<500, Error>}
1331
+ */
1332
+ export async function organizationWebhooksEnable(webhookId, params, config) {
1333
+ const extraHeaders = {
1334
+ ...(params?.idempotencyKey != null ? { "Idempotency-Key": String(params.idempotencyKey) } : {}),
1335
+ };
1336
+ const res = await _request("POST", `/organization/webhooks/${encodeURIComponent(webhookId)}/enable`, { extraHeaders }, config);
1337
+ return res.json();
1338
+ }
1339
+ /**
1340
+ * @throws {ApiError<400, Error>}
1341
+ * @throws {ApiError<401, Error>}
1342
+ * @throws {ApiError<403, Error>}
1343
+ * @throws {ApiError<404, Error>}
1344
+ * @throws {ApiError<409, Error>}
1345
+ * @throws {ApiError<429, Error>}
1346
+ * @throws {ApiError<500, Error>}
1347
+ */
1348
+ export async function organizationWebhooksRotateSecret(webhookId, body, params, config) {
1349
+ const extraHeaders = {
1350
+ ...(params?.idempotencyKey != null ? { "Idempotency-Key": String(params.idempotencyKey) } : {}),
1351
+ };
1352
+ const res = await _request("POST", `/organization/webhooks/${encodeURIComponent(webhookId)}/rotate-secret`, { body, extraHeaders }, config);
1353
+ return res.json();
1354
+ }
1286
1355
  /**
1287
1356
  * @throws {ApiError<400, Error>}
1288
1357
  * @throws {ApiError<401, Error>}
@@ -1311,6 +1380,8 @@ export async function organizationWebhooksDeliveries(webhookId, params, config)
1311
1380
  const searchParams = new URLSearchParams();
1312
1381
  if (params?.limit != null)
1313
1382
  searchParams.set("limit", String(params.limit));
1383
+ if (params?.cursor != null)
1384
+ searchParams.set("cursor", String(params.cursor));
1314
1385
  const res = await _request("GET", `/organization/webhooks/${encodeURIComponent(webhookId)}/deliveries`, { searchParams }, config);
1315
1386
  return res.json();
1316
1387
  }
package/dist/openapi.d.ts CHANGED
@@ -394,6 +394,18 @@ export interface operations {
394
394
  };
395
395
  };
396
396
  };
397
+ "projects.availability": {
398
+ parameters: {
399
+ query?: Pick<SnakeKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").projectsAvailability>[1]>>, "interval" | "from" | "to" | "unit_type">;
400
+ };
401
+ responses: {
402
+ 200: {
403
+ content: {
404
+ "application/json": Awaited<ReturnType<typeof import("./openapi-zod/client.js").projectsAvailability>>;
405
+ };
406
+ };
407
+ };
408
+ };
397
409
  "projects.units_search": {
398
410
  parameters: {
399
411
  query?: Pick<SnakeKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").projectsUnitsSearch>[0]>>, "city" | "neighborhood_id" | "developer" | "status" | "project_type" | "listing_category" | "features" | "banks" | "listing_type" | "property_type" | "bedrooms" | "bedrooms_min" | "bedrooms_max" | "bathrooms" | "bathrooms_min" | "price_min" | "price_max" | "area_min" | "area_max" | "sort" | "limit" | "cursor">;
@@ -589,6 +601,52 @@ export interface operations {
589
601
  };
590
602
  };
591
603
  };
604
+ "organization.webhooks.update": {
605
+ parameters: {
606
+ header?: Pick<HeaderKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksUpdate>[2]>>, "Idempotency-Key">;
607
+ };
608
+ requestBody: {
609
+ content: {
610
+ "application/json": Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksUpdate>[1];
611
+ };
612
+ };
613
+ responses: {
614
+ 200: {
615
+ content: {
616
+ "application/json": Awaited<ReturnType<typeof import("./openapi-zod/client.js").organizationWebhooksUpdate>>;
617
+ };
618
+ };
619
+ };
620
+ };
621
+ "organization.webhooks.enable": {
622
+ parameters: {
623
+ header?: Pick<HeaderKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksEnable>[1]>>, "Idempotency-Key">;
624
+ };
625
+ responses: {
626
+ 200: {
627
+ content: {
628
+ "application/json": Awaited<ReturnType<typeof import("./openapi-zod/client.js").organizationWebhooksEnable>>;
629
+ };
630
+ };
631
+ };
632
+ };
633
+ "organization.webhooks.rotate_secret": {
634
+ parameters: {
635
+ header?: Pick<HeaderKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksRotateSecret>[2]>>, "Idempotency-Key">;
636
+ };
637
+ requestBody: {
638
+ content: {
639
+ "application/json": Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksRotateSecret>[1];
640
+ };
641
+ };
642
+ responses: {
643
+ 200: {
644
+ content: {
645
+ "application/json": Awaited<ReturnType<typeof import("./openapi-zod/client.js").organizationWebhooksRotateSecret>>;
646
+ };
647
+ };
648
+ };
649
+ };
592
650
  "organization.webhooks.delete": {
593
651
  parameters: {
594
652
  header?: Pick<HeaderKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksDelete>[1]>>, "Idempotency-Key">;
@@ -603,7 +661,7 @@ export interface operations {
603
661
  };
604
662
  "organization.webhooks.deliveries": {
605
663
  parameters: {
606
- query?: Pick<SnakeKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksDeliveries>[1]>>, "limit">;
664
+ query?: Pick<SnakeKeys<NonNullable<Parameters<typeof import("./openapi-zod/client.js").organizationWebhooksDeliveries>[1]>>, "limit" | "cursor">;
607
665
  };
608
666
  responses: {
609
667
  200: {
@@ -0,0 +1,18 @@
1
+ /** The shape every cursor-paginated list endpoint returns. */
2
+ export interface Page<T> {
3
+ data: T[];
4
+ pagination: {
5
+ has_more: boolean;
6
+ next_cursor?: string | null;
7
+ };
8
+ }
9
+ /**
10
+ * Yields every item of a cursor-paginated endpoint, fetching the next page only
11
+ * when the previous one is consumed. `fetchPage` receives `params` plus the
12
+ * cursor, so path arguments go in a closure:
13
+ *
14
+ * paginate((p) => kite.projects.units(42, p), { beds: 2 })
15
+ */
16
+ export declare function paginate<P extends {
17
+ cursor?: string;
18
+ }, T>(fetchPage: (params: P) => Promise<Page<T>>, params: Omit<P, "cursor">): AsyncGenerator<T>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Yields every item of a cursor-paginated endpoint, fetching the next page only
3
+ * when the previous one is consumed. `fetchPage` receives `params` plus the
4
+ * cursor, so path arguments go in a closure:
5
+ *
6
+ * paginate((p) => kite.projects.units(42, p), { beds: 2 })
7
+ */
8
+ export async function* paginate(fetchPage, params) {
9
+ let cursor;
10
+ do {
11
+ const page = await fetchPage({ ...params, cursor });
12
+ yield* page.data;
13
+ cursor = page.pagination.has_more ? (page.pagination.next_cursor ?? undefined) : undefined;
14
+ } while (cursor);
15
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Header Kite signs each webhook delivery with. Deliveries also carry the
3
+ * deprecated `Darak-Signature` with the same value; either verifies.
4
+ */
5
+ export declare const SIGNATURE_HEADER = "Kite-Signature";
6
+ /** How old a signature may be before it is rejected, in seconds. */
7
+ export declare const TOLERANCE_SECONDS = 300;
8
+ export interface VerifyResult {
9
+ valid: boolean;
10
+ /** Why not, for your logs. Never send it back to the caller. */
11
+ reason?: "malformed" | "no_match" | "too_old";
12
+ }
13
+ export interface VerifyOptions {
14
+ /** Seconds a signature stays valid (default 300). */
15
+ toleranceSeconds?: number;
16
+ /** Current time in Unix seconds; for tests. */
17
+ now?: number;
18
+ }
19
+ /**
20
+ * Checks a `Kite-Signature` header (`t=<unix>,v1=<hex>`) against the raw
21
+ * request body: HMAC-SHA256 of `${t}.${body}` under your endpoint's signing
22
+ * secret, compared in constant time. Pass the body exactly as received, before
23
+ * any JSON parsing. `secret` may be an array so a rotation can overlap: the old
24
+ * secret keeps verifying until the deploy carrying the new one is through.
25
+ * During a rotation overlap the header has a `v1` entry per live secret; the
26
+ * signature is valid if any of them matches.
27
+ *
28
+ * Imported from `@kite-sa/sdk/webhooks` because it needs `node:crypto`; the
29
+ * main entry stays runtime-neutral.
30
+ */
31
+ export declare function verifyWebhookSignature(header: string | null | undefined, body: string, secret: string | readonly string[], options?: VerifyOptions): VerifyResult;
@@ -0,0 +1,49 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ /**
3
+ * Header Kite signs each webhook delivery with. Deliveries also carry the
4
+ * deprecated `Darak-Signature` with the same value; either verifies.
5
+ */
6
+ export const SIGNATURE_HEADER = "Kite-Signature";
7
+ /** How old a signature may be before it is rejected, in seconds. */
8
+ export const TOLERANCE_SECONDS = 300;
9
+ /**
10
+ * Checks a `Kite-Signature` header (`t=<unix>,v1=<hex>`) against the raw
11
+ * request body: HMAC-SHA256 of `${t}.${body}` under your endpoint's signing
12
+ * secret, compared in constant time. Pass the body exactly as received, before
13
+ * any JSON parsing. `secret` may be an array so a rotation can overlap: the old
14
+ * secret keeps verifying until the deploy carrying the new one is through.
15
+ * During a rotation overlap the header has a `v1` entry per live secret; the
16
+ * signature is valid if any of them matches.
17
+ *
18
+ * Imported from `@kite-sa/sdk/webhooks` because it needs `node:crypto`; the
19
+ * main entry stays runtime-neutral.
20
+ */
21
+ export function verifyWebhookSignature(header, body, secret, options = {}) {
22
+ if (!header)
23
+ return { valid: false, reason: "malformed" };
24
+ const pairs = header
25
+ .split(",")
26
+ .map((p) => p.trim().split("=", 2))
27
+ .filter((p) => p.length === 2);
28
+ const tText = pairs.find(([k]) => k === "t")?.[1];
29
+ const t = Number(tText);
30
+ // After a secret rotation the header carries one `v1` per live secret (new
31
+ // first) until the overlap ends; any of them may match.
32
+ const v1s = pairs.filter(([k, v]) => k === "v1" && v).map(([, v]) => v);
33
+ if (v1s.length === 0 || !tText || !Number.isFinite(t)) {
34
+ return { valid: false, reason: "malformed" };
35
+ }
36
+ // Age first and independently of the secret: a genuine but stale signature
37
+ // is a replay, not an authentication failure.
38
+ const now = options.now ?? Math.floor(Date.now() / 1000);
39
+ if (Math.abs(now - t) > (options.toleranceSeconds ?? TOLERANCE_SECONDS)) {
40
+ return { valid: false, reason: "too_old" };
41
+ }
42
+ const secrets = typeof secret === "string" ? [secret] : secret;
43
+ const given = v1s.map((v1) => Buffer.from(v1, "utf8"));
44
+ const matches = secrets.some((s) => {
45
+ const expected = Buffer.from(createHmac("sha256", s).update(`${t}.${body}`).digest("hex"));
46
+ return given.some((g) => expected.length === g.length && timingSafeEqual(expected, g));
47
+ });
48
+ return matches ? { valid: true } : { valid: false, reason: "no_match" };
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kite-sa/sdk",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Official JavaScript/TypeScript client for the Kite API: Saudi real-estate listings and market data.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -8,6 +8,10 @@
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
10
  "import": "./dist/index.js"
11
+ },
12
+ "./webhooks": {
13
+ "types": "./dist/webhooks.d.ts",
14
+ "import": "./dist/webhooks.js"
11
15
  }
12
16
  },
13
17
  "files": [