@medivy/sdk 0.0.0-stage → 0.3.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 ADDED
@@ -0,0 +1,97 @@
1
+ # Changelog — @medivy/sdk
2
+
3
+ Semver, separate from the API's `/v1` (README → Versioning and compatibility).
4
+ `0.x` is a preview: a minor bump may break the typed surface.
5
+
6
+ ## 0.3.0 — 2026-12-02
7
+
8
+ ### Added
9
+
10
+ - **Products and variants** (MP-364, `catalog:write`): `products.create`,
11
+ `products.update`, `products.createVariant` and `variants.update`. Every one
12
+ needs your own `idempotencyKey`. SKUs are unique across Medivy
13
+ (`duplicate_sku`); a buy price needs the key's `cost:read` scope.
14
+ - **Stock adjustments** (MP-364, `stock:write`): `stockAdjustments.create`
15
+ (one outlet, 1–100 lines, all or none; `insufficient_stock`,
16
+ `unknown_batch`). It creates no accounting journal.
17
+ - **Purchasing** (MP-364): `purchaseOrders.list/get/create/update`,
18
+ `purchaseInvoices.list/get/create/receive/journal` (`purchase:read`,
19
+ `purchase:write`, `accounting:write`). `purchaseInvoices.create` dedupes on
20
+ your `invoiceNumber`, so its `idempotencyKey` is optional. **Receiving does
21
+ not post an accounting journal**: read `journalStatus` and call
22
+ `purchaseInvoices.journal` when you want the ledger entry.
23
+ - **CRM and sales documents** (MP-364; scopes `deals:read` / `deals:write` for pipelines and deals,
24
+ `commercial:read` / `commercial:write` for estimates and proposals, `invoices:write` for the header):
25
+ `pipelines.list/create/update/createStage`, `pipelineStages.update`,
26
+ `deals.list/get/create/update`, `estimates.list/get/create/update`,
27
+ `proposals.list/get/create/update/addLine`, `proposalLines.update` and
28
+ `invoices.update` (due date, notes, payment term). The dash's `preparedForId` is
29
+ `customerId`; lines use `variantId` / `unitId`. `crm:read` / `crm:write` stay for contacts
30
+ (the latter is still reserved). Cashback beneficiaries and deleting are not in the API.
31
+ - **Invoice cancel / void** (MP-364, `invoices:void`): `invoices.cancel(id, { reason })`,
32
+ `invoices.void(id, { reason })` and `invoices.ledgerReversal(id)` (`accounting:write`).
33
+ **Cancelling or voiding does not reverse the invoice's journals**: read `ledgerReversal`
34
+ (`pending` / `done` / `none`, also on `invoices.get`) and call `invoices.ledgerReversal`
35
+ when you want the ledger entry. Payments, payouts and stock follow the dash's rules.
36
+ - **POS operations** (MP-364, `pos:read` / `pos:write`): `posSessions.list/get/createCashMovement`
37
+ (open shifts, one shift's detail, a manual cash in / out in an open shift), `heldCarts.list`
38
+ (read-only; `cartData` is the till app's own snapshot) and `posFees.list/create/update`.
39
+ Fee writes need an admin / owner user and a key without an outlet restriction. No device or
40
+ sign-in details, nothing clinical; opening / closing shifts and parking carts stay on the till.
41
+ - New error codes `virtual_account_active`, `invoice_not_terminated`, `nothing_to_reverse`, `unknown_pipeline`, `unknown_stage`, plus `duplicate_sku`, `unknown_batch`, `duplicate_invoice_number`,
42
+ `already_journaled`, `invoice_not_received`, `consignment_invoice`,
43
+ `accounting_period_closed` and `posting_rule_missing`.
44
+
45
+ ### Breaking
46
+
47
+ - **Every key is camelCase** (MP-363), following the API's v1 contract:
48
+ response fields (`nextCursor`, `outletId`, `createdAt`, `isActive`, …), query
49
+ parameters (`dateFrom`, `outletId`, …), request bodies (`externalId`,
50
+ `unitPrice`, `paymentChannelId`, …), error bodies (`requestId`) and error
51
+ `details` (`saleId`, `maxAmount`). Error and enum *codes* are unchanged
52
+ (`duplicate_external_id`, `allow_negative`, …). `sales.refund`'s
53
+ `credit_note` result is `creditNote`.
54
+
55
+ ## 0.2.0 — 2026-11-22
56
+
57
+ First version meant for npm (0.1.0 was tagged but never published).
58
+
59
+ ### Breaking
60
+
61
+ - **`idempotencyKey` is required on writes with no natural dedupe key**
62
+ (MP-264): `invoices.create`, `invoices.issue`, `invoices.pay` and
63
+ `sales.refund` take `{ idempotencyKey }` as a required argument
64
+ (`IdempotentWriteOptions`), and so do `client.call()` / `client.request()`
65
+ for those operations. Without it the call throws `MedivyError` with
66
+ `code: "idempotency_key_required"` naming the operation, before any request
67
+ is sent. Derive the key from your own invoice / payment / refund id and store
68
+ it before the call, so a retry after a crash or restart sends the same key
69
+ (README → Writes).
70
+ - `client.call()` / `client.request()` take the options as a typed rest
71
+ argument (`OptionsArg<K>`); a call with an operation id typed as a union that
72
+ includes one of those writes also needs the key.
73
+
74
+ ### Added
75
+
76
+ - The list of key-required writes comes from the contract: the v1 routes emit
77
+ `x-idempotency: "required" | "optional"` (and `x-idempotency-natural-key`
78
+ for `optional`) in `docs/api/public-v1.openapi.json`; the generator emits
79
+ `OPERATIONS[id].idempotencyKeyRequired` and the
80
+ `IdempotencyKeyRequiredOperationId` type, and refuses a write without the
81
+ extension.
82
+ - `MedivyError.code` (`ClientErrorCode` for errors the SDK raises itself;
83
+ `MedivyApiError.code` is unchanged).
84
+ - `CHANGELOG.md` ships in the package.
85
+ - `Outlet.sia_number` / `Outlet.sia_expires_at` (both nullable): the outlet's
86
+ SIA (pharmacy licence number) and its expiry date, on `outlets.list` /
87
+ `outlets.get` (MP-277, an additive v1 response field).
88
+
89
+ ### Unchanged
90
+
91
+ - `sales.create` keeps the generated fallback key: its required `external_id`
92
+ dedupes a later retry (409 `duplicate_external_id`).
93
+
94
+ ## 0.1.0 — 2026-11-20
95
+
96
+ Initial preview (MP-248): generated v1 surface, retries, cursors,
97
+ Idempotency-Key, typed errors. Tagged `sdk-v0.1.0`, never published.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Medivy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,388 @@
1
- # Temporary Holding Version
1
+ # @medivy/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A typed client for the **Medivy public API v1** (`https://api.medivy.id/v1`),
4
+ generated from its OpenAPI contract (MP-248). It covers every v1 operation:
5
+ reads, writes (POS sales and refunds, invoices, invoice payments), cursor
6
+ pagination, `Idempotency-Key`, rate-limit headers and the structured error
7
+ shape.
8
+
9
+ > **Status: preview (0.x).** The API surface may still change before 1.0.0;
10
+ > breaking changes are listed in `CHANGELOG.md`. Releases are published only
11
+ > by `.github/workflows/sdk-release.yml` (see [Release](#release-and-ownership)).
12
+
13
+ This package is a **client** of the public API. It is separate from
14
+ `@medivy/api-core`, which is server code and is never published. It holds no
15
+ secrets and calls nothing besides the base URL you give it.
16
+
17
+ ## Supported runtimes: server-side only
18
+
19
+ | Runtime | Supported |
20
+ | --- | --- |
21
+ | Node.js ≥ 20 | yes (global `fetch`, `crypto.randomUUID`, `AbortController`) |
22
+ | Bun ≥ 1.1 | yes |
23
+ | Deno ≥ 1.40 / 2.x | yes (`npm:@medivy/sdk`; `--allow-net`, plus `--allow-env` to read `MEDIVY_API_KEY`) |
24
+ | Browsers, React Native, mobile apps | **no, never** |
25
+ | Cloudflare Workers / other edge runtimes | not in the test matrix yet. The SDK uses only web-standard APIs, so it should work: pass `apiKey` from a secret binding. |
26
+
27
+ **Never ship an API key in a browser bundle or an app.** An org API key acts
28
+ as its API user across the whole organization, so anyone who has the key has
29
+ that access. Keep the key in a secret manager or in your server's environment,
30
+ and call Medivy from your backend. The API itself sends no CORS headers and
31
+ answers `OPTIONS` with 405, so a browser can't call it anyway. The client also
32
+ throws at construction if it finds a DOM (`document`).
33
+
34
+ ## Exports
35
+
36
+ - ESM only (`"type": "module"`): `import { MedivyClient } from "@medivy/sdk"`.
37
+ There is no CommonJS build. Node ≥ 20 can `import()` it from CJS.
38
+ - Types are included (`dist/index.d.ts`, built with `tsc`). There are no
39
+ runtime dependencies.
40
+ - One entry point, `.`, which exports: `MedivyClient`, the errors
41
+ (`MedivyError`, `MedivyApiError`, `MedivyConnectionError`, `isApiError`,
42
+ `KNOWN_ERROR_CODES`), every schema type (`Sale`, `Invoice`, `Product`, …)
43
+ and per-operation types (`SalesCreateBody`, `ProductsListQuery`,
44
+ `SalesCreateResponse`, …), and the `OPERATIONS` table with
45
+ `OPENAPI_SHA256` / `OPENAPI_VERSION`.
46
+
47
+ ## Quick start
48
+
49
+ ```ts
50
+ import { MedivyClient, isApiError } from "@medivy/sdk"
51
+
52
+ const medivy = new MedivyClient({ apiKey: process.env.MEDIVY_API_KEY })
53
+ // or just `new MedivyClient()`: it reads MEDIVY_API_KEY itself
54
+
55
+ const { data: outlets } = await medivy.outlets.list()
56
+ const { data: product } = await medivy.products.get("prd-…")
57
+ ```
58
+
59
+ The organization comes from the key. There is no org id in any call. A key
60
+ reaches only what its **scopes** allow, and never more than its **API user's**
61
+ permissions and outlets
62
+ ([docs/public-api-v1.md → Scopes and access](../../docs/public-api-v1.md)).
63
+
64
+ ### Resources
65
+
66
+ Each method is generated from an operationId (`<resource><Action>`):
67
+
68
+ | Resource | Methods |
69
+ | --- | --- |
70
+ | `outlets` | `list`, `listAll`, `get` |
71
+ | `paymentChannels` | `list` |
72
+ | `units` | `list` |
73
+ | `products` | `list`, `listAll`, `get` |
74
+ | `prices` | `list`, `listAll` |
75
+ | `stockLevels`, `batches`, `stockMovements` | `list`, `listAll` |
76
+ | `contacts`, `loyaltyAccounts` | `list`, `listAll`, `get` |
77
+ | `sales` | `list`, `listAll`, `get`, `create`, `refund` |
78
+ | `invoices` | `list`, `listAll`, `get`, `create`, `issue`, `pay` |
79
+ | `payments` | `list`, `listAll`, `get` |
80
+ | `reports` | `revenue`, `salesSummary`, `salesPerformance`, `productPerformance`, `stockMovement` |
81
+
82
+ Filters are the API's own camelCase query parameters, typed per endpoint. A
83
+ boolean filter takes `true` or `false`. An unknown parameter is refused before
84
+ the request is sent (the API would answer 400).
85
+
86
+ ### Pagination
87
+
88
+ ```ts
89
+ const page = await medivy.sales.list({ dateFrom: "2026-11-01", dateTo: "2026-11-14", limit: 100 })
90
+ page.nextCursor // pass as { cursor } for the next page; null = last page
91
+
92
+ for await (const sale of medivy.sales.listAll({ dateFrom: "2026-11-01", dateTo: "2026-11-14" })) {
93
+ // every sale, page after page
94
+ }
95
+ ```
96
+
97
+ ### Dates and timezones
98
+
99
+ Timestamps (`completedAt`, …) are ISO 8601 with an offset in the zone of the record's outlet (`2026-12-01T01:30:00.000+08:00`),
100
+ and a record with an `outletId` names that zone in `timezone`. A day filter (`dateFrom` / `dateTo`, `from` / `to`) is a whole
101
+ local day of each record's outlet; pass `timezone` (an IANA name or `UTC`) to count the days of one zone for the whole request:
102
+
103
+ ```ts
104
+ const utcDays = await medivy.sales.list({ dateFrom: "2026-12-01", dateTo: "2026-12-01", timezone: "UTC" })
105
+ ```
106
+
107
+ Cursors are opaque, signed, and bound to the key, the endpoint and the exact
108
+ filters and `limit`. `listAll` keeps all of those the same between pages. For
109
+ an incremental sync, use the time filters (`since` on stock movements,
110
+ `updatedFrom` on products, date ranges on sales, invoices and payments).
111
+
112
+ ### Writes: Idempotency-Key and externalId
113
+
114
+ Every write sends an `Idempotency-Key`. Generate **one key per logical
115
+ operation**, store it with your record, and reuse it whenever you retry that
116
+ operation, including after a crash or a restart.
117
+
118
+ #### Invoices, invoice payments and refunds: the key is required
119
+
120
+ `invoices.create`, `invoices.issue`, `invoices.pay` and `sales.refund` have no
121
+ natural dedupe key: nothing in the body tells Medivy that a second request is a
122
+ retry of the first. A key the SDK made up would live only in your process
123
+ memory, so after a crash or a restart your retry would carry a **new** key and
124
+ create a second invoice, payment or refund. These calls therefore take
125
+ `{ idempotencyKey }` as a **required** argument (a TypeScript error without
126
+ it), and at runtime they throw `MedivyError` with
127
+ `code === "idempotency_key_required"` before anything is sent.
128
+
129
+ Derive the key from **your own** id for that operation, and store it before
130
+ the call:
131
+
132
+ ```ts
133
+ // 1. persist your record (and with it, its key) BEFORE calling Medivy
134
+ const invoice = await db.invoices.insert({ id: "ERP-INV-1042", status: "pending" })
135
+ const idempotencyKey = `invoice-${invoice.id}` // stable: same input → same key
136
+
137
+ // 2. call; a retry after a crash recomputes the same key from the stored id
138
+ const { data } = await medivy.invoices.create(
139
+ { customerId: "con-…", outletId: "otl-…", lines: [{ variantId: "prv-…", qty: 2, unitPrice: 950 }] },
140
+ { idempotencyKey },
141
+ )
142
+ await db.invoices.update(invoice.id, { medivyId: data.id, status: "created" })
143
+
144
+ // each logical operation gets its own key
145
+ await medivy.invoices.issue(data.id, { idempotencyKey: `invoice-${invoice.id}-issue` })
146
+ await medivy.invoices.pay(data.id, { paymentChannelId: "pch-…", amount: 1900 }, { idempotencyKey: `payment-${erpPayment.id}` })
147
+ await medivy.sales.refund(saleId, refundBody, { idempotencyKey: `refund-${erpRefund.id}` })
148
+ ```
149
+
150
+ Which writes require a key comes from the contract (`x-idempotency: required`
151
+ in `docs/api/public-v1.openapi.json`), not from a list in the SDK:
152
+ `IdempotencyKeyRequiredOperationId` is the generated type, and
153
+ `OPERATIONS[id].idempotencyKeyRequired` is the runtime flag. A new v1 write
154
+ with no natural key is required by default.
155
+
156
+ #### Sales: externalId dedupes, the key is optional
157
+
158
+ ```ts
159
+ const idempotencyKey = order.medivyIdempotencyKey ??= crypto.randomUUID()
160
+ const { data: sale } = await medivy.sales.create(
161
+ {
162
+ outletId: "otl-…",
163
+ externalId: order.id, // unique per organization
164
+ lines: [{ variantId: "prv-…", qty: 2, unitPrice: 5000 }],
165
+ payments: [{ paymentChannelId: "pch-…", amount: 10000 }],
166
+ },
167
+ { idempotencyKey },
168
+ )
169
+ ```
170
+
171
+ - If you leave out `idempotencyKey` on `sales.create`, the client makes a UUID
172
+ and reuses it only for **its own** retries of that call. That is safe only
173
+ because `externalId` (required, your own sale id) stops a later retry from
174
+ recording the sale twice.
175
+ - The same key and the same body return the stored answer.
176
+ `client.request(...)` shows this as `meta.idempotencyReplayed === true`.
177
+ - The same key with a different body throws `idempotency_key_reused` (422).
178
+ After you fix a request, send it with a **new** key.
179
+ - `externalId` is the business-level guard: a second sale with the same
180
+ `externalId` throws `duplicate_external_id` (409), and
181
+ `e.details.saleId` is the existing sale. Look a sale up with
182
+ `sales.list({ externalId })`.
183
+ - The other writes always need your key: `sales.refund(id, body, { idempotencyKey })`,
184
+ `invoices.create(body, { idempotencyKey })`, `invoices.issue(id, { idempotencyKey })`,
185
+ `invoices.pay(id, body, { idempotencyKey })`.
186
+
187
+ ### Errors
188
+
189
+ Every non-2xx answer throws `MedivyApiError`, which has these fields: `status`,
190
+ `code` (stable: branch on it), `message` (written for people, may change),
191
+ `requestId`, `details` (machine-readable context of some write errors),
192
+ `retryAfterSeconds` and `rateLimit`. When no HTTP answer arrives at all, the
193
+ client throws `MedivyConnectionError` (`timedOut`, `idempotencyKey`).
194
+
195
+ ```ts
196
+ try {
197
+ await medivy.sales.create(body, { idempotencyKey })
198
+ } catch (e) {
199
+ if (isApiError(e, "duplicate_external_id")) return e.details?.saleId // typed
200
+ if (isApiError(e, "price_mismatch")) console.warn(e.details?.line, e.details?.unitPrice)
201
+ if (isApiError(e, "insufficient_scope")) /* grant the scope in Settings → API Keys */
202
+ throw e
203
+ }
204
+ ```
205
+
206
+ `KNOWN_ERROR_CODES` lists every code and its HTTP status. A unit test keeps it
207
+ equal to the server's catalog. A code added in a later API release still
208
+ arrives as a string.
209
+
210
+ ### Retries, timeouts, rate limits
211
+
212
+ - The client retries 429, 500, 502, 503, 504, 409 `idempotency_in_progress`
213
+ and connection errors, up to `maxRetries` times (default 2). It waits for
214
+ `Retry-After` when the server sends one, and otherwise backs off
215
+ exponentially with jitter. When `Retry-After` is longer than
216
+ `retryMaxDelayMs` (default 30 s), the error is thrown at once with
217
+ `retryAfterSeconds` set. A write is retried with the **same**
218
+ Idempotency-Key, which is safe: a 5xx releases the key on the server, and a
219
+ request that already succeeded is replayed, not run twice.
220
+ - Other 4xx answers are never retried.
221
+ - `timeoutMs` (default 30 s) applies to each attempt. Pass `signal` to cancel.
222
+ - Limits per key: 300 reads, 10 reports and 60 writes per 60 s. Every
223
+ response's `RateLimit-*` headers are parsed into
224
+ `meta.rateLimit = { limit, remaining, resetSeconds, policy }`.
225
+ `remaining` is `null` on Cloudflare, which doesn't report it.
226
+ - `onResponse(meta)` runs after every attempt. Use it for logging, metrics or
227
+ pacing. `meta` never contains the key.
228
+
229
+ ### Options
230
+
231
+ ```ts
232
+ new MedivyClient({
233
+ apiKey, // default: process.env.MEDIVY_API_KEY
234
+ baseUrl, // default https://api.medivy.id
235
+ fetch, // custom fetch (proxy, instrumentation, tests)
236
+ timeoutMs: 30_000,
237
+ maxRetries: 2,
238
+ retryBaseDelayMs: 500,
239
+ retryMaxDelayMs: 30_000,
240
+ userAgent: "acme-erp/2.1", // appended to medivy-sdk-js/<version>
241
+ onResponse: (meta) => {},
242
+ })
243
+ ```
244
+
245
+ Per call: `{ signal, timeoutMs, maxRetries, headers }`, plus `idempotencyKey`
246
+ on writes (required on invoices, invoice payments and refunds).
247
+ `client.request(operationId, { path, query, body }, options)` returns
248
+ `{ data, meta }`; for those writes `options` is required there too.
249
+
250
+ ## How it stays in sync with the API
251
+
252
+ ```
253
+ workers/medivy-public-api (routes)
254
+ └─ bun run check:public-api-contract [--update] → docs/api/public-v1.openapi.json
255
+ └─ bun run --cwd packages/medivy-sdk generate → src/generated/v1.ts (types, OPERATIONS, resources)
256
+ ```
257
+
258
+ - `src/generated/v1.ts` is generated (`scripts/generate.ts`). Never edit it by
259
+ hand. The runtime (`src/client.ts`, `src/errors.ts`) is hand-written and
260
+ knows only HTTP.
261
+ - `bun run check:public-api-contract --update` (in workers/medivy-public-api)
262
+ rewrites the contract **and** regenerates the SDK. Commit both files.
263
+ - Drift checks in `bun run test:unit`:
264
+ - `scripts/generate.test.ts` fails when the OpenAPI file changed and the
265
+ SDK wasn't regenerated. It also checks that every operation's method,
266
+ path, params and idempotency in the table match the contract, and that
267
+ every write declares `x-idempotency` (`required`, or `optional` with a
268
+ required natural-key body field named by `x-idempotency-natural-key`).
269
+ The v1 route helper (`v1WriteRoute`'s `naturalKey`) emits both.
270
+ - `workers/medivy-public-api/src/app/sdk-contract.test.ts` runs the SDK
271
+ against the real v1 app (with stub auth and services). It covers the wire
272
+ format, signed cursors, idempotency replay, error codes and details,
273
+ `RateLimit-*` headers and 429, and checks that `KNOWN_ERROR_CODES` equals
274
+ the server's `ERROR_CODES`.
275
+ - `src/client.test.ts` builds a request for every OpenAPI operation and checks
276
+ it against the spec. It also covers retries, timeouts, pagination, errors,
277
+ the browser guard and that the key never leaks.
278
+ - The dev integration test (`tests/integration/medivy-sdk/`,
279
+ `bun run test:integration`) runs the SDK against the v1 app on the dev DB:
280
+ reads, cursors, a sale with externalId and replay, a refund, and an invoice
281
+ through create, issue and pay, with typed errors. It uses a rolled-back
282
+ fixture org and API key.
283
+ - The generator fails on any JSON Schema construct it doesn't know, so a new
284
+ construct is caught there and never turns into `unknown` without notice.
285
+
286
+ ## Versioning and compatibility
287
+
288
+ - **Semver, separate from the API's `/v1`.** `0.x` until the first public
289
+ release, then `1.0.0`. Every 1.x release targets API **v1**.
290
+ - **Minor** (1.x.0): an additive API change that has been regenerated (new
291
+ endpoint, optional parameter, response field or error code), or a new SDK
292
+ feature.
293
+ - **Patch**: fixes and doc changes. The typed surface doesn't change.
294
+ - **Major**: a breaking change to the SDK's own API (renamed method, changed
295
+ option or default), or a new API version (`/v2`, which gets its own major
296
+ version while v1 is still supported).
297
+ - The API promises additive-only changes within v1
298
+ ([docs/public-api-v1.md → Versioning](../../docs/public-api-v1.md)). So an
299
+ older SDK keeps working against a newer v1 server: unknown response fields
300
+ are kept, and unknown error codes arrive as strings. A newer SDK against an
301
+ older server only lacks the newer endpoints.
302
+ - The SDK supports each Node.js LTS line until it reaches end of life.
303
+ Dropping a runtime version is a major release.
304
+ - When `Deprecation` or `Sunset` headers arrive, they show up in `meta`.
305
+
306
+ ## Release and ownership
307
+
308
+ **Owner: the Medivy platform team** (the owners of `workers/medivy-public-api`
309
+ and the v1 contract). Every regenerated contract change goes in the same PR as
310
+ the SDK regeneration. The release manager of the API decides when to cut an
311
+ SDK release. **Package:** `@medivy/sdk` on the npm org
312
+ [`medivy`](https://www.npmjs.com/org/medivy). **License:** MIT (`LICENSE`).
313
+
314
+ Publishing happens only in CI (`.github/workflows/sdk-release.yml`), never from
315
+ a laptop:
316
+
317
+ 1. One PR bumps `version` in `package.json` and `SDK_VERSION` in
318
+ `src/version.ts` together (a unit test checks they match), adds a
319
+ `## <version>` entry to `CHANGELOG.md`, and is merged to main.
320
+ 2. Push a tag `sdk-v<version>` on that main commit:
321
+ `git tag sdk-v0.2.0 <sha> && git push origin sdk-v0.2.0`. A version with a
322
+ pre-release part (`0.2.0-rc.1`) is published under the `next` dist-tag;
323
+ others go to `latest`.
324
+ 3. The **verify** job checks, in order:
325
+ - the tag is on main and names `package.json`'s version;
326
+ - the metadata (`scripts/release-check.ts`);
327
+ - the contract and the SDK regeneration are up to date;
328
+ - the SDK's unit tests pass, and so does the SDK against the real v1 app
329
+ (no database);
330
+ - tsc and the build pass;
331
+ - the built package imports and constructs on Node 22;
332
+ - `CHANGELOG.md` has a `## <version>` entry;
333
+ - the tarball holds only `dist/`, `README.md`, `CHANGELOG.md`, `LICENSE`
334
+ and `package.json`.
335
+ 4. The **publish** job waits for approval in the GitHub environment
336
+ `npm-release`, refuses a version that is already on npm, and publishes.
337
+
338
+ To rehearse, run "SDK release" from the Actions tab with **dry run** on.
339
+ Everything runs, including `npm publish --dry-run`, and nothing is uploaded.
340
+
341
+ ### One-time setup
342
+
343
+ 1. **GitHub environment:** Settings → Environments → New environment
344
+ `npm-release`. Add yourself (and any other release manager) as required
345
+ reviewers, and limit it to tags matching `sdk-v*`.
346
+ 2. **First publish, bootstrap token:** npm can only attach a trusted publisher
347
+ to a package that exists. Create a granular access token on npmjs.com:
348
+ - permissions: read and write, limited to the `@medivy` scope;
349
+ - expiry: 7 days.
350
+
351
+ Add it as the **environment** secret `NPM_TOKEN` of `npm-release`, not as a
352
+ repository secret. Then tag `sdk-v0.2.0` (the first published version; the
353
+ older `sdk-v0.1.0` tag never ran and must not be re-run — 0.1.0 predates the
354
+ required `idempotencyKey`, see CHANGELOG.md). The workflow uses the token
355
+ whenever the secret is set.
356
+ 3. **Switch to trusted publishing (OIDC):** on npmjs.com, open `@medivy/sdk` →
357
+ Settings → Trusted publishing → GitHub Actions, and enter:
358
+ - repository `medivycare/medivy-platform`
359
+ - workflow `sdk-release.yml`
360
+ - environment `npm-release`
361
+
362
+ Then delete the `NPM_TOKEN` secret and revoke the token. From then on no
363
+ long-lived credential exists. Also set the package's publishing access to
364
+ "require two-factor authentication and disallow tokens", so only this
365
+ workflow can publish.
366
+
367
+ **Provenance:** npm only attests packages built from **public** repositories.
368
+ This repository is private, so releases carry no provenance statement, and
369
+ `--provenance` would fail. Revisit this if the SDK moves to its own public
370
+ repository.
371
+
372
+ **npm name check** (read-only, 2026-11-20): `medivy`, `@medivy/sdk` and
373
+ `medivy-sdk` were all unpublished. The `medivy` npm org was created by the
374
+ product owner on 2026-11-21.
375
+
376
+ ## Development
377
+
378
+ ```sh
379
+ bun run --cwd packages/medivy-sdk generate # after the contract changed
380
+ bun run --cwd packages/medivy-sdk check:generated # the drift check alone
381
+ bun test packages/medivy-sdk # unit tests (no network)
382
+ bun run --cwd packages/medivy-sdk build # ESM + .d.ts → dist/ (git-ignored)
383
+ bunx tsc --noEmit -p packages/medivy-sdk
384
+ ```
385
+
386
+ The build compiles `src/` with web-platform types only (no Node, Bun or Deno
387
+ types), so the SDK can't depend on one runtime. A unit test checks the source
388
+ for `Bun.`, `node:` and `Deno.` imports as well.
@@ -0,0 +1,55 @@
1
+ import { type OperationId, type OperationTypes, type PaginatedOperationId, type Resources } from "./generated/v1.js";
2
+ import type { ApiResponse, CallArgs, OperationCaller, OptionsArg, RequestOptions, ResponseMeta } from "./types.js";
3
+ export declare const DEFAULT_BASE_URL = "https://api.medivy.id";
4
+ export interface MedivyClientOptions {
5
+ /**
6
+ * The org API key (`mdv_…`). Default: the `MEDIVY_API_KEY` environment
7
+ * variable. Load it from a secret manager / server env — never hard-code it.
8
+ */
9
+ apiKey?: string;
10
+ /** default `https://api.medivy.id` (paths already start with `/v1`) */
11
+ baseUrl?: string;
12
+ /** a fetch implementation (default: the global fetch) — tests, proxies, instrumentation */
13
+ fetch?: typeof fetch;
14
+ /** per-attempt timeout, ms (default 30 000) */
15
+ timeoutMs?: number;
16
+ /** retries after 429 / 5xx / 409 idempotency_in_progress / connection errors (default 2) */
17
+ maxRetries?: number;
18
+ /** first backoff when the server sends no Retry-After, ms (default 500; doubles per retry, with jitter) */
19
+ retryBaseDelayMs?: number;
20
+ /** never wait longer than this before a retry, ms (default 30 000); a longer Retry-After fails fast instead */
21
+ retryMaxDelayMs?: number;
22
+ /** appended to the User-Agent (`medivy-sdk-js/<version> <yours>`) */
23
+ userAgent?: string;
24
+ /** called after every HTTP answer (each attempt) — logging, metrics, rate-limit tracking */
25
+ onResponse?: (meta: ResponseMeta) => void;
26
+ }
27
+ /** The generated resources live on the client: `client.products.list()`, `client.sales.create()`, … */
28
+ export interface MedivyClient extends Resources {
29
+ }
30
+ export declare class MedivyClient implements OperationCaller {
31
+ #private;
32
+ readonly baseUrl: string;
33
+ readonly timeoutMs: number;
34
+ readonly maxRetries: number;
35
+ readonly retryBaseDelayMs: number;
36
+ readonly retryMaxDelayMs: number;
37
+ constructor(options?: MedivyClientOptions);
38
+ /** never print the key */
39
+ toJSON(): {
40
+ baseUrl: string;
41
+ timeoutMs: number;
42
+ maxRetries: number;
43
+ };
44
+ /**
45
+ * The body of one operation's 2xx answer (what the resource methods return).
46
+ * `options` (with `idempotencyKey`) is required for the writes in
47
+ * `IdempotencyKeyRequiredOperationId`.
48
+ */
49
+ call<K extends OperationId>(operationId: K, args?: CallArgs, ...[options]: OptionsArg<K>): Promise<OperationTypes[K]["response"]>;
50
+ /** One operation with its response metadata (request id, rate limit, idempotency replay). */
51
+ request<K extends OperationId>(operationId: K, args?: CallArgs, ...[options]: OptionsArg<K>): Promise<ApiResponse<OperationTypes[K]["response"]>>;
52
+ /** Every row of a paged list: follows `nextCursor` with the same filters and limit. */
53
+ paginate<K extends PaginatedOperationId>(operationId: K, args?: CallArgs, options?: RequestOptions): AsyncGenerator<OperationTypes[K]["response"]["data"][number]>;
54
+ }
55
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAUA,OAAO,EAA+B,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,KAAK,oBAAoB,EAAE,KAAK,SAAS,EAAE,MAAM,mBAAmB,CAAA;AACjJ,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,eAAe,EAAE,UAAU,EAAiB,cAAc,EAAE,YAAY,EAAgB,MAAM,YAAY,CAAA;AAG/I,eAAO,MAAM,gBAAgB,0BAA0B,CAAA;AAEvD,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,2FAA2F;IAC3F,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;IACpB,+CAA+C;IAC/C,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,4FAA4F;IAC5F,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,2GAA2G;IAC3G,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,+GAA+G;IAC/G,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,qEAAqE;IACrE,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,4FAA4F;IAC5F,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,YAAY,KAAK,IAAI,CAAA;CAC1C;AA6DD,uGAAuG;AACvG,MAAM,WAAW,YAAa,SAAQ,SAAS;CAAG;AAElD,qBAAa,YAAa,YAAW,eAAe;;IAIlD,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAA;IACjC,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAA;gBAIpB,OAAO,GAAE,mBAAwB;IAuB7C,0BAA0B;IAC1B,MAAM;;;;;IAIN;;;;OAIG;IACG,IAAI,CAAC,CAAC,SAAS,WAAW,EAAE,WAAW,EAAE,CAAC,EAAE,IAAI,GAAE,QAAa,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;IAI3I,6FAA6F;IACvF,OAAO,CAAC,CAAC,SAAS,WAAW,EAAE,WAAW,EAAE,CAAC,EAAE,IAAI,GAAE,QAAa,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;IA8G3J,uFAAuF;IAChF,QAAQ,CAAC,CAAC,SAAS,oBAAoB,EAAE,WAAW,EAAE,CAAC,EAAE,IAAI,GAAE,QAAa,EAAE,OAAO,GAAE,cAAmB,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;CAqBlL"}