@kite-sa/sdk 0.6.0 → 0.9.2

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/dist/generated.js CHANGED
@@ -2,6 +2,14 @@
2
2
  export function createEndpoints(request) {
3
3
  return {
4
4
  analytics: {
5
+ /**
6
+ * List advertisers by matching listings. The advertisers behind the listings a
7
+ * search matches: one row per advertiser, with how many matching listings they
8
+ * hold, their price range and where they list.
9
+ */
10
+ advertisers: (params) => request("GET", "/advertisers", {
11
+ query: params,
12
+ }),
5
13
  /**
6
14
  * Find below-market listings. Residential listings asking noticeably less than
7
15
  * similar listings nearby, biggest gap first.
@@ -84,6 +92,11 @@ export function createEndpoints(request) {
84
92
  listings: {
85
93
  /** Get listings by id. Up to 100 listings in one call, in the order requested. */
86
94
  batch: (params) => request("GET", "/listings/batch", { query: params }),
95
+ /**
96
+ * Get a listing's advertiser contact. The advertiser's phone number for one
97
+ * active listing.
98
+ */
99
+ contact: (id) => request("GET", `/listings/${encodeURIComponent(String(id))}/contact`),
87
100
  /** Count listings. How many listings match the same filters as search. */
88
101
  count: (params) => request("GET", "/listings/count", { query: params }),
89
102
  /** Get a listing. One active listing. */
@@ -100,6 +113,24 @@ export function createEndpoints(request) {
100
113
  search: (params) => request("GET", "/listings", { query: params }),
101
114
  },
102
115
  market: {
116
+ /**
117
+ * Project absorption by area, developer or type. Month-by-month absorption
118
+ * pooled over projects: per city (the default), neighborhood, developer,
119
+ * property type or project type, the units on offer at the start and end of each
120
+ * month, units gone, released and re-added, the pooled and median absorption
121
+ * rate, and months of stock at the month's pace.
122
+ */
123
+ absorption: (params) => request("GET", "/market/absorption", {
124
+ query: (params ?? {}),
125
+ }),
126
+ /**
127
+ * Places, population and landmarks around a point or in a neighborhood. What is
128
+ * around a location: mapped places by category, the resident population and how
129
+ * it changed over five years, and the nearest landmarks.
130
+ */
131
+ areaContext: (params) => request("GET", "/market/area-context", {
132
+ query: (params ?? {}),
133
+ }),
103
134
  /**
104
135
  * Area distribution. Histogram and percentiles of floor/plot area (m²) over
105
136
  * listings in the sample that state an area (`without_area_count` did not).
@@ -107,6 +138,14 @@ export function createEndpoints(request) {
107
138
  areaDistribution: (params) => request("GET", "/market/area-distribution", {
108
139
  query: params,
109
140
  }),
141
+ /**
142
+ * Registered sale price against the asking price. What plots advertised for sale
143
+ * went on to register at, as a share of what their ads were asking: a
144
+ * negotiation margin to set bids by.
145
+ */
146
+ askToDeal: (params) => request("GET", "/market/ask-to-deal", {
147
+ query: params,
148
+ }),
110
149
  /**
111
150
  * Commercial rent per m² by neighborhood. Asking rent per m² of commercial space
112
151
  * (shops, offices, warehouses, commercial land and whole buildings) by
@@ -125,6 +164,13 @@ export function createEndpoints(request) {
125
164
  landPrices: (params) => request("GET", "/market/land-prices", {
126
165
  query: params,
127
166
  }),
167
+ /**
168
+ * Plots for sale against their last registered sale. How the plots on the market
169
+ * compare with what they last sold for.
170
+ */
171
+ landResale: (params) => request("GET", "/market/land-resale", {
172
+ query: params,
173
+ }),
128
174
  /**
129
175
  * Prices by neighborhood. Median and quartile price per neighborhood in a city,
130
176
  * most expensive first.
@@ -257,6 +303,11 @@ export function createEndpoints(request) {
257
303
  * answered.
258
304
  */
259
305
  deliveries: (webhookId, params) => request("GET", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/deliveries`, { query: (params ?? {}) }),
306
+ /**
307
+ * Re-enable a webhook endpoint. Turns a disabled endpoint back on and resets
308
+ * its failure count.
309
+ */
310
+ enable: (webhookId, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/enable`, { headers: headers }),
260
311
  /** List webhook endpoints. Every endpoint this organization has subscribed. */
261
312
  list: () => request("GET", "/organization/webhooks"),
262
313
  /**
@@ -264,9 +315,40 @@ export function createEndpoints(request) {
264
315
  * `event_id` so a receiver that already handled it can recognise the repeat.
265
316
  */
266
317
  replay: (webhookId, deliveryId, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/deliveries/${encodeURIComponent(String(deliveryId))}/replay`, { headers: headers }),
318
+ /**
319
+ * Rotate a webhook signing secret. Issues a new signing secret, shown once in
320
+ * the response.
321
+ */
322
+ rotateSecret: (webhookId, body, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/rotate-secret`, { body, headers: headers }),
323
+ /**
324
+ * Send a test event. Sends one event of `event_type` (default
325
+ * `listing.created`) to the endpoint now and returns what it answered.
326
+ */
327
+ test: (webhookId, body, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/test`, { body, headers: headers }),
328
+ /**
329
+ * Update a webhook endpoint. Changes the URL, event types, filters or
330
+ * description of an endpoint; send only what changes.
331
+ */
332
+ update: (webhookId, body, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/update`, { body, headers: headers }),
267
333
  },
268
334
  },
269
335
  projects: {
336
+ /**
337
+ * Get a project's absorption by month. How fast a project's offered units go,
338
+ * per calendar month: units on offer at the start and end, units gone, units
339
+ * re-added and released, the absorption rate (units gone ÷ units at the start),
340
+ * and months of stock left at that pace.
341
+ */
342
+ absorption: (id, params) => request("GET", `/projects/${encodeURIComponent(String(id))}/absorption`, { query: (params ?? {}) }),
343
+ /**
344
+ * Get a project's unit availability over time. Daily snapshots of a project's
345
+ * unit count and the availability its source reports, as daily, weekly or
346
+ * monthly points, each with the units absorbed since the previous point. This is
347
+ * **listed availability**, not contracts: it comes from what the project's
348
+ * source page showed on the day, so a unit counts as absorbed when the source
349
+ * stops showing it, not when it is sold or leased.
350
+ */
351
+ availability: (id, params) => request("GET", `/projects/${encodeURIComponent(String(id))}/availability`, { query: (params ?? {}) }),
270
352
  /** List developers. Developers with active projects on Kite, most projects first. */
271
353
  developers: (params) => request("GET", "/developers", {
272
354
  query: (params ?? {}),
@@ -329,13 +411,22 @@ export function createEndpoints(request) {
329
411
  },
330
412
  transactions: {
331
413
  /**
332
- * Search registered deals. Individual sale deals registered with the Ministry of
333
- * Justice, from its quarterly open data, in one city: month, neighborhood,
334
- * land-use class, area, price and price per m².
414
+ * Search registered deals. Individual registered sale deals in one city: month,
415
+ * neighborhood, land-use class, area, price and price per m².
335
416
  */
336
417
  search: (params) => request("GET", "/transactions", {
337
418
  query: params,
338
419
  }),
339
420
  },
421
+ valuations: {
422
+ /**
423
+ * Check the asking price for any home. The asking-price range for a home you
424
+ * describe, from the asking prices of similar homes nearby: like an appraiser's
425
+ * comparables, but for any unit, not just one listed on Kite.
426
+ */
427
+ askingRange: (params) => request("GET", "/valuations/asking-range", {
428
+ query: params,
429
+ }),
430
+ },
340
431
  };
341
432
  }
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 CursorPage } from "./paginate.js";
3
4
  export type { operations } from "./openapi.js";
4
5
  export type { Endpoints } from "./generated.js";
6
+ export { paginate, type Page, type CursorPage } 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.9.2";
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<const P extends object, T>(fetchPage: (params: P & {
86
+ cursor?: string;
87
+ }) => Promise<CursorPage<T>>, params: P): 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.9.2";
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
@@ -99,16 +114,18 @@ export class Kite {
99
114
  body: options.body === undefined ? undefined : JSON.stringify(options.body),
100
115
  signal: AbortSignal.timeout(this.timeoutMs),
101
116
  });
117
+ if (res.ok) {
118
+ const body = await res.text();
119
+ return JSON.parse(body);
120
+ }
102
121
  }
103
122
  catch (err) {
104
- if (attempt < this.maxRetries) {
123
+ if (!(err instanceof SyntaxError) && attempt < this.maxRetries) {
105
124
  await sleep(backoff(attempt));
106
125
  continue;
107
126
  }
108
127
  throw err;
109
128
  }
110
- if (res.ok)
111
- return (await res.json());
112
129
  const error = await toError(res);
113
130
  const retryable = res.status === 429 || res.status >= 500;
114
131
  const wait = error.retryAfter ?? backoff(attempt) / 1000;
@@ -132,15 +149,29 @@ export class Kite {
132
149
  return this.reference.enums();
133
150
  }
134
151
  }
152
+ function newIdempotencyKey() {
153
+ const c = globalThis.crypto;
154
+ if (c?.randomUUID)
155
+ return c.randomUUID();
156
+ // Node 18 has no global `crypto` without a flag. Keys are scoped to one API key,
157
+ // so collision resistance, not unpredictability, is what matters here.
158
+ const rand = () => Math.random().toString(36).slice(2);
159
+ return `${Date.now().toString(36)}-${rand()}-${rand()}`;
160
+ }
135
161
  /** Exponential backoff with jitter, in milliseconds: ~0.5s, 1s, 2s, … */
136
162
  function backoff(attempt) {
137
163
  return Math.min(8000, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5);
138
164
  }
139
165
  async function toError(res) {
140
- const retryAfter = Number(res.headers.get("retry-after"));
166
+ const header = res.headers.get("retry-after")?.trim() ?? "";
167
+ const retryAfter = /^\d+(?:\.\d+)?$/.test(header)
168
+ ? Number(header)
169
+ : /[a-z]/i.test(header)
170
+ ? Math.max(0, (Date.parse(header.endsWith("GMT") ? header : header + " GMT") - Date.now()) / 1000)
171
+ : NaN;
141
172
  const requestId = res.headers.get("x-request-id");
142
173
  const body = (await res.json().catch(() => null));
143
174
  const e = body?.error;
144
- return new KiteError(res.status, e?.type ?? "api_error", e?.code ?? `http_${res.status}`, e?.message ?? `The API returned HTTP ${res.status}.`, e?.request_id ?? requestId, e?.param ?? null, Number.isFinite(retryAfter) && res.headers.has("retry-after") ? retryAfter : null);
175
+ return new KiteError(res.status, e?.type ?? "api_error", e?.code ?? `http_${res.status}`, e?.message ?? `The API returned HTTP ${res.status}.`, e?.request_id ?? requestId, e?.param ?? null, Number.isFinite(retryAfter) ? retryAfter : null);
145
176
  }
146
177
  export default Kite;